shipshape-core 0.11.0

Core library for shipshape: contract normalizer, repo-fact detection, audit scoring, release engine, and the versioned protocol DTOs.
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
//! The engine-owned version-bump arithmetic (`release-rust-workspace-multicrate`
//! facet 2).
//!
//! `shipshape release plan --bump major|minor|patch` supplies only a semantic level;
//! the engine **computes** the new version from the current manifest version — there
//! is no hand-typed literal version (`--version` was removed in 0.3.0,
//! `release-drop-version-flag`, and stays removed). This module is the pure,
//! side-effect-free core of that computation: parse a strict `X.Y.Z` version and
//! apply a [`BumpLevel`]. It fails **closed** on a non-semver manifest version rather
//! than guess, so a malformed version aborts `release plan` instead of publishing an
//! unintended number.
//!
//! The bump is strict `MAJOR.MINOR.PATCH` (three non-negative integers): a
//! pre-release or build-metadata version (`1.2.3-rc.1`, `1.2.3+build`) is refused —
//! bumping such a version is ambiguous, and a release cut publishes a plain release
//! version, so refusing is the safe, unsurprising behaviour.

use crate::protocol::plan::BumpLevel;

/// Why an engine-owned bump plan could not be built. This covers an invalid source
/// version and plan-time edit-set conflicts such as non-equivalent workspace pins;
/// both refuse before an approval artifact is sealed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BumpError {
    /// The source version associated with the failed bump plan.
    pub version: String,
    /// Why it was rejected (human-readable), e.g. "expected MAJOR.MINOR.PATCH".
    pub reason: String,
}

/// Compute the next version by applying `level` to a strict `X.Y.Z` `current`
/// version.
///
/// - `major` → `(X+1).0.0`
/// - `minor` → `X.(Y+1).0`
/// - `patch` → `X.Y.(Z+1)`
///
/// # Errors
/// [`BumpError`] when `current` is not a strict `MAJOR.MINOR.PATCH` of three
/// non-negative integers (a pre-release/build suffix, a missing/extra component, a
/// non-numeric or empty component, or a `u64`-overflowing component). Failing closed
/// here means a malformed manifest version aborts the plan rather than silently
/// producing a wrong release version.
pub fn bump_version(level: BumpLevel, current: &str) -> Result<String, BumpError> {
    let (major, minor, patch) = parse_semver_core(current)?;
    let (major, minor, patch) = match level {
        // A checked add keeps the (practically unreachable) `u64::MAX` overflow a loud
        // error rather than a wrapped, silently-wrong version.
        BumpLevel::Major => (checked_incr(major, current)?, 0, 0),
        BumpLevel::Minor => (major, checked_incr(minor, current)?, 0),
        BumpLevel::Patch => (major, minor, checked_incr(patch, current)?),
    };
    Ok(format!("{major}.{minor}.{patch}"))
}

/// Parse a strict `MAJOR.MINOR.PATCH` core into its three integers, rejecting
/// anything else.
fn parse_semver_core(v: &str) -> Result<(u64, u64, u64), BumpError> {
    let reject = |reason: &str| BumpError {
        version: v.to_string(),
        reason: reason.to_string(),
    };
    // A pre-release (`-`) or build-metadata (`+`) suffix is not a plain release
    // version — refuse rather than bump ambiguously.
    if v.contains('-') || v.contains('+') {
        return Err(reject(
            "a pre-release or build-metadata version cannot be bumped; expected a plain \
             MAJOR.MINOR.PATCH release version",
        ));
    }
    let mut parts = v.split('.');
    let mut next = |which: &str| -> Result<u64, BumpError> {
        let comp = parts
            .next()
            .ok_or_else(|| reject("expected MAJOR.MINOR.PATCH (a component is missing)"))?;
        parse_component(comp, which, v)
    };
    let major = next("major")?;
    let minor = next("minor")?;
    let patch = next("patch")?;
    // A fourth component (or trailing dot) is not `X.Y.Z`.
    if parts.next().is_some() {
        return Err(reject(
            "expected exactly MAJOR.MINOR.PATCH (too many components)",
        ));
    }
    Ok((major, minor, patch))
}

/// Parse one version component as a non-negative integer, rejecting empty,
/// non-digit, or leading-zero forms (`01`) so the version is canonical.
fn parse_component(comp: &str, which: &str, full: &str) -> Result<u64, BumpError> {
    let reject = |reason: String| BumpError {
        version: full.to_string(),
        reason,
    };
    if comp.is_empty() {
        return Err(reject(format!("the {which} component is empty")));
    }
    if !comp.bytes().all(|b| b.is_ascii_digit()) {
        return Err(reject(format!(
            "the {which} component `{comp}` is not a non-negative integer"
        )));
    }
    // Reject a non-canonical leading zero (`01`) — `0` itself is fine.
    if comp.len() > 1 && comp.starts_with('0') {
        return Err(reject(format!(
            "the {which} component `{comp}` has a leading zero"
        )));
    }
    comp.parse::<u64>().map_err(|_| {
        reject(format!(
            "the {which} component `{comp}` does not fit in a u64"
        ))
    })
}

/// Increment a component, turning the (unreachable in practice) overflow into a
/// loud [`BumpError`] rather than a wrapped value.
fn checked_incr(n: u64, full: &str) -> Result<u64, BumpError> {
    n.checked_add(1).ok_or_else(|| BumpError {
        version: full.to_string(),
        reason: "a version component would overflow on bump".to_string(),
    })
}

// ── Cut-time edit transforms (pure) ──────────────────────────────────────────
//
// The engine-owned bump phase applies a deterministic edit set inside the clean
// checkout (`release-rust-workspace-multicrate` facet 2). These are the *pure* text
// transforms behind those edits — no filesystem, no process — so each is exhaustively
// unit-tested and the effectful executor ([`crate::release::bump_exec`]) is thin glue.
// Every transform **fails closed**: it returns a [`BumpEditError`] rather than write an
// ambiguous or silently-wrong result onto the irreversible cut path.

