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.examples.authoring_inputs

Requirements index · View definition

evidence Valid

Requirement

When authoring evidence for a named example, its complete fenced declaration MUST be included in the mandatory input set defined by cite requirements.authoring.mandatory_inputs.

Rationale

Obligation. When the subject of an assessment is a named example, its complete fenced declaration MUST be in the mandatory input set.

Test. The only test marked for this requirement is src/authoring/inputs.rs#mod[tests]/fn[bundle_combines_direct_references_terms_and_current_existing_selectors]. The step that matters is where it prepares sources with the example requirements.case as the subject:

  • It calls AssessmentSources::prepare(root.path(), "requirements.case").
  • It asserts subject_kind is AssessmentKind::Definition(DefinitionKind::Example, false), so the subject really is an example.
  • It asserts mandatory_inputs()[0]["requirements"] == "requirements.case".
  • It asserts mandatory_inputs()[0]["text"] equals the full fenced declaration: the :::{example} case opening line, the body line containing the {cite} and {test} roles, and the closing :::.

This asserts the whole declaration, fences included, so a body-only or truncated input would fail. The same test also checks that the example is included when it is cited by another subject, though the requirement does not call for that.

Edge cases. The example in the test is a single-line body with no option lines. The requirement names no distinction for options or multi-line bodies. prepare supplies the subject’s input through the same InputSelector::Requirements path as requirements, with no example-specific transformation. So I do not treat these as gaps.

Other obligations. Deduplication and generated-evidence omission belong to requirements.authoring.mandatory_inputs. That requirement is cited only and is not reassessed here.

No gaps found.

Inputs

Implementation

