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.references.structural_hash

Requirements index · View definition

evidence Valid

Requirement

A node’s structural hash MUST be the SHA-256 digest of an unambiguous encoding of its outline-relevant structure, including siblings its profile attaches to it: the kinds of its named grammar nodes and, in source order, its text pieces. A text piece MUST be the text of a leaf token, or text inside a node that no child token covers. Each text piece MUST be hashed as its ordered list of words, where words are separated by whitespace, the whitespace itself, including leading and trailing whitespace, is never hashed, and each word is encoded separately, so ab cd and abcd differ. The same rule MUST apply in every language. Comments MUST be excluded, except comment kinds the profile includes; the Rust profile MUST include doc comments. For an included comment, only its text and its profile’s comment group MUST be hashed, not its delimiter tokens such as //, ///, //!, /*, */, or a leading *; the Rust profile’s groups are inner and outer doc comments. The words of consecutive included comments of one group MUST be hashed as one ordered list, so reflowing them across more or fewer lines or comments does not change the hash, while moving text between groups does. A line node’s hash MUST be computed by the same word rule over the line’s text. A node’s identity hash MUST be computed the same way but MUST also exclude its outline descendants and their attached siblings, so editing a descendant does not change its ancestors’ selectors.

Rationale

The reviewed tests adequately cover requirements.references.structural_hash. All paths are in src/outline/tests.rs unless noted.

SHA-256 digest of an unambiguous encoding, with grammar kinds and nesting

  • hashes_include_grammar_kinds_nesting_and_sha256_digests checks that identical text x; hashes differently under the Rust and Python grammars, so kinds are hashed.
  • The same test checks that a nested encoding differs from a sibling encoding, so structure is hashed unambiguously.
  • It also asserts exact SHA-256 vectors: the empty-input digest for both the structural and identity hash, and the tagged, length-prefixed digest of a hello line.

Text pieces, words and whitespace

  • prose_words_are_encoded_separately checks ab cd against abcd in a Rust doc comment and in a Markdown section. It also checks that whitespace and line breaks are not hashed.
  • string_literals_hash_as_words covers leaf string tokens in Rust, TOML and YAML block scalars.
  • markdown_hashes_include_paragraph_text_between_punctuation_tokens and reflowing_markdown_paragraphs_keeps_the_hash cover text inside a node that no child token covers.
  • plain_text_line_hashes_ignore_whitespace_but_not_word_breaks covers the line node rule. It checks leading, trailing and interior whitespace, and that twowords and two word differ. It also compares the result with hash::line.

Same rule in every language

  • The tests span Rust, Python, TypeScript, CSS, Markdown, TOML, YAML and plain text.

Comment exclusion and Rust doc comments

  • hashes_skip_whitespace_and_plain_comments_but_not_doc_comments covers Rust plain comments, and also checks that doc comment and attribute edits change the hash.
  • comments_are_excluded_from_hashes_in_every_other_profile covers Python, TypeScript, CSS, Markdown, TOML and YAML. For each it checks that comment changes or removal leave the hash unchanged and that a non-comment change alters it.

Included comments hashed by text and group only

  • reflowing_doc_comments_keeps_the_hash and editing_a_doc_comment_word_changes_the_hash cover reflow across lines and comments. reflowing_doc_comments_keeps_the_hash also compares /// with /** * */.
  • reflowing_inner_and_block_doc_comments_keeps_the_hash compares //! with /*! */ and block /** * */ with ///.
  • inner_and_outer_doc_comments_hash_in_separate_groups checks that moving text between the inner and outer groups changes the hash. It also checks that splitting words within one group does not.

Siblings attached by the profile, and the identity hash

  • Only the Rust (attributes, outer doc comments) and Python (decorators) profiles attach siblings. The other profiles use attaches: never.
  • identity_hashes_include_own_attached_siblings_but_not_descendants checks that a node’s own attached doc comment and attribute change its identity hash. It also checks that a descendant’s doc or attribute edits change the ancestor’s structural hash but not its identity hash.
  • python_decorators_attach_to_the_decorated_definition_for_hashing makes the same checks for Python decorators.
  • anonymous_selectors_use_identity_hashes and tests/evidence_boundaries.rs#fn[outline_inputs_survive_moves_and_unhashed_comments_but_not_edits] give end-to-end coverage of these hash properties.
  • src/redaction/tests.rs#fn[hashes_do_not_depend_on_credential_values] is marked against this requirement and uses the same hash path.

