loopflow 0.12.10

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
mod support;

use std::fs;
use std::process::Command;
use std::thread;
use std::time::{Duration, Instant};

use loopflow::ops::{
    bump_version, generate_release, release_bump, release_check, release_notes, release_run,
    release_status, release_tag, NullProgress, ReleaseNotesDegradation, ReleaseNotesStatus,
    ReleaseRunOutcome,
};
use loopflow_test_support::TestRepo;
use support::EnvGuard;

fn write_gh_script(pr_list: &str) -> String {
    format!(
        "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n  echo 'gh version 2.0.0'\n  exit 0\nfi\ncase \"$1 $2\" in\n  'pr list')\n    cat <<'JSON'\n{pr_list}\nJSON\n    exit 0;;\nesac\necho \"unexpected gh invocation: $@\" >&2\nexit 1\n"
    )
}

fn write_gh_status_script(run_list: &str, release_view: &str) -> String {
    format!(
        "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n  echo 'gh version 2.0.0'\n  exit 0\nfi\ncase \"$1 $2\" in\n  'run list')\n    case \"$*\" in *databaseId*) ;; *) echo 'databaseId was not requested' >&2; exit 1;; esac\n    cat <<'JSON'\n{run_list}\nJSON\n    exit 0;;\n  'release view')\n    cat <<'JSON'\n{release_view}\nJSON\n    exit 0;;\n  'pr list') echo '[]'; exit 0;;\nesac\necho \"unexpected gh invocation: $@\" >&2\nexit 1\n"
    )
}

fn write_gh_incomplete_release_script() -> &'static str {
    "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n  echo 'gh version 2.0.0'\n  exit 0\nfi\ncase \"$1 $2\" in\n  'release view') exit 1;;\n  'run list') echo '[]'; exit 0;;\nesac\necho \"unexpected gh invocation: $@\" >&2\nexit 1\n"
}

fn write_gh_failed_release_script() -> &'static str {
    "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n  echo 'gh version 2.0.0'\n  exit 0\nfi\ncase \"$1 $2\" in\n  'release view') exit 1;;\n  'run list') cat <<'JSON'\n[{\"databaseId\":42,\"headBranch\":\"v0.9.1\",\"status\":\"completed\",\"conclusion\":\"failure\",\"url\":\"https://example.com/run/42\"}]\nJSON\n    exit 0;;\n  'pr list') echo '[]'; exit 0;;\nesac\necho \"unexpected gh invocation: $@\" >&2\nexit 1\n"
}

fn write_gh_dropped_auto_merge_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
log="{log_path}"
armed="{log_path}.armed"
if [ "$1" = "--version" ]; then
  exit 0
fi
printf '%s\n' "$*" >> "$log"
case "$1 $2" in
  'pr list')
    case " $* " in
      *' --head '*)
        head="$(git rev-parse HEAD)"
        printf '[{{"number":1176,"state":"OPEN","mergeCommit":null,"url":"https://example.com/pr/1176","headRefOid":"%s"}}]\n' "$head"
        ;;
      *) echo '[]' ;;
    esac
    exit 0;;
  'pr view')
    head="$(git rev-parse HEAD)"
    if [ -f "$armed" ]; then
      printf '{{"state":"MERGED","mergeStateStatus":"UNKNOWN","mergeCommit":{{"oid":"%s"}},"url":"https://example.com/pr/1176"}}\n' "$head"
    else
      printf '{{"state":"OPEN","mergeStateStatus":"CLEAN","mergeCommit":null,"url":"https://example.com/pr/1176"}}\n'
    fi
    exit 0;;
  'api graphql')
    if [ -f "$armed" ]; then echo 'true'; else echo 'false'; fi
    exit 0;;
  'pr merge')
    touch "$armed"
    exit 0;;
  'release view') exit 1;;
esac
echo "unexpected gh invocation: $*" >&2
exit 1
"#
    )
}

fn write_gh_dirty_release_script(
    log_path: &str,
    release_branch: &str,
    main_branch: &str,
) -> String {
    format!(
        r#"#!/bin/sh
log="{log_path}"
integrated="{log_path}.integrated"
seen="{log_path}.seen"
release_branch="{release_branch}"
main_branch="{main_branch}"
if [ "$1" = "--version" ]; then
  exit 0
fi
printf '%s\n' "$*" >> "$log"
case "$1 $2" in
  'pr list')
    case " $* " in
      *' --head '*)
        head="$(git ls-remote origin "refs/heads/$release_branch" | cut -f1)"
        printf '[{{"number":1176,"state":"OPEN","isDraft":false,"mergeCommit":null,"url":"https://example.com/pr/1176","headRefOid":"%s"}}]\n' "$head"
        ;;
      *) echo '[]' ;;
    esac
    exit 0;;
  'pr view')
    release_head="$(git ls-remote origin "refs/heads/$release_branch" | cut -f1)"
    if [ -f "$integrated" ]; then
      printf '{{"state":"MERGED","mergeStateStatus":"UNKNOWN","mergeCommit":{{"oid":"%s"}},"url":"https://example.com/pr/1176"}}\n' "$release_head"
    elif [ ! -f "$seen" ]; then
      touch "$seen"
      printf '{{"state":"OPEN","mergeStateStatus":"DIRTY","mergeCommit":null,"url":"https://example.com/pr/1176"}}\n'
    else
      main_head="$(git ls-remote origin "refs/heads/$main_branch" | cut -f1)"
      if git merge-base --is-ancestor "$main_head" "$release_head"; then
        merge_state=CLEAN
      else
        merge_state=BEHIND
      fi
      printf '{{"state":"OPEN","mergeStateStatus":"%s","mergeCommit":null,"url":"https://example.com/pr/1176"}}\n' "$merge_state"
    fi
    exit 0;;
  'api graphql') echo 'false'; exit 0;;
  'pr merge')
    release_head="$(git ls-remote origin "refs/heads/$release_branch" | cut -f1)"
    main_head="$(git ls-remote origin "refs/heads/$main_branch" | cut -f1)"
    if git merge-base --is-ancestor "$main_head" "$release_head"; then
      touch "$integrated"
    fi
    exit 0;;
  'pr ready'|'pr edit') exit 0;;
  'release view') exit 1;;