/// Why a cut-time bump edit could not be applied to a file's text. Each variant is a
/// fail-closed refusal — the executor aborts the cut rather than commit a wrong edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BumpEditError {
    /// The `[workspace.package]` section, or its `version = "…"` line, was not found —
    /// the workspace root manifest is not the shape the bump expects.
    WorkspaceVersionNotFound,
    /// Neither the root `[workspace.package]` nor `[package]` table carried the
    /// expected `version = "…"` line, so the engine cannot identify a version source.
    RootManifestVersionNotFound,
    /// A pin rewrite found no line declaring `dependency` with the exact `from`
    /// requirement — the sealed pin does not match the tree, so the executor refuses
    /// rather than guess (fail closed on **zero** matches).
    PinNotFound {
        /// The dependency whose `=<from>` pin was expected.
        dependency: String,
        /// The exact requirement string that was expected (`=<from_version>`).
        from: String,
    },
    /// A pin rewrite found declarations of `dependency` whose requirements are not
    /// all the sealed `from` value, so equivalence cannot be established. Equivalent
    /// duplicates are supported and rewritten as one deterministic set.
    PinAmbiguous {
        /// The dependency whose explicit requirements conflict.
        dependency: String,
        /// The exact sealed requirement every explicit declaration must carry.
        from: String,
        /// Total number of explicit version declarations inspected.
        count: usize,
    },
    /// A Cargo manifest could not be parsed by the shared discovery/edit parser.
    ManifestUnparseable {
        /// Parser diagnostic suitable for an actionable plan/cut refusal.
        reason: String,
    },
    /// The CHANGELOG had no `## [Unreleased]` section to finalize, but the contract's
    /// changelog mode said the engine should finalize one — fail closed rather than
    /// tag a release whose notes were never promoted.
    ChangelogUnreleasedNotFound,
    /// Marker-aware finalization requires exactly one ordered marker pair.
    ChangelogMarkersMalformed,
    /// The requested release heading already exists while new notes remain to cut.
    ChangelogReleaseConflict {
        /// Version whose existing section conflicts with the pending notes.
        version: String,
    },
    /// Finalization found neither authored entries nor compiled fragment/trailer notes.
    ChangelogNotesEmpty,
}

impl std::fmt::Display for BumpEditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WorkspaceVersionNotFound => write!(
                f,
                "could not find a `[workspace.package]` `version = \"\"` line matching the \
                 sealed bump in the workspace root manifest"
            ),
            Self::RootManifestVersionNotFound => write!(
                f,
                "could not find a root `[package]` `version = \"\"` line matching the sealed \
                 bump after no `[workspace.package]` version source was found"
            ),
            Self::PinNotFound { dependency, from } => write!(
                f,
                "no `{dependency} = \"{from}\"` intra-workspace pin found to rewrite (the sealed \
                 plan's pin does not match the tree)"
            ),
            Self::PinAmbiguous {
                dependency,
                from,
                count,
            } => write!(
                f,
                "`{dependency}` has {count} explicit version declarations that are not all \
                 `{from}` — refusing to rewrite an ambiguous pin set"
            ),
            Self::ManifestUnparseable { reason } => {
                write!(
                    f,
                    "could not parse Cargo manifest while discovering exact pins: {reason}"
                )
            }
            Self::ChangelogUnreleasedNotFound => write!(
                f,
                "the contract asks the engine to finalize the CHANGELOG, but no `## [Unreleased]` \
                 section was found to promote"
            ),
            Self::ChangelogMarkersMalformed => write!(
                f,
                "the CHANGELOG must contain exactly one ordered shipshape-changelog Unreleased marker pair"
            ),
            Self::ChangelogReleaseConflict { version } => write!(
                f,
                "the CHANGELOG already contains a release heading for `{version}` while pending notes remain"
            ),
            Self::ChangelogNotesEmpty => write!(
                f,
                "the CHANGELOG has no authored, fragment, or trailer-derived notes to release"
            ),
        }
    }
}

impl std::error::Error for BumpEditError {}

/// The `[workspace.package]` `version = "…"` value, or `None` when the section or its
/// `version` line is absent.
#[must_use]
pub fn workspace_version(manifest: &str) -> Option<String> {
    section_version(manifest, "workspace.package")
}

/// The root `[package]` `version = "…"` value, or `None` when the table or its version
/// line is absent.
#[must_use]
pub fn package_version(manifest: &str) -> Option<String> {
    section_version(manifest, "package")
}

/// The release version source in a root Cargo manifest. A workspace package version is
/// authoritative when present; otherwise a plain single-crate `[package]` version is
/// used. This is deliberately a shape check, not a best-effort search across tables.
#[must_use]
pub fn root_manifest_version(manifest: &str) -> Option<String> {
    workspace_version(manifest).or_else(|| package_version(manifest))
}

fn section_version(manifest: &str, section: &str) -> Option<String> {
    let mut in_section = false;
    for line in manifest.lines() {
        let trimmed = strip_comment(line).trim();
        if let Some(header) = section_header(trimmed) {
            in_section = header == section;
        } else if in_section && line_starts_with_key(trimmed, "version") {
            if let Some(v) = scan_key_string(trimmed, "version") {
                return Some(v);
            }
        }
    }
    None
}

/// Rewrite the `[workspace.package]` `version = "<from>"` line to `to`, returning the
/// new manifest text.
///
/// Scoped to the `[workspace.package]` section (the single source of truth for the
/// release version) so a `version` key in any other table — `[package]`,
/// `[dependencies.foo]`, `[workspace.dependencies]` — is never touched. Preserves the
/// line's exact indentation and quote style; only the value between the quotes changes.
///
/// **Verified against `from`** (llm-review defense-in-depth): the line is rewritten only
/// when its current value is exactly `from` (the sealed pre-bump version). This makes the
/// edit fail closed on a tree that does not match the plan, and — since the whole-key scan
/// is line-oriented — it also sidesteps a `version = "…"` occurrence *inside a quoted
/// string value* (e.g. a `description` that mentions a version) unless that string
/// happens to equal `from`, in which case a following real `version` line still matches.
///
/// # Errors
/// [`BumpEditError::WorkspaceVersionNotFound`] when the section, or a `version = "<from>"`
/// line within it, is absent (fail closed rather than write a manifest with no bump).
pub fn set_workspace_version(
    manifest: &str,
    from: &str,
    to: &str,
) -> Result<String, BumpEditError> {
    set_section_version(manifest, "workspace.package", from, to)
        .ok_or(BumpEditError::WorkspaceVersionNotFound)
}

/// Rewrite the root `[package]` `version = "<from>"` line to `to`, preserving the
/// line's formatting and failing closed when the sealed source version is absent.
pub fn set_package_version(manifest: &str, from: &str, to: &str) -> Result<String, BumpEditError> {
    set_section_version(manifest, "package", from, to)
        .ok_or(BumpEditError::RootManifestVersionNotFound)
}