I found no obligation without a test and no wrong expected result. There are no acknowledged gaps, and none are needed.

Inputs

Implementation

Input 21: outline src/outline/css.rs static[PROFILE]
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
    name: "css",
    extensions: &["css"],
    language: Some(|| tree_sitter_css::LANGUAGE.into()),
    kinds: KINDS,
    is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: false,
    attaches: never,
};
Input 22: outline src/outline/markdown.rs static[PROFILE]
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
    name: "markdown",
    extensions: &["md", "markdown"],
    language: Some(|| tree_sitter_md::LANGUAGE.into()),
    kinds: KINDS,
    is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: false,
    attaches: never,
};
Input 23: outline src/outline/plain.rs static[PROFILE]
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
    name: "plain-text",
    extensions: &[],
    language: None,
    kinds: &[],
    is_comment: kind_is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: false,
    attaches: never,
};
Input 24: outline src/outline/toml.rs static[PROFILE]
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
    name: "toml",
    extensions: &["toml"],
    language: Some(|| tree_sitter_toml_ng::LANGUAGE.into()),
    kinds: KINDS,
    is_comment: kind_is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: false,
    attaches: never,
};
Input 26: outline src/outline/yaml.rs static[PROFILE]
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
    name: "yaml",
    extensions: &["yml", "yaml"],
    language: Some(|| tree_sitter_yaml::LANGUAGE.into()),
    kinds: KINDS,
    is_comment: kind_is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: true,
    attaches: never,
};

Tests