esac
echo "unexpected gh invocation: $*" >&2
exit 1
"#
    )
}

fn git(repo: &TestRepo, args: &[&str]) {
    let _ = git_output(repo, args);
}

fn git_output(repo: &TestRepo, args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .current_dir(repo.path())
        .output()
        .expect("run git");
    assert!(
        output.status.success(),
        "git {:?} failed: {}",
        args,
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

fn git_output_bare(repo: &TestRepo, args: &[&str]) -> String {
    let output = Command::new("git")
        .arg("--git-dir")
        .arg(repo.bare_path())
        .args(args)
        .output()
        .expect("run git");
    assert!(
        output.status.success(),
        "git --git-dir {:?} {:?} failed: {}",
        repo.bare_path(),
        args,
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

fn wait_for_path(path: &std::path::Path) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while !path.exists() {
        assert!(
            Instant::now() < deadline,
            "timed out waiting for {}",
            path.display()
        );
        thread::sleep(Duration::from_millis(20));
    }
}

#[test]
fn release_generates_notes_and_writes_file() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.8.0"]);
    fs::write(repo.path().join("feature.txt"), "released\n").unwrap();
    git(&repo, &["add", "feature.txt"]);
    git(&repo, &["commit", "-m", "Add release command"]);
    let sha = git_output(&repo, &["rev-parse", "HEAD"]);
    let pr_list = format!(
        r#"[{{"number":101,"title":"Add release command","body":"Users can now run lf release.","mergeCommit":{{"oid":"{sha}"}}}}]"#
    );
    let gh_script = write_gh_script(&pr_list);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let version =
        generate_release(repo.path(), "v0.9.1", &NullProgress).expect("release should succeed");

    assert_eq!(version, "0.9.1");

    let notes = fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).expect("read notes");
    assert!(notes.starts_with("# v0.9.1\n\n"));
    assert!(notes.contains("## Merged PRs"));
    assert!(notes.contains("- #101 Add release command"));
}

#[test]
fn release_keeps_existing_header() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);

    generate_release(repo.path(), "0.9.2", &NullProgress).expect("release should succeed");

    let notes = fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).expect("read notes");
    assert_eq!(notes.lines().next().expect("first line"), "# v0.9.2");
    assert_eq!(notes.matches("# v0.9.2").count(), 1);
}

#[test]
fn release_with_bump_keyword() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);

    let version =
        generate_release(repo.path(), "patch", &NullProgress).expect("release should succeed");
    assert_eq!(version, "0.9.2");

    let notes = fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).expect("read notes");
    assert!(notes.starts_with("# v0.9.2\n\n"));
}

#[test]
fn release_notes_falls_back_when_agent_cli_is_missing() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    fs::write(repo.path().join("weekly.txt"), "self-contained\n").unwrap();
    git(&repo, &["add", "weekly.txt"]);
    git(
        &repo,
        &["commit", "-m", "Make weekly release self-contained"],
    );
    let sha = git_output(&repo, &["rev-parse", "HEAD"]);
    let pr_list = format!(
        r#"[{{"number":101,"title":"Make weekly release self-contained","body":"Release automation no longer requires a workstation CLI.","additions":42,"deletions":7,"changedFiles":3,"mergeCommit":{{"oid":"{sha}"}}}}]"#
    );
    let gh_script = write_gh_script(&pr_list);
    let lf_script =
        "#!/bin/sh\necho \"'claude' CLI not found. Install it and rerun \\`lf init\\`.\" >&2\nexit 1\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    // A staged unreleased artifact still gets promoted; it is no longer a
    // decisions ledger and no longer injected into the notes.
    fs::create_dir_all(repo.path().join("release/unreleased")).unwrap();
    fs::write(
        repo.path().join("release/unreleased/CHANGES.md"),
        "staged artifact\n",
    )
    .unwrap();

    let notes = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect("release notes should fall back");

    assert!(notes.starts_with("# v0.9.1\n\n"));
    assert!(notes.contains("loopflow:release-notes=degraded;reason=missing-cli;gate=safe"));
    assert!(notes.contains("_Generated mechanically for v0.9.1._"));
    // Notes synthesize from the merged PRs, not a central ledger.
    assert!(notes.contains("Make weekly release self-contained"));
    assert!(!notes.contains("## Release decisions"));
    assert_eq!(
        fs::read_to_string(repo.path().join("release/v0.9.1/NOTES.md")).unwrap(),
        notes,
    );
    // The unreleased dir was promoted to the version dir.
    assert!(!repo.path().join("release/unreleased").exists());
    assert!(repo.path().join("release/v0.9.1/CHANGES.md").exists());
}

#[test]
fn release_notes_falls_back_for_every_provider_degradation_class() {
    let gh_script = write_gh_script("[]");
    let lf_script = "#!/bin/sh\ncat .provider-failure >&2\nexit 1\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let cases = [
        (
            "failed to select provider account: no eligible managed codex account: 'primary'",
            ReleaseNotesDegradation::Cooldown,
        ),
        (
            "agent stopped after account subscription limit",
            ReleaseNotesDegradation::Quota,
        ),
        (
            "agent stopped after account credential invalidated",
            ReleaseNotesDegradation::Authentication,
        ),
        (
            "agent stopped after provider rate limit",
            ReleaseNotesDegradation::RateLimit,
        ),
        (
            "agent stopped after provider unavailable",
            ReleaseNotesDegradation::ProviderUnavailable,
        ),
        (
            "agent stopped after provider capacity",
            ReleaseNotesDegradation::ProviderUnavailable,
        ),
        (
            "agent stopped after provider transport",
            ReleaseNotesDegradation::ProviderUnavailable,
        ),
    ];

    for (failure, degradation) in cases {
        let repo = TestRepo::new();
        git(&repo, &["tag", "v0.9.0"]);
        fs::write(repo.path().join(".provider-failure"), failure).unwrap();

        let notes = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
            .expect("provider degradation should select deterministic notes");

        assert!(notes.contains(&format!(
            "loopflow:release-notes=degraded;reason={degradation};gate=safe"
        )));
        assert!(notes.contains("_Generated mechanically for v0.9.1._"));
        assert!(notes.len() < 60 * 1024);
    }
}

