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.authoring.invocation

Requirements index · View definition

evidence Valid

Requirement

habeas author <full-name> [--config <name>] [--missing | --force] [--stdout] [-v|--verbose] MUST author the evidence of one existing requirement or named example in the current project, under cite requirements.authoring.refresh. It MUST report the selected subject, backend, model, evidence destination, and usage-record path on completion. The evidence destination MUST identify the evidence-file path by default or stdout when --stdout is selected. In stdout mode, the completion report and diagnostics MUST go to stderr. author-evidence MUST remain an alias for the single-subject command.

Rationale

The reviewed tests adequately cover requirements.authoring.invocation. I did not need to read implementation source.

Obligations and the tests that check them

  • Author one existing requirement or named example.
    • tests/authoring_cli.rs#fn[initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template] runs author for both a requirement and an example. It checks the evidence record: requirement is set for one and example for the other, and the other field is absent.
    • fn[author_rejects_unknown_subjects_and_conflicting_targets] checks that an unknown name fails and names the subject in stderr. It also checks that <name> --all is rejected with “cannot be used with” and leaves the evidence file unchanged.
  • Report subject, backend, model, evidence destination and usage path on completion.
    • fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] asserts that stdout starts with {SUBJECT}: ollama / {MODEL}. It also checks the Evidence: line, whose path canonicalizes to evidence/{SUBJECT}.json, and the Usage: line.
    • The initial-prompt test repeats the subject/backend/model check for both subject kinds. It also checks that the Evidence: path equals the project evidence file and that the Usage: path is a file.
  • Evidence destination is the path by default and stdout with --stdout. The default case is covered above. fn[stdout_emits_only_evidence_json_without_changing_project_files] asserts Evidence: stdout\n in stderr.
  • In stdout mode the report and diagnostics go to stderr. The stdout test parses the whole of stdout as the evidence JSON, so any report or diagnostic text on stdout would fail it. It asserts that stderr holds the {SUBJECT}: ollama / {MODEL} line, the Evidence: line and the usage path. It runs with and without --verbose and for every determination kind. It also checks that project evidence is unchanged, or not created when none existed.
  • --config <name>. fn[an_explicit_configuration_selects_the_nondefault_workspace_profile] selects a non-default profile. It asserts that the request used alternate-model and that usage records the model and backend.
  • -v and --verbose. fn[verbose_single_author_reports_only_false_rationale_without_source_inputs] exercises both spellings. The stdout test exercises --verbose together with --stdout.
  • author-evidence alias. It is used as a real invocation in the ollama CLI test, in the stdout test and in the batch test. The batch test also covers it with a named example.
  • --missing/--force and --stdout, under the cited requirements.authoring.refresh. tests/authoring_batch.rs#fn[missing_keeps_current_records_and_force_reassesses_every_selected_subject] covers the single-subject cases:
    • The default and explicit --missing skip a current record with no model call, and the report says “1 skipped as current”.
    • A bad configuration is not resolved when nothing needs assessment.
    • --missing --force and --stdout --missing are rejected.
    • --force and --stdout each reassess and invoke the model.
    • An invalid evidence file is repaired under --missing.

Gaps and open questions: none established. The tests/authoring_cli.rs#impl[Fixture] helpers (run, command) are reached from the marked tests. No {fixme} acknowledgments apply.

Inputs

Tests

