Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

116 KB
Raw Blame
//! `app lift`: once the front door answers every recorded case in Rust, remove the fallback, the
//! kill switches and the units' bindings, and prove the pure binary on the recorded cases.
//!
//! The lift is made on a copy of `rust/` and only copied back when every check passes, so a lift
//! that fails leaves the repository as it was.

use crate::walk::Canonical;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, bail, ensure};
use regex::Regex;
use serde::{Deserialize, Serialize};
use toml_edit::{DocumentMut, Item as TomlItem, value};

use crate::app::{self, ReplayOptions, ReplayOutcome};
use crate::front_door::{self, APP_DIR, AppKind, MAIN_RS, STATE_FILE, State};
use crate::front_door_http as http_door;
use crate::gate::{self, Check};

const BINDING_DEPS: [&str; 9] = [
    "napi",
    "napi-derive",
    "napi-build",
    "wasm-bindgen",
    "pyo3",
    "pyo3-build-config",
    "magnus",
    "rb-sys",
    "jni",
];
const GENERATED_FILES: [&str; 3] = ["build.rs", "index.cjs", "index.d.ts"];
const GENERATED_DIRS: [&str; 7] = ["python", "go", "ruby", "java", "include", "shadow", "pkg"];
const GENERATED_MODULES: [&str; 6] = ["js", "wire", "pyconv", "rbconv", "utf16", "pynum"];
const ASSET_DIRS: [&str; 9] = [
    "assets",
    "templates",
    "static",
    "data",
    "locales",
    "i18n",
    "public",
    "resources",
    "share",
];
const TARGET_TRIPLE: &str = r"\b(?:x86_64|aarch64|i686|i586|armv7|arm|thumbv7em|wasm32|wasm64|riscv64gc|powerpc64le|s390x|loongarch64)-[a-z0-9_]+(?:-[a-z0-9_]+){1,2}\b";

const LIFTED_MAIN: &str = "mod cli;
mod units;

use std::process::ExitCode;

fn main() -> ExitCode {
    let matches = cli::command().get_matches();
    let (command, sub) = matches.subcommand().unwrap_or((cli::ROOT, &matches));
    units::dispatch(command, sub).unwrap_or_else(|| {
        eprintln!(\"{}: no handler for `{command}`\", cli::ROOT);
        ExitCode::from(2)
    })
}
";

#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Mark {
    Pass,
    Warn,
    Fail,
    Skip,
}

/// One line of the lift checklist.
#[derive(Debug, Serialize)]
pub struct Item {
    pub name: String,
    pub mark: Mark,
    pub detail: String,
}

impl Item {
    fn new(name: impl Into<String>, mark: Mark, detail: impl Into<String>) -> Self {
        Item {
            name: name.into(),
            mark,
            detail: detail.into(),
        }
    }

    fn from_check(prefix: &str, check: Check) -> Self {
        Item::new(
            format!("{prefix}: {}", check.name),
            if check.passed { Mark::Pass } else { Mark::Fail },
            check.detail,
        )
    }
}

pub struct LiftOptions<'a> {
    pub repo: &'a Path,
}

#[derive(Debug, Serialize)]
pub struct LiftOutcome {
    pub lifted: bool,
    /// Why the lift did not happen.
    pub blockers: Vec<String>,
    pub checklist: Vec<Item>,
    pub units: Vec<String>,
    /// Files the lift removed, relative to the repository.
    pub removed: Vec<String>,
    pub binary: Option<PathBuf>,
    /// The recorded cases against the lifted binary.
    pub replay: Option<ReplayOutcome>,
    /// The copy the lift was checked in, kept when a check failed.
    pub stage: Option<PathBuf>,
}

impl LiftOutcome {
    fn refused(blockers: Vec<String>, checklist: Vec<Item>, stage: Option<PathBuf>) -> Self {
        LiftOutcome {
            lifted: false,
            blockers,
            checklist,
            units: Vec::new(),
            removed: Vec::new(),
            binary: None,
            replay: None,
            stage,
        }
    }
}

/// What the obligation ledger adds to what blocks `app lift`: what nobody waived or attested (one
/// sentence per group), or, when the decisions, the bindings or the cases cannot be read, one
/// blocker that says so. A read error never turns into "nothing blocks". `shown` is the repository
/// as the person named it, so the commands can be copied.
pub(crate) fn obligation_blockers(repo: &Path, shown: &str) -> Vec<String> {
    match crate::obligations::standing::standing(repo) {
        Ok(standing) => crate::obligations::standing::lift_blockers(&standing, shown),
        Err(e) => vec![format!("{OBLIGATIONS_UNCHECKED}{e:#}")],
    }
}

/// The start of the line that says the obligations could not be read.
pub const OBLIGATIONS_UNCHECKED: &str = "the obligations could not be checked: ";

/// Whether this blocker line comes from the obligation registry (a sentence of `lift_blockers`
/// or the read that failed). The MCP server uses it to point to `obligations --check`; the two
/// texts are the ones this module writes, not copies.
pub fn is_obligation_blocker(line: &str) -> bool {
    line.starts_with(OBLIGATIONS_UNCHECKED)
        || line.contains(crate::obligations::standing::LISTS_THEM_ALL)
}

fn copy_tree(from: &Path, to: &Path) -> Result<()> {
    copy_tree_inner(from, to, true)
}

fn copy_tree_inner(from: &Path, to: &Path, is_root: bool) -> Result<()> {
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)?.flatten() {
        let name = entry.file_name();
        if is_root && (name == "target" || name == ".git") {
            continue;
        }
        let kind = entry.file_type()?;
        if kind.is_dir() {
            copy_tree_inner(&entry.path(), &to.join(&name), false)?;
        } else if kind.is_file() {
            std::fs::copy(entry.path(), to.join(&name))?;
        }
    }
    Ok(())
}

fn files_under(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if dir == root && (entry.file_name() == "target" || entry.file_name() == ".git") {
                continue;
            }
            match entry.file_type() {
                Ok(t) if t.is_dir() => stack.push(path),
                Ok(t) if t.is_file() => out.push(path),
                _ => {}
            }
        }
    }
    out.sort();
    out
}

fn remove_empty_dirs(root: &Path) {
    let Ok(entries) = std::fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        if entry.file_type().is_ok_and(|t| t.is_dir()) && entry.file_name() != "target" {
            remove_empty_dirs(&entry.path());
            let _ = std::fs::remove_dir(entry.path());
        }
    }
}

/// Makes `to` hold what `from` holds (its `target/` aside); returns the files removed from `to`.
fn sync(from: &Path, to: &Path) -> Result<()> {
    std::fs::read_dir(from).with_context(|| format!("reading {}", from.display()))?;
    for path in files_under(to) {
        let rel = path.strip_prefix(to).unwrap_or(&path);
        if !from.join(rel).exists() {
            std::fs::remove_file(&path)?;
        }
    }
    copy_tree(from, to)?;
    remove_empty_dirs(to);
    Ok(())
}

/// Modules `port.rs` reaches through `crate::` and `super::`, transitively.
fn port_modules(src: &Path) -> BTreeSet<String> {
    let single = Regex::new(r"(?:crate|super)::([A-Za-z_][A-Za-z0-9_]*)").expect("valid regex");
    let group = Regex::new(r"(?:crate|super)::\{([^}]*)\}").expect("valid regex");
    let module_file = |name: &str| -> Option<PathBuf> {
        [
            src.join(format!("{name}.rs")),
            src.join(name).join("mod.rs"),
        ]
        .into_iter()
        .find(|p| p.is_file())
    };
    let mut keep = BTreeSet::new();
    let mut queue = vec![src.join("port.rs")];
    while let Some(file) = queue.pop() {
        let text = std::fs::read_to_string(&file).unwrap_or_default();
        let mut names: Vec<String> = single
            .captures_iter(&text)
            .map(|c| c[1].to_string())
            .collect();
        for c in group.captures_iter(&text) {
            names.extend(
                c[1].split(',')
                    .filter_map(|n| n.split("::").next())
                    .map(|n| n.trim().to_string()),
            );
        }
        for name in names {
            if name == "port" || keep.contains(&name) {
                continue;
            }
            if let Some(path) = module_file(&name) {
                keep.insert(name);
                queue.push(path);
            }
        }
    }
    keep
}

/// Turns a unit crate into a plain library: no `cdylib`, no binding dependencies, `lib.rs` that
/// only exposes `port` (and the modules it uses), and, for a crate `bridge` made, no generated
/// wrappers. Returns the paths it removed.
/// The crates under `rust_dir` that `roots` depend on by path, transitively, roots excluded.
fn path_dependencies(roots: &[PathBuf], rust_dir: &Path) -> Vec<PathBuf> {
    let mut seen: BTreeSet<PathBuf> = roots.iter().cloned().collect();
    let mut found = Vec::new();
    let mut queue: Vec<PathBuf> = roots.to_vec();
    while let Some(dir) = queue.pop() {
        let Ok(text) = std::fs::read_to_string(dir.join("Cargo.toml")) else {
            continue;
        };
        let Ok(doc) = text.parse::<DocumentMut>() else {
            continue;
        };
        for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
            let Some(deps) = doc.get(table).and_then(TomlItem::as_table_like) else {
                continue;
            };
            for (_, dep) in deps.iter() {
                let Some(path) = dep.get("path").and_then(TomlItem::as_str) else {
                    continue;
                };
                let Ok(target) = dir.join(path).canonical() else {
                    continue;
                };
                if target.starts_with(rust_dir) && seen.insert(target.clone()) {
                    found.push(target.clone());
                    queue.push(target);
                }
            }
        }
    }
    found.sort();
    found
}

/// `lib.rs` of a stripped unit: `port` and the generated modules it uses, in the order rustfmt
/// keeps module declarations.
fn stripped_lib_rs(keep: &[String]) -> String {
    let mut modules: Vec<&str> = keep.iter().map(String::as_str).collect();
    modules.push("port");
    modules.sort_unstable();
    modules.dedup();
    modules.iter().map(|m| format!("pub mod {m};\n")).collect()
}

pub fn strip_unit(dir: &Path) -> Result<Vec<PathBuf>> {
    let cargo = dir.join("Cargo.toml");
    let mut doc: DocumentMut = std::fs::read_to_string(&cargo)
        .with_context(|| format!("reading {}", cargo.display()))?
        .parse()
        .with_context(|| format!("parsing {}", cargo.display()))?;
    if let Some(lib) = doc.get_mut("lib").and_then(TomlItem::as_table_mut) {
        lib.remove("crate-type");
        if lib.is_empty() {
            doc.remove("lib");
        }
    }
    for table in ["dependencies", "build-dependencies"] {
        if let Some(deps) = doc.get_mut(table).and_then(TomlItem::as_table_like_mut) {
            for dep in BINDING_DEPS {
                deps.remove(dep);
            }
        }
    }
    if doc
        .get("build-dependencies")
        .and_then(TomlItem::as_table_like)
        .is_some_and(|t| t.is_empty())
    {
        doc.remove("build-dependencies");
    }
    if let Some(package) = doc.get_mut("package").and_then(TomlItem::as_table_mut) {
        package.remove("build");
    }
    std::fs::write(&cargo, doc.to_string())?;

    let mut removed = Vec::new();
    if !dir.join(crate::bridge::MANIFEST).exists() {
        return Ok(removed);
    }
    let src = dir.join("src");
    let keep = port_modules(&src);
    let kept: Vec<String> = keep.iter().cloned().collect();
    std::fs::write(src.join("lib.rs"), stripped_lib_rs(&kept))?;
    for file in GENERATED_FILES {
        let path = dir.join(file);
        if path.is_file() {
            std::fs::remove_file(&path)?;
            removed.push(path);
        }
    }
    for sub in GENERATED_DIRS {
        let path = dir.join(sub);
        if path.is_dir() {
            removed.extend(files_under(&path));
            std::fs::remove_dir_all(&path)?;
        }
    }
    for module in GENERATED_MODULES {
        let path = src.join(format!("{module}.rs"));
        if !keep.contains(module) && path.is_file() {
            std::fs::remove_file(&path)?;
            removed.push(path);
        }
    }
    for entry in std::fs::read_dir(dir)?.flatten() {
        let path = entry.path();
        if path.extension().is_some_and(|e| e == "node") && path.is_file() {
            std::fs::remove_file(&path)?;
            removed.push(path);
        }
    }
    Ok(removed)
}

fn lifted_units_rs(state: &State) -> String {
    let mut out = String::from(
        "//! Written by `rust-anything app lift`: every command is answered in Rust.\n\n\
         use std::process::ExitCode;\n\n\
         use clap::ArgMatches;\n\n",
    );
    for unit in &state.units {
        out += &format!("mod {};\n", front_door::ident(&unit.name));
    }
    out += "\npub fn dispatch(command: &str, matches: &ArgMatches) -> Option<ExitCode> {\n    match command {\n";
    for unit in &state.units {
        let pattern: Vec<String> = unit.commands.iter().map(|c| format!("{c:?}")).collect();
        out += &format!(
            "        {} => Some({}::run(command, matches)),\n",
            pattern.join(" | "),
            front_door::ident(&unit.name)
        );
    }
    out += "        _ => None,\n    }\n}\n";
    out
}

/// The cases `rust/app/tests/app_cases.rs` skips and `app replay` still checks: trycmd compares
/// line order exactly, written files by their exact paths, and a `[..]` only inside one line.
fn trycmd_skips<'a>(
    unordered: &[&'a String],
    renamed: &'a [String],
    across: &'a [String],
) -> Vec<&'a String> {
    let mut skipped: Vec<&String> = unordered.to_vec();
    for case in renamed.iter().chain(across) {
        if !skipped.contains(&case) {
            skipped.push(case);
        }
    }
    skipped
}