#[test]
fn release_notes_bounds_oversized_pr_bodies_and_queue_metadata() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    fs::write(
        repo.path().join("RELEASE_NOTES.md"),
        "previous voice ".repeat(4_000),
    )
    .unwrap();
    fs::create_dir_all(repo.path().join("release/unreleased")).unwrap();
    fs::write(
        repo.path().join("release/unreleased/DECISIONS.md"),
        "bounded decision ".repeat(4_000),
    )
    .unwrap();
    fs::write(repo.path().join("bounded.txt"), "bounded\n").unwrap();
    git(&repo, &["add", "bounded.txt"]);
    git(&repo, &["commit", "-m", "Bound release context"]);
    let sha = git_output(&repo, &["rev-parse", "HEAD"]);
    let pr_list = serde_json::to_string(&vec![serde_json::json!({
        "number": 202,
        "title": "Bound release context",
        "body": "x".repeat(100_000),
        "additions": 8,
        "deletions": 2,
        "changedFiles": 1,
        "mergeCommit": {"oid": sha},
    })])
    .unwrap();
    let gh_script = write_gh_script(&pr_list);
    let lf_script = "#!/bin/sh\ncp \"$LF_RELEASE_NOTES_CONTEXT\" RELEASE_CONTEXT.json\nprintf '# v0.9.1\\n\\nBounded narrative notes.\\n' > RELEASE_NOTES.md\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);

    let notes = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect("bounded narrative notes should succeed");

    let context_path = repo.path().join("RELEASE_CONTEXT.json");
    assert!(fs::metadata(&context_path).unwrap().len() <= 128 * 1024);
    let context: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(context_path).unwrap()).unwrap();
    assert!(context["merged_prs"][0]["body"].as_str().unwrap().len() <= 4 * 1024);
    assert!(context["omissions"]["text_bytes"].as_u64().unwrap() >= 95_000);
    assert!(context["decisions"].as_str().unwrap().len() <= 16 * 1024);
    assert!(context["previous_release_notes"].as_str().unwrap().len() <= 16 * 1024);
    assert!(context["omissions"]["decisions_bytes"].as_u64().unwrap() > 0);
    assert!(
        context["omissions"]["previous_release_notes_bytes"]
            .as_u64()
            .unwrap()
            > 0
    );
    assert!(notes.len() < 60 * 1024);
    assert!(!notes.contains(&"x".repeat(1_000)));
}

#[test]
fn interrupted_release_notes_retry_replaces_partial_state_once() {
    let gh_script = write_gh_script("[]");
    let lf_script = r#"#!/bin/sh
attempt=1
if [ -f .notes-attempt ]; then
  attempt=2
fi
printf '%s' "$attempt" > .notes-attempt
cp "$LF_RELEASE_NOTES_CONTEXT" "RELEASE_CONTEXT.$attempt.json"
if [ "$attempt" = "1" ]; then
  printf '# v0.9.1\n\nPartial notes that must not ship.\n' > RELEASE_NOTES.md
  echo 'operator interrupted release-notes generation' >&2
  exit 130
fi
printf '# v0.9.1\n\nConcise resumed release notes.\n' > RELEASE_NOTES.md
"#;
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    let previous_notes = "# v0.9.0\n\nPrevious safe notes.\n";
    fs::write(repo.path().join("RELEASE_NOTES.md"), previous_notes).unwrap();

    let error = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect_err("an unclassified interruption must keep the gate red");
    assert!(error.to_string().contains("release gate blocked"));
    assert_eq!(
        fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).unwrap(),
        previous_notes
    );

    let notes = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect("retry should replace partial state");

    assert!(
        fs::metadata(repo.path().join("RELEASE_CONTEXT.1.json"))
            .unwrap()
            .len()
            <= 128 * 1024
    );
    assert!(
        fs::metadata(repo.path().join("RELEASE_CONTEXT.2.json"))
            .unwrap()
            .len()
            <= 128 * 1024
    );
    assert!(notes.contains("Concise resumed release notes."));
    assert!(!notes.contains("Partial notes that must not ship."));
    assert_eq!(notes.matches("loopflow:release-notes=").count(), 1);
    let archived = fs::read_to_string(repo.path().join("release/v0.9.1/NOTES.md")).unwrap();
    assert_eq!(archived, notes);
    assert_eq!(
        fs::read_dir(repo.path().join("release/v0.9.1"))
            .unwrap()
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name() == "NOTES.md")
            .count(),
        1
    );
}

#[test]
fn successful_agent_without_fresh_notes_keeps_release_gate_unsafe() {
    let gh_script = write_gh_script("[]");
    let lf_script = "#!/bin/sh\nexit 0\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    let previous_notes = "# v0.9.0\n\nPrevious safe notes.\n";
    fs::write(repo.path().join("RELEASE_NOTES.md"), previous_notes).unwrap();

    let error = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect_err("missing fresh notes must stop the gate");

    assert!(error.to_string().contains("release gate blocked"));
    assert!(error.to_string().contains("fresh RELEASE_NOTES.md"));
    assert_eq!(
        fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).unwrap(),
        previous_notes
    );
}

