orchestratectl 0.1.2

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
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
//! Integration tests for `orchestratectl run merge` (issue
//! `bundle-worktree-merge`). The merge backend is stubbed via `OCTL_MERGE_SH`
//! so the tests exercise orchestratectl's integration — node resolution,
//! source resolution, terminal-report submission, failure handling — without
//! a real git worktree, workmux, or tmux.

use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;

use serde_json::Value;
use tempfile::TempDir;

mod common;
use common::TestHome;

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");
    c.env("TMUX_BIN", "/usr/bin/true");
    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)
    );
    serde_json::from_slice(&out.stdout).expect("stdout is valid JSON")
}

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

fn run_dir(home: &TempDir, run_id: &str) -> std::path::PathBuf {
    home.path().join("runs").join(run_id)
}

/// Forge a `node.created` for `n-0001` carrying a real (existing) worktree
/// path + branch so `run merge` can `cd` into it and resolve the branch.
fn forge_worker_node(home: &TempDir, run_id: &str, kind: &str, worktree: &Path, branch: &str) {
    let node = home.path().join(format!("node-{run_id}.json"));
    std::fs::write(
        &node,
        format!(
            r#"{{"kind":"{kind}","task":"x","worktree_path":"{}","branch":"{branch}","tmux_session":"octl","tmux_window_id":"@42"}}"#,
            worktree.display()
        ),
    )
    .unwrap();
    run_ok(bin(home).args([
        "--output",
        "json",
        "event",
        "create",
        run_id,
        "--kind",
        "node.created",
        "--node-id",
        "n-0001",
        "--from-file",
        node.to_str().unwrap(),
    ]));
}

/// Write an executable fake merge backend that records its argv (one line) to
/// `<dir>/merge.log` and exits `code`.
fn fake_merge_sh(dir: &Path, code: i32, stderr: &str) -> std::path::PathBuf {
    let p = dir.join("fake-merge.sh");
    let log = dir.join("merge.log");
    let body = format!(
        "#!/bin/bash\nprintf '%s ' \"$@\" >> '{}'\nprintf '\\n' >> '{}'\n{}\nexit {code}\n",
        log.display(),
        log.display(),
        if stderr.is_empty() {
            String::new()
        } else {
            format!("echo '{stderr}' >&2")
        },
    );
    std::fs::write(&p, body).unwrap();
    let mut perms = std::fs::metadata(&p).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&p, perms).unwrap();
    p
}

fn read_events(events: &Path) -> Vec<Value> {
    std::fs::read_to_string(events)
        .unwrap_or_default()
        .lines()
        .map(|l| serde_json::from_str::<Value>(l).unwrap())
        .collect()
}

fn node_reports(events: &Path) -> Vec<Value> {
    read_events(events)
        .into_iter()
        .filter(|v| v["kind"] == "node.report")
        .collect()
}

/// A clean merge: the backend exits 0, and `run merge` appends a terminal
/// `node.report` carrying `via: "explicit-merge"`.
#[test]
fn successful_merge_submits_explicit_merge_report() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "code", "merge-ok");
    forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    // A `code` run is interactive: the human's `/worktree-merge` supplies
    // `--confirm-interactive` (issue `interactive-code-run-self-merged`).
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--source",
        "main",
        "--confirm-interactive",
    ]));
    assert_eq!(v["data"]["merged"], true);
    assert_eq!(v["data"]["branch"], "wt/test-x");
    assert_eq!(v["data"]["source"], "main");

    // The backend was invoked with the resolved target and branch.
    let argv = std::fs::read_to_string(scratch.path().join("merge.log")).unwrap();
    assert!(
        argv.contains("--target main") && argv.contains("wt/test-x"),
        "merge backend argv was {argv:?}"
    );

    // Exactly one terminal report, stamped with the explicit-merge marker.
    let events = run_dir(&home, &run_id).join("events.jsonl");
    let reports = node_reports(&events);
    assert_eq!(reports.len(), 1, "expected one terminal node.report");
    assert_eq!(reports[0]["data"]["success"], true);
    assert_eq!(reports[0]["data"]["via"], "explicit-merge");
}

/// `--report-file` carries a rich §7.3 payload (`discussion_items`,
/// `spinoff_proposals`) so an autonomous kind merges AND delivers its
/// structured report in one call. `run merge` stamps `via: "explicit-merge"`
/// and submits the agent's payload verbatim otherwise.
#[test]
fn report_file_payload_is_submitted_with_marker() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "research", "merge-rich");
    forge_worker_node(&home, &run_id, "research", worktree.path(), "wt/test-x");

    let report = scratch.path().join("report.json");
    std::fs::write(
        &report,
        r#"{
            "success": true,
            "summary": "research delivered",
            "discussion_items": [{"topic": "scope creep", "severity": "discuss"}],
            "spinoff_proposals": [{"proposed_title": "follow-up", "proposed_kind": "research"}],
            "wrap_up_recommendations": ["read sources/"]
        }"#,
    )
    .unwrap();

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--report-file",
        report.to_str().unwrap(),
    ]));

    let events = run_dir(&home, &run_id).join("events.jsonl");
    let reports = node_reports(&events);
    assert_eq!(reports.len(), 1);
    let data = &reports[0]["data"];
    assert_eq!(data["via"], "explicit-merge");
    assert_eq!(data["summary"], "research delivered");
    assert_eq!(data["discussion_items"][0]["topic"], "scope creep");
    assert_eq!(data["spinoff_proposals"][0]["proposed_title"], "follow-up");
    assert_eq!(data["wrap_up_recommendations"][0], "read sources/");
}

