mkit-core 0.4.0

Content-addressed VCS primitives for mkit: BLAKE3 hashing, canonical objects, refs, packs, and transport traits
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
//! Conflict / operation state sidecar.
//!
//! mkit's `.mkit/index` stays a single-stage **resolved** staging area
//! (see SPEC-INDEX — no unmerged stages 1/2/3). When a merge,
//! cherry-pick, or rebase pauses on a conflict we instead persist the
//! state needed to resume or abort in a small set of files under
//! `.mkit/`, using Git-compatible names where they exist plus one
//! documented mkit sidecar:
//!
//! - `MERGE_HEAD`        — 64-hex of the other parent (merge: theirs).
//!   Presence ⇒ a merge is in progress.
//! - `CHERRY_PICK_HEAD`  — 64-hex of the commit being picked.
//!   Presence ⇒ a cherry-pick is in progress.
//! - `REVERT_HEAD`       — 64-hex of the commit being reverted.
//!   Presence ⇒ a revert is in progress.
//! - `ORIG_HEAD`         — 64-hex of HEAD before the op (for `--abort`).
//! - `MERGE_MSG` / `CHERRY_PICK_MSG` / `REVERT_MSG` — pending commit message bytes.
//! - `mkit-conflicts`    — the sidecar: one line per conflicting path,
//!   recording the conflict kind and the base/ours/theirs blob hashes.
//!   Used by `--abort` cleanup and by the "unresolved conflicts remain"
//!   gate on `--continue`.
//!
//! Rebase reuses the existing `.mkit/rebase-apply/` directory and writes
//! the same `mkit-conflicts` sidecar **inside** that directory when it
//! pauses.
//!
//! `mkit-conflicts` line format (tab-separated, one per path):
//!
//! ```text
//! <kind>\t<base_hex|->\t<ours_hex|->\t<theirs_hex|->\t<path>
//! ```
//!
//! where `<kind>` is one of `modify`, `addadd`, `deletemodify` and a
//! missing side is encoded as a single `-`. The `<path>` is the final
//! field so it may itself contain no `\t` (validated via
//! [`crate::index::validate_index_path`] on read) and runs to end of
//! line.

use std::fs;
use std::io;
use std::path::Path;

use crate::hash::{self, HEX_LEN, Hash};
use crate::index::validate_index_path;
use crate::layout::RepoLayout;
use crate::ops::merge::{Conflict, ConflictKind};

/// File name: other parent of an in-progress merge.
pub const MERGE_HEAD: &str = "MERGE_HEAD";
/// File name: commit being applied by an in-progress cherry-pick.
pub const CHERRY_PICK_HEAD: &str = "CHERRY_PICK_HEAD";
/// File name: HEAD before the in-progress operation started.
pub const ORIG_HEAD: &str = "ORIG_HEAD";
/// File name: pending merge commit message.
pub const MERGE_MSG: &str = "MERGE_MSG";
/// File name: pending cherry-pick commit message.
pub const CHERRY_PICK_MSG: &str = "CHERRY_PICK_MSG";
/// File name: commit being reverted by an in-progress revert.
pub const REVERT_HEAD: &str = "REVERT_HEAD";
/// File name: pending revert commit message.
pub const REVERT_MSG: &str = "REVERT_MSG";
/// File name: the conflict sidecar (also used inside `rebase-apply/`).
pub const CONFLICTS_FILE: &str = "mkit-conflicts";
/// File name: the operation's full result tree (clean changes + ours-at-
/// conflict) recorded when a conflict pauses, so `--abort` can distinguish
/// operation-authored paths from genuine user work.
pub const RESULT_TREE: &str = "MKIT_OP_RESULT";

/// Hard cap on any single state file we read back (1 MiB). Conflict
/// sidecars list at most one line per repo path; 1 MiB is generous.
const MAX_STATE_BYTES: u64 = 1024 * 1024;