#[test]
fn release_notes_rejects_a_successful_agent_with_stale_version() {
    let gh_script = write_gh_script("[]");
    let lf_script =
        "#!/bin/sh\nprintf '# v0.9.0\\n\\nWrong generated release.\\n' > RELEASE_NOTES.md\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    let previous_notes = "# v0.9.0\n\nPrevious safe notes.\n";
    fs::write(repo.path().join("RELEASE_NOTES.md"), previous_notes).unwrap();

    let error = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect_err("stale-version notes must stop the gate");

    assert!(error.to_string().contains("release gate blocked"));
    assert!(error.to_string().contains("must start with '# v0.9.1'"));
    assert_eq!(
        fs::read_to_string(repo.path().join("RELEASE_NOTES.md")).unwrap(),
        previous_notes
    );
}

#[test]
fn oversized_agent_notes_keep_queue_metadata_unsafe() {
    let gh_script = write_gh_script("[]");
    let lf_script = r#"#!/bin/sh
{
  printf '# v0.9.1\n\n'
  i=0
  while [ "$i" -lt 7000 ]; do
    printf '0123456789'
    i=$((i + 1))
  done
} > RELEASE_NOTES.md
"#;
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);

    let error = release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect_err("oversized queue metadata must stop the gate");

    assert!(error.to_string().contains("release gate blocked"));
    assert!(error.to_string().contains("maximum queue metadata"));
    assert!(!repo.path().join("RELEASE_NOTES.md").exists());
}

#[test]
fn release_notes_context_fuses_decisions_with_exact_commits() {
    let gh_script = write_gh_script("[]");
    let lf_script = "#!/bin/sh\ncp \"$LF_RELEASE_NOTES_CONTEXT\" RELEASE_CONTEXT.json\nprintf '# v0.9.1\\n\\nPrepared from context.\\n' > RELEASE_NOTES.md\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    fs::write(repo.path().join("feature.txt"), "release behavior\n").unwrap();
    git(&repo, &["add", "feature.txt"]);
    git(&repo, &["commit", "-m", "Ship release behavior"]);
    fs::create_dir_all(repo.path().join("release/unreleased")).unwrap();
    fs::write(
        repo.path().join("release/unreleased/DECISIONS.md"),
        "Prefer explicit completion evidence.\n",
    )
    .unwrap();

    release_notes(repo.path(), "0.9.1", Some("v0.9.0"), None, &NullProgress)
        .expect("release notes should succeed");

    let context: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(repo.path().join("RELEASE_CONTEXT.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        context["decisions"],
        "Prefer explicit completion evidence.\n"
    );
    assert_eq!(context["commits"][0]["title"], "Ship release behavior");
    assert!(context["merged_prs"].as_array().unwrap().is_empty());
}

#[test]
fn bump_version_patch() {
    assert_eq!(bump_version("v1.2.3", "patch").unwrap(), "1.2.4");
}

#[test]
fn bump_version_minor() {
    assert_eq!(bump_version("1.2.3", "minor").unwrap(), "1.3.0");
}

#[test]
fn bump_version_major() {
    assert_eq!(bump_version("v0.9.1", "major").unwrap(), "1.0.0");
}

#[test]
fn bump_version_invalid_format() {
    assert!(bump_version("1.2", "patch").is_err());
}

#[test]
fn release_check_returns_merged_prs() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    fs::write(repo.path().join("feature.txt"), "new stuff\n").unwrap();
    git(&repo, &["add", "feature.txt"]);
    git(&repo, &["commit", "-m", "Add feature"]);
    let sha = git_output(&repo, &["rev-parse", "HEAD"]);
    let old_sha = git_output(&repo, &["rev-parse", "v0.9.0"]);
    let pr_list = format!(
        r#"[{{"number":41,"title":"Old same-day change","body":"Already tagged","mergeCommit":{{"oid":"{old_sha}"}}}},{{"number":42,"title":"Add feature","body":"New stuff","additions":100,"deletions":10,"changedFiles":3,"mergeCommit":{{"oid":"{sha}"}}}}]"#
    );
    let gh_script = write_gh_script(&pr_list);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let changes = release_check(repo.path(), None).expect("check should succeed");
    assert_eq!(changes.commits.len(), 1);
    assert_eq!(changes.commits[0].title, "Add feature");
    assert_eq!(changes.merged_prs.len(), 1);
    assert_eq!(changes.merged_prs[0].number, 42);
    assert_eq!(changes.merged_prs[0].title, "Add feature");
}

#[test]
fn release_check_uses_direct_commits_as_release_truth() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    fs::write(repo.path().join("direct.txt"), "shipped without a PR\n").unwrap();
    git(&repo, &["add", "direct.txt"]);
    git(&repo, &["commit", "-m", "Ship a direct commit"]);

    let changes = release_check(repo.path(), None).expect("check should succeed");

    assert_eq!(changes.commits.len(), 1);
    assert_eq!(changes.commits[0].title, "Ship a direct commit");
    assert!(changes.merged_prs.is_empty());
}

#[test]
fn release_check_reconciles_version_tags_to_origin() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.0"]);
    git(&repo, &["push", "origin", "v0.9.0"]);
    let stale_sha = git_output(&repo, &["rev-parse", "v0.9.0"]);

    fs::write(repo.path().join("repair.txt"), "remote release truth\n").unwrap();
    git(&repo, &["add", "repair.txt"]);
    git(&repo, &["commit", "-m", "Repair release tag"]);
    let remote_sha = git_output(&repo, &["rev-parse", "HEAD"]);
    git(&repo, &["push", "origin", "HEAD:refs/heads/tag-repair"]);
    git_output_bare(
        &repo,
        &["update-ref", "refs/tags/v0.9.0", &remote_sha, &stale_sha],
    );
    let changes = release_check(repo.path(), None).expect("check should reconcile tags");

    assert!(changes.commits.is_empty());
    assert_eq!(git_output(&repo, &["rev-parse", "v0.9.0"]), remote_sha);
}

#[test]
fn release_check_reads_evidence_without_running_repository_hooks() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join(".lf")).unwrap();
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    app:\n      verify:\n        - exit 19\n",
    )
    .unwrap();

    let changes = release_check(repo.path(), Some("app")).expect("check should stay read-only");

    assert!(!changes.commits.is_empty());
}

