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.ci.input_containment

Requirements index · View definition

evidence Valid

Requirement

Every file named directly by an evidence input or resolved from its selector MUST resolve within the project root unless permitted by workspace path configuration or discovered Cargo generated-output policy. Symlink targets MUST follow the same policy. Validation MUST enforce explicit workspace disallow entries and report missing, unreadable, or excluded files. It MUST check existing generated inputs without running a build. cite requirements.configuration.evidence_paths cite requirements.authoring.generated_inputs

Rationale

I found no gaps. Every obligation in requirements.ci.input_containment has code reachable from the two {impl} items and a test that exercises it.

Reachability. src/evidence.rs#fn[validate_input] calls validate_outline_input or validate_resolved_input. Those call InputSelector::resolve and OutlineCache::parse, which call read_project_file or check_project_file. That reaches src/authoring/access.rs#fn[resolve_evidence_file], which carries out the path rules. The authoring side, src/authoring/tools.rs#fn[project_path], calls SourceAccess::path, which uses the same policy code.

Obligations, code and tests

  • Files resolve within the project root unless permitted by workspace allow or generated-output policy.
    • Code: resolve_evidence_file rejects a path whose requested location or resolved target is outside the root. It makes an exception only for policy.allowed(...) or for a discovered generated root (generated_roots).
    • Tests: symlinks_may_resolve_inside_but_not_to_a_sibling_with_the_same_prefix checks the outside-root rejection, and configured_external_inputs_validate_and_remain_subject_to_freshness_and_disallow checks an external allow. discovered_external_cargo_outputs_validate_freshness_and_obey_disallow checks the generated-output exception, and explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets checks allow and disallow together.
  • Symlink targets follow the same policy.
    • Code: resolve canonicalizes the path, so the target is what gets checked. The root check requires both the requested path and the target to be inside, and check_disallow checks both.
    • Tests: symlinks_may_resolve_inside_but_not_to_a_sibling_with_the_same_prefix, explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets (alias to a disallowed target), disallowed_ancestors_cannot_redirect_reads_into_allowed_targets, policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees, and evidence_rejects_disallowed_ancestors_even_when_symlinks_target_allowed_sources.
  • Validation enforces explicit disallow entries.
    • Code: PathPolicy::check_disallow, called from resolve_evidence_file.
    • Tests: status_applies_workspace_disallow_to_existing_evidence, definition_and_requirements_inputs_obey_containment_for_declaring_files (definition and requirements inputs), configured_external_inputs_validate_and_remain_subject_to_freshness_and_disallow, and discovered_external_cargo_outputs_validate_freshness_and_obey_disallow (disallow overrides the generated-output permission).
  • Validation reports missing, unreadable, or excluded files.
    • Code: missing files give cannot open ... from resolve, unreadable ones give cannot read ... from read_project_file, and excluded ones give the “disallowed” error. validate_outline_input pushes these errors with the input label.
    • Tests: unreadable_and_missing_inputs_are_reported, plus the disallow tests above. The unreadable assertion runs only when the file really is unreadable, for example when the test is not running as a privileged user. That is an environmental guard, not a missing test.
  • Existing generated inputs are checked without running a build.
    • Code: generated_roots runs cargo metadata --offline --locked --no-deps, and discover_generated_roots reads existing root-output records. Neither runs a build.
    • Test: discovered_external_cargo_outputs_validate_freshness_and_obey_disallow asserts that the target directory does not exist afterwards.

The requirement cites requirements.configuration.evidence_paths and requirements.authoring.generated_inputs. I treated both as context and did not reassess their own implementation or tests.

I found no unspecified extra behavior.

Inputs

Implementation

