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.whole_record

Requirements index · View definition

evidence Valid

Requirement

A record MUST be changed only if every rewrite a mapping calls for in it verifies under cite requirements.refactor.outline_inputs, cite requirements.refactor.definition_inputs, cite requirements.refactor.subject_text, and cite requirements.refactor.reference_digest; otherwise the whole record MUST be left unchanged and reported with the check that failed. Records that no mapping affects MUST be left byte-identical.

Rationale

I found no gap. requirements.refactor.whole_record is carried out by src/refactor.rs#fn[rewrite_record], which carries the {impl} reference. The obligations and their code are below.

Obligations and code

  • Change a record only if every rewrite the mappings call for verifies. rewrite_record works on a clone of the record and collects failures from each check. These checks run in it or in code it reaches:
    • Definition and example records: the mapped-back body check against the recorded requirement or example field (subject_text), and the reference-digest check through States::digests (reference_digest).
    • Citation and site records: the item’s inputs pass through rewrite_input, which does the outline-hash check (outline_inputs) and the requirements/definition check (definition_inputs). The citation equivalence check same_citations also runs.
    • Site records have no body field. sites::validate_review requires a site review’s inputs to include a requirements input for the declaration of its requirement. rewrite_input therefore covers the body check for the site’s requirement field.
  • Otherwise leave the whole record unchanged and report the failed check. If failures is non-empty, rewrite_record returns Outcome::Unchanged(failures.join("; ")). The partially rewritten value is discarded, so no rewrite is partially applied. fn[refactor] collects these outcomes and lists them under “records unchanged”. Each reason names the check that failed, for example “requirement text of X changed”, “the reference set of X changed”, or “inputs[i]: … no longer has the recorded hash”.
  • Leave records no mapping affects byte-identical. rewrite_record returns Outcome::Unaffected when changed is false. refactor writes only records in Changed, so unaffected records are never rewritten.

Tests (each carries a {test} reference to the subject)

  • tests/refactor.rs#fn[a_moved_function_keeps_its_evidence_current] asserts that the unaffected rules.check record is byte-identical and that it is absent from the report.
  • fn[a_function_edited_while_moving_leaves_its_records_stale] covers an outline-hash failure. The record is byte-identical afterwards and the report names the failed check.
  • fn[a_requirement_edited_while_moving_keeps_its_old_record] covers a subject-text failure. The record is unchanged and no new file is created.
  • fn[a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite] covers a digest failure when the text and requirements-input rewrites would otherwise verify. It asserts that nothing is rewritten and that only the reference-set failure is reported.
  • fn[a_term_edited_while_moving_leaves_its_definition_input_stale] covers a definition-input failure.
  • fn[a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved] covers a digest failure on a record that reads nothing moved.
  • fn[a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged] covers the citation-review check.

Together these cover the all-or-nothing behaviour, the reporting of the failed check, and the byte-identical case.

Inputs

Implementation

Input 6: 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,
    })
}

Tests