/// Errors raised by the conflict-state subsystem.
#[derive(Debug, thiserror::Error)]
pub enum ConflictStateError {
    /// On-disk state was malformed (bad hex, bad kind, bad path, …).
    #[error("conflict state on disk is malformed")]
    Invalid,
    /// Underlying I/O failure.
    #[error(transparent)]
    Io(#[from] io::Error),
}

/// Result alias.
pub type ConflictStateResult<T> = Result<T, ConflictStateError>;

/// One recorded conflicting path: the conflict kind plus the three blob
/// hashes carried by [`Conflict`]. A missing side is `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictRecord {
    /// Repo-relative path.
    pub path: String,
    /// Conflict kind.
    pub kind: ConflictKind,
    /// Base-side blob hash (`None` for add/add).
    pub base_hash: Option<Hash>,
    /// Ours-side blob hash (`None` when ours deleted).
    pub ours_hash: Option<Hash>,
    /// Theirs-side blob hash (`None` when theirs deleted).
    pub theirs_hash: Option<Hash>,
}

impl From<&Conflict> for ConflictRecord {
    fn from(c: &Conflict) -> Self {
        Self {
            path: c.path.clone(),
            kind: c.kind,
            base_hash: c.base_hash,
            ours_hash: c.ours_hash,
            theirs_hash: c.theirs_hash,
        }
    }
}

fn kind_tag(kind: ConflictKind) -> &'static str {
    match kind {
        ConflictKind::ModifyModify => "modify",
        ConflictKind::AddAdd => "addadd",
        ConflictKind::DeleteModify => "deletemodify",
    }
}

fn kind_from_tag(tag: &str) -> Option<ConflictKind> {
    match tag {
        "modify" => Some(ConflictKind::ModifyModify),
        "addadd" => Some(ConflictKind::AddAdd),
        "deletemodify" => Some(ConflictKind::DeleteModify),
        _ => None,
    }
}

fn hex_or_dash(h: Option<Hash>) -> String {
    match h {
        Some(h) => hash::to_hex(&h),
        None => "-".to_string(),
    }
}

fn parse_hex_or_dash(field: &str) -> Result<Option<Hash>, ConflictStateError> {
    if field == "-" {
        return Ok(None);
    }
    if field.len() != HEX_LEN {
        return Err(ConflictStateError::Invalid);
    }
    hash::from_hex(field)
        .map(Some)
        .map_err(|_| ConflictStateError::Invalid)
}

/// Serialise conflict records to the `mkit-conflicts` line format.
#[must_use]
pub fn serialize_conflicts(records: &[ConflictRecord]) -> Vec<u8> {
    let mut out = String::new();
    for r in records {
        out.push_str(kind_tag(r.kind));
        out.push('\t');
        out.push_str(&hex_or_dash(r.base_hash));
        out.push('\t');
        out.push_str(&hex_or_dash(r.ours_hash));
        out.push('\t');
        out.push_str(&hex_or_dash(r.theirs_hash));
        out.push('\t');
        out.push_str(&r.path);
        out.push('\n');
    }
    out.into_bytes()
}

/// Parse the `mkit-conflicts` line format. Rejects malformed lines.
///
/// # Errors
/// [`ConflictStateError::Invalid`] on any malformed line (bad field
/// count, unknown kind, bad hex, or a path failing
/// [`validate_index_path`]).
pub fn deserialize_conflicts(data: &[u8]) -> ConflictStateResult<Vec<ConflictRecord>> {
    let text = core::str::from_utf8(data).map_err(|_| ConflictStateError::Invalid)?;
    let mut out = Vec::new();
    for line in text.split('\n') {
        if line.is_empty() {
            continue;
        }
        // kind, base, ours, theirs, path — exactly 5 fields; the path is
        // last and may not contain a tab.
        let mut fields = line.splitn(5, '\t');
        let kind = fields.next().ok_or(ConflictStateError::Invalid)?;
        let base = fields.next().ok_or(ConflictStateError::Invalid)?;
        let ours = fields.next().ok_or(ConflictStateError::Invalid)?;
        let theirs = fields.next().ok_or(ConflictStateError::Invalid)?;
        let path = fields.next().ok_or(ConflictStateError::Invalid)?;
        let kind = kind_from_tag(kind).ok_or(ConflictStateError::Invalid)?;
        if !validate_index_path(path) {
            return Err(ConflictStateError::Invalid);
        }
        out.push(ConflictRecord {
            path: path.to_string(),
            kind,
            base_hash: parse_hex_or_dash(base)?,
            ours_hash: parse_hex_or_dash(ours)?,
            theirs_hash: parse_hex_or_dash(theirs)?,
        });
    }
    Ok(out)
}