Input 7: outline src/authoring/tools.rs fn[project_path]
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.ci.input_containment`
fn project_path(sources: &AssessmentSources, relative: &str) -> io::Result<PathBuf> {
    sources.access.path(&sources.root, Path::new(relative))
}
Input 9: outline src/evidence.rs fn[validate_input]
// {impl}`requirements.ci.input_containment`
// {impl}`requirements.ci.outline_inputs`
// {impl}`requirements.ci.requirements_inputs`
// {impl}`requirements.definitions.inputs`
// {impl}`requirements.ci.errors`
pub(crate) fn validate_input(
    root: &Path,
    definitions: &BTreeMap<String, Declaration>,
    outlines: &OutlineCache,
    input: &Value,
    label: &str,
    errors: &mut Vec<String>,
) -> Option<ResolvedInput> {
    let Some(object) = input.as_object() else {
        errors.push(format!("{label}: expected a JSON object"));
        return None;
    };
    if object.contains_key("definition") {
        check_keys(object, &["definition", "text"], label, errors);
        let definition = string_field(object, "definition", label, errors);
        let text = text_field(object, label, errors);
        // Resolving the definition does not depend on a well-formed `text`.
        let definition = definition?;
        return validate_resolved_input(
            root,
            definitions,
            outlines,
            &InputSelector::Definition {
                definition: definition.to_owned(),
            },
            text.as_deref(),
            None,
            label,
            errors,
        );
    }
    if object.contains_key("requirements") || object.contains_key("matches") {
        check_keys(object, &["requirements", "matches", "text"], label, errors);
        let requirements = string_field(object, "requirements", label, errors);
        let matches = array_field(object, "matches", label, errors).and_then(|values| {
            let mut names = Vec::new();
            for (index, value) in values.iter().enumerate() {
                match value.as_str() {
                    Some(name) => names.push(name.to_owned()),
                    None => errors.push(format!("{label}: matches[{index}] must be a string")),
                }
            }
            // Duplicates among the string entries are a separate failure.
            if names.iter().collect::<BTreeSet<_>>().len() != names.len() {
                errors.push(format!(
                    "{label}: matches must have distinct definition names"
                ));
            }
            (names.len() == values.len()).then_some(names)
        });
        let text = text_field(object, label, errors);
        // Resolving the selection depends only on `requirements`; each
        // comparison runs when its recorded field is well formed.
        let requirements = requirements?;
        let selector = InputSelector::Requirements {
            requirements: requirements.to_owned(),
        };
        return validate_resolved_input(
            root,
            definitions,
            outlines,
            &selector,
            text.as_deref(),
            matches.as_deref(),
            label,
            errors,
        );
    }
    validate_outline_input(root, definitions, outlines, object, label, errors)
}

Tests

Input 4: outline src/authoring/access.rs mod[tests]/fn[explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets]
  • File: src/authoring/access.rs
  • Selector: mod[tests]/fn[explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets]
  • Kind: fn
  • src/authoring/access.rs:860–906
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.ci.input_containment`
    #[test]
    fn explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets() {
        let root = tempfile::tempdir().unwrap();
        let external = tempfile::tempdir().unwrap();
        fs::create_dir_all(root.path().join("generated/private")).unwrap();
        fs::create_dir(root.path().join("evidence")).unwrap();
        fs::write(root.path().join("generated/ok.txt"), "generated\n").unwrap();
        fs::write(root.path().join("generated/private/secret.txt"), "secret\n").unwrap();
        fs::write(root.path().join("evidence/old.txt"), "old judgment\n").unwrap();
        fs::write(external.path().join("outside.txt"), "outside\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        let external_toml = toml::Value::String(external.path().display().to_string());
        fs::write(root.path().join("habeas.toml"), format!(
            "version = 1\n[evidence]\nallow = ['generated', 'evidence', {external_toml}]\ndisallow = ['generated/private']\n"
        )).unwrap();
        let root = fs::canonicalize(root.path()).unwrap();
        let access = SourceAccess::load(&root).unwrap();
        for path in [
            root.join("generated/ok.txt"),
            root.join("evidence/old.txt"),
            external.path().join("outside.txt"),
        ] {
            assert!(access.file(&root, &path).is_ok(), "{}", path.display());
            assert!(resolve_evidence_file(&root, path.to_str().unwrap()).is_ok());
        }
        let error = access
            .file(&root, Path::new("generated/private/secret.txt"))
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
        assert!(resolve_evidence_file(&root, "generated/private/secret.txt").is_err());
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(
                root.join("generated/private/secret.txt"),
                root.join("generated/alias.txt"),
            )
            .unwrap();
            let error = access
                .file(&root, Path::new("generated/alias.txt"))
                .unwrap_err();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
        }
    }