Input 7: 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 8: 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 9: outline tests/refactor.rs fn[a_requirement_edited_while_moving_keeps_its_old_record]
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_requirement_edited_while_moving_keeps_its_old_record() {
    let temp = project();
    let root = temp.path();
    author(root);
    move_load_requirement(root, "Configuration MUST load quickly.");
    let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(
        report.contains("- evidence/rules.load.json: requirement text of core.load changed"),
        "{report}"
    );
    assert_eq!(
        fs::read(root.join("evidence/rules.load.json")).unwrap(),
        before
    );
    assert!(!root.join("evidence/core.load.json").exists());
}
Input 10: outline tests/refactor.rs fn[a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite]
  • File: tests/refactor.rs
  • Selector: fn[a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite]
  • Kind: fn
  • tests/refactor.rs:754–786
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite() {
    let temp = project();
    let root = temp.path();
    author(root);
    move_load_requirement(root, "Configuration MUST load.");
    // A new `{impl}` is not part of the move.
    fs::write(
        root.join("src/config.rs"),
        config_source("").replace(
            "// {impl}`rules.check`\n",
            "// {impl}`rules.check`\n// {impl}`rules.load`\n",
        ),
    )
    .unwrap();
    let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    // Its text and requirements input would be rewritten, but the reference
    // set check fails, so nothing is.
    assert!(
        report.contains("- evidence/rules.load.json: the reference set of core.load changed"),
        "{report}"
    );
    assert!(!report.contains("text of core.load changed"), "{report}");
    assert_eq!(
        fs::read(root.join("evidence/rules.load.json")).unwrap(),
        before
    );
}
Input 11: outline tests/refactor.rs fn[a_term_edited_while_moving_leaves_its_definition_input_stale]
  • File: tests/refactor.rs
  • Selector: fn[a_term_edited_while_moving_leaves_its_definition_input_stale]
  • Kind: fn
  • tests/refactor.rs:870–895
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_term_edited_while_moving_leaves_its_definition_input_stale() {
    let temp = project();
    let root = temp.path();
    add_term(root);
    fs::remove_file(root.join("md/terms.md")).unwrap();
    fs::write(
        root.join("md/glossary.md"),
        "# Glossary\n\n:::{definition} term\n:phrase: term\n\nA longer word.\n:::\n",
    )
    .unwrap();
    let before = fs::read(root.join("evidence/usage.use.json")).unwrap();
    let report = stdout(&refactor(root, &["--map", "terms.term=glossary.term"]));
    assert!(
        report.contains(
            "- evidence/usage.use.json: inputs[1]: glossary.term no longer selects what it recorded"
        ),
        "{report}"
    );
    assert_eq!(
        fs::read(root.join("evidence/usage.use.json")).unwrap(),
        before
    );
}
Input 12: 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);
}
Input 13: outline tests/refactor.rs fn[a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged]
  • File: tests/refactor.rs
  • Selector: fn[a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged]
  • Kind: fn
  • tests/refactor.rs:1164–1218
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged() {
    let temp = project();
    let root = temp.path();
    fs::write(
        root.join("src/config.rs"),
        format!(
            "{}\n// {{cite}}`rules.load`\nfn helper() {{}}\n",
            config_source("")
        ),
    )
    .unwrap();
    author(root);
    let path = root.join("evidence/citations/src/config.rs/fn[helper].json");
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    fs::write(
        &path,
        serde_json::to_string_pretty(&json!({
            "file": "src/config.rs",
            "item": "fn[helper]",
            "citations": [{"role": "cite", "name": "rules.load", "commentary": ""}],
            "determination": true,
            "rationale": "`src/config.rs#fn[helper]` relies on `rules.load`.",
            "inputs": [
                habeas::outline_input(root, "src/config.rs", "fn[helper]").unwrap(),
                requirements_input("rules.load", &["rules.load"], &LOAD_TEXT),
            ],
        }))
        .unwrap(),
    )
    .unwrap();
    let before = fs::read(&path).unwrap();
    // The helper moves, and now cites a different requirement. Plain
    // comments are not hashed, so only its citations reveal the change.
    fs::write(root.join("src/config.rs"), config_source("")).unwrap();
    fs::write(
        root.join("src/helper.rs"),
        "// {cite}`rules.check`\nfn helper() {}\n",
    )
    .unwrap();
    let report = stdout(&refactor(
        root,
        &["--map", "src/config.rs#fn[helper]=src/helper.rs#fn[helper]"],
    ));
    assert!(
        report.contains(
            "- evidence/citations/src/config.rs/fn[helper].json: the citations of src/helper.rs#fn[helper] differ from the recorded ones"
        ),
        "{report}"
    );
    assert_eq!(fs::read(&path).unwrap(), before);
    assert!(!root.join("evidence/citations/src/helper.rs").exists());
}

Referenced definitions

Input 2: requirements selection requirements.refactor.outline_inputs
:::{req} outline_inputs
An outline input MUST be rewritten only if the mapped node exists and its
structural hash, computed under
{cite}`requirements.references.structural_hash` over the
{term}`requirements.refactor.mapped_back` text of the node, equals the recorded
hash.
:::
Input 3: requirements selection requirements.refactor.definition_inputs
:::{req} definition_inputs
A requirements or definition input MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current text of each definition it
records equals the recorded text and, for a requirements input, the mapped
selection's current matches are exactly the recorded matches with the mapping
applied.
:::
Input 4: requirements selection requirements.refactor.subject_text
:::{req} subject_text
A record's `requirement` or `example` field MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current body of its subject equals
the recorded body.
:::
Input 5: requirements selection requirements.refactor.reference_digest
:::{req} reference_digest
A record's `references` digest MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current reference set of its subject,
under {cite}`requirements.ci.reference_set`, has the recorded digest.
:::
Input 14: definition requirements.refactor.mapped_back
:::{definition} mapped_back
:phrase: mapped-back