#[test]
fn release_check_returns_empty_without_tag() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    // No tags means the first-parent history is the initial release range.
    let changes = release_check(repo.path(), None).expect("check should succeed");
    assert!(!changes.commits.is_empty());
    assert!(changes.merged_prs.is_empty());
}

#[test]
fn release_run_is_a_green_noop_without_merged_changes() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);

    let outcome = release_run(repo.path(), "patch", None, &NullProgress)
        .expect("empty release should succeed");

    assert_eq!(
        outcome,
        ReleaseRunOutcome::NoChanges {
            target: "default".to_string(),
            latest_tag: Some("v0.9.1".to_string()),
        }
    );
}

#[test]
fn release_run_checks_the_host_local_publisher_role() {
    let gh_script = write_gh_status_script("[]", r#"{"isDraft":false}"#);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    let checked = repo.path().join("publisher-checked");
    let publisher = repo.path().join("publisher.sh");
    fs::write(
        &publisher,
        format!(
            "#!/bin/sh\n[ \"$1\" = check ] || exit 19\n: > '{}'\n",
            checked.display()
        ),
    )
    .expect("write publisher");
    fs::create_dir_all(repo.path().join(".lf")).expect("create config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      publisher: [\"sh\", \"{repo}/publisher.sh\"]\n",
    )
    .expect("write config");
    git(&repo, &["add", ".lf/config.yaml", "publisher.sh"]);
    git(&repo, &["commit", "-m", "Configure publisher role"]);
    git(&repo, &["push", "origin", "HEAD"]);
    git(&repo, &["tag", "v0.9.1"]);

    let outcome = release_run(repo.path(), "patch", None, &NullProgress)
        .expect("configured publisher should pass preflight");

    assert!(checked.exists());
    assert_eq!(
        outcome,
        ReleaseRunOutcome::NoChanges {
            target: "default".to_string(),
            latest_tag: Some("v0.9.1".to_string()),
        }
    );
}

#[test]
fn release_run_rearms_a_dropped_auto_merge_for_the_exact_head() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);
    git(&repo, &["push", "origin", "v0.9.1"]);
    fs::write(repo.path().join("feature.txt"), "release me\n").unwrap();
    git(&repo, &["add", "feature.txt"]);
    git(&repo, &["commit", "-m", "Add release change"]);
    git(&repo, &["push", "origin", "HEAD"]);
    let head = git_output(&repo, &["rev-parse", "HEAD"]);
    let state = tempfile::tempdir().expect("release state");
    let log_path = state.path().join("gh.log");
    let gh_script = write_gh_dropped_auto_merge_script(&log_path.to_string_lossy());
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let outcome = release_run(repo.path(), "patch", None, &NullProgress)
        .expect("release should re-arm and resume");

    let ReleaseRunOutcome::Released(receipt) = outcome else {
        panic!("expected a released receipt");
    };
    assert_eq!(receipt.version, "0.9.2");
    assert_eq!(receipt.tag, "v0.9.2");
    assert_eq!(receipt.commit, head);
    let log = fs::read_to_string(log_path).expect("read gh log");
    assert!(log.contains("api graphql"));
    assert!(log.contains(&format!(
        "pr merge 1176 --squash --auto --match-head-commit {head}"
    )));
}

#[test]
fn release_run_reintegrates_a_dirty_existing_pr() {
    let repo = TestRepo::new();
    let main_branch = git_output(&repo, &["branch", "--show-current"]);
    let state = tempfile::tempdir().expect("release state");
    let log_path = state.path().join("gh.log");
    let prepare_runs = state.path().join("prepare-runs");
    let advance_once = state.path().join("advance-once");
    git(&repo, &["tag", "v0.9.1"]);
    git(&repo, &["push", "origin", "v0.9.1"]);
    fs::write(repo.path().join("feature.txt"), "release me\n").unwrap();
    git(&repo, &["add", "feature.txt"]);
    git(&repo, &["commit", "-m", "Add release change"]);
    git(&repo, &["push", "origin", "HEAD"]);

    let release_branch = "jack/release-default-v0-9-2";
    git(&repo, &["checkout", "-b", release_branch]);
    fs::write(
        repo.path().join("RELEASE_NOTES.md"),
        "# v0.9.2\n\nRelease notes.\n",
    )
    .unwrap();
    git(&repo, &["add", "RELEASE_NOTES.md"]);
    git(&repo, &["commit", "-m", "release: v0.9.2"]);
    git(&repo, &["push", "-u", "origin", release_branch]);
    git(&repo, &["checkout", &main_branch]);
    git(&repo, &["branch", "-D", release_branch]);
    git(
        &repo,
        &[
            "update-ref",
            "-d",
            &format!("refs/remotes/origin/{release_branch}"),
        ],
    );
    fs::write(
        repo.path().join("RELEASE_NOTES.md"),
        "# v0.9.1\n\nCorrected prior release notes.\n",
    )
    .unwrap();
    fs::create_dir_all(repo.path().join(".lf")).unwrap();
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      prepare:\n      - sh prepare.sh {version}\n",
    )
    .unwrap();
    fs::write(
        repo.path().join("prepare.sh"),
        format!(
            "#!/bin/sh\nprintf 'run\\n' >> '{}'\nprintf '%s\\n' \"$1\" > prepared-version.txt\ngit -C '{}' rev-parse 'origin/{}' > prepared-main.txt\nif [ ! -f '{}' ]; then\n  : > '{}'\n  printf 'late main change\\n' > '{}/late-main.txt'\n  git -C '{}' add late-main.txt\n  git -C '{}' commit -m 'Advance main during release preparation'\n  git -C '{}' push origin HEAD\nfi\n",
            prepare_runs.display(),
            repo.path().display(),
            main_branch,
            advance_once.display(),
            advance_once.display(),
            repo.path().display(),
            repo.path().display(),
            repo.path().display(),
            repo.path().display(),
        ),
    )
    .unwrap();
    git(
        &repo,
        &["add", "RELEASE_NOTES.md", ".lf/config.yaml", "prepare.sh"],
    );
    git(&repo, &["commit", "-m", "Correct prior release notes"]);
    git(&repo, &["push", "origin", "HEAD"]);

    let gh_script =
        write_gh_dirty_release_script(&log_path.to_string_lossy(), release_branch, &main_branch);
    let lf_script = "#!/bin/sh\ncat > RELEASE_NOTES.md <<'EOF'\n# v0.9.2\n\n<!-- loopflow:release-notes=narrative;gate=safe -->\n\nRegenerated release notes.\nEOF\n";
    let _env = EnvGuard::new(&[("gh", gh_script.as_str()), ("lf", lf_script)]);
    std::env::set_var("LF_RUN_CONTEXT", "agent");
    std::env::set_var("LF_RUN_ID", "run_stale");
    std::env::set_var("LF_RUN_LEASE", "stale-lease");
    std::env::set_var("LF_AGENT_INVOCATION_ID", "invocation_stale");
    std::env::set_var("LF_WAVE_ID", "wave_stale");

    let outcome = release_run(repo.path(), "patch", None, &NullProgress)
        .expect("release should reintegrate without inheriting Task authority");

    let ReleaseRunOutcome::Released(receipt) = outcome else {
        panic!("expected a released receipt");
    };
    let integrated_head = git_output_bare(
        &repo,
        &["rev-parse", &format!("refs/heads/{release_branch}")],
    );
    let integrated_parent = git_output_bare(&repo, &["rev-parse", &format!("{integrated_head}^")]);
    assert_eq!(receipt.commit, integrated_head);
    assert_eq!(
        fs::read_to_string(&prepare_runs)
            .expect("read preparation runs")
            .lines()
            .count(),
        2,
        "a main advance after preparation must rerun preparation"
    );
    assert_eq!(
        git_output_bare(
            &repo,
            &["show", &format!("{integrated_head}:prepared-main.txt")],
        ),
        integrated_parent
    );
    assert_eq!(
        git_output_bare(
            &repo,
            &["show", &format!("{integrated_head}:RELEASE_NOTES.md")],
        ),
        "# v0.9.2\n\n<!-- loopflow:release-notes=narrative;gate=safe -->\n\nRegenerated release notes."
    );
    assert_eq!(
        git_output_bare(
            &repo,
            &["show", &format!("{integrated_head}:prepared-version.txt")],
        ),
        "0.9.2"
    );
    let log = fs::read_to_string(log_path).expect("read gh log");
    assert!(log.contains(&format!(
        "pr merge 1176 --squash --auto --match-head-commit {integrated_head}"
    )));
}