/// A `--report-file` that contradicts the merge (`success: false` or
/// `cancelled: true`) is rejected BEFORE the merge runs. A clean merge is a
/// success; such a report — stamped explicit-merge — would either mis-terminalize
/// a live node or fail the reducer's confirmed-merge adoption gate and strand
/// teardown (4-model review of `reducer-adopt-explicit-merge`).
#[test]
fn non_success_report_file_is_rejected() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();

    for body in [
        r#"{"success": false, "summary": "blocked"}"#,
        r#"{"success": true, "cancelled": true, "summary": "cancelled"}"#,
    ] {
        let run_id = create_run(&home, "code", "reject-nonsuccess");
        forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/foo");
        let report = scratch.path().join("bad-report.json");
        std::fs::write(&report, body).unwrap();
        let merge_sh = fake_merge_sh(scratch.path(), 0, "");
        let out = bin(&home)
            .env("OCTL_MERGE_SH", &merge_sh)
            .args([
                "--output",
                "json",
                "run",
                "merge",
                &run_id,
                "--source",
                "main",
                // Confirm the interactive merge so the report-shape gate — not
                // the interactive-confirmation gate — is what rejects the body.
                "--confirm-interactive",
                "--report-file",
                report.to_str().unwrap(),
            ])
            .output()
            .expect("spawn");
        assert!(!out.status.success(), "must reject: {body}");
        let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
        assert_eq!(err["error"]["code"], "invalid_merge_report", "body: {body}");
        // The merge backend must NOT have run (rejection is pre-merge).
        assert!(
            !scratch.path().join("merge.log").exists(),
            "merge backend must not run when the report is rejected: {body}"
        );
        // No terminal report was appended.
        let events = run_dir(&home, &run_id).join("events.jsonl");
        assert_eq!(node_reports(&events).len(), 0, "no report appended: {body}");
    }
}

/// A malformed `--report-file` is rejected BEFORE the merge runs — the backend
/// is never invoked and no event is appended.
#[test]
fn bad_report_file_rejected_before_merge() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "merge-badreport");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    // Missing the required `success` field.
    let report = scratch.path().join("bad.json");
    std::fs::write(&report, r#"{"summary": "no success field"}"#).unwrap();

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output",
            "json",
            "run",
            "merge",
            &run_id,
            "--report-file",
            report.to_str().unwrap(),
        ])
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr JSON");
    assert_eq!(err["error"]["code"], "schema_violation");
    assert!(
        !scratch.path().join("merge.log").exists(),
        "merge must not run when the report file is invalid"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(node_reports(&events).len(), 0);
}

/// A merge failure (conflict / dirty tree / lock timeout): the backend exits
/// non-zero, `run merge` surfaces `merge_failed`, and NO terminal report is
/// appended — the node stays live for the agent to recover and retry.
#[test]
fn failed_merge_surfaces_error_and_writes_no_report() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "code", "merge-fail");
    forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 1, "Error: rebase conflict");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output",
            "json",
            "run",
            "merge",
            &run_id,
            "--confirm-interactive",
        ])
        .output()
        .expect("spawn");
    assert!(!out.status.success(), "merge failure must exit non-zero");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(err["error"]["code"], "merge_failed");

    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(
        node_reports(&events).len(),
        0,
        "a failed merge must not submit a terminal report"
    );
}

/// `--dry-run` resolves inputs and reports the planned merge without invoking
/// the backend or appending any event. It is a read-only preview with no merge
/// and no report, so the `code`-run confirmation gate does NOT apply: a bare
/// `--dry-run` on a `code` run succeeds WITHOUT `--confirm-interactive` (the gate
/// only guards a real merge — issue `interactive-code-run-self-merged`).
#[test]
fn dry_run_resolves_without_side_effects() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "code", "merge-dry");
    forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 1, "should never run");
    // No `--confirm-interactive`: a dry-run of a `code` run must not require it.
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--dry-run",
    ]));
    assert_eq!(v["data"]["dry_run"], true);
    assert_eq!(v["data"]["branch"], "wt/test-x");

    // The backend was never invoked and no report was written.
    assert!(
        !scratch.path().join("merge.log").exists(),
        "dry-run must not invoke the merge backend"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(node_reports(&events).len(), 0);
}

