Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.refactor.command

Requirements index · View definition

evidence Valid

Requirement

habeas refactor --map <old>=<new> [--map <old>=<new>]... [--dry-run] MUST update the repository after the user has already moved the mapped items. It MUST NOT move or edit code or directives itself, except as cite requirements.refactor.reference_rewrite specifies. It MUST list each record it changed and each record a mapping affects that it left unchanged, with the reason, and MUST succeed when every mapping is valid.

Rationale

I found no gaps against requirements.refactor.command.

Invocation syntax.

  • src/main.rs#enum[Command] declares Refactor with a required, repeatable --map old=new and a --dry-run flag.
  • The src/main.rs#fn[main]/use@118842506675 arm, marked {impl}, calls habeas::refactor(&root, &mappings, dry_run).
  • It prints the report and returns success when the call returns Ok.
  • Every test that runs the command asserts exit success, for example a_moved_function_keeps_its_evidence_current and a_function_edited_while_moving_leaves_its_records_stale.

Update after the user has moved the items. src/refactor.rs#fn[refactor], marked {impl}, loads the records and parses the mappings. It then computes states against the current repository and decides each record through rewrite_record. The tests move the code first and then run the command, and they check afterwards that errors(root) is empty.

MUST NOT move or edit code or directives, except as reference_rewrite specifies.

  • refactor writes only two kinds of file: the sources and book files in states.rewritten, which hold rewritten references and anchors, and the evidence/ records.
  • Nothing else is written.
  • a_moved_requirement_renames_its_references_and_evidence snapshots the repository and asserts that only evidence/core.load.json, evidence/rules.load.json, md/notes.md and src/config.rs differ.
  • reference_rewrite and its rewrite_source code are cited as context, so I did not reassess them.

List each changed record. refactor prints “Changed N records:” with path or path -> target. a_moved_function_keeps_its_evidence_current asserts this output, and a_moved_requirement_renames_its_references_and_evidence asserts the -> target form.

List each affected-but-unchanged record, with the reason.

  • rewrite_record returns Outcome::Unchanged(reason) when a check fails. The reasons it produces include a missing hash, text changed, a reference-set change, and a citation mismatch.
  • The overwrite-conflict loop in refactor also adds records to unchanged, with the reason “would be overwritten”.
  • The report prints these as “Left N records unchanged…: - path: reason”.
  • Tests assert the reasons: a_function_edited_while_moving_leaves_its_records_stale checks the inputs[1]: … no longer has the recorded hash line. a_moved_requirement_renames_its_references_and_evidence checks the rules.* glob reason. a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved checks the reference-set reason.
  • Both tests that expect a record to stay unchanged also assert that its file is byte-for-byte the same.
  • Unaffected records are correctly omitted, and a_moved_function_keeps_its_evidence_current asserts that rules.check is not mentioned.

MUST succeed when every mapping is valid. Stale or refused records produce Unchanged entries, not errors. The tests above assert success even when records are left stale. Invalid mappings belong to requirements.refactor.invalid_mappings, which is a separate requirement.

Dry-run. The [--dry-run] part of the syntax is implemented in refactor and tested by a_dry_run_reports_the_same_changes_and_writes_nothing. That test carries a {test} reference to requirements.refactor.dry_run, which holds the dry-run behavior. The command text states no separate dry-run obligation.

No unspecified behavior, untested obligation, or reachability gap found.

Inputs

Implementation

