gen-circleci-orb 0.0.16

Generate a CircleCI orb to provide the facilities offered by a CLI program
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
use anyhow::Result;

pub struct PatchOpts {
    pub binary: String,
    /// One or more CircleCI namespaces to publish the orb under.
    /// Each namespace gets its own `ensure-orb-registered-<ns>` job and
    /// `orb-tools/publish: name: publish-orb-<ns>` workflow step.
    pub namespaces: Vec<String>,
    pub docker_namespace: String,
    pub orb_dir: String,
    pub build_workflow: String,
    pub release_workflow: String,
    pub requires_job: Option<String>,
    pub release_after_job: Option<String>,
    pub orb_tools_version: String,
    pub docker_orb_version: String,
    pub docker_context: String,
    pub orb_context: String,
    /// Namespaces that should be registered as private orbs.
    /// A namespace listed here gets `--private` in its `circleci orb create` command.
    /// Namespaces not listed are registered as public.
    /// Visibility is set at orb creation time and cannot be changed afterwards.
    pub private_namespaces: Vec<String>,
    pub mcp: bool,
}

pub struct PatchReport {
    pub insertions: Vec<String>,
    pub skipped: Vec<String>,
}

/// Patch a build/validation CircleCI config string.
/// Returns the modified content and a report of what was changed or skipped.
pub fn patch_build(content: &str, opts: &PatchOpts) -> (String, PatchReport) {
    let mut report = PatchReport {
        insertions: vec![],
        skipped: vec![],
    };
    let mut lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();

    // 1. Add orb-tools to orbs section
    let orb_entry = format!("  orb-tools: circleci/orb-tools@{}", opts.orb_tools_version);
    if content.contains("orb-tools:") {
        report.skipped.push("orb-tools orb".to_string());
    } else if let Some(pos) = find_section_end(&lines, "orbs:") {
        lines.insert(pos, orb_entry);
        report.insertions.push("orb-tools orb".to_string());
    }

    // 2. Add jobs section if missing, then add build-binary + regenerate-orb jobs
    let jobs_present = content.contains("build-binary:") && content.contains("regenerate-orb:");
    if jobs_present {
        report
            .skipped
            .push("build-binary and regenerate-orb jobs".to_string());
    } else {
        let build_block = build_binary_job(opts);
        let regen_block = regenerate_orb_job(opts);
        if let Some(pos) = find_section_end(&lines, "jobs:") {
            for (i, l) in build_block.iter().enumerate() {
                lines.insert(pos + i, l.clone());
            }
            let after_build = pos + build_block.len();
            for (i, l) in regen_block.iter().enumerate() {
                lines.insert(after_build + i, l.clone());
            }
        } else {
            // No jobs section — insert before workflows:
            if let Some(wf_pos) = find_top_level(&lines, "workflows:") {
                lines.insert(wf_pos, String::new());
                lines.insert(wf_pos, String::new());
                // Insert regen block first (it goes last in jobs), then build block before it
                let regen_len = regen_block.len();
                for (i, _) in regen_block.iter().rev().enumerate() {
                    lines.insert(wf_pos, regen_block[regen_len - 1 - i].clone());
                }
                let build_len = build_block.len();
                for (i, _) in build_block.iter().rev().enumerate() {
                    lines.insert(wf_pos, build_block[build_len - 1 - i].clone());
                }
                lines.insert(wf_pos, "jobs:".to_string());
            }
        }
        report
            .insertions
            .push("build-binary and regenerate-orb jobs".to_string());
    }

    // 3. Add workflow steps (regenerate-orb, orb-tools/pack, orb-tools/validate)
    if content.contains("orb-tools/pack:") {
        report.skipped.push("workflow steps".to_string());
    } else {
        let step_block = pack_validate_steps(opts);
        if let Some(pos) = find_workflow_jobs_end(&lines, &opts.build_workflow) {
            for (i, l) in step_block.iter().enumerate() {
                lines.insert(pos + i, l.clone());
            }
        }
        report.insertions.push("workflow steps".to_string());
    }

    let mut output = lines.join("\n");
    if content.ends_with('\n') {
        output.push('\n');
    }
    (output, report)
}

/// Patch a release CircleCI config string.
/// Returns the modified content and a report of what was changed or skipped.
pub fn patch_release(content: &str, opts: &PatchOpts) -> (String, PatchReport) {
    let mut report = PatchReport {
        insertions: vec![],
        skipped: vec![],
    };
    let mut lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();

    // 1. Add docker + orb-tools orbs
    // Check specifically for circleci orb entries, not random "docker:" keys in job defs
    let docker_entry = format!("  docker: circleci/docker@{}", opts.docker_orb_version);
    let orb_entry = format!("  orb-tools: circleci/orb-tools@{}", opts.orb_tools_version);
    let has_docker_orb = content.contains("  docker: circleci/");
    let has_orb_tools = content.contains("  orb-tools: circleci/");

    if has_docker_orb && has_orb_tools {
        report.skipped.push("docker and orb-tools orbs".to_string());
    } else {
        if let Some(pos) = find_section_end(&lines, "orbs:") {
            let mut insert_pos = pos;
            if !has_orb_tools {
                lines.insert(insert_pos, orb_entry);
                insert_pos += 1;
            }
            if !has_docker_orb {
                lines.insert(insert_pos, docker_entry);
            }
            report
                .insertions
                .push("docker and orb-tools orbs".to_string());
        }
    }

    // 2. Add build-binary-release, ensure-orb-registered-<ns> (per namespace), and build-container jobs
    let has_binary_release = content.contains("build-binary-release:");
    let missing_ensure_ns: Vec<&String> = opts
        .namespaces
        .iter()
        .filter(|ns| !content.contains(&format!("  ensure-orb-registered-{ns}:")))
        .collect();
    let has_container = content.contains("build-container:");
    if has_binary_release && missing_ensure_ns.is_empty() && has_container {
        report.skipped.push(
            "release jobs (build-binary-release, ensure-orb-registered, build-container)"
                .to_string(),
        );
    } else {
        if let Some(pos) = find_section_end(&lines, "jobs:") {
            let mut insert_pos = pos;
            if !has_binary_release {
                let binary_block = build_binary_release_job(opts);
                let binary_len = binary_block.len();
                for (i, l) in binary_block.into_iter().enumerate() {
                    lines.insert(insert_pos + i, l);
                }
                insert_pos += binary_len;
            }
            for ns in &missing_ensure_ns {
                let ensure_block = ensure_orb_registered_job_for(
                    ns,
                    &opts.binary,
                    opts.private_namespaces.contains(ns),
                );
                let ensure_len = ensure_block.len();
                for (i, l) in ensure_block.into_iter().enumerate() {
                    lines.insert(insert_pos + i, l);
                }
                insert_pos += ensure_len;
            }
            if !has_container {
                let container_block = build_container_job(opts);
                for (i, l) in container_block.into_iter().enumerate() {
                    lines.insert(insert_pos + i, l);
                }
            }
        } else if let Some(wf_pos) = find_top_level(&lines, "workflows:") {
            // No top-level jobs section — create one before workflows:
            lines.insert(wf_pos, String::new());
            lines.insert(wf_pos, String::new());
            let container_block = build_container_job(opts);
            let container_len = container_block.len();
            for i in 0..container_len {
                lines.insert(wf_pos, container_block[container_len - 1 - i].clone());
            }
            // Insert ensure jobs in reverse order to preserve namespace ordering
            for ns in opts.namespaces.iter().rev() {
                if missing_ensure_ns.contains(&ns) {
                    let ensure_block = ensure_orb_registered_job_for(
                        ns,
                        &opts.binary,
                        opts.private_namespaces.contains(ns),
                    );
                    let ensure_len = ensure_block.len();
                    for i in 0..ensure_len {
                        lines.insert(wf_pos, ensure_block[ensure_len - 1 - i].clone());
                    }
                }
            }
            let binary_block = build_binary_release_job(opts);
            let binary_len = binary_block.len();
            for i in 0..binary_len {
                lines.insert(wf_pos, binary_block[binary_len - 1 - i].clone());
            }
            lines.insert(wf_pos, "jobs:".to_string());
        }
        report.insertions.push(
            "release jobs (build-binary-release, ensure-orb-registered, build-container)"
                .to_string(),
        );
    }

    // 3. Add release workflow steps
    let all_ns_steps_present = opts.namespaces.iter().all(|ns| {
        content.contains(&format!("      - ensure-orb-registered-{ns}:"))
            && content.contains(&format!("name: publish-orb-{ns}"))
    });
    if content.contains("pack-orb-release")
        && content.contains("      - build-binary-release:")
        && content.contains("      - build-container:")
        && all_ns_steps_present
    {
        report.skipped.push("release workflow steps".to_string());
    } else {
        let step_block = release_workflow_steps(opts);
        if let Some(pos) = find_workflow_jobs_end(&lines, &opts.release_workflow) {
            for (i, l) in step_block.iter().enumerate() {
                lines.insert(pos + i, l.clone());
            }
        }
        report.insertions.push("release workflow steps".to_string());
    }

    // 4. Re-wire toolkit/release_crate to require all publish-orb-<ns> jobs
    //    so crates.io is published after ALL orb namespaces (Docker → orb → crates.io ordering).
    let publish_jobs: Vec<String> = opts
        .namespaces
        .iter()
        .map(|ns| format!("publish-orb-{ns}"))
        .collect();
    if rewire_release_crate_requires(&mut lines, &opts.release_workflow, &publish_jobs) {
        report
            .insertions
            .push("release_crate rewire to require orb publish".to_string());
    } else {
        report
            .skipped
            .push("release_crate rewire (already wired or no requires line)".to_string());
    }

    let mut output = lines.join("\n");
    if content.ends_with('\n') {
        output.push('\n');
    }
    (output, report)
}