/// Persist the operation's full result tree under `dir` (the per-op state
/// directory: `.mkit` for merge/cherry-pick/revert, the rebase dir for
/// rebase). Used by `--abort` to treat operation-authored paths as
/// discardable. Best-effort cleanup is done by the per-op clear functions
/// (or by removing the rebase dir).
///
/// # Errors
/// [`ConflictStateError::Io`] if the file cannot be written.
pub fn write_result_tree(dir: &Path, tree: &Hash) -> ConflictStateResult<()> {
    write_hex_file(dir, RESULT_TREE, tree)
}

/// Read the persisted operation result tree under `dir`, if any.
///
/// # Errors
/// [`ConflictStateError::Invalid`] if the file is malformed.
pub fn read_result_tree(dir: &Path) -> ConflictStateResult<Option<Hash>> {
    read_hex_file(&dir.join(RESULT_TREE))
}

/// Remove the persisted operation result tree (best-effort).
pub fn clear_result_tree(dir: &Path) {
    let _ = fs::remove_file(dir.join(RESULT_TREE));
}

fn write_hex_file(state_dir: &Path, name: &str, h: &Hash) -> ConflictStateResult<()> {
    let mut buf = hash::to_hex(h);
    buf.push('\n');
    fs::write(state_dir.join(name), buf.as_bytes())?;
    Ok(())
}

fn read_hex_file(path: &Path) -> ConflictStateResult<Option<Hash>> {
    let raw = match read_capped(path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(ConflictStateError::Io(e)),
    };
    let trimmed = raw.trim_end_matches(['\n', '\r', ' ', '\t']);
    if trimmed.len() != HEX_LEN {
        return Err(ConflictStateError::Invalid);
    }
    hash::from_hex(trimmed)
        .map(Some)
        .map_err(|_| ConflictStateError::Invalid)
}

fn read_capped(path: &Path) -> io::Result<String> {
    let meta = fs::metadata(path)?;
    if meta.len() > MAX_STATE_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "state too large",
        ));
    }
    let raw = fs::read(path)?;
    String::from_utf8(raw).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "non-utf8"))
}

/// Persisted state for an in-progress merge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeState {
    /// The other (theirs) parent of the merge.
    pub merge_head: Hash,
    /// HEAD before the merge started.
    pub orig_head: Hash,
    /// Pending merge commit message.
    pub message: Vec<u8>,
}

/// Persisted state for an in-progress cherry-pick.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CherryPickState {
    /// The commit being picked.
    pub cherry_pick_head: Hash,
    /// HEAD before the cherry-pick started.
    pub orig_head: Hash,
    /// Pending commit message (the picked commit's message).
    pub message: Vec<u8>,
}

/// Persisted state for an in-progress revert.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RevertState {
    /// The commit being reverted.
    pub revert_head: Hash,
    /// HEAD before the revert started.
    pub orig_head: Hash,
    /// Pending commit message (the generated `Revert "..."` message).
    pub message: Vec<u8>,
}

/// Write revert state + the conflict sidecar.
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures.
pub fn write_revert_state(
    layout: &RepoLayout,
    state: &RevertState,
    conflicts: &[ConflictRecord],
) -> ConflictStateResult<()> {
    fs::create_dir_all(layout.worktree_state_dir())?;
    write_hex_file(layout.worktree_state_dir(), REVERT_HEAD, &state.revert_head)?;
    write_hex_file(layout.worktree_state_dir(), ORIG_HEAD, &state.orig_head)?;
    fs::write(layout.revert_msg_file(), &state.message)?;
    fs::write(layout.conflicts_file(), serialize_conflicts(conflicts))?;
    Ok(())
}