Input 3: outline src/main.rs fn[main]/use@118842506675
    // {impl}`requirements.cli.clap`
    let cli = Cli::parse();
    // {impl}`requirements.configuration.workspace_location`
    // {impl}`requirements.configuration.workspace_structure`
    // {impl}`requirements.configuration.loading`
    // Commands other than `author` load only the evidence settings, so status
    // and book rendering never need authoring configuration or credentials.
    // {impl}`requirements.authoring.deterministic_validation`
    // Only commands that resolve evidence inputs use the workspace evidence
    // path policy; setup, the session-start hook, and support queries do not.
    // `status` and `info` render the validation report, which records an
    // invalid workspace file as one finding and still runs the other checks,
    // so they must not stop here.
    // {impl}`requirements.ci.errors`
    if !matches!(
        cli.command,
        Command::Mdbook {
            command: Some(MdbookCommand::Supports { .. })
        } | Command::Setup { .. }
            | Command::Coverage { .. }
            | Command::CoverageCheck
            | Command::Test
            | Command::CoverageProcess { .. }
            | Command::Hook { .. }
            | Command::Status { .. }
            | Command::Info { .. }
    ) {
        habeas::config::load_workspace_evidence(&std::env::current_dir()?)?;
    }
    match cli.command {
        Command::Coverage { args } => {
            std::process::exit(habeas::execution_coverage::run(
                &setup::project_root()?,
                &args,
            )?);
        }
        // {impl}`requirements.test-coverage.check`
        Command::CoverageCheck => {
            let report = habeas::execution_coverage::check(&setup::project_root()?)?;
            print!("{}", report.text);
            std::process::exit(i32::from(!report.passed));
        }
        // {impl}`requirements.test-coverage.test`
        Command::Test => {
            std::process::exit(habeas::execution_coverage::test(&setup::project_root()?)?);
        }
        Command::CoverageProcess { args } => {
            std::process::exit(habeas::execution_coverage::collect_process(&args)?);
        }
        // {impl}`requirements.cli.mdbook`
        Command::Mdbook { command: None } => {
            let (context, mut book) = mdbook_preprocessor::parse_input(io::stdin())?;
            habeas::preprocess_book(&mut book, &context.root)?;
            serde_json::to_writer(io::stdout().lock(), &book)?;
            Ok(())
        }
        // {impl}`requirements.cli.invocation`
        Command::Mdbook {
            command: Some(MdbookCommand::Supports { renderer }),
        } => {
            if renderer == "html" {
                Ok(())
            } else {
                std::process::exit(1)
            }
        }
        // {impl}`requirements.cli.setup`
        // {impl}`requirements.cli.setup_local_path`
        Command::Setup { path } => setup::run(path.as_deref()),
        // {impl}`requirements.cli.status`
        // {impl}`requirements.cli.fixme_summary`
        // {impl}`requirements.cli.fixme_issues`
        Command::Status {
            all,
            selection,
            verbose,
            coverage,
        } => {
            let root = setup::project_root()?;
            io::stdout().lock().write_all(
                habeas::status_markdown_with_coverage(
                    &root,
                    all,
                    selection.as_deref(),
                    verbose,
                    coverage,
                    &habeas::GithubIssues::from_env(&root),
                )?
                .as_bytes(),
            )?;
            Ok(())
        }
        // {impl}`requirements.refactor.command`
        // {impl}`requirements.refactor.invalid_mappings`
        Command::Refactor { mappings, dry_run } => {
            let root = setup::project_root()?;
            match habeas::refactor(&root, &mappings, dry_run) {
                Ok(report) => {
                    io::stdout().lock().write_all(report.as_bytes())?;
                    Ok(())
                }
                Err(habeas::RefactorError::Usage(message)) => {
                    use clap::CommandFactory;
Input 4: outline src/refactor.rs fn[refactor]
/// Runs `habeas refactor` with `--map` values, reporting what it changed,
/// or with `dry_run`, what it would change.
// {impl}`requirements.refactor.command`
// {impl}`requirements.refactor.dry_run`
// {impl}`requirements.refactor.record_files`
// {impl}`requirements.refactor.equivalence`
// {impl}`requirements.refactor.rationale.untouched`
pub fn refactor(root: &Path, values: &[String], dry_run: bool) -> Result<String, RefactorError> {
    let root = fs::canonicalize(root)?;
    let records = load_records(&root)?;
    let mappings = parse_mappings(&root, values, &records)?;
    let states = States::compute(&root, mappings)?;
    let mut changed = Vec::new();
    let mut unchanged = Vec::new();
    let mut targets = BTreeMap::<String, usize>::new();
    for (path, record) in &records {
        match rewrite_record(&states, path, record)? {
            Outcome::Unaffected => {}
            Outcome::Unchanged(reason) => unchanged.push((path.clone(), reason)),
            Outcome::Changed {
                path: target,
                value,
                mentions,
            } => {
                *targets.entry(target.clone()).or_default() += 1;
                changed.push((path.clone(), target, value, mentions));
            }
        }
    }
    // A move may take the place of a record that moves away, but only if
    // that record's move survives: dropping one conflict can expose another,
    // so conflicts are dropped until none remain.
    loop {
        let moving = changed
            .iter()
            .filter(|(path, target, ..)| path != target)
            .map(|(path, ..)| path.clone())
            .collect::<BTreeSet<_>>();
        let before = changed.len();
        changed.retain(|(path, target, ..)| {
            let conflict = targets[target] > 1
                || (path != target && root.join(target).exists() && !moving.contains(target));
            if conflict {
                unchanged.push((path.clone(), format!("{target} would be overwritten")));
            }
            !conflict
        });
        if changed.len() == before {
            break;
        }
    }
    unchanged.sort();

    if !dry_run {
        for (file, (content, _)) in &states.rewritten {
            fs::write(root.join(file), content)?;
        }
        for (path, ..) in &changed {
            if !changed.iter().any(|(_, target, ..)| target == path) {
                let old = root.join(path);
                if fs::remove_file(&old).is_ok() {
                    prune(&root, &old);
                }
            }
        }
        for (_, target, value, _) in &changed {
            let target = root.join(target);
            if let Some(parent) = target.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(
                &target,
                format!(
                    "{}\n",
                    serde_json::to_string_pretty(value).map_err(io::Error::from)?
                ),
            )?;
        }
    }

    let (rewrote, change, leave) = if dry_run {
        ("Would rewrite", "Would change", "Would leave")
    } else {
        ("Rewrote", "Changed", "Left")
    };
    let mut report = String::new();
    if !states.rewritten.is_empty() {
        let _ = writeln!(
            report,
            "{rewrote} references or anchors in {} files:",
            states.rewritten.len()
        );
        for (file, (_, edits)) in &states.rewritten {
            let _ = writeln!(report, "- {file} ({edits})");
        }
    }
    let _ = writeln!(report, "{change} {} records:", changed.len());
    for (path, target, _, mentions) in &changed {
        if path == target {
            let _ = writeln!(report, "- {path}");
        } else {
            let _ = writeln!(report, "- {path} -> {target}");
        }
        for mention in mentions {
            let _ = writeln!(report, "  - review the rationale's {mention}");
        }
    }
    if !unchanged.is_empty() {
        let _ = writeln!(
            report,
            "{leave} {} records unchanged; they stay stale until reassessed:",
            unchanged.len()
        );
        for (path, reason) in &unchanged {
            let _ = writeln!(report, "- {path}: {reason}");
        }
    }
    Ok(report)
}

Tests

Input 5: outline tests/refactor.rs fn[a_moved_function_keeps_its_evidence_current]
// {test}`requirements.refactor.moved_function`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_function_keeps_its_evidence_current() {
    let temp = project();
    let root = temp.path();
    author(root);
    assert_eq!(errors(root), Vec::<String>::new());
    move_load(root, "");
    let stale = errors(root);
    assert!(
        stale.iter().any(|error| error.contains("fn[load]")),
        "{stale:#?}"
    );
    let unaffected = fs::read(root.join("evidence/rules.check.json")).unwrap();

    let output = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(
        report.contains("Changed 1 records:\n- evidence/rules.load.json\n"),
        "{report}"
    );
    // The other mention of the old file is listed for review.
    assert!(
        report.contains("review the rationale's `src/config.rs`"),
        "{report}"
    );
    // `rules.check` reads no moved node, so it is unaffected and unchanged.
    assert!(!report.contains("rules.check"), "{report}");
    assert_eq!(
        fs::read(root.join("evidence/rules.check.json")).unwrap(),
        unaffected
    );
    assert_eq!(errors(root), Vec::<String>::new());
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.load.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][1]["file"], "src/config/load.rs");
    assert_eq!(
        record["rationale"],
        "`src/config/load.rs#fn[load]` loads it, as `rules.load` asks; `verify` tests it in `src/config.rs`."
    );
    // Running it again changes nothing.
    let again = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(
        stdout(&again).contains("Changed 0 records:"),
        "{}",
        stdout(&again)
    );
}
Input 6: outline tests/refactor.rs fn[a_function_edited_while_moving_leaves_its_records_stale]
// {test}`requirements.refactor.edited_while_moving`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.command`
#[test]
fn a_function_edited_while_moving_leaves_its_records_stale() {
    let temp = project();
    let root = temp.path();
    author(root);
    move_load(root, " parse();");
    let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
    let output = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(
        report.contains(
            "- evidence/rules.load.json: inputs[1]: src/config/load.rs#fn[load] no longer has the recorded hash"
        ),
        "{report}"
    );
    assert_eq!(
        fs::read(root.join("evidence/rules.load.json")).unwrap(),
        before
    );
    assert!(!errors(root).is_empty());
}
Input 7: outline tests/refactor.rs fn[a_moved_requirement_renames_its_references_and_evidence]
// {test}`requirements.refactor.moved_requirement`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_requirement_renames_its_references_and_evidence() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::write(
        root.join("md/notes.md"),
        "Loading follows {cite}`rules.load`.\n",
    )
    .unwrap();
    // `load` moves to the `core` chapter; references still name the old name.
    fs::write(
        root.join("md/rules.md"),
        "# Rules\n\n:::{req} check\n:impl: data.txt\nThe data MUST be checked.\n:::\n",
    )
    .unwrap();
    fs::write(
        root.join("md/core.md"),
        "# Core\n\n:::{req} load\nConfiguration MUST load.\n:::\n",
    )
    .unwrap();
    let before = snapshot(root);
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(report.contains("- src/config.rs (2)"), "{report}");
    assert!(report.contains("- md/notes.md (1)"), "{report}");
    assert_eq!(
        fs::read_to_string(root.join("md/notes.md")).unwrap(),
        "Loading follows {cite}`core.load`.\n"
    );
    // Only the rewritten references and the moved evidence changed.
    let after = snapshot(root);
    let differing = before
        .keys()
        .chain(after.keys())
        .filter(|file| before.get(*file) != after.get(*file))
        .cloned()
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        differing.into_iter().collect::<Vec<_>>(),
        [
            "evidence/core.load.json",
            "evidence/rules.load.json",
            "md/notes.md",
            "src/config.rs",
        ]
    );
    assert!(
        report.contains("- evidence/rules.load.json -> evidence/core.load.json"),
        "{report}"
    );
    // The glob no longer matches what it recorded, so that record is stale.
    assert!(
        report.contains(
            "- evidence/rules.check.json: inputs[0]: rules.* no longer selects what it recorded"
        ),
        "{report}"
    );
    assert!(!root.join("evidence/rules.load.json").exists());
    let source = fs::read_to_string(root.join("src/config.rs")).unwrap();
    assert!(source.contains("// {impl}`core.load`") && source.contains("// {test}`core.load`"));
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.load.json")).unwrap())
            .unwrap();
    assert_eq!(
        record["inputs"][0],
        requirements_input("core.load", &["core.load"], &LOAD_TEXT)
    );
    assert!(
        record["rationale"]
            .as_str()
            .unwrap()
            .contains("as `core.load` asks")
    );
    let remaining = errors(root);
    assert!(
        remaining
            .iter()
            .all(|error| error.starts_with("evidence/rules.check.json")),
        "{remaining:#?}"
    );
}
Input 8: outline tests/refactor.rs fn[a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved]
  • File: tests/refactor.rs
  • Selector: fn[a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved]
  • Kind: fn
  • tests/refactor.rs:1048–1088
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.command`
#[test]
fn a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved() {
    let temp = project();
    let root = temp.path();
    author(root);
    // `rules.check` records only its glob input, so a move touches only its
    // reference set.
    let path = root.join("evidence/rules.check.json");
    let mut record: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    record["inputs"] = json!([record["inputs"][0]]);
    fs::write(&path, serde_json::to_string_pretty(&record).unwrap()).unwrap();
    let before = fs::read(&path).unwrap();
    // `check` moves, and an extra `{impl}` is added that is not part of it.
    fs::write(
        root.join("src/config.rs"),
        config_source("")
            .replace("// {impl}`rules.check`\nfn check() {}\n\n", "")
            .replace(
                "// {impl}`rules.load`\n",
                "// {impl}`rules.load`\n// {impl}`rules.check`\n",
            ),
    )
    .unwrap();
    fs::write(
        root.join("src/check.rs"),
        "// {impl}`rules.check`\nfn check() {}\n",
    )
    .unwrap();
    let report = stdout(&refactor(
        root,
        &["--map", "src/config.rs#fn[check]=src/check.rs#fn[check]"],
    ));
    assert!(
        report.contains("- evidence/rules.check.json: the reference set of rules.check changed"),
        "{report}"
    );
    assert_eq!(fs::read(&path).unwrap(), before);
}

Referenced definitions

Input 2: requirements selection requirements.refactor.reference_rewrite
:::{req} reference_rewrite
For a definition-name mapping, `habeas refactor` MUST rewrite each `{impl}`,
`{test}`, `{cite}`, `{fixme}`, and `{term}` reference that names an old name,
in the book and in the sources reference discovery considers. For a path or
node mapping, it MUST rewrite each `:impl:` or `:test:` anchor that names an
old file or node. It MUST change nothing else in those files.
:::

Other sources

Input 1: requirements selection requirements.refactor.command
:::{req} command
`habeas refactor --map <old>=<new> [--map <old>=<new>]... [--dry-run]` MUST
update the repository after the user has already moved the mapped items. It
MUST NOT move or edit code or directives itself, except as
{cite}`requirements.refactor.reference_rewrite` specifies. It MUST list each
record it changed and each record a mapping affects that it left unchanged,
with the reason, and MUST succeed when every mapping is valid.
:::
Input 9: outline src/refactor.rs fn[rewrite_record]
/// Decides one record under the mappings.
// {impl}`requirements.refactor.whole_record`
// {impl}`requirements.refactor.subject_text`
// {impl}`requirements.refactor.record_fields`
// {impl}`requirements.refactor.reference_digest`
fn rewrite_record(states: &States, path: &str, record: &Value) -> io::Result<Outcome> {
    let mappings = &states.mappings;
    let Some(kind) = record_kind(path) else {
        return Ok(Outcome::Unaffected);
    };
    let mut value = record.clone();
    let mut changed = false;
    let mut failures = Vec::new();
    let new_path = match &kind {
        RecordKind::Definition(name) => {
            let new = mappings.name(name).unwrap_or_else(|| name.clone());
            let field = if record.get("example").is_some() {
                "example"
            } else {
                "requirement"
            };
            let body = |definitions: &BTreeMap<String, Declaration>, name: &str| {
                definitions
                    .get(name)
                    .map(|definition| definition.text.clone())
            };
            if new != *name
                || body(&states.definitions, name) != body(&states.definitions_post, &new)
            {
                match (
                    body(&states.definitions_back, name),
                    body(&states.definitions_post, &new),
                ) {
                    (Some(back), Some(current))
                        if Some(back.as_str()) == record[field].as_str() =>
                    {
                        value[field] = Value::String(current);
                        changed = true;
                    }
                    (_, None) => {
                        failures.push(format!("{new}: no current definition"));
                        changed = true;
                    }
                    _ => {
                        failures.push(format!("{field} text of {new} changed"));
                        changed = true;
                    }
                }
            }
            if let Some(recorded) = record.get("references").and_then(Value::as_str)
                && let Some((current, back)) = states.digests(&new, name)?
                && current != recorded
                && (new != *name || current != back)
            {
                if back == recorded {
                    value["references"] = Value::String(current);
                    changed = true;
                } else {
                    failures.push(format!("the reference set of {new} changed"));
                    changed = true;
                }
            }
            if new != *name {
                changed = true;
            }
            format!("evidence/{new}.json")
        }
        RecordKind::Citation | RecordKind::Site => {
            let file = record
                .get("file")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let item = record
                .get("item")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let (new_file, new_item) = mappings
                .node(file, item)
                .unwrap_or((file.to_owned(), item.to_owned()));
            if (new_file.as_str(), new_item.as_str()) != (file, item) {
                value["file"] = json!(new_file);
                value["item"] = json!(new_item);
                changed = true;
            }
            match &kind {
                RecordKind::Citation => {
                    if let Some(citations) =
                        value.get_mut("citations").and_then(Value::as_array_mut)
                    {
                        for citation in citations {
                            let name = citation["name"].as_str().unwrap_or_default();
                            if let Some(new) = mappings.name(name) {
                                citation["name"] = json!(new);
                                changed = true;
                            }
                            let commentary = citation["commentary"]
                                .as_str()
                                .unwrap_or_default()
                                .to_owned();
                            let (new, edits) =
                                rewrite_source(mappings, Path::new("commentary"), &commentary);
                            if edits > 0 {
                                citation["commentary"] = json!(new);
                                changed = true;
                            }
                        }
                    }
                    // :::{impl} requirements.refactor.equivalence
                    // A citation review validates against the citations its
                    // item currently carries, so a review whose rewritten
                    // citations differ from those would validate differently
                    // after the move; the record is left unchanged instead.
                    // :::
                    if changed && !same_citations(states, &new_file, &new_item, &value) {
                        failures.push(format!(
                            "the citations of {} differ from the recorded ones",
                            address(&new_file, &new_item)
                        ));
                    }
                    crate::citations::review_path(&new_file, &new_item)
                }
                _ => {
                    let requirement = record
                        .get("requirement")
                        .and_then(Value::as_str)
                        .unwrap_or_default();
                    let new = mappings
                        .name(requirement)
                        .unwrap_or_else(|| requirement.to_owned());
                    if new != requirement {
                        value["requirement"] = json!(new);
                        changed = true;
                    }
                    crate::sites::review_path(&new, &new_file, &new_item)
                }
            }
        }
    };
    if let Some(inputs) = value.get_mut("inputs").and_then(Value::as_array_mut) {
        for (index, input) in inputs.iter_mut().enumerate() {
            match rewrite_input(states, input) {
                None => {}
                Some(Ok(new)) => {
                    if new != *input {
                        *input = new;
                        changed = true;
                    }
                }
                Some(Err(error)) => {
                    failures.push(format!("inputs[{index}]: {error}"));
                    changed = true;
                }
            }
        }
    }
    if !changed {
        return Ok(Outcome::Unaffected);
    }
    if !failures.is_empty() {
        return Ok(Outcome::Unchanged(failures.join("; ")));
    }
    let mut mentions = Vec::new();
    if let Some(rationale) = value.get("rationale").and_then(Value::as_str) {
        let (rewritten, found) = rewrite_rationale(mappings, rationale);
        value["rationale"] = Value::String(rewritten);
        mentions = found;
    }
    Ok(Outcome::Changed {
        path: new_path,
        value,
        mentions,
    })
}
Input 10: outline src/refactor.rs enum[Outcome]
// {cite}`habeas:util`
/// What `habeas refactor` does with one record.
enum Outcome {
    /// No mapping affects it.
    Unaffected,
    /// It is rewritten, and possibly moved.
    Changed {
        path: String,
        value: Value,
        mentions: Vec<String>,
    },
    /// A mapping affects it but a check failed.
    Unchanged(String),
}