#[test]
fn release_run_fails_closed_when_the_publisher_role_is_missing() {
    let gh_script = write_gh_script("[]");
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join(".lf")).expect("create config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      publisher: [\"missing-release-publisher-role\"]\n",
    )
    .expect("write config");
    git(&repo, &["add", ".lf/config.yaml"]);
    git(&repo, &["commit", "-m", "Require publisher role"]);
    git(&repo, &["push", "origin", "HEAD"]);
    git(&repo, &["tag", "v0.9.1"]);
    let head_before = git_output(&repo, &["rev-parse", "HEAD"]);
    let tags_before = git_output(&repo, &["tag", "--list"]);

    let error = release_run(repo.path(), "patch", None, &NullProgress)
        .expect_err("missing publisher authority must stop release");

    assert!(error.to_string().contains("missing-release-publisher-role"));
    assert_eq!(git_output(&repo, &["rev-parse", "HEAD"]), head_before);
    assert_eq!(git_output(&repo, &["tag", "--list"]), tags_before);
}

#[test]
fn release_run_refuses_to_skip_an_incomplete_tag() {
    let _env = EnvGuard::new(&[("gh", write_gh_incomplete_release_script())]);

    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join(".lf")).expect("create config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      publisher: [\"true\"]\n",
    )
    .expect("write config");
    git(&repo, &["tag", "v0.9.1"]);

    let error = release_run(repo.path(), "patch", None, &NullProgress)
        .expect_err("incomplete tag should stop the release");

    assert!(error.to_string().contains("v0.9.1 is incomplete"));
}

#[test]
fn release_run_keeps_a_failed_tag_red_until_a_fix_merges() {
    let _env = EnvGuard::new(&[("gh", write_gh_failed_release_script())]);

    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join(".lf")).expect("create config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      publisher: [\"true\"]\n",
    )
    .expect("write config");
    git(&repo, &["tag", "v0.9.1"]);

    let error = release_run(repo.path(), "patch", None, &NullProgress)
        .expect_err("failed build without a fix should stay red");

    assert!(error.to_string().contains("no merged fix is available"));
}

#[test]
fn active_tagged_publisher_blocks_concurrent_cleanup_until_exit() {
    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);
    git(&repo, &["push", "origin", "v0.9.1"]);
    let state = tempfile::tempdir().expect("publisher state");
    let ready = state.path().join("ready");
    let publish = state.path().join("publish");
    let completed = state.path().join("completed");
    let exit = state.path().join("exit");
    let published = state.path().join("published");
    let publisher = repo.path().join("publisher.sh");
    fs::write(
        &publisher,
        format!(
            r#"#!/bin/sh
case "$1" in
  check) exit 0 ;;
  publish)
    worktree="$LF_RELEASE_SOURCE_REPO"
    [ -e "$worktree/.git" ] || {{ echo 'tagged source missing' >&2; exit 41; }}
    [ ! -f "$worktree/publisher.sh" ] || {{ echo 'publisher control came from tag' >&2; exit 42; }}
    : > '{}'
    attempts=0
    while [ ! -f '{}' ] && [ "$attempts" -lt 500 ]; do
      attempts=$((attempts + 1))
      sleep 0.02
    done
    [ -d "$worktree" ] || {{ echo 'publisher worktree disappeared' >&2; exit 43; }}
    : > '{}'
    : > '{}'
    attempts=0
    while [ ! -f '{}' ] && [ "$attempts" -lt 500 ]; do
      attempts=$((attempts + 1))
      sleep 0.02
    done
    [ -d "$worktree" ] || {{ echo 'publisher worktree disappeared before exit' >&2; exit 44; }}
    exit 0 ;;