Input 3: outline tests/authoring_batch.rs fn[missing_keeps_current_records_and_force_reassesses_every_selected_subject]
/// Under `--missing`, the default, a named subject or `--all` keeps current
/// records without a model or configuration; `--force` reassesses them, and
/// `--stdout` implies it.
// {test}`requirements.authoring.refresh`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.batch`
// {test}`requirements.references.coverage.report`
#[test]
fn missing_keeps_current_records_and_force_reassesses_every_selected_subject() {
    let server = Server::start(false, None);
    let fixture = Fixture::new(&server.endpoint, None);
    let first = fixture.run(&["author", "--all"]);
    assert!(
        first.status.success(),
        "{}",
        String::from_utf8_lossy(&first.stderr)
    );
    assert_eq!(server.subjects().len(), 6);
    let alpha = fixture.evidence("requirements.alpha");

    // Without a usable configuration, current records are still kept: no
    // configuration is resolved when nothing needs assessment.
    fs::write(&fixture.config, "not toml [").unwrap();
    // An item nothing reads is warned about even when nothing is assessed.
    fs::write(fixture.project.join("src/extra.rs"), "pub fn orphan() {}\n").unwrap();
    for args in [
        &["author", "requirements.alpha"][..],
        &["author", "requirements.alpha", "--missing"],
        &["author-evidence", "requirements.alpha_case"],
    ] {
        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!(
                "{}: evidence is current; 1 skipped as current (use --force to reassess)",
                args[1]
            )
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("nodes have coverage warnings. Use `status --coverage` to see them."),
            "{args:?}: {stderr}"
        );
        assert!(
            !stderr.contains("function orphan has no recent coverage"),
            "{stderr}"
        );
    }
    for args in [&["author", "--all"][..], &["author", "--all", "--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(),
            "0 authored; 6 skipped as current; 0 failed"
        );
    }
    assert_eq!(server.subjects().len(), 6, "no model was invoked");
    assert_eq!(fixture.usage().len(), 6);
    assert_eq!(fixture.evidence("requirements.alpha"), alpha);

    // `--missing` and `--force` are mutually exclusive, and `--stdout`
    // already implies `--force`.
    for args in [
        &["author", "requirements.alpha", "--missing", "--force"][..],
        &["author", "--all", "--missing", "--force"],
        &["author", "requirements.alpha", "--stdout", "--missing"],
    ] {
        let output = fixture.run(args);
        assert!(!output.status.success(), "{args:?}");
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("cannot be used with"),
            "{args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    assert_eq!(server.subjects().len(), 6);

    fs::write(&fixture.config, &fixture.config_text).unwrap();
    let forced = fixture.run(&["author", "requirements.alpha", "--force"]);
    assert!(
        forced.status.success(),
        "{}",
        String::from_utf8_lossy(&forced.stderr)
    );
    assert_eq!(
        server.subjects().last().unwrap(),
        "requirement requirements.alpha"
    );
    assert_eq!(server.subjects().len(), 7);
    let stdout = fixture.run(&["author", "requirements.alpha", "--stdout"]);
    assert!(
        stdout.status.success(),
        "{}",
        String::from_utf8_lossy(&stdout.stderr)
    );
    let printed: Value = serde_json::from_slice(&stdout.stdout).unwrap();
    assert_eq!(printed["requirement"], alpha["requirement"]);
    assert_eq!(server.subjects().len(), 8, "--stdout implies --force");
    let all = fixture.run(&["author", "--all", "--force"]);
    assert!(
        all.status.success(),
        "{}",
        String::from_utf8_lossy(&all.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&all.stdout).trim(),
        "6 authored; 0 skipped as current; 0 failed; policy once"
    );
    assert_eq!(server.subjects().len(), 14);
    fs::write(
        fixture.project.join("evidence/requirements.alpha.json"),
        "{invalid",
    )
    .unwrap();
    let repaired = fixture.run(&["author", "--all", "--missing"]);
    assert!(repaired.status.success(), "{repaired:?}");
    assert_eq!(server.subjects().len(), 15);
    assert_eq!(
        fixture.evidence("requirements.alpha")["determination"],
        true
    );

    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 4: outline tests/authoring_cli.rs struct[Fixture]
// {test}`requirements.authoring.invocation`
struct Fixture {
    temp: TempDir,
    project: PathBuf,
    config: PathBuf,
    state: PathBuf,
    evidence: PathBuf,
    original: String,
}
Input 5: outline tests/authoring_cli.rs impl[Fixture]/fn[run]
    // {test}`requirements.authoring.invocation`
    // {test}`requirements.authoring.deterministic_validation`
    fn run(&self, args: &[&str]) -> Output {
        self.command().args(args).output().unwrap()
    }
Input 6: outline tests/authoring_cli.rs impl[Fixture]/fn[command]
    // {test}`requirements.authoring.invocation`
    fn command(&self) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_habeas"));
        command
            .current_dir(&self.project)
            .env("XDG_CONFIG_HOME", &self.config)
            .env("XDG_STATE_HOME", &self.state)
            .env("APPDATA", &self.config)
            .env("LOCALAPPDATA", &self.state)
            .env("HOME", self.temp.path())
            .env("HABEAS_TEST_MODEL_KEY", AUTH)
            // No test contacts GitHub: nothing listens on this port, so
            // issues are unreachable and count as open.
            .env("HABEAS_GITHUB_API_URL", "http://127.0.0.1:9");
        command
    }