The *mapped-back* form of current text or a current address is the text or
address with each new side of the mappings replaced by its old side.
:::

Other sources

Input 1: requirements selection requirements.refactor.whole_record
:::{req} whole_record
A record MUST be changed only if every rewrite a mapping calls for in it
verifies under {cite}`requirements.refactor.outline_inputs`,
{cite}`requirements.refactor.definition_inputs`,
{cite}`requirements.refactor.subject_text`, and
{cite}`requirements.refactor.reference_digest`; otherwise the whole record MUST
be left unchanged and reported with the check that failed. Records that no
mapping affects MUST be left byte-identical.
:::
Input 15: 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)
}
Input 16: outline src/refactor.rs fn[rewrite_input]
/// Rewrites one input, or returns `None` when no mapping affects it.
// {impl}`requirements.refactor.outline_inputs`
// {impl}`requirements.refactor.definition_inputs`
fn rewrite_input(states: &States, input: &Value) -> Option<Result<Value, String>> {
    let mappings = &states.mappings;
    let root = &states.root;
    match InputSelector::from_input(input)? {
        InputSelector::Outline { file, item } => {
            let recorded = input.get("hash").and_then(Value::as_str)?;
            let mapped = mappings.node(&file, &item);
            let (new_file, new_item) = mapped.clone().unwrap_or((file.clone(), item.clone()));
            if mapped.is_none() && !states.rewritten.contains_key(&new_file) {
                return None;
            }
            let back = states.hash(&states.outlines_back, &new_file, &new_item);
            let current = states.hash(&states.outlines_post, &new_file, &new_item);
            Some(match (back, current) {
                (Ok(back), Ok(current)) if back == recorded => {
                    Ok(json!({"file": new_file, "item": new_item, "hash": current}))
                }
                (Err(error), _) | (_, Err(error)) => Err(error),
                _ => Err(format!(
                    "{} no longer has the recorded hash",
                    address(&new_file, &new_item)
                )),
            })
        }
        selector @ (InputSelector::Requirements { .. } | InputSelector::Definition { .. }) => {
            let (new_selector, names) = match &selector {
                InputSelector::Requirements { requirements } => (
                    InputSelector::Requirements {
                        requirements: mappings
                            .selection(requirements)
                            .unwrap_or_else(|| requirements.clone()),
                    },
                    input
                        .get("matches")
                        .and_then(Value::as_array)
                        .into_iter()
                        .flatten()
                        .filter_map(Value::as_str)
                        .map(str::to_owned)
                        .collect::<Vec<_>>(),
                ),
                InputSelector::Definition { definition } => (
                    InputSelector::Definition {
                        definition: mappings
                            .name(definition)
                            .unwrap_or_else(|| definition.clone()),
                    },
                    vec![definition.clone()],
                ),
                InputSelector::Outline { .. } => unreachable!(),
            };
            let affected = new_selector != selector
                || names.iter().any(|name| {
                    let new = mappings.name(name).unwrap_or_else(|| name.clone());
                    mappings.name(name).is_some()
                        || states.definitions.get(name).map(|d| &d.raw_lines)
                            != states.definitions_post.get(&new).map(|d| &d.raw_lines)
                });
            if !affected {
                return None;
            }
            let back = selector
                .resolve(root, &states.definitions_back, &states.outlines_back)
                .map(|resolved| selector.to_input(&resolved));
            let current = new_selector
                .resolve(root, &states.definitions_post, &states.outlines_post)
                .map(|resolved| new_selector.to_input(&resolved));
            Some(match (back, current) {
                (Ok(back), Ok(current))
                    if &back == input && {
                        let mut mapped = names
                            .iter()
                            .map(|name| mappings.name(name).unwrap_or_else(|| name.clone()))
                            .collect::<Vec<_>>();
                        mapped.sort();
                        current
                            .get("matches")
                            .is_none_or(|matches| *matches == json!(mapped))
                    } =>
                {
                    Ok(current)
                }
                (_, Err(error)) => Err(error),
                _ => Err(format!(
                    "{} no longer selects what it recorded",
                    match &new_selector {
                        InputSelector::Requirements { requirements } => requirements,
                        InputSelector::Definition { definition } => definition,
                        InputSelector::Outline { .. } => unreachable!(),
                    }
                )),
            })
        }
    }
}
Input 17: outline src/refactor.rs impl[States]
impl States {
    /// Computes the post and mapped-back states from the current repository.
    // {impl}`requirements.refactor.definition_inputs`
    fn compute(root: &Path, mappings: Mappings) -> io::Result<Self> {
        let definitions = crate::evidence::load_definitions(root)?;
        let mut failures = Vec::new();
        let files = crate::evidence::discovered_files(root, &mut failures);
        let references = crate::evidence::collect_references_with_progress(
            root,
            &files,
            &mut failures,
            &mut |_| {},
        );
        if !failures.is_empty() {
            return Err(io::Error::other(failures.join("\n")));
        }
        let mut sources = files
            .iter()
            .map(|file| display_path(root, file))
            .collect::<BTreeSet<_>>();
        sources.extend(
            definitions
                .values()
                .map(|definition| definition.file.clone()),
        );
        let mut rewritten = BTreeMap::new();
        let mut post = HashMap::new();
        let mut back = HashMap::new();
        for file in &sources {
            let Ok(content) = fs::read_to_string(root.join(file)) else {
                continue;
            };
            let (new, edits) = rewrite_source(&mappings, Path::new(file), &content);
            let reverted = mappings.text_back(&new);
            if reverted != content {
                back.insert(file.clone(), reverted);
            }
            if edits > 0 {
                post.insert(file.clone(), new.clone());
                rewritten.insert(file.clone(), (new, edits));
            }
        }
        let rewrite = |text: &str, file: &str| rewrite_source(&mappings, Path::new(file), text).0;
        let definitions_post = definitions
            .iter()
            .map(|(name, definition)| {
                let mut definition = definition.clone();
                definition.text = rewrite(&definition.text, &definition.file);
                definition.raw_lines = rewrite(&definition.raw_lines.join("\n"), &definition.file)
                    .split('\n')
                    .map(str::to_owned)
                    .collect();
                for anchor in &mut definition.anchors {
                    if let Some(new) = mappings.address(&anchor.label()) {
                        *anchor = Anchor::parse(anchor.kind, &new);
                    }
                }
                (name.clone(), definition)
            })
            .collect::<BTreeMap<_, _>>();
        let definitions_back = definitions_post
            .iter()
            .map(|(name, definition)| {
                let old = mappings.name_back(name).unwrap_or_else(|| name.clone());
                let mut definition = definition.clone();
                definition.text = mappings.text_back(&definition.text);
                definition.raw_lines = definition
                    .raw_lines
                    .iter()
                    .map(|line| mappings.text_back(line))
                    .collect();
                if let Some(opening) = definition.raw_lines.first_mut() {
                    *opening = opening_back(opening, name, &old);
                }
                for anchor in &mut definition.anchors {
                    if let Some(old) = mappings.address_back(&anchor.label()) {
                        *anchor = Anchor::parse(anchor.kind, &old);
                    }
                }
                (old, definition)
            })
            .collect();
        let references_post = references
            .iter()
            .map(|reference| {
                let mut reference = reference.clone();
                if let Some(new) = mappings.name(&reference.name) {
                    reference.name = new;
                }
                if let Some(body) = &mut reference.commentary {
                    *body = rewrite_source(&mappings, Path::new("commentary"), body).0;
                }
                reference
            })
            .collect::<Vec<_>>();
        let references_back = references_post
            .iter()
            .map(|reference| {
                let mut reference = reference.clone();
                if let Some(old) = mappings.name_back(&reference.name) {
                    reference.name = old;
                }
                if let Some(body) = &mut reference.commentary {
                    *body = mappings.text_back(body);
                }
                reference
            })
            .collect();
        Ok(Self {
            root: root.to_owned(),
            mappings,
            files,
            rewritten,
            definitions,
            definitions_post,
            definitions_back,
            references_post,
            references_back,
            outlines_post: OutlineCache::with_overrides(post),
            outlines_back: OutlineCache::with_overrides(back),
        })
    }

