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

Requirements index · View definition

evidence Valid

Requirement

Every source item outside the book that carries at least one {cite} reference other than a citation of habeas:util under cite requirements.references.util MUST have a citation review: an assessment of that item’s citations, recorded at evidence/citations/<file>/<selector>.json, where <file> is the item’s project-relative path, <selector> is its outline selector with every / and % percent-encoded, and the root node uses _root. The review MUST use the prompt defined by cite requirements.authoring.citation_prompt. For citations of project requirements and examples, the reviewer MUST assess whether the item should be re-checked or kept in sync when the cited definition changes, and whether the reference procedure of cite requirements.references.procedure calls for {impl} or {test} instead. For citations of built-ins, the reviewer MUST check the permitted reference roles and forms and any citation-review criteria stated in the built-in’s fixed text, using the item’s source and commentary. A permitted citation role alone MUST NOT suffice when the fixed text states additional criteria. Mandatory inputs, under cite requirements.authoring.mandatory_inputs, MUST be the item’s outline node, each cited declaration or built-in text, and the citations’ commentary. The record MUST contain the item’s file and selector, its citations by role, name, and commentary, determination, rationale, and inputs, with determinations under cite requirements.ci.outcomes. Validation MUST require a current, accepted review for every such item and report stale, missing, or orphaned reviews; a review MUST become stale when the item’s hash, a cited declaration, or its citations or their commentary change. Authoring with --all MUST include citation reviews, and habeas author citations:<file>#<selector> MUST author the review of the one item it names, under cite requirements.authoring.refresh, where omitting #<selector> names the file’s root node. A citation in a requirement or example declaration is reviewed as part of that definition’s own assessment instead.

Rationale

I judge the tests adequate. I did not request implementation source. I reviewed only the supplied test sources and did not run them.

How the tests map to the obligations in requirements.references.citation_review:

  • Required review and its location.
    • tests/references.rs#fn[citation_reviews_are_required_current_and_not_orphaned] asserts the “missing citation review” error for src/lib.rs fn[helper], with the path evidence/citations/src/lib.rs/fn[helper].json.
    • The same test asserts the missing-review error for the root node of notes.txt, with the path evidence/citations/notes.txt/_root.json.
    • It asserts that a citation in md/guide.md (the book) needs no review.
  • Percent-encoding. tests/references.rs#fn[review_paths_encode_selectors] checks that / becomes %2F. It also checks that an existing % is encoded first, so that %5B becomes %255B.
  • habeas:util exemption. tests/references.rs#fn[habeas_util_citations_cover_their_item_without_a_citation_review] covers four cases.
    • Inline, fenced and bare habeas:util citations need no review.
    • An item that mixes habeas:util with another citation still gets a missing-review error.
    • A habeas:util reference made with {impl} or {test} is rejected.
    • No evidence path is expected for habeas:util.
  • Staleness, validation and orphans. citation_reviews_are_required_current_and_not_orphaned covers each trigger the requirement names.
    • Changed commentary or citations produce “citations changed”. Reflowing whitespace does not.
    • An edited item produces “outline input changed”.
    • An edited cited declaration produces “input text changed”.
    • Missing item or declaration inputs, an unexpected field and malformed citations are each reported.
    • A FIXME determination is rejected because a citation review cannot accept it. A false determination is reported with its rationale. A valid true record yields no errors.
    • Removing the citations produces “orphaned citation review”.
    • src/authoring/batch.rs#fn[orphaned_citation_and_site_reviews_are_deleted] also covers deletion of orphaned reviews.
  • Prompt and mandatory inputs.
    • src/authoring/mod.rs#fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations] asserts the prompt text, the Item under review: line, the Citations to check: JSON payload (role, name, commentary), and the mandatory set. That set is the item node, the cited declaration and the built-in text, all present in the initial request. It also asserts the background and judgment-rules text, no leftover {{ placeholders, <root> for the root selector, the exactly-once submission rule, and the tool list.
    • The same test asserts the record fields file, item, citations, determination and inputs, and that a recorded review passes validation.
    • src/authoring/inputs.rs#fn[citation_review_inputs_combine_item_declarations_terms_and_built_ins_once] checks that inputs are deduplicated and that an unresolvable input aborts preparation.
    • src/authoring/mod.rs#fn[coverage_explanations_use_standard_citation_authoring_and_freshness] covers the built-in case. It asserts the built-in text is in the inputs and that the prompt contains the built-in criteria and “MUST NOT submit a FIXME”. It also asserts that a changed built-in commentary makes the review stale.
  • Authoring. tests/authoring_batch.rs#fn[batch_authors_citation_reviews_and_preserves_current_ones] covers four behaviors.
    • author --all authors the citation review, and the result validates.
    • A second run reports the review as skipped.
    • Naming the single review with citations:src/lib.rs#fn[helper] preserves a current review without a model or valid config, and --force re-authors it.
    • A single named review can be authored with --stdout. The omitted-selector (root) form is checked by the parse assertion in the src/authoring/mod.rs test above.
  • The two without_citation_reviews items are helpers that filter validation errors. They are harmless.

Weak spot: the record["rationale"] field is not asserted directly on an authored record. The validator exercises it through the “determination is false: ” message, so I don’t count it as a gap.

I found no unacknowledged gap.

Inputs

Tests