/// Read revert state. Returns `Ok(None)` when none is in progress.
///
/// # Errors
/// [`ConflictStateError::Invalid`] on malformed state.
pub fn read_revert_state(layout: &RepoLayout) -> ConflictStateResult<Option<RevertState>> {
    let Some(revert_head) = read_hex_file(&layout.revert_head_file())? else {
        return Ok(None);
    };
    let orig_head = read_hex_file(&layout.orig_head_file())?.ok_or(ConflictStateError::Invalid)?;
    let message = match fs::read(layout.revert_msg_file()) {
        Ok(m) => m,
        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(e) => return Err(ConflictStateError::Io(e)),
    };
    Ok(Some(RevertState {
        revert_head,
        orig_head,
        message,
    }))
}

/// Remove all revert state files (idempotent).
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures other than absence.
pub fn clear_revert_state(layout: &RepoLayout) -> ConflictStateResult<()> {
    remove_if_present(&layout.revert_head_file())?;
    remove_if_present(&layout.revert_msg_file())?;
    remove_if_present(&layout.orig_head_file())?;
    remove_if_present(&layout.conflicts_file())?;
    remove_if_present(&layout.result_tree_file())?;
    Ok(())
}

/// `true` when a revert is in progress (`REVERT_HEAD` present).
#[must_use]
pub fn is_revert_in_progress(layout: &RepoLayout) -> bool {
    layout.revert_head_file().exists()
}

/// Write merge state + the conflict sidecar.
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures.
pub fn write_merge_state(
    layout: &RepoLayout,
    state: &MergeState,
    conflicts: &[ConflictRecord],
) -> ConflictStateResult<()> {
    fs::create_dir_all(layout.worktree_state_dir())?;
    write_hex_file(layout.worktree_state_dir(), MERGE_HEAD, &state.merge_head)?;
    write_hex_file(layout.worktree_state_dir(), ORIG_HEAD, &state.orig_head)?;
    fs::write(layout.merge_msg_file(), &state.message)?;
    fs::write(layout.conflicts_file(), serialize_conflicts(conflicts))?;
    Ok(())
}

/// Read merge state. Returns `Ok(None)` when no merge is in progress.
///
/// # Errors
/// [`ConflictStateError::Invalid`] on malformed state.
pub fn read_merge_state(layout: &RepoLayout) -> ConflictStateResult<Option<MergeState>> {
    let Some(merge_head) = read_hex_file(&layout.merge_head_file())? else {
        return Ok(None);
    };
    let orig_head = read_hex_file(&layout.orig_head_file())?.ok_or(ConflictStateError::Invalid)?;
    let message = match fs::read(layout.merge_msg_file()) {
        Ok(m) => m,
        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(e) => return Err(ConflictStateError::Io(e)),
    };
    Ok(Some(MergeState {
        merge_head,
        orig_head,
        message,
    }))
}

/// Write cherry-pick state + the conflict sidecar.
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures.
pub fn write_cherry_pick_state(
    layout: &RepoLayout,
    state: &CherryPickState,
    conflicts: &[ConflictRecord],
) -> ConflictStateResult<()> {
    fs::create_dir_all(layout.worktree_state_dir())?;
    write_hex_file(
        layout.worktree_state_dir(),
        CHERRY_PICK_HEAD,
        &state.cherry_pick_head,
    )?;
    write_hex_file(layout.worktree_state_dir(), ORIG_HEAD, &state.orig_head)?;
    fs::write(layout.cherry_pick_msg_file(), &state.message)?;
    fs::write(layout.conflicts_file(), serialize_conflicts(conflicts))?;
    Ok(())
}