esac
exit 2
"#,
            ready.display(),
            publish.display(),
            published.display(),
            completed.display(),
            exit.display(),
        ),
    )
    .expect("write publisher");

    let gh_script = format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  echo 'gh version 2.0.0'
  exit 0
fi
case "$1 $2" in
  'release view')
    if [ -f '{}' ]; then
      echo '{{"isDraft":false}}'
      exit 0
    fi
    exit 1 ;;
  'run list')
    echo '[{{"databaseId":42,"headBranch":"v0.9.1","status":"completed","conclusion":"success"}}]'
    exit 0 ;;
  'run download') exit 0 ;;
esac
echo "unexpected gh invocation: $@" >&2
exit 1
"#,
        published.display(),
    );
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    fs::create_dir_all(repo.path().join(".lf")).expect("config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        "release:\n  targets:\n    default:\n      publisher: [\"sh\", \"{repo}/publisher.sh\"]\n",
    )
    .expect("release config");
    git(&repo, &["add", ".lf/config.yaml", "publisher.sh"]);
    git(&repo, &["commit", "-m", "Add current publisher controller"]);
    git(&repo, &["push", "origin", "HEAD"]);
    let tags_before = git_output(&repo, &["tag", "--list"]);
    let neighbor = repo.create_named_worktree("neighbor");
    let repo_name = repo
        .path()
        .file_name()
        .expect("repo name")
        .to_string_lossy();
    let publisher_worktree = repo
        .path()
        .parent()
        .expect("repo parent")
        .join(format!("{repo_name}.publish-default-v0-9-1"));

    let release = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["release", "run", "patch"])
        .current_dir(repo.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("start release re-entry");

    wait_for_path(&ready);
    assert!(publisher_worktree.exists());
    let removal = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["wt", "remove", "publish-default-v0-9-1"])
        .current_dir(repo.path())
        .output()
        .expect("attempt concurrent cleanup");

    assert!(!removal.status.success());
    assert!(
        String::from_utf8_lossy(&removal.stderr).contains("release publisher for v0.9.1"),
        "unexpected cleanup error: {}",
        String::from_utf8_lossy(&removal.stderr)
    );
    assert!(publisher_worktree.exists());
    assert!(neighbor.exists());

    fs::write(&publish, "").expect("allow publication");
    wait_for_path(&completed);
    assert!(
        publisher_worktree.exists(),
        "owner cleanup must wait for publisher exit"
    );
    fs::write(&exit, "").expect("allow publisher exit");

    let output = release
        .wait_with_output()
        .expect("wait for release re-entry");
    assert!(
        output.status.success(),
        "release re-entry failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!publisher_worktree.exists());
    assert!(neighbor.exists());
    assert_eq!(git_output(&repo, &["tag", "--list"]), tags_before);
}

#[test]
fn release_bump_updates_cargo_toml() {
    let repo = TestRepo::new();
    fs::write(
        repo.path().join("Cargo.toml"),
        "[package]\nname = \"test\"\nversion = \"0.9.0\"\n",
    )
    .unwrap();

    release_bump(repo.path(), "0.9.1", None, &NullProgress).expect("bump should succeed");

    let content = fs::read_to_string(repo.path().join("Cargo.toml")).unwrap();
    assert!(content.contains("version = \"0.9.1\""));
    assert!(!content.contains("version = \"0.9.0\""));
}

#[test]
fn release_status_reports_latest_tag_and_release() {
    let gh_script = write_gh_status_script(
        r#"[{"databaseId":7,"headBranch":"main","displayTitle":"Retry v0.9.1","status":"completed","conclusion":"failure","url":"https://example.com/run/7"},{"databaseId":42,"headBranch":"v0.9.1","displayTitle":"Release v0.9.1","status":"completed","conclusion":"success","url":"https://example.com/run/42"}]"#,
        r#"{"isDraft":false}"#,
    );
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);

    let status = release_status(repo.path(), None).expect("status should succeed");
    assert_eq!(status.target, "default");
    assert_eq!(status.latest_tag.as_deref(), Some("v0.9.1"));
    assert_eq!(status.workflow_status.as_deref(), Some("completed"));
    assert_eq!(status.workflow_conclusion.as_deref(), Some("success"));
    assert_eq!(status.notes_status, Some(ReleaseNotesStatus::Missing));
    assert!(status.release_exists);
}

#[test]
fn release_status_reports_degraded_notes_as_gate_safe() {
    let gh_script = write_gh_status_script(
        r#"[{"databaseId":42,"headBranch":"v0.9.1","status":"completed","conclusion":"success"}]"#,
        r#"{"isDraft":false}"#,
    );
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join("release/v0.9.1")).unwrap();
    fs::write(
        repo.path().join("release/v0.9.1/NOTES.md"),
        "# v0.9.1\n\n<!-- loopflow:release-notes=degraded;reason=quota;gate=safe -->\n\nConcise fallback notes.\n",
    )
    .unwrap();
    git(&repo, &["add", "release/v0.9.1/NOTES.md"]);
    git(&repo, &["commit", "-m", "Archive degraded release notes"]);
    git(&repo, &["tag", "v0.9.1"]);

    let status = release_status(repo.path(), None).expect("status should read tagged notes");

    assert_eq!(
        status.notes_status,
        Some(ReleaseNotesStatus::Degraded(ReleaseNotesDegradation::Quota))
    );
    assert!(status.release_exists);
}

