mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
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
//! Shared test harness for the end-to-end CLI suites.
//!
//! The state-machine suite (`state_machine.rs`) and the fault-injection suites
//! (`crash_recovery.rs`, `corruption_rejection.rs`, `lock_contention.rs`) all
//! drive the real `mkit` binary and assert the same repo-invariant battery, so
//! that machinery lives here.
//!
//! Each integration-test binary compiles its own copy of this module, so not
//! every binary uses every helper — hence the crate-wide `allow(dead_code)`.

#![allow(dead_code)]
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

use mkit_core::Hash;
use mkit_core::index::read_index;
use mkit_core::layout::RepoLayout;
use mkit_core::object::Object;
use mkit_core::ops::live_objects;
use mkit_core::refs;
use mkit_core::sign::{KeyPair, save_key, verify_commit, verify_remix, verify_tag};
use mkit_core::store::ObjectStore;
use mkit_core::to_hex;

/// Deterministic seed for the prewritten signing key, so commits don't depend
/// on `keygen` randomness (faster + reproducible across runs).
pub(crate) const KEY_SEED: [u8; 32] = [0x11; 32];

// ---------------------------------------------------------------------------
// Loud skips (#505 PR 2/5)
// ---------------------------------------------------------------------------
//
// Tests that depend on an external tool or an opt-in environment flag used
// to `return` quietly (green) when the dependency was missing — a
// tool-less CI reported green while validating nothing. These helpers make
// that loud instead: under `MKIT_TEST_STRICT=1` (set in CI jobs that are
// expected to have the dependency) a missing tool/flag panics the test
// rather than silently skipping it.

// Not every integration-test binary that compiles this module calls these
// (see the file-level `allow(dead_code)` rationale above) — allow the
// re-export to go unused in binaries that only need `require_env_flag`.
#[allow(unused_imports)]
pub(crate) use mkit_test_util::{require_tool, tool_available};

/// Returns `true` if the opt-in environment flag `var` is set to `"1"`
/// (e.g. `MKIT_SSH_E2E_REAL`). If it is not: panic when `MKIT_TEST_STRICT`
/// is set, otherwise print a loud `SKIP:` line and return `false`.
///
/// Unlike `require_tool`, this doesn't test for a missing dependency — it
/// gates an opt-in, environment-fragile e2e suite. `MKIT_TEST_STRICT`
/// should therefore only be set alongside the flag itself in a CI job that
/// actually provisions the real e2e environment.
pub(crate) fn require_env_flag(var: &str) -> bool {
    if std::env::var(var).as_deref() == Ok("1") {
        return true;
    }
    assert!(
        std::env::var_os("MKIT_TEST_STRICT").is_none(),
        "{var}=1 required (MKIT_TEST_STRICT set) but not set"
    );
    eprintln!("SKIP: {var} not set to 1");
    false
}

// ---------------------------------------------------------------------------
// Driving the real binary
// ---------------------------------------------------------------------------

/// Spawn the real `mkit` binary, fully isolated from the developer's
/// environment, with a non-interactive editor so nothing ever blocks.
pub(crate) fn mkit(cwd: &Path, xdg: &Path, args: &[&str]) -> Output {
    mkit_env(cwd, xdg, args, &[])
}

/// [`mkit`] with extra environment variables set on the CHILD process —
/// never on this test process, where `std::env::set_var` is banned by
/// `clippy::disallowed_methods` (it races other threads on POSIX). This is
/// how a test injects an env-var knob such as `MKIT_PACK_REBASELINE_DEPTH`.
pub(crate) fn mkit_env(
    cwd: &Path,
    xdg: &Path,
    args: &[&str],
    extra_env: &[(&str, &str)],
) -> Output {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_mkit"));
    cmd.args(args)
        .current_dir(cwd)
        .env("XDG_CONFIG_HOME", xdg)
        .env("HOME", xdg)
        .env("EDITOR", "true")
        .env("VISUAL", "true")
        .env("GIT_EDITOR", "true")
        .stdin(Stdio::null());
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.output().expect("spawn mkit")
}

/// Prewrite a deterministic Ed25519 signing key at the default path.
pub(crate) fn install_fixed_key(root: &Path) -> Result<(), String> {
    let keys = root.join(".mkit").join("keys");
    std::fs::create_dir_all(&keys).map_err(|e| format!("mkdir keys: {e}"))?;
    let kp = KeyPair::from_seed(KEY_SEED);
    save_key(&keys.join("default.key"), &kp).map_err(|e| format!("save_key: {e}"))?;
    Ok(())
}