/// Apply patches to CI config files on disk (or dry-run).
pub fn apply_patches(
    ci_dir: &std::path::Path,
    opts: &PatchOpts,
    dry_run: bool,
) -> Result<Vec<String>> {
    let mut summary = vec![];

    for (filename, patch_fn) in &[
        (
            "config.yml",
            patch_build as fn(&str, &PatchOpts) -> (String, PatchReport),
        ),
        (
            "release.yml",
            patch_release as fn(&str, &PatchOpts) -> (String, PatchReport),
        ),
    ] {
        let path = ci_dir.join(filename);
        if !path.exists() {
            summary.push(format!("{filename}: not found, skipped"));
            continue;
        }
        let content = std::fs::read_to_string(&path)?;
        let (patched, report) = patch_fn(&content, opts);

        for ins in &report.insertions {
            summary.push(format!("{filename}: inserted {ins}"));
        }
        for sk in &report.skipped {
            summary.push(format!("{filename}: skipped {sk} (already present)"));
        }

        if !dry_run && patched != content {
            std::fs::write(&path, &patched)?;
        }
    }

    Ok(summary)
}

// ── helpers ──────────────────────────────────────────────────────────────────

fn find_top_level(lines: &[String], header: &str) -> Option<usize> {
    lines.iter().position(|l| l.trim_end() == header)
}

/// Find the line index where new entries should be inserted inside a top-level section.
/// Returns the index of the first top-level line *after* the section header.
fn find_section_end(lines: &[String], header: &str) -> Option<usize> {
    let start = find_top_level(lines, header)?;
    for (i, l) in lines.iter().enumerate().skip(start + 1) {
        if !l.is_empty() && !l.starts_with(' ') && !l.starts_with('\t') && !l.starts_with('#') {
            return Some(i);
        }
    }
    Some(lines.len())
}

/// Find the insertion point at the end of a named workflow's `jobs:` list.
fn find_workflow_jobs_end(lines: &[String], workflow: &str) -> Option<usize> {
    let wf_line = format!("  {workflow}:");
    let wf_idx = lines
        .iter()
        .position(|l| l.trim_end() == wf_line.trim_end())?;

    // Find `    jobs:` within this workflow
    let mut jobs_idx = None;
    for (i, line) in lines.iter().enumerate().skip(wf_idx + 1) {
        let l = line.trim_end();
        if !line.starts_with("  ") {
            break;
        }
        if l == "    jobs:" || l == "  jobs:" {
            jobs_idx = Some(i);
            break;
        }
    }
    let jobs_start = jobs_idx?;

    // Scan forward to find where the jobs list ends
    for (i, l) in lines.iter().enumerate().skip(jobs_start + 1) {
        if l.trim_end().is_empty() {
            continue;
        }
        // Jobs entries are indented 6+ spaces; anything less ends the block
        let indent = l.len() - l.trim_start().len();
        if indent <= 2 {
            return Some(i);
        }
    }
    Some(lines.len())
}

fn build_binary_job(opts: &PatchOpts) -> Vec<String> {
    let binary = &opts.binary;
    vec![
        "  build-binary:".to_string(),
        "    docker:".to_string(),
        "      - image: rust:latest".to_string(),
        "    steps:".to_string(),
        "      - checkout".to_string(),
        "      - run:".to_string(),
        "          name: Build binary".to_string(),
        "          command: cargo build --release".to_string(),
        "      - persist_to_workspace:".to_string(),
        "          root: target/release".to_string(),
        format!("          paths: [{binary}]"),
    ]
}

fn regenerate_orb_job(opts: &PatchOpts) -> Vec<String> {
    let binary = &opts.binary;
    let orb_dir = &opts.orb_dir;
    // gen-circleci-orb is pre-installed in its own Docker image (jerusdp/gen-circleci-orb).
    // The target binary is attached from the build-binary workspace — no runtime installs needed.
    let mut lines = vec![
        "  regenerate-orb:".to_string(),
        "    docker:".to_string(),
        "      - image: jerusdp/gen-circleci-orb:latest".to_string(),
        "    steps:".to_string(),
        "      - checkout".to_string(),
        "      - attach_workspace:".to_string(),
        "          at: /tmp/bin".to_string(),
        "      - run:".to_string(),
        "          name: Regenerate orb source".to_string(),
        "          command: |".to_string(),
        "            export PATH=\"/tmp/bin:$PATH\"".to_string(),
        "            gen-circleci-orb generate \\".to_string(),
        format!("              --binary {binary} \\"),
    ];
    // Each namespace gets its own --orb-namespace flag (repeatable CLI arg).
    for ns in &opts.namespaces {
        lines.push(format!("              --orb-namespace {ns} \\"));
    }
    lines.push(format!("              --orb-dir {orb_dir}"));
    lines
}

fn pack_validate_steps(opts: &PatchOpts) -> Vec<String> {
    let orb_dir = &opts.orb_dir;
    let mut steps = vec![];

    // build-binary workflow step — compiles the binary and persists to workspace
    steps.push("      - build-binary:".to_string());
    if let Some(req) = &opts.requires_job {
        steps.push(format!("          requires: [{req}]"));
    }

    // regenerate-orb workflow step — attaches workspace, installs gen-circleci-orb, runs generate
    steps.push("      - regenerate-orb:".to_string());
    steps.push("          requires: [build-binary]".to_string());

    // orb-tools/pack (source_dir + workspace persistence; validates on pack)
    steps.push("      - orb-tools/pack:".to_string());
    steps.push("          name: pack-orb".to_string());
    steps.push(format!("          source_dir: {orb_dir}/src"));
    steps.push("          requires: [regenerate-orb]".to_string());

    // orb-tools/review (best-practice review of packed orb)
    steps.push("      - orb-tools/review:".to_string());
    steps.push("          name: review-orb".to_string());
    steps.push(format!("          source_dir: {orb_dir}/src"));
    steps.push("          requires: [pack-orb]".to_string());

    steps
}