    /// A node's structural hash in a state.
    fn hash(&self, outlines: &OutlineCache, file: &str, item: &str) -> Result<String, String> {
        let parsed = outlines.parse(&self.root, file);
        let parsed = parsed.as_ref().as_ref().map_err(Clone::clone)?;
        let index = parsed.resolve(file, item)?;
        Ok(parsed.outline.nodes[index].structural_hash.clone())
    }

    /// The post state's reference-set digest of a current definition, and
    /// the mapped-back digest of its old name.
    // {impl}`requirements.refactor.reference_digest`
    fn digests(&self, new: &str, old: &str) -> io::Result<Option<(String, String)>> {
        let (Some(post), Some(back)) = (
            self.definitions_post.get(new),
            self.definitions_back.get(old),
        ) else {
            return Ok(None);
        };
        let sites = crate::evidence::definition_sites(
            &self.root,
            new,
            post,
            &self.files,
            &self.outlines_post,
        )?;
        let current = crate::evidence::reference_set_digest(
            &self.root,
            &self.outlines_post,
            new,
            post,
            &self.references_post,
            &sites,
        );
        let mut entries = crate::evidence::reference_set_entries(
            &self.root,
            &self.outlines_back,
            old,
            back,
            &self.references_back,
            &sites,
        );
        for entry in &mut entries {
            if entry.origin != "anchor"
                && let Some((file, item)) = self.mappings.node_back(&entry.file, &entry.item)
            {
                entry.file = file;
                entry.item = item;
            }
        }
        Ok(Some((current, crate::evidence::digest_entries(entries))))
    }
}
Input 18: outline src/refactor.rs fn[same_citations]
// {cite}`habeas:util`
/// Whether a citation review's citations, as rewritten, are the post
/// state's citations of its item.
fn same_citations(states: &States, file: &str, item: &str, value: &Value) -> bool {
    let items = crate::citations::citation_items(
        &states.root,
        &states.definitions_post,
        &states.references_post,
        &states.outlines_post,
    );
    let Some(current) = items.get(&(file.to_owned(), item.to_owned())) else {
        return false;
    };
    let recorded = value["citations"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|citation| crate::citations::Citation {
            role: match citation["role"].as_str() {
                Some("cite") => "cite",
                Some("impl") => "impl",
                Some("test") => "test",
                Some("fixme") => "fixme",
                _ => "",
            },
            name: citation["name"].as_str().unwrap_or_default().to_owned(),
            commentary: citation["commentary"]
                .as_str()
                .unwrap_or_default()
                .to_owned(),
        })
        .collect::<Vec<_>>();
    crate::citations::same_citations(&recorded, &current.citations)
}
Input 19: outline src/sites.rs fn[validate_review]
/// Validates one review file against its current site.
// {impl}`requirements.ci.errors`
// {impl}`requirements.references.site_review`
fn validate_review(
    root: &Path,
    label: &str,
    site: &SiteItem,
    definitions: &BTreeMap<String, Declaration>,
    references: &[SourceReference],
    outlines: &OutlineCache,
    errors: &mut Vec<String>,
) {
    let content = match fs::read_to_string(root.join(label)) {
        Ok(content) => content,
        Err(error) => {
            errors.push(format!("{label}: cannot read site review: {error}"));
            return;
        }
    };
    let value: Value = match serde_json::from_str(&content) {
        Ok(value) => value,
        Err(error) => {
            errors.push(format!("{label}: invalid JSON: {error}"));
            return;
        }
    };
    let Some(object) = value.as_object() else {
        errors.push(format!("{label}: expected a JSON object"));
        return;
    };
    check_keys(
        object,
        &[
            "requirement",
            "file",
            "item",
            "queries",
            "applies",
            "fixmes",
            "determination",
            "rationale",
            "inputs",
        ],
        label,
        errors,
    );
    for (field, expected) in [
        ("requirement", &site.requirement),
        ("file", &site.file),
        ("item", &site.item),
    ] {
        if let Some(recorded) = string_field(object, field, label, errors)
            && recorded != expected
        {
            errors.push(format!("{label}: {field} must be {expected:?}"));
        }
    }
    if let Some(recorded) = array_field(object, "queries", label, errors) {
        let queries = site.queries();
        let current = queries.iter().map(|query| json!(query)).collect::<Vec<_>>();
        if *recorded != current {
            errors.push(format!(
                "{label}: queries changed for {} {}: recorded {}, now {}",
                site.file,
                site.selector_label(),
                Value::Array(recorded.clone()),
                Value::Array(current)
            ));
        }
    }
    if let Some(recorded) = array_field(object, "fixmes", label, errors) {
        let current = site_fixmes(root, site, references, outlines);
        let parsed = recorded
            .iter()
            .map(|fixme| {
                Some(SiteFixme {
                    item: fixme.get("item")?.as_str()?.to_owned(),
                    commentary: fixme.get("commentary")?.as_str()?.to_owned(),
                })
            })
            .collect::<Option<Vec<_>>>();
        match parsed {
            None => errors.push(format!(
                "{label}: fixmes must be an array of objects with string item and commentary"
            )),
            Some(parsed) if !same_fixmes(&parsed, &current) => errors.push(format!(
                "{label}: {{fixme}} references to {} inside {} {} changed: recorded {}, now {}",
                site.requirement,
                site.file,
                site.selector_label(),
                Value::Array(parsed.iter().map(SiteFixme::to_value).collect()),
                Value::Array(current.iter().map(SiteFixme::to_value).collect())
            )),
            Some(_) => {}
        }
    }
    let applies = match object.get("applies") {
        Some(Value::Bool(applies)) => Some(*applies),
        Some(_) => {
            errors.push(format!("{label}: applies must be a Boolean"));
            None
        }
        None => {
            errors.push(format!("{label}: missing field \"applies\""));
            None
        }
    };
    let determination = match object.get("determination") {
        Some(value) => match Judgment::from_value(value) {
            Ok(judgment) => Some(judgment),
            Err(error) => {
                errors.push(format!("{label}: determination: {error}"));
                None
            }
        },
        None => {
            errors.push(format!("{label}: missing field \"determination\""));
            None
        }
    };
    let rationale = string_field(object, "rationale", label, errors);
    if rationale.is_some_and(|text| text.trim().is_empty()) {
        errors.push(format!("{label}: rationale must not be empty"));
    }
    if applies == Some(false)
        && determination
            .as_ref()
            .is_some_and(|judgment| *judgment != Judgment::True)
    {
        errors.push(format!(
            "{label}: applies is false, so the determination must be true"
        ));
    }
    match &determination {
        Some(Judgment::False) => errors.push(format!(
            "{label}: determination is false{}",
            rationale
                .filter(|text| !text.trim().is_empty())
                .map_or(String::new(), |text| format!(": {}", text.trim()))
        )),
        Some(Judgment::Fixme(entries)) => crate::evidence::validate_fixme_entries(
            root,
            label,
            &site.requirement,
            entries,
            &site.fixmes(root, references),
            errors,
        ),
        _ => {}
    }
    let Some(inputs) = array_field(object, "inputs", label, errors) else {
        return;
    };
    let mut selects_site = false;
    let mut declared = BTreeSet::new();
    for (index, input) in inputs.iter().enumerate() {
        validate_input(
            root,
            definitions,
            outlines,
            input,
            &format!("{label}: inputs[{index}]"),
            errors,
        );
        match InputSelector::from_input(input) {
            Some(InputSelector::Outline { file, item }) => {
                selects_site |= file == site.file && item == site.item;
            }
            Some(InputSelector::Requirements { .. }) => declared.extend(
                input
                    .get("matches")
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten()
                    .filter_map(Value::as_str)
                    .map(str::to_owned),
            ),
            _ => {}
        }
    }
    if !selects_site {
        errors.push(format!(
            "{label}: inputs must select the site {} {}",
            site.file,
            site.selector_label()
        ));
    }
    let mut needed = vec![site.requirement.clone()];
    if let Some(declaration) = definitions.get(&site.requirement) {
        needed.extend(cited_declarations(declaration, definitions));
    }
    for name in needed {
        if !declared.contains(&name) {
            errors.push(format!(
                "{label}: inputs must include the declaration of {name}"
            ));
        }
    }
}