/// After `app record` re-records a lifted app, rewrite `rust/app/tests/app_cases.rs` so it skips
/// the cases trycmd cannot check in the new recording, as `app lift` chose them for the old one.
/// Returns how many cases it skips, or `None` when there is no lifted trycmd test to rewrite.
pub fn refresh_cases_test(repo: &Path) -> Result<Option<usize>> {
    if !repo.join(APP_DIR).join(CASES_TEST).is_file() {
        return Ok(None);
    }
    let Some(config) = app::Config::load(repo)? else {
        return Ok(None);
    };
    Ok(update_cases_test(repo, &config, None, &BTreeSet::new())?.map(|(count, _)| count))
}

const CASES_TEST: &str = "tests/app_cases.rs";
const MANUAL_SKIP: &str = "// Hand-added skip.";
const RECORDED_SKIPS: &str = "// Automatically skipped cases: ";

// A refresh can succeed before the new case metadata is saved. Keep skip ownership in
// the test itself so a retry can still remove a skip that the new recording no longer needs.
fn recorded_skips_header(test: &str) -> Option<(BTreeSet<String>, &str)> {
    let (names, body) = test.strip_prefix(RECORDED_SKIPS)?.split_once('\n')?;
    let names: Vec<String> = serde_json::from_str(names).ok()?;
    let count = names.len();
    let unique: BTreeSet<_> = names.into_iter().collect();
    (unique.len() == count).then_some((unique, body))
}

fn recording_skips(repo: &Path, config: &app::Config) -> Result<BTreeSet<String>> {
    let unordered: Vec<_> = config.unordered.keys().collect();
    let renamed = app::cases_with_normalized_file_names(repo, config)?;
    let across = app::cases_normalized_across_lines(repo, config);
    Ok(trycmd_skips(&unordered, &renamed, &across)
        .into_iter()
        .cloned()
        .collect())
}

/// Before a record replaces the cases, remember which skips the old recording required.
/// Those may disappear even if the same case now has stable output.
pub(crate) fn previous_cases_test_skips(
    repo: &Path,
    config: Option<&app::Config>,
) -> BTreeSet<String> {
    let Ok(test) = std::fs::read_to_string(repo.join(APP_DIR).join(CASES_TEST)) else {
        return BTreeSet::new();
    };
    if let Some((skips, _)) = recorded_skips_header(&test) {
        return skips;
    }
    if let Some(config) = config {
        // An invalid old normalizer can be fixed by this recording. If its old skips cannot
        // be inferred, preserve any live skips in the test.
        let mut skips = recording_skips(repo, config).unwrap_or_default();
        let dir = app::cases_dir(repo);
        let meta = app::CaseMeta::load(&dir).ok().flatten();
        // A failed refresh can leave newer case files beside the previous config and metadata.
        // Only trust a file-derived skip if those files still match the completed recording.
        skips.retain(|name| {
            config.unordered.contains_key(name)
                || meta
                    .as_ref()
                    .and_then(|m| m.cases.get(name))
                    .is_some_and(|entry| entry.digest == app::case_digest(&dir, name))
        });
        return skips;
    }
    BTreeSet::new()
}

/// rustfmt can move arguments between lines and omit their trailing comma. Keep string
/// literals intact: whitespace in a filename or an ignore reason is part of the user's edit.
fn cases_test_tokens(code: &str) -> impl Iterator<Item = &str> {
    static TOKEN: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
        Regex::new(r#"//[^\r\n]*|"(?:\\.|[^"\\])*"|\w+|[^\s]"#).expect("valid Rust token pattern")
    });
    TOKEN
        .find_iter(code)
        .filter(|m| m.as_str() != "," || !code[m.end()..].trim_start().starts_with(')'))
        .map(|m| m.as_str())
}

pub(crate) fn save_record_config(
    repo: &Path,
    config: &app::Config,
    previous: Option<&app::Config>,
    previous_skips: &BTreeSet<String>,
) -> Result<Option<String>> {
    let path = app::cases_dir(repo).join(app::CONFIG_FILE);
    let text = serde_json::to_string_pretty(config)? + "\n";
    if !repo.join(APP_DIR).join(CASES_TEST).is_file() {
        std::fs::write(path, text)?;
        return Ok(None);
    }
    let backup = if previous.is_some() {
        Some(std::fs::read(&path)?)
    } else {
        None
    };
    crate::setup::write(&path, &text)?;
    match update_cases_test(repo, config, previous, previous_skips) {
        Ok(refreshed) => Ok(refreshed.map(|(_, note)| note)),
        Err(error) => {
            // A retry must still recognize the test's old name and manual skips.
            let restored = match backup {
                Some(original) => crate::setup::write_bytes(&path, &original),
                None => std::fs::remove_file(&path).map_err(Into::into),
            };
            match restored {
                Ok(()) => Err(error),
                Err(rollback) => Err(error.context(format!(
                    "restoring {} also failed: {rollback}",
                    path.display()
                ))),
            }
        }
    }
}