/// Read cherry-pick state. Returns `Ok(None)` when none is in progress.
///
/// # Errors
/// [`ConflictStateError::Invalid`] on malformed state.
pub fn read_cherry_pick_state(layout: &RepoLayout) -> ConflictStateResult<Option<CherryPickState>> {
    let Some(cherry_pick_head) = read_hex_file(&layout.cherry_pick_head_file())? else {
        return Ok(None);
    };
    let orig_head = read_hex_file(&layout.orig_head_file())?.ok_or(ConflictStateError::Invalid)?;
    let message = match fs::read(layout.cherry_pick_msg_file()) {
        Ok(m) => m,
        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(e) => return Err(ConflictStateError::Io(e)),
    };
    Ok(Some(CherryPickState {
        cherry_pick_head,
        orig_head,
        message,
    }))
}

/// Read the conflict sidecar from `dir` (either `.mkit/` for merge /
/// cherry-pick or `.mkit/rebase-apply/` for rebase). Returns an empty
/// vector when the file is absent.
///
/// # Errors
/// [`ConflictStateError::Invalid`] on malformed lines.
pub fn read_conflicts(dir: &Path) -> ConflictStateResult<Vec<ConflictRecord>> {
    let path = dir.join(CONFLICTS_FILE);
    let raw = match read_capped(&path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(ConflictStateError::Io(e)),
    };
    deserialize_conflicts(raw.as_bytes())
}

/// Write the conflict sidecar into `dir`.
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures.
pub fn write_conflicts(dir: &Path, conflicts: &[ConflictRecord]) -> ConflictStateResult<()> {
    fs::create_dir_all(dir)?;
    fs::write(dir.join(CONFLICTS_FILE), serialize_conflicts(conflicts))?;
    Ok(())
}

fn remove_if_present(path: &Path) -> ConflictStateResult<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(ConflictStateError::Io(e)),
    }
}

/// Remove all merge state files (idempotent).
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures other than absence.
pub fn clear_merge_state(layout: &RepoLayout) -> ConflictStateResult<()> {
    remove_if_present(&layout.merge_head_file())?;
    remove_if_present(&layout.merge_msg_file())?;
    remove_if_present(&layout.orig_head_file())?;
    remove_if_present(&layout.conflicts_file())?;
    remove_if_present(&layout.result_tree_file())?;
    Ok(())
}

/// Remove all cherry-pick state files (idempotent).
///
/// # Errors
/// [`ConflictStateError::Io`] on filesystem failures other than absence.
pub fn clear_cherry_pick_state(layout: &RepoLayout) -> ConflictStateResult<()> {
    remove_if_present(&layout.cherry_pick_head_file())?;
    remove_if_present(&layout.cherry_pick_msg_file())?;
    remove_if_present(&layout.orig_head_file())?;
    remove_if_present(&layout.conflicts_file())?;
    remove_if_present(&layout.result_tree_file())?;
    Ok(())
}

/// `true` when a merge is in progress (`MERGE_HEAD` present).
#[must_use]
pub fn is_merge_in_progress(layout: &RepoLayout) -> bool {
    layout.merge_head_file().exists()
}

/// `true` when a cherry-pick is in progress (`CHERRY_PICK_HEAD` present).
#[must_use]
pub fn is_cherry_pick_in_progress(layout: &RepoLayout) -> bool {
    layout.cherry_pick_head_file().exists()
}

/// `true` when any merge / cherry-pick / rebase is in progress. Used to
/// refuse starting a second such operation while one is unfinished.
#[must_use]
pub fn any_op_in_progress(layout: &RepoLayout) -> bool {
    is_merge_in_progress(layout)
        || is_cherry_pick_in_progress(layout)
        || is_revert_in_progress(layout)
        || crate::ops::rebase::is_rebase_in_progress(layout)
}