Input 5: outline src/authoring/access.rs mod[tests]/fn[disallowed_ancestors_cannot_redirect_reads_into_allowed_targets]
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.ci.input_containment`
    #[cfg(unix)]
    #[test]
    fn disallowed_ancestors_cannot_redirect_reads_into_allowed_targets() {
        let root = tempfile::tempdir().unwrap();
        for directory in ["private", "public", "sub"] {
            fs::create_dir(root.path().join(directory)).unwrap();
        }
        fs::write(root.path().join("public/file.txt"), "public source\n").unwrap();
        std::os::unix::fs::symlink("../public", root.path().join("private/link")).unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['public']\ndisallow = ['private']\n",
        )
        .unwrap();
        let access = SourceAccess::load(root.path()).unwrap();
        assert!(
            access
                .file(root.path(), Path::new("public/file.txt"))
                .is_ok()
        );
        for path in [
            "private/link/file.txt",
            "sub/../private/link/file.txt",
            "private/link",
        ] {
            let error = access.path(root.path(), Path::new(path)).unwrap_err();
            assert_eq!(
                error.kind(),
                io::ErrorKind::PermissionDenied,
                "{path}: {error}"
            );
            assert!(error.to_string().contains(path), "{error}");
        }
    }
Input 6: outline src/authoring/access.rs mod[tests]/fn[policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees]
  • File: src/authoring/access.rs
  • Selector: mod[tests]/fn[policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees]
  • Kind: fn
  • src/authoring/access.rs:1064–1140
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.ci.input_containment`
    #[cfg(unix)]
    #[test]
    fn policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees() {
        let root = tempfile::tempdir().unwrap();
        for directory in ["actual/nested", "actual/private", "private"] {
            fs::create_dir_all(root.path().join(directory)).unwrap();
        }
        fs::write(root.path().join("actual/private/file.txt"), "actual\n").unwrap();
        fs::write(root.path().join("private/file.txt"), "wrong subtree\n").unwrap();
        std::os::unix::fs::symlink(root.path().join("actual/nested"), root.path().join("alias"))
            .unwrap();
        git(root.path(), &["init", "--quiet"]);
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['alias/../private']\n",
        )
        .unwrap();
        let access = SourceAccess::load(root.path()).unwrap();
        assert!(
            access
                .file(root.path(), Path::new("actual/private/file.txt"))
                .is_ok()
        );
        assert!(
            access
                .file(root.path(), Path::new("alias/../private/file.txt"))
                .is_ok()
        );
        assert_eq!(
            access
                .file(root.path(), Path::new("private/file.txt"))
                .unwrap_err()
                .kind(),
            io::ErrorKind::PermissionDenied
        );
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['.']\ndisallow = ['alias/../private']\n",
        )
        .unwrap();
        let access = SourceAccess::load(root.path()).unwrap();
        for denied in ["actual/private/file.txt", "alias/../private/file.txt"] {
            assert_eq!(
                access
                    .file(root.path(), Path::new(denied))
                    .unwrap_err()
                    .kind(),
                io::ErrorKind::PermissionDenied
            );
            assert!(resolve_evidence_file(root.path(), denied).is_err());
        }
        assert!(
            access
                .file(root.path(), Path::new("private/file.txt"))
                .is_ok()
        );
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['actual/private']\n",
        )
        .unwrap();
        let access = SourceAccess::load(root.path()).unwrap();
        assert_eq!(
            access
                .file(
                    root.path(),
                    Path::new("actual/private/../../private/file.txt")
                )
                .unwrap_err()
                .kind(),
            io::ErrorKind::PermissionDenied
        );
    }