/// Roll the run's manifest to a terminal `status` by appending a `run.status`
/// event — the supervisor's own rollup, driven directly so a test needn't spawn
/// a real supervisor.
fn set_run_status(home: &TempDir, run_id: &str, scratch: &Path, status: &str) {
    let f = scratch.join(format!("run-status-{status}.json"));
    std::fs::write(&f, format!(r#"{{"status":"{status}"}}"#)).unwrap();
    run_ok(bin(home).args([
        "--output",
        "json",
        "event",
        "create",
        run_id,
        "--kind",
        "run.status",
        "--from-file",
        f.to_str().unwrap(),
    ]));
}

/// Assert `run merge` fails with `run_already_terminal` and never spawned the
/// merge backend a second time. `expected_backend_lines` is how many argv lines
/// the shared `merge.log` should hold (the count from any earlier merges).
fn assert_refused_terminal(
    out: std::process::Output,
    scratch: &Path,
    expected_backend_lines: usize,
) {
    assert!(!out.status.success(), "the merge must be refused");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "run_already_terminal",
        "a terminal run must surface run_already_terminal, not merge_spawn_failed: {err}"
    );
    let log = scratch.join("merge.log");
    let lines = std::fs::read_to_string(&log).map_or(0, |s| s.lines().count());
    assert_eq!(
        lines, expected_backend_lines,
        "the refused merge must NOT invoke the merge backend"
    );
}

/// Re-merging an already-finished run fails with the clear `run_already_terminal`
/// error, NOT the misleading `merge_spawn_failed` (issue
/// `merge-terminal-misleading`). Repro: a spinoff self-merges; the supervisor
/// then rolls the manifest to `done` AND tears the worktree down (invariant #5);
/// a second `run merge` on the same id must refuse up front — no merge.sh spawn.
#[test]
fn second_merge_on_terminal_run_is_run_already_terminal() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "double-merge");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    // First merge: succeeds and appends the explicit-merge report.
    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output", "json", "run", "merge", &run_id, "--source", "main",
    ]));
    assert_eq!(v["data"]["merged"], true);

    // Reproduce the real post-teardown state the supervisor leaves: the run
    // rolled up terminal and its worktree was removed.
    set_run_status(&home, &run_id, scratch.path(), "done");
    std::fs::remove_dir_all(worktree.path()).unwrap();

    // Second merge: refused up front with the clear terminal error, no spawn.
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    let msg = err["error"]["message"].as_str().unwrap_or_default();
    assert!(
        msg.contains("no worktree left to merge"),
        "the message must explain there is nothing to merge: {msg}"
    );
    // merge.log holds exactly the ONE line from the first merge.
    assert_refused_terminal(out, scratch.path(), 1);
}

/// A `cancelled` run is refused regardless of its worktree: cancellation is a
/// deliberate teardown the reducer never adopts a merge against, so `run merge`
/// must never spawn the backend for it. Here the worktree still EXISTS, proving
/// the refusal is on status alone (issue `merge-terminal-misleading`).
#[test]
fn merge_on_cancelled_run_is_refused() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "cancelled-merge");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");
    set_run_status(&home, &run_id, scratch.path(), "cancelled");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert!(
        err["error"]["message"]
            .as_str()
            .unwrap_or_default()
            .contains("cancelled"),
        "the message must name the cancellation: {err}"
    );
    assert_refused_terminal(out, scratch.path(), 0);
}

/// A terminal run torn down WITHOUT ever being explicitly merged — a genuine
/// autonomous `failed` whose worktree the supervisor removed — also refuses with
/// the clear terminal error, not `merge_spawn_failed`. This is the case a
/// marker-only guard would have missed (it has no explicit-merge report).
#[test]
fn terminal_failed_torn_down_is_run_already_terminal() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "failed-torn-down");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");
    set_run_status(&home, &run_id, scratch.path(), "failed");
    std::fs::remove_dir_all(worktree.path()).unwrap();

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");
    assert_refused_terminal(out, scratch.path(), 0);
}

/// A NON-terminal run whose worktree has vanished surfaces the distinct
/// `worktree_missing` error (not `run_already_terminal`, not the misleading
/// `merge_spawn_failed`) — the worktree was removed out from under a live run.
#[test]
fn nonterminal_missing_worktree_is_worktree_missing() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "live-no-worktree");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");
    // No terminal status — the run is still live; just remove its worktree.
    std::fs::remove_dir_all(worktree.path()).unwrap();

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(err["error"]["code"], "worktree_missing", "{err}");
    assert!(
        !scratch.path().join("merge.log").exists(),
        "the merge backend must not run when the worktree is missing"
    );
}

/// A `NotFound` from the merge-backend spawn is only re-attributed to a missing
/// worktree when the worktree is ACTUALLY gone. With a present worktree but a
/// bad `OCTL_MERGE_SH` override (nonexistent backend), the error must remain the
/// generic `merge_spawn_failed` — not a spurious `worktree_missing` (round-2
/// review: the `NotFound` remap must not misattribute a missing backend).
#[test]
fn missing_backend_with_live_worktree_is_merge_spawn_failed() {
    let home = TestHome::new();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "bad-backend");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    // Worktree present, but the backend path does not exist.
    let out = bin(&home)
        .env("OCTL_MERGE_SH", "/no/such/merge-backend.sh")
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "merge_spawn_failed",
        "a missing backend (worktree present) must not be misread as worktree_missing: {err}"
    );
}