fn set_section_version(manifest: &str, section: &str, from: &str, to: &str) -> Option<String> {
    let mut out = String::with_capacity(manifest.len() + to.len());
    let mut in_section = false;
    let mut replaced = false;
    let ends_with_newline = manifest.ends_with('\n');
    let mut lines = manifest.lines().peekable();
    while let Some(line) = lines.next() {
        let trimmed = strip_comment(line).trim();
        if let Some(header) = section_header(trimmed) {
            in_section = header == section;
        } else if in_section && !replaced && line_starts_with_key(trimmed, "version") {
            if let Some(rewritten) = replace_exact_string_value(line, "version", from, to) {
                out.push_str(&rewritten);
                push_line_ending(&mut out, lines.peek().is_some(), ends_with_newline);
                replaced = true;
                continue;
            }
        }
        out.push_str(line);
        push_line_ending(&mut out, lines.peek().is_some(), ends_with_newline);
    }
    replaced.then_some(out)
}

/// One local Cargo dependency declaration discovered by the shared plan/cut parser.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PinDeclaration {
    /// Resolved package name (`package = "…"` when renamed, otherwise the table key).
    pub(crate) package: String,
    /// Literal version requirement, or `None` for a path/workspace-only declaration.
    pub(crate) requirement: Option<String>,
}

/// Parse local dependency declarations from normal, dev, build, and target-specific
/// Cargo dependency tables. `toml_edit` owns the TOML grammar, so dotted keys and
/// multiline inline tables have the same meaning during discovery and execution.
pub(crate) fn cargo_pin_declarations(manifest: &str) -> Result<Vec<PinDeclaration>, String> {
    pin_declarations(manifest, false)
}

/// Parse the root `[workspace.dependencies]` declarations. These declarations are
/// edit targets in their own right: a member's `{ workspace = true }` use contains no
/// version literal, while the exact internal pin lives here.
pub(crate) fn cargo_workspace_pin_declarations(
    manifest: &str,
) -> Result<Vec<PinDeclaration>, String> {
    pin_declarations(manifest, true)
}

fn pin_declarations(manifest: &str, workspace_only: bool) -> Result<Vec<PinDeclaration>, String> {
    use toml_edit::{DocumentMut, Item};

    fn declaration(key: &str, item: &Item, require_local: bool) -> Option<PinDeclaration> {
        let fields = item.as_table_like()?;
        let local = fields.get("path").and_then(Item::as_str).is_some()
            || fields.get("workspace").and_then(Item::as_bool) == Some(true);
        if require_local && !local {
            return None;
        }
        Some(PinDeclaration {
            package: fields
                .get("package")
                .and_then(Item::as_str)
                .unwrap_or(key)
                .to_string(),
            requirement: fields
                .get("version")
                .and_then(Item::as_str)
                .map(str::to_string),
        })
    }

    fn collect_member_tables(doc: &DocumentMut, out: &mut Vec<PinDeclaration>) {
        const KINDS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
        for kind in KINDS {
            if let Some(deps) = doc.get(kind).and_then(Item::as_table_like) {
                out.extend(
                    deps.iter()
                        .filter_map(|(name, dep)| declaration(name, dep, true)),
                );
            }
        }
        if let Some(targets) = doc.get("target").and_then(Item::as_table_like) {
            for (_, target) in targets.iter() {
                let Some(target) = target.as_table_like() else {
                    continue;
                };
                for kind in KINDS {
                    if let Some(deps) = target.get(kind).and_then(Item::as_table_like) {
                        out.extend(
                            deps.iter()
                                .filter_map(|(name, dep)| declaration(name, dep, true)),
                        );
                    }
                }
            }
        }
    }

    let doc = manifest
        .parse::<DocumentMut>()
        .map_err(|error| format!("Cargo manifest TOML could not be parsed: {error}"))?;
    let mut out = Vec::new();
    if workspace_only {
        if let Some(deps) = doc
            .get("workspace")
            .and_then(Item::as_table_like)
            .and_then(|workspace| workspace.get("dependencies"))
            .and_then(Item::as_table_like)
        {
            out.extend(
                deps.iter()
                    .filter_map(|(name, dep)| declaration(name, dep, false)),
            );
        }
    } else {
        collect_member_tables(&doc, &mut out);
    }
    Ok(out)
}

/// Rewrite a single intra-workspace `=`-pin (`dependency = "…, version = \"<from>\""`)
/// from `from` to `to`, returning the new manifest text.
///
/// Precise and fail-closed (`release-rust-workspace-multicrate` facet 3): it collects
/// declarations of `dependency` and rewrites every declaration iff all literal version
/// requirements are **exactly** `from` — refusing on zero
/// ([`BumpEditError::PinNotFound`]) or any non-equivalent requirement
/// ([`BumpEditError::PinAmbiguous`]). It
/// matches both the inline-table form (`dep = { path = "…", version = "=X" }`) and the
/// dependency sub-table form (`[dependencies.dep]` … `version = "=X"`), the two shapes
/// [`crate::facts`] records a requirement for.
///
/// # Errors
/// [`BumpEditError::PinNotFound`] / [`BumpEditError::PinAmbiguous`] as above.
pub fn rewrite_pin(
    manifest: &str,
    dependency: &str,
    from: &str,
    to: &str,
) -> Result<String, BumpEditError> {
    rewrite_pin_inner(manifest, dependency, from, to, false)
}

/// Rewrite an exact internal pin owned by the root `[workspace.dependencies]` table.
pub fn rewrite_workspace_pin(
    manifest: &str,
    dependency: &str,
    from: &str,
    to: &str,
) -> Result<String, BumpEditError> {
    rewrite_pin_inner(manifest, dependency, from, to, true)
}

fn rewrite_deps(
    deps: &mut dyn toml_edit::TableLike,
    dependency: &str,
    from: &str,
    to: &str,
    require_local: bool,
) -> usize {
    use toml_edit::{Item, Value};
    let mut rewritten = 0;
    for (key, item) in deps.iter_mut() {
        let Some(fields) = item.as_table_like_mut() else {
            continue;
        };
        let local = fields.get("path").and_then(Item::as_str).is_some()
            || fields.get("workspace").and_then(Item::as_bool) == Some(true);
        let package = fields
            .get("package")
            .and_then(Item::as_str)
            .unwrap_or(key.get());
        if package == dependency
            && (!require_local || local)
            && fields.get("version").and_then(Item::as_str) == Some(from)
        {
            let version = fields
                .get_mut("version")
                .and_then(Item::as_value_mut)
                .expect("a string version is a value");
            let decor = version.decor().clone();
            *version = Value::from(to);
            *version.decor_mut() = decor;
            rewritten += 1;
        }
    }
    rewritten
}