Input 7: outline tests/authoring_cli.rs fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]
// {test}`requirements.authoring.complete_initial_bundle`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.additional_read`
// {test}`requirements.authoring.acknowledged_gap`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.ci.review_criteria`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_inputs`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.invocation`
// {test}`requirements.configuration.serialization`
// {test}`requirements.ci.fixme_implementation_gap`
// {test}`requirements.authoring.finish_search.empty`
// {test}`requirements.authoring.finish_search.completion`
#[test]
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.reporting`
fn ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free() {
    let server = Server::start(vec![
        reply(vec![
            call("list", "list_files", json!({})),
            call(
                "search",
                "ripgrep",
                json!({"path":"extra.txt","pattern":"needle"}),
            ),
            call(
                "read",
                "habeas",
                json!({"file":"extra.txt","line_start":10}),
            ),
            call(
                "repeat",
                "habeas",
                json!({"file":"extra.txt","line_start":10}),
            ),
            call(
                "missing",
                "habeas",
                json!({"file":"absent.txt","line_start":1}),
            ),
        ]),
        json!({"__finish_latest_search":true}),
        reply(vec![call(
            "submit",
            "submit_judgment",
            json!({
            "determination":{"FIXME":["example/app#125"]},"rationale":"SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."}),
        )]),
    ]);
    let fixture = Fixture::new(&server.endpoint);
    let user_config = fixture.config.join("habeas/config.toml");
    let configured = fs::read(&user_config).unwrap();
    let output = fixture.run(&["author-evidence", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    // The user configuration, with its environment-resolved key, is not
    // rewritten.
    assert_eq!(fs::read(&user_config).unwrap(), configured);
    let requests = server.finish();
    assert_eq!(requests.len(), 3);
    for request in &requests {
        assert!(request.headers.starts_with("POST /api/chat HTTP/1.1\r\n"));
        assert!(request.headers.to_ascii_lowercase().contains(&format!(
            "authorization: bearer {}",
            AUTH.to_ascii_lowercase()
        )));
        assert_eq!(request.body["model"], MODEL);
        assert_eq!(request.body["options"]["temperature"], 0.25);
        assert_eq!(request.body["options"]["num_ctx"], 4096);
        assert_eq!(request.body["think"], false);
        assert_eq!(request.body["stream"], false);
    }
    let prompt = prompt_text(&requests[0].body);
    for text in [
        "Assess whether a project's tests adequately check one requirement.",
        REQUIREMENT,
        "SECRET_DEFINITION_TEXT",
        "fn ready_test()",
        "You MUST end by calling submit_judgment",
    ] {
        assert!(prompt.contains(text), "prompt missing {text}");
    }
    assert!(!prompt.contains("pub fn ready()"), "{prompt}");
    assert!(!prompt.contains("OLD_RATIONALE_MUST_NOT_REACH_MODEL"));
    let mut tools = requests[0].body["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|tool| tool["function"]["name"].as_str().unwrap())
        .collect::<Vec<_>>();
    tools.sort();
    assert_eq!(
        tools,
        [
            "ast_grep",
            "finish_search",
            "github",
            "habeas",
            "list_files",
            "next_page",
            "outline",
            "references",
            "ripgrep",
            "submit_judgment"
        ]
    );
    let results = requests[1].body["messages"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|message| message["role"] == "tool")
        .collect::<Vec<_>>();
    assert_eq!(results.len(), 5);
    assert!(results.iter().any(|message| {
        message["content"]
            .as_str()
            .unwrap()
            .contains("SECRET_SOURCE_PAYLOAD")
    }));
    assert!(
        results
            .iter()
            .any(|message| message["content"].as_str().unwrap().contains("absent.txt"))
    );

    let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
    assert_eq!(
        evidence["determination"],
        json!({"FIXME":["example/app#125"]})
    );
    assert_eq!(
        evidence["rationale"],
        "SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."
    );
    assert_eq!(evidence["requirement"], REQUIREMENT);
    let inputs = evidence["inputs"].as_array().unwrap();
    assert!(
        inputs
            .iter()
            .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready_test]"),
        "{inputs:#?}"
    );
    // The acknowledgment reaches the model as metadata, without the
    // containing implementation. Its body is protected by the reference set.
    assert!(prompt.contains(":github: example/app#125"));
    assert!(prompt.contains("One acknowledged gap."));
    // GitHub is unreachable, so the issue is supplied as open, but the state
    // is not recorded.
    assert!(
        prompt.contains("\"reference\": \"example/app#125\"")
            && prompt.contains("\"state\": \"open\""),
        "{prompt}"
    );
    assert!(!evidence.to_string().contains("github_issues"));
    assert!(!fixture.usage().to_string().contains("github_issues"));
    assert!(
        !inputs
            .iter()
            .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready]"),
        "{inputs:#?}"
    );
    // CI accepts the FIXME judgment: its evidence has no validation error.
    let report = habeas::validate_repository(&fixture.project).unwrap();
    let label = format!("evidence/{SUBJECT}.json");
    assert!(
        !report.errors.iter().any(|error| error.contains(&label)),
        "{:#?}",
        report.errors
    );
    // The same record with a false determination is rejected.
    let mut rejected = evidence.clone();
    rejected["determination"] = json!(false);
    let accepted = fs::read(&fixture.evidence).unwrap();
    fs::write(&fixture.evidence, rejected.to_string()).unwrap();
    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(
        report.errors.iter().any(|error| error.contains(&label)),
        "{:#?}",
        report.errors
    );
    fs::write(&fixture.evidence, accepted).unwrap();
    assert!(
        inputs
            .iter()
            .any(|input| input["definition"] == "terms.readiness")
    );
    let extra = inputs
        .iter()
        .filter(|input| input["file"] == "extra.txt")
        .collect::<Vec<_>>();
    // The search only locates lines and records nothing; the reads cover
    // lines 10-12, one plain-text line node each, and the repeated delivery
    // is recorded once, by selector and hash only.
    assert_eq!(
        extra,
        habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 10, 12)
            .unwrap()
            .iter()
            .collect::<Vec<_>>(),
        "repeated delivery is deduplicated in evidence"
    );
    assert!(
        !evidence["inputs"]
            .to_string()
            .contains("SECRET_SOURCE_PAYLOAD")
    );
    assert!(
        !inputs
            .iter()
            .any(|input| input["file"] == "absent.txt" || input["file"] == ".")
    );

    let usage = fixture.usage();
    assert_eq!(usage["outcome"], "completed");
    assert_eq!(usage["determination"], "FIXME");
    assert_eq!(usage["evidence_written"], true);
    assert_eq!(usage["request_count"], 3);
    assert_eq!(usage["tool_call_count"], 7);
    assert_eq!(usage["tool_calls"]["habeas"], 3);
    assert_eq!(usage["tool_failures"]["habeas"], 1);
    // The directory listing counts as a tool call but is not an input.
    assert_eq!(usage["tool_calls"]["list_files"], 1);
    assert_eq!(usage["tool_calls"]["ripgrep"], 1);
    assert_eq!(usage["tool_calls"]["finish_search"], 1);
    let usage_inputs = usage["inputs"].as_array().unwrap();
    assert!(
        !usage_inputs
            .iter()
            .any(|input| input["origin"] == "list_files"),
        "{usage_inputs:?}"
    );
    // Search snippets count toward usage, without becoming evidence inputs.
    assert!(
        usage_inputs.iter().any(|input| input["origin"] == "ripgrep"
            && input["kind"] == "search"
            && input["bytes"].as_u64().unwrap() > 0
            && input["lines"].as_u64().unwrap() > 0),
        "{usage_inputs:?}"
    );
    assert!(
        usage_inputs
            .iter()
            .any(|input| input["origin"] == "habeas" && input["unique"] == true),
        "{usage_inputs:?}"
    );
    assert_eq!(usage["tokens"]["input"], 33);
    assert_eq!(usage["tokens"]["output"], 21);
    assert_eq!(usage["tokens"]["complete"], true);
    assert!(
        usage["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .any(|input| input["origin"] == "habeas"
                && input["unique"] == false
                && input["sent_in_request"] == 1)
    );
    assert!(
        usage["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .any(|input| input["origin"] == "mandatory"
                && input["kind"] == "definition"
                && input["bytes"].as_u64().unwrap() > 0)
    );
    let serialized = usage.to_string();
    for secret in [
        "SECRET_REQUIREMENT_TEXT",
        "SECRET_DEFINITION_TEXT",
        "SECRET_SOURCE_PAYLOAD",
        "SECRET_RATIONALE",
        AUTH,
        "#125",
    ] {
        assert!(
            !serialized.contains(secret),
            "usage contains source or credential content: {secret}"
        );
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains(MODEL) && stdout.contains("Evidence:") && stdout.contains("Usage:"));
    // By default the report names the subject and backend and identifies the
    // evidence file it wrote.
    assert!(
        stdout.starts_with(&format!("{SUBJECT}: ollama / {MODEL}")),
        "{stdout}"
    );
    let evidence = stdout
        .lines()
        .find_map(|line| line.strip_prefix("Evidence: "))
        .unwrap();
    assert!(
        evidence.ends_with(&format!("evidence/{SUBJECT}.json")),
        "{stdout}"
    );
    assert_eq!(
        fs::canonicalize(evidence).unwrap(),
        fs::canonicalize(fixture.project.join(format!("evidence/{SUBJECT}.json"))).unwrap()
    );
}
Input 8: outline tests/authoring_cli.rs fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.documentation`
fn authoring_uses_nearest_workspace_configuration_without_a_user_file() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination":true,"rationale":"The supplied sources support the subject."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
    fs::write(
        fixture.project.join("habeas.toml"),
        "version = 1\n[authoring]\ndefault = 'missing-parent-choice'\n",
    )
    .unwrap();
    let nested = fixture.project.join("src/nested");
    fs::create_dir(&nested).unwrap();
    let workspace = nested.join("habeas.toml");
    fs::write(
        &workspace,
        format!(
            "version = 1\n[authoring]\ndefault = 'workspace'\n[authoring.configs.workspace]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'workspace-model'\nendpoint = '{}'\napi_key = 'WORKSPACE_LITERAL_KEY'\n",
            server.endpoint
        ),
    )
    .unwrap();
    let configurations = [fixture.project.join("habeas.toml"), workspace.clone()];
    let before = configurations
        .iter()
        .map(|path| fs::read(path).unwrap())
        .collect::<Vec<_>>();
    let output = fixture
        .command()
        .current_dir(&nested)
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    // Running the configured feature rewrites neither configuration file,
    // and creates no user configuration.
    for (path, before) in configurations.iter().zip(&before) {
        assert_eq!(&fs::read(path).unwrap(), before, "{}", path.display());
    }
    assert!(!fixture.config.join("habeas/config.toml").exists());
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].body["model"], "workspace-model");
    assert!(requests[0].headers.contains("WORKSPACE_LITERAL_KEY"));
    assert!(
        !requests[0]
            .body
            .to_string()
            .contains("WORKSPACE_LITERAL_KEY")
    );
    let usage = fixture.usage();
    assert_eq!(usage["model"], "workspace-model");
    for text in [
        usage.to_string(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    ] {
        assert!(!text.contains("WORKSPACE_LITERAL_KEY"), "{text}");
    }
}
Input 9: outline tests/authoring_cli.rs fn[an_explicit_configuration_selects_the_nondefault_workspace_profile]
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.configuration`
#[test]
fn an_explicit_configuration_selects_the_nondefault_workspace_profile() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination":true,"rationale":"The supplied sources support the subject."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
    let nested = fixture.project.join("src/nested");
    fs::create_dir(&nested).unwrap();
    fs::write(nested.join("habeas.toml"), format!(
        "version = 1\n[authoring]\ndefault = 'default'\n[authoring.configs.default]\nbackend = 'ollama'\nmodel = 'WRONG_DEFAULT_MODEL'\nendpoint = 'http://127.0.0.1:9'\n[authoring.configs.alternate]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'alternate-model'\nendpoint = '{}'\napi_key = 'ALTERNATE_TEST_KEY'\n", server.endpoint
    )).unwrap();
    let output = fixture
        .command()
        .current_dir(&nested)
        .args(["author", SUBJECT, "--config", "alternate", "--force"])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].body["model"], "alternate-model");
    assert!(requests[0].headers.contains("ALTERNATE_TEST_KEY"));
    assert_eq!(fixture.usage()["model"], "alternate-model");
    assert_eq!(fixture.usage()["backend"], "ollama");
}
Input 10: outline tests/authoring_cli.rs fn[initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template]
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.prompt_parts`
// {test}`requirements.authoring.fixme_inputs`
// {test}`requirements.authoring.invocation`
#[test]
fn initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template() {
    let template = approved_text("initial_prompt", 0);
    let subject_template = approved_text("initial_prompt", 1);
    for (subject, kind) in [
        (SUBJECT, "requirement"),
        ("requirements.ready_case", "example"),
    ] {
        let server = Server::start(vec![reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination":true,"rationale":"covered"}),
        )])]);
        let fixture = Fixture::new(&server.endpoint);
        fs::write(
            fixture.project.join("md/requirements.md"),
            format!(
                ":::{{req}} ready\n{REQUIREMENT}\n:::\n\n:::{{example}} ready_case\nCalling ready succeeds. {{cite}}`requirements.ready`\n:::\n"
            ),
        )
        .unwrap();
        let output = fixture.run(&["author", subject]);
        assert!(output.status.success(), "{output:?}");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.starts_with(&format!("{subject}: ollama / {MODEL}")),
            "{stdout}"
        );
        let evidence_path = stdout
            .lines()
            .find_map(|line| line.strip_prefix("Evidence: "))
            .unwrap();
        assert_eq!(
            std::path::Path::new(evidence_path),
            fixture.project.join(format!("evidence/{subject}.json"))
        );
        let record: Value = serde_json::from_slice(&fs::read(evidence_path).unwrap()).unwrap();
        let field = if kind == "requirement" {
            "requirement"
        } else {
            "example"
        };
        let other = if kind == "requirement" {
            "example"
        } else {
            "requirement"
        };
        assert!(record.get(other).is_none(), "{record}");
        assert_eq!(
            record[field],
            if kind == "requirement" {
                REQUIREMENT
            } else {
                "Calling ready succeeds. {cite}`requirements.ready`"
            }
        );
        let usage_path = stdout
            .lines()
            .find_map(|line| line.strip_prefix("Usage: "))
            .unwrap();
        assert!(std::path::Path::new(usage_path).is_file(), "{stdout}");
        let requests = server.finish();
        let (system, prompt) = opening(&requests[0].body);

        let task = if kind == "requirement" {
            format!(
                "{}\n{}",
                approved_text("requirement_task", 0),
                approved_text("testing_bar", 0)
            )
        } else {
            approved_text("example_task", 0).to_owned()
        };
        // Apart from the substitutions, the system prompt is the first block
        // as written, with nothing that names the subject.
        let expected = template
            .replace("{{subject_kind}}", kind)
            .replace(
                "{{habeas_background}}",
                approved_text("habeas_background", 0),
            )
            .replace("{{reference_roles}}", approved_text("habeas_background", 1))
            .replace("{{subject_task}}", &task)
            .replace("{{judgment_rules}}", approved_text("judgment_rules", 0));
        assert!(!expected.contains("{{"), "{expected}");
        assert_eq!(system, expected);
        assert!(!system.contains(subject), "{system}");
        let acknowledgments: Value = serde_json::from_str(
            prompt
                .split_once("# Acknowledgments\n\n")
                .unwrap()
                .1
                .split_once("\n\n# Mandatory inputs")
                .unwrap()
                .0,
        )
        .unwrap();
        if kind == "requirement" {
            assert_eq!(
                acknowledgments,
                json!([{
                    "body": ":github: example/app#125\n One acknowledged gap.",
                    "file": "src/lib.rs",
                    "issues": [{"reference": "example/app#125", "state": "open"}],
                    "item": "fn[ready]",
                }])
            );
        } else {
            assert_eq!(acknowledgments, json!([]));
        }
        let (before, after) = subject_template.split_once("{{mandatory_inputs}}").unwrap();
        // The subject is not distributed, so its distributed task is empty.
        let before = before
            .replace("{{subject_kind}}", kind)
            .replace("{{subject_name}}", subject)
            .replace("{{distributed_task}}", "")
            .replace(
                "{{acknowledgments}}",
                &serde_json::to_string_pretty(&acknowledgments).unwrap(),
            );
        assert!(
            before.contains(&format!("\nSubject: {kind} {subject}\n")),
            "{before}"
        );
        assert!(!before.contains("{{") && !after.contains("{{"));
        // Apart from the substitutions, the subject message is the second
        // block as written.
        assert!(prompt.starts_with(&before), "{prompt}");
        assert!(prompt.ends_with(after), "{prompt}");
        let rendered = &prompt[before.len()..prompt.len() - after.len()];

        // The mandatory inputs are a JSON array of evidence inputs.
        let inputs: Vec<Value> = serde_json::from_str(rendered).unwrap();
        assert!(!inputs.is_empty());
        for input in &inputs {
            let forms = [
                ("file", &["item", "hash", "text"][..]),
                ("requirements", &["matches", "text"][..]),
                ("definition", &["text"][..]),
            ];
            let matching = forms
                .iter()
                .filter(|(key, _)| input.get(key).is_some())
                .collect::<Vec<_>>();
            assert_eq!(matching.len(), 1, "one evidence-input form: {input}");
            for field in matching[0].1 {
                assert!(input.get(field).is_some(), "{input} lacks {field}");
            }
        }
        let defined = |name: &str| {
            inputs
                .iter()
                .any(|input| input["definition"] == name || input["requirements"] == name)
        };
        assert!(defined(subject), "{inputs:?}");
        if kind == "example" {
            assert!(defined(SUBJECT), "cited requirement supplied: {inputs:?}");
        } else {
            assert!(defined("terms.readiness"), "{inputs:?}");
        }
    }
}
Input 11: outline tests/authoring_cli.rs fn[author_rejects_unknown_subjects_and_conflicting_targets]
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.batch`
#[test]
fn author_rejects_unknown_subjects_and_conflicting_targets() {
    let fixture = Fixture::new("http://127.0.0.1:1");
    let output = fixture.run(&["author", "requirements.absent"]);
    assert!(!output.status.success(), "{output:?}");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("requirements.absent"), "{stderr}");
    for args in [
        ["author", SUBJECT, "--all"],
        ["author", "--all", "--stdout"],
        ["author-evidence", SUBJECT, "--all"],
    ] {
        let output = fixture.run(&args);
        assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("cannot be used with"), "{stderr}");
    }
    assert_eq!(
        fs::read_to_string(&fixture.evidence).unwrap(),
        fixture.original
    );
}
Input 12: outline tests/authoring_cli.rs fn[verbose_single_author_reports_only_false_rationale_without_source_inputs]
// {test}`requirements.authoring.reporting`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.persistence`
#[test]
fn verbose_single_author_reports_only_false_rationale_without_source_inputs() {
    for (determination, flag) in [(false, "-v"), (false, "--verbose"), (true, "-v")] {
        let rationale = "REVIEW_RATIONALE_ONLY:\n\n- The captured test misses an interesting boundary.\n- Add an assertion for that boundary.";
        let server = Server::start(vec![reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination": determination, "rationale": rationale}),
        )])]);
        let fixture = Fixture::new(&server.endpoint);
        common::coverage_setup(&fixture.project);
        let output = fixture.run(&["author", SUBJECT, flag]);
        assert!(output.status.success(), "{output:?}");
        assert_eq!(server.finish().len(), 1);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(
            stderr.contains(&format!("{SUBJECT}: false")),
            !determination,
            "{stderr}"
        );
        assert_eq!(stderr.contains(rationale), !determination, "{stderr}");
        assert!(!stdout.contains(rationale), "{stdout}");
        for text in [&stdout, &stderr] {
            assert!(!text.contains("SECRET_REQUIREMENT_TEXT"), "{text}");
            assert!(!text.contains("SECRET_DEFINITION_TEXT"), "{text}");
            assert!(!text.contains("pub fn ready()"), "{text}");
            assert!(!text.contains("— true"), "{text}");
            assert!(!text.contains(&format!("{SUBJECT}: true")), "{text}");
        }
        assert!(stdout.contains("Evidence:"), "{stdout}");
        assert!(stdout.contains("Usage:"), "{stdout}");
        let evidence: Value =
            serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
        assert_eq!(evidence["determination"], determination);
        assert_eq!(evidence["rationale"], rationale);
        let errors = habeas::validate_repository(&fixture.project)
            .unwrap()
            .errors;
        assert_eq!(
            errors
                .iter()
                .any(|error| error.contains("determination is false")),
            !determination,
            "{errors:?}"
        );
        if determination {
            assert!(errors.is_empty(), "{errors:?}");
        }
    }
}
Input 13: outline tests/authoring_cli.rs fn[stdout_emits_only_evidence_json_without_changing_project_files]
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.reporting`
// {test}`requirements.ci.schema`
#[test]
fn stdout_emits_only_evidence_json_without_changing_project_files() {
    for (determination, kind, existing_evidence, verbose) in [
        (json!(true), "true", true, false),
        (json!(false), "false", true, false),
        (json!({"FIXME":["#125"]}), "FIXME", true, false),
        (json!(true), "true", false, false),
        (json!(false), "false", true, true),
        (json!(true), "true", true, true),
    ] {
        let rationale = "The supplied sources explain this judgment.";
        let server = Server::start(vec![reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination":determination,"rationale":rationale}),
        )])]);
        let fixture = Fixture::new(&server.endpoint);
        if !existing_evidence {
            fs::remove_dir_all(fixture.project.join("evidence")).unwrap();
        }
        let mut args = vec!["author-evidence", SUBJECT, "--stdout"];
        if verbose {
            args.push("--verbose");
        }
        let output = fixture.run(&args);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(server.finish().len(), 1);
        let evidence: Value = serde_json::from_slice(&output.stdout).unwrap();
        assert!(output.stdout.ends_with(b"\n"));
        assert_eq!(evidence["requirement"], REQUIREMENT);
        assert_eq!(evidence["determination"], determination);
        assert_eq!(evidence["rationale"], rationale);
        let inputs = evidence["inputs"].as_array().unwrap();
        assert!(inputs.iter().any(|input| input["requirements"] == SUBJECT));
        assert!(
            inputs
                .iter()
                .any(|input| input["definition"] == "terms.readiness")
        );
        assert!(
            inputs
                .iter()
                .any(|input| input["file"] == "src/lib.rs" && input["item"].is_string())
        );
        // The record has exactly the schema's fields, and outline inputs carry
        // only their file, selector, and hash, never source text.
        let keys = |value: &Value| {
            let mut keys: Vec<_> = value.as_object().unwrap().keys().cloned().collect();
            keys.sort();
            keys
        };
        assert_eq!(
            keys(&evidence),
            [
                "determination",
                "inputs",
                "rationale",
                "references",
                "requirement"
            ]
        );
        for input in inputs.iter().filter(|input| input.get("item").is_some()) {
            assert_eq!(keys(input), ["file", "hash", "item"], "{input}");
        }
        if existing_evidence {
            assert_eq!(
                fs::read_to_string(&fixture.evidence).unwrap(),
                fixture.original
            );
        } else {
            assert!(!fixture.project.join("evidence").exists());
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains(&format!("{SUBJECT}: ollama / {MODEL}")),
            "{stderr}"
        );
        assert!(!stderr.contains("— true"), "{stderr}");
        assert!(!stderr.contains(&format!("{SUBJECT}: true")), "{stderr}");
        assert_eq!(
            stderr.contains(&format!("{SUBJECT}: false")),
            kind == "false",
            "{stderr}"
        );
        if kind == "FIXME" {
            assert!(stderr.contains("— FIXME"), "{stderr}");
        }
        assert_eq!(
            stderr.contains(rationale),
            verbose && kind == "false",
            "{stderr}"
        );
        assert!(!stderr.contains("SECRET_REQUIREMENT_TEXT"), "{stderr}");
        assert!(!stderr.contains("SECRET_DEFINITION_TEXT"), "{stderr}");
        assert!(stderr.contains("Evidence: stdout\n"));
        let usage_path = stderr
            .lines()
            .find_map(|line| line.strip_prefix("Usage: "))
            .expect("stderr reports usage location");
        assert!(std::path::Path::new(usage_path).is_file());
        let usage = fixture.usage();
        assert_eq!(usage["outcome"], "completed");
        assert_eq!(usage["determination"], kind);
        assert_eq!(usage["evidence_output"], "stdout");
        assert_eq!(usage["evidence_written"], true);
    }
}

Referenced definitions

Input 2: 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.authoring.invocation
:::{req} invocation
`habeas author <full-name> [--config <name>] [--missing | --force] [--stdout] [-v|--verbose]`
MUST author the evidence of one existing requirement or named example in the
current project, under {cite}`requirements.authoring.refresh`. It MUST report the
selected subject, backend, model, evidence destination, and usage-record path on
completion. The evidence destination MUST identify the evidence-file path by
default or stdout when `--stdout` is selected. In stdout mode, the completion
report and diagnostics MUST go to stderr. `author-evidence` MUST remain an alias
for the single-subject command.
:::