/// The guard does NOT block a terminal run whose worktree still EXISTS. This is
/// the load-bearing crash-safety / adoption path (issues
/// `reducer-adopt-explicit-merge`, `merge-skips-teardown`): a watchdog
/// `agent-died` false positive terminalizes the run to `failed` while the
/// still-alive agent's worktree survives (a blocked handoff preserves it), and
/// a merge that appended its report then crashed before teardown also leaves the
/// worktree in place. Either way `run merge` must fall through and complete —
/// worktree existence, not the merge marker, is the discriminator.
#[test]
fn terminal_but_unmerged_run_still_merges() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "swallowed-then-merge");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    // Watchdog false positive: the node is terminalized as agent-died, and the
    // run is rolled up to `failed` — but the worktree still exists.
    append_node_report(
        &home,
        &run_id,
        scratch.path(),
        r#"{"success": false, "failed": true, "reason": "agent-died"}"#,
    );
    set_run_status(&home, &run_id, scratch.path(), "failed");

    // The still-alive agent's `run merge` must PROCEED (worktree exists → the
    // guard falls through, so the reducer can adopt the merge).
    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output", "json", "run", "merge", &run_id, "--source", "main",
    ]));
    assert_eq!(
        v["data"]["merged"], true,
        "a terminal run with a surviving worktree must still accept run merge: {}",
        v["data"]
    );
}

/// A run id that names no run surfaces `run_not_found` (not a backend spawn).
#[test]
fn missing_run_is_run_not_found() {
    let home = TestHome::new();
    let out = bin(&home)
        .args([
            "--output",
            "json",
            "run",
            "merge",
            "01jxsnap000000000000000000",
        ])
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(err["error"]["code"], "run_not_found");
}

/// Run `git <args>` in `cwd`, asserting success.
fn git(cwd: &Path, args: &[&str]) {
    let ok = Command::new("git")
        .current_dir(cwd)
        .args(args)
        .output()
        .expect("spawn git")
        .status
        .success();
    assert!(ok, "git {args:?} failed in {}", cwd.display());
}

/// True when local branch `branch` exists in `repo`.
fn branch_exists(repo: &Path, branch: &str) -> bool {
    Command::new("git")
        .current_dir(repo)
        .args(["rev-parse", "--verify", "--quiet", branch])
        .output()
        .expect("spawn git")
        .status
        .success()
}

/// Init a real repo on `main` with a linked worktree on `wt/foo`, returning
/// `(repo, worktree)` — enough for a full `git worktree remove` + `branch -D`
/// round-trip through `run merge`'s synchronous teardown.
fn init_repo_with_worktree(tmp: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
    let repo = tmp.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    git(&repo, &["init", "-q", "-b", "main"]);
    git(&repo, &["config", "user.email", "t@example.com"]);
    git(&repo, &["config", "user.name", "t"]);
    std::fs::write(repo.join("README"), "x").unwrap();
    git(&repo, &["add", "-A"]);
    git(&repo, &["commit", "-qm", "init"]);
    let wt = tmp.join("wt");
    git(
        &repo,
        &[
            "worktree",
            "add",
            "-q",
            "-b",
            "wt/foo",
            wt.to_str().unwrap(),
        ],
    );
    (repo, wt)
}

/// Submit a terminal `node.report` for `n-0001` via the agent self-report path,
/// so a test can pre-terminalize a node the way the watchdog's synthesized
/// report does — before `run merge` runs.
fn append_node_report(home: &TempDir, run_id: &str, scratch: &Path, data: &str) {
    let f = scratch.join("pre-report.json");
    std::fs::write(&f, data).unwrap();
    run_ok(bin(home).args([
        "--output",
        "json",
        "node",
        "report",
        run_id,
        "n-0001",
        "--from-file",
        f.to_str().unwrap(),
    ]));
}

/// THE `merge-skips-teardown` / `agent-died-merge-no-teardown-interactive` fix
/// (issue `reducer-adopt-explicit-merge`): a long-lived interactive node the
/// watchdog falsely declared `agent-died` is already terminal when the still-alive
/// agent runs `run merge`. The octl-core reducer now ADOPTS the late
/// `via: "explicit-merge"` report even against that terminal node — overwriting
/// `last_report` and reconciling status to `Done` — so `any_node_merged_explicitly`
/// sees the merge and the SUPERVISOR (invariant #5) warrants teardown. `run merge`
/// no longer reclaims inline.
///
/// This run was never supervised (`--skip-materialize` skeleton), so there is no
/// live/restartable supervisor and the worktree/branch survive THIS call
/// (`supervisor: NotSupervised`) — real teardown is driven by a reattached
/// supervisor, proven end-to-end under a real detached supervisor in
/// `e2e_spinoff::swallowed_agent_died_then_merge_reattaches_and_tears_down`. Here
/// we assert the load-bearing projection change: the report is adopted.
#[test]
fn merge_adopts_swallowed_report_and_defers_teardown() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "code", "swallowed-merge");
    forge_worker_node(&home, &run_id, "code", &wt, "wt/foo");

    // Watchdog false positive: the node is terminalized as agent-died BEFORE the
    // merge. Pre-fix the reducer would swallow the explicit-merge report; now it
    // adopts it.
    append_node_report(
        &home,
        &run_id,
        scratch.path(),
        r#"{"success": false, "failed": true, "reason": "agent-died"}"#,
    );

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--source",
        "main",
        "--confirm-interactive",
    ]));

    assert_eq!(v["data"]["merged"], true);
    // Never supervised → no teardown actor to (re)start; the supervisor owns
    // teardown, so this call leaves the resources for it.
    assert_eq!(
        v["data"]["supervisor"]["state"], "not-supervised",
        "a never-supervised run has no teardown actor: {}",
        v["data"]
    );
    assert!(
        wt.exists(),
        "run merge no longer reclaims inline; the supervisor owns teardown"
    );
    assert!(
        branch_exists(&repo, "wt/foo"),
        "the branch is left for the supervisor"
    );

    // THE fix: the reducer ADOPTED the explicit-merge report onto the projection,
    // reconciling the watchdog-FAILED node to Done, so a supervisor can now warrant
    // teardown (contrast the pre-fix behavior, where last_report stayed agent-died).
    let node_show =
        run_ok(bin(&home).args(["--output", "json", "node", "show", &run_id, "n-0001"]));
    assert_eq!(node_show["data"]["last_report"]["via"], "explicit-merge");
    assert_eq!(node_show["data"]["status"], "done");
}