fn rewrite_member_tables(
    doc: &mut toml_edit::DocumentMut,
    dependency: &str,
    from: &str,
    to: &str,
) -> usize {
    use toml_edit::Item;
    const KINDS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
    let mut rewritten = 0;
    for kind in KINDS {
        if let Some(deps) = doc.get_mut(kind).and_then(Item::as_table_like_mut) {
            rewritten += rewrite_deps(deps, dependency, from, to, true);
        }
    }
    if let Some(targets) = doc.get_mut("target").and_then(Item::as_table_like_mut) {
        for (_, target) in targets.iter_mut() {
            let Some(target) = target.as_table_like_mut() else {
                continue;
            };
            for kind in KINDS {
                if let Some(deps) = target.get_mut(kind).and_then(Item::as_table_like_mut) {
                    rewritten += rewrite_deps(deps, dependency, from, to, true);
                }
            }
        }
    }
    rewritten
}

fn rewrite_pin_inner(
    manifest: &str,
    dependency: &str,
    from: &str,
    to: &str,
    workspace_only: bool,
) -> Result<String, BumpEditError> {
    use toml_edit::{DocumentMut, Item};

    let declarations: Vec<PinDeclaration> = (if workspace_only {
        cargo_workspace_pin_declarations(manifest)
    } else {
        cargo_pin_declarations(manifest)
    })
    .map_err(|reason| BumpEditError::ManifestUnparseable { reason })?
    .into_iter()
    .filter(|d| d.package == dependency)
    .collect();
    let explicit = declarations
        .iter()
        .filter(|d| d.requirement.is_some())
        .count();
    let matching = declarations
        .iter()
        .filter(|d| d.requirement.as_deref() == Some(from))
        .count();
    if matching == 0 {
        return Err(BumpEditError::PinNotFound {
            dependency: dependency.to_string(),
            from: from.to_string(),
        });
    }
    if matching != explicit {
        return Err(BumpEditError::PinAmbiguous {
            dependency: dependency.to_string(),
            from: from.to_string(),
            count: explicit,
        });
    }

    let mut doc =
        manifest
            .parse::<DocumentMut>()
            .map_err(|error| BumpEditError::ManifestUnparseable {
                reason: error.to_string(),
            })?;
    let rewritten = if workspace_only {
        doc.get_mut("workspace")
            .and_then(Item::as_table_like_mut)
            .and_then(|workspace| workspace.get_mut("dependencies"))
            .and_then(Item::as_table_like_mut)
            .map_or(0, |deps| rewrite_deps(deps, dependency, from, to, false))
    } else {
        rewrite_member_tables(&mut doc, dependency, from, to)
    };
    if rewritten != matching {
        return Err(BumpEditError::PinAmbiguous {
            dependency: dependency.to_string(),
            from: from.to_string(),
            count: explicit,
        });
    }
    Ok(doc.to_string())
}

/// Finalize a Keep-a-Changelog CHANGELOG: promote the `## [Unreleased]` section's
/// content under a new dated `## [<version>] - <date>` header, leaving a fresh empty
/// `## [Unreleased]` above it for the next cycle. Returns the new text.
///
/// Deliberately conservative: it inserts one dated header immediately after the
/// `## [Unreleased]` line and does not otherwise reflow the file, so it composes with a
/// human-curated body. `date` is `YYYY-MM-DD`.
///
/// # Errors
/// [`BumpEditError::ChangelogUnreleasedNotFound`] when there is no `## [Unreleased]`
/// header to promote (fail closed — the contract asked for a finalize there is nothing
/// to finalize).
pub fn finalize_changelog(text: &str, version: &str, date: &str) -> Result<String, BumpEditError> {
    let ends_with_newline = text.ends_with('\n');
    let mut out = String::with_capacity(text.len() + version.len() + date.len() + 16);
    let mut inserted = false;
    let mut lines = text.lines().peekable();
    while let Some(line) = lines.next() {
        out.push_str(line);
        push_line_ending(&mut out, lines.peek().is_some(), ends_with_newline);
        if !inserted && is_unreleased_header(line) {
            // A blank line, then the dated release header — Keep a Changelog style.
            out.push('\n');
            out.push_str("## [");
            out.push_str(version);
            out.push_str("] - ");
            out.push_str(date);
            // Guarantee a newline after the inserted header even at EOF, so the
            // promoted content is not glued onto it.
            out.push('\n');
            inserted = true;
        }
    }
    if inserted {
        Ok(out)
    } else {
        Err(BumpEditError::ChangelogUnreleasedNotFound)
    }
}

/// Finalize a marker-owned changelog region without allowing the released section or
/// marker comments to enter the release notes. `compiled_notes` contains any fragment
/// and trailer-derived material gathered by the effectful executor.
pub fn finalize_marker_changelog(
    text: &str,
    version: &str,
    date: &str,
    compiled_notes: &str,
) -> Result<String, BumpEditError> {
    const START: &str = "<!-- oss-changelog:unreleased-start -->";
    const END: &str = "<!-- oss-changelog:unreleased-end -->";
    const SKELETON: &str = "<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n\n### Added\n\n### Changed\n\n### Fixed\n<!-- oss-changelog:unreleased-end -->";

    let starts: Vec<_> = text.match_indices(START).map(|(i, _)| i).collect();
    let ends: Vec<_> = text.match_indices(END).map(|(i, _)| i).collect();
    if starts.is_empty() && ends.is_empty() {
        let marked = wrap_unreleased_markers(text)?;
        return finalize_marker_changelog(&marked, version, date, compiled_notes);
    }
    if starts.len() != 1 || ends.len() != 1 || starts[0] >= ends[0] {
        return Err(BumpEditError::ChangelogMarkersMalformed);
    }
    let start = starts[0];
    let end = ends[0];
    let region = &text[start + START.len()..end];
    if !region.lines().any(is_unreleased_header) {
        return Err(BumpEditError::ChangelogUnreleasedNotFound);
    }
    if region.lines().any(is_release_heading) {
        return Err(BumpEditError::ChangelogMarkersMalformed);
    }

    let notes = release_note_content(&[region, compiled_notes]);
    let heading_prefix = format!("## [{version}]");
    let existing = text
        .lines()
        .any(|line| line.trim().starts_with(&heading_prefix));
    if existing {
        if notes.is_empty() {
            return Ok(text.to_string());
        }
        return Err(BumpEditError::ChangelogReleaseConflict {
            version: version.to_string(),
        });
    }
    if notes.is_empty() {
        return Err(BumpEditError::ChangelogNotesEmpty);
    }

    let after_marker = end + END.len();
    let prefix = text[..start].trim_end_matches('\n');
    let suffix = text[after_marker..].trim_start_matches('\n');
    let mut out = String::with_capacity(text.len() + notes.len() + version.len() + 64);
    if !prefix.is_empty() {
        out.push_str(prefix);
        out.push_str("\n\n");
    }
    out.push_str(SKELETON);
    out.push_str("\n\n## [");
    out.push_str(version);
    out.push_str("] - ");
    out.push_str(date);
    out.push_str("\n\n");
    out.push_str(&notes);
    if !suffix.is_empty() {
        out.push_str("\n\n");
        out.push_str(suffix.trim_end_matches('\n'));
    }
    if text.ends_with('\n') {
        out.push('\n');
    }
    Ok(out)
}