Input 8: outline src/authoring/batch.rs mod[tests]/fn[orphaned_citation_and_site_reviews_are_deleted]
    // {test}`requirements.authoring.batch`
    // {test}`requirements.references.site_review`
    // {test}`requirements.references.citation_review`
    #[test]
    fn orphaned_citation_and_site_reviews_are_deleted() {
        let temp =
            crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
        let root = temp.path();
        crate::sites::tests::write_review(root, "fn[check_two]", serde_json::json!({}));
        crate::sites::tests::write_review(root, "fn[other]", serde_json::json!({}));
        fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
        fs::write(
            root.join("evidence/citations/src/lib.rs/fn[gone].json"),
            "{}",
        )
        .unwrap();
        let inspection = crate::evidence::inspect_repository(root).unwrap();
        assert_eq!(
            delete_orphaned_reviews(root, &inspection).unwrap(),
            [
                "evidence/citations/src/lib.rs/fn[gone].json",
                "evidence/sites/requirements.rule/src/lib.rs/fn[other].json",
            ]
        );
        assert!(
            root.join("evidence/sites/requirements.rule/src/lib.rs/fn[check_two].json")
                .exists()
        );
        assert!(
            !root
                .join("evidence/sites/requirements.rule/src/lib.rs/fn[other].json")
                .exists()
        );
    }