/// The healthy interactive path is unchanged: when the node is LIVE at merge
/// time the reducer adopts the `explicit-merge` report, so `run merge` leaves
/// teardown to the supervisor (invariant #5) and does NOT reclaim inline — the
/// worktree/branch survive this call (a real supervisor, absent in this test,
/// would tear them down). Guards against the fix over-reaching into the path
/// that already works.
#[test]
fn merge_defers_to_supervisor_when_report_adopted() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "code", "adopted-merge");
    forge_worker_node(&home, &run_id, "code", &wt, "wt/foo");

    // No pre-terminalization: the node is live, so the explicit-merge report is
    // adopted and a supervisor owns teardown.
    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--source",
        "main",
        "--confirm-interactive",
    ]));

    assert_eq!(v["data"]["merged"], true);
    assert!(
        wt.exists(),
        "adopted path must NOT reclaim inline — the supervisor is the teardown actor"
    );
    assert!(
        branch_exists(&repo, "wt/foo"),
        "adopted path must leave the branch for the supervisor"
    );
    // The report was adopted onto the projection.
    let node_show =
        run_ok(bin(&home).args(["--output", "json", "node", "show", &run_id, "n-0001"]));
    assert_eq!(node_show["data"]["last_report"]["via"], "explicit-merge");
}

/// A FAILED merge (backend exits non-zero) on an already-terminal node must NOT
/// adopt or tear down anything — the worktree + branch survive and `run merge`
/// surfaces `merge_failed`. Guards the ordering: the terminal report is appended
/// (and thus the reducer's adoption + the supervisor's teardown are reachable)
/// ONLY AFTER `run_merge_sh` confirms the merge landed, so a failed merge can
/// never mark a branch merged or warrant its deletion.
#[test]
fn failed_merge_on_preterminal_node_reclaims_nothing() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "code", "swallowed-merge-fail");
    forge_worker_node(&home, &run_id, "code", &wt, "wt/foo");

    // Pre-terminalize the node so its report would be swallowed on a *successful*
    // merge — but here the merge itself fails.
    append_node_report(
        &home,
        &run_id,
        scratch.path(),
        r#"{"success": false, "failed": true, "reason": "agent-died"}"#,
    );

    let merge_sh = fake_merge_sh(scratch.path(), 1, "Error: rebase conflict");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output",
            "json",
            "run",
            "merge",
            &run_id,
            "--source",
            "main",
            "--confirm-interactive",
        ])
        .output()
        .expect("spawn");

    assert!(!out.status.success(), "a failed merge must exit non-zero");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(err["error"]["code"], "merge_failed");
    assert!(wt.exists(), "a failed merge must not reclaim the worktree");
    assert!(
        branch_exists(&repo, "wt/foo"),
        "a failed merge must not reclaim the branch"
    );
}

// --- Interactive-run merge gate (issue `interactive-code-run-self-merged`) ---
//
// An interactive (`code`) run is human-reviewed: only the reviewer merges it via
// `/worktree-merge`, never the coding agent. A real bug had an interactive run
// self-merge to `done` and tear its worktree down with no human merge and no
// review pause, because the agent ran a bare `run merge` on itself. The gate
// below refuses that bare merge; the human's `/worktree-merge` carries
// `--confirm-interactive`.

/// A `code` (interactive) run refuses a bare `run merge`: no confirmation flag
/// means the caller is presumed to be the coding agent self-merging, which
/// bypasses the human review gate. The refusal is pre-merge — the backend never
/// runs and NO terminal report is appended, so the run stays live for the human.
#[test]
fn interactive_run_merge_without_confirmation_is_refused() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "code", "no-selfmerge");
    forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let out = bin(&home)
        .env("OCTL_MERGE_SH", &merge_sh)
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");

    assert!(
        !out.status.success(),
        "an interactive run must refuse a bare (unconfirmed) merge"
    );
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "interactive_merge_requires_confirmation",
        "body: {err}"
    );

    // The gate is pre-merge: the backend never ran and no terminal report exists,
    // so the branch/worktree survive and the run is still awaiting the human.
    assert!(
        !scratch.path().join("merge.log").exists(),
        "the merge backend must NOT run when the interactive gate refuses"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(
        node_reports(&events).len(),
        0,
        "no explicit-merge report may be appended for an unconfirmed interactive merge"
    );
}