/// Remove structural marker/header lines and empty category headings from one note
/// source. This is also the final defense that marker comments cannot leak into a
/// cargo-dist announcement body.
fn release_note_content(sources: &[&str]) -> String {
    use std::collections::BTreeMap;

    const START: &str = "<!-- oss-changelog:unreleased-start -->";
    const END: &str = "<!-- oss-changelog:unreleased-end -->";
    const ORDER: [&str; 6] = [
        "Added",
        "Changed",
        "Deprecated",
        "Removed",
        "Fixed",
        "Security",
    ];
    let mut preamble = Vec::new();
    let mut sections: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for source in sources {
        let mut current: Option<String> = None;
        for line in source.lines() {
            let trimmed = line.trim();
            if trimmed == START || trimmed == END || is_unreleased_header(line) {
                continue;
            }
            if let Some(heading) = trimmed.strip_prefix("### ") {
                current = Some(heading.to_string());
                sections.entry(heading.to_string()).or_default();
            } else if let Some(heading) = &current {
                sections
                    .entry(heading.clone())
                    .or_default()
                    .push(line.to_string());
            } else {
                preamble.push(line.to_string());
            }
        }
    }

    let mut kept = Vec::new();
    let preamble = preamble.join("\n").trim().to_string();
    if !preamble.is_empty() {
        kept.push(preamble);
    }
    let mut headings: Vec<_> = sections.keys().cloned().collect();
    headings.sort_by_key(|heading| {
        ORDER
            .iter()
            .position(|candidate| candidate == heading)
            .unwrap_or(ORDER.len())
    });
    for heading in headings {
        let body = sections.remove(&heading).expect("heading came from map");
        let body = collapse_blank_lines(&body.join("\n"));
        if !body.is_empty() {
            kept.push(format!("### {heading}\n\n{body}"));
        }
    }
    kept.join("\n\n")
}

fn collapse_blank_lines(text: &str) -> String {
    let mut out = Vec::new();
    let mut previous_blank = false;
    for line in text.trim().lines() {
        let blank = line.trim().is_empty();
        if blank && previous_blank {
            continue;
        }
        out.push(line);
        previous_blank = blank;
    }
    out.join("\n")
}

fn wrap_unreleased_markers(text: &str) -> Result<String, BumpEditError> {
    let mut offset = 0;
    let mut header_start = None;
    let mut section_end = text.len();
    for line in text.split_inclusive('\n') {
        if header_start.is_none() && is_unreleased_header(line.trim_end_matches('\n')) {
            header_start = Some(offset);
        } else if header_start.is_some()
            && (is_release_heading(line) || is_link_definition(line.trim()))
        {
            section_end = offset;
            break;
        }
        offset += line.len();
    }
    let header_start = header_start.ok_or(BumpEditError::ChangelogUnreleasedNotFound)?;
    let mut marked = String::with_capacity(text.len() + 100);
    marked.push_str(&text[..header_start]);
    marked.push_str("<!-- oss-changelog:unreleased-start -->\n");
    marked.push_str(&text[header_start..section_end]);
    if !marked.ends_with('\n') {
        marked.push('\n');
    }
    marked.push_str("<!-- oss-changelog:unreleased-end -->\n");
    marked.push_str(text[section_end..].trim_start_matches('\n'));
    Ok(marked)
}

/// Whether `line` is a `## [Unreleased]` header (Keep a Changelog), tolerant of
/// surrounding whitespace and `Unreleased` letter-case.
fn is_release_heading(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with("## ") && !trimmed.starts_with("### ") && !is_unreleased_header(line)
}

fn is_link_definition(line: &str) -> bool {
    line.starts_with('[') && line.contains("]: ")
}

fn is_unreleased_header(line: &str) -> bool {
    let t = line.trim();
    let Some(rest) = t.strip_prefix("##") else {
        return false;
    };
    let rest = rest.trim();
    rest.eq_ignore_ascii_case("[unreleased]")
}

/// The bracketed section name of a TOML header line (`[a.b.c]` → `Some("a.b.c")`), or
/// `None` when the line is not a bare section header.
fn section_header(trimmed: &str) -> Option<&str> {
    // Only a plain `[header]`; an array-of-tables `[[x]]` is not a bump target.
    let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
    if inner.starts_with('[') || inner.contains('[') {
        return None;
    }
    Some(inner.trim())
}

/// Whether a trimmed line starts with `key =`, excluding a matching string embedded in
/// another key's value. Section version reads and writes use this stricter rule; inline
/// dependency-table scans intentionally use the more flexible token search below.
fn line_starts_with_key(line: &str, key: &str) -> bool {
    line.strip_prefix(key)
        .is_some_and(|rest| rest.trim_start().starts_with('='))
}

/// Replace a whole-key `key = "<old>"` with `key = "<new>"` on `line`, but only when
/// the current value is exactly `old`; returns the rewritten line or `None`.
fn replace_exact_string_value(line: &str, key: &str, old: &str, new: &str) -> Option<String> {
    let current = scan_key_string(strip_comment(line).trim(), key)?;
    if current != old {
        return None;
    }
    replace_string_value(line, key, new)
}

/// Replace the value of a whole-key `key = "…"` on `line` with `new` (keeping quote
/// style and everything else on the line), or `None` when the line has no such key.
///
/// Operates on the raw `line` (so indentation and a trailing inline `# comment` are
/// preserved), locating the quoted value via the same whole-key scan used to read it.
fn replace_string_value(line: &str, key: &str, new: &str) -> Option<String> {
    let (val_start, quote) = locate_key_string(line, key)?;
    // `val_start` points at the opening quote; find the closing quote.
    let after_open = val_start + 1;
    let rel_close = line[after_open..].find(quote)?;
    let close = after_open + rel_close;
    let mut out = String::with_capacity(line.len() + new.len());
    out.push_str(&line[..after_open]);
    out.push_str(new);
    out.push_str(&line[close..]);
    Some(out)
}

/// The value of a whole-key `key = "…"` in `s` (matching the facts parser's whole-token
/// discipline), or `None`.
fn scan_key_string(s: &str, key: &str) -> Option<String> {
    let (open, quote) = locate_key_string(s, key)?;
    let after_open = open + 1;
    let rel_close = s[after_open..].find(quote)?;
    Some(s[after_open..after_open + rel_close].to_string())
}