Input 4: outline src/authoring/inputs.rs impl[AssessmentSources]/fn[prepare]
    // {impl}`requirements.authoring.invocation`
    // {impl}`requirements.authoring.mandatory_inputs`
    // {impl}`requirements.authoring_input`
    // {impl}`requirements.examples.authoring_inputs`
    // {impl}`requirements.examples.definition`
    // {impl}`requirements.references.authoring_inputs`
    // {impl}`requirements.definitions.authoring_inputs`
    // {impl}`requirements.authoring.source_tools`
    // {impl}`requirements.references.anchors`
    // {impl}`requirements.ci.reference_set`
    // {impl}`requirements.references.builtin_definitions`
    // {impl}`requirements.references.site_review`
    pub(crate) fn prepare(root: &Path, subject_name: &str) -> io::Result<Self> {
        let root = fs::canonicalize(root)?;
        let access = SourceAccess::load(&root)?;
        let definitions = load_definitions(&root)?;
        let subject = definitions
            .get(subject_name)
            .filter(|definition| definition.kind != DefinitionKind::Term)
            .ok_or_else(|| {
                io::Error::other(format!(
                    "{subject_name}: no matching requirement or named example"
                ))
            })?;
        let mut selectors = vec![InputSelector::Requirements {
            requirements: subject_name.to_owned(),
        }];

        let mut builtins = Vec::new();
        for (kind, name) in crate::text_references(&subject.text, true) {
            // A `{fixme}` in a declaration is a validation error when named
            // and is not an edge when unnamed.
            if matches!(kind, ReferenceKind::Term | ReferenceKind::Fixme) {
                continue;
            }
            // A built-in has no declaration; its fixed text is supplied instead.
            if let Some(builtin) = crate::builtins::builtin(&name) {
                if kind == ReferenceKind::Cite && !builtins.contains(&builtin.name) {
                    builtins.push(builtin.name);
                }
                continue;
            }
            if !definitions
                .get(&name)
                .is_some_and(|definition| definition.kind != DefinitionKind::Term)
            {
                return Err(io::Error::other(format!(
                    "{subject_name}: referenced subject {name} does not exist"
                )));
            }
            // Only `{cite}` leaves the subject; its `{impl}` and `{test}`
            // references point into it from the definitions it implements or tests.
            if kind != ReferenceKind::Cite {
                continue;
            }
            insert_selector(
                &mut selectors,
                InputSelector::Requirements { requirements: name },
            );
        }

        let outlines = OutlineCache::default();
        let mut errors = Vec::new();
        let files = discovered_files(&root, &mut errors);
        let references = crate::evidence::collect_references_with_progress(
            &root,
            &files,
            &mut errors,
            &mut |_| {},
        );
        if !errors.is_empty() {
            return Err(io::Error::other(errors.join("\n")));
        }
        let sites =
            crate::evidence::definition_sites(&root, subject_name, subject, &files, &outlines)?;
        // The same edges determine the reference contributions below.
        let reference_set = crate::evidence::reference_set_digest(
            &root,
            &outlines,
            subject_name,
            subject,
            &references,
            &sites,
        );
        // Tests contribute source. Refining declarations contribute their text;
        // implementation references outside declarations only locate code.
        for reference in references.iter().filter(|reference| {
            reference.name == subject_name
                && matches!(reference.kind, ReferenceKind::Impl | ReferenceKind::Test)
        }) {
            // Generated evidence, including symlink aliases, is omitted by
            // default rather than denied.
            if access.omit_generated_evidence(&root, &reference.file) {
                continue;
            }
            let selector = reference_selector(&root, &definitions, &outlines, reference)?;
            if reference.kind == ReferenceKind::Test
                || matches!(selector, InputSelector::Requirements { .. })
            {
                access.file(&root, &reference.file)?;
                insert_selector(&mut selectors, selector);
            }
        }

        // {impl}`requirements.references.anchors`
        for anchor in &subject.anchors {
            if access.omit_generated_evidence(&root, Path::new(&anchor.file)) {
                continue;
            }
            let selector = access
                .file(&root, Path::new(&anchor.file))
                .and_then(|_| {
                    anchor
                        .resolve(&root, &outlines)
                        .map(|_| anchor.selector())
                        .map_err(io::Error::other)
                })
                .map_err(|error| {
                    io::Error::new(
                        error.kind(),
                        format!(
                            "{subject_name}: cannot read :{}: anchor {}: {error}",
                            anchor.kind.label(),
                            anchor.label()
                        ),
                    )
                })?;
            if anchor.kind == ReferenceKind::Test {
                insert_selector(&mut selectors, selector);
            }
        }

        // {impl}`requirements.authoring.fixme_inputs`
        let mut acknowledgments = crate::evidence::fixme_acknowledgments(
            &root,
            &outlines,
            references.iter().filter(|reference| {
                reference.name == subject_name
                    && !crate::sites::in_own_site(&root, &sites, reference)
                    && !access.omit_generated_evidence(&root, &reference.file)
            }),
        )
        .map_err(io::Error::other)?;
        for acknowledgment in &acknowledgments {
            access.file(&root, Path::new(acknowledgment["file"].as_str().unwrap()))?;
        }

        // Existing evidence only decides whether to reassess; its inputs are
        // not carried forward.
        let mut mandatory = Vec::new();
        for selector in selectors {
            if !generated_evidence_selector(&root, &access, &selector) {
                mandatory.push(source_input(
                    &root,
                    &access,
                    &definitions,
                    &outlines,
                    &selector,
                )?);
            }
        }
        // The dependency collector receives bodies separately so Markdown and
        // non-Markdown reference-literal rules keep their source semantics.
        let dependencies = crate::terms::dependencies(
            &root,
            &definitions,
            &outlines,
            json!({"inputs": mandatory, "acknowledgments": acknowledgments})
                .as_object()
                .unwrap(),
            Some(&subject.text),
        )
        .map_err(io::Error::other)?;
        for definition in dependencies {
            let input = source_input(
                &root,
                &access,
                &definitions,
                &outlines,
                &InputSelector::Definition { definition },
            )?;
            if !mandatory.contains(&input) {
                mandatory.push(input);
            }
        }
        mandatory.extend(builtins.into_iter().map(builtin_input));
        let github = GithubIssues::from_env(&root);
        let issue_states = crate::github::input_issue_states(
            &root,
            &github,
            &references,
            &definitions,
            &mandatory,
        );
        let issue_names = acknowledgments.iter().flat_map(|acknowledgment| {
            crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap()).issues
        });
        let issues = github.read_all(issue_names);
        for acknowledgment in &mut acknowledgments {
            let parsed = crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap());
            let mut seen = std::collections::BTreeSet::new();
            acknowledgment["issues"] = parsed
                .issues
                .into_iter()
                .filter(|issue| seen.insert(issue.clone()))
                .map(|reference| {
                    let state = issues
                        .get(&reference)
                        .map_or("open", crate::github::IssueRead::state);
                    json!({"reference": reference, "state": state})
                })
                .collect();
        }
        Ok(Self {
            root,
            access,
            subject_name: subject_name.to_owned(),
            has_applicable_fixme: !acknowledgments.is_empty(),
            subject_kind: AssessmentKind::Definition(
                subject.kind,
                crate::structural::has_query_directive(subject),
            ),
            subject_text: subject.text.clone(),
            outlines,
            reference_set,
            acknowledgments,
            mandatory,
            issue_states,
            github,
            recorded: Vec::new(),
        })
    }

Tests