/// The human path: `--confirm-interactive` lets a `code` run merge, submitting
/// the terminal `explicit-merge` report exactly as before the gate existed.
#[test]
fn interactive_run_merge_with_confirmation_proceeds() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "code", "human-merge");
    forge_worker_node(&home, &run_id, "code", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--source",
        "main",
        "--confirm-interactive",
    ]));
    assert_eq!(v["data"]["merged"], true);

    let events = run_dir(&home, &run_id).join("events.jsonl");
    let reports = node_reports(&events);
    assert_eq!(
        reports.len(),
        1,
        "the confirmed merge submits one terminal report"
    );
    assert_eq!(reports[0]["data"]["via"], "explicit-merge");
}

/// Autonomous kinds are unaffected: a `spinoff` self-merges with NO
/// confirmation flag (the gate is scoped to `Kind::Code` only).
#[test]
fn autonomous_run_merge_needs_no_confirmation() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "auto-merge");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output", "json", "run", "merge", &run_id, "--source", "main",
    ]));
    assert_eq!(
        v["data"]["merged"], true,
        "an autonomous kind self-merges without --confirm-interactive"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(node_reports(&events).len(), 1);
}

/// `--confirm-interactive` is an inert no-op on an autonomous kind: passing it to
/// a `spinoff` merge behaves identically to omitting it (merges, one report). The
/// `worktree-merge` skill passes the flag unconditionally, so this pins that the
/// flag never perturbs an autonomous self-merge.
#[test]
fn autonomous_run_merge_accepts_confirmation_flag_as_noop() {
    let home = TestHome::new();
    let scratch = TempDir::new().unwrap();
    let worktree = TempDir::new().unwrap();
    let run_id = create_run(&home, "spinoff", "auto-merge-flag");
    forge_worker_node(&home, &run_id, "spinoff", worktree.path(), "wt/test-x");

    let merge_sh = fake_merge_sh(scratch.path(), 0, "");
    let v = run_ok(bin(&home).env("OCTL_MERGE_SH", &merge_sh).args([
        "--output",
        "json",
        "run",
        "merge",
        &run_id,
        "--source",
        "main",
        "--confirm-interactive",
    ]));
    assert_eq!(
        v["data"]["merged"], true,
        "an autonomous kind merges the same whether or not the flag is present"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    let reports = node_reports(&events);
    assert_eq!(reports.len(), 1);
    assert_eq!(reports[0]["data"]["via"], "explicit-merge");
}

// --- Concurrent self-merge race (issue `concurrent-self-merge-race`) ---
//
// Several independent spinoffs that self-merge into the SAME source branch within
// seconds must serialize on the merge lock, never observe each other's mid-merge
// (transient-dirty) target state. The bug: merge.sh checked the target worktree
// for cleanliness BEFORE taking the serializing flock, so a concurrent merge that
// was mid-rebase made the checker fail with a spurious "uncommitted changes in
// target". The fix moves that check inside the lock; a lock-acquisition timeout is
// surfaced as a distinct, retryable `merge_in_progress` error. These two tests
// drive the REAL bundled `scripts/merge.sh` (via `OCTL_MERGE_SH`) against a real
// git repo + linked worktree; both exercised paths return before `workmux`, so
// they need neither `workmux` nor a live tmux.

/// Materialize the real bundled merge backend (not the stub) into `dir` with the
/// exec bit set, so these tests exercise the actual locking + cleanliness logic.
/// The checked-in `scripts/merge.sh` is not tracked executable, so it must be
/// copied + chmod'd (mirroring how `run merge` materializes the embedded copy).
fn real_merge_sh(dir: &Path) -> std::path::PathBuf {
    let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("scripts/merge.sh");
    let body = std::fs::read(&src).expect("read scripts/merge.sh");
    let dst = dir.join("merge.sh");
    std::fs::write(&dst, body).unwrap();
    let mut perms = std::fs::metadata(&dst).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&dst, perms).unwrap();
    dst
}