#[test]
fn release_status_reports_unmarked_notes_as_legacy() {
    let gh_script = write_gh_status_script("[]", r#"{"isDraft":false}"#);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join("release/v0.9.1")).unwrap();
    fs::write(
        repo.path().join("release/v0.9.1/NOTES.md"),
        "# v0.9.1\n\nNotes from before status markers.\n",
    )
    .unwrap();
    git(&repo, &["add", "release/v0.9.1/NOTES.md"]);
    git(&repo, &["commit", "-m", "Archive legacy release notes"]);
    git(&repo, &["tag", "v0.9.1"]);

    let status = release_status(repo.path(), None).expect("status should read legacy notes");

    assert_eq!(status.notes_status, Some(ReleaseNotesStatus::Legacy));
    assert!(status.release_exists);
}

#[test]
fn release_status_does_not_trust_malformed_safe_markers() {
    let gh_script = write_gh_status_script("[]", r#"{"isDraft":false}"#);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let markers = [
        "narrative;gate=unsafe -->",
        "degraded;reason=quota -->",
        "degraded;reason=unknown;gate=safe -->",
    ];

    for marker in markers {
        let repo = TestRepo::new();
        fs::create_dir_all(repo.path().join("release/v0.9.1")).unwrap();
        fs::write(
            repo.path().join("release/v0.9.1/NOTES.md"),
            format!("# v0.9.1\n\n<!-- loopflow:release-notes={marker}\n\nNotes.\n"),
        )
        .unwrap();
        git(&repo, &["add", "release/v0.9.1/NOTES.md"]);
        git(&repo, &["commit", "-m", "Archive malformed release notes"]);
        git(&repo, &["tag", "v0.9.1"]);

        let status = release_status(repo.path(), None).expect("status should fail closed");

        assert_eq!(status.notes_status, Some(ReleaseNotesStatus::Legacy));
    }
}

#[test]
fn release_status_does_not_count_a_draft_as_complete() {
    let gh_script = write_gh_status_script(
        r#"[{"databaseId":42,"headBranch":"v0.9.1","status":"completed","conclusion":"success"}]"#,
        r#"{"isDraft":true}"#,
    );
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    git(&repo, &["tag", "v0.9.1"]);

    let status = release_status(repo.path(), None).expect("status should succeed");

    assert!(!status.release_exists);
}

#[test]
fn release_status_scopes_to_named_target() {
    let gh_script = write_gh_status_script(
        r#"[{"databaseId":7,"headBranch":"cli/v1.2.3","displayTitle":"Release cli/v1.2.3","status":"completed","conclusion":"success","url":"https://example.com/run/7"}]"#,
        r#"{"isDraft":false}"#,
    );
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);

    let repo = TestRepo::new();
    fs::create_dir_all(repo.path().join(".lf")).expect("create config dir");
    fs::write(
        repo.path().join(".lf/config.yaml"),
        r#"
release:
  targets:
    cli:
      tag_prefix: "cli/"
"#,
    )
    .expect("write config");
    git(&repo, &["tag", "cli/v1.2.3"]);

    let status = release_status(repo.path(), Some("cli")).expect("status should succeed");
    assert_eq!(status.target, "cli");
    assert_eq!(status.latest_tag.as_deref(), Some("cli/v1.2.3"));
    assert!(status.release_exists);
}

#[test]
fn release_tag_is_idempotent_when_remote_tag_matches_head() {
    let repo = TestRepo::new();
    let head = git_output(&repo, &["rev-parse", "HEAD"]);

    let tag = release_tag(repo.path(), "0.9.1", None).expect("first tag should succeed");
    assert_eq!(tag, "v0.9.1");

    let second = release_tag(repo.path(), "0.9.1", None).expect("second tag should be no-op");
    assert_eq!(second, "v0.9.1");

    let remote_tag = git_output_bare(&repo, &["rev-parse", "refs/tags/v0.9.1"]);
    assert_eq!(remote_tag, head);
}

#[test]
fn release_run_resumes_an_existing_explicit_tag() {
    let gh_script = write_gh_status_script("[]", r#"{"isDraft":false}"#);
    let _env = EnvGuard::new(&[("gh", gh_script.as_str())]);
    let repo = TestRepo::new();
    let intended_notes = "# v0.9.1\n\n<!-- loopflow:release-notes=narrative;gate=safe -->\n\nConcise intended artifact.\n";
    fs::create_dir_all(repo.path().join("release/v0.9.1")).unwrap();
    fs::write(repo.path().join("release/v0.9.1/NOTES.md"), intended_notes).unwrap();
    git(&repo, &["add", "release/v0.9.1/NOTES.md"]);
    git(&repo, &["commit", "-m", "Prepare exact release artifact"]);
    release_tag(repo.path(), "0.9.1", None).expect("tag should succeed");

    let result = release_run(repo.path(), "0.9.1", None, &NullProgress)
        .expect("interrupted release should resume from its tag");

    let ReleaseRunOutcome::Resumed(receipt) = result else {
        panic!("expected resumed release");
    };
    assert_eq!(receipt.version, "0.9.1");
    assert_eq!(receipt.tag, "v0.9.1");
    assert!(receipt.release_exists);
    let status = release_status(repo.path(), None).expect("status should preserve narrative notes");
    assert_eq!(status.notes_status, Some(ReleaseNotesStatus::Narrative));
    assert_eq!(
        git_output_bare(&repo, &["show", "v0.9.1:release/v0.9.1/NOTES.md",],),
        intended_notes.trim()
    );
    assert_eq!(
        git_output_bare(
            &repo,
            &["for-each-ref", "--format=%(refname)", "refs/tags/v0.9.1"],
        )
        .lines()
        .count(),
        1
    );
}

#[test]
fn release_tag_fails_if_remote_tag_points_to_different_commit() {
    let repo = TestRepo::new();
    release_tag(repo.path(), "0.9.1", None).expect("initial tag should succeed");

    repo.create_file("CHANGELOG.md", "new release prep");
    repo.stage_all();
    repo.commit("change after tag");

    let err = release_tag(repo.path(), "0.9.1", None).expect_err("mismatched tag should fail");
    let message = err.to_string();
    assert!(message.contains("already exists on origin"));
    assert!(message.contains("expected"));
}