Input 8: outline src/authoring/tools.rs mod[tests]/fn[search_uses_the_validated_target_when_symlinks_precede_parent_components]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[search_uses_the_validated_target_when_symlinks_precede_parent_components]
  • Kind: fn
  • src/authoring/tools.rs:2705–2730
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.ci.input_containment`
    #[cfg(unix)]
    #[test]
    fn search_uses_the_validated_target_when_symlinks_precede_parent_components() {
        let root = project();
        fs::create_dir_all(root.path().join("actual/nested")).unwrap();
        fs::write(root.path().join("actual/needle.txt"), "actual needle\n").unwrap();
        fs::write(root.path().join("needle.txt"), "wrong needle\n").unwrap();
        std::os::unix::fs::symlink(root.path().join("actual/nested"), root.path().join("alias"))
            .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let result = dispatch(
            &sources,
            "ripgrep",
            &json!({"path":"alias/../needle.txt", "pattern":"needle", "context":0}),
        )
        .unwrap();
        assert_eq!(matched(&result).len(), 1);
        assert_eq!(matched(&result)[0]["file"], "actual/needle.txt");
        assert_eq!(
            matched(&result)[0]["lines"],
            json!([{"text": "actual needle", "matched": true}])
        );
    }
Input 10: outline src/evidence.rs mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors]
  • Kind: fn
  • src/evidence.rs:2566–2667
    // {test}`requirements.integration.report_api`
    // {test}`requirements.ci.errors`
    // {test}`requirements.ci.diagnostics`
    // {test}`requirements.ci.input_containment`
    // {test}`requirements.ci.definition_errors`
    // {test}`requirements.ci.orphans`
    // {test}`requirements.ci.coverage`
    // {test}`requirements.ci.determination`
    // {test}`requirements.ci.outline_inputs`
    // {test}`requirements.ci.requirement_text`
    // {test}`requirements.ci.schema`
    #[test]
    fn collects_missing_orphan_format_false_and_changed_line_errors() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/requirements.md"),
            "# Requirements\n\n:::{req} one\nFirst.\n:::\n\n:::{req} two\nSecond.\n:::\n\n:::{req} three\nThird.\n:::\n\n:::{req} one\nDuplicate.\n:::\n\n:::{req} empty\n  \n:::\n",
        )
        .unwrap();
        fs::write(
            temp.path().join("evidence/requirements.one.json"),
            json!({
                "requirement": "Old text.",
                "determination": false,
                "rationale": "Work remains.",
                "inputs": [
                    {
                        "file": "src/main.rs",
                        "item": "",
                        "hash": "0".repeat(64)
                    },
                    {
                        "file": "",
                        "item": 0,
                        "hash": "ABC"
                    },
                    {
                        "file": "src/main.rs",
                        "item": "fn[missing]",
                        "hash": "0".repeat(64)
                    },
                    {
                        "file": "src/main.rs",
                        "line_start": 1,
                        "line_end": 1,
                        "text": ["// first line"]
                    },
                    {
                        "requirements": "requirements.two",
                        "matches": ["requirements.two"],
                        "text": [1]
                    }
                ]
            })
            .to_string(),
        )
        .unwrap();
        fs::write(
            temp.path().join("evidence/requirements.three.json"),
            json!({"requirement": 3, "inputs": {}}).to_string(),
        )
        .unwrap();
        fs::write(
            temp.path().join("evidence/ghost.json"),
            json!({
                "requirement": "Ghost.",
                "determination": true,
                "rationale": "A valid but orphaned file.",
                "inputs": []
            })
            .to_string(),
        )
        .unwrap();
        fs::write(temp.path().join("evidence/broken.json"), "{").unwrap();

        let report = validate_repository(temp.path()).unwrap();
        let errors = report.errors.join("\n");
        for detail in [
            "no matching requirement",
            "invalid JSON",
            "missing for requirement",
            "requirement text changed",
            "- Old text.",
            "+ First.",
            "determination is false",
            "inputs[0]: outline input changed: src/main.rs <root> (now lines 1-2) no longer has the recorded hash",
            "inputs[1]: file must be a nonempty path",
            "inputs[1]: item must be a string",
            "inputs[1]: hash must be a lowercase hexadecimal SHA-256 digest",
            "inputs[2]: src/main.rs: no outline node matches \"fn[missing]\"",
            "inputs[3]: unexpected field \"line_start\"",
            "inputs[3]: missing field \"item\"",
            "inputs[4]: text[0] must be a string",
            "requirement must be a string",
            "missing field \"determination\"",
            "inputs must be an array",
            "duplicate requirement requirements.one; first declared at md/requirements.md:3",
            "requirement requirements.empty has no text",
        ] {
            assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
        }
    }
Input 11: outline tests/commands.rs fn[status_applies_workspace_disallow_to_existing_evidence]
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.cli.status`
// {test}`requirements.authoring.deterministic_validation`
#[test]
fn status_applies_workspace_disallow_to_existing_evidence() {
    let temp = fixture();
    fs::write(
        temp.path().join("habeas.toml"),
        "version = 1\n[evidence]\nallow = ['src']\ndisallow = ['src/main.rs']\n",
    )
    .unwrap();
    let output = habeas(temp.path(), &["status", "requirements.ready"]);
    assert!(output.status.success(), "{output:?}");
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(
        text.contains("Invalid") && text.contains("disallowed"),
        "{text}"
    );
    assert!(text.contains("src/main.rs"), "{text}");
}
Input 12: 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}"
    );
}
Input 13: outline tests/evidence_boundaries.rs fn[symlinks_may_resolve_inside_but_not_to_a_sibling_with_the_same_prefix]
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.schema`
#[cfg(unix)]
#[test]
fn symlinks_may_resolve_inside_but_not_to_a_sibling_with_the_same_prefix() {
    use std::os::unix::fs::symlink;

    let temp = fixture();
    let root = temp.path().join("project");
    symlink(root.join("data.txt"), root.join("inside.txt")).unwrap();
    write_inputs(&root, vec![outline(&root, "inside.txt", "")]);
    assert!(validate_repository(&root).unwrap().errors.is_empty());

    let sibling = temp.path().join("project-sibling");
    fs::create_dir(&sibling).unwrap();
    fs::write(sibling.join("outside.rs"), "fn outside() {}\n").unwrap();
    symlink(sibling.join("outside.rs"), root.join("escape.rs")).unwrap();
    {
        let input = json!({"file":"escape.rs", "item":"fn[outside]", "hash":"0".repeat(64)});
        write_inputs(&root, vec![input]);
        let errors = validate_repository(&root).unwrap().errors.join("\n");
        assert!(
            errors.contains("escape.rs resolves outside the repository"),
            "{errors}"
        );
    }
}
Input 14: outline tests/evidence_boundaries.rs fn[definition_and_requirements_inputs_obey_containment_for_declaring_files]
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.schema`
#[test]
fn definition_and_requirements_inputs_obey_containment_for_declaring_files() {
    let temp = fixture();
    let root = temp.path().join("project");
    fs::create_dir(root.join("md/private")).unwrap();
    fs::write(
        root.join("md/private/terms.md"),
        ":::{req} secret\nSecret.\n:::\n\n:::{definition} term\n:phrase: term\n\nA term.\n:::\n",
    )
    .unwrap();
    let term = json!([
        ":::{definition} term",
        ":phrase: term",
        "",
        "A term.",
        ":::"
    ]);
    let inputs = vec![
        json!({"definition": "private.terms.term", "text": term}),
        json!({
            "requirements": "private.terms.*",
            "matches": ["private.terms.secret"],
            "text": [":::{req} secret", "Secret.", ":::"],
        }),
    ];
    write_inputs(&root, inputs.clone());
    let own_errors = |root: &Path| {
        validate_repository(root)
            .unwrap()
            .errors
            .into_iter()
            .filter(|error| error.starts_with("evidence/rules.ready.json"))
            .collect::<Vec<_>>()
    };
    assert!(own_errors(&root).is_empty(), "{:?}", own_errors(&root));

    fs::write(
        root.join("habeas.toml"),
        "version = 1\n[evidence]\ndisallow = ['md/private']\n",
    )
    .unwrap();
    let errors = own_errors(&root);
    assert_eq!(errors.len(), 2, "{errors:?}");
    assert!(errors[0].contains("inputs[0]") && errors[0].contains("disallowed"));
    assert!(errors[1].contains("inputs[1]") && errors[1].contains("disallowed"));
    assert!(
        errors
            .iter()
            .all(|error| error.contains("md/private/terms.md"))
    );
}
Input 15: outline tests/evidence_boundaries.rs fn[unreadable_and_missing_inputs_are_reported]
// {test}`requirements.ci.input_containment`
// {test}`requirements.configuration.evidence_paths`
#[cfg(unix)]
#[test]
fn unreadable_and_missing_inputs_are_reported() {
    use std::os::unix::fs::PermissionsExt;

    let temp = fixture();
    let root = temp.path().join("project");
    fs::write(root.join("locked.txt"), "secret\n").unwrap();
    let input = outline(&root, "locked.txt", "");
    fs::set_permissions(root.join("locked.txt"), fs::Permissions::from_mode(0o000)).unwrap();
    let missing = json!({"file": "gone.txt", "item": "", "hash": "0".repeat(64)});
    write_inputs(&root, vec![input, missing]);
    let errors = validate_repository(&root).unwrap().errors.join("\n");
    // A privileged user can read the file regardless of its mode.
    let unreadable = fs::read(root.join("locked.txt")).is_err();
    fs::set_permissions(root.join("locked.txt"), fs::Permissions::from_mode(0o644)).unwrap();
    assert!(
        errors.contains("inputs[1]: cannot open gone.txt"),
        "{errors}"
    );
    if unreadable {
        assert!(
            errors.contains("inputs[0]: cannot read locked.txt"),
            "{errors}"
        );
    }
}
Input 16: outline tests/evidence_boundaries.rs fn[configured_external_inputs_validate_and_remain_subject_to_freshness_and_disallow]
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.configuration.loading`
#[test]
fn configured_external_inputs_validate_and_remain_subject_to_freshness_and_disallow() {
    let temp = fixture();
    let root = temp.path().join("project");
    let external = temp.path().join("generated");
    fs::create_dir(&external).unwrap();
    let source = external.join("generated.rs");
    fs::write(&source, "pub fn generated() {}\n").unwrap();
    let external_toml = toml::Value::String(external.display().to_string());
    let config = format!("version = 1\n[evidence]\nallow = [{external_toml}]\n");
    fs::write(root.join("habeas.toml"), &config).unwrap();
    {
        let input = outline(&root, source.to_str().unwrap(), "fn[generated]");
        write_inputs(&root, vec![input]);
        fs::write(root.join("habeas.toml"), "version = 1\n").unwrap();
        assert!(
            validate_repository(&root)
                .unwrap()
                .errors
                .join("\n")
                .contains("outside the repository")
        );
        fs::write(root.join("habeas.toml"), &config).unwrap();
        let report = validate_repository(&root).unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
        fs::write(&source, "pub fn generated() { changed(); }\n").unwrap();
        assert!(
            validate_repository(&root)
                .unwrap()
                .errors
                .join("\n")
                .contains("outline input changed")
        );
        fs::write(&source, "pub fn generated() {}\n").unwrap();
        fs::write(
            root.join("habeas.toml"),
            format!("{config}disallow = [{external_toml}]\n"),
        )
        .unwrap();
        assert!(
            validate_repository(&root)
                .unwrap()
                .errors
                .join("\n")
                .contains("disallowed")
        );
    }
}
Input 17: outline tests/evidence_boundaries.rs fn[evidence_rejects_disallowed_ancestors_even_when_symlinks_target_allowed_sources]
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.outline_inputs`
#[cfg(unix)]
#[test]
fn evidence_rejects_disallowed_ancestors_even_when_symlinks_target_allowed_sources() {
    let temp = fixture();
    let root = temp.path().join("project");
    for directory in ["private", "public", "sub"] {
        fs::create_dir(root.join(directory)).unwrap();
    }
    // Every struct needs a reference under rust_item_coverage.
    let cite = "// {cite}`rules.ready`".to_owned();
    fs::write(
        root.join("public/source.rs"),
        format!("{cite}\npub struct Source;\n"),
    )
    .unwrap();
    std::os::unix::fs::symlink("../public", root.join("private/link")).unwrap();
    fs::write(
        root.join("habeas.toml"),
        "version = 1\n[evidence]\nallow = ['public']\ndisallow = ['private']\n",
    )
    .unwrap();
    for file in [
        "public/source.rs",
        "private/link/source.rs",
        "sub/../private/link/source.rs",
    ] {
        {
            let mut input = outline(&root, "public/source.rs", "struct[Source]");
            input["file"] = json!(file);
            write_inputs(&root, vec![input]);
            let errors =
                without_citation_reviews(validate_repository(&root).unwrap().errors).join("\n");
            if file == "public/source.rs" {
                assert!(errors.is_empty(), "{errors}");
            } else {
                assert!(errors.contains("disallowed"), "{file}: {errors}");
                assert!(errors.contains(file), "{errors}");
            }
        }
    }
}
Input 18: outline tests/evidence_boundaries.rs fn[discovered_external_cargo_outputs_validate_freshness_and_obey_disallow]
// {test}`requirements.authoring.generated_inputs`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.integration.report_api`
#[test]
fn discovered_external_cargo_outputs_validate_freshness_and_obey_disallow() {
    let temp = fixture();
    let root = temp.path().join("project");
    fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = 'fixture'\nversion = '0.1.0'\n",
    )
    .unwrap();
    fs::write(
        root.join("Cargo.lock"),
        "version = 4\n\n[[package]]\nname = 'fixture'\nversion = '0.1.0'\n",
    )
    .unwrap();
    fs::write(root.join("src/lib.rs"), "").unwrap();
    fs::create_dir(root.join(".cargo")).unwrap();
    let build = temp.path().join("external-build");
    let target = temp.path().join("external-target");
    fs::write(
        root.join(".cargo/config.toml"),
        format!(
            "[build]\nbuild-dir = {}\ntarget-dir = {}\n",
            toml::Value::String(build.display().to_string()),
            toml::Value::String(target.display().to_string()),
        ),
    )
    .unwrap();
    let out = build.join("debug/build/fixture-hash/out");
    fs::create_dir_all(&out).unwrap();
    fs::write(
        out.parent().unwrap().join("root-output"),
        out.to_str().unwrap(),
    )
    .unwrap();
    let generated = out.join("generated.rs");
    fs::write(&generated, "pub fn generated() {}\n").unwrap();
    {
        fs::write(root.join("habeas.toml"), "version = 1\n").unwrap();
        let input = outline(&root, generated.to_str().unwrap(), "fn[generated]");
        write_inputs(&root, vec![input]);
        let report = validate_repository(&root).unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
        fs::write(&generated, "pub fn generated() { changed(); }\n").unwrap();
        let errors = validate_repository(&root).unwrap().errors.join("\n");
        assert!(errors.contains("outline input changed"), "{errors}");
        fs::write(&generated, "pub fn generated() {}\n").unwrap();
        fs::write(
            root.join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['../external-build']\n",
        )
        .unwrap();
        let errors = validate_repository(&root).unwrap().errors.join("\n");
        assert!(errors.contains("disallowed"), "{errors}");
    }
    assert!(!target.exists(), "metadata must not run a build");
}