fn update_cases_test(
    repo: &Path,
    config: &app::Config,
    previous: Option<&app::Config>,
    previous_skips: &BTreeSet<String>,
) -> Result<Option<(usize, String)>> {
    let app_dir = repo.join(APP_DIR);
    let test = app_dir.join(CASES_TEST);
    if !test.is_file() || !State::load(repo)?.lifted {
        return Ok(None);
    }
    let doc: DocumentMut = std::fs::read_to_string(app_dir.join("Cargo.toml"))?.parse()?;
    let binary = doc["package"]["name"]
        .as_str()
        .context("rust/app/Cargo.toml has no package name")?;
    let before = std::fs::read_to_string(&test)?;
    let header = recorded_skips_header(&before);
    let (previous_skips, body) = match &header {
        Some((skips, body)) => (skips, *body),
        None => (previous_skips, before.as_str()),
    };
    let skip = Regex::new(&format!(r#"(?:(?P<manual>{})\s*)?\.\s*skip\s*\(\s*"\.\./app-cases/(?P<name>[\w .-]+)\.toml"\s*,?\s*\)"#, regex::escape(MANUAL_SKIP)))
        .expect("valid skip pattern");
    let mut marked = BTreeSet::new();
    let old: Vec<String> = skip
        .captures_iter(body)
        .map(|c| {
            let name = c["name"].to_owned();
            if c.name("manual").is_some() {
                marked.insert(name.clone());
            }
            name
        })
        .collect();
    let existing: BTreeSet<_> = old.iter().cloned().collect();
    let needed = recording_skips(repo, config)?;
    let cases = app::cases_dir(repo);
    let manual: BTreeSet<_> = existing
        .iter()
        .filter(|name| marked.contains(*name) || !previous_skips.contains(*name))
        .filter(|name| cases.join(format!("{name}.toml")).is_file())
        .cloned()
        .collect();
    let reset = config.effects.as_ref().and_then(|e| e.db_reset.as_deref());
    let old_refs: Vec<_> = old.iter().collect();
    let old_name = previous.map_or(config.name.as_str(), |p| &p.name);
    let old_reset = previous.and_then(|p| p.effects.as_ref()?.db_reset.as_deref());
    let matches_before = |reset| {
        let expected = cases_test_body(old_name, binary, &old_refs, reset, &marked);
        cases_test_tokens(body).eq(cases_test_tokens(&expected))
    };
    let generated = old.len() == existing.len()
        && (matches_before(old_reset) || (previous.is_none() && matches_before(Some(""))));
    let added: Vec<_> = needed.difference(&existing).cloned().collect();
    let list = |names: Vec<String>| {
        if names.is_empty() {
            "none".into()
        } else {
            names
                .into_iter()
                .map(|name| format!("{name}.toml"))
                .collect::<Vec<_>>()
                .join(", ")
        }
    };
    let path = format!("{APP_DIR}/{CASES_TEST}");
    if !generated {
        let guidance = if reset.is_some() {
            "ignore this test and run `app replay` instead: trycmd cannot run --db-reset"
                .to_string()
        } else {
            format!(
                "required trycmd skips: {}",
                list(needed.into_iter().collect())
            )
        };
        return Ok(Some((
            existing.len(),
            format!("{path} was edited and left unchanged; {guidance}"),
        )));
    }
    let skipped: Vec<_> = if reset.is_some() {
        manual.iter().collect()
    } else {
        needed.union(&manual).collect()
    };
    let after = cases_test_rs_with_manual(&config.name, binary, &skipped, reset, &manual);
    if !cases_test_tokens(&before).eq(cases_test_tokens(&after)) {
        crate::setup::write(&test, &after)?;
        front_door::rustfmt(&test);
    }
    let note = if reset.is_some() {
        format!("{path} is ignored: trycmd cannot run --db-reset; run `app replay` for these cases")
    } else {
        format!(
            "{path}: added trycmd skips: {}; kept skips: {}",
            list(added),
            list(
                skipped
                    .iter()
                    .filter(|name| existing.contains(**name))
                    .map(|name| (**name).clone())
                    .collect()
            )
        )
    };
    Ok(Some((skipped.len(), note)))
}

/// `rust/app/tests/app_cases.rs`: the recorded cases through trycmd. A recording that resets
/// state before each case (`--db-reset`) cannot be run that way, since trycmd has no hook to run
/// the reset: the test stays, ignored, and says where the cases are run.
fn cases_test_rs(
    case_bin: &str,
    binary: &str,
    unordered: &[&String],
    reset: Option<&str>,
) -> String {
    cases_test_rs_with_manual(case_bin, binary, unordered, reset, &BTreeSet::new())
}

fn cases_test_rs_with_manual(
    case_bin: &str,
    binary: &str,
    unordered: &[&String],
    reset: Option<&str>,
    manual: &BTreeSet<String>,
) -> String {
    let recorded: Vec<_> = unordered
        .iter()
        .filter(|case| !manual.contains(**case))
        .collect();
    let names = serde_json::to_string(&recorded).expect("case names serialize to JSON");
    let body = cases_test_body(case_bin, binary, unordered, reset, manual);
    format!("{RECORDED_SKIPS}{names}\n{body}")
}

fn cases_test_body(
    case_bin: &str,
    binary: &str,
    unordered: &[&String],
    reset: Option<&str>,
    manual: &BTreeSet<String>,
) -> String {
    let ignore = if reset.is_some() {
        "#[ignore = \"the recording runs a --db-reset command before each case, which trycmd cannot: run `rust-anything app replay <repo> --build <the binary>`\"]\n"
    } else {
        ""
    };
    if reset.is_some() && unordered.is_empty() {
        return format!("#[test]\n{ignore}fn recorded_cases() {{}}\n");
    }
    let skips: String = unordered
        .iter()
        .map(|case| {
            let marker = if manual.contains(*case) {
                format!("\n        {MANUAL_SKIP}")
            } else {
                String::new()
            };
            format!(
                "{marker}\n        .skip({:?})",
                format!("../app-cases/{case}.toml")
            )
        })
        .collect();
    let bin_env = format!("CARGO_BIN_EXE_{binary}");
    format!(
        "#[test]\n{ignore}\
         fn recorded_cases() {{\n    \
             trycmd::TestCases::new()\n        \
                 .register_bin(\n            \
                     {case_bin:?},\n            \
                     std::path::Path::new(env!({bin_env:?})),\n        \
                 )\n        \
                 .case(\"../app-cases/*.toml\"){skips};\n\
         }}\n"
    )
}

fn same_code(a: &str, b: &str) -> bool {
    let squash = |s: &str| s.split_whitespace().collect::<String>();
    squash(a) == squash(b)
}

const MODE_GUARD: &str = "    if std::env::var_os(\"RUST_ANYTHING_MODE\").is_none_or(|mode| mode != \"old\")\n        && let Ok(matches) = cli::command().try_get_matches_from(&argv)\n    {\n";
const BEFORE_MODE_GUARD: &str =
    "    if let Ok(matches) = cli::command().try_get_matches_from(&argv) {\n";

fn generated_mains(state: &State) -> Vec<String> {
    match state.kind {
        AppKind::Cli => vec![
            MAIN_RS.to_string(),
            MAIN_RS.replace(MODE_GUARD, BEFORE_MODE_GUARD),
        ],
        AppKind::Http => http_door::main_rs_versions(),
        AppKind::Library => Vec::new(),
    }
}

fn is_generated_main(code: &str, state: &State) -> bool {
    generated_mains(state).iter().any(|m| same_code(code, m))
}

fn ship_settings(doc: &mut DocumentMut) {
    if doc["package"].get("rust-version").is_none() {
        doc["package"]["rust-version"] = value(crate::MIN_RUST);
    }
    let release = doc["profile"]["release"].or_insert(toml_edit::table());
    if let Some(release) = release.as_table_like_mut() {
        if release.get("lto").is_none() {
            release.insert("lto", value(true));
        }
        if release.get("codegen-units").is_none() {
            release.insert("codegen-units", value(1));
        }
    }
    if let Some(profile) = doc["profile"].as_table_mut() {
        profile.set_implicit(true);
    }
}

fn lift_library(stage_app: &Path, state: &mut State) -> Result<()> {
    state.lifted = true;
    let _ = std::fs::remove_file(stage_app.join(crate::library::CARGO_CONFIG));
    let lib = stage_app.join("src/lib.rs");
    std::fs::write(&lib, crate::library::lib_rs(state, true))?;
    front_door::rustfmt(&lib);
    std::fs::write(
        stage_app.join(STATE_FILE),
        serde_json::to_string_pretty(state)? + "\n",
    )?;
    let cargo = stage_app.join("Cargo.toml");
    let mut doc: DocumentMut = std::fs::read_to_string(&cargo)?.parse()?;
    doc["package"]["description"] = value(format!(
        "`{}` in Rust, lifted by rust-anything from its units' ports",
        state.name
    ));
    ship_settings(&mut doc);
    std::fs::write(&cargo, doc.to_string())?;
    Ok(())
}

fn lift_app(
    stage_app: &Path,
    state: &mut State,
    case_bin: &str,
    unordered: &[&String],
    reset: Option<&str>,
) -> Result<()> {
    if state.kind == AppKind::Library {
        return lift_library(stage_app, state);
    }
    let http = state.kind == AppKind::Http;
    let main = stage_app.join("src/main.rs");
    if is_generated_main(&std::fs::read_to_string(&main)?, state) {
        let lifted = if http {
            http_door::lifted_main_rs()
        } else {
            LIFTED_MAIN.to_string()
        };
        std::fs::write(&main, lifted)?;
    }
    let _ = std::fs::remove_file(stage_app.join("src/original.rs"));
    let cli = stage_app.join("src/cli.rs");
    if let Ok(text) = std::fs::read_to_string(&cli) {
        std::fs::write(
            &cli,
            text.replace(
                "/// Routes argv to a command. Anything this parser rejects runs the original, so it never\n/// has to match every way the original accepts its arguments.\n",
                "/// Parses argv into a command and its arguments.\n",
            ),
        )?;
    }
    state.lifted = true;
    let units = stage_app.join("src/units/mod.rs");
    let routing = if http {
        http_door::units_rs(state, true)
    } else {
        lifted_units_rs(state)
    };
    let names: Vec<String> = state
        .units
        .iter()
        .map(|unit| front_door::ident(&unit.name))
        .collect();
    let unit_names: Vec<&str> = names.iter().map(String::as_str).collect();
    let routing = front_door::keep_helper_modules(
        &std::fs::read_to_string(&units).unwrap_or_default(),
        &routing,
        &unit_names,
    );
    std::fs::write(&units, routing)?;
    front_door::rustfmt(&units);
    std::fs::write(
        stage_app.join(STATE_FILE),
        serde_json::to_string_pretty(state)? + "\n",
    )?;

    let cargo = stage_app.join("Cargo.toml");
    let mut doc: DocumentMut = std::fs::read_to_string(&cargo)?.parse()?;
    let binary = doc["package"]["name"]
        .as_str()
        .context("rust/app/Cargo.toml has no package name")?
        .to_string();
    if let Some(description) = doc["package"].get("description").and_then(|d| d.as_str())
        && description.starts_with("Front door for")
    {
        doc["package"]["description"] = value(format!(
            "`{}` in Rust, lifted by rust-anything from its front door",
            state.name
        ));
    }
    ship_settings(&mut doc);
    if http {
        if let Some(deps) = doc
            .get_mut("dependencies")
            .and_then(TomlItem::as_table_like_mut)
        {
            deps.remove("reqwest");
        }
        std::fs::write(&cargo, doc.to_string())?;
        front_door::rustfmt(&main);
        return Ok(());
    }
    doc["dev-dependencies"]["trycmd"] = value("1");
    std::fs::write(&cargo, doc.to_string())?;
    std::fs::create_dir_all(stage_app.join("tests"))?;
    let test = stage_app.join("tests/app_cases.rs");
    let skips = if reset.is_some() { &[][..] } else { unordered };
    std::fs::write(&test, cases_test_rs(case_bin, &binary, skips, reset))?;
    front_door::rustfmt(&test);
    front_door::rustfmt(&main);
    Ok(())
}

fn command_output(program: &str, args: &[&str]) -> Option<String> {
    let out = Command::new(program).args(args).output().ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

fn target_items(repo: &Path, stage_app: &Path, target_dir: &Path) -> Vec<Item> {
    let decisions = repo.join("rust/DECISIONS.md");
    let Ok(text) = std::fs::read_to_string(&decisions) else {
        return vec![Item::new(
            "targets",
            Mark::Skip,
            "no rust/DECISIONS.md: only the host target was built",
        )];
    };
    let triple = Regex::new(TARGET_TRIPLE).expect("valid regex");
    let targets: BTreeSet<&str> = triple.find_iter(&text).map(|m| m.as_str()).collect();
    if targets.is_empty() {
        return vec![Item::new(
            "targets",
            Mark::Skip,
            "rust/DECISIONS.md names no target triple: only the host target was built",
        )];
    }
    let host = command_output("rustc", &["-vV"]).and_then(|v| {
        v.lines()
            .find_map(|l| l.strip_prefix("host: ").map(str::to_string))
    });
    let installed: Vec<String> = command_output("rustup", &["target", "list", "--installed"])
        .map(|t| t.lines().map(str::to_string).collect())
        .unwrap_or_default();
    targets
        .into_iter()
        .map(|target| {
            let name = format!("target {target}");
            if host.as_deref() == Some(target) {
                return Item::new(name, Mark::Pass, "the host: built and tested above");
            }
            if !installed.iter().any(|t| t == target) {
                return Item::new(
                    name,
                    Mark::Skip,
                    format!("not installed here: `rustup target add {target}` to check it"),
                );
            }
            let out = Command::new("cargo")
                .args(["check", "--quiet", "--target", target, "--manifest-path"])
                .arg(stage_app.join("Cargo.toml"))
                .env("CARGO_TARGET_DIR", target_dir)
                .output();
            match out {
                Ok(o) if o.status.success() => {
                    Item::new(name, Mark::Pass, "`cargo check` passes (not linked)")
                }
                Ok(o) => Item::new(
                    name,
                    Mark::Fail,
                    String::from_utf8_lossy(&o.stderr)
                        .lines()
                        .rev()
                        .take(10)
                        .collect::<Vec<_>>()
                        .into_iter()
                        .rev()
                        .collect::<Vec<_>>()
                        .join("\n"),
                ),
                Err(e) => Item::new(name, Mark::Fail, e.to_string()),
            }
        })
        .collect()
}

/// Folders of the machine itself: a file there belongs to the host, so it cannot be embedded or
/// shipped with the binary.
const HOST_DIRS: [&str; 7] = [
    "/proc/", "/sys/", "/dev/", "/etc/", "/usr/", "/var/", "/run/",
];

fn is_host_path(path: &str) -> bool {
    HOST_DIRS.iter().any(|dir| path.starts_with(dir))
}

fn asset_items(repo: &Path, sources: &[PathBuf]) -> Vec<Item> {
    let reads =
        Regex::new(r#"(?:read_to_string|read|read_dir|read_to_end|File::open|open)\(\s*"([^"]+)""#)
            .expect("valid regex");
    let mut items = Vec::new();
    let mut included = String::new();
    for root in sources {
        for file in files_under(root) {
            if file.extension().is_none_or(|e| e != "rs") {
                continue;
            }
            let text = std::fs::read_to_string(&file).unwrap_or_default();
            for line in text.lines().filter(|l| l.contains("include_")) {
                included += line;
            }
            for c in reads.captures_iter(&text).filter(|c| !is_host_path(&c[1])) {
                items.push(Item::new(
                    "assets",
                    Mark::Warn,
                    format!(
                        "{} reads `{}` at run time from the working directory: embed it with include_str!/include_bytes! or ship it with the binary",
                        file.file_name().unwrap_or_default().to_string_lossy(),
                        &c[1]
                    ),
                ));
            }
        }
    }
    for dir in ASSET_DIRS {
        if repo.join(dir).is_dir() && !included.contains(dir) {
            items.push(Item::new(
                "assets",
                Mark::Warn,
                format!(
                    "the original has `{dir}/` and no include_str!/include_bytes! names it: embed what the app reads, or ship it with the binary"
                ),
            ));
        }
    }
    if items.is_empty() {
        items.push(Item::new(
            "assets",
            Mark::Pass,
            "no file read at run time from a fixed path, and no asset folder in the original",
        ));
    }
    items
}

/// Source with its comments blanked (strings are kept), so a scan reads code and not prose.
fn without_comments(src: &str) -> String {
    blanked(src, true)
}

/// Source with its comments and the text of its string literals blanked: only code is left.
fn code_only(src: &str) -> String {
    blanked(src, false)
}

fn blanked(src: &str, keep_strings: bool) -> String {
    let b = src.as_bytes();
    let mut out = String::with_capacity(src.len());
    let mut i = 0;
    let mut in_str = false;
    while i < b.len() {
        let c = b[i];
        if in_str {
            if c == b'\\' && i + 1 < b.len() {
                let len = src[i + 1..].chars().next().map_or(1, char::len_utf8);
                if keep_strings {
                    out.push_str(&src[i..i + 1 + len]);
                } else if b[i + 1] == b'\n' {
                    out.push('\n');
                }
                i += 1 + len;
                continue;
            }
            if c == b'"' {
                in_str = false;
            }
            let len = src[i..].chars().next().map_or(1, char::len_utf8);
            if keep_strings || c == b'"' || c == b'\n' {
                out.push_str(&src[i..i + len]);
            }
            i += len;
        } else if c == b'/' && b.get(i + 1) == Some(&b'/') {
            while i < b.len() && b[i] != b'\n' {
                i += 1;
            }
        } else if c == b'/' && b.get(i + 1) == Some(&b'*') {
            let mut depth = 1;
            i += 2;
            while i < b.len() && depth > 0 {
                if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
                    depth += 1;
                    i += 2;
                } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
                    depth -= 1;
                    i += 2;
                } else {
                    if b[i] == b'\n' {
                        out.push('\n');
                    }
                    i += 1;
                }
            }
        } else if c == b'\'' {
            // A char literal such as '"' must not open a string.
            let len = char_literal_len(&src[i..]).unwrap_or(1);
            out.push_str(&src[i..i + len]);
            i += len;
        } else if let Some(len) = raw_string_len(src, i) {
            if keep_strings {
                out.push_str(&src[i..i + len]);
            } else {
                out.extend(src[i..i + len].chars().filter(|&c| c == '\n'));
                out.push_str("\"\"");
            }
            i += len;
        } else {
            if c == b'"' {
                in_str = true;
            }
            let len = src[i..].chars().next().map_or(1, char::len_utf8);
            out.push_str(&src[i..i + len]);
            i += len;
        }
    }
    out
}

/// The length of the char literal `s` starts with (`'"'`, `'\''`, `'\u{22}'`); `None` for a
/// lifetime or a label.
fn char_literal_len(s: &str) -> Option<usize> {
    let mut chars = s.char_indices().skip(1);
    let (_, first) = chars.next()?;
    match first {
        '\'' => None,
        '\\' => {
            chars.next()?;
            chars.take(10).find(|&(_, c)| c == '\'').map(|(j, _)| j + 1)
        }
        _ => chars.next().filter(|&(_, c)| c == '\'').map(|(j, _)| j + 1),
    }
}

/// The length of the raw string literal (`r"…"`, `br#"…"#`, `cr"…"`) that starts at byte `i`.
fn raw_string_len(src: &str, i: usize) -> Option<usize> {
    let b = src.as_bytes();
    if !matches!(b[i], b'r' | b'b' | b'c')
        || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'))
    {
        return None;
    }
    let mut j = i + usize::from(b[i] != b'r');
    if b.get(j) != Some(&b'r') {
        return None;
    }
    j += 1;
    let hashes = b[j..].iter().take_while(|&&c| c == b'#').count();
    j += hashes;
    if b.get(j) != Some(&b'"') {
        return None;
    }
    j += 1;
    let close = format!("\"{}", "#".repeat(hashes));
    let end = src[j..]
        .find(&close)
        .map_or(src.len(), |k| j + k + close.len());
    Some(end - i)
}

/// Programs that run other programs or interpret the original's language.
const INTERPRETERS: [&str; 24] = [
    "node",
    "nodejs",
    "python",
    "python3",
    "py",
    "ruby",
    "java",
    "php",
    "dotnet",
    "deno",
    "bun",
    "tsx",
    "ts-node",
    "sh",
    "bash",
    "zsh",
    "dash",
    "cmd",
    "powershell",
    "pwsh",
    "env",
    "npx",
    "npm",
    "perl",
];

/// Crates that embed an interpreter or a VM, or run other processes: a front door built on one
/// answers from the original's language, not from Rust.
const EMBEDDED_RUNTIMES: [&str; 18] = [
    "pyo3",
    "rquickjs",
    "deno_core",
    "deno_runtime",
    "boa_engine",
    "mlua",
    "rlua",
    "rustpython",
    "rustpython-vm",
    "magnus",
    "rutie",
    "v8",
    "wasmtime",
    "wasmer",
    "duct",
    "subprocess",
    "xshell",
    "cmd_lib",
];

/// What the scan of a lifted front door looks for: the recorded command's words and the
/// repository folder name the original; everything else is generic.
struct EscapeScan<'a> {
    repo: &'a Path,
    /// The recorded command's words that name a file (`tcli.py`, `dist/cli.js`).
    entry_words: Vec<String>,
    /// The program names those words give (`tcli`).
    entry_stems: Vec<String>,
}

impl<'a> EscapeScan<'a> {
    fn new(repo: &'a Path, run: &[String]) -> Self {
        let entry_words: Vec<String> = run
            .iter()
            .filter(|w| !w.starts_with('-') && (w.contains('.') || w.contains('/')))
            .filter(|w| repo.join(w).exists())
            .cloned()
            .collect();
        let entry_stems = run
            .iter()
            .filter(|w| !w.starts_with('-'))
            .filter_map(|w| {
                Path::new(w)
                    .file_stem()
                    .map(|s| s.to_string_lossy().to_lowercase())
            })
            .collect();
        EscapeScan {
            repo,
            entry_words,
            entry_stems,
        }
    }

    /// Failures and warnings for the Rust sources and manifests of `crates`: a spawned process,
    /// an embedded interpreter, a path into the original.
    fn scan(&self, crates: &[PathBuf]) -> (Vec<String>, Vec<String>) {
        let spawn = Regex::new(
            r"\bprocess::Command::new\b|\btokio::process\b|\bCommandExt\b|\.exec\(\)|\blibc::(?:exec\w*|system|popen|posix_spawn\w*|fork)\b",
        )
        .expect("valid regex");
        let plain_new = Regex::new(r"\bCommand::new\b").expect("valid regex");
        let import =
            Regex::new(r"(?s)process::(?:Command\b|\{[^}]*\bCommand\b)").expect("valid regex");
        let literal = Regex::new(r#"Command::new\(\s*&?\s*"([^"]*)""#).expect("valid regex");
        let repo_path = self.repo.to_string_lossy().into_owned();
        let mut failures = Vec::new();
        let mut warnings = Vec::new();
        for dir in crates {
            let crate_name = dir
                .file_name()
                .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
            if let Ok(manifest) = std::fs::read_to_string(dir.join("Cargo.toml"))
                && let Ok(doc) = manifest.parse::<DocumentMut>()
            {
                for table in ["dependencies", "build-dependencies", "dev-dependencies"] {
                    for dep in doc
                        .get(table)
                        .and_then(TomlItem::as_table_like)
                        .into_iter()
                        .flat_map(|t| t.iter().map(|(k, _)| k.to_string()))
                    {
                        if EMBEDDED_RUNTIMES.contains(&dep.as_str()) {
                            failures.push(format!(
                                "{crate_name}: depends on `{dep}`, which runs an interpreter or another process: the lifted binary has to answer in Rust"
                            ));
                        }
                    }
                }
            }
            let mut files: Vec<PathBuf> = files_under(&dir.join("src"));
            let build = dir.join("build.rs");
            if build.is_file() {
                files.push(build);
            }
            for file in files {
                if file.extension().is_none_or(|e| e != "rs") {
                    continue;
                }
                let rel = file
                    .strip_prefix(dir)
                    .unwrap_or(&file)
                    .display()
                    .to_string();
                let source = std::fs::read_to_string(&file).unwrap_or_default();
                let text = without_comments(&source);
                let code = code_only(&source);
                let code: Vec<&str> = code.lines().collect();
                // The call, with the lines after it: rustfmt puts a long argument on its own line.
                let all: Vec<&str> = text.lines().collect();
                let mut spawns: Vec<(usize, String)> = Vec::new();
                // `Command::new` is also clap's: it starts a process only where the file brings
                // in the standard library's `Command`.
                let imports_process = import.is_match(&text);
                for (n, line) in all.iter().enumerate() {
                    if spawn.is_match(line) || (imports_process && plain_new.is_match(line)) {
                        spawns.push((n + 1, all[n..all.len().min(n + 3)].join(" ")));
                    }
                }
                if spawns.is_empty() && imports_process {
                    spawns.push((1, "use std::process::Command".to_string()));
                }
                for (n, line) in spawns {
                    let at = format!("{crate_name}/{rel}:{n}");
                    let program = literal.captures(&line).map(|c| c[1].to_string());
                    let base = program.as_deref().map(|p| {
                        Path::new(p)
                            .file_stem()
                            .map_or_else(String::new, |s| s.to_string_lossy().to_lowercase())
                    });
                    let original = base.as_ref().is_some_and(|b| {
                        INTERPRETERS.contains(&b.as_str())
                            || b.starts_with("python")
                            || self.entry_stems.contains(b)
                    });
                    match program {
                        Some(p) if !original => warnings.push(format!(
                            "{at}: starts the process `{p}`: the lifted binary needs it installed (the original hidden replay below ran it)"
                        )),
                        Some(p) => failures.push(format!(
                            "{at}: starts `{p}`, the original's interpreter or program: a front door that shells out to the original is not Rust"
                        )),
                        None => failures.push(format!(
                            "{at}: spawns a process whose program is not a string literal (`{}`), so the lift cannot tell it is not the original",
                            line.trim()
                        )),
                    }
                }
                for (n, line) in text.lines().enumerate() {
                    let at = format!("{crate_name}/{rel}:{}", n + 1);
                    if code.get(n).is_some_and(|l| l.contains("original::")) {
                        failures.push(format!(
                            "{at}: still calls `original::`: answer the case in Rust"
                        ));
                    }
                    if (!repo_path.is_empty() && line.contains(&repo_path))
                        || line.contains("RUST_ANYTHING_REPO")
                        || (line.contains("CARGO_MANIFEST_DIR") && line.contains(".."))
                    {
                        failures.push(format!(
                            "{at}: builds a path into the repository the original lives in: the lifted binary must not read it"
                        ));
                    }
                    for word in &self.entry_words {
                        if line.contains(&format!("\"{word}\""))
                            || line.contains(&format!("/{word}\""))
                        {
                            failures
                                .push(format!("{at}: names the original's entry point `{word}`"));
                        }
                    }
                }
            }
        }
        (failures, warnings)
    }
}

/// The original's files moved out of the way while the lifted binary is replayed, put back when
/// this is dropped (a failed lift, a panic and a finished lift alike).
struct HiddenOriginal {
    moved: Vec<(PathBuf, PathBuf)>,
}

const HIDDEN_SUFFIX: &str = ".rust-anything-hidden";

/// Fails when a top-level file or folder of the repository is still moved away by a lift that was
/// stopped, or by one that is replaying now.
fn refuse_leftover(repo: &Path) -> Result<()> {
    let leftover = std::fs::read_dir(repo)
        .with_context(|| format!("reading {}", repo.display()))?
        .flatten()
        .map(|e| e.path())
        .find(|p| {
            p.file_name()
                .is_some_and(|n| n.to_string_lossy().ends_with(HIDDEN_SUFFIX))
        });
    if let Some(hidden) = leftover {
        let name = hidden.to_string_lossy();
        bail!(
            "{} is left over from an earlier lift that was stopped, or another lift is replaying \
             now: once no lift runs, move it back to {} first",
            hidden.display(),
            &name[..name.len() - HIDDEN_SUFFIX.len()]
        );
    }
    Ok(())
}

impl HiddenOriginal {
    /// Hides what the recorded command runs: each word that names a file or folder of the
    /// repository (outside `rust/`), as the top-level folder or file that holds it.
    fn hide(repo: &Path, run: &[String]) -> Result<Self> {
        let mut tops: Vec<PathBuf> = Vec::new();
        for word in run.iter().filter(|w| !w.starts_with('-')) {
            let Ok(path) = repo.join(word).canonical() else {
                continue;
            };
            let Ok(rel) = path.strip_prefix(repo) else {
                continue;
            };
            let Some(first) = rel.components().next() else {
                continue;
            };
            let name = first.as_os_str().to_string_lossy();
            if name == "rust" || name == ".git" || name.ends_with(HIDDEN_SUFFIX) {
                continue;
            }
            let top = repo.join(first.as_os_str());
            if !tops.contains(&top) {
                tops.push(top);
            }
        }
        refuse_leftover(repo)?;
        let mut hidden = HiddenOriginal { moved: Vec::new() };
        for top in tops {
            let mut target = top.clone().into_os_string();
            target.push(HIDDEN_SUFFIX);
            let target = PathBuf::from(target);
            std::fs::rename(&top, &target).with_context(|| {
                format!("hiding {} to replay without the original", top.display())
            })?;
            hidden.moved.push((top, target));
        }
        Ok(hidden)
    }

    fn names(&self, repo: &Path) -> Vec<String> {
        self.moved
            .iter()
            .map(|(from, _)| {
                from.strip_prefix(repo)
                    .unwrap_or(from)
                    .to_string_lossy()
                    .into_owned()
            })
            .collect()
    }
}

impl Drop for HiddenOriginal {
    fn drop(&mut self) {
        for (from, to) in self.moved.drain(..).rev() {
            if let Err(e) = std::fs::rename(&to, &from) {
                eprintln!(
                    "could not move {} back to {}: {e}; move it back by hand",
                    to.display(),
                    from.display()
                );
            }
        }
    }
}

/// What the recording checks that the lifted `cargo test` (trycmd) does not: it reads command
/// lines, standard streams and written files, and nothing the recording added besides.
fn trycmd_gaps(repo: &Path, config: Option<&app::Config>) -> Vec<&'static str> {
    let mut gaps = Vec::new();
    if let Some(config) = config {
        if config.effects.is_some() {
            gaps.push("the effects (HTTP calls, mail, database)");
        }
        if config.float_tolerance.is_some() || !config.float_files.is_empty() {
            gaps.push("the float tolerance");
        }
        if !config.normalizers.is_empty() || config.normalize.iter().any(|n| n != "key-order") {
            gaps.push("the normalizers (timestamps, ids, patterns)");
        }
    }
    let has = |ext: &str| {
        std::fs::read_dir(app::cases_dir(repo))
            .into_iter()
            .flatten()
            .flatten()
            .any(|e| e.path().extension().is_some_and(|x| x == ext))
    };
    if has("removed") {
        gaps.push("the files a case removes");
    }
    if has(crate::effects::EXT) && !gaps.iter().any(|g| g.starts_with("the effects")) {
        gaps.push("the effects (HTTP calls, mail, database)");
    }
    gaps
}

const JOURNAL: &str = "rust/lift-commit.json";

/// The commit of a lift that passed its checks: the checked copy and the folders it is copied
/// into. It stays on disk until the lift is logged, so a lift that stops part way is finished by
/// the next one instead of leaving the app lifted and a unit still bound.
#[derive(Debug, Serialize, Deserialize)]
struct Journal {
    stage: PathBuf,
    library: bool,
    syncs: Vec<(PathBuf, PathBuf)>,
    /// The files the copy removes, saved before it removes any.
    #[serde(default)]
    removed: Vec<PathBuf>,
    /// The copy is done, and only the build is left: a retry does not copy over what was edited
    /// since.
    #[serde(default)]
    copied: bool,
    /// The recorded cases against the checked copy.
    #[serde(default)]
    replay: Option<ReplayOutcome>,
}

impl Journal {
    fn load(repo: &Path) -> Result<Option<Self>> {
        let path = repo.join(JOURNAL);
        match std::fs::read_to_string(&path) {
            Ok(text) => serde_json::from_str(&text)
                .map(Some)
                .with_context(|| format!("parsing {}", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }

    fn save(&self, repo: &Path) -> Result<()> {
        let path = repo.join(JOURNAL);
        let tmp = path.with_extension("json.tmp");
        std::fs::write(&tmp, serde_json::to_string_pretty(self)? + "\n")
            .with_context(|| format!("writing {}", tmp.display()))?;
        std::fs::rename(&tmp, &path).with_context(|| format!("writing {}", path.display()))
    }

    /// Copies the checked copy over each folder, once: the files it removes are saved first, and
    /// that it is done after.
    fn apply(&mut self, repo: &Path) -> Result<()> {
        if self.copied {
            return Ok(());
        }
        for dir in std::iter::once(&self.stage).chain(self.syncs.iter().map(|(from, _)| from)) {
            ensure!(
                dir.is_dir(),
                "a lift stopped while it copied the lifted crates into rust/, and the checked copy \
                 it copied from ({}) is gone: restore rust/ from version control, delete \
                 {JOURNAL}, and lift again",
                dir.display()
            );
        }
        for (from, to) in &self.syncs {
            for path in files_under(to) {
                let rel = path.strip_prefix(to).unwrap_or(&path);
                if !from.join(rel).exists() && !self.removed.contains(&path) {
                    self.removed.push(path);
                }
            }
        }
        self.save(repo)?;
        for (from, to) in &self.syncs {
            sync(from, to)?;
        }
        self.copied = true;
        self.save(repo)
    }

    /// The commit is logged: the journal goes, then the checked copy.
    fn finish(repo: &Path) {
        let Ok(Some(journal)) = Self::load(repo) else {
            return;
        };
        if let Err(e) = std::fs::remove_file(repo.join(JOURNAL)) {
            eprintln!(
                "warning: {JOURNAL} was not removed ({e}): delete it, then {}",
                journal.stage.display()
            );
            return;
        }
        let _ = std::fs::remove_dir_all(&journal.stage);
    }
}

/// Applies the journal and builds the lifted app; returns the binary.
fn commit(repo: &Path, journal: &mut Journal) -> Result<Option<PathBuf>> {
    journal.apply(repo)?;
    let app_dir = repo.join(APP_DIR);
    let target_dir = app_dir.join("target");
    let binary = if journal.library {
        crate::library::cargo_build_lib(&app_dir, Some(&target_dir))?;
        None
    } else {
        Some(front_door::cargo_build(&app_dir, Some(&target_dir))?)
    };
    Ok(binary)
}

fn relative_to(repo: &Path, paths: &[PathBuf]) -> Vec<String> {
    paths
        .iter()
        .map(|p| {
            p.strip_prefix(repo)
                .unwrap_or(p)
                .to_string_lossy()
                .into_owned()
        })
        .collect()
}

/// Lifts the app and, when it did, appends the lift to the repository's audit log.
pub fn lift(opts: &LiftOptions) -> Result<LiftOutcome> {
    let outcome = lift_app_dir(opts)?;
    if crate::audit::lifted(opts.repo, &outcome) {
        Journal::finish(opts.repo);
    }
    Ok(outcome)
}

fn lift_app_dir(opts: &LiftOptions) -> Result<LiftOutcome> {
    let repo = crate::walk::resolve_root(opts.repo)?;
    let _lock = front_door::WireLock::take(&repo)?;
    if let Some(mut journal) = Journal::load(&repo)? {
        let binary = commit(&repo, &mut journal)?;
        let state = State::load(&repo)?;
        return Ok(LiftOutcome {
            lifted: true,
            blockers: Vec::new(),
            checklist: vec![Item::new(
                "commit",
                Mark::Pass,
                "finished a lift that stopped while it copied the checked crates into rust/",
            )],
            units: state.units.iter().map(|u| u.crate_name.clone()).collect(),
            removed: relative_to(&repo, &journal.removed),
            binary,
            replay: journal.replay,
            stage: None,
        });
    }
    refuse_leftover(&repo)?;
    let mut state = State::load(&repo)?;
    if state.lifted {
        bail!("{} is already lifted", repo.join(APP_DIR).display());
    }
    let library = state.kind == AppKind::Library;
    let config = app::Config::load(&repo)?;
    ensure!(
        library || config.is_some(),
        "no recorded cases: run `app record` first"
    );
    let case_bin = config
        .as_ref()
        .map_or_else(|| state.name.clone(), |c| c.name.clone());
    let key_order = config
        .as_ref()
        .is_some_and(|c| c.normalize.iter().any(|n| n == "key-order"));
    let unordered: Vec<&String> = config
        .as_ref()
        .map(|c| c.unordered.keys().collect())
        .unwrap_or_default();
    // Cases trycmd cannot check: it compares written files by their exact paths.
    let renamed = match &config {
        Some(config) => app::cases_with_normalized_file_names(&repo, config)?,
        None => Vec::new(),
    };
    // Nor output a normalizer rewrote across lines: its `[..]` stands for several lines.
    let across = config
        .as_ref()
        .map(|config| app::cases_normalized_across_lines(&repo, config))
        .unwrap_or_default();
    // trycmd cannot run the command the recording resets state with before each case.
    let reset: Option<String> = config
        .as_ref()
        .and_then(|c| c.effects.as_ref())
        .and_then(|effects| effects.db_reset.clone());
    let skipped = trycmd_skips(&unordered, &renamed, &across);
    let app_dir = repo.join(APP_DIR);
    let rust_dir = repo
        .join("rust")
        .canonical()
        .unwrap_or_else(|_| repo.join("rust"));
    let mut blockers = Vec::new();
    if state.units.is_empty() {
        blockers.push(if state.kind == AppKind::Cli {
            format!(
                "no unit is wired yet: run `rust-anything app wire` first ({})",
                front_door::WHOLE_COMMANDS
            )
        } else {
            "no unit is wired yet: run `rust-anything app wire` first".to_string()
        });
    }
    let mut units = Vec::new();
    for unit in &state.units {
        let dir = app_dir
            .join(&unit.path)
            .canonical()
            .with_context(|| format!("unit crate {} not found", unit.path))?;
        if !dir.starts_with(&rust_dir) {
            blockers.push(format!(
                "{}: lift works on unit crates under rust/, and this one is at {}",
                unit.crate_name,
                dir.display()
            ));
        }
        let glue = app_dir
            .join("src/units")
            .join(format!("{}.rs", front_door::ident(&unit.name)));
        let glue_text = std::fs::read_to_string(&glue).unwrap_or_default();
        if !library && front_door::is_stub(&glue_text) {
            blockers.push(format!(
                "{}: the glue in {} is still the generated stub",
                unit.name,
                glue.display()
            ));
        } else if !library && code_only(&glue_text).contains("original::") {
            blockers.push(format!(
                "{}: the glue in {} still hands cases to the original (`original::`): answer them in Rust, then lift again",
                unit.name,
                glue.display()
            ));
        }
        units.push((unit.clone(), dir));
    }
    let main = std::fs::read_to_string(app_dir.join("src/main.rs")).unwrap_or_default();
    if !library && !is_generated_main(&main, &state) && code_only(&main).contains("original::") {
        blockers.push(
            "src/main.rs was changed and still calls the original: remove `mod original`, `original::report_fallbacks()` and `original::run` by hand, then lift again"
                .to_string(),
        );
    }

    let target_dir = app_dir.join("target");
    let before = if library {
        crate::library::cargo_build_lib(&app_dir, Some(&target_dir))
            .and_then(|()| crate::library::replay(&repo, &state, None))
    } else {
        front_door::cargo_build(&app_dir, Some(&target_dir)).and_then(|exe| {
            app::replay(&ReplayOptions {
                case: None,
                repo: &repo,
                build: Some(&app::shell_quote(&exe.to_string_lossy())),
                timeout_secs: None,
                port: None,
            })
        })
    };
    let replay_before = match &before {
        Ok(r) => Some((r.passed, r.total)),
        Err(_) => None,
    };
    match before {
        Err(e) => blockers.push(format!("the front door does not build: {e:#}")),
        Ok(replay) => {
            if replay.passed != replay.total {
                blockers.push(format!(
                    "{} of {} cases fail against the front door (see {})",
                    replay.total - replay.passed,
                    replay.total,
                    replay.report.display()
                ));
            }
            match &replay.fallback {
                None => blockers.push(
                    "the front door does not report its fallbacks (src/original.rs changed?)"
                        .to_string(),
                ),
                Some(f) if f.cases > 0 => {
                    let mut names = f.names.iter().take(10).cloned().collect::<Vec<_>>();
                    if f.names.len() > 10 {
                        names.push(format!("and {} more", f.names.len() - 10));
                    }
                    blockers.push(if library {
                        format!(
                            "{} of {} exports are still only in the original ({}): wire their units",
                            f.cases,
                            f.total,
                            names.join(", ")
                        )
                    } else {
                        format!(
                            "{} of {} cases still fall back to the original ({}): wire units for them",
                            f.cases,
                            f.total,
                            names.join(", ")
                        )
                    });
                }
                Some(_) => {}
            }
        }
    }
    for (unit, dir) in &units {
        let checks = if dir.join(crate::bridge::MANIFEST).exists() {
            gate::gate(dir, &[])?.checks
        } else {
            let mut checks = gate::rust_checks(dir, &dir.join("target"));
            checks.push(gate::ported_check(dir));
            checks
        };
        let failed: Vec<&str> = checks
            .iter()
            .filter(|c| !c.passed)
            .map(|c| c.name)
            .collect();
        if !failed.is_empty() {
            blockers.push(format!(
                "{}: gate fails ({}): run `rust-anything gate {}`",
                unit.crate_name,
                failed.join(", "),
                crate::app::cli_path(dir)
            ));
        }
    }
    // What the original offers that no case exercises, and nobody waived or attested, blocks too.
    // A read error of the decisions or the bindings is a blocker, not a failure.
    blockers.extend(obligation_blockers(&repo, &crate::app::cli_path(opts.repo)));
    if !blockers.is_empty() {
        return Ok(LiftOutcome::refused(blockers, Vec::new(), None));
    }

    let stage = std::env::temp_dir().join(format!(
        "rust-anything-lift-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    ));
    let stage_rust = stage.join("rust");
    copy_tree(&app_dir, &stage_rust.join("app"))?;
    if app::cases_dir(&repo).is_dir() {
        copy_tree(&app::cases_dir(&repo), &stage_rust.join("app-cases"))?;
    }
    let mut staged_units = Vec::new();
    for (unit, dir) in &units {
        let rel = dir.strip_prefix(&rust_dir).unwrap_or(dir);
        let staged = stage_rust.join(rel);
        copy_tree(dir, &staged)?;
        strip_unit(&staged)?;
        staged_units.push((unit.clone(), dir.clone(), staged));
    }
    let app_canon = app_dir.canonical().unwrap_or_else(|_| app_dir.clone());
    let mut dep_roots: Vec<PathBuf> = units.iter().map(|(_, dir)| dir.clone()).collect();
    dep_roots.push(app_canon.clone());
    let mut staged_deps = Vec::new();
    for dir in path_dependencies(&dep_roots, &rust_dir) {
        if dir == app_canon {
            continue;
        }
        let rel = dir.strip_prefix(&rust_dir).unwrap_or(&dir);
        let staged = stage_rust.join(rel);
        copy_tree(&dir, &staged)?;
        strip_unit(&staged)?;
        staged_deps.push((dir, staged));
    }
    let stage_app = stage_rust.join("app");
    lift_app(
        &stage_app,
        &mut state,
        &case_bin,
        &skipped,
        reset.as_deref(),
    )?;

    let mut checklist = Vec::new();
    if !library {
        let run: Vec<String> = config.as_ref().map(|c| c.run.clone()).unwrap_or_default();
        let mut crates = vec![stage_app.clone()];
        crates.extend(staged_units.iter().map(|(_, _, s)| s.clone()));
        crates.extend(staged_deps.iter().map(|(_, s)| s.clone()));
        let (failures, warnings) = EscapeScan::new(&repo, &run).scan(&crates);
        for line in &failures {
            checklist.push(Item::new("no original", Mark::Fail, line.clone()));
        }
        for line in &warnings {
            checklist.push(Item::new("no original", Mark::Warn, line.clone()));
        }
        if failures.is_empty() && warnings.is_empty() {
            checklist.push(Item::new(
                "no original",
                Mark::Pass,
                "no process is started, no interpreter is embedded and no path leads into the original in rust/app or the units",
            ));
        }
    }
    for (unit, dir, staged) in &staged_units {
        for check in gate::rust_checks(staged, &dir.join("target")) {
            checklist.push(Item::from_check(&unit.crate_name, check));
        }
    }
    for (dir, staged) in &staged_deps {
        let name = dir
            .file_name()
            .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
        for check in gate::rust_checks(staged, &dir.join("target")) {
            checklist.push(Item::from_check(&name, check));
        }
    }
    for check in gate::rust_checks(&stage_app, &target_dir) {
        checklist.push(Item::from_check("rust/app", check));
    }
    let gaps = trycmd_gaps(&repo, config.as_ref());
    checklist.push(Item::new(
        "replay in CI",
        if state.kind != AppKind::Cli
            || key_order
            || !skipped.is_empty()
            || reset.is_some()
            || !gaps.is_empty()
        {
            Mark::Warn
        } else {
            Mark::Pass
        },
        if !gaps.is_empty() && state.kind == AppKind::Cli && !library {
            format!(
                "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which does not check {}{}: run `rust-anything app replay <repo> --build <the binary>` in CI for those",
                gaps.join(", "),
                if across.is_empty() {
                    String::new()
                } else {
                    format!(
                        ", and skips the {} cases a normalizer that spans lines rewrote{}",
                        across.len(),
                        if config.as_ref().is_some_and(|c| c.across_lines.is_none()) {
                            " (this recording did not keep which cases those are, so it skips every case with a `[..]`: record again to skip only them)"
                        } else {
                            ""
                        }
                    )
                }
            )
        } else {
            String::from(if library {
            "the recorded cases ran through the units' bindings, which the lift removes: `cargo test` on the crates is what CI keeps; turn the cases that matter into Rust tests"
        } else if state.kind == AppKind::Http {
            "trycmd runs command lines only: run `rust-anything app replay <repo> --build <the binary>` in CI for the HTTP cases"
        } else if reset.is_some() {
            "the recording resets state with a --db-reset command before each case, which trycmd cannot run: rust/app/tests/app_cases.rs is ignored on `cargo test`, so run `rust-anything app replay <repo> --build <the binary>` in CI"
        } else if !unordered.is_empty() {
            "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which compares line order exactly, so it skips the cases whose order the original's own runs disagreed on: also run `rust-anything app replay` in CI for them"
        } else if !renamed.is_empty() {
            "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which compares written files by their exact names, so it skips the cases that wrote a file named by a normalized value (a time, an id): also run `rust-anything app replay` in CI for them"
        } else if key_order {
            "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which compares JSON as text: also run `rust-anything app replay` in CI for the key-order normalizer"
        } else {
            "rust/app/tests/app_cases.rs runs the recorded cases with trycmd on `cargo test`"
        })
        },
    ));
    checklist.extend(target_items(&repo, &stage_app, &target_dir));
    let mut sources = vec![stage_app.join("src")];
    sources.extend(staged_units.iter().map(|(_, _, s)| s.join("src")));
    checklist.extend(asset_items(&repo, &sources));

    if library {
        let references = crate::library::original_references(&repo, &state);
        checklist.push(if references.is_empty() {
            Item::new(
                "original package",
                Mark::Pass,
                "nothing in the original names the units' bindings or shadows",
            )
        } else {
            Item::new(
                "original package",
                Mark::Warn,
                format!(
                    "these files use the units' bindings or shadows, which the lift removes; the original stays as reference, so point them back at its own modules: {}",
                    references.join(", ")
                ),
            )
        });
        let unchanged = staged_units.iter().all(|(_, dir, staged)| {
            std::fs::read(dir.join("src/port.rs")).ok()
                == std::fs::read(staged.join("src/port.rs")).ok()
        });
        let built = crate::library::cargo_build_lib(&stage_app, Some(&target_dir));
        let (passed, total) = replay_before.unwrap_or((0, 0));
        checklist.push(Item::new(
            "replay",
            if built.is_ok() && unchanged && passed == total {
                Mark::Pass
            } else {
                Mark::Fail
            },
            match built {
                Err(e) => format!("{e:#}"),
                Ok(()) => format!(
                    "{passed}/{total} recorded cases matched through the bindings before the lift; the lift leaves every port.rs as it was, and the whole API builds as one Rust library"
                ),
            },
        ));
    }
    let built = if library {
        Ok(PathBuf::new())
    } else {
        front_door::cargo_build(&stage_app, Some(&target_dir))
    };
    let replay = match built {
        Ok(_) if library => None,
        Err(e) => {
            checklist.push(Item::new("build", Mark::Fail, format!("{e:#}")));
            None
        }
        Ok(exe) => {
            // The lifted binary has no fallback hook, so nothing it reports can say it did not
            // use the original: replay it with the original's entry point moved away, which a
            // front door that still shells out to it cannot survive.
            let run: Vec<String> = config.as_ref().map(|c| c.run.clone()).unwrap_or_default();
            let hidden = HiddenOriginal::hide(&repo, &run)?;
            let names = hidden.names(&repo);
            let replay = app::replay(&ReplayOptions {
                case: None,
                repo: &repo,
                build: Some(&app::shell_quote(&exe.to_string_lossy())),
                timeout_secs: None,
                port: None,
            });
            drop(hidden);
            let replay = replay?;
            let answered = replay.fallback.as_ref().map_or(0, |f| f.cases);
            checklist.push(Item::new(
                "replay",
                if replay.passed != replay.total || answered != 0 {
                    Mark::Fail
                } else if names.is_empty() {
                    Mark::Warn
                } else {
                    Mark::Pass
                },
                format!(
                    "{}/{} cases pass against the lifted binary with the original hidden ({}); {} cases fell back to the original",
                    replay.passed,
                    replay.total,
                    if names.is_empty() {
                        "nothing in the repository was named by the recorded command, so nothing could be hidden".to_string()
                    } else {
                        format!("moved away for the run: {}", names.join(", "))
                    },
                    answered
                ),
            ));
            Some(replay)
        }
    };
    let failed: Vec<String> = checklist
        .iter()
        .filter(|i| i.mark == Mark::Fail)
        .map(|i| format!("{}: {}", i.name, i.detail))
        .collect();
    if !failed.is_empty() {
        let mut outcome = LiftOutcome::refused(failed, checklist, Some(stage));
        outcome.replay = replay;
        return Ok(outcome);
    }

    let mut syncs = vec![(stage_app, app_dir)];
    syncs.extend(
        staged_units
            .into_iter()
            .map(|(_, dir, staged)| (staged, dir)),
    );
    syncs.extend(staged_deps.into_iter().map(|(dir, staged)| (staged, dir)));
    let mut journal = Journal {
        stage,
        library,
        syncs,
        removed: Vec::new(),
        copied: false,
        replay,
    };
    journal.save(&repo)?;
    let binary = commit(&repo, &mut journal)?;
    Ok(LiftOutcome {
        lifted: true,
        blockers: Vec::new(),
        checklist,
        units: state.units.iter().map(|u| u.crate_name.clone()).collect(),
        removed: relative_to(&repo, &journal.removed),
        binary,
        replay: journal.replay,
        stage: None,
    })
}

#[cfg(test)]
mod tests {
    #[test]
    fn re_recording_a_lifted_app_refreshes_its_trycmd_skips() {
        let repo = crate::app::temp_dir("lift-refresh-skips").unwrap();
        let app_dir = repo.join(APP_DIR);
        let cases = repo.join(crate::app::CASES_DIR);
        std::fs::create_dir_all(app_dir.join("tests")).unwrap();
        std::fs::create_dir_all(&cases).unwrap();
        std::fs::write(
            app_dir.join("Cargo.toml"),
            "[package]\nname = \"tool-app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        let state = |lifted: bool| {
            format!(
                "{{\"schema\":\"rust-anything/front-door@1\",\"name\":\"tool\",\"commands\":[],\"units\":[],\"lifted\":{lifted},\"kind\":\"cli\"}}\n"
            )
        };
        let test = app_dir.join("tests/app_cases.rs");
        let stale = cases_test_rs("tool", "tool-app", &[], None);
        std::fs::write(&test, &stale).unwrap();
        // A case the new recording found unordered, which the test written at lift time runs.
        std::fs::write(
            cases.join(crate::app::CONFIG_FILE),
            r#"{"schema":"s","name":"tool","run":["x"],"unordered":{"listing":["stdout"]}}"#,
        )
        .unwrap();

        std::fs::write(app_dir.join(STATE_FILE), state(false)).unwrap();
        assert_eq!(refresh_cases_test(&repo).unwrap(), None, "not lifted yet");
        assert_eq!(std::fs::read_to_string(&test).unwrap(), stale);

        std::fs::write(app_dir.join(STATE_FILE), state(true)).unwrap();
        assert_eq!(refresh_cases_test(&repo).unwrap(), Some(1));
        let refreshed = std::fs::read_to_string(&test).unwrap();
        assert!(
            refreshed.contains(".skip(\"../app-cases/listing.toml\")"),
            "{refreshed}"
        );
        assert!(
            refreshed.contains("env!(\"CARGO_BIN_EXE_tool-app\")"),
            "{refreshed}"
        );
        let previous = app::Config::load(&repo).unwrap().unwrap();
        let previous_skips = previous_cases_test_skips(&repo, Some(&previous));
        let mut next = previous.clone();
        next.unordered.clear();
        next.unordered
            .insert("changed".into(), vec!["stderr".into()]);
        for case in ["listing", "manual", "changed"] {
            std::fs::write(cases.join(format!("{case}.toml")), "").unwrap();
        }
        // rustfmt collapses register_bin and removes its trailing comma. This is also how
        // tests from older versions look, before app record protected hand edits.
        let manual = refreshed.replace(
            ".case(\"../app-cases/*.toml\")",
            ".case(\"../app-cases/*.toml\").skip(\"../app-cases/manual.toml\")",
        );
        std::fs::write(&test, &manual).unwrap();
        let update = |previous, config, skips: &BTreeSet<String>| {
            update_cases_test(&repo, config, Some(previous), skips)
                .unwrap()
                .unwrap()
                .1
        };
        let note = update(&previous, &next, &previous_skips);
        let merged = std::fs::read_to_string(&test).unwrap();
        assert!(
            merged.contains("manual.toml") && merged.contains("changed.toml"),
            "{merged}"
        );
        assert!(!merged.contains("listing.toml"), "{merged}");
        assert!(note.contains("added trycmd skips: changed.toml"), "{note}");
        assert!(note.contains("kept skips: manual.toml"), "{note}");

        let next_skips = recording_skips(&repo, &next).unwrap();
        let mut noisy_manual = next.clone();
        noisy_manual
            .unordered
            .insert("manual".into(), vec!["stdout".into()]);
        update(&next, &noisy_manual, &next_skips);
        update(
            &noisy_manual,
            &next,
            &recording_skips(&repo, &noisy_manual).unwrap(),
        );
        assert!(
            std::fs::read_to_string(&test)
                .unwrap()
                .contains("manual.toml")
        );
        let mut invalid = next.clone();
        invalid.normalizers.insert("target".into(), "[".into());
        assert_eq!(previous_cases_test_skips(&repo, Some(&invalid)), next_skips);
        let mut reset = next.clone();
        reset.effects =
            Some(serde_json::from_value(serde_json::json!({"db_reset":"reset"})).unwrap());
        assert!(update(&next, &reset, &next_skips).contains("is ignored"));
        let ignored = std::fs::read_to_string(&test).unwrap();
        assert!(
            ignored.contains("#[ignore") && ignored.contains("manual.toml"),
            "{ignored}"
        );
        update(&reset, &next, &next_skips);
        let active = std::fs::read_to_string(&test).unwrap();
        assert!(
            !active.contains("#[ignore") && active.contains("manual.toml"),
            "{active}"
        );
        std::fs::remove_file(cases.join("manual.toml")).unwrap();
        update(&next, &next, &next_skips);
        let refreshed = std::fs::read_to_string(&test).unwrap();
        assert!(!refreshed.contains("manual.toml"), "{refreshed}");

        let legacy_reset = cases_test_body("tool", "tool-app", &[], Some(""), &BTreeSet::new());
        std::fs::write(&test, legacy_reset).unwrap();
        assert_eq!(refresh_cases_test(&repo).unwrap(), Some(1));
        let restored = std::fs::read_to_string(&test).unwrap();
        assert!(!restored.contains("#[ignore"), "{restored}");
        assert!(restored.contains("listing.toml"), "{restored}");

        let changed = ".skip(\"../app-cases/changed.toml\")";
        for custom in [
            refreshed.replace(".case(", ".env(\"TZ\", \"UTC\").case("),
            refreshed.replace("app-cases/*.toml", "app-cases/ *.toml"),
            refreshed.replacen(RECORDED_SKIPS, &format!("{RECORDED_SKIPS}?"), 1),
            refreshed.replace(r#"["changed"]"#, r#"["changed","changed"]"#),
            refreshed.replace(changed, &format!("{changed}{changed}")),
            format!("#[cfg(unix)]\n{refreshed}"),
            merged
                .replace(
                    "// Hand-added skip.\n        .skip(",
                    "// Hand-added skip. .skip(",
                )
                .replace(");\n", ")\n;\n"),
        ] {
            std::fs::write(&test, &custom).unwrap();
            let note = update(&next, &previous, &next_skips);
            assert!(
                note.contains("left unchanged") && note.contains("listing.toml"),
                "{note}"
            );
            assert_eq!(std::fs::read_to_string(&test).unwrap(), custom);
        }
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn a_failed_lifted_test_refresh_restores_the_exact_config() {
        let repo = crate::app::temp_dir("lift-refresh-rollback").unwrap();
        let dir = repo.join(APP_DIR);
        std::fs::create_dir_all(dir.join("tests")).unwrap();
        std::fs::create_dir_all(app::cases_dir(&repo)).unwrap();
        let path = app::cases_dir(&repo).join(app::CONFIG_FILE);
        let test = dir.join(CASES_TEST);
        let original = cases_test_rs("old", "tool-app", &[], None);
        std::fs::write(&test, &original).unwrap();
        std::fs::write(
            dir.join(STATE_FILE),
            r#"{"schema":"s","name":"old","commands":[],"units":[],"lifted":true}"#,
        )
        .unwrap();
        let old = app::Config::new("old");
        let new = app::Config::new("new");
        let skips = BTreeSet::new();
        // With no Cargo.toml, the refresh fails after the new config was written.
        assert!(save_record_config(&repo, &new, None, &skips).is_err());
        assert!(!path.exists());
        let bytes = "{ \"schema\":\"s\", \"name\":\"old\", \"run\":[], \"extra\":true }\r\n";
        std::fs::write(&path, bytes).unwrap();
        assert!(save_record_config(&repo, &new, Some(&old), &skips).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), bytes);
        assert_eq!(std::fs::read_to_string(&test).unwrap(), original);

        // A config path that cannot be replaced must not change the binary registered in
        // an otherwise writable test.
        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"tool-app\"\n").unwrap();
        std::fs::remove_file(&path).unwrap();
        std::fs::create_dir(&path).unwrap();
        assert!(save_record_config(&repo, &new, None, &skips).is_err());
        assert_eq!(std::fs::read_to_string(&test).unwrap(), original);
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn retry_after_a_failed_refresh_preserves_a_hand_added_skip() {
        let repo = app::temp_dir("lift-retry-skips").unwrap();
        let dir = repo.join(APP_DIR);
        let cases = app::cases_dir(&repo);
        std::fs::create_dir_all(dir.join("tests")).unwrap();
        std::fs::create_dir_all(&cases).unwrap();
        let mut old = app::Config::new("tool");
        old.normalizers.insert("trace".into(), "first\nlast".into());
        std::fs::write(
            cases.join(app::CONFIG_FILE),
            serde_json::to_vec(&old).unwrap(),
        )
        .unwrap();
        std::fs::write(
            dir.join(STATE_FILE),
            r#"{"schema":"s","name":"tool","commands":[],"units":[],"lifted":true}"#,
        )
        .unwrap();
        let test = dir.join(CASES_TEST);
        let manual = "manual".to_string();
        let automatic = "automatic".to_string();
        // Tests written before recording-owned skips had an explicit list.
        let original = cases_test_body(
            "tool",
            "tool-app",
            &[&automatic, &manual],
            None,
            &BTreeSet::new(),
        );
        std::fs::write(&test, &original).unwrap();
        let mut meta = app::CaseMeta::default();
        for (name, stdout) in [(&automatic, "[..]\n"), (&manual, "stable\n")] {
            std::fs::write(cases.join(format!("{name}.toml")), "bin.name = \"tool\"\n").unwrap();
            std::fs::write(cases.join(format!("{name}.stdout")), stdout).unwrap();
            meta.cases.insert(
                name.clone(),
                app::CaseEntry {
                    digest: app::case_digest(&cases, name),
                    wild: vec![],
                },
            );
        }
        meta.save(&cases).unwrap();
        let previous = previous_cases_test_skips(&repo, Some(&old));
        assert_eq!(previous, BTreeSet::from([automatic.clone()]));

        // The recorder has already written new stdout when refreshing without Cargo.toml fails.
        std::fs::write(cases.join("manual.stdout"), "[..]\n").unwrap();
        assert!(save_record_config(&repo, &old, Some(&old), &previous).is_err());
        assert_eq!(std::fs::read_to_string(&test).unwrap(), original);

        let retry = previous_cases_test_skips(&repo, Some(&old));
        for name in [&automatic, &manual] {
            std::fs::write(cases.join(format!("{name}.stdout")), "stable\n").unwrap();
        }
        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"tool-app\"\n").unwrap();
        save_record_config(&repo, &old, Some(&old), &retry).unwrap();
        let refreshed = std::fs::read_to_string(&test).unwrap();
        assert!(
            refreshed.contains("manual.toml") && refreshed.contains(MANUAL_SKIP),
            "{refreshed}"
        );
        assert!(!refreshed.contains("automatic.toml"), "{refreshed}");
        // Legacy recordings have no digest to distinguish an unmarked skip from a hand edit.
        std::fs::remove_file(cases.join(app::META_FILE)).unwrap();
        std::fs::write(&test, &original).unwrap();
        std::fs::write(cases.join("manual.stdout"), "[..]\n").unwrap();
        assert!(previous_cases_test_skips(&repo, Some(&old)).is_empty());
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn refreshed_skips_survive_stale_metadata_without_becoming_manual() {
        let repo = app::temp_dir("lift-retry-after-refresh").unwrap();
        let dir = repo.join(APP_DIR);
        let cases = app::cases_dir(&repo);
        std::fs::create_dir_all(dir.join("tests")).unwrap();
        std::fs::create_dir_all(&cases).unwrap();
        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"tool-app\"\n").unwrap();
        std::fs::write(
            dir.join(STATE_FILE),
            r#"{"schema":"s","name":"tool","commands":[],"units":[],"lifted":true}"#,
        )
        .unwrap();
        let test = dir.join(CASES_TEST);
        let manual = ".skip(\"../app-cases/manual.toml\")";
        let automatic = ".skip(\"../app-cases/automatic.toml\")";
        let copied = ".skip(\"../app-cases/copied.toml\")";
        let original = cases_test_rs("tool", "tool-app", &[], None);
        let glob = ".case(\"../app-cases/*.toml\")";
        std::fs::write(&test, original.replace(glob, &format!("{glob}{manual}"))).unwrap();
        let mut config = app::Config::new("tool");
        config
            .normalizers
            .insert("trace".into(), "first\nlast".into());
        for name in ["manual", "automatic", "copied"] {
            std::fs::write(cases.join(format!("{name}.toml")), "bin.name = \"tool\"\n").unwrap();
        }
        std::fs::write(cases.join("automatic.stdout"), "stable\n").unwrap();
        let mut meta = app::CaseMeta::default();
        meta.cases.insert(
            "automatic".into(),
            app::CaseEntry {
                digest: app::case_digest(&cases, "automatic"),
                wild: vec![],
            },
        );
        meta.save(&cases).unwrap();
        std::fs::write(
            cases.join(app::CONFIG_FILE),
            serde_json::to_vec(&config).unwrap(),
        )
        .unwrap();
        for direct in [false, true] {
            let previous = previous_cases_test_skips(&repo, Some(&config));
            std::fs::write(cases.join("automatic.stdout"), "[..]\n").unwrap();
            save_record_config(&repo, &config, Some(&config), &previous).unwrap();
            let refreshed = std::fs::read_to_string(&test).unwrap();
            assert!(refreshed.contains(automatic), "{refreshed}");
            assert!(refreshed.contains(manual), "{refreshed}");
            // Snapshot or metadata publication failed after the test was refreshed. On a retry
            // the sidecar still describes the old stable stdout. A copied skip is a hand edit.
            if direct {
                std::fs::write(
                    &test,
                    refreshed.replace(automatic, &format!("{automatic}{copied}")),
                )
                .unwrap();
            }
            let previous = previous_cases_test_skips(&repo, Some(&config));
            std::fs::write(cases.join("automatic.stdout"), "stable\n").unwrap();
            if direct {
                refresh_cases_test(&repo).unwrap();
            } else {
                save_record_config(&repo, &config, Some(&config), &previous).unwrap();
            }
            let retried = std::fs::read_to_string(&test).unwrap();
            assert!(!retried.contains(automatic), "{retried}");
            assert!(retried.contains(manual), "{retried}");
            if direct {
                assert!(retried.contains(copied), "{retried}");
            }
        }
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn a_recording_that_resets_state_gets_an_ignored_cases_test() {
        let slow = "slow".to_string();
        let plain = cases_test_rs("tool", "tool-app", &[&slow], None);
        assert!(plain.contains("trycmd::TestCases::new()"), "{plain}");
        assert!(
            plain.contains(".skip(\"../app-cases/slow.toml\")"),
            "{plain}"
        );
        assert!(!plain.contains("#[ignore"), "{plain}");
        // trycmd has no hook to run the reset command, so no case could pass: the test stays,
        // ignored, and names where the cases run.
        let reset = cases_test_rs("tool", "tool-app", &[], Some("sh fixtures/setup.sh"));
        assert!(reset.contains("#[ignore ="), "{reset}");
        assert!(reset.contains("rust-anything app replay"), "{reset}");
        assert!(!reset.contains("trycmd::TestCases"), "{reset}");
    }

    #[test]
    fn cases_a_normalizer_rewrote_across_lines_stay_out_of_trycmd() {
        let repo = crate::app::temp_dir("lift-across").unwrap();
        let cases = crate::app::cases_dir(&repo);
        std::fs::create_dir_all(&cases).unwrap();
        for (file, text) in [
            ("crash.toml", "bin.name = \"tool\"\n"),
            ("crash.stderr", "[..]ValueError: bad\n"),
            ("plain.toml", "bin.name = \"tool\"\n"),
            ("plain.stdout", "42\n"),
        ] {
            std::fs::write(cases.join(file), text).unwrap();
        }
        let config: crate::app::Config = serde_json::from_value(serde_json::json!({
            "schema": crate::app::SCHEMA,
            "name": "tool",
            "run": ["python3", "tool.py"],
            "normalizers": {"traceback": "Traceback \\(most recent call last\\):\n(?:  [^\n]*\n)*"},
        }))
        .unwrap();
        let across = crate::app::cases_normalized_across_lines(&repo, &config);
        std::fs::remove_dir_all(&repo).unwrap();
        let slow = "slow".to_string();
        let skipped = super::trycmd_skips(&[&slow], &[], &across);
        let test = cases_test_rs("tool", "tool-app", &skipped, None);
        assert!(
            test.contains(".skip(\"../app-cases/crash.toml\")"),
            "{test}"
        );
        assert!(test.contains(".skip(\"../app-cases/slow.toml\")"), "{test}");
        assert!(!test.contains("plain.toml"), "{test}");
    }

    #[test]
    fn a_read_of_a_system_path_is_not_an_asset() {
        let base =
            std::env::temp_dir().join(format!("rust-anything-assets-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let src = base.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("main.rs"),
            "fn main() {\n    let _ = std::fs::read_to_string(\"/proc/self/status\");\n    \
             let _ = std::fs::read_to_string(\"/etc/hostname\");\n    \
             let _ = std::fs::read_to_string(\"templates/page.html\");\n}\n",
        )
        .unwrap();
        let items = asset_items(&base, &[src]);
        let warned: Vec<&str> = items.iter().map(|i| i.detail.as_str()).collect();
        // Only the file next to the app is an asset: the host's files are not shipped.
        assert_eq!(warned.len(), 1, "{warned:?}");
        assert!(warned[0].contains("templates/page.html"), "{warned:?}");
        std::fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn stripped_lib_rs_lists_modules_as_rustfmt_orders_them() {
        assert_eq!(
            super::stripped_lib_rs(&["utf16".into(), "js".into()]),
            "pub mod js;\npub mod port;\npub mod utf16;\n"
        );
    }

    #[test]
    fn path_dependencies_are_found_transitively_under_rust() {
        let root = crate::app::temp_dir("lift-deps").unwrap();
        let rust = root.join("rust");
        let write = |name: &str, deps: &str| {
            let dir = rust.join(name);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("Cargo.toml"),
                format!("[package]\nname = \"{name}\"\n\n[dependencies]\n{deps}"),
            )
            .unwrap();
        };
        std::fs::create_dir_all(root.join("outside")).unwrap();
        write(
            "unit-rs",
            "shared = { path = \"../shared\" }\nother = { path = \"../../outside\" }\nserde = \"1\"\n",
        );
        write("shared", "leaf = { path = \"../leaf\" }\n");
        write("leaf", "");
        let rust = rust.canonical().unwrap();
        let found = super::path_dependencies(&[rust.join("unit-rs")], &rust);
        std::fs::remove_dir_all(&root).unwrap();
        assert_eq!(found, [rust.join("leaf"), rust.join("shared")]);
    }

    use super::*;

    fn crate_with(tag: &str, glue: &str, deps: &str) -> (PathBuf, PathBuf) {
        let root = crate::app::temp_dir(tag).unwrap();
        let dir = root.join("rust/app");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!("[package]\nname = \"app\"\n\n[dependencies]\n{deps}"),
        )
        .unwrap();
        std::fs::write(dir.join("src/glue.rs"), glue).unwrap();
        (root, dir)
    }

    #[test]
    fn a_glue_that_runs_the_original_is_not_pure() {
        let repo_dir = crate::app::temp_dir("lift-scan-repo").unwrap();
        std::fs::write(repo_dir.join("tcli.py"), "").unwrap();
        let repo = repo_dir.as_path();
        let inside = format!("fn f() {{ let _ = \"{}/data\"; }}", repo.display());
        let run = vec!["python3".to_string(), "tcli.py".to_string()];
        for (glue, what) in [
            (
                "fn f() { std::process::Command::new(\"python3\").arg(\"x\").status(); }",
                "starts `python3`",
            ),
            (
                "fn f(p: &str) { Command::new(p).status(); }\nuse std::process::Command;",
                "not a string literal",
            ),
            (
                "use std::process::Command;\nfn f() {\n    Command::new(\n        \"node\",\n    );\n}",
                "starts `node`",
            ),
            (
                "use std::process::{Child, Command};",
                "not a string literal",
            ),
            (&inside, "builds a path into the repository"),
            (
                "fn f() { let _ = \"tcli.py\"; }",
                "names the original's entry point",
            ),
            (
                "fn f() { crate::original::run(); }",
                "still calls `original::`",
            ),
        ] {
            let (root, dir) = crate_with("lift-scan", glue, "");
            let (failures, _) = EscapeScan::new(repo, &run).scan(&[dir]);
            std::fs::remove_dir_all(&root).unwrap();
            assert!(
                failures.iter().any(|f| f.contains(what)),
                "{glue}: {failures:?}"
            );
        }
        std::fs::remove_dir_all(&repo_dir).unwrap();
        let repo = Path::new("/nowhere/repo");
        // An embedded interpreter is refused through the manifest alone.
        let (root, dir) = crate_with("lift-scan-dep", "", "pyo3 = \"0.22\"\n");
        let (failures, _) = EscapeScan::new(repo, &run).scan(&[dir]);
        std::fs::remove_dir_all(&root).unwrap();
        assert!(failures.iter().any(|f| f.contains("pyo3")), "{failures:?}");
    }

    #[test]
    fn a_comment_or_an_unrelated_tool_is_not_an_escape() {
        let repo = Path::new("/nowhere/repo");
        let run = vec!["python3".to_string(), "tcli.py".to_string()];
        let glue = "// the old glue called `original::run` and Command::new(\"python3\")\n\
                    /* tcli.py */\nfn f() { let _ = std::process::Command::new(\"git\").status(); }\n\
                    fn g() -> &'static str { \"http://example.test//not-a-comment\" }\n\
                    const HELP: &str = \"see original::run\";\n";
        let (root, dir) = crate_with("lift-scan-ok", glue, "serde = \"1\"\n");
        let (failures, warnings) = EscapeScan::new(repo, &run).scan(&[dir]);
        std::fs::remove_dir_all(&root).unwrap();
        assert!(failures.is_empty(), "{failures:?}");
        // A program that is not the original's is shown, not refused: the hidden replay decides.
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("`git`"), "{warnings:?}");
    }

    #[test]
    fn the_checks_trycmd_does_not_run_are_named() {
        let repo = crate::app::temp_dir("lift-gaps").unwrap();
        let config: app::Config = serde_json::from_str(
            r#"{"schema":"s","name":"t","run":["x"],"normalizers":{"id":"\\d+"},"effects":{}}"#,
        )
        .unwrap();
        let none = trycmd_gaps(&repo, None);
        assert!(none.is_empty(), "{none:?}");
        std::fs::create_dir_all(app::cases_dir(&repo)).unwrap();
        std::fs::write(app::cases_dir(&repo).join("a.removed"), "x\n").unwrap();
        let gaps = trycmd_gaps(&repo, Some(&config));
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(
            gaps,
            [
                "the effects (HTTP calls, mail, database)",
                "the normalizers (timestamps, ids, patterns)",
                "the files a case removes"
            ]
        );
    }

    #[test]
    fn the_original_is_moved_away_and_always_put_back() {
        let repo = crate::app::temp_dir("lift-hide").unwrap();
        std::fs::write(repo.join("tcli.py"), "print(1)").unwrap();
        std::fs::create_dir_all(repo.join("rust/app")).unwrap();
        std::fs::create_dir_all(repo.join("lib")).unwrap();
        std::fs::write(repo.join("lib/a.js"), "").unwrap();
        let run: Vec<String> = ["node", "lib/a.js", "tcli.py", "--flag", "rust/app"]
            .map(String::from)
            .to_vec();
        let repo = repo.canonical().unwrap();
        {
            let hidden = HiddenOriginal::hide(&repo, &run).unwrap();
            assert_eq!(hidden.names(&repo), ["lib", "tcli.py"]);
            assert!(!repo.join("tcli.py").exists());
            assert!(!repo.join("lib").exists());
            assert!(repo.join("rust/app").is_dir());
        }
        assert!(repo.join("tcli.py").is_file());
        assert!(repo.join("lib/a.js").is_file());
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn a_stopped_lift_is_refused_by_the_next() {
        let repo = crate::app::temp_dir("lift-stopped").unwrap();
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/cli.js"), "console.log(1)").unwrap();
        let repo = repo.canonical().unwrap();
        let run: Vec<String> = ["node", "src/cli.js"].map(String::from).to_vec();
        std::mem::forget(HiddenOriginal::hide(&repo, &run).unwrap());
        assert!(!repo.join("src").exists());

        let err = HiddenOriginal::hide(&repo, &run)
            .err()
            .map(|e| e.to_string());
        let refused = refuse_leftover(&repo).err().map(|e| e.to_string());
        std::fs::rename(repo.join("src.rust-anything-hidden"), repo.join("src")).unwrap();
        std::fs::remove_dir_all(&repo).unwrap();
        let err = err.expect("the leftover must be refused");
        assert!(err.contains("src.rust-anything-hidden"), "{err}");
        assert!(err.contains("left over"), "{err}");
        assert_eq!(refused.as_deref(), Some(err.as_str()));
    }

    #[test]
    fn a_second_lift_does_not_replay_while_the_first_has_the_original_hidden() {
        let repo = crate::app::temp_dir("lift-two").unwrap();
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/cli.js"), "console.log(1)").unwrap();
        let repo = repo.canonical().unwrap();
        let run: Vec<String> = ["node", "src/cli.js"].map(String::from).to_vec();
        let first = HiddenOriginal::hide(&repo, &run).unwrap();
        let second = HiddenOriginal::hide(&repo, &run);
        assert!(second.is_err(), "the second lift must not replay");
        drop(second);
        drop(first);
        assert!(repo.join("src/cli.js").is_file());
        assert!(!repo.join("src.rust-anything-hidden").exists());
        std::fs::remove_dir_all(&repo).unwrap();
    }

    fn journal_fixture(tag: &str) -> (PathBuf, PathBuf, Journal) {
        let repo = crate::app::temp_dir(tag).unwrap();
        let app_dir = repo.join(APP_DIR);
        let unit = repo.join("rust/words-rs");
        let stage = repo.join("stage");
        let stage_app = stage.join("app");
        let stage_unit = stage.join("words-rs");
        for d in [&app_dir, &unit, &stage_app, &stage_unit] {
            std::fs::create_dir_all(d.join("src")).unwrap();
        }
        let state = |lifted: bool| {
            format!(
                "{{\"schema\":\"rust-anything/front-door@1\",\"name\":\"t\",\"commands\":[],\"units\":[],\"lifted\":{lifted},\"kind\":\"cli\"}}\n"
            )
        };
        std::fs::write(app_dir.join(STATE_FILE), state(false)).unwrap();
        std::fs::write(stage_app.join(STATE_FILE), state(true)).unwrap();
        std::fs::write(app_dir.join("src/fallback.rs"), "").unwrap();
        std::fs::write(stage_app.join("src/main.rs"), "fn main() {}\n").unwrap();
        std::fs::write(unit.join("index.cjs"), "binding").unwrap();
        std::fs::write(unit.join("src/port.rs"), "").unwrap();
        std::fs::write(stage_unit.join("src/port.rs"), "").unwrap();
        let journal = Journal {
            stage,
            library: false,
            syncs: vec![(stage_app, app_dir), (stage_unit, unit.clone())],
            removed: Vec::new(),
            copied: false,
            replay: None,
        };
        journal.save(&repo).unwrap();
        (repo, unit, journal)
    }

    #[test]
    fn a_commit_stopped_part_way_is_finished_by_the_next_lift() {
        let (repo, unit, mut journal) = journal_fixture("lift-commit");
        let app_dir = repo.join(APP_DIR);
        let saved_unit = repo.join("unit-aside");
        std::fs::rename(&unit, &saved_unit).unwrap();
        std::fs::write(&unit, "not a folder").unwrap();
        let first = journal.apply(&repo);
        std::fs::remove_file(&unit).unwrap();
        std::fs::rename(&saved_unit, &unit).unwrap();
        assert!(first.is_err());
        assert!(State::load(&repo).unwrap().lifted, "rust/app was copied");
        assert!(!app_dir.join("src/fallback.rs").exists());
        let mut pending = Journal::load(&repo)
            .unwrap()
            .expect("the commit is still pending");
        assert_eq!(pending.syncs, journal.syncs);
        assert!(!pending.copied);

        pending.apply(&repo).unwrap();
        assert_eq!(
            pending.removed,
            [app_dir.join("src/fallback.rs"), unit.join("index.cjs")]
        );
        assert!(Journal::load(&repo).unwrap().unwrap().copied);
        Journal::finish(&repo);
        assert!(Journal::load(&repo).unwrap().is_none());
        assert!(
            !repo.join("stage").exists(),
            "the checked copy goes once the commit is done"
        );
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn a_missing_staged_crate_stops_the_commit_before_a_file_goes() {
        let (repo, unit, mut journal) = journal_fixture("lift-commit-unit-gone");
        std::fs::remove_dir_all(repo.join("stage/words-rs")).unwrap();
        let err = journal.apply(&repo).unwrap_err().to_string();
        let kept = unit.join("index.cjs").is_file();
        let app_kept = repo.join(APP_DIR).join("src/fallback.rs").is_file();
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(err.contains("words-rs"), "{err}");
        assert!(kept && app_kept, "a live file was removed");
    }

    #[test]
    fn a_retried_commit_builds_what_is_there_without_copying_again() {
        let (repo, _unit, mut journal) = journal_fixture("lift-commit-copied");
        journal.apply(&repo).unwrap();
        let main = repo.join(APP_DIR).join("src/main.rs");
        std::fs::write(&main, "fn main() {} // fixed by hand\n").unwrap();
        let mut pending = Journal::load(&repo).unwrap().unwrap();
        pending.apply(&repo).unwrap();
        let main_now = std::fs::read_to_string(&main).unwrap();
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(main_now, "fn main() {} // fixed by hand\n");
    }

    #[test]
    fn a_lift_the_audit_log_missed_stays_pending() {
        let repo = crate::app::temp_dir("lift-audit").unwrap();
        let app_dir = repo.join(APP_DIR);
        std::fs::create_dir_all(app_dir.join("src")).unwrap();
        std::fs::write(
            app_dir.join("Cargo.toml"),
            "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
        )
        .unwrap();
        std::fs::write(app_dir.join("src/lib.rs"), "").unwrap();
        std::fs::write(
            app_dir.join(STATE_FILE),
            "{\"schema\":\"rust-anything/front-door@1\",\"name\":\"t\",\"commands\":[],\"units\":[],\"lifted\":true,\"kind\":\"library\"}\n",
        )
        .unwrap();
        std::fs::create_dir_all(repo.join(crate::audit::FILE)).unwrap();
        let journal = Journal {
            stage: repo.join("stage"),
            library: true,
            syncs: Vec::new(),
            removed: Vec::new(),
            copied: true,
            replay: None,
        };
        journal.save(&repo).unwrap();
        let outcome = lift(&LiftOptions { repo: &repo }).unwrap();
        let pending = Journal::load(&repo).unwrap();
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(outcome.lifted);
        assert!(pending.is_some(), "the journal went with no audit entry");
    }

    #[test]
    fn a_commit_whose_copy_is_gone_says_how_to_recover() {
        let repo = crate::app::temp_dir("lift-commit-gone").unwrap();
        std::fs::create_dir_all(repo.join("rust")).unwrap();
        let journal = Journal {
            stage: repo.join("no-such-stage"),
            library: false,
            syncs: Vec::new(),
            removed: Vec::new(),
            copied: false,
            replay: None,
        };
        journal.save(&repo).unwrap();
        let err = Journal::load(&repo)
            .unwrap()
            .unwrap()
            .apply(&repo)
            .unwrap_err()
            .to_string();
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(err.contains("no-such-stage"), "{err}");
        assert!(err.contains(JOURNAL), "{err}");
    }

    #[test]
    fn a_quote_char_literal_or_a_raw_string_does_not_hide_code() {
        for src in [
            "fn f() -> char { '\\\"' } // calls original::run\nfn g() {}\n",
            "fn f() -> u8 { b'\"' } // calls original::run\n",
            "fn f() -> &'static str { r\"C:\\\" } // calls original::run\n",
            "fn f() -> &'static str { r#\"say \"hi\"\"# } // calls original::run\n",
            "fn f() -> &'static [u8] { br##\"a \"# b\"## } // calls original::run\n",
        ] {
            let out = without_comments(src);
            assert!(!out.contains("original::"), "{src}: {out:?}");
        }
        for src in [
            "fn f() -> char { '\\'' } fn g() { original::run() }\n",
            "fn f<'a>(x: &'a str) -> &'a str { x } fn g() { original::run() }\n",
            "fn f() -> char { '\\u{22}' } fn g() { original::run() }\n",
            "fn f() -> &'static str { r#\"// not a comment\"# } fn g() { original::run() }\n",
            "fn r#type() -> char { 'é' } fn g() { original::run() }\n",
        ] {
            let out = without_comments(src);
            assert!(out.contains("original::run"), "{src}: {out:?}");
            assert!(code_only(src).contains("original::run"), "{src}");
        }
        for src in [
            "const HELP: &str = r#\"Example: \" // original::run\"#;\n",
            "const HELP: &str = \"see original::run\";\n",
        ] {
            let out = code_only(src);
            assert!(!out.contains("original::"), "{src}: {out:?}");
            assert!(without_comments(src).contains("original::run"), "{src}");
        }
        let src = "const A: &str = \"a\\\nb\";\nfn g() { original::run() }\n";
        let out = code_only(src);
        assert_eq!(out.lines().count(), src.lines().count(), "{out:?}");
        assert!(
            out.lines()
                .nth(2)
                .is_some_and(|l| l.contains("original::run")),
            "{out:?}"
        );
    }

    #[test]
    fn port_modules_follow_crate_paths() {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-lift-mods-{}", std::process::id()));
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("port.rs"),
            "use crate::utf16::len;\nuse crate::{helpers, Thing};\n",
        )
        .unwrap();
        std::fs::write(src.join("utf16.rs"), "").unwrap();
        std::fs::write(src.join("helpers.rs"), "use super::deep;\n").unwrap();
        std::fs::write(src.join("deep.rs"), "").unwrap();
        std::fs::write(src.join("wire.rs"), "").unwrap();
        let keep: Vec<String> = port_modules(&src).into_iter().collect();
        assert_eq!(keep, ["deep", "helpers", "utf16"]);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_front_door_main_from_before_the_mode_guard_is_still_generated() {
        assert!(
            MAIN_RS.contains(MODE_GUARD) || MAIN_RS.contains(BEFORE_MODE_GUARD),
            "MAIN_RS no longer has the line the earlier form is derived from"
        );
        let state = State {
            schema: String::new(),
            name: "tcli".into(),
            commands: Vec::new(),
            units: Vec::new(),
            lifted: false,
            kind: AppKind::Cli,
            routes: Vec::new(),
            api: Vec::new(),
        };
        let before = MAIN_RS.replace(MODE_GUARD, BEFORE_MODE_GUARD);
        assert!(is_generated_main(MAIN_RS, &state));
        assert!(is_generated_main(&before, &state));
        assert!(is_generated_main(&before.replace('\n', "\n\n  "), &state));
        let changed = format!("{before}\nfn extra() {{ original::run(); }}\n");
        assert!(!is_generated_main(&changed, &state));
    }

    #[test]
    fn lifted_routing_has_no_kill_switch() {
        let state = State {
            schema: String::new(),
            name: "tcli".into(),
            commands: vec!["words".into()],
            units: vec![front_door::WiredUnit {
                name: "wordcount".into(),
                crate_name: "wordcount-rs".into(),
                path: "../wordcount-rs".into(),
                commands: vec!["words".into(), "tcli".into()],
                switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
                routes: Vec::new(),
                unit: None,
                shadow: None,
                kept: Vec::new(),
            }],
            lifted: true,
            kind: AppKind::Cli,
            routes: Vec::new(),
            api: Vec::new(),
        };
        let code = lifted_units_rs(&state);
        assert!(code.contains("\"words\" | \"tcli\" => Some(wordcount::run(command, matches)),"));
        assert!(!code.contains("RUST_ANYTHING_UNIT"));
        assert!(!LIFTED_MAIN.contains("original"));
    }

    /// A copy of the obligations `ts-cli` repository, in its own folder.
    fn obligations_repo(tag: &str) -> PathBuf {
        let repo = crate::app::temp_dir(tag).unwrap();
        let fixture =
            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/obligations-ts-cli");
        copy_tree(&fixture, &repo).unwrap();
        repo
    }

    fn write(repo: &Path, rel: &str, text: &str) {
        let path = repo.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, text).unwrap();
    }

    #[test]
    fn what_blocks_is_one_line_per_group_and_an_unread_file_is_a_blocker_not_silence() {
        // A readable repository: what nobody waived blocks, one sentence per group.
        let repo = obligations_repo("lift-blockers-ok");
        let lines = obligation_blockers(&repo, "my-repo");
        assert!(
            lines
                .iter()
                .any(|l| l.contains("no recorded case exercises")),
            "{lines:#?}"
        );
        assert!(
            lines.iter().all(|l| !l.contains("could not be checked")),
            "{lines:#?}"
        );
        std::fs::remove_dir_all(&repo).unwrap();

        // Invalid decisions: one blocker that says so, never an empty list.
        let repo = obligations_repo("lift-blockers-decisions");
        write(
            &repo,
            "rust/obligations-decisions.toml",
            "this is [not toml\n",
        );
        let lines = obligation_blockers(&repo, "my-repo");
        assert_eq!(lines.len(), 1, "{lines:#?}");
        assert!(
            lines[0].starts_with(
                "the obligations could not be checked: invalid rust/obligations-decisions.toml"
            ),
            "{}",
            lines[0]
        );
        std::fs::remove_dir_all(&repo).unwrap();

        // Invalid bindings, the same.
        let repo = obligations_repo("lift-blockers-bindings");
        write(
            &repo,
            "rust/obligations-bindings.toml",
            "this is [not toml\n",
        );
        let lines = obligation_blockers(&repo, "my-repo");
        assert_eq!(lines.len(), 1, "{lines:#?}");
        assert!(
            lines[0].starts_with(
                "the obligations could not be checked: invalid rust/obligations-bindings.toml"
            ),
            "{}",
            lines[0]
        );
        std::fs::remove_dir_all(&repo).unwrap();

        // A case `.toml` that cannot be read blocks too, with its path: the ledger is not read.
        let repo = obligations_repo("lift-blockers-case");
        write(&repo, "rust/app-cases/c1.toml", "this is [not toml\n");
        let lines = obligation_blockers(&repo, "my-repo");
        assert_eq!(lines.len(), 1, "{lines:#?}");
        assert!(
            lines[0].starts_with("the obligations could not be checked: ")
                && lines[0].contains("rust/app-cases/c1.toml"),
            "{}",
            lines[0]
        );
        std::fs::remove_dir_all(&repo).unwrap();
    }
}