fn build_binary_release_job(opts: &PatchOpts) -> Vec<String> {
    let binary = &opts.binary;
    vec![
        "  build-binary-release:".to_string(),
        "    docker:".to_string(),
        "      - image: rust:latest".to_string(),
        "    steps:".to_string(),
        "      - checkout".to_string(),
        "      - run:".to_string(),
        "          name: Build release binary".to_string(),
        format!("          command: cargo build --release -p {binary}"),
        "      - persist_to_workspace:".to_string(),
        "          root: target/release".to_string(),
        format!("          paths: [{binary}]"),
    ]
}

/// Build the job definition lines for one `ensure-orb-registered-<ns>` job.
/// Uses orb-tools/default executor (same circleci/circleci-cli image as orb-tools/publish,
/// so the CircleCI CLI is pre-installed). The orb-publishing context injects CIRCLE_TOKEN.
/// circleci setup must be called first — without it the CLI has no session config and
/// every orb command fails with "please set a token with 'circleci setup'".
fn ensure_orb_registered_job_for(ns: &str, binary: &str, private: bool) -> Vec<String> {
    // --private must be passed at creation time; visibility cannot be changed afterwards.
    let create_flags = if private {
        "--private --no-prompt"
    } else {
        "--no-prompt"
    };
    vec![
        format!("  ensure-orb-registered-{ns}:"),
        "    executor: orb-tools/default".to_string(),
        "    steps:".to_string(),
        "      - run:".to_string(),
        "          name: Ensure orb is registered".to_string(),
        "          command: |".to_string(),
        "            circleci setup --token \"${CIRCLE_TOKEN}\" --host https://circleci.com --no-prompt".to_string(),
        format!("            circleci orb info {ns}/{binary} > /dev/null 2>&1 || \\"),
        format!("              circleci orb create {ns}/{binary} {create_flags}"),
    ]
}

fn build_container_job(opts: &PatchOpts) -> Vec<String> {
    let binary = &opts.binary;
    let docker_ns = &opts.docker_namespace;
    let orb_dir = &opts.orb_dir;
    // Version is read from versions.env written by toolkit/calculate_versions.
    // The release pipeline is approval-triggered (not tag-triggered), so CIRCLE_TAG is empty.
    // The binary is attached from the build-binary-release workspace and copied into the
    // Docker build context so the image contains the freshly-compiled binary.
    let version_var = format!("CRATE_VERSION_{}", binary.to_uppercase().replace('-', "_"));
    vec![
        "  build-container:".to_string(),
        "    docker:".to_string(),
        "      - image: cimg/base:stable".to_string(),
        "    steps:".to_string(),
        "      - checkout".to_string(),
        "      - setup_remote_docker".to_string(),
        "      - attach_workspace:".to_string(),
        "          at: /tmp/release-versions".to_string(),
        "      - attach_workspace:".to_string(),
        "          at: /tmp/bin".to_string(),
        "      - run:".to_string(),
        "          name: Build and push Docker image".to_string(),
        "          command: |".to_string(),
        "            source /tmp/release-versions/versions.env".to_string(),
        format!("            VERSION=${{{version_var}}}"),
        format!("            cp /tmp/bin/{binary} {orb_dir}/{binary}"),
        format!("            docker build -t {docker_ns}/{binary}:${{VERSION}} -t {docker_ns}/{binary}:latest {orb_dir}"),
        "            echo \"${DOCKERHUB_PASSWORD}\" | docker login -u \"${DOCKERHUB_USERNAME}\" --password-stdin".to_string(),
        format!("            docker push {docker_ns}/{binary}:${{VERSION}}"),
        format!("            docker push {docker_ns}/{binary}:latest"),
    ]
}

fn release_workflow_steps(opts: &PatchOpts) -> Vec<String> {
    let binary = &opts.binary;
    let docker_ctx = &opts.docker_context;
    let orb_ctx = &opts.orb_context;
    let orb_dir = &opts.orb_dir;
    // release_after_job is the approval gate; build-binary-release, pack-orb-release, and
    // all ensure-orb-registered-<ns> jobs require it so they run in parallel immediately
    // after the gate clears.
    let requires = opts
        .release_after_job
        .as_deref()
        .map(|r| format!("[{r}]"))
        .unwrap_or_default();
    // Variable name: CRATE_VERSION_ + binary uppercased with hyphens replaced by underscores.
    // This matches the format written by toolkit/calculate_versions into versions.env.
    let version_var = format!("CRATE_VERSION_{}", binary.to_uppercase().replace('-', "_"));
    let mut steps = vec![];

    // build-binary-release: compile the release binary, persist to workspace
    steps.push("      - build-binary-release:".to_string());
    if !requires.is_empty() {
        steps.push(format!("          requires: {requires}"));
    }

    // Pack orb source (parallel with build-binary-release; both require the approval gate)
    steps.push("      - orb-tools/pack:".to_string());
    steps.push("          name: pack-orb-release".to_string());
    steps.push(format!("          source_dir: {orb_dir}/src"));
    if !requires.is_empty() {
        steps.push(format!("          requires: {requires}"));
    }

    // build-container: requires binary from workspace → sequential after build-binary-release
    steps.push("      - build-container:".to_string());
    steps.push("          requires: [build-binary-release]".to_string());
    steps.push(format!("          context: [{docker_ctx}]"));

    // Per-namespace: ensure-orb-registered-<ns> + orb-tools/publish: name: publish-orb-<ns>
    // Each namespace gets its own registration check and its own publish job.
    // Ensure jobs run in parallel with build-container (both require the approval gate).
    // Each publish job fans in from build-container, pack-orb-release, and its own ensure job.
    for ns in &opts.namespaces {
        // ensure-orb-registered-<ns>: dedicated job (not a pre-step — see job definition comment)
        steps.push(format!("      - ensure-orb-registered-{ns}:"));
        if !requires.is_empty() {
            steps.push(format!("          requires: {requires}"));
        }
        steps.push(format!("          context: [{orb_ctx}]"));

        // orb-tools/publish: inject CIRCLE_TAG via pre-steps (pipeline is approval-triggered,
        // not tag-triggered, so CIRCLE_TAG is empty; inject it from versions.env).
        steps.push("      - orb-tools/publish:".to_string());
        steps.push(format!("          name: publish-orb-{ns}"));
        steps.push("          pre-steps:".to_string());
        steps.push("            - attach_workspace:".to_string());
        steps.push("                at: /tmp/release-versions".to_string());
        steps.push("            - run:".to_string());
        steps.push("                name: Export orb version as CIRCLE_TAG".to_string());
        steps.push("                command: |".to_string());
        steps.push("                  source /tmp/release-versions/versions.env".to_string());
        // orb-tools/publish requires CIRCLE_TAG to match ^v[0-9]+\.[0-9]+\.[0-9]+$
        steps.push(format!(
            "                  echo \"export CIRCLE_TAG=v${{{version_var}}}\" >> \"$BASH_ENV\""
        ));
        steps.push(format!("          orb_name: {ns}/{binary}"));
        steps.push("          pub_type: production".to_string());
        steps.push("          vcs_type: github".to_string());
        steps.push(format!(
            "          requires: [build-container, pack-orb-release, ensure-orb-registered-{ns}]"
        ));
        steps.push(format!("          context: [{orb_ctx}]"));
    }

    steps
}