Referenced definitions

Input 2: requirements selection requirements.configuration.evidence_paths
:::{req} evidence_paths
The workspace `[evidence]` table MUST serialize EvidenceConfig. `allow` and
`disallow` MUST be arrays of nonempty literal paths, each naming a file or a
directory subtree. Relative paths MUST resolve from the selected `habeas.toml`
directory; absolute paths MUST be supported. These paths are not glob patterns.
An omitted `allow` or `disallow` MUST mean an empty array, and an absent
`[evidence]` table MUST mean both are empty, so only the default source-access
rules apply. No operation requires the section. The table has no user-file
counterpart, and these rules have no invocation options. This section refines
{impl}`requirements.configuration.feature_sections` for the evidence feature.

For authoring reads, a matching disallow MUST reject the path; otherwise a
matching allow MUST permit it; otherwise the default source-access rules MUST
apply. Explicit allow MUST override every default, including Git tracking,
project containment, generated-evidence exclusion, and automatic generated-output
rules. Disallow MUST win even when an allow or generated-output rule also matches.
Both the requested path and its resolved symlink target MUST be checked for
disallow, so an allowed alias cannot expose a disallowed target.

The same explicit disallow rules and external-path exceptions MUST apply when
resolving recorded evidence inputs, including ordinary validation. Validation MUST
remain independent of Git index membership: it
checks the recorded inputs' existence and contents. Loading path policy MUST NOT
resolve credentials or validate unused authoring settings.
:::
Input 3: requirements selection requirements.authoring.generated_inputs
:::{req} generated_inputs
Habeas MUST permit existing Cargo build-script output directories as an exception
to default Git tracking and containment restrictions. It MUST discover the Cargo
build directory using metadata and inspect existing build-script output records,
without running a build or executing build scripts. It MUST NOT treat its own
inherited `OUT_DIR` environment variable as the workspace's output directory.
Only discovered output directories and their contents MUST receive this default
permission; unrelated build artifacts MUST remain subject to ordinary rules.
Workspace disallow entries MUST override this permission.