Input 9: outline src/authoring/inputs.rs mod[tests]/fn[citation_review_inputs_combine_item_declarations_terms_and_built_ins_once]
  • File: src/authoring/inputs.rs
  • Selector: mod[tests]/fn[citation_review_inputs_combine_item_declarations_terms_and_built_ins_once]
  • Kind: fn
  • src/authoring/inputs.rs:1233–1296
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.references.citation_review`
    #[test]
    fn citation_review_inputs_combine_item_declarations_terms_and_built_ins_once() {
        let root = project();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} unit\n:phrase: unit\nA unit.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\nReady uses {}.\n:::\n\n:::{{req}} other\nOther uses {}.\n:::\n",
                role("term", "terms.unit"),
                role("term", "terms.unit")
            ),
        )
        .unwrap();
        let util = "// :::{cite} habeas:util\n// Glue.\n// :::\n".to_owned();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\n// {}\n// {}\n{util}{util}fn helper() {{}}\n",
                role("cite", "requirements.ready"),
                role("cite", "requirements.ready"),
                role("cite", "requirements.other"),
            ),
        )
        .unwrap();
        let sources =
            AssessmentSources::prepare_citation(root.path(), "src/lib.rs", "fn[helper]").unwrap();
        let inputs = sources.mandatory_inputs();
        // The item, each cited declaration once, the shared term once, and the
        // built-in text once.
        assert_eq!(inputs[0]["item"], "fn[helper]");
        let count =
            |key: &str, value: &str| inputs.iter().filter(|input| input[key] == value).count();
        assert_eq!(
            count("requirements", "requirements.ready"),
            1,
            "{inputs:#?}"
        );
        assert_eq!(
            count("requirements", "requirements.other"),
            1,
            "{inputs:#?}"
        );
        assert_eq!(count("definition", "terms.unit"), 1, "{inputs:#?}");
        assert_eq!(count("builtin", "habeas:util"), 1, "{inputs:#?}");
        assert_eq!(inputs.len(), 5, "{inputs:#?}");

        // An unresolvable mandatory input aborts preparation.
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['md/terms.md']\n",
        )
        .unwrap();
        let error = AssessmentSources::prepare_citation(root.path(), "src/lib.rs", "fn[helper]")
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("md/terms.md"), "{error}");
    }
Input 10: outline src/authoring/mod.rs mod[tests]/fn[coverage_explanations_use_standard_citation_authoring_and_freshness]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[coverage_explanations_use_standard_citation_authoring_and_freshness]
  • Kind: fn
  • src/authoring/mod.rs:4170–4259
    // {test}`requirements.test-coverage.check.exceptions.author`
    // {test}`requirements.references.citation_review`
    // {test}`requirements.authoring.citation_prompt`
    #[tokio::test]
    async fn coverage_explanations_use_standard_citation_authoring_and_freshness() {
        let project = inputs::tests::project();
        let source = "// :::{cite} habeas:coverage\n// Defensive invariant abort, inaccessible through the API.\n// :::\nfn helper() {}\n";
        fs::write(project.path().join("src/lib.rs"), source).unwrap();
        let subject = AuthoringSubject::parse("citations:src/lib.rs#fn[helper]");
        let mut sources = subject.sources(project.path()).unwrap();
        let mandatory = sources.mandatory_inputs().to_vec();
        assert_eq!(mandatory[0]["item"], "fn[helper]");
        assert!(
            mandatory[0]["text"].to_string().contains("fn helper() {}"),
            "{mandatory:?}"
        );
        assert!(
            mandatory[0]["hash"]
                .as_str()
                .is_some_and(|hash| hash.len() == 64),
            "{mandatory:?}"
        );
        assert!(mandatory.iter().any(|input| {
            input["builtin"] == "habeas:coverage"
                && input["text"][0]
                    .as_str()
                    .unwrap()
                    .contains("difficulty alone")
        }));
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(prompt.contains("Defensive invariant abort"));
        assert!(prompt.contains("For a built-in citation"));
        assert!(prompt.contains("MUST NOT submit a FIXME"));
        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
        let provider = RecordingProvider::new(vec![judgment(
            json!(true),
            "The supplied source and explanation support the citation.",
        )]);
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert_eq!(record["determination"], true);
        assert_eq!(record["citations"][0]["name"], "habeas:coverage");
        assert!(
            record["inputs"]
                .as_array()
                .unwrap()
                .iter()
                .any(|input| input["file"] == "src/lib.rs"
                    && input["item"] == "fn[helper]"
                    && input["hash"] == mandatory[0]["hash"]),
            "{record:?}"
        );
        assert!(
            record["inputs"]
                .as_array()
                .unwrap()
                .iter()
                .all(|input| input.get("builtin").is_none())
        );
        let path = subject.evidence_path(project.path());
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap();
        fs::write(
            project.path().join("src/lib.rs"),
            source.replace("inaccessible", "reachable"),
        )
        .unwrap();
        let definitions = crate::evidence::load_definitions(project.path()).unwrap();
        let mut errors = Vec::new();
        let references = crate::evidence::collect_references(project.path(), &mut errors);
        let outlines = crate::inputs::OutlineCache::default();
        let item =
            crate::citations::citation_items(project.path(), &definitions, &references, &outlines)
                .remove(&("src/lib.rs".into(), "fn[helper]".into()))
                .unwrap();
        crate::citations::validate_review(
            project.path(),
            &item.review_path(),
            &item,
            &definitions,
            &outlines,
            &mut errors,
        );
        assert!(
            errors
                .iter()
                .any(|error| error.contains("citations changed")),
            "{errors:?}"
        );
    }
Input 11: outline src/authoring/mod.rs mod[tests]/fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations]
  • Kind: fn
  • src/authoring/mod.rs:4261–4416
    // {test}`requirements.authoring.citation_prompt`
    // {test}`requirements.references.citation_review`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.authoring.judgment_rules`
    // {test}`requirements.authoring.adaptive`
    #[tokio::test]
    async fn citation_reviews_use_their_prompt_and_record_the_item_and_citations() {
        let project = inputs::tests::project();
        let cite = "{cite}`requirements.ready`";
        fs::write(
            project.path().join("src/lib.rs"),
            format!(
                "// {cite}\n// :::{{cite}} habeas:util\n// Formats output for the caller.\n// :::\nfn helper() {{}}\n"
            ),
        )
        .unwrap();
        let subject = AuthoringSubject::parse("citations:src/lib.rs#fn[helper]");
        assert_eq!(
            subject.evidence_path(project.path()),
            project
                .path()
                .join("evidence/citations/src/lib.rs/fn[helper].json")
        );
        let mut sources = subject.sources(project.path()).unwrap();
        assert!(!sources.has_applicable_fixme);
        let mandatory = sources.mandatory_inputs().to_vec();
        assert_eq!(mandatory[0]["file"], "src/lib.rs");
        assert_eq!(mandatory[0]["item"], "fn[helper]");
        assert_eq!(mandatory[1]["requirements"], "requirements.ready");
        assert_eq!(mandatory[2]["builtin"], "habeas:util");
        assert!(
            mandatory[2]["text"][0]
                .as_str()
                .unwrap()
                .starts_with("Cite this on an item that serves")
        );

        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
        let provider = RecordingProvider::new(vec![judgment(json!(true), "Both are sensible.")]);
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let prompts = provider.prompts();
        let expected: Vec<_> = tool_definitions_with("submit_judgment", false)
            .unwrap()
            .into_iter()
            .map(|tool| tool.name)
            .collect();
        assert_eq!(prompts[0].1, expected);
        let duplicate = json!({"determination":true,"rationale":"Both are sensible."});
        let duplicate_provider = ScriptedProvider {
            turns: vec![vec![
                ("submit_judgment", duplicate.clone()),
                ("submit_judgment", duplicate),
            ]],
            requests: RefCell::default(),
        };
        let mut duplicate_sources = subject.sources(project.path()).unwrap();
        assert!(
            assess(&duplicate_provider, &mut duplicate_sources, &mut usage)
                .await
                .unwrap_err()
                .to_string()
                .contains("exactly once")
        );
        let prompt = &prompts[0].0;
        assert!(
            prompt.contains("Review one source item's citations."),
            "{prompt}"
        );
        assert!(
            prompt.contains("Item under review: src/lib.rs fn[helper]"),
            "{prompt}"
        );
        assert!(
            prompt.contains("Formats output for the caller."),
            "{prompt}"
        );
        // The initial request carries the complete mandatory set.
        assert!(
            prompt.contains(mandatory[0]["hash"].as_str().unwrap()),
            "{prompt}"
        );
        assert!(prompt.contains("The project MUST be ready."), "{prompt}");
        assert!(
            prompt.contains("Cite this on an item that serves"),
            "{prompt}"
        );
        // Prompts are recorded as serialized requests.
        for background in [
            approved_text("habeas_background", 0),
            approved_text("habeas_background", 1),
            approved_text("judgment_rules", 0),
        ] {
            let background = serde_json::to_string(background).unwrap();
            assert!(prompt.contains(background.trim_matches('"')), "{prompt}");
        }
        assert!(!prompt.contains("{{"), "{prompt}");

        let citations = json!([
            {"role": "cite", "name": "requirements.ready", "commentary": ""},
            {"role": "cite", "name": "habeas:util", "commentary": "Formats output for the caller."}
        ]);
        let request: Value = serde_json::from_str(prompt).unwrap();
        // Compare the actual placeholder payload, rather than text which
        // could also appear independently in the mandatory source inputs.
        let user = request["chat_history"]
            .as_array()
            .unwrap()
            .iter()
            .find(|message| message["role"] == "user")
            .unwrap();
        let subject_text = user["content"][0]["text"].as_str().unwrap();
        let payload = subject_text
            .lines()
            .find_map(|line| line.strip_prefix("Citations to check: "))
            .unwrap();
        assert_eq!(serde_json::from_str::<Value>(payload).unwrap(), citations);
        assert_eq!(record["file"], "src/lib.rs");
        assert_eq!(record["item"], "fn[helper]");
        assert_eq!(record["citations"], citations);
        assert_eq!(record["determination"], true);
        let inputs = record["inputs"].as_array().unwrap();
        assert!(inputs.iter().all(|input| input.get("builtin").is_none()));
        assert_eq!(inputs.len(), 2, "{inputs:#?}");

        // The recorded review satisfies validation for its item.
        let path = subject.evidence_path(project.path());
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, record.to_string()).unwrap();
        let errors = crate::validate_repository(project.path()).unwrap().errors;
        assert!(
            !errors
                .iter()
                .any(|error| error.starts_with("evidence/citations/")),
            "{errors:#?}"
        );

        // A name without a selector reviews the file's root node.
        assert!(matches!(
            AuthoringSubject::parse("citations:notes.txt"),
            AuthoringSubject::Citation { file, item } if file == "notes.txt" && item.is_empty()
        ));

        // The root node's selector is shown as `<root>` in the prompt.
        fs::write(project.path().join("notes.txt"), format!("Notes. {cite}\n")).unwrap();
        let sources = AuthoringSubject::parse("citations:notes.txt")
            .sources(project.path())
            .unwrap();
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(
            prompt.contains("Item under review: notes.txt <root>"),
            "{prompt}"
        );
        assert!(!prompt.contains("{{"), "{prompt}");
    }