/// Find `toolkit/release_crate:` in the named release workflow and update its
/// `requires:` line to list all `publish_jobs`. Returns true if a change was made.
/// Idempotent: returns false if all publish jobs are already present, or if no requires line.
fn rewire_release_crate_requires(
    lines: &mut [String],
    workflow: &str,
    publish_jobs: &[String],
) -> bool {
    // Locate the named workflow
    let wf_line = format!("  {workflow}:");
    let Some(wf_idx) = lines
        .iter()
        .position(|l| l.trim_end() == wf_line.trim_end())
    else {
        return false;
    };

    // Find the `- toolkit/release_crate:` entry (6-space indent) inside the workflow
    let mut rc_idx = None;
    for (i, l) in lines.iter().enumerate().skip(wf_idx + 1) {
        if !l.starts_with("  ") && !l.is_empty() {
            break; // left the workflow block
        }
        if l.starts_with("      - toolkit/release_crate:") {
            rc_idx = Some(i);
            break;
        }
    }
    let Some(rc_idx) = rc_idx else {
        return false;
    };

    // Scan the job properties until the next sibling entry or end of workflow
    let scan_start = rc_idx + 1;
    for (offset, l) in lines[scan_start..].iter().enumerate() {
        if l.starts_with("      - ") {
            break; // next workflow job — left this block
        }
        if !l.is_empty() && !l.starts_with("  ") {
            break; // left the workflow section entirely
        }
        if l.contains("requires:") {
            // Already correct if every publish job appears in the requires line
            if publish_jobs.iter().all(|j| l.contains(j.as_str())) {
                return false;
            }
            let joined = publish_jobs.join(", ");
            lines[scan_start + offset] = format!("          requires: [{joined}]");
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_opts() -> PatchOpts {
        PatchOpts {
            binary: "mytool".to_string(),
            namespaces: vec!["my-org".to_string()],
            docker_namespace: "my-docker-org".to_string(),
            orb_dir: "orb".to_string(),
            build_workflow: "validation".to_string(),
            release_workflow: "release".to_string(),
            requires_job: Some("common-tests".to_string()),
            // The approval gate job that binary build and orb pack run after.
            // Docker/orb publish run before crates.io to establish the correct release order.
            release_after_job: Some("approve-release".to_string()),
            orb_tools_version: "12.3.3".to_string(),
            docker_orb_version: "3.0.1".to_string(),
            docker_context: "docker".to_string(),
            orb_context: "orb-publishing".to_string(),
            private_namespaces: vec![],
            mcp: false,
        }
    }

    fn make_opts_two_ns() -> PatchOpts {
        PatchOpts {
            namespaces: vec!["my-org".to_string(), "other-org".to_string()],
            ..make_opts()
        }
    }

    const BUILD_FIXTURE: &str = "\
version: 2.1

orbs:
  toolkit: jerus-org/circleci-toolkit@6.0.0

jobs:
  some-job:
    docker:
      - image: cimg/base:stable
    steps:
      - run: echo hello

workflows:
  validation:
    jobs:
      - some-job
";

    // Typical toolkit 6.0 config: no top-level jobs section, only orbs + workflows.
    const BUILD_FIXTURE_NO_JOBS: &str = "\
version: 2.1

parameters:
  min_rust_version:
    type: string
    default: \"1.87\"

orbs:
  toolkit: jerus-org/circleci-toolkit@6.0.0

workflows:
  validation:
    jobs:
      - toolkit/required_builds:
          min_rust_version: << pipeline.parameters.min_rust_version >>

      - toolkit/common_tests:
          min_rust_version: << pipeline.parameters.min_rust_version >>

      - toolkit/idiomatic_rust:
          filters:
            branches:
              ignore: main
";

    const RELEASE_FIXTURE: &str = "\
version: 2.1

orbs:
  toolkit: jerus-org/circleci-toolkit@6.0.0

jobs:
  release-mytool:
    docker:
      - image: cimg/rust:stable
    steps:
      - checkout

workflows:
  release:
    jobs:
      - release-mytool
";

    // Toolkit-style release.yml: no top-level jobs section, only orbs + workflows.
    // This is the common case for projects using only toolkit jobs.
    const RELEASE_FIXTURE_NO_JOBS: &str = "\
version: 2.1

orbs:
  toolkit: jerus-org/circleci-toolkit@6.0.0

workflows:
  release:
    jobs:
      - toolkit/release_crate:
          name: release-mytool
          context: [release]
      - toolkit/release_prlog:
          requires: [release-mytool]
          context: [release]
";

    // Toolkit-style release.yml with toolkit/release_crate requiring an approval gate.
    // This is the pattern init must re-wire to require publish-orb-<namespace> instead.
    const RELEASE_FIXTURE_WITH_RELEASE_CRATE: &str = "\
version: 2.1

orbs:
  toolkit: jerus-org/circleci-toolkit@6.0.0

workflows:
  release:
    jobs:
      - approve-release:
          type: approval
      - toolkit/release_crate:
          name: release-mytool
          requires: [approve-release]
          context: [release]
      - toolkit/release_prlog:
          requires: [release-mytool]
          context: [release]
";

    // ── patch_build (no pre-existing jobs section) ───────────────────────────

    #[test]
    fn patch_build_wires_workflow_steps_when_no_jobs_section() {
        let (output, report) = patch_build(BUILD_FIXTURE_NO_JOBS, &make_opts());
        assert!(
            output.contains("regenerate-orb:"),
            "missing job def:\n{output}"
        );
        assert!(
            output.contains("orb-tools/pack:"),
            "pack step not wired into workflow:\n{output}"
        );
        assert!(
            output.contains("orb-tools/review:"),
            "review step not wired into workflow:\n{output}"
        );
        // Both the job and the workflow steps should be in the report
        assert!(
            report
                .insertions
                .iter()
                .any(|s| s.contains("regenerate-orb")),
            "report missing regenerate-orb"
        );
        assert!(
            report.insertions.iter().any(|s| s.contains("workflow")),
            "report missing workflow steps"
        );
    }

    // ── patch_build ───────────────────────────────────────────────────────────

    #[test]
    fn patch_build_adds_orb_tools_to_orbs_section() {
        let (output, report) = patch_build(BUILD_FIXTURE, &make_opts());
        assert!(
            output.contains("orb-tools: circleci/orb-tools@12.3.3"),
            "missing orb-tools entry:\n{output}"
        );
        assert!(
            report.insertions.iter().any(|s| s.contains("orb-tools")),
            "report missing orb-tools insertion"
        );
    }

    #[test]
    fn patch_build_adds_build_binary_job() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        assert!(
            output.contains("  build-binary:"),
            "missing build-binary job:\n{output}"
        );
    }

    /// Collect lines belonging to a top-level job block (2-space indented header).
    /// Returns the content lines (not the header itself) as a single string.
    fn job_block(output: &str, job_name: &str) -> String {
        let header = format!("  {job_name}:");
        let mut in_block = false;
        let mut result = String::new();
        for line in output.lines() {
            if line.trim_end() == header.trim_end() {
                in_block = true;
                continue;
            }
            if in_block {
                // A non-empty line starting with ≤2 spaces that isn't the header means a new
                // top-level section or job; the block is done.
                if !line.is_empty() && !line.starts_with("   ") && !line.starts_with('\t') {
                    break;
                }
                result.push_str(line);
                result.push('\n');
            }
        }
        result
    }

    #[test]
    fn build_binary_uses_public_rust_image() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary");
        assert!(
            block.contains("rust:latest"),
            "build-binary must use the public rust:latest image, not a private CI image:\n{block}"
        );
    }

    #[test]
    fn build_binary_runs_cargo_build_release() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary");
        assert!(
            block.contains("cargo build --release"),
            "build-binary must run cargo build --release:\n{block}"
        );
    }

    #[test]
    fn build_binary_persists_to_workspace() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary");
        assert!(
            block.contains("persist_to_workspace"),
            "build-binary must persist binary to workspace:\n{block}"
        );
    }

    #[test]
    fn patch_build_adds_regenerate_orb_job() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        assert!(output.contains("regenerate-orb:"), "missing job:\n{output}");
        // gen-circleci-orb is pre-installed in its own image; no install step needed
        assert!(
            !output.contains("install-from-binstall-release.sh"),
            "regenerate-orb must not bootstrap cargo-binstall — use the gen-circleci-orb image:\n{output}"
        );
        assert!(
            !output.contains("cargo-binstall --no-confirm gen-circleci-orb"),
            "regenerate-orb must not install gen-circleci-orb at runtime:\n{output}"
        );
        assert!(
            output.contains("gen-circleci-orb generate"),
            "missing generate step:\n{output}"
        );
    }

    #[test]
    fn regenerate_orb_uses_gen_circleci_orb_image_and_attaches_workspace() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let block = job_block(&output, "regenerate-orb");
        assert!(
            block.contains("jerusdp/gen-circleci-orb:latest"),
            "regenerate-orb must use the gen-circleci-orb Docker image (gen-circleci-orb is pre-installed):\n{block}"
        );
        assert!(
            block.contains("attach_workspace"),
            "regenerate-orb must attach workspace to get the target binary:\n{block}"
        );
        assert!(
            !block.contains("cargo-binstall"),
            "regenerate-orb must not install anything — gen-circleci-orb is in the image:\n{block}"
        );
    }

    #[test]
    fn workflow_build_binary_precedes_regenerate_orb() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let bb_pos = output
            .find("      - build-binary:")
            .expect("no build-binary workflow step");
        let regen_pos = output
            .find("      - regenerate-orb:")
            .expect("no regenerate-orb workflow step");
        assert!(
            bb_pos < regen_pos,
            "build-binary must appear before regenerate-orb in the workflow"
        );
    }

    #[test]
    fn build_binary_workflow_step_requires_configured_job() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        // The build-binary workflow step must require the user-configured prerequisite
        let after_bb = output
            .split("      - build-binary:")
            .nth(1)
            .expect("no build-binary workflow step");
        let step_block = after_bb.split("      - ").next().unwrap_or(after_bb);
        assert!(
            step_block.contains("requires: [common-tests]"),
            "build-binary workflow step must require the configured job:\n{step_block}"
        );
    }

    #[test]
    fn regenerate_orb_workflow_step_requires_build_binary() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let after_regen = output
            .split("      - regenerate-orb:")
            .nth(1)
            .expect("no regenerate-orb workflow step");
        let step_block = after_regen.split("      - ").next().unwrap_or(after_regen);
        assert!(
            step_block.contains("requires: [build-binary]"),
            "regenerate-orb workflow step must require build-binary:\n{step_block}"
        );
    }

    #[test]
    fn patch_build_adds_workflow_steps() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        assert!(
            output.contains("orb-tools/pack:"),
            "missing pack step:\n{output}"
        );
        assert!(
            output.contains("orb-tools/review:"),
            "missing review step:\n{output}"
        );
        // Parameters must use snake_case (orb-tools@12 API)
        assert!(
            output.contains("source_dir: orb/src"),
            "pack/review must use source_dir (not source-dir):\n{output}"
        );
        assert!(
            !output.contains("destination-orb-path"),
            "must not use deprecated destination-orb-path:\n{output}"
        );
    }

    #[test]
    fn patch_build_is_idempotent() {
        let (first, _) = patch_build(BUILD_FIXTURE, &make_opts());
        let (second, second_report) = patch_build(&first, &make_opts());
        assert_eq!(
            first, second,
            "second patch changed content — not idempotent"
        );
        assert!(
            second_report
                .skipped
                .iter()
                .any(|s| s.contains("orb-tools")),
            "expected orb-tools skipped on second run"
        );
        assert!(
            second_report
                .skipped
                .iter()
                .any(|s| s.contains("build-binary")),
            "expected build-binary and regenerate-orb skipped on second run"
        );
    }

    #[test]
    fn patch_build_job_in_jobs_section_not_workflows() {
        let (output, _) = patch_build(BUILD_FIXTURE, &make_opts());
        // The regenerate-orb: job definition must appear in the jobs section
        let jobs_pos = output.find("\njobs:").expect("no jobs: section");
        let workflows_pos = output.find("\nworkflows:").expect("no workflows: section");
        let job_def_pos = output.find("  regenerate-orb:").expect("no job def");
        assert!(
            job_def_pos > jobs_pos && job_def_pos < workflows_pos,
            "job definition not in jobs section"
        );
    }

    // ── patch_release ─────────────────────────────────────────────────────────

    #[test]
    fn patch_release_adds_docker_and_orb_tools_orbs() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        assert!(
            output.contains("docker: circleci/docker@3.0.1"),
            "missing docker orb:\n{output}"
        );
        assert!(
            output.contains("orb-tools: circleci/orb-tools@12.3.3"),
            "missing orb-tools orb:\n{output}"
        );
    }

    #[test]
    fn patch_release_adds_build_container_job() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        assert!(
            output.contains("build-container:"),
            "missing job:\n{output}"
        );
        assert!(
            output.contains("docker build"),
            "missing docker build step:\n{output}"
        );
        assert!(
            output.contains("docker push"),
            "missing docker push step:\n{output}"
        );
        // Version comes from versions.env written by calculate_versions, not from git tags.
        // The release pipeline is approval-triggered (not tag-triggered), so CIRCLE_TAG is empty.
        assert!(
            !output.contains("${CIRCLE_TAG}"),
            "must not use CIRCLE_TAG (empty in approval-triggered pipelines):\n{output}"
        );
        assert!(
            output.contains("versions.env"),
            "must source versions.env to get the release version:\n{output}"
        );
        assert!(
            output.contains("attach_workspace"),
            "must attach workspace to get versions.env and the binary:\n{output}"
        );
        assert!(
            output.contains("docker login -u \"${DOCKERHUB_USERNAME}\""),
            "must log in to Docker Hub with DOCKERHUB_USERNAME before pushing:\n{output}"
        );
        assert!(
            output.contains("--password-stdin"),
            "must use --password-stdin (not -p flag) for Docker login:\n{output}"
        );
        assert!(
            output.contains(":latest"),
            "must also push a :latest tag:\n{output}"
        );
    }

    #[test]
    fn patch_release_uses_docker_namespace_not_orb_namespace() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // Docker build/push must use docker_namespace, not the orb namespace
        assert!(
            output.contains("docker build -t my-docker-org/mytool"),
            "docker build must use docker_namespace:\n{output}"
        );
        assert!(
            output.contains("docker push my-docker-org/mytool"),
            "docker push must use docker_namespace:\n{output}"
        );
        assert!(
            !output.contains("docker build -t my-org/"),
            "docker build must NOT use orb namespace:\n{output}"
        );
    }

    #[test]
    fn patch_release_adds_workflow_steps() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // Pack step must appear in release workflow to provide workspace for publish
        assert!(
            output.contains("orb-tools/pack:"),
            "missing pack step in release workflow:\n{output}"
        );
        assert!(
            output.contains("orb-tools/publish:"),
            "missing publish step:\n{output}"
        );
        assert!(
            output.contains("publish-orb-my-org"),
            "missing publish job name:\n{output}"
        );
        assert!(
            output.contains("pub_type: production"),
            "publish must set pub_type production:\n{output}"
        );
        assert!(
            output.contains("vcs_type: github"),
            "publish must set vcs_type (required by orb-tools/publish):\n{output}"
        );
    }

    #[test]
    fn patch_release_is_idempotent() {
        let (first, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let (second, second_report) = patch_release(&first, &make_opts());
        assert_eq!(
            first, second,
            "second release patch changed content — not idempotent"
        );
        assert!(
            !second_report.skipped.is_empty(),
            "expected skipped entries on second run"
        );
    }

    #[test]
    fn patch_release_includes_namespace_and_binary_in_publish() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // orb-tools@12 uses snake_case orb_name (not hyphenated orb-name)
        assert!(
            output.contains("orb_name: my-org/mytool"),
            "missing orb_name (underscore):\n{output}"
        );
        assert!(
            !output.contains("orb-path:"),
            "must not use deprecated orb-path:\n{output}"
        );
    }

    #[test]
    fn patch_release_adds_build_container_job_when_no_jobs_section() {
        // release.yml with only toolkit jobs (no top-level jobs: section) is the
        // common case. patch_release must create the jobs: section and insert
        // both build-binary-release and build-container, not silently skip them.
        let (output, _) = patch_release(RELEASE_FIXTURE_NO_JOBS, &make_opts());
        assert!(
            output.contains("build-binary-release:"),
            "build-binary-release job definition missing when no pre-existing jobs section:\n{output}"
        );
        assert!(
            output.contains("build-container:"),
            "build-container job definition missing when no pre-existing jobs section:\n{output}"
        );
        let jobs_pos = output.find("\njobs:").expect("jobs: section not created");
        let workflows_pos = output.find("\nworkflows:").expect("no workflows: section");
        let binary_release_pos = output
            .find("  build-binary-release:")
            .expect("no build-binary-release job definition");
        let container_pos = output
            .find("  build-container:")
            .expect("no build-container job definition");
        assert!(
            binary_release_pos > jobs_pos && binary_release_pos < workflows_pos,
            "build-binary-release definition must be in jobs: section, not workflows:\n{output}"
        );
        assert!(
            container_pos > jobs_pos && container_pos < workflows_pos,
            "build-container definition must be in jobs: section, not workflows:\n{output}"
        );
    }

    // ── new: build-binary-release job in release.yml ──────────────────────────

    #[test]
    fn patch_release_adds_build_binary_release_job() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        assert!(
            output.contains("  build-binary-release:"),
            "missing build-binary-release job definition:\n{output}"
        );
        let jobs_pos = output.find("\njobs:").expect("no jobs: section");
        let workflows_pos = output.find("\nworkflows:").expect("no workflows: section");
        let pos = output
            .find("  build-binary-release:")
            .expect("no build-binary-release job");
        assert!(
            pos > jobs_pos && pos < workflows_pos,
            "build-binary-release must be in the jobs section:\n{output}"
        );
    }

    #[test]
    fn build_binary_release_job_uses_rust_latest() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary-release");
        assert!(
            block.contains("rust:latest"),
            "build-binary-release must use the public rust:latest image:\n{block}"
        );
    }

    #[test]
    fn build_binary_release_job_has_package_flag() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary-release");
        assert!(
            block.contains("cargo build --release -p mytool"),
            "build-binary-release must compile with -p <binary> flag:\n{block}"
        );
    }

    #[test]
    fn build_binary_release_job_persists_binary_to_workspace() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-binary-release");
        assert!(
            block.contains("persist_to_workspace"),
            "build-binary-release must persist binary to workspace:\n{block}"
        );
        assert!(
            block.contains("paths: [mytool]"),
            "build-binary-release must persist the binary by name:\n{block}"
        );
    }

    // ── new: build-container uses versions.env + workspace binary ─────────────

    #[test]
    fn build_container_sources_versions_env() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-container");
        assert!(
            block.contains("source /tmp/release-versions/versions.env"),
            "build-container must source versions.env to get the release version:\n{block}"
        );
    }

    #[test]
    fn build_container_attaches_release_versions_workspace() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-container");
        assert!(
            block.contains("at: /tmp/release-versions"),
            "build-container must attach the release-versions workspace:\n{block}"
        );
    }

    #[test]
    fn build_container_attaches_bin_workspace() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-container");
        assert!(
            block.contains("at: /tmp/bin"),
            "build-container must attach the bin workspace to get the compiled binary:\n{block}"
        );
    }

    #[test]
    fn build_container_copies_workspace_binary() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-container");
        assert!(
            block.contains("cp /tmp/bin/mytool orb/mytool"),
            "build-container must copy binary from workspace into the Docker build context:\n{block}"
        );
    }

    #[test]
    fn build_container_uses_crate_version_var() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "build-container");
        // Variable name formula: CRATE_VERSION_ + binary.to_uppercase().replace('-', '_')
        // mytool → CRATE_VERSION_MYTOOL
        assert!(
            block.contains("CRATE_VERSION_MYTOOL"),
            "build-container must derive version from CRATE_VERSION_<BINARY> env var:\n{block}"
        );
    }

    // ── new: release workflow step ordering ──────────────────────────────────

    #[test]
    fn release_workflow_has_build_binary_release_step() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        assert!(
            output.contains("      - build-binary-release:"),
            "missing build-binary-release workflow step:\n{output}"
        );
    }

    #[test]
    fn release_workflow_binary_and_pack_both_require_approval_gate() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // build-binary-release step block
        let after_binary = output
            .split("      - build-binary-release:")
            .nth(1)
            .expect("no build-binary-release workflow step");
        let binary_step = after_binary
            .split("      - ")
            .next()
            .unwrap_or(after_binary);
        assert!(
            binary_step.contains("requires: [approve-release]"),
            "build-binary-release workflow step must require the approval gate:\n{binary_step}"
        );
        // pack-orb-release step block
        let after_pack = output
            .split("name: pack-orb-release")
            .nth(1)
            .expect("no pack-orb-release step");
        let pack_step = after_pack.split("      - ").next().unwrap_or(after_pack);
        assert!(
            pack_step.contains("requires: [approve-release]"),
            "pack-orb-release step must require the approval gate (runs in parallel with build-binary-release):\n{pack_step}"
        );
    }

    #[test]
    fn release_workflow_container_requires_build_binary_release() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let after_container = output
            .split("      - build-container:")
            .nth(1)
            .expect("no build-container workflow step");
        let step_block = after_container
            .split("      - ")
            .next()
            .unwrap_or(after_container);
        assert!(
            step_block.contains("requires: [build-binary-release]"),
            "build-container must require build-binary-release (not the approval gate directly):\n{step_block}"
        );
    }

    #[test]
    fn release_workflow_publish_has_pre_steps_circle_tag_injection() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // orb-tools/publish requires CIRCLE_TAG for pub_type: production.
        // Since the pipeline is approval-triggered (not tag-triggered), CIRCLE_TAG must be
        // injected via pre-steps from versions.env.
        assert!(
            output.contains("pre-steps:"),
            "orb-tools/publish must have pre-steps to inject CIRCLE_TAG:\n{output}"
        );
        assert!(
            output.contains("Export orb version as CIRCLE_TAG"),
            "pre-steps must contain a named step that exports CIRCLE_TAG:\n{output}"
        );
        assert!(
            output.contains("CIRCLE_TAG"),
            "pre-steps must set CIRCLE_TAG in BASH_ENV:\n{output}"
        );
        assert!(
            output.contains("BASH_ENV"),
            "pre-steps must export CIRCLE_TAG via BASH_ENV:\n{output}"
        );
    }

    #[test]
    fn release_workflow_publish_pre_steps_use_versions_env() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // The pre-steps must source versions.env from the workspace to get the version.
        // The workspace is attached first, then the env file sourced.
        assert!(
            output.contains("/tmp/release-versions"),
            "publish pre-steps must attach the release-versions workspace:\n{output}"
        );
        assert!(
            output.contains("source /tmp/release-versions/versions.env"),
            "publish pre-steps must source versions.env to read CRATE_VERSION_*:\n{output}"
        );
    }

    #[test]
    fn release_workflow_publish_pre_steps_inject_correct_variable() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // Variable name: CRATE_VERSION_ + binary.to_uppercase().replace('-', '_')
        // mytool → CRATE_VERSION_MYTOOL
        // orb-tools/publish pub_type:production requires CIRCLE_TAG matching ^v[0-9]+\.[0-9]+\.[0-9]+$
        // so the v prefix is mandatory.
        assert!(
            output.contains("CIRCLE_TAG=v${CRATE_VERSION_MYTOOL}"),
            "CIRCLE_TAG must have a v prefix — orb-tools/publish requires tag pattern ^v\\d+\\.\\d+\\.\\d+$:\n{output}"
        );
    }

    // ── ensure-orb-registered: separate job (not a pre-step) ────────────────
    // pre-steps run before the orb-tools job configures CLI auth, so the CLI has
    // no token. The fix is a dedicated inline job using `executor: orb-tools/default`
    // (same image as orb-tools/publish — CLI pre-installed) with the orb-publishing
    // context, which injects CIRCLECI_CLI_TOKEN directly (the CLI reads it automatically).

    #[test]
    fn patch_release_adds_ensure_orb_registered_job() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // Job name always includes namespace suffix for unambiguous multi-namespace support.
        assert!(
            output.contains("  ensure-orb-registered-my-org:"),
            "missing ensure-orb-registered-my-org job definition:\n{output}"
        );
        let jobs_pos = output.find("\njobs:").expect("no jobs: section");
        let workflows_pos = output.find("\nworkflows:").expect("no workflows: section");
        let pos = output
            .find("  ensure-orb-registered-my-org:")
            .expect("no ensure-orb-registered-my-org job");
        assert!(
            pos > jobs_pos && pos < workflows_pos,
            "ensure-orb-registered-my-org must be defined in the jobs section:\n{output}"
        );
    }

    #[test]
    fn ensure_orb_registered_job_uses_orb_tools_executor() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "ensure-orb-registered-my-org");
        // orb-tools/default uses the circleci/circleci-cli Docker image — CLI pre-installed.
        // No need to add a circleci/circleci-cli orb dependency.
        assert!(
            block.contains("executor: orb-tools/default"),
            "ensure-orb-registered-my-org must use orb-tools/default executor (has CLI pre-installed):\n{block}"
        );
    }

    #[test]
    fn ensure_orb_registered_job_runs_circleci_setup() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "ensure-orb-registered-my-org");
        // The CLI has no session config in a fresh executor. circleci setup must be called
        // with CIRCLE_TOKEN (the orb-publishing context variable) before any orb commands.
        assert!(
            block.contains("circleci setup") && block.contains("CIRCLE_TOKEN"),
            "ensure-orb-registered-my-org must run circleci setup --token ${{CIRCLE_TOKEN}}:\n{block}"
        );
    }

    #[test]
    fn ensure_orb_registered_job_uses_idempotent_check() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "ensure-orb-registered-my-org");
        assert!(
            block.contains("circleci orb info my-org/mytool"),
            "ensure job must check the specific orb before creating:\n{block}"
        );
        assert!(
            block.contains("circleci orb create my-org/mytool --no-prompt"),
            "ensure job must create the specific orb with --no-prompt:\n{block}"
        );
        assert!(
            !block.contains("|| true"),
            "must not use `|| true` — real failures (wrong token, wrong namespace) must surface:\n{block}"
        );
    }

    #[test]
    fn release_workflow_has_ensure_orb_registered_step() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        assert!(
            output.contains("      - ensure-orb-registered-my-org:"),
            "missing ensure-orb-registered-my-org workflow step:\n{output}"
        );
    }

    #[test]
    fn release_workflow_ensure_orb_step_requires_approval_gate() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let after_step = output
            .split("      - ensure-orb-registered-my-org:")
            .nth(1)
            .expect("no ensure-orb-registered-my-org workflow step");
        let step_block = after_step.split("      - ").next().unwrap_or(after_step);
        assert!(
            step_block.contains("requires: [approve-release]"),
            "ensure-orb-registered-my-org must require the approval gate:\n{step_block}"
        );
    }

    #[test]
    fn release_workflow_ensure_orb_step_uses_orb_publishing_context() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let after_step = output
            .split("      - ensure-orb-registered-my-org:")
            .nth(1)
            .expect("no ensure-orb-registered-my-org workflow step");
        let step_block = after_step.split("      - ").next().unwrap_or(after_step);
        assert!(
            step_block.contains("context: [orb-publishing]"),
            "ensure-orb-registered-my-org must run in the orb-publishing context:\n{step_block}"
        );
    }

    #[test]
    fn release_workflow_publish_requires_ensure_orb_registered() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let after_publish = output
            .split("      - orb-tools/publish:")
            .nth(1)
            .expect("no orb-tools/publish step");
        // Split on "\n      - " (newline-anchored) so 12-space pre-step items
        // (which contain "      - " as a substring) do not cause a false cut.
        let publish_block = after_publish
            .split("\n      - ")
            .next()
            .unwrap_or(after_publish);
        assert!(
            publish_block.contains("ensure-orb-registered"),
            "orb-tools/publish must require ensure-orb-registered:\n{publish_block}"
        );
    }

    #[test]
    fn release_workflow_publish_pre_steps_no_ensure_orb_step() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        // The ensure step is now a separate job, not a pre-step. The pre-steps block
        // of orb-tools/publish should only contain workspace attachment and CIRCLE_TAG export.
        let after_publish = output
            .split("      - orb-tools/publish:")
            .nth(1)
            .expect("no orb-tools/publish step");
        let pre_steps_block = after_publish
            .split("          orb_name:")
            .next()
            .unwrap_or(after_publish);
        assert!(
            !pre_steps_block.contains("circleci orb info"),
            "orb info must not be in orb-tools/publish pre-steps — it belongs in the separate ensure-orb-registered job:\n{pre_steps_block}"
        );
        assert!(
            !pre_steps_block.contains("circleci orb create"),
            "orb create must not be in orb-tools/publish pre-steps — it belongs in the separate ensure-orb-registered job:\n{pre_steps_block}"
        );
    }

    // ── release_crate rewiring ─────────────────────────────────────────────────
    // toolkit/release_crate must require publish-orb-<namespace> so crates.io is
    // published after the orb (same ordering established in gen-circleci-orb itself).

    #[test]
    fn patch_release_rewires_release_crate_requires_to_orb_publish() {
        let (output, _) = patch_release(RELEASE_FIXTURE_WITH_RELEASE_CRATE, &make_opts());
        let wf_section = output.split("workflows:").nth(1).unwrap_or("");
        let after_rc = wf_section
            .split("- toolkit/release_crate:")
            .nth(1)
            .expect("no toolkit/release_crate step");
        // Get the block for this job only (up to next same-level entry)
        let block = after_rc.split("\n      - ").next().unwrap_or(after_rc);
        assert!(
            block.contains("publish-orb-my-org"),
            "toolkit/release_crate requires must be updated to publish-orb-my-org:\n{block}"
        );
        assert!(
            !block.contains("approve-release"),
            "toolkit/release_crate must no longer require approve-release:\n{block}"
        );
    }

    #[test]
    fn patch_release_rewire_is_idempotent() {
        let (first, _) = patch_release(RELEASE_FIXTURE_WITH_RELEASE_CRATE, &make_opts());
        let (second, report) = patch_release(&first, &make_opts());
        assert_eq!(first, second, "second run must not change output");
        assert!(
            report
                .skipped
                .iter()
                .any(|s| s.contains("release_crate rewire")),
            "idempotent rewire must appear in skipped report:\n{:?}",
            report.skipped
        );
    }

    #[test]
    fn patch_release_rewire_reports_insertion() {
        let (_, report) = patch_release(RELEASE_FIXTURE_WITH_RELEASE_CRATE, &make_opts());
        assert!(
            report
                .insertions
                .iter()
                .any(|s| s.contains("release_crate rewire")),
            "rewire must appear in insertions report:\n{:?}",
            report.insertions
        );
    }

    // ── multi-namespace support ────────────────────────────────────────────────
    // When --orb-namespace / --public-orb-namespace / --private-orb-namespace is given
    // multiple times, each namespace gets its own ensure-orb-registered-<ns> job and
    // publish-orb-<ns> workflow step. toolkit/release_crate must require ALL publish jobs.

    #[test]
    fn patch_release_adds_per_namespace_ensure_and_publish_jobs() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts_two_ns());
        assert!(
            output.contains("  ensure-orb-registered-my-org:"),
            "missing ensure-orb-registered-my-org job:\n{output}"
        );
        assert!(
            output.contains("  ensure-orb-registered-other-org:"),
            "missing ensure-orb-registered-other-org job:\n{output}"
        );
        assert!(
            output.contains("name: publish-orb-my-org"),
            "missing publish-orb-my-org step:\n{output}"
        );
        assert!(
            output.contains("name: publish-orb-other-org"),
            "missing publish-orb-other-org step:\n{output}"
        );
    }

    #[test]
    fn each_publish_job_requires_its_own_ensure_job() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts_two_ns());
        // publish-orb-my-org must require ensure-orb-registered-my-org (not other-org).
        // Split on "\n      - " (6-space indent, workflow-level) to get just this job's block —
        // pre-steps use 12-space indent so they are not split on.
        let after_my_org = output
            .split("name: publish-orb-my-org")
            .nth(1)
            .expect("no publish-orb-my-org step");
        let my_org_block = after_my_org
            .split("\n      - ")
            .next()
            .unwrap_or(after_my_org);
        assert!(
            my_org_block.contains("ensure-orb-registered-my-org"),
            "publish-orb-my-org must require ensure-orb-registered-my-org:\n{my_org_block}"
        );
        assert!(
            !my_org_block.contains("ensure-orb-registered-other-org"),
            "publish-orb-my-org must NOT require other-org's ensure job:\n{my_org_block}"
        );

        // publish-orb-other-org must require ensure-orb-registered-other-org
        let after_other_org = output
            .split("name: publish-orb-other-org")
            .nth(1)
            .expect("no publish-orb-other-org step");
        let other_org_block = after_other_org
            .split("\n      - ")
            .next()
            .unwrap_or(after_other_org);
        assert!(
            other_org_block.contains("ensure-orb-registered-other-org"),
            "publish-orb-other-org must require ensure-orb-registered-other-org:\n{other_org_block}"
        );
    }

    #[test]
    fn rewire_requires_all_publish_jobs_for_multiple_namespaces() {
        let (output, _) = patch_release(RELEASE_FIXTURE_WITH_RELEASE_CRATE, &make_opts_two_ns());
        let wf_section = output.split("workflows:").nth(1).unwrap_or("");
        let after_rc = wf_section
            .split("- toolkit/release_crate:")
            .nth(1)
            .expect("no toolkit/release_crate step");
        let block = after_rc.split("\n      - ").next().unwrap_or(after_rc);
        assert!(
            block.contains("publish-orb-my-org"),
            "requires must include publish-orb-my-org:\n{block}"
        );
        assert!(
            block.contains("publish-orb-other-org"),
            "requires must include publish-orb-other-org:\n{block}"
        );
    }

    #[test]
    fn multi_namespace_patch_release_is_idempotent() {
        let (first, _) = patch_release(RELEASE_FIXTURE, &make_opts_two_ns());
        let (second, second_report) = patch_release(&first, &make_opts_two_ns());
        assert_eq!(
            first, second,
            "second multi-namespace patch must not change content"
        );
        assert!(
            !second_report.skipped.is_empty(),
            "expected skipped entries on second run"
        );
    }

    // ── orb visibility (public vs private, per namespace) ────────────────────
    // circleci orb create sets visibility at creation time — it cannot be changed
    // after the orb exists. --private must be passed when the orb is first registered.
    // Each namespace has independent visibility: a production namespace can be public
    // while a preprod/testing namespace is kept private.

    #[test]
    fn ensure_orb_create_omits_private_flag_for_public_orb() {
        let (output, _) = patch_release(RELEASE_FIXTURE, &make_opts());
        let block = job_block(&output, "ensure-orb-registered-my-org");
        assert!(
            block.contains("circleci orb create my-org/mytool --no-prompt"),
            "public orb create must not have --private flag:\n{block}"
        );
        assert!(
            !block.contains("--private"),
            "public orb must not pass --private to circleci orb create:\n{block}"
        );
    }

    #[test]
    fn ensure_orb_create_includes_private_flag_when_namespace_is_private() {
        let opts = PatchOpts {
            private_namespaces: vec!["my-org".to_string()],
            ..make_opts()
        };
        let (output, _) = patch_release(RELEASE_FIXTURE, &opts);
        let block = job_block(&output, "ensure-orb-registered-my-org");
        assert!(
            block.contains("circleci orb create my-org/mytool --private --no-prompt"),
            "private namespace orb create must include --private flag:\n{block}"
        );
    }

    #[test]
    fn mixed_visibility_public_namespace_has_no_private_flag() {
        // my-org is public; other-org is private
        let opts = PatchOpts {
            namespaces: vec!["my-org".to_string(), "other-org".to_string()],
            private_namespaces: vec!["other-org".to_string()],
            ..make_opts()
        };
        let (output, _) = patch_release(RELEASE_FIXTURE, &opts);
        let my_org_block = job_block(&output, "ensure-orb-registered-my-org");
        assert!(
            !my_org_block.contains("--private"),
            "my-org is public — must not have --private:\n{my_org_block}"
        );
        assert!(
            my_org_block.contains("circleci orb create my-org/mytool --no-prompt"),
            "my-org create must be public:\n{my_org_block}"
        );
    }

    #[test]
    fn mixed_visibility_private_namespace_has_private_flag() {
        // my-org is public; other-org is private
        let opts = PatchOpts {
            namespaces: vec!["my-org".to_string(), "other-org".to_string()],
            private_namespaces: vec!["other-org".to_string()],
            ..make_opts()
        };
        let (output, _) = patch_release(RELEASE_FIXTURE, &opts);
        let other_org_block = job_block(&output, "ensure-orb-registered-other-org");
        assert!(
            other_org_block.contains("circleci orb create other-org/mytool --private --no-prompt"),
            "other-org is private — create must have --private:\n{other_org_block}"
        );
    }
}