/// Locate a whole-key `key = "…"` in `s`, returning the byte offset of the opening
/// quote and the quote char. "Whole key" = the char before `key` is not an identifier
/// char, and `key` is immediately followed (past spaces) by `=` then a quote.
fn locate_key_string(s: &str, key: &str) -> Option<(usize, char)> {
    let mut search = 0;
    while let Some(rel) = s[search..].find(key) {
        let pos = search + rel;
        let prev_is_ident = s[..pos]
            .chars()
            .next_back()
            .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '-');
        let after = &s[pos + key.len()..];
        let after_trimmed = after.trim_start();
        if !prev_is_ident {
            if let Some(rest) = after_trimmed.strip_prefix('=') {
                let rest_trimmed = rest.trim_start();
                if let Some(q) = rest_trimmed.chars().next() {
                    if q == '"' || q == '\'' {
                        // Offset of the quote in the original string.
                        let consumed = s.len() - rest_trimmed.len();
                        return Some((consumed, q));
                    }
                }
            }
        }
        search = pos + key.len();
    }
    None
}

/// Strip a trailing `# comment` from a TOML line, respecting quoted `#`s crudely: it
/// cuts at the first `#` not inside a quote. Sufficient for manifest lines the bump
/// touches (version/pin values never contain `#`).
fn strip_comment(line: &str) -> &str {
    let mut in_str: Option<char> = None;
    for (i, c) in line.char_indices() {
        match in_str {
            Some(q) => {
                if c == q {
                    in_str = None;
                }
            }
            None => match c {
                '"' | '\'' => in_str = Some(c),
                '#' => return &line[..i],
                _ => {}
            },
        }
    }
    line
}