Discovery MUST tolerate missing builds or unavailable metadata; callers MUST be
able to allow undiscovered outputs explicitly using `habeas.toml`. The model's
root directory listing MUST expose available generated-output directories,
including external ones. Generated inputs MUST use outline inputs and receive
ordinary freshness checks. Validation MUST NOT
invoke a build to materialize an input.
:::

Other sources

Input 1: requirements selection requirements.ci.input_containment
:::{req} input_containment
Every file named directly by an evidence input or resolved from its selector MUST resolve within the project root unless permitted by workspace path configuration or discovered Cargo generated-output policy. Symlink targets MUST follow the same policy. Validation MUST enforce explicit workspace disallow entries and report missing, unreadable, or excluded files. It MUST check existing generated inputs without running a build. {cite}`requirements.configuration.evidence_paths` {cite}`requirements.authoring.generated_inputs`
:::
Input 19: outline src/authoring/access.rs fn[resolve_evidence_file]
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.authoring.generated_inputs`
// {impl}`requirements.configuration.loading`
pub(crate) fn resolve_evidence_file(root: &Path, file: &str) -> io::Result<PathBuf> {
    let root = fs::canonicalize(root)?;
    let (requested, target) = resolve(&root, Path::new(file))?;
    let policy = PathPolicy::load(&root)?;
    policy.check_disallow(&root.join(file), &target)?;
    if (!requested.starts_with(&root) || !target.starts_with(&root))
        && !policy.allowed(&requested, &target)
        && !generated_roots(&root)
            .iter()
            .any(|directory| requested.starts_with(directory) && target.starts_with(directory))
    {
        return Err(denied(format!(
            "{file} resolves outside the repository without an allowed evidence path"
        )));
    }
    if !target.is_file() {
        return Err(io::Error::other(format!("{file} is not a project file")));
    }
    Ok(target)
}
Input 20: outline src/inputs.rs fn[check_project_file]
// {cite}`habeas:util`
fn check_project_file(root: &Path, file: &str) -> Result<PathBuf, String> {
    crate::authoring::access::resolve_evidence_file(root, file).map_err(|error| error.to_string())
}
Input 21: outline src/authoring/access.rs fn[resolve]
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.configuration.evidence_paths`
fn resolve(root: &Path, relative: &Path) -> io::Result<(PathBuf, PathBuf)> {
    if relative.as_os_str().is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "path must not be empty",
        ));
    }
    let joined = root.join(relative);
    let target = fs::canonicalize(&joined).map_err(|error| {
        io::Error::new(
            error.kind(),
            format!("cannot open {}: {error}", relative.display()),
        )
    })?;
    let requested = requested_location(&joined)?;
    Ok((requested, target))
}
Input 22: outline src/authoring/access.rs fn[generated_roots]
// {impl}`requirements.authoring.generated_inputs`
pub(crate) fn generated_roots(root: &Path) -> Vec<PathBuf> {
    let Ok(output) = Command::new("cargo")
        .current_dir(root)
        .args([
            "metadata",
            "--offline",
            "--locked",
            "--no-deps",
            "--format-version=1",
        ])
        .output()
    else {
        return Vec::new();
    };
    if !output.status.success() {
        return Vec::new();
    }
    let Ok(metadata) = serde_json::from_slice::<serde_json::Value>(&output.stdout) else {
        return Vec::new();
    };
    let Some(directory) = metadata
        .get("build_directory")
        .or_else(|| metadata.get("target_directory"))
        .and_then(serde_json::Value::as_str)
    else {
        return Vec::new();
    };
    let Ok(directory) = fs::canonicalize(directory) else {
        return Vec::new();
    };
    discover_generated_roots(&directory)
}
Input 23: outline src/authoring/access.rs fn[discover_generated_roots]
// {impl}`requirements.authoring.generated_inputs`
fn discover_generated_roots(build_root: &Path) -> Vec<PathBuf> {
    let mut roots = BTreeSet::new();
    let mut directories = vec![(build_root.to_owned(), 0)];
    while let Some((directory, depth)) = directories.pop() {
        let Ok(entries) = fs::read_dir(&directory) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if entry.file_name() == "root-output" {
                let Ok(text) = fs::read_to_string(&path) else {
                    continue;
                };
                let Ok(out) = fs::canonicalize(text.trim()) else {
                    continue;
                };
                let Ok(sibling) = fs::canonicalize(directory.join("out")) else {
                    continue;
                };
                if out == sibling && out.starts_with(build_root) && out.is_dir() {
                    roots.insert(out);
                }
            } else if depth < 4 && entry.file_type().is_ok_and(|kind| kind.is_dir()) {
                // Only inspect Cargo's profile[/triple]/build/<package> layout.
                if depth < 2
                    || directory.file_name().is_some_and(|name| name == "build")
                    || entry.file_name() == "build"
                {
                    directories.push((path, depth + 1));
                }
            }
        }
    }
    roots.into_iter().collect()
}
Input 24: outline src/authoring/access.rs impl[PathPolicy]
impl PathPolicy {
    // {impl}`requirements.configuration.evidence_paths`
    // {impl}`requirements.configuration.workspace_location`
    // {impl}`requirements.configuration.loading`
    pub(crate) fn load(root: &Path) -> io::Result<Self> {
        let Some(config) = crate::config::load_workspace_evidence(root)? else {
            return Ok(Self::default());
        };
        Ok(Self {
            allow: config
                .evidence
                .allow
                .iter()
                .map(|path| config.root.join(path))
                .collect(),
            disallow: config
                .evidence
                .disallow
                .iter()
                .map(|path| config.root.join(path))
                .collect(),
        })
    }