Input 2: outline src/outline/tests.rs fn[hashes_include_grammar_kinds_nesting_and_sha256_digests]
// {test}`requirements.references.structural_hash`
#[test]
fn hashes_include_grammar_kinds_nesting_and_sha256_digests() {
    // Identical leaf text parsed under distinct grammars has distinct kinds.
    let rust = outline("sample.rs", "x;");
    let python = outline("sample.py", "x;");
    assert_ne!(
        rust.nodes[0].structural_hash,
        python.nodes[0].structural_hash
    );
    let mut nested = super::hash::Encoder::new();
    nested.kind("a");
    nested.kind("b");
    nested.words("x");
    nested.end();
    nested.end();
    let mut siblings = super::hash::Encoder::new();
    siblings.kind("a");
    siblings.end();
    siblings.kind("b");
    siblings.words("x");
    siblings.end();
    assert_ne!(nested.finish(), siblings.finish());
    // Standard SHA-256 empty vector, and SHA-256 of a tagged, length-prefixed
    // text token: b"T" + 5_u64.to_le_bytes() + b"hello".
    let empty = outline("sample.txt", "");
    for hash in [
        &empty.nodes[0].structural_hash,
        &empty.nodes[0].identity_hash,
    ] {
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }
    let line = outline("sample.txt", "hello");
    assert_eq!(
        line.nodes[1].structural_hash,
        "8b8d04e8a7ca68bfe4afe50ada62c244b03c0dcd31aafb2b885c81095f1fdd5c"
    );
    assert_eq!(line.nodes[1].identity_hash, line.nodes[1].structural_hash);
}
Input 3: outline src/outline/tests.rs fn[identity_hashes_include_own_attached_siblings_but_not_descendants]
// {test}`requirements.references.structural_hash`
// {test}`requirements.references.outlines`
#[test]
fn identity_hashes_include_own_attached_siblings_but_not_descendants() {
    let hashes = |source: &str, selector: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline
            .resolve(selector)
            .unwrap_or_else(|error| panic!("{selector}: {error:?}"))];
        (node.structural_hash.clone(), node.identity_hash.clone())
    };

    // A descendant's attached doc comment and attribute are outside its
    // ancestor's identity hash, though inside its structural hash.
    let base = "mod m {\n    /// Doc.\n    #[inline]\n    fn a() {}\n}\n";
    let (structural, identity) = hashes(base, "mod[m]");
    for edited in [
        base.replace("Doc.", "Changed doc."),
        base.replace("inline", "cold"),
        base.replace("    /// Doc.\n", ""),
    ] {
        let (edited_structural, edited_identity) = hashes(&edited, "mod[m]");
        assert_ne!(edited_structural, structural, "{edited}");
        assert_eq!(edited_identity, identity, "{edited}");
    }

    // A node's own attached doc comment and attribute are part of its identity
    // hash, so they distinguish otherwise identical anonymous nodes.
    let own = |source: &str| {
        let outline = outline("src/lib.rs", source);
        outline.nodes[1].identity_hash.clone()
    };
    let plain = own("use a::A;\n");
    let documented = own("/// Doc.\nuse a::A;\n");
    let attributed = own("#[cfg(test)]\nuse a::A;\n");
    assert_ne!(plain, documented);
    assert_ne!(plain, attributed);
    assert_ne!(own("/// Other.\nuse a::A;\n"), documented);
    assert_ne!(own("#[cfg(not(test))]\nuse a::A;\n"), attributed);
    // The identity hash of a node without descendants is its structural hash.
    let (structural, identity) = hashes("#[cfg(test)]\nfn b() {}\n", "fn[b]");
    assert_eq!(structural, identity);
}
Input 4: outline src/outline/tests.rs fn[anonymous_selectors_use_identity_hashes]
// {test}`requirements.references.selector_use`
// {test}`requirements.references.outline_selectors`
// {test}`requirements.references.structural_hash`
#[test]
fn anonymous_selectors_use_identity_hashes() {
    let before = outline(
        "src/lib.rs",
        "use alpha::A;\nuse beta::B;\nstruct Packet;\n",
    );
    let inserted = outline(
        "src/lib.rs",
        "use gamma::C;\n\nuse alpha::A;\nuse beta::B;\nstruct Packet;\n",
    );
    let changed = outline(
        "src/lib.rs",
        "use alpha::Z;\nuse beta::B;\nstruct Packet;\n",
    );
    let before_selectors = selectors(&before);
    assert!(before_selectors[0].starts_with("use@"));
    assert_eq!(before_selectors[0].len(), "use@".len() + 12);
    assert_eq!(before_selectors[2], "struct[Packet]");
    for selector in &before_selectors {
        assert!(inserted.resolve(selector).is_ok(), "{selector}");
    }
    assert!(changed.resolve(&before_selectors[0]).is_err());
    assert!(changed.resolve(&before_selectors[1]).is_ok());
    let twice = outline("src/lib.rs", "use a::A;\nuse a::A;\n");
    let twice = selectors(&twice);
    assert!(
        twice[0].ends_with("#1") && twice[1].ends_with("#2"),
        "{twice:?}"
    );
}
Input 5: outline src/outline/tests.rs fn[hashes_skip_whitespace_and_plain_comments_but_not_doc_comments]
// {test}`requirements.references.structural_hash`
// {test}`requirements.references.selector_raw_lines`
// {test}`requirements.references.outlines`
#[test]
fn hashes_skip_whitespace_and_plain_comments_but_not_doc_comments() {
    let base = concat!(
        "/// Doc.\n#[inline]\n// {cite}",
        "`a.b`\nfn run() { let x = 1; }\n"
    );
    let hash = |source: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline.resolve("fn[run]").unwrap()];
        (node.structural_hash.clone(), node.line_start, node.line_end)
    };
    let (original, start, end) = hash(base);
    assert_eq!((start, end), (1, 4));
    let (moved, start, _) = hash(&format!("\n\n{base}"));
    assert_eq!((moved.as_str(), start), (original.as_str(), 3));
    assert_eq!(
        hash(concat!(
            "/// Doc.\n#[inline]\n// {cite}",
            "`c.d`\nfn run() {\n    let x  =  1;\n}\n"
        ))
        .0,
        original
    );
    assert_ne!(hash(&base.replace("Doc.", "Docs.")).0, original);
    assert_ne!(hash(&base.replace("inline", "cold")).0, original);
    assert_ne!(hash(&base.replace("= 1", "= 2")).0, original);

    let parent = |source: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline.resolve("mod[m]").unwrap()];
        (node.structural_hash.clone(), node.identity_hash.clone())
    };
    let (structural, identity) = parent("mod m { fn a() {} }");
    let (edited_structural, edited_identity) = parent("mod m { fn a() { 1; } }");
    assert_ne!(structural, edited_structural);
    assert_eq!(identity, edited_identity);
}
Input 6: outline src/outline/tests.rs fn[reflowing_doc_comments_keeps_the_hash]
// {test}`requirements.references.structural_hash`
#[test]
fn reflowing_doc_comments_keeps_the_hash() {
    let original = run_hash("/// a\n/// b\nfn run() {}\n");
    assert_eq!(run_hash("/// a b\nfn run() {}\n"), original);
    assert_eq!(run_hash("///   a\n///\n///   b  \nfn run() {}\n"), original);
    assert_eq!(run_hash("/** a\n * b\n */\nfn run() {}\n"), original);
    assert_ne!(run_hash("/// a c\nfn run() {}\n"), original);
    assert_ne!(run_hash("/// b a\nfn run() {}\n"), original);
}
Input 7: outline src/outline/tests.rs fn[prose_words_are_encoded_separately]
// {test}`requirements.references.structural_hash`
#[test]
fn prose_words_are_encoded_separately() {
    assert_ne!(
        run_hash("/// ab cd\nfn run() {}\n"),
        run_hash("/// abcd\nfn run() {}\n")
    );
    let section = |source: &str| {
        let outline = outline("a.md", source);
        outline.nodes[outline.resolve("section[H]").unwrap()]
            .structural_hash
            .clone()
    };
    assert_ne!(section("# H\nab cd\n"), section("# H\nabcd\n"));
    assert_eq!(section("# H\nab cd\n"), section("# H\n  ab\ncd  \n"));
}
Input 8: outline src/outline/tests.rs fn[editing_a_doc_comment_word_changes_the_hash]
// {test}`requirements.references.structural_hash`
#[test]
fn editing_a_doc_comment_word_changes_the_hash() {
    let original = run_hash("/// Returns the count.\nfn run() {}\n");
    assert_ne!(run_hash("/// Returns the total.\nfn run() {}\n"), original);
    assert_ne!(run_hash("/// Returns  the count\nfn run() {}\n"), original);
    assert_eq!(
        run_hash("/// Returns  the\n/// count.\nfn run() {}\n"),
        original
    );
}
Input 9: outline src/outline/tests.rs fn[string_literals_hash_as_words]
// {test}`requirements.references.structural_hash`
#[test]
fn string_literals_hash_as_words() {
    assert_eq!(
        run_hash("fn run() { \"ab cd\"; }\n"),
        run_hash("fn run() { \"ab  cd\"; }\n")
    );
    assert_ne!(
        run_hash("fn run() { \"ab cd\"; }\n"),
        run_hash("fn run() { \"abcd\"; }\n")
    );
    let pair = |source: &str| {
        let outline = outline("a.toml", source);
        outline.nodes[outline.resolve("pair[a]").unwrap()]
            .structural_hash
            .clone()
    };
    assert_eq!(pair("a = \"a  b\"\n"), pair("a = \"a b\"\n"));
    assert_ne!(pair("a = \"a b\"\n"), pair("a = \"ab\"\n"));
    let block = |source: &str| {
        let outline = outline("a.yml", source);
        outline.nodes[outline.resolve("pair[a]").unwrap()]
            .structural_hash
            .clone()
    };
    let original = block("a: |\n  one two\n  three\n");
    assert_eq!(block("a: |\n  one   two\n    three\n"), original);
    assert_eq!(block("a: |\n  one\n  two three\n"), original);
    assert_ne!(block("a: |\n  onetwo\n  three\n"), original);
}
Input 10: outline src/outline/tests.rs fn[reflowing_markdown_paragraphs_keeps_the_hash]
// {test}`requirements.references.structural_hash`
#[test]
fn reflowing_markdown_paragraphs_keeps_the_hash() {
    let section = |source: &str| {
        let outline = outline("a.md", source);
        outline.nodes[outline.resolve("section[H]").unwrap()]
            .structural_hash
            .clone()
    };
    let original = section("# H\n\nThe quick brown\nfox jumps.\n");
    assert_eq!(section("# H\n\nThe quick\nbrown fox jumps.\n"), original);
    assert_eq!(section("# H\n\nThe quick brown fox jumps.\n"), original);
    assert_ne!(section("# H\n\nThe quick brownfox jumps.\n"), original);
}
Input 11: outline src/outline/tests.rs fn[reflowing_inner_and_block_doc_comments_keeps_the_hash]
// {test}`requirements.references.structural_hash`
#[test]
fn reflowing_inner_and_block_doc_comments_keeps_the_hash() {
    let module = |source: &str| {
        let outline = outline("src/lib.rs", source);
        outline.nodes[outline.resolve("mod[m]").unwrap()]
            .structural_hash
            .clone()
    };
    let original = module("mod m {\n    //! one two\n    //! three\n}\n");
    assert_eq!(
        module("mod m {\n    //! one\n    //! two three\n}\n"),
        original
    );
    assert_eq!(module("mod m {\n    /*! one two three */\n}\n"), original);
    assert_ne!(module("mod m {\n    //! one two\n}\n"), original);
    assert_eq!(
        run_hash("/**\n * a b\n * c\n */\nfn run() {}\n"),
        run_hash("/// a\n/// b c\nfn run() {}\n")
    );
}
Input 12: outline src/outline/tests.rs fn[markdown_hashes_include_paragraph_text_between_punctuation_tokens]
// {test}`requirements.references.structural_hash`
#[test]
fn markdown_hashes_include_paragraph_text_between_punctuation_tokens() {
    let hash = |source: &str| outline("a.md", source).nodes[1].structural_hash.clone();
    assert_ne!(
        hash("# Skill\nUse ready.\n"),
        hash("# Skill\nUse ready now.\n")
    );
    assert_eq!(
        hash("# Skill\nUse ready.\n"),
        hash("# Skill\nUse   ready.\n"),
        "whitespace is not hashed"
    );
}
Input 13: outline src/outline/tests.rs fn[comments_are_excluded_from_hashes_in_every_other_profile]
// {test}`requirements.references.structural_hash`
#[test]
fn comments_are_excluded_from_hashes_in_every_other_profile() {
    // Each case: path, selector, original source, sources differing from it
    // only in comments, and a source with a changed non-comment word.
    let cases: &[(&str, &str, &str, &[&str], &str)] = &[
        (
            "a.py",
            "def[f]",
            "def f(x):\n    # note\n    return x  # trailing\n",
            &[
                "def f(x):\n    # other note\n    return x  # changed\n",
                "def f(x):\n    return x\n",
            ],
            "def f(x):\n    # note\n    return y  # trailing\n",
        ),
        (
            "a.ts",
            "function[f]",
            "function f() {\n  // note\n  return /* inline */ 1;\n}\n",
            &[
                "function f() {\n  // other note\n  return /* changed */ 1;\n}\n",
                "function f() {\n  return 1;\n}\n",
            ],
            "function f() {\n  // note\n  return /* inline */ 2;\n}\n",
        ),
        (
            "a.css",
            "rule[a]",
            "a { /* note */ color: red; }\n",
            &[
                "a { /* other note */ color: red; }\n",
                "a { color: red; }\n",
            ],
            "a { /* note */ color: blue; }\n",
        ),
        (
            "a.md",
            "section[H]",
            "# H\n\n<!-- note -->\n\ntext\n",
            &["# H\n\n<!-- other note -->\n\ntext\n", "# H\n\ntext\n"],
            "# H\n\n<!-- note -->\n\nprose\n",
        ),
        (
            "a.toml",
            "table[t]",
            "[t]\n# note\na = 1 # trailing\n",
            &["[t]\n# other note\na = 1 # changed\n", "[t]\na = 1\n"],
            "[t]\n# note\na = 2 # trailing\n",
        ),
        (
            "a.yml",
            "pair[a]",
            "a:\n  # note\n  b: 1 # trailing\n",
            &["a:\n  # other note\n  b: 1 # changed\n", "a:\n  b: 1\n"],
            "a:\n  # note\n  b: 2 # trailing\n",
        ),
    ];
    for (path, selector, source, same, changed) in cases {
        let original = node_hash(path, source, selector);
        for edited in *same {
            assert_eq!(
                node_hash(path, edited, selector),
                original,
                "{path}: {edited}"
            );
        }
        assert_ne!(
            node_hash(path, changed, selector),
            original,
            "{path}: {changed}"
        );
    }
}
Input 14: outline src/outline/tests.rs fn[python_decorators_attach_to_the_decorated_definition_for_hashing]
// {test}`requirements.references.structural_hash`
#[test]
fn python_decorators_attach_to_the_decorated_definition_for_hashing() {
    let source = "@cache\ndef f():\n    pass\n";
    let original = node_hash("a.py", source, "def[f]");
    assert_ne!(
        node_hash("a.py", "@other\ndef f():\n    pass\n", "def[f]"),
        original
    );
    assert_ne!(
        node_hash("a.py", "def f():\n    pass\n", "def[f]"),
        original
    );
    assert_eq!(
        node_hash("a.py", "@cache\n\n\ndef f():\n  pass\n", "def[f]"),
        original
    );

    // A method's decorator is in its class's structural hash but outside the
    // class's identity hash.
    let class = |source: &str| {
        let outline = outline("a.py", source);
        let node = &outline.nodes[outline.resolve("class[C]").unwrap()];
        (node.structural_hash.clone(), node.identity_hash.clone())
    };
    let (structural, identity) = class("class C:\n    @cache\n    def m(self):\n        pass\n");
    let (edited_structural, edited_identity) =
        class("class C:\n    @other\n    def m(self):\n        pass\n");
    assert_ne!(edited_structural, structural);
    assert_eq!(edited_identity, identity);
}
Input 15: outline src/outline/tests.rs fn[plain_text_line_hashes_ignore_whitespace_but_not_word_breaks]
// {test}`requirements.references.structural_hash`
#[test]
fn plain_text_line_hashes_ignore_whitespace_but_not_word_breaks() {
    let line = |source: &str| {
        outline("notes.txt", source).nodes[1]
            .structural_hash
            .clone()
    };
    let original = line("two words\n");
    assert_eq!(original, super::hash::line("two words"));
    for edited in [
        "  two words\n",
        "two words  \n",
        "two \t  words\n",
        "\ttwo words \n",
    ] {
        assert_eq!(line(edited), original, "{edited:?}");
    }
    assert_ne!(line("twowords\n"), original);
    assert_ne!(line("two word\n"), original);
}
Input 16: outline src/outline/tests.rs fn[inner_and_outer_doc_comments_hash_in_separate_groups]
// {test}`requirements.references.structural_hash`
#[test]
fn inner_and_outer_doc_comments_hash_in_separate_groups() {
    let module = |source: &str| node_hash("src/lib.rs", source, "mod[m]");
    // Moving a word from a nested item's outer doc comment into the module's
    // adjacent inner doc comment changes the module's hash.
    assert_ne!(
        module("mod m {\n    //! one\n    /// two\n    fn f() {}\n}\n"),
        module("mod m {\n    //! one two\n    fn f() {}\n}\n")
    );
    // Within one group, splitting words across comments keeps the hash.
    assert_eq!(
        module("mod m {\n    //! one\n    //! two\n    fn f() {}\n}\n"),
        module("mod m {\n    //! one two\n    fn f() {}\n}\n")
    );
}
Input 17: outline src/redaction/tests.rs fn[hashes_do_not_depend_on_credential_values]
// {test}`requirements.authoring.redaction`
// {test}`requirements.references.structural_hash`
#[test]
fn hashes_do_not_depend_on_credential_values() {
    let config = |key: &str| {
        format!(
            "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\n[authoring.configs.cloud.credentials]\naccess_key_id = '{key}'\nsecret_access_key = 'secret'\n"
        )
    };
    let hashes = |path: &str, source: &str| {
        let redaction = Redaction::of_file(Path::new(path), source);
        outline(path, source, &redaction)
            .nodes
            .iter()
            .map(|node| (node.selector.clone(), node.structural_hash.clone()))
            .collect::<Vec<_>>()
    };
    assert_eq!(
        hashes("habeas.toml", &config("first")),
        hashes("habeas.toml", &config("second-value"))
    );
    assert_ne!(
        hashes("notes.toml", &config("first")),
        hashes("notes.toml", &config("second-value"))
    );

    let token = github_token();
    let other = format!("gh{}_{}", "p", "aB3dE5fG7hJ9kL1mN3pQ5rS7tV9wX1yZ3aB5");
    let rust = |token: &str| {
        format!(
            "/// Uses `{token}` by default.\nfn token() -> &'static str {{\n    \"{token}\"\n}}\n"
        )
    };
    assert_eq!(
        hashes("src/lib.rs", &rust(&token)),
        hashes("src/lib.rs", &rust(&other))
    );
    let text = |token: &str| format!("token {token}\nother line\n");
    assert_eq!(
        hashes("notes.txt", &text(&token)),
        hashes("notes.txt", &text(&other))
    );
    // Changing code outside a redacted region still changes the hash.
    assert_ne!(
        hashes("src/lib.rs", &rust(&token)),
        hashes("src/lib.rs", &rust(&token).replace("default", "design"))
    );
}
Input 18: outline tests/evidence_boundaries.rs fn[outline_inputs_survive_moves_and_unhashed_comments_but_not_edits]
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.diagnostics`
// {test}`requirements.ci.schema`
// {test}`requirements.ci.fixme_stale_input`
// {test}`requirements.references.selector_raw_lines`
// {test}`requirements.references.structural_hash`
#[test]
fn outline_inputs_survive_moves_and_unhashed_comments_but_not_edits() {
    let temp = fixture();
    let root = temp.path().join("project");
    // Citation reviews of the cited functions are checked elsewhere.
    let errors = |inputs: Vec<Value>| {
        write_inputs(&root, inputs);
        without_citation_reviews(validate_repository(&root).unwrap().errors).join("\n")
    };
    let rust = "// {cite}`rules.ready`\nfn alpha() { work(1); }\n\n/// Docs.\n// {cite}`rules.ready`\n#[allow(dead_code)]\nfn beta() {}\n";
    fs::write(root.join("src/lib.rs"), rust).unwrap();
    let inputs = vec![
        outline(&root, "src/lib.rs", "fn[alpha]"),
        outline(&root, "src/lib.rs", "fn[beta]"),
        habeas::outline_inputs_for_lines(&root, "data.txt", 2, 2)
            .unwrap()
            .remove(0),
    ];
    assert_eq!(errors(inputs.clone()), "");

    // Moving nodes and lines, and editing unhashed comments, keeps inputs valid.
    fs::write(
        root.join("src/lib.rs"),
        format!("// {{cite}}`rules.ready` moved below a new line\n\n{rust}")
            .replace("fn alpha() { work(1); }", "fn alpha() {\n    work(1);\n}"),
    )
    .unwrap();
    fs::write(root.join("data.txt"), "zero\nfirst\nsecond\n").unwrap();
    assert_eq!(errors(inputs.clone()), "");

    // Editing another node must not invalidate beta's recorded input.
    fs::write(root.join("src/lib.rs"), rust.replace("work(1)", "work(2)")).unwrap();
    assert_eq!(errors(vec![inputs[1].clone()]), "");

    // Editing a node's code or its doc comment makes the input stale, naming the
    // file, selector, and current line range.
    fs::write(
        root.join("src/lib.rs"),
        rust.replace("work(1)", "work(2)")
            .replace("/// Docs.", "/// Changed docs."),
    )
    .unwrap();
    let found = errors(inputs.clone());
    for expected in [
        "inputs[0]: outline input changed: src/lib.rs fn[alpha] (now lines 1-2) no longer has the recorded hash",
        "inputs[1]: outline input changed: src/lib.rs fn[beta] (now lines 4-7) no longer has the recorded hash",
    ] {
        assert!(found.contains(expected), "missing {expected:?}: {found}");
    }
    assert!(!found.contains("inputs[2]"), "{found}");
    assert!(!found.contains("work(2)"), "no diff: {found}");

    // An edited plain-text line is a different node.
    fs::write(root.join("data.txt"), "first\nchanged\n").unwrap();
    let found = errors(inputs[2..].to_vec());
    assert!(
        found.contains("data.txt: no outline node matches \"line@"),
        "{found}"
    );

    fs::write(
        root.join("src/lib.rs"),
        "// {cite}`rules.ready`\n#[cfg(a)]\nfn dup() {}\n// {cite}`rules.ready`\n#[cfg(b)]\nfn dup() {}\n",
    )
    .unwrap();
    let hash = "0".repeat(64);
    for (input, expected) in [
        (
            json!({"file":"src/lib.rs", "item":"fn[missing]", "hash":hash}),
            "src/lib.rs: no outline node matches \"fn[missing]\"",
        ),
        (
            json!({"file":"src/lib.rs", "item":"fn[dup]", "hash":hash}),
            "src/lib.rs: outline selector \"fn[dup]\" is ambiguous",
        ),
        (
            json!({"file":"src/lib.rs", "item":"fn[unclosed", "hash":hash}),
            "src/lib.rs: invalid outline selector \"fn[unclosed\"",
        ),
        (
            json!({"file":"src/lib.rs", "item":"fn[dup]#2", "hash":"ABC"}),
            "hash must be a lowercase hexadecimal SHA-256 digest",
        ),
        (
            json!({"file":"missing.txt", "item":"", "hash":hash}),
            "cannot open missing.txt",
        ),
        (
            json!({"file":"data.txt", "line_start":1, "line_end":1, "text":["first"]}),
            "unexpected field \"line_start\"",
        ),
        (
            json!({"rust_file":"src/lib.rs", "rust_item":"fn[dup]#1", "text":["fn dup() {}"]}),
            "unexpected field \"rust_file\"",
        ),
        (
            json!({"file":"src/lib.rs", "item":"fn[dup]#1", "hash":hash, "text":["fn dup() {}"]}),
            "unexpected field \"text\"",
        ),
    ] {
        let found = errors(vec![input]);
        assert!(found.contains(expected), "missing {expected:?}: {found}");
    }
    fs::write(root.join("src/broken.rs"), "fn {").unwrap();
    let found = errors(vec![
        json!({"file":"src/broken.rs", "item":"", "hash":hash}),
    ]);
    assert!(
        found.contains("src/broken.rs: cannot parse rust source"),
        "{found}"
    );
}

Other sources

Input 1: requirements selection requirements.references.structural_hash
:::{req} structural_hash
A node's structural hash MUST be the SHA-256 digest of an unambiguous encoding of
its outline-relevant structure, including siblings its profile attaches to it:
the kinds of its named grammar nodes and, in source order, its text pieces. A
text piece MUST be the text of a leaf token, or text inside a node that no child
token covers. Each text piece MUST be hashed as its ordered list of words, where
words are separated by whitespace, the whitespace itself, including leading and
trailing whitespace, is never hashed, and each word is encoded separately, so
`ab cd` and `abcd` differ. The same rule MUST apply in every language. Comments
MUST be excluded, except comment kinds the profile includes; the Rust profile MUST include doc comments. For an included comment, only its text and its
profile's comment group MUST be hashed, not its delimiter tokens such as `//`,
`///`, `//!`, `/*`, `*/`, or a leading `*`; the Rust profile's groups are inner
and outer doc comments. The words of consecutive included comments of one group
MUST be hashed as one ordered list, so reflowing them across more or fewer lines
or comments does not change the hash, while moving text between groups does. A `line`
node's hash MUST be computed by the same word rule over the line's text. A node's
identity hash MUST be computed the same way but MUST also exclude its outline
descendants and their attached siblings, so editing a descendant does not change
its ancestors' selectors.
:::
Input 19: outline src/outline/python.rs fn[attaches]
/// Decorators attach to the decorated definition.
// {cite}`habeas:util`
fn attaches(node: Node<'_>, _source: &str) -> bool {
    node.kind() == "decorator"
}
Input 20: outline src/outline/rust.rs fn[attaches]
/// Attributes and outer doc comments attach to the following item.
fn attaches(node: Node<'_>, _source: &str) -> bool {
    node.kind() == "attribute_item" || has_marker(node, "outer_doc_comment_marker")
}
Input 25: outline src/outline/typescript.rs const[TYPESCRIPT]
// {impl}`requirements.references.outline_comments`
const TYPESCRIPT: Profile = Profile {
    name: "typescript",
    extensions: &["ts", "mts", "cts"],
    language: Some(|| tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
    kinds: KINDS,
    is_comment: kind_is_comment,
    hashes_comment: never,
    comment_prose: super::profile::whole_comment,
    comment_binds_to_container: never,
    trailing_comments_outside: false,
    attaches: never,
};