/// Exit codes a well-behaved `mkit` command may return — `OK` plus the
/// documented sysexits-style errors from `mkit-cli/src/exit.rs`. Anything else
/// (notably 101 from a Rust panic, or `None` from a signal) is a violation.
pub(crate) const ALLOWED_EXIT: &[i32] = &[0, 1, 64, 65, 66, 69, 73, 75, 76, 77, 78];

/// Assert a command exited with an allowlisted code and did not panic.
pub(crate) fn check_exit(out: &Output, label: &str) -> Result<(), String> {
    let stderr = String::from_utf8_lossy(&out.stderr);
    match out.status.code() {
        Some(c) if ALLOWED_EXIT.contains(&c) => {}
        Some(c) => {
            return Err(format!(
                "[{label}] disallowed exit code {c}; stderr: {stderr}"
            ));
        }
        None => return Err(format!("[{label}] killed by signal; stderr: {stderr}")),
    }
    for marker in ["panicked at", "thread 'main' panicked", "RUST_BACKTRACE"] {
        if stderr.contains(marker) {
            return Err(format!("[{label}] panic in stderr: {stderr}"));
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Invariant battery (test-local validator over mkit-core primitives)
// ---------------------------------------------------------------------------

/// The "no corruption" subset of the invariant battery that does NOT read
/// operation-state roots: content-addressing integrity over every loose
/// object, a well-formed HEAD, and a parseable index.
///
/// This is the right oracle after a *deliberately garbled* operation-state
/// image (a malformed `MERGE_HEAD` / `rebase-apply/todo`, …), where the full
/// [`check_invariants`] would correctly fail-closed: `live_objects()` →
/// `collect_roots()` reads those sidecar files and errors on malformed roots,
/// which is expected for a garbled state, not a sign of repo corruption.
pub(crate) fn check_store_intact(root: &Path, label: &str) -> Result<(), String> {
    let layout = RepoLayout::single(root);
    let store = ObjectStore::open(&layout).map_err(|e| format!("[{label}] open store: {e}"))?;

    // Content-addressing integrity: every loose object's bytes re-hash to its
    // path. `read` recomputes BLAKE3 and rejects on mismatch.
    let present = store
        .iter_object_hashes()
        .map_err(|e| format!("[{label}] enumerate objects: {e}"))?;
    for h in &present {
        store
            .read(h)
            .map_err(|e| format!("[{label}] object {} failed integrity: {e}", to_hex(h)))?;
    }

    // HEAD is well-formed (symbolic-to-branch or a 64-hex detached hash).
    refs::read_head(&layout).map_err(|e| format!("[{label}] HEAD malformed: {e}"))?;

    // Index parses.
    read_index(&layout).map_err(|e| format!("[{label}] index unparseable: {e}"))?;
    Ok(())
}

/// The full repo-invariant battery. Builds on [`check_store_intact`] and adds:
/// signed-root reachability + signature validity, gc-safety over mkit's own
/// retention live-set, and no leaked lock files. Only valid on a *parseable*
/// repo state (post-recovery / non-garbled).
pub(crate) fn check_invariants(root: &Path, label: &str) -> Result<(), String> {
    check_store_intact(root, label)?;
    let layout = RepoLayout::single(root);
    let mkit_dir = layout.common_dir().to_path_buf();
    let store = ObjectStore::open(&layout).map_err(|e| format!("[{label}] open store: {e}"))?;

    // Collect *signed* roots: HEAD, every head ref, every tag ref. A listed ref
    // whose on-disk bytes are malformed (hash == None) is corruption.
    let mut roots: Vec<Hash> = Vec::new();
    if let Some(h) =
        refs::resolve_head(&layout).map_err(|e| format!("[{label}] resolve HEAD: {e}"))?
    {
        roots.push(h);
    }
    for r in refs::list_refs(&layout).map_err(|e| format!("[{label}] list heads: {e}"))? {
        match r.hash {
            Some(h) => roots.push(h),
            None => {
                return Err(format!(
                    "[{label}] head ref '{}' has malformed bytes",
                    r.name
                ));
            }
        }
    }
    for r in refs::list_tags(&layout).map_err(|e| format!("[{label}] list tags: {e}"))? {
        match r.hash {
            Some(h) => roots.push(h),
            None => {
                return Err(format!(
                    "[{label}] tag ref '{}' has malformed bytes",
                    r.name
                ));
            }
        }
    }

    // Signature validity over the signed reachable set. Stash roots (unannotated
    // zero-sig commits) are NOT walked here — broad presence (incl. stash) is
    // covered by the gc live-set check below.
    let mut visited: HashSet<String> = HashSet::new();
    let mut work = roots;
    while let Some(h) = work.pop() {
        if !visited.insert(to_hex(&h)) {
            continue;
        }
        let obj = store
            .read_object(&h)
            .map_err(|e| format!("[{label}] reachable object {} unreadable: {e}", to_hex(&h)))?;
        match obj {
            Object::Commit(c) => {
                verify_commit(&c)
                    .map_err(|e| format!("[{label}] commit {} bad signature: {e}", to_hex(&h)))?;
                work.push(c.tree_hash);
                work.extend(c.parents);
            }
            Object::Remix(r) => {
                verify_remix(&r)
                    .map_err(|e| format!("[{label}] remix {} bad signature: {e}", to_hex(&h)))?;
                work.push(r.tree_hash);
                work.extend(r.parents);
            }
            Object::Tag(t) => {
                // `tag -a` creates an UNSIGNED annotated tag (zero signature);
                // only `tag -s` signs. Verify only when a signature is present,
                // mirroring the stash / unannotated-commit exemption.
                if t.signature != [0u8; 64] {
                    verify_tag(&t)
                        .map_err(|e| format!("[{label}] tag {} bad signature: {e}", to_hex(&h)))?;
                }
                work.push(t.target);
            }
            Object::Tree(t) => {
                work.extend(t.entries.into_iter().map(|e| e.object_hash));
            }
            Object::ChunkedBlob(cb) => work.extend(cb.chunks),
            Object::Blob(_) | Object::Delta(_) => {}
        }
    }

    // gc-safety: every object mkit would retain (its own live-set — refs, stash,
    // ORIG_HEAD, in-progress state, conflict sidecars, attestations, recovery
    // roots, and their closure incl. chunked-blob chunks) must be present.
    let live =
        live_objects(&store, &layout).map_err(|e| format!("[{label}] collect gc live-set: {e}"))?;
    for h in &live {
        store
            .read(h)
            .map_err(|e| format!("[{label}] live object {} missing/corrupt: {e}", to_hex(h)))?;
    }

    // No leaked *held* locks: every `.mkit/*.lock` is acquired and released
    // within a single command, so none may still be kernel-locked once the
    // command has returned. The sentinel files themselves are allowed (even
    // expected) to persist on disk — `repo_lock` never unlinks them (see
    // `mkit_core::repo_lock` module docs): unlinking on release reopens the
    // stale-vs-live inode-swap race a blocking wait exists to close. So the
    // check here is "not currently locked," not "does not exist."
    if let Ok(rd) = std::fs::read_dir(&mkit_dir) {
        for ent in rd.flatten() {
            let name = ent.file_name();
            let name = name.to_string_lossy();
            if !name.ends_with(".lock") {
                continue;
            }
            let path = ent.path();
            let file = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .open(&path)
                .map_err(|e| format!("[{label}] open lock sentinel .mkit/{name}: {e}"))?;
            match file.try_lock() {
                Ok(()) => {
                    let _ = file.unlock();
                }
                Err(_) => {
                    return Err(format!("[{label}] leaked held lock: .mkit/{name}"));
                }
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Operation-state inspection
// ---------------------------------------------------------------------------

/// Which resumable operation, if any, is in progress (by sidecar presence).
pub(crate) fn in_progress(mkit_dir: &Path) -> Option<&'static str> {
    if mkit_dir.join("rebase-apply").exists() || mkit_dir.join("rebase-merge").exists() {
        Some("rebase")
    } else if mkit_dir.join("CHERRY_PICK_HEAD").exists() {
        Some("cherry-pick")
    } else if mkit_dir.join("REVERT_HEAD").exists() {
        Some("revert")
    } else if mkit_dir.join("MERGE_HEAD").exists() {
        Some("merge")
    } else {
        None
    }
}

/// If `verb` left any on-disk residue after concluding, return a description of
/// the first piece found — else `None`. Residue is the in-progress marker, the
/// shared `mkit-conflicts` sidecar, or the op-specific message file
/// (`MERGE_MSG`/`CHERRY_PICK_MSG`/`REVERT_MSG`) — all of which the core
/// `clear_*_state` helpers remove. `ORIG_HEAD` is deliberately NOT checked: a
/// `reset` legitimately leaves it. Rebase keeps its sidecar/message *inside*
/// `rebase-apply/`, which the directory check already covers.
pub(crate) fn operation_residue(mkit_dir: &Path, verb: &str) -> Option<String> {
    let (head, msg) = match verb {
        "merge" => ("MERGE_HEAD", "MERGE_MSG"),
        "cherry-pick" => ("CHERRY_PICK_HEAD", "CHERRY_PICK_MSG"),
        "revert" => ("REVERT_HEAD", "REVERT_MSG"),
        "rebase" => {
            return (mkit_dir.join("rebase-apply").exists()
                || mkit_dir.join("rebase-merge").exists())
            .then(|| "rebase-apply/".to_owned());
        }
        _ => return None,
    };
    for residue in [head, "mkit-conflicts", msg] {
        if mkit_dir.join(residue).exists() {
            return Some(residue.to_owned());
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Repo fixture + conflict builders (used by the fault-injection suites)
// ---------------------------------------------------------------------------

/// A throwaway repo on a fresh temp dir, initialised with the fixed signing key
/// (no `keygen`), plus an isolated XDG/HOME dir.
pub(crate) struct Repo {
    pub dir: tempfile::TempDir,
    pub xdg: tempfile::TempDir,
}

impl Repo {
    /// `init` + install the fixed key.
    pub(crate) fn new() -> Self {
        let dir = tempfile::tempdir().expect("tempdir");
        let xdg = tempfile::tempdir().expect("xdg tempdir");
        let r = Repo { dir, xdg };
        r.ok(&["init"]);
        install_fixed_key(r.path()).expect("install key");
        r
    }

    pub(crate) fn path(&self) -> &Path {
        self.dir.path()
    }
    pub(crate) fn xdg(&self) -> &Path {
        self.xdg.path()
    }
    pub(crate) fn mkit_dir(&self) -> PathBuf {
        self.path().join(".mkit")
    }

    pub(crate) fn run(&self, args: &[&str]) -> Output {
        self.run_env(args, &[])
    }

    /// [`Repo::run`] with extra environment variables on the child (see
    /// [`mkit_env`]).
    pub(crate) fn run_env(&self, args: &[&str], extra_env: &[(&str, &str)]) -> Output {
        mkit_env(self.path(), self.xdg(), args, extra_env)
    }

    /// Run and assert success.
    pub(crate) fn ok(&self, args: &[&str]) -> Output {
        self.ok_env(args, &[])
    }

    /// [`Repo::ok`] with extra environment variables on the child.
    pub(crate) fn ok_env(&self, args: &[&str], extra_env: &[(&str, &str)]) -> Output {
        let out = self.run_env(args, extra_env);
        assert!(
            out.status.success(),
            "expected `mkit {}` to succeed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr)
        );
        out
    }

    pub(crate) fn write(&self, rel: &str, body: &[u8]) {
        let p = self.path().join(rel);
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(p, body).unwrap();
    }

    /// write + `add` + `commit -m`.
    pub(crate) fn commit_file(&self, rel: &str, body: &[u8], msg: &str) {
        self.write(rel, body);
        self.ok(&["add", rel]);
        self.ok(&["commit", "-m", msg]);
    }
}

impl Default for Repo {
    fn default() -> Self {
        Self::new()
    }
}

/// Build a base commit then a `feature` branch and `main` that edit the same
/// file divergently, leaving the repo checked out on `main` — so the next
/// `merge`/`cherry-pick`/`revert feature` conflicts. Returns the `feature`
/// branch name.
pub(crate) fn diverge_on(repo: &Repo, path: &str) -> &'static str {
    repo.commit_file(path, b"base\n", "base");
    repo.ok(&["branch", "feature"]);
    repo.ok(&["checkout", "feature"]);
    repo.commit_file(path, b"theirs\n", "theirs");
    repo.ok(&["checkout", "main"]);
    repo.commit_file(path, b"ours\n", "ours");
    "feature"
}

/// Drive `verb` into a conflicted, in-progress state on a freshly diverged
/// repo. `verb` ∈ {"merge","cherry-pick","revert","rebase"}. Returns the repo
/// with the operation paused (its sidecars on disk). Panics if the op does not
/// actually conflict (keeps the builders honest).
pub(crate) fn conflicted(verb: &str) -> Repo {
    let repo = Repo::new();
    let feature = diverge_on(&repo, "a.txt");
    let args: Vec<&str> = match verb {
        "merge" => vec!["merge", feature],
        "cherry-pick" => vec!["cherry-pick", feature],
        "revert" => {
            // Revert conflicts against a *divergent* HEAD: revert the base-era
            // change of `feature`'s tip after `main` moved the same file.
            vec!["revert", feature]
        }
        "rebase" => vec!["rebase", feature],
        other => panic!("unknown verb {other}"),
    };
    let out = repo.run(&args);
    assert!(
        !out.status.success(),
        "expected `mkit {}` to conflict, but it succeeded",
        args.join(" ")
    );
    assert!(
        in_progress(&repo.mkit_dir()) == Some(verb),
        "expected {verb} in progress, got {:?}; stderr: {}",
        in_progress(&repo.mkit_dir()),
        String::from_utf8_lossy(&out.stderr)
    );
    repo
}