Input 3: outline src/authoring/inputs.rs mod[tests]/fn[bundle_combines_direct_references_terms_and_current_existing_selectors]
  • File: src/authoring/inputs.rs
  • Selector: mod[tests]/fn[bundle_combines_direct_references_terms_and_current_existing_selectors]
  • Kind: fn
  • src/authoring/inputs.rs:955–1058
    // {test}`requirements.authoring.complete_initial_bundle`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring_input`
    // {test}`requirements.examples.authoring_inputs`
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.definitions.authoring_inputs`
    // {test}`requirements.ci.authoring_inputs`
    // {test}`requirements.ci.reference_set`
    #[test]
    fn bundle_combines_direct_references_terms_and_current_existing_selectors() {
        let root = project();
        let terms = format!(
            ":::{{definition}} unit\n:phrase: unit\nA {}.\n:::\n\n:::{{definition}} value\n:phrase: value\nA {}.\n:::\n",
            role("term", "terms.value"),
            role("term", "terms.unit")
        );
        fs::write(root.path().join("md/terms.md"), terms).unwrap();
        let declarations = format!(
            ":::{{req}} ready\nReady uses {} and {}.\n:::\n\n:::{{req}} base\nBase cites {}.\n:::\n\n:::{{req}} distant\nDistant MUST work.\n:::\n\n:::{{example}} case\nReady example. {} {}\n:::\n",
            role("cite", "requirements.base"),
            role("term", "terms.unit"),
            role("cite", "requirements.distant"),
            role("cite", "requirements.ready"),
            role("test", "requirements.ready")
        );
        fs::write(root.path().join("md/requirements.md"), declarations).unwrap();
        fs::write(root.path().join("src/lib.rs"), format!("struct Thing;\nimpl Thing {{\n    // {}\n    fn run(&self) {{}}\n    fn unrelated(&self) {{}}\n}}\n// {}\nfn test_ready() {{}}\n", role("impl", "requirements.ready"), role("test", "requirements.ready"))).unwrap();
        fs::write(root.path().join("notes.txt"), "new source text\n").unwrap();
        fs::create_dir(root.path().join("evidence")).unwrap();
        fs::write(
            root.path().join("evidence/requirements.ready.json"),
            json!({
                "determination": false, "rationale": "old secret judgment",
                "inputs": [{"file":"notes.txt", "line_start":1, "line_end":1, "text":["old text"]}]
            })
            .to_string(),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        // The recorded digest covers the same `{impl}` and `{test}` edges.
        assert_eq!(
            sources.reference_set,
            crate::evidence::reference_set_digest_for(root.path(), "requirements.ready").unwrap()
        );
        let inputs = sources.mandatory_inputs();
        assert!(sources.recorded_inputs().is_empty());
        assert!(
            !inputs
                .iter()
                .any(|input| input["item"] == "impl[Thing]/fn[run]")
        );
        assert!(inputs.iter().any(|input| input["item"] == "fn[test_ready]"));
        assert!(!inputs.iter().any(|input| input["item"] == "impl[Thing]"));
        assert!(
            inputs
                .iter()
                .any(|input| input["requirements"] == "requirements.case")
        );
        assert!(
            inputs
                .iter()
                .any(|input| input["requirements"] == "requirements.base")
        );
        assert!(
            !inputs
                .iter()
                .any(|input| input["requirements"] == "requirements.distant")
        );
        assert_eq!(
            inputs
                .iter()
                .filter(|input| input.get("definition").is_some())
                .count(),
            2
        );
        // Earlier evidence inputs are not carried forward.
        assert!(!inputs.iter().any(|input| input["file"] == "notes.txt"));
        assert!(
            !serde_json::to_string(inputs)
                .unwrap()
                .contains("old secret judgment")
        );
        let example = AssessmentSources::prepare(root.path(), "requirements.case").unwrap();
        assert!(matches!(
            example.subject_kind,
            AssessmentKind::Definition(DefinitionKind::Example, false)
        ));
        assert_eq!(
            example.mandatory_inputs()[0]["requirements"],
            "requirements.case"
        );
        assert_eq!(
            example.mandatory_inputs()[0]["text"],
            json!([
                ":::{example} case",
                format!(
                    "Ready example. {} {}",
                    role("cite", "requirements.ready"),
                    role("test", "requirements.ready")
                ),
                ":::"
            ])
        );
    }

Referenced definitions

Input 2: 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`.
:::

Other sources

Input 1: requirements selection requirements.examples.authoring_inputs
:::{req} authoring_inputs
When authoring evidence for a named example, its complete fenced declaration
MUST be included in the mandatory input set defined by
{cite}`requirements.authoring.mandatory_inputs`.
:::