    // {impl}`requirements.configuration.evidence_paths`
    pub(crate) fn allowed(&self, requested: &Path, target: &Path) -> bool {
        self.allow
            .iter()
            .any(|rule| matches_rule(rule, requested, target))
    }

    // {impl}`requirements.configuration.evidence_paths`
    // {impl}`requirements.authoring.tool_descriptions.special_cases`
    pub(crate) fn check_disallow(&self, requested: &Path, target: &Path) -> io::Result<()> {
        if self.disallow.is_empty() {
            return Ok(());
        }
        // Retain locations traversed before a symlink redirects the request. Resolving
        // each parent also preserves filesystem semantics for subsequent `..`.
        let locations: Vec<_> = requested
            .ancestors()
            .filter_map(|path| requested_location(path).ok())
            .collect();
        if let Some(rule) = self.disallow.iter().find(|rule| {
            matches_rule(rule, requested, target)
                || locations
                    .iter()
                    .any(|path| matches_rule(rule, path, target))
        }) {
            return Err(denied(format!(
                "{} is disallowed by habeas.toml rule {}; update the workspace evidence policy before retrying",
                requested.display(),
                rule.display()
            )));
        }
        Ok(())
    }
}
Input 25: outline src/inputs.rs impl[OutlineCache]/fn[parse]
    // {impl}`requirements.authoring.outline_tool`
    /// Reads and parses a permitted file, or returns the cached result.
    pub(crate) fn parse(&self, root: &Path, file: &str) -> Arc<Result<ParsedSource, String>> {
        let key = root.join(file);
        if let Some(parsed) = self.files.lock().expect("outline cache lock").get(&key) {
            return parsed.clone();
        }
        let read = match self.overrides.get(file) {
            Some(content) => check_project_file(root, file).map(|path| (path, content.clone())),
            None => read_project_file(root, file),
        };
        let parsed = Arc::new(read.and_then(|(path, source)| {
            let redaction = Redaction::of_file(&path, &source);
            let profile = outline::profile_for_path(&path);
            let outline =
                outline::parse_redacted(profile, &source, &redaction).map_err(|error| {
                    format!("{file}: cannot parse {} source: {error}", profile.name)
                })?;
            Ok(ParsedSource {
                redacted: redaction.apply(&source).into_owned(),
                path: fs::canonicalize(&path).unwrap_or(path),
                source,
                outline,
            })
        }));
        self.files
            .lock()
            .expect("outline cache lock")
            .insert(key, parsed.clone());
        parsed
    }