/// Kills and reaps a spawned child on drop — panic-safe cleanup for the
/// background merge-lock holder, so a failing assertion can't leave a `flock`
/// process (and its lock) alive for the rest of its sleep.
struct ChildGuard(std::process::Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// Spawn a background holder of the repo's merge lock — `flock`ing exactly the
/// path merge.sh derives (`<git-common-dir>/worktree-merge.lock`) — that touches
/// `ready` once it holds the lock, then holds it. The returned guard releases
/// the lock (kills the holder) on drop.
fn hold_merge_lock(repo: &Path, ready: &Path) -> ChildGuard {
    let lock = repo.join(".git").join("worktree-merge.lock");
    let child = Command::new("flock")
        .arg("-x")
        .arg(&lock)
        .arg("-c")
        .arg(format!("touch '{}'; sleep 30", ready.display()))
        .spawn()
        .expect("spawn flock holder");
    ChildGuard(child)
}

/// Spawn a holder that mimics a concurrent merge's full life: acquire the lock,
/// transiently dirty the target (`dirty`), signal `ready`, hold briefly, then
/// clean the target and release. A merge that blocks on the lock during the
/// dirty window must NOT observe the dirt — it acquires only after the clean.
fn hold_lock_dirty_then_clean(repo: &Path, dirty: &Path, ready: &Path) -> ChildGuard {
    let lock = repo.join(".git").join("worktree-merge.lock");
    let child = Command::new("flock")
        .arg("-x")
        .arg(&lock)
        .arg("-c")
        .arg(format!(
            "touch '{dirty}'; touch '{ready}'; sleep 2; rm -f '{dirty}'",
            dirty = dirty.display(),
            ready = ready.display(),
        ))
        .spawn()
        .expect("spawn flock holder");
    ChildGuard(child)
}

/// Create a dir holding a fake `workmux` that exits `code`, to prepend to PATH so
/// the real merge.sh can reach (and get past) the merge step without a real
/// workmux/tmux. Returns the dir to prepend.
fn fake_workmux_dir(dir: &Path, code: i32) -> std::path::PathBuf {
    let bindir = dir.join("fakebin");
    std::fs::create_dir_all(&bindir).unwrap();
    let p = bindir.join("workmux");
    std::fs::write(&p, format!("#!/bin/bash\nexit {code}\n")).unwrap();
    let mut perms = std::fs::metadata(&p).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&p, perms).unwrap();
    bindir
}

/// `PATH` with `prepend` in front of the inherited one.
fn path_with(prepend: &Path) -> String {
    format!(
        "{}:{}",
        prepend.display(),
        std::env::var("PATH").unwrap_or_default()
    )
}

/// Poll for a path to appear, up to `secs`. Panics if it never does.
fn wait_for(path: &Path, secs: u64) {
    for _ in 0..(secs * 50) {
        if path.exists() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    panic!("timed out waiting for {}", path.display());
}

/// THE regression for the race: another merge holds the lock AND the target
/// worktree is (transiently) dirty. Pre-fix, merge.sh checked the target BEFORE
/// the lock and failed immediately with the spurious "uncommitted changes in
/// target" (`merge_failed`). Post-fix, the checker lives inside the lock, so this
/// merge serializes: it blocks on the held lock and, when the hold outlasts the
/// timeout, surfaces the DISTINCT, retryable `merge_in_progress` — never the false
/// dirty-target failure. No terminal report is written (the merge never ran).
#[test]
fn concurrent_self_merge_serializes_instead_of_false_dirty() {
    let home = TestHome::new();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "spinoff", "race-merge");
    forge_worker_node(&home, &run_id, "spinoff", &wt, "wt/foo");

    // Simulate another merge's mid-rebase transient state: the target worktree is
    // dirty. Pre-fix this alone (checked before the lock) produced the false
    // positive; post-fix it is only inspected once we hold the lock.
    std::fs::write(repo.join("RACE.txt"), "in-flight merge state").unwrap();

    // Another merge holds the serializing lock for the whole test.
    let ready = gitroot.path().join("lock-ready");
    let _holder = hold_merge_lock(&repo, &ready);
    wait_for(&ready, 5);

    // Our merge waits on the lock, then times out (1s) — a serialization
    // conflict, surfaced as the distinct retryable code, NOT a dirty-tree error.
    let out = bin(&home)
        .env("OCTL_MERGE_SH", real_merge_sh(gitroot.path()))
        .env("MERGE_LOCK_TIMEOUT", "1")
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");

    assert!(
        !out.status.success(),
        "a merge blocked by a concurrent one must not succeed"
    );
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "merge_in_progress",
        "a lock-held concurrent merge must surface the distinct serialization code, \
         not a dirty-tree failure: {err}"
    );
    let msg = err["error"]["message"].as_str().unwrap_or_default();
    assert!(
        msg.contains("another merge is holding"),
        "the error must name the serialization conflict, not the transient dirt: {msg}"
    );
    assert!(
        !msg.to_lowercase().contains("uncommitted changes in target"),
        "the false-positive dirty-target error must be gone: {msg}"
    );

    // The merge never ran, so no terminal report was appended.
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(
        node_reports(&events).len(),
        0,
        "a serialized-out merge must not submit a terminal report"
    );
}