Input 12: outline src/evidence.rs mod[tests]/fn[without_citation_reviews]
    /// Validation errors other than citation reviews, for fixtures that test
    /// other checks.
    // {test}`requirements.references.citation_review`
    pub(crate) fn without_citation_reviews(errors: Vec<String>) -> Vec<String> {
        errors
            .into_iter()
            .filter(|error| !error.starts_with("evidence/citations/"))
            .collect()
    }
Input 13: outline tests/authoring_batch.rs fn[batch_authors_citation_reviews_and_preserves_current_ones]
// {test}`requirements.references.citation_review`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.refresh`
// {test}`requirements.references.coverage.report`
#[test]
fn batch_authors_citation_reviews_and_preserves_current_ones() {
    let server = Server::start(false, None);
    let fixture = Fixture::new(&server.endpoint, None);
    let source = fixture.project.join("src/lib.rs");
    let cite = "// {cite}`requirements.alpha`\n".to_owned();
    fs::write(
        &source,
        format!(
            "{}{cite}pub fn helper() {{}}\n",
            fs::read_to_string(&source).unwrap()
        ),
    )
    .unwrap();
    let output = fixture.run(&["author", "--all"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let subjects = server.subjects();
    assert_eq!(subjects.len(), 7, "{subjects:?}");
    assert!(
        subjects.contains(&"src/lib.rs fn[helper]".to_owned()),
        "{subjects:?}"
    );
    let review: Value = serde_json::from_slice(
        &fs::read(
            fixture
                .project
                .join("evidence/citations/src/lib.rs/fn[helper].json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(
        review["citations"],
        json!([{"role": "cite", "name": "requirements.alpha", "commentary": ""}])
    );
    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);

    let again = fixture.run(&["author", "--all"]);
    assert_eq!(
        String::from_utf8_lossy(&again.stdout).trim(),
        "0 authored; 7 skipped as current; 0 failed"
    );
    // A single named citation review that is current is kept under
    // `--missing`, the default, without a model or configuration.
    fs::write(&fixture.config, "not toml [").unwrap();
    let citation = "citations:src/lib.rs#fn[helper]";
    for args in [
        &["author", citation][..],
        &["author", citation, "--missing"],
    ] {
        let output = fixture.run(args);
        assert!(
            output.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            String::from_utf8_lossy(&output.stdout).trim(),
            format!(
                "{citation}: evidence is current; 1 skipped as current (use --force to reassess)"
            )
        );
    }
    assert_eq!(server.subjects().len(), 7, "no model was invoked");
    fs::write(&fixture.config, &fixture.config_text).unwrap();
    let path = fixture
        .project
        .join("evidence/citations/src/lib.rs/fn[helper].json");
    let mut before: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
    before["rationale"] = json!("CURRENT_RECORD_BEFORE_FORCE");
    fs::write(&path, before.to_string()).unwrap();
    let output = fixture.run(&["author", citation, "--force"]);
    assert!(output.status.success(), "{output:?}");
    assert_eq!(server.subjects().len(), 8);
    assert_eq!(
        serde_json::from_slice::<Value>(&fs::read(&path).unwrap()).unwrap()["item"],
        "fn[helper]"
    );
    assert!(
        !fs::read_to_string(&path)
            .unwrap()
            .contains("CURRENT_RECORD_BEFORE_FORCE")
    );
    let output = fixture.run(&["author", "--all", "--force"]);
    assert!(output.status.success(), "{output:?}");
    assert_eq!(server.subjects().len(), 15);
    assert_eq!(
        server
            .subjects()
            .iter()
            .filter(|s| *s == "src/lib.rs fn[helper]")
            .count(),
        3
    );
    // A citation review can also be named on its own.
    let single = fixture.run(&["author", "citations:src/lib.rs#fn[helper]", "--stdout"]);
    assert!(
        single.status.success(),
        "{}",
        String::from_utf8_lossy(&single.stderr)
    );
    let printed: Value = serde_json::from_slice(&single.stdout).unwrap();
    assert_eq!(printed["item"], "fn[helper]");
    // The coverage summary stays on stderr; stdout holds only the record.
    let stderr = String::from_utf8_lossy(&single.stderr);
    assert!(
        stderr.contains("nodes have coverage warnings. Use `status --coverage` to see them."),
        "{stderr}"
    );
    assert!(
        !stderr.contains("coverage history is incomplete"),
        "{stderr}"
    );
    assert_eq!(server.subjects().len(), 16);
}
Input 14: outline tests/evidence_boundaries.rs fn[without_citation_reviews]
/// Validation errors other than citation reviews.
// {test}`requirements.references.citation_review`
fn without_citation_reviews(errors: Vec<String>) -> Vec<String> {
    errors
        .into_iter()
        .filter(|error| !error.starts_with("evidence/citations/"))
        .collect()
}
Input 15: outline tests/references.rs fn[habeas_util_citations_cover_their_item_without_a_citation_review]
  • File: tests/references.rs
  • Selector: fn[habeas_util_citations_cover_their_item_without_a_citation_review]
  • Kind: fn
  • tests/references.rs:131–185
// {test}`requirements.references.util`
// {test}`requirements.references.citation_review`
// {test}`requirements.references.rust_item_coverage`
#[test]
fn habeas_util_citations_cover_their_item_without_a_citation_review() {
    let temp = project();
    let root = temp.path();
    let cr = role("cite");
    let source = format!(
        "// {cr}`habeas:util`\nfn inline() {{}}\n\n\
         // :::{cr} habeas:util\n// Formats output for its caller.\n// :::\nfn fenced() {{}}\n\n\
         // :::{cr} habeas:util\n// :::\nfn bare() {{}}\n\n\
         // {cr}`habeas:util`\n// {cr}`rules.ready`\nfn mixed() {{}}\n\n\
         // {im}`habeas:util`\nfn implemented() {{}}\n\n\
         // {te}`habeas:util`\nfn tested() {{}}\n",
        im = role("impl"),
        te = role("test"),
    );
    fs::write(root.join("src/lib.rs"), source).unwrap();
    let errors = errors(root);
    // Inline and fenced citations, with or without commentary, cover their
    // item and need no citation review.
    for item in ["inline", "fenced", "bare"] {
        assert!(!has(&errors, &format!("function {item} ")), "{errors:#?}");
        assert!(
            !has(
                &errors,
                &format!("missing citation review for src/lib.rs fn[{item}]")
            ),
            "{errors:#?}"
        );
    }
    // Another citation on the same item still needs its review.
    assert!(
        has(&errors, "missing citation review for src/lib.rs fn[mixed]"),
        "{errors:#?}"
    );
    // Only {cite} may reference it.
    for line in [17, 20] {
        let expected = format!(
            "src/lib.rs:{line}: built-in habeas:util may only be referenced with {}",
            role("cite")
        );
        assert!(has(&errors, &expected), "missing {expected:?}: {errors:#?}");
    }
    assert!(
        has(&errors, "function implemented has no recent coverage"),
        "{errors:#?}"
    );
    assert!(
        has(&errors, "function tested has no recent coverage"),
        "{errors:#?}"
    );
    assert!(!has(&errors, "evidence/habeas:util"), "{errors:#?}");
}
Input 16: outline tests/references.rs fn[citation_reviews_are_required_current_and_not_orphaned]
// {test}`requirements.references.citation_review`
// {test}`requirements.ci.outcomes`
// {test}`requirements.ci.orphans`
// {test}`requirements.ci.errors`
#[test]
fn citation_reviews_are_required_current_and_not_orphaned() {
    let temp = project();
    let root = temp.path();
    let cr = role("cite");
    let helper = |body: &str| {
        format!(
            "// {cr}`rules.ready`\n// :::{cr} habeas:util\n// {body}\n// :::\nfn helper() {{\n    work();\n}}\n"
        )
    };
    fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
    fs::write(root.join("notes.txt"), format!("See {cr}`rules.ready`.\n")).unwrap();
    // Citations in the book are reviewed with their declaration instead.
    fs::write(
        root.join("md/guide.md"),
        format!("# Guide\n\nSee {cr}`rules.ready`.\n"),
    )
    .unwrap();
    let path = "evidence/citations/src/lib.rs/fn[helper].json";
    let errors_for = |prefix: &str| {
        errors(root)
            .into_iter()
            .filter(|error| error.starts_with(prefix))
            .collect::<Vec<_>>()
    };
    let missing = errors_for("evidence/citations/");
    assert!(
        has(
            &missing,
            "evidence/citations/src/lib.rs/fn[helper].json: missing citation review for src/lib.rs fn[helper] at src/lib.rs:1"
        ),
        "{missing:#?}"
    );
    assert!(
        has(
            &missing,
            "evidence/citations/notes.txt/_root.json: missing citation review for notes.txt <root>"
        ),
        "{missing:#?}"
    );
    assert!(!has(&missing, "md/guide.md"), "{missing:#?}");

    let citations = json!([
        {"role": "cite", "name": "rules.ready", "commentary": ""},
        {"role": "cite", "name": "habeas:util", "commentary": "Formats output."}
    ]);
    fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
    let write = |record: Value| fs::write(root.join(path), record.to_string()).unwrap();
    write(review(root, citations.clone(), json!(true)));
    assert_eq!(errors_for(path), Vec::<String>::new());
    write(review(
        root,
        json!([null, {"role": "broken", "name": 7, "commentary": 8}]),
        json!(true),
    ));
    let malformed = errors_for(path);
    assert!(
        has(&malformed, "citations[0]: expected a JSON object"),
        "{malformed:?}"
    );
    assert!(
        has(&malformed, "citations[1]: unknown role"),
        "{malformed:?}"
    );
    assert!(
        has(&malformed, "citations[1]: name must be a string"),
        "{malformed:?}"
    );
    assert!(
        has(&malformed, "citations[1]: commentary must be a string"),
        "{malformed:?}"
    );

    // A citation review cannot accept a `{fixme}`, so FIXME is reported; a
    // false review is reported with its rationale.
    write(review(
        root,
        citations.clone(),
        json!({"FIXME": ["example/rules#4"]}),
    ));
    assert!(
        has(
            &errors_for(path),
            "determination is FIXME, but a citation review cannot accept a"
        ),
        "{:#?}",
        errors_for(path)
    );
    write(review(root, citations.clone(), json!(false)));
    assert!(
        has(
            &errors_for(path),
            "determination is false: The citations are sensible."
        ),
        "{:#?}",
        errors_for(path)
    );

    // Changed commentary or citations make the review stale; reflowing does not.
    write(review(root, citations.clone(), json!(true)));
    fs::write(root.join("src/lib.rs"), helper("Formats  output.")).unwrap();
    assert_eq!(errors_for(path), Vec::<String>::new());
    fs::write(root.join("src/lib.rs"), helper("Formats all output.")).unwrap();
    assert!(
        has(&errors_for(path), "citations changed"),
        "{:#?}",
        errors_for(path)
    );
    fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();

    // So do an edited item and an edited cited declaration.
    fs::write(
        root.join("src/lib.rs"),
        helper("Formats output.").replace("work()", "rest()"),
    )
    .unwrap();
    assert!(
        has(&errors_for(path), "outline input changed"),
        "{:#?}",
        errors_for(path)
    );
    fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
    fs::write(
        root.join("md/rules.md"),
        ":::{req} ready\nReady now.\n:::\n",
    )
    .unwrap();
    assert!(
        has(&errors_for(path), "input text changed"),
        "{:#?}",
        errors_for(path)
    );
    fs::write(root.join("md/rules.md"), ":::{req} ready\nReady.\n:::\n").unwrap();

    // The item and each cited declaration must be inputs.
    let mut record = review(root, citations.clone(), json!(true));
    record["inputs"] = json!([]);
    write(record);
    let found = errors_for(path);
    assert!(
        has(&found, "inputs must select the reviewed item"),
        "{found:#?}"
    );
    assert!(
        has(
            &found,
            "inputs must include the cited declaration rules.ready"
        ),
        "{found:#?}"
    );
    let mut record = review(root, citations.clone(), json!(true));
    record["extra"] = json!(1);
    write(record);
    assert!(has(&errors_for(path), "unexpected field \"extra\""));

    // Removing the citations orphans the review.
    write(review(root, citations, json!(true)));
    fs::write(
        root.join("src/lib.rs"),
        format!("// {}`rules.ready`\nfn helper() {{}}\n", role("impl")),
    )
    .unwrap();
    assert!(
        has(&errors_for(path), "orphaned citation review"),
        "{:#?}",
        errors_for(path)
    );
    // The review is not mistaken for misplaced definition evidence.
    assert!(!has(&errors(root), "no matching requirement or example"));
}
Input 17: outline tests/references.rs fn[review_paths_encode_selectors]
// {test}`requirements.references.citation_review`
#[test]
fn review_paths_encode_selectors() {
    let temp = project();
    let root = temp.path();
    let cr = role("cite");
    fs::write(
        root.join("src/lib.rs"),
        format!("struct Thing;\nimpl Thing {{\n    // {cr}`rules.ready`\n    fn run() {{}}\n}}\n"),
    )
    .unwrap();
    let slashed = errors(root);
    assert!(
        has(
            &slashed,
            "evidence/citations/src/lib.rs/impl[Thing]%2Ffn[run].json: missing citation review for src/lib.rs impl[Thing]/fn[run]"
        ),
        "{slashed:#?}"
    );

    // A `%` already in the selector is encoded before `/`, so it is not
    // mistaken for an encoded `/`.
    fs::write(
        root.join("src/lib.rs"),
        format!(
            "impl [u8; 4] {{
    // {cr}`rules.ready`
    fn edge() {{}}
}}
"
        ),
    )
    .unwrap();
    let encoded = errors(root);
    assert!(
        has(
            &encoded,
            "evidence/citations/src/lib.rs/impl[%255Bu8;%25204%255D]%2Ffn[edge].json: missing citation review for src/lib.rs impl[%5Bu8;%204%5D]/fn[edge]"
        ),
        "{encoded:#?}"
    );
}

Referenced definitions

Input 2: requirements selection requirements.references.util
:::{req} util
Habeas MUST provide the built-in `habeas:util` under
{cite}`requirements.references.builtin_definitions`, with this text:

> Cite this on an item that serves other code, including code outside the
> project such as a library calling a trait implementation it requires, and
> carries out no requirement or example itself: it has no obligations and no
> end-user-observable behavior of its own. A review that reaches it from a root judges what it does
> as part of that root.

Only `{cite}` MAY reference it, inline or fenced, with or without commentary. An
item whose only citations are of `habeas:util` MUST NOT need a citation review
under {cite}`requirements.references.citation_review`. A citation of
`habeas:util` MUST cover its item under
{cite}`requirements.references.rust_item_coverage`.
:::
Input 3: requirements selection requirements.authoring.citation_prompt
:::{req} citation_prompt
A citation review under {cite}`requirements.references.citation_review` MUST use
the same tools and exactly-once submission rule as other assessments and this
prompt, replacing `{{item_file}}`, `{{item_selector}}` (with `<root>` for the
root node), `{{citations}}` (the item's `{cite}` references as JSON with role,
name, and commentary), `{{habeas_background}}` and `{{reference_roles}}` under
{cite}`requirements.authoring.habeas_background`, `{{judgment_rules}}` under
{cite}`requirements.authoring.judgment_rules`, and `{{mandatory_inputs}}`, the
first block as its system prompt and the second as its subject message under
{cite}`requirements.authoring.prompt_parts`:

```text
# Task

Review one source item's citations. Your determination should be the one any
careful reviewer would reach from the same text and sources.

# Background: Habeas terms

{{habeas_background}}

{{reference_roles}}

# Your task

The mandatory inputs at the end contain the source item and the declarations
or fixed built-in text of its citations.

Assess each listed citation using the rules below. For citations of project
requirements and examples, decide whether the item implements part of a cited
requirement, not whether it does so correctly. Do not look for requirements or
examples the item does not cite, except as needed to assess a built-in's stated
citation criteria.

1. For citations of project requirements and examples, apply the reference
   procedure in order: if the item is a
   test designed to verify the cited requirement or example, it calls for
   {test}; otherwise, if it is a root of the cited definition's
   implementation as the reference roles describe, it calls for {impl};
   otherwise the citation is right if a change to the cited text could
   require changing the item, as when the item relies on behavior the text
   specifies or must agree with a form or value it defines; read the item's
   callers only when the item's own code does not settle this. A citation for
   which this calls for a different role, or for no reference at all, is a gap.
2. A citation of a requirement or example the item also references with {impl}
   or {test} is redundant and is a gap.
3. Treat commentary as context. For a built-in citation, check its permitted
   reference roles and forms and assess any citation-review criteria stated in
   its fixed text using the source and commentary.
   Read other sources when a stated reason relies on them.
   Record a gap when the stated criteria are not met.

# How to judge

{{judgment_rules}}

# Submitting

Choose true when your task finds no gap, and false otherwise. A citation review
MUST NOT submit a FIXME determination. You MUST end by calling submit_judgment
with determination and rationale until one submission is accepted.
A rejected submission does not complete the assessment. A judgment written in your
reply text is not accepted.
```

```text
# Subject

Item under review: {{item_file}} {{item_selector}}
Citations to check: {{citations}}
Judge against: the declarations or fixed built-in text it cites.

# Mandatory inputs

{{mandatory_inputs}}
```
:::
Input 4: requirements selection requirements.references.procedure
:::{req} procedure
A source item MUST choose its references under {cite}`requirements.references.roles`
for each candidate definition by this procedure, and MAY carry several:

1. If the item is a test designed to verify the definition, it MUST use
   `{test}`. A test helper a reviewer reaches by following such a test needs no
   reference to the definition.
2. Otherwise, if the item is a root of the definition's implementation, it
   MUST use `{impl}`. Code or a type carries out part of a definition when it
   makes a decision, performs a check, produces an output, or handles a case
   the definition specifies, or when the definition constrains its shape:
   fields, variants, serialized form, or validation. A root is such an item
   that no other item marked `{impl}` for the definition reaches, where an item
   reaches what it calls, the types it uses, and the implementations of trait
   methods it calls, and what those reach in turn. An item reached from a root
   needs no reference to the definition. An item that is a site of a distributed definition
   under {cite}`requirements.references.distributed` needs no reference to it;
   its site review covers it.
3. Otherwise, if the item should be re-checked or kept in sync when the
   definition changes, it MUST use `{cite}`.
4. If the item carries no reference after applying steps 1 to 3 to every
   definition and no assessment reads it under
   {cite}`requirements.references.rust_item_coverage`, it MUST cite the
   built-in `habeas:util` under {cite}`requirements.references.util` when it
   serves other code. An item that does neither carries out behavior that needs
   a requirement, or is not needed.

A `{fixme}` reference is added independently of this procedure, and MUST NOT
count as an item's reference for {cite}`requirements.references.rust_item_coverage`.
:::
Input 5: requirements selection requirements.authoring.mandatory_inputs
:::{req} mandatory_inputs
The harness MUST construct each assessment's mandatory input set by combining
the contributions specified by the requirements applicable to that subject and
its inputs. A requirement that contributes inputs MUST cite this requirement and
define which sources it contributes and when. The harness MUST include every
applicable contribution, deduplicate identical selections, and report
unresolvable mandatory inputs before inference. The complete set MUST be supplied
in the initial model request.
Generated output under project-root `evidence/`, including symlink aliases, MUST
be omitted from mandatory inputs when the default exclusion applies. An explicit
workspace allow MUST permit those selections; an explicit disallow MUST abort
under {cite}`requirements.authoring.read_denial.mandatory`.
:::
Input 6: requirements selection requirements.ci.outcomes
:::{req} outcomes
Every assessment judgment MUST use one of these outcomes, applying
{cite}`requirements.ci.review_criteria`:

- `true`: the reviewed tests adequately check a requirement or example under
  {cite}`requirements.ci.review_criteria`, including applicable testing
  exemptions and obligations assessed by a refining requirement or a site's
  own review. For a citation or site review, the review finds no gap under its
  own task.
- `false`: the sources do not support the subject, or information is missing,
  and the gaps are not all acknowledged by `{fixme}` references to it.
- `FIXME`: some aspects remain unmet or untested, and `{fixme}` references to
  the subject acknowledge every one of those gaps. The reviewer MUST explain the
  gaps and their source locations in the rationale and record their issue
  references or other identifying content from the supplied acknowledgments or
  inputs.

The JSON `determination` MUST be `true`, `false`, or an object containing exactly
`"FIXME"` with a nonempty array of nonempty strings, such as
`{"FIXME": ["example/queue#125", "rust-lang/rust#123"]}`. A gap MUST count as
acknowledged only by a `{fixme}` reference under
{cite}`requirements.references.roles` whose body describes that gap and that
references the assessed definition, or, for a site review, the distributed requirement from within that site; a citation review MUST NOT accept a `{fixme}`; a plain
`FIXME` comment, another marker such as `TODO`, or prose MUST NOT. The strings
MUST list each distinct issue reference the acknowledging `{fixme}` references
name in their option lines, as written after `:github:`, and, for a `{fixme}`
naming no issue, its body's words, without comment delimiters, joined by single
spaces. A `{fixme}` reference describing a gap that the review establishes no
longer exists within its task's scope MUST itself be treated as a gap. A reference
describing only an implementation defect MUST NOT create a test-adequacy gap or
require implementation review; it MUST acknowledge a testing gap only when its
body describes that same gap. A `{fixme}` naming a GitHub issue that
{cite}`requirements.authoring.github_reads` reports closed MUST NOT count as
acknowledging its gap. A FIXME judgment MUST be grounded in recorded evidence
inputs or, for an acknowledgment supplied under
{cite}`requirements.authoring.fixme_inputs`, the reference-set digest covering
that acknowledgment.
:::
Input 7: requirements selection requirements.authoring.refresh
:::{req} refresh
Every `habeas author` form MUST accept `--missing` and `--force`, which are
mutually exclusive; `--missing` MUST be the default. Under `--missing`, the
command MUST assess only the selected subjects whose evidence is missing, stale,
or invalid, and MUST preserve every current record without invoking a model,
including accepted FIXME judgments and current false judgments; a current false
judgment is reassessed only when its subject or inputs change or `--force` is
given. Under `--force`, the command MUST assess every selected subject. `--stdout`
MUST imply `--force`, because it writes no evidence. The command MUST report the
number of selected subjects it skipped as current. When no assessment is needed,
the command MUST succeed without resolving model configuration or credentials.
:::

Other sources

Input 1: requirements selection requirements.references.citation_review
:::{req} citation_review
Every source item outside the book that carries at least one `{cite}` reference
other than a citation of `habeas:util` under {cite}`requirements.references.util`
MUST have a citation review: an assessment of that item's citations, recorded at
`evidence/citations/<file>/<selector>.json`, where `<file>` is the item's
project-relative path, `<selector>` is its outline selector with every `/` and
`%` percent-encoded, and the root node uses `_root`. The review MUST use the
prompt defined by {cite}`requirements.authoring.citation_prompt`. For citations
of project requirements and examples, the reviewer MUST assess whether the item
should be re-checked or kept in sync when the cited definition changes, and
whether the reference procedure of
{cite}`requirements.references.procedure` calls for `{impl}` or `{test}` instead.
For citations of built-ins, the reviewer MUST check the permitted reference
roles and forms and any citation-review criteria stated in the built-in's fixed
text, using the item's source and commentary. A permitted citation role alone
MUST NOT suffice when the fixed text states additional criteria. Mandatory inputs,
under {cite}`requirements.authoring.mandatory_inputs`, MUST be the item's outline
node, each cited declaration or built-in text, and the citations' commentary. The record MUST contain the item's file and selector,
its citations by role, name, and commentary, `determination`, `rationale`, and
`inputs`, with determinations under {cite}`requirements.ci.outcomes`. Validation
MUST require a current, accepted review for every such item and report stale,
missing, or orphaned reviews; a review MUST become stale when the item's hash,
a cited declaration, or its citations or their commentary change. Authoring with
`--all` MUST include citation reviews, and `habeas author citations:<file>#<selector>`
MUST author the review of the one item it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>`
names the file's root node. A citation in a requirement or example
declaration is reviewed as part of that definition's own assessment instead.
:::