/// Human-readable name of whichever op is in progress, for error text.
#[must_use]
pub fn in_progress_op_name(layout: &RepoLayout) -> Option<&'static str> {
    if is_merge_in_progress(layout) {
        Some("merge")
    } else if is_cherry_pick_in_progress(layout) {
        Some("cherry-pick")
    } else if is_revert_in_progress(layout) {
        Some("revert")
    } else if crate::ops::rebase::is_rebase_in_progress(layout) {
        Some("rebase")
    } else {
        None
    }
}

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

    fn h(seed: &str) -> Hash {
        hash::hash(seed.as_bytes())
    }

    #[test]
    fn conflict_records_round_trip() {
        let records = vec![
            ConflictRecord {
                path: "src/main.rs".into(),
                kind: ConflictKind::ModifyModify,
                base_hash: Some(h("b")),
                ours_hash: Some(h("o")),
                theirs_hash: Some(h("t")),
            },
            ConflictRecord {
                path: "new.txt".into(),
                kind: ConflictKind::AddAdd,
                base_hash: None,
                ours_hash: Some(h("o2")),
                theirs_hash: Some(h("t2")),
            },
            ConflictRecord {
                path: "gone.txt".into(),
                kind: ConflictKind::DeleteModify,
                base_hash: Some(h("b3")),
                ours_hash: None,
                theirs_hash: Some(h("t3")),
            },
        ];
        let bytes = serialize_conflicts(&records);
        let parsed = deserialize_conflicts(&bytes).unwrap();
        assert_eq!(parsed, records);
    }

    #[test]
    fn rejects_bad_kind() {
        let line = format!("bogus\t-\t{}\t-\tpath.txt\n", hash::to_hex(&h("o")));
        assert!(deserialize_conflicts(line.as_bytes()).is_err());
    }

    #[test]
    fn rejects_bad_path() {
        let line = format!("modify\t-\t{}\t-\t../escape\n", hash::to_hex(&h("o")));
        assert!(deserialize_conflicts(line.as_bytes()).is_err());
    }

    #[test]
    fn rejects_short_hex() {
        let line = "modify\tdeadbeef\t-\t-\tpath.txt\n";
        assert!(deserialize_conflicts(line.as_bytes()).is_err());
    }

    #[test]
    fn rejects_truncated_line() {
        let line = "modify\t-\t-\n";
        assert!(deserialize_conflicts(line.as_bytes()).is_err());
    }

    #[test]
    fn merge_state_round_trip() {
        let tmp = TempDir::new().unwrap();
        let mkit = RepoLayout::single(tmp.path());
        fs::create_dir_all(mkit.worktree_state_dir()).unwrap();
        let state = MergeState {
            merge_head: h("theirs"),
            orig_head: h("orig"),
            message: b"Merge branch 'x'".to_vec(),
        };
        let conflicts = vec![ConflictRecord {
            path: "a.txt".into(),
            kind: ConflictKind::ModifyModify,
            base_hash: Some(h("b")),
            ours_hash: Some(h("o")),
            theirs_hash: Some(h("t")),
        }];
        write_merge_state(&mkit, &state, &conflicts).unwrap();
        assert!(is_merge_in_progress(&mkit));
        assert!(any_op_in_progress(&mkit));
        let read = read_merge_state(&mkit).unwrap().unwrap();
        assert_eq!(read, state);
        assert_eq!(
            read_conflicts(mkit.worktree_state_dir()).unwrap(),
            conflicts
        );
        clear_merge_state(&mkit).unwrap();
        assert!(!is_merge_in_progress(&mkit));
        assert!(read_merge_state(&mkit).unwrap().is_none());
    }

    #[test]
    fn cherry_pick_state_round_trip() {
        let tmp = TempDir::new().unwrap();
        let mkit = RepoLayout::single(tmp.path());
        fs::create_dir_all(mkit.worktree_state_dir()).unwrap();
        let state = CherryPickState {
            cherry_pick_head: h("pick"),
            orig_head: h("orig"),
            message: b"original message".to_vec(),
        };
        write_cherry_pick_state(&mkit, &state, &[]).unwrap();
        assert!(is_cherry_pick_in_progress(&mkit));
        let read = read_cherry_pick_state(&mkit).unwrap().unwrap();
        assert_eq!(read, state);
        clear_cherry_pick_state(&mkit).unwrap();
        assert!(!is_cherry_pick_in_progress(&mkit));
    }

    #[test]
    fn clear_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let mkit = RepoLayout::single(tmp.path());
        fs::create_dir_all(mkit.worktree_state_dir()).unwrap();
        clear_merge_state(&mkit).unwrap();
        clear_cherry_pick_state(&mkit).unwrap();
    }
}