/// The genuine dirty-target safety check is preserved: with NO concurrent merge
/// (the lock is free) but the target worktree carrying real uncommitted user
/// work, merge.sh acquires the lock, finds the target dirty, and blocks with its
/// existing dirty-target message (`merge_failed`). Guards against the fix
/// weakening the real safety check while removing the racy pre-lock one.
#[test]
fn genuine_dirty_target_still_blocks() {
    let home = TestHome::new();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "spinoff", "dirty-target");
    forge_worker_node(&home, &run_id, "spinoff", &wt, "wt/foo");

    // Real uncommitted user work in the target, and NO lock holder — the merge
    // will acquire the lock and must still refuse a dirty target.
    std::fs::write(repo.join("USER-WORK.txt"), "human's uncommitted edit").unwrap();

    let out = bin(&home)
        .env("OCTL_MERGE_SH", real_merge_sh(gitroot.path()))
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");

    assert!(
        !out.status.success(),
        "a genuinely dirty target must still block the merge"
    );
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "merge_failed",
        "a genuine dirty target is a hard merge failure, not a serialization retry: {err}"
    );
    let msg = err["error"]["message"].as_str().unwrap_or_default();
    assert!(
        msg.to_lowercase().contains("uncommitted changes in target"),
        "the genuine dirty-target message must survive: {msg}"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(node_reports(&events).len(), 0);
}

/// The PRIMARY behavior the fix enables: a merge that starts while a concurrent
/// merge holds the lock AND has the target transiently dirty must SERIALIZE —
/// block on the lock, and only proceed once the peer releases and the target is
/// clean again — then SUCCEED. Pre-fix, the pre-lock dirty check made it fail
/// spuriously; post-fix, the check is behind the lock, so the transient dirt is
/// never observed and the merge lands. A fake `workmux` (exit 0) lets the real
/// merge.sh reach and pass the merge step without a real workmux/tmux.
#[test]
fn concurrent_self_merge_waits_then_succeeds() {
    let home = TestHome::new();
    let gitroot = TempDir::new().unwrap();
    let (repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "spinoff", "race-success");
    forge_worker_node(&home, &run_id, "spinoff", &wt, "wt/foo");

    let fakebin = fake_workmux_dir(gitroot.path(), 0);

    // A peer holds the lock, dirties the target for ~2s, then cleans + releases.
    let dirty = repo.join("PEER-INFLIGHT.txt");
    let ready = gitroot.path().join("lock-ready");
    let _holder = hold_lock_dirty_then_clean(&repo, &dirty, &ready);
    wait_for(&ready, 5); // peer now holds the lock with the target dirty

    // Launch our merge WHILE the peer holds the lock + target is dirty. It must
    // block on the lock (never seeing the dirt), then land once the peer frees.
    let v = run_ok(
        bin(&home)
            .env("OCTL_MERGE_SH", real_merge_sh(gitroot.path()))
            .env("PATH", path_with(&fakebin))
            .env("MERGE_LOCK_TIMEOUT", "30")
            .args([
                "--output", "json", "run", "merge", &run_id, "--source", "main",
            ]),
    );

    assert_eq!(
        v["data"]["merged"], true,
        "a merge that serialized behind a concurrent one must still land: {}",
        v["data"]
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    let reports = node_reports(&events);
    assert_eq!(reports.len(), 1, "the serialized merge submits one report");
    assert_eq!(reports[0]["data"]["via"], "explicit-merge");
}

/// A downstream command exiting 75 must NOT masquerade as the lock-timeout
/// `merge_in_progress`. merge.sh reserves exit 75 for the lock-timeout branch
/// and normalizes `workmux`'s exit, so a `workmux` that exits 75 (with the lock
/// free and the target clean) surfaces as a plain `merge_failed`.
#[test]
fn downstream_exit_75_is_not_merge_in_progress() {
    let home = TestHome::new();
    let gitroot = TempDir::new().unwrap();
    let (_repo, wt) = init_repo_with_worktree(gitroot.path());
    let run_id = create_run(&home, "spinoff", "exit75");
    forge_worker_node(&home, &run_id, "spinoff", &wt, "wt/foo");

    // No lock holder, target clean — the merge reaches workmux, which exits 75.
    let fakebin = fake_workmux_dir(gitroot.path(), 75);
    let out = bin(&home)
        .env("OCTL_MERGE_SH", real_merge_sh(gitroot.path()))
        .env("PATH", path_with(&fakebin))
        .args([
            "--output", "json", "run", "merge", &run_id, "--source", "main",
        ])
        .output()
        .expect("spawn");

    assert!(
        !out.status.success(),
        "a workmux failure must fail the merge"
    );
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON envelope");
    assert_eq!(
        err["error"]["code"], "merge_failed",
        "a downstream exit 75 must not be misread as a lock-timeout retry: {err}"
    );
    let events = run_dir(&home, &run_id).join("events.jsonl");
    assert_eq!(
        node_reports(&events).len(),
        0,
        "a failed merge writes no report"
    );
}

/// The human's sanctioned merge path — the bundled `worktree-merge` skill — MUST
/// pass `--confirm-interactive`, or a `code`-run merge driven through it would
/// hit the gate and fail. Cheap regression insurance against silently dropping
/// the flag from the skill template.
#[test]
fn worktree_merge_skill_passes_confirm_interactive() {
    let template = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("skills/worktree-merge/SKILL.template.md");
    let body = std::fs::read_to_string(&template)
        .unwrap_or_else(|e| panic!("read {}: {e}", template.display()));
    assert!(
        body.contains("--confirm-interactive"),
        "worktree-merge SKILL must pass --confirm-interactive so the human's \
         `code`-run merge clears the interactive gate"
    );
}