Input 26: outline src/inputs.rs fn[read_project_file]
pub(crate) fn read_project_file(root: &Path, file: &str) -> Result<(PathBuf, String), String> {
    let path = check_project_file(root, file)?;
    let content =
        fs::read_to_string(&path).map_err(|error| format!("cannot read {file}: {error}"))?;
    Ok((path, content))
}
Input 27: outline src/evidence.rs fn[validate_outline_input]
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.ci.errors`
// {impl}`requirements.authoring.generated_inputs`
fn validate_outline_input(
    root: &Path,
    definitions: &BTreeMap<String, Declaration>,
    outlines: &OutlineCache,
    object: &Map<String, Value>,
    label: &str,
    errors: &mut Vec<String>,
) -> Option<ResolvedInput> {
    check_keys(object, &["file", "item", "hash"], label, errors);
    let file = string_field(object, "file", label, errors).and_then(|file| {
        if file.is_empty() {
            errors.push(format!("{label}: file must be a nonempty path"));
            None
        } else {
            Some(file)
        }
    });
    let item = string_field(object, "item", label, errors);
    let hash = string_field(object, "hash", label, errors).and_then(|hash| {
        if is_sha256_hex(hash) {
            Some(hash)
        } else {
            errors.push(format!(
                "{label}: hash must be a lowercase hexadecimal SHA-256 digest"
            ));
            None
        }
    });
    // Resolution needs the file and item but not the hash.
    let (Some(file), Some(item)) = (file, item) else {
        return None;
    };
    let selector = InputSelector::Outline {
        file: file.to_owned(),
        item: item.to_owned(),
    };
    let resolved = match selector.resolve(root, definitions, outlines) {
        Ok(resolved) => resolved,
        Err(error) => {
            errors.push(format!("{label}: {error}"));
            return None;
        }
    };
    if let (Some(node), Some(range), Some(hash)) = (&resolved.node, resolved.ranges.first(), hash)
        && node.hash != hash
    {
        errors.push(format!(
            "{label}: outline input changed: {file} {} (now lines {}-{}) no longer has the recorded hash",
            if item.is_empty() { "<root>" } else { item },
            range.line_start,
            range.line_end
        ));
    }
    Some(resolved)
}