/// Append the correct line ending: a `\n` between lines, and preserve whether the file
/// ended with a trailing newline (so a rewrite is byte-faithful).
fn push_line_ending(out: &mut String, more_lines: bool, ends_with_newline: bool) {
    if more_lines || ends_with_newline {
        out.push('\n');
    }
}

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

    #[test]
    fn patch_minor_major_from_a_normal_version() {
        assert_eq!(bump_version(BumpLevel::Patch, "0.4.0").unwrap(), "0.4.1");
        assert_eq!(bump_version(BumpLevel::Minor, "0.4.0").unwrap(), "0.5.0");
        assert_eq!(bump_version(BumpLevel::Major, "0.4.0").unwrap(), "1.0.0");
    }

    #[test]
    fn minor_and_major_reset_lower_components() {
        assert_eq!(bump_version(BumpLevel::Minor, "1.2.3").unwrap(), "1.3.0");
        assert_eq!(bump_version(BumpLevel::Major, "1.2.3").unwrap(), "2.0.0");
        assert_eq!(bump_version(BumpLevel::Patch, "1.2.3").unwrap(), "1.2.4");
    }

    #[test]
    fn zero_versions_bump_canonically() {
        assert_eq!(bump_version(BumpLevel::Patch, "0.0.0").unwrap(), "0.0.1");
        assert_eq!(bump_version(BumpLevel::Minor, "0.0.0").unwrap(), "0.1.0");
        assert_eq!(bump_version(BumpLevel::Major, "0.0.0").unwrap(), "1.0.0");
    }

    #[test]
    fn a_pre_release_or_build_version_is_refused() {
        assert!(bump_version(BumpLevel::Patch, "1.2.3-rc.1").is_err());
        assert!(bump_version(BumpLevel::Patch, "1.2.3+build.5").is_err());
    }

    #[test]
    fn a_non_xyz_version_is_refused() {
        for bad in ["1.2", "1.2.3.4", "1", "", "v1.2.3", "1.2.x", "1..2", "1.2."] {
            assert!(
                bump_version(BumpLevel::Patch, bad).is_err(),
                "expected `{bad}` to be refused"
            );
        }
    }

    #[test]
    fn a_leading_zero_component_is_refused() {
        assert!(bump_version(BumpLevel::Patch, "1.02.3").is_err());
        assert!(bump_version(BumpLevel::Patch, "01.2.3").is_err());
        // But a bare zero component is canonical and fine.
        assert!(bump_version(BumpLevel::Patch, "0.1.0").is_ok());
    }

    #[test]
    fn the_error_carries_the_offending_version() {
        let err = bump_version(BumpLevel::Patch, "not-semver").unwrap_err();
        assert_eq!(err.version, "not-semver");
        assert!(!err.reason.is_empty());
    }

    // ── set_workspace_version ────────────────────────────────────────────────

    #[test]
    fn sets_the_workspace_package_version_only() {
        let manifest = "[workspace]\nmembers = [\"a\"]\n\n[workspace.package]\nversion = \"0.4.0\"\nedition = \"2021\"\n";
        let out = set_workspace_version(manifest, "0.4.0", "0.5.0").unwrap();
        assert!(out.contains("version = \"0.5.0\""));
        assert!(!out.contains("0.4.0"));
        // Everything else preserved.
        assert!(out.contains("edition = \"2021\""));
        assert!(out.ends_with('\n'));
    }

    #[test]
    fn does_not_touch_a_version_in_another_section() {
        let manifest =
            "[package]\nversion = \"9.9.9\"\n\n[workspace.package]\nversion = \"0.4.0\"\n";
        let out = set_workspace_version(manifest, "0.4.0", "0.5.0").unwrap();
        assert!(out.contains("[package]\nversion = \"9.9.9\""));
        assert!(out.contains("[workspace.package]\nversion = \"0.5.0\""));
    }

    #[test]
    fn does_not_match_a_version_inside_a_description_string() {
        let manifest = "[workspace.package]\ndescription = 'requires version = \"0.4.0\"'\nversion = \"0.4.0\"\n";
        let out = set_workspace_version(manifest, "0.4.0", "0.5.0").unwrap();
        assert!(
            out.contains("requires version = \"0.4.0\""),
            "description untouched: {out}"
        );
        assert!(
            out.contains("version = \"0.5.0\""),
            "real version bumped: {out}"
        );
    }

    #[test]
    fn fails_closed_when_the_current_version_does_not_match_from() {
        let manifest = "[workspace.package]\nversion = \"1.2.3\"\n";
        assert_eq!(
            set_workspace_version(manifest, "0.4.0", "0.5.0"),
            Err(BumpEditError::WorkspaceVersionNotFound)
        );
    }

    #[test]
    fn package_version_is_available_for_a_plain_single_crate_manifest() {
        let manifest = "[package]\nname = \"acme\"\nversion = \"1.0.0\"\n";
        assert_eq!(package_version(manifest).as_deref(), Some("1.0.0"));
        assert_eq!(root_manifest_version(manifest).as_deref(), Some("1.0.0"));
        assert_eq!(
            set_package_version(manifest, "1.0.0", "2.0.0").unwrap(),
            "[package]\nname = \"acme\"\nversion = \"2.0.0\"\n"
        );
        let with_description =
            "[package]\ndescription = 'requires version = \"1.0.0\"'\nversion = \"1.0.0\"\n";
        let out = set_package_version(with_description, "1.0.0", "2.0.0").unwrap();
        assert!(out.contains("requires version = \"1.0.0\""));
        assert_eq!(package_version(&out).as_deref(), Some("2.0.0"));
    }

    #[test]
    fn root_manifest_version_prefers_workspace_inheritance() {
        let manifest =
            "[package]\nversion = \"9.9.9\"\n\n[workspace.package]\nversion = \"1.0.0\"\n";
        assert_eq!(root_manifest_version(manifest).as_deref(), Some("1.0.0"));
    }

    #[test]
    fn package_rewrite_fails_closed_when_neither_root_version_shape_matches() {
        let manifest = "[package]\nname = \"acme\"\n";
        assert_eq!(
            set_package_version(manifest, "1.0.0", "2.0.0"),
            Err(BumpEditError::RootManifestVersionNotFound)
        );
    }

    // ── rewrite_pin ──────────────────────────────────────────────────────────

    #[test]
    fn rewrites_an_inline_table_pin() {
        let manifest = "[dependencies]\nshipshape-core = { path = \"../shipshape-core\", version = \"=0.4.0\" }\nserde = \"1\"\n";
        let out = rewrite_pin(manifest, "shipshape-core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("version = \"=0.5.0\""));
        assert!(out.contains("path = \"../shipshape-core\""));
        assert!(out.contains("serde = \"1\""));
    }

    #[test]
    fn rewrites_a_subtable_pin() {
        let manifest =
            "[dependencies.shipshape-core]\npath = \"../shipshape-core\"\nversion = \"=0.4.0\"\n";
        let out = rewrite_pin(manifest, "shipshape-core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("version = \"=0.5.0\""));
    }

    #[test]
    fn rewrites_dotted_dependency_keys() {
        let manifest = "[dependencies]\ncore.path = \"../core\"\ncore.version = \"=0.4.0\"\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("core.version = \"=0.5.0\""), "{out}");
    }

    #[test]
    fn rewrites_multiline_inline_workspace_dependency() {
        let manifest = "[workspace.dependencies]\ncore = {\n  path = \"crates/core\",\n  version = \"=0.4.0\"\n}\n";
        let declarations = cargo_workspace_pin_declarations(manifest).unwrap();
        assert_eq!(declarations.len(), 1);
        let out = rewrite_workspace_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("version = \"=0.5.0\""), "{out}");
    }

    #[test]
    fn rewrites_dotted_workspace_dependency_keys() {
        let manifest =
            "[workspace.dependencies]\ncore.path = \"crates/core\"\ncore.version = \"=0.4.0\"\n";
        let out = rewrite_workspace_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("core.version = \"=0.5.0\""), "{out}");
    }

    #[test]
    fn root_exact_pin_without_path_is_still_an_edit_target() {
        let manifest = "[workspace.dependencies]\ncore = { version = \"=0.4.0\" }\n";
        let declarations = cargo_workspace_pin_declarations(manifest).unwrap();
        assert_eq!(declarations[0].requirement.as_deref(), Some("=0.4.0"));
        let out = rewrite_workspace_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("version = \"=0.5.0\""), "{out}");
    }

    #[test]
    fn rewrite_is_scoped_to_cargo_tables_and_local_declarations() {
        let manifest = "[dependencies]\ncore = { path = \"../core\", version = \"=0.4.0\" }\n[dev-dependencies]\nregistry-core = { package = \"core\", version = \"=0.4.0\" }\n[package.metadata.tool.dependencies]\ncore = { path = \"schema/core\", version = \"=0.4.0\" }\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert_eq!(out.matches("=0.5.0").count(), 1, "{out}");
        assert_eq!(out.matches("=0.4.0").count(), 2, "{out}");
    }

    #[test]
    fn rewrite_preserves_version_value_comments() {
        let manifest =
            "[dependencies.core]\npath = \"../core\"\nversion = \"=0.4.0\" # release-managed\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(
            out.contains("version = \"=0.5.0\" # release-managed"),
            "{out}"
        );
    }

    #[test]
    fn pin_rewrite_fails_closed_when_absent() {
        let manifest =
            "[dependencies]\nshipshape-core = { path = \"../shipshape-core\", version = \"^0.4\" }\n";
        assert_eq!(
            rewrite_pin(manifest, "shipshape-core", "=0.4.0", "=0.5.0"),
            Err(BumpEditError::PinNotFound {
                dependency: "shipshape-core".into(),
                from: "=0.4.0".into(),
            })
        );
    }

    #[test]
    fn pin_rewrite_leaves_a_caret_dep_untouched_even_with_same_crate() {
        // A different crate sharing the exact from-string must not be rewritten.
        let manifest = "[dependencies]\nshipshape-core = { path = \"../c\", version = \"=0.4.0\" }\nother = \"=0.4.0\"\n";
        let out = rewrite_pin(manifest, "shipshape-core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("shipshape-core = { path = \"../c\", version = \"=0.5.0\" }"));
        // `other = "=0.4.0"` is a plain registry dep, not our pin — untouched.
        assert!(out.contains("other = \"=0.4.0\""));
    }

    #[test]
    fn pin_rewrite_updates_every_equivalent_dependency_table() {
        let manifest = "[dependencies]\ncore = { path = \"a\", version = \"=0.4.0\" }\n[dev-dependencies]\ncore = { path = \"a\", version = \"=0.4.0\" }\n[build-dependencies]\ncore = { path = \"a\", version = \"=0.4.0\" }\n[target.'cfg(unix)'.dependencies]\ncore = { path = \"a\", version = \"=0.4.0\" }\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert_eq!(out.matches("version = \"=0.5.0\"").count(), 4);
        assert!(!out.contains("version = \"=0.4.0\""));
    }

    #[test]
    fn pin_rewrite_fails_closed_on_non_equivalent_matches() {
        let manifest = "[dependencies]\ncore = { path = \"a\", version = \"=0.4.0\" }\n[dev-dependencies]\ncore = { path = \"a\", version = \"^0.4\" }\n";
        let err = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap_err();
        assert!(matches!(err, BumpEditError::PinAmbiguous { count: 2, .. }));
    }

    #[test]
    fn pin_rewrite_uses_resolved_package_aliases() {
        let manifest = "[dependencies]\nalias = { package = \"core\", path = \"../core\", version = \"=0.4.0\" }\n[dev-dependencies.alias]\npackage = \"core\"\npath = \"../core\"\nversion = \"=0.4.0\"\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert_eq!(out.matches("version = \"=0.5.0\"").count(), 2);
    }

    #[test]
    fn pin_rewrite_ignores_non_dependency_tables_and_registry_dependencies() {
        let manifest = "[dependencies]\ncore = { path = \"../core\", version = \"=0.4.0\" }\n[dev-dependencies]\ncore = { version = \"^0.4\" }\n[package.metadata.release]\ncore = { version = \"=999.0.0\" }\n[patch.crates-io]\ncore = { path = \"vendor/core\", version = \"=999.0.0\" }\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert!(out.contains("version = \"=0.5.0\""));
        assert!(out.contains("core = { version = \"^0.4\" }"));
        assert_eq!(out.matches("version = \"=999.0.0\"").count(), 2);
    }

    #[test]
    fn path_only_duplicates_are_neutral() {
        let manifest = "[dependencies]\ncore = { path = \"../core\", version = \"=0.4.0\" }\n[target.'cfg(unix)'.dev-dependencies.core]\npath = \"../core\"\n";
        let out = rewrite_pin(manifest, "core", "=0.4.0", "=0.5.0").unwrap();
        assert_eq!(out.matches("=0.5.0").count(), 1);
        assert!(out.contains("[target.'cfg(unix)'.dev-dependencies.core]\npath"));
    }

    // ── finalize_changelog ───────────────────────────────────────────────────

    #[test]
    fn finalizes_the_unreleased_section() {
        let text = "# Changelog\n\n## [Unreleased]\n### Added\n- a thing\n";
        let out = finalize_changelog(text, "0.5.0", "2026-08-13").unwrap();
        assert!(out.contains("## [Unreleased]\n\n## [0.5.0] - 2026-08-13"));
        assert!(out.contains("- a thing"));
    }

    #[test]
    fn changelog_finalize_fails_closed_without_unreleased() {
        let text = "# Changelog\n\n## [0.4.0] - 2026-01-01\n";
        assert_eq!(
            finalize_changelog(text, "0.5.0", "2026-08-13"),
            Err(BumpEditError::ChangelogUnreleasedNotFound)
        );
    }

    #[test]
    fn marker_finalize_places_release_outside_markers_and_strips_markers_from_notes() {
        let text = "# Changelog\n\n<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n\n### Added\n\n### Changed\n\n### Fixed\n<!-- oss-changelog:unreleased-end -->\n\n## [0.6.1] - 2026-08-21\n\nOld.\n";
        let compiled =
            "### Changed\n\n- Agent Skills terminology.\n<!-- oss-changelog:unreleased-end -->\n";
        let out = finalize_marker_changelog(text, "0.6.2", "2026-08-23", compiled).unwrap();
        let end = out.find("<!-- oss-changelog:unreleased-end -->").unwrap();
        let release = out.find("## [0.6.2] - 2026-08-23").unwrap();
        assert!(
            release > end,
            "released section must be outside markers: {out}"
        );
        assert_eq!(
            out.matches("<!-- oss-changelog:unreleased-end -->").count(),
            1
        );
        assert!(out.contains("### Changed\n\n- Agent Skills terminology."));
        assert_eq!(out.matches("### Changed").count(), 2, "skeleton + release");
        assert!(out.contains("## [0.6.1] - 2026-08-21"));
    }

    #[test]
    fn marker_finalize_is_idempotent_only_when_no_notes_are_pending() {
        let text = "<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n\n### Added\n### Changed\n### Fixed\n<!-- oss-changelog:unreleased-end -->\n\n## [0.6.2] - 2026-08-23\n\n- shipped\n";
        assert_eq!(
            finalize_marker_changelog(text, "0.6.2", "2026-08-23", "").unwrap(),
            text
        );
        assert!(matches!(
            finalize_marker_changelog(text, "0.6.2", "2026-08-23", "- pending"),
            Err(BumpEditError::ChangelogReleaseConflict { .. })
        ));
    }

    #[test]
    fn marker_finalize_migrates_a_markerless_changelog() {
        let text = "# Changelog\n\n## [Unreleased]\n\n### Fixed\n\n- Authored fix.\n\n## 0.9.0 - 2026-08-01\n\nOld.\n\n[unreleased]: https://example.test/compare/v0.9.0...HEAD\n";
        let out =
            finalize_marker_changelog(text, "1.0.0", "2026-08-23", "### Fixed\n\n- Trailer fix.")
                .unwrap();
        assert!(out.contains("<!-- oss-changelog:unreleased-start -->"));
        assert!(
            out.contains(
                "## [1.0.0] - 2026-08-23\n\n### Fixed\n\n- Authored fix.\n\n- Trailer fix."
            ),
            "{out}"
        );
        assert_eq!(out.matches("### Fixed").count(), 2, "skeleton + release");
        assert!(out.contains("## 0.9.0 - 2026-08-01"));
        assert!(out.contains("[unreleased]: https://example.test/compare/v0.9.0...HEAD"));
    }

    #[test]
    fn markerless_unreleased_does_not_promote_link_definitions() {
        let text = "## [Unreleased]\n\n### Added\n\n- First release.\n\n[unreleased]: https://example.test/compare/v0.1.0...HEAD\n";
        let out = finalize_marker_changelog(text, "0.1.0", "2026-08-23", "").unwrap();
        let release = out.find("## [0.1.0] - 2026-08-23").unwrap();
        let link = out.find("[unreleased]: https://example.test").unwrap();
        assert!(link > release);
        assert!(!out[release..link].contains("[unreleased]:"));
    }

    #[test]
    fn marker_finalize_refuses_a_dated_release_inside_unreleased() {
        let broken = "<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n\n## [0.6.2] - 2026-08-23\n\n### Fixed\n- old\n<!-- oss-changelog:unreleased-end -->\n";
        assert_eq!(
            finalize_marker_changelog(broken, "0.6.3", "2026-08-24", "- new"),
            Err(BumpEditError::ChangelogMarkersMalformed)
        );
    }

    #[test]
    fn marker_finalize_refuses_malformed_markers_and_empty_releases() {
        let malformed = "<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n";
        assert_eq!(
            finalize_marker_changelog(malformed, "1.0.0", "2026-08-23", "- note"),
            Err(BumpEditError::ChangelogMarkersMalformed)
        );
        let empty = "<!-- oss-changelog:unreleased-start -->\n## [Unreleased]\n### Added\n### Changed\n### Fixed\n<!-- oss-changelog:unreleased-end -->\n";
        assert_eq!(
            finalize_marker_changelog(empty, "1.0.0", "2026-08-23", ""),
            Err(BumpEditError::ChangelogNotesEmpty)
        );
    }
}