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.configuration.state_location

Requirements index · View definition

evidence Valid

Requirement

Habeas MUST store persistent per-user activity state under $XDG_STATE_HOME/habeas on Unix when XDG_STATE_HOME is an absolute, nonempty path, otherwise under $HOME/.local/state/habeas. On Windows it MUST use %LOCALAPPDATA%/habeas/state. HOME and LOCALAPPDATA MUST likewise be absolute, nonempty paths to be used. Features MUST use a named subdirectory under that state root and document their record formats and locations.

State MUST persist across invocations and MUST NOT be stored in the project repository, the configuration file, or a disposable cache directory. Habeas MUST create the required directories when recording state. If it cannot determine or write the state location, the operation requiring that state MUST report the failure and MUST NOT claim that its history was recorded.

Rationale

The reviewed tests adequately cover requirements.configuration.state_location. I judged this from the supplied test text alone and did not request any implementation source.

Location rules

  • tests/configuration.rs#fn[locations_use_absolute_xdg_values_and_platform_fallbacks] checks the Unix case where an absolute XDG_STATE_HOME gives $XDG_STATE_HOME/habeas.
  • The same test checks that an empty or relative XDG_STATE_HOME falls back to $HOME/.local/state/habeas.
  • It checks that on Windows LOCALAPPDATA gives <LOCALAPPDATA>/habeas/state.
  • It checks that the lookup returns an error when no variable is available.
  • tests/configuration.rs#fn[base_directories_must_be_absolute_and_nonempty] covers the clause that HOME and LOCALAPPDATA must be absolute and nonempty.
  • That test feeds empty and relative values on both platforms and asserts an error that names the variable.
  • It also checks that a relative XDG_STATE_HOME falls back to an absolute HOME.

Named subdirectory per feature, with documented formats and locations

  • tests/authoring_cli.rs#fn[usage_record_identifies_its_run_and_unusable_state_is_reported] checks that usage records land in habeas/authoring/usage under the state root. The state root is a fresh temporary directory, so this also shows that the directories are created when recording.
  • tests/authoring_batch.rs#fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed] checks the GitHub cache at habeas/github/<owner>+<repo>+<n>.json. On Windows it checks habeas/state/github/....
  • tests/configuration.rs#fn[configuration_documentation_covers_locations_structure_editing_and_removal] asserts that md/reference.md documents the usage and GitHub cache locations and formats, on both Unix and Windows.

Persistence across invocations

  • The usage test runs author twice and checks that the first record is byte-identical afterwards and that there are now two records.
  • The GitHub tests reuse cached entries across status invocations (tests/authoring_batch.rs test above).
  • src/github.rs#mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not] also checks reuse across read calls.

Not stored in the project repository

  • tests/authoring_cli.rs#fn[undeterminable_unwritable_or_project_state_fails_before_a_model_request] covers a state root inside the project.
  • tests/authoring_cli.rs#fn[state_reaching_the_project_through_a_symlink_is_refused] covers a state root that is a symlink into the project, and one whose nearest existing ancestor is such a symlink.
  • tests/authoring_batch.rs#fn[github_reads_do_not_cache_in_a_state_root_inside_the_project] covers the GitHub cache, for a direct path and a symlink alias.
  • The exact-path assertions on the state root also show it is not placed in a cache directory.
  • The documentation test supports the “not the configuration file” clause with its check that Habeas never creates or rewrites the configuration files. The configuration file is user-edited, so no behavioral test is needed for that clause.

Failure reporting, without claiming history was recorded

  • Undeterminable location: with XDG_STATE_HOME and HOME removed, author fails with a “cannot determine Habeas…” error, before any model request and without touching evidence.
  • Unwritable location: with a state root that is a file, author fails with “cannot create authoring state directory” and the blocker file is left unchanged.
  • Usage write failure: usage_write_failures_are_reported_without_claiming_recorded_history asserts a nonzero exit, a “cannot record” message, and no “Usage:” output on stdout.
  • GitHub cache write failure: cache_write_failures_are_reported_instead_of_returning_uncached_success asserts IssueRead::Failed with “cannot record GitHub cache”.

I found no obligation that lacks a test or an assertion.

Inputs

Tests

Input 2: outline src/github.rs mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not]
  • File: src/github.rs
  • Selector: mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not]
  • Kind: fn
  • src/github.rs:882–919
    // {test}`requirements.authoring.github_reads`
    // {test}`requirements.configuration.state_location`
    #[test]
    fn results_are_cached_by_issue_for_an_hour_and_failures_are_not() {
        let github = FakeGithub::start(&[
            ("/repos/o/r/issues/1", 200, issue("open", "")),
            ("/repos/o/r/issues/3", 503, json!({})),
        ]);
        let cache = tempfile::tempdir().unwrap();
        let issues =
            GithubIssues::with_api(github.endpoint.clone(), Some(cache.path().to_owned()), None);
        let reads = issues.read_all(["o/r#1".to_owned(), "o/r#2".to_owned(), "o/r#3".to_owned()]);
        assert_eq!(reads["o/r#1"].state(), "open");
        assert_eq!(reads["o/r#2"], IssueRead::Missing);
        assert!(matches!(reads["o/r#3"], IssueRead::Failed(_)));
        assert_eq!(github.count(), 3);
        // Definitive results are reused; the failure is retried.
        let again = issues.read_all(["o/r#1".to_owned(), "o/r#2".to_owned(), "o/r#3".to_owned()]);
        assert_eq!(again["o/r#1"], reads["o/r#1"]);
        assert_eq!(again["o/r#2"], IssueRead::Missing);
        assert_eq!(github.count(), 4);
        assert!(!cache.path().join("o+r+3.json").exists());

        // An entry an hour old, or from another endpoint, is read again.
        let path = cache.path().join("o+r+1.json");
        let mut entry: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        entry["fetched"] = json!(entry["fetched"].as_u64().unwrap() - 3600);
        fs::write(&path, entry.to_string()).unwrap();
        issues.read("o/r#1");
        assert_eq!(github.count(), 5);
        issues.read("o/r#1");
        assert_eq!(github.count(), 5);
        let other = FakeGithub::start(&[]);
        let moved =
            GithubIssues::with_api(other.endpoint.clone(), Some(cache.path().to_owned()), None);
        assert_eq!(moved.read("o/r#1"), IssueRead::Missing);
        assert_eq!(other.count(), 1);
    }
Input 3: outline src/github.rs mod[tests]/fn[cache_write_failures_are_reported_instead_of_returning_uncached_success]
  • File: src/github.rs
  • Selector: mod[tests]/fn[cache_write_failures_are_reported_instead_of_returning_uncached_success]
  • Kind: fn
  • src/github.rs:1067–1083
    // {test}`requirements.authoring.github_reads`
    // {test}`requirements.configuration.state_location`
    #[test]
    fn cache_write_failures_are_reported_instead_of_returning_uncached_success() {
        let github = FakeGithub::start(&[("/repos/o/r/issues/1", 200, issue("open", ""))]);
        let state = tempfile::tempdir().unwrap();
        let blocked = state.path().join("github");
        fs::write(&blocked, "not a directory").unwrap();
        let issues = GithubIssues::with_api(github.endpoint.clone(), Some(blocked.clone()), None);
        let result = issues.read("o/r#1");
        assert!(
            matches!(result, IssueRead::Failed(ref message) if message.contains("cannot record GitHub cache")),
            "{result:?}"
        );
        assert_eq!(github.count(), 1);
        assert_eq!(fs::read_to_string(blocked).unwrap(), "not a directory");
    }
Input 4: outline tests/authoring_batch.rs fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed]
// {test}`requirements.ci.fixme_closed_issue`
// {test}`requirements.cli.fixme_issues`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.outcomes`
// {test}`requirements.configuration.state_location`
#[test]
fn closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed() {
    let server = Server::start_with(false, Behavior::ClosedIssueIsFalse);
    let github = FakeGithub::start();
    let fixture = Fixture::new(&server.endpoint, None);
    let source = fixture.project.join("src/lib.rs");
    fs::write(
        &source,
        fs::read_to_string(&source).unwrap().replace(
            "pub fn beta()",
            "// :::{fixme} requirements.beta\n// :github: example/queue#125\n// Zero capacity is untested.\n// :::\npub fn beta()",
        ),
    )
    .unwrap();
    let run = |args: &[&str]| {
        let output = fixture
            .command()
            .env("HABEAS_GITHUB_API_URL", &github.endpoint)
            .env("GITHUB_TOKEN", "TEST_GITHUB_TOKEN")
            .args(args)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).unwrap()
    };
    run(&["author", "--all"]);
    assert!(github.headers.lock().unwrap().iter().any(|headers| {
        headers
            .to_ascii_lowercase()
            .contains("authorization: bearer test_github_token\r\n")
    }));
    assert_eq!(server.subjects().len(), 6);
    // The issue was open, so record the acknowledged gap as current FIXME
    // evidence.
    let mut beta = fixture.evidence("requirements.beta");
    beta["determination"] = json!({"FIXME": ["example/queue#125"]});
    fs::write(
        fixture.project.join("evidence/requirements.beta.json"),
        serde_json::to_vec_pretty(&beta).unwrap(),
    )
    .unwrap();
    let cache = fixture.state.join(if cfg!(windows) {
        "habeas/state/github/example+queue+125.json"
    } else {
        "habeas/github/example+queue+125.json"
    });
    assert!(
        cache.exists(),
        "GitHub reads are cached under the state root"
    );
    let status = run(&["status"]);
    assert!(!status.contains("stale"), "{status}");
    let reads = github.requests();

    *github.state.lock().unwrap() = "closed";
    // The cached open state is reused for an hour.
    assert!(!run(&["status"]).contains("stale"));
    assert_eq!(github.requests(), reads);
    fs::remove_file(&cache).unwrap();
    let status = run(&["status"]);
    assert_eq!(github.requests(), reads + 1);
    let row = status
        .lines()
        .find(|line| line.starts_with("| `requirements.beta`"))
        .unwrap_or_else(|| panic!("{status}"));
    assert!(row.contains("Invalid"), "{status}");
    for expected in [
        "evidence/requirements.beta.json: stale: issue example/queue#125, named by the acknowledging {fixme} to requirements.beta at src/lib.rs:5, is closed",
        "src/lib.rs:5: {fixme} names example/queue#125, which is closed",
        "src/lib.rs:9: fn beta fails: its {fixme} at line 5 names example/queue#125, which is closed",
    ] {
        assert!(status.contains(expected), "{expected}\n{status}");
    }
    // Repository validation, which does not contact GitHub, still accepts it.
    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);
    assert_eq!(github.requests(), reads + 1);

    run(&["author", "--all"]);
    let subjects = server.subjects();
    assert_eq!(subjects.len(), 7, "{subjects:?}");
    assert_eq!(subjects[6], "requirement requirements.beta");
    let beta = fixture.evidence("requirements.beta");
    assert_eq!(beta["determination"], json!(false), "{beta}");
    // Issue states are supplied with inputs but never recorded.
    assert!(!beta.to_string().contains("github_issues"), "{beta}");
    for run in fixture.usage() {
        assert!(!run.to_string().contains("github_issues"), "{run}");
    }
}
Input 5: outline tests/authoring_batch.rs fn[github_reads_do_not_cache_in_a_state_root_inside_the_project]
/// A state root inside the project, directly or through a symlink, is not
/// used for the GitHub cache: `status` still reads GitHub, uncached, and
/// `author` refuses the location before writing anything there.
// {test}`requirements.configuration.state_location`
#[test]
fn github_reads_do_not_cache_in_a_state_root_inside_the_project() {
    let server = Server::start(false, None);
    let github = FakeGithub::start();
    let fixture = Fixture::new(&server.endpoint, None);
    let source = fixture.project.join("src/lib.rs");
    fs::write(
        &source,
        fs::read_to_string(&source).unwrap().replace(
            "pub fn beta()",
            "// :::{fixme} requirements.beta\n// :github: example/queue#125\n// Zero capacity is untested.\n// :::\npub fn beta()",
        ),
    )
    .unwrap();
    let inside = fixture.project.join("state");
    let mut states = vec![(inside.clone(), inside.clone())];
    #[cfg(unix)]
    {
        let alias = fixture.project.parent().unwrap().join("state-alias");
        std::os::unix::fs::symlink(&fixture.project, &alias).unwrap();
        states.push((alias.join("state"), inside.clone()));
    }
    for (state, written) in states {
        let run = |args: &[&str]| {
            fixture
                .command()
                .env("XDG_STATE_HOME", &state)
                .env("LOCALAPPDATA", &state)
                .env("HABEAS_GITHUB_API_URL", &github.endpoint)
                .args(args)
                .output()
                .unwrap()
        };
        let before = github.requests();
        let status = run(&["status"]);
        assert!(
            status.status.success(),
            "{}",
            String::from_utf8_lossy(&status.stderr)
        );
        assert_eq!(github.requests(), before, "no uncached fallback");
        assert!(String::from_utf8_lossy(&status.stderr).contains("cannot locate GitHub cache"));
        assert!(!written.exists(), "{state:?}");
        let author = run(&["author", "--all"]);
        assert!(!author.status.success());
        assert!(
            String::from_utf8_lossy(&author.stderr)
                .contains("must be outside the project repository"),
            "{}",
            String::from_utf8_lossy(&author.stderr)
        );
        assert!(!written.exists(), "{state:?}");
    }
    assert!(server.subjects().is_empty());
}
Input 6: outline tests/authoring_cli.rs fn[usage_record_identifies_its_run_and_unusable_state_is_reported]
// {test}`requirements.authoring.usage_storage`
#[cfg(unix)]
#[test]
// {test}`requirements.configuration.state_location`
fn usage_record_identifies_its_run_and_unusable_state_is_reported() {
    let server = Server::start(vec![
        reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination":true,"rationale":"covered"}),
        )]);
        2
    ]);
    let fixture = Fixture::new(&server.endpoint);
    let output = fixture.run(&["author", SUBJECT]);
    assert!(output.status.success(), "{output:?}");
    let directory = fixture.state.join("habeas/authoring/usage");
    let files = fs::read_dir(&directory)
        .unwrap()
        .map(|entry| entry.unwrap().path())
        .collect::<Vec<_>>();
    assert_eq!(files.len(), 1);
    let usage: Value = serde_json::from_slice(&fs::read(&files[0]).unwrap()).unwrap();
    let run_id = usage["run_id"].as_str().unwrap();
    assert!(!run_id.is_empty());
    assert_eq!(
        files[0].file_name().unwrap().to_str().unwrap(),
        format!("{run_id}.json"),
        "the record is named after its run"
    );
    assert_eq!(usage["version"], 1);
    assert_eq!(
        usage["project_root"],
        fixture.project.canonicalize().unwrap().to_str().unwrap()
    );
    assert_eq!(usage["subject"], SUBJECT);
    assert_eq!(usage["subject_kind"], "requirement");
    assert_eq!(usage["backend"], "ollama");
    assert_eq!(usage["model"], MODEL);
    assert_eq!(usage["evidence_output"], "file");
    let start = usage["start_time_ms"].as_u64().unwrap();
    let end = usage["end_time_ms"].as_u64().unwrap();
    assert!(start > 0 && start <= end, "{usage}");

    let first_bytes = fs::read(&files[0]).unwrap();
    let second = fixture.run(&["author", SUBJECT, "--force"]);
    assert!(second.status.success(), "{second:?}");
    assert_eq!(fs::read(&files[0]).unwrap(), first_bytes);
    assert_eq!(fs::read_dir(&directory).unwrap().count(), 2);
    server.finish();

    // A state location that cannot be determined or created is reported
    // before any model request, and no evidence is written.
    let blocker = fixture.temp.path().join("not-a-directory");
    fs::write(&blocker, "").unwrap();
    for (variable, value) in [
        ("XDG_STATE_HOME", Some(blocker.as_os_str())),
        ("XDG_STATE_HOME", None),
    ] {
        let mut command = fixture.command();
        match value {
            Some(value) => command.env(variable, value),
            None => command.env_remove(variable).env_remove("HOME"),
        };
        let output = command
            .args(["author", SUBJECT, "--force"])
            .output()
            .unwrap();
        assert!(!output.status.success(), "{value:?}: {output:?}");
        assert!(!output.stderr.is_empty(), "{value:?}: {output:?}");
        assert!(output.stdout.is_empty(), "{value:?}: {output:?}");
    }
    let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
    assert_eq!(
        evidence["rationale"], "covered",
        "failed runs preserved the evidence"
    );
}
Input 7: outline tests/authoring_cli.rs fn[undeterminable_unwritable_or_project_state_fails_before_a_model_request]
// {test}`requirements.configuration.state_location`
#[cfg(unix)]
#[test]
fn undeterminable_unwritable_or_project_state_fails_before_a_model_request() {
    let server = Server::start(Vec::new());
    let fixture = Fixture::new(&server.endpoint);
    for args in [
        &["author", SUBJECT, "--config", "mock"][..],
        &["author", "--all", "--config", "mock"][..],
    ] {
        let output = fixture
            .command()
            .env_remove("XDG_STATE_HOME")
            .env_remove("HOME")
            .args(args)
            .output()
            .unwrap();
        assert_unrecorded_failure(&output, "cannot determine Habeas");

        let blocked = fixture.temp.path().join("state-file");
        fs::write(&blocked, "not a directory").unwrap();
        let output = fixture
            .command()
            .env("XDG_STATE_HOME", &blocked)
            .args(args)
            .output()
            .unwrap();
        assert_unrecorded_failure(&output, "cannot create authoring state directory");
        assert_eq!(fs::read_to_string(&blocked).unwrap(), "not a directory");

        let inside = fixture.project.join("state");
        let output = fixture
            .command()
            .env("XDG_STATE_HOME", &inside)
            .args(args)
            .output()
            .unwrap();
        assert_unrecorded_failure(&output, "must be outside the project repository");
        assert!(!inside.join("habeas/authoring").exists());
    }
    assert!(server.finish().is_empty());
    assert_eq!(
        fs::read_to_string(&fixture.evidence).unwrap(),
        fixture.original
    );
}
Input 8: outline tests/authoring_cli.rs fn[state_reaching_the_project_through_a_symlink_is_refused]
// {test}`requirements.configuration.state_location`
#[cfg(unix)]
#[test]
fn state_reaching_the_project_through_a_symlink_is_refused() {
    let server = Server::start(Vec::new());
    let fixture = Fixture::new(&server.endpoint);
    // A state root that is itself a symlink into the project, and one whose
    // nearest existing ancestor is such a symlink.
    let alias = fixture.temp.path().join("state-alias");
    std::os::unix::fs::symlink(&fixture.project, &alias).unwrap();
    for state in [alias.clone(), alias.join("not/yet/created")] {
        let output = fixture
            .command()
            .env("XDG_STATE_HOME", &state)
            .args(["author", SUBJECT, "--config", "mock"])
            .output()
            .unwrap();
        assert_unrecorded_failure(&output, "must be outside the project repository");
        assert!(!fixture.project.join("habeas").exists());
        assert!(!fixture.project.join("not").exists());
    }
    assert!(server.finish().is_empty());
}
Input 9: outline tests/authoring_cli.rs fn[usage_write_failures_are_reported_without_claiming_recorded_history]
// {test}`requirements.configuration.state_location`
#[cfg(unix)]
#[test]
fn usage_write_failures_are_reported_without_claiming_recorded_history() {
    use std::os::unix::fs::PermissionsExt;
    for args in [&["author", SUBJECT][..], &["author", "--all"][..]] {
        let fixture = Fixture::new("http://unconfigured");
        let usage = fixture.state.join("habeas/authoring/usage");
        let server = Server::start_with(
            vec![reply(vec![call(
                "submit",
                "submit_judgment",
                json!({"determination":true,"rationale":"The supplied sources support the subject."}),
            )])],
            move || {
                for entry in fs::read_dir(&usage).unwrap() {
                    let path = entry.unwrap().path();
                    fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
                }
            },
        );
        let config_path = fixture.config.join("habeas/config.toml");
        let config = fs::read_to_string(&config_path)
            .unwrap()
            .replace("http://unconfigured", &server.endpoint);
        fs::write(config_path, config).unwrap();
        let output = fixture.command().args(args).output().unwrap();
        assert_eq!(server.finish().len(), 1);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(!output.status.success(), "{stderr}");
        assert!(stderr.contains("cannot record"), "{stderr}");
        assert!(
            !String::from_utf8_lossy(&output.stdout).contains("Usage:"),
            "{output:?}"
        );
    }
}
Input 10: outline tests/configuration.rs fn[locations_use_absolute_xdg_values_and_platform_fallbacks]
// {test}`requirements.configuration.user_location`
// {test}`requirements.configuration.state_location`
#[test]
fn locations_use_absolute_xdg_values_and_platform_fallbacks() {
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let config = dir.path().join("config");
    let state = dir.path().join("state");
    let vars = BTreeMap::from([
        ("HOME", home.as_os_str().to_owned()),
        ("XDG_CONFIG_HOME", config.as_os_str().to_owned()),
        ("XDG_STATE_HOME", state.as_os_str().to_owned()),
    ]);
    let lookup = |name: &str| vars.get(name).cloned();
    assert_eq!(
        user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
        config.join("habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
        state.join("habeas")
    );
    for invalid_xdg in ["", "relative"] {
        let lookup = |name: &str| {
            Some(if name == "HOME" {
                home.as_os_str().to_owned()
            } else {
                OsString::from(invalid_xdg)
            })
        };
        assert_eq!(
            user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
            home.join(".config/habeas/config.toml")
        );
        assert_eq!(
            state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
            home.join(".local/state/habeas")
        );
    }
    let windows = |name: &str| match name {
        "APPDATA" => Some(config.as_os_str().to_owned()),
        "LOCALAPPDATA" => Some(state.as_os_str().to_owned()),
        _ => None,
    };
    assert_eq!(
        user_config_path_from(ConfigPlatform::Windows, windows).unwrap(),
        config.join("habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Windows, windows).unwrap(),
        state.join("habeas/state")
    );
    assert!(user_config_path_from(ConfigPlatform::Unix, |_| None).is_err());
    assert!(state_root_from(ConfigPlatform::Windows, |_| None).is_err());
}
Input 11: outline tests/configuration.rs fn[configuration_documentation_covers_locations_structure_editing_and_removal]
// {test}`requirements.configuration.documentation`
// {test}`requirements.configuration.state_location`
#[test]
fn configuration_documentation_covers_locations_structure_editing_and_removal() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let reference = fs::read_to_string(root.join("md/reference.md")).unwrap();
    // Collapse line breaks so phrases may wrap.
    let reference = reference.split_whitespace().collect::<Vec<_>>().join(" ");
    for phrase in [
        // Locations of the user and project files.
        "Create and edit `$XDG_CONFIG_HOME/habeas/config.toml`, or `$HOME/.config/habeas/config.toml`",
        "On Windows, use `%APPDATA%/habeas/config.toml`",
        "The nearest enclosing `habeas.toml` supplies workspace settings",
        // Structure and schema version.
        "Each must start with the schema version `version = 1`",
        "the top level may contain only feature tables",
        // Editing by hand, without a management command or generated state.
        "you create and edit both by hand with a text editor; there is no configuration-management command",
        "Habeas never creates, repairs, or rewrites them",
        // Resolution rules and defaults.
        "Selection order is `--config`, the user's per-project selection, workspace default, then user default",
        "omitted settings use their documented defaults",
        "Relative paths in this file use its directory as their base",
        "An allow overrides all defaults; disallow wins if both match",
        "Paths name literal files or directory subtrees, not globs",
        "An omitted `allow` or `disallow` means an empty list",
        "delete the whole `[evidence]` table to restore the default source-access rules",
        "`reauthorings` must be a positive integer; without it, the last 3 commits",
        "$XDG_STATE_HOME/habeas/authoring/usage",
        "$HOME/.local/state/habeas/authoring/usage",
        "%LOCALAPPDATA%/habeas/state/authoring/usage",
        "$XDG_STATE_HOME/habeas/github",
        "`<owner>+<repo>+<number>.json`, recording the `issue`",
        "Unix time it was `fetched` in seconds",
        // Credential-source references.
        "add `api_key_env = \"OLLAMA_API_KEY\"`",
        "aws_profile = \"research\"",
        // Changing and removing settings and selections.
        "To remove an optional setting or selection, delete its key or table",
        "Remove the project table or default field to remove a selection",
        "Delete a configuration's table to remove it",
        "delete `concurrency` to restore the default",
        "Delete `endpoint` to return to the local default",
    ] {
        assert!(
            reference.contains(phrase),
            "md/reference.md lacks {phrase:?}"
        );
    }
}
Input 12: outline tests/configuration.rs fn[authoring_documentation_shows_each_configuration_task]
// {test}`requirements.authoring.configuration_documentation`
// {test}`requirements.configuration.state_location`
// {test}`requirements.configuration.documentation`
#[test]
fn authoring_documentation_shows_each_configuration_task() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let section = |document: &str, start: &str, end: &str| {
        let text = fs::read_to_string(root.join(document)).unwrap();
        let (_, rest) = text.split_once(start).unwrap();
        rest.split_once(end).unwrap().0.to_owned()
    };
    let chapter = section(
        "md/requirements/authoring.md",
        ":::{req} configuration_documentation",
        "## Recording results",
    );
    let reference = section(
        "md/reference.md",
        "## Authoring evidence with a model",
        "### Assessment policy",
    );

    // Each example is a complete user or workspace file, and every placeholder
    // it uses is identified in the prose that introduces it.
    let mut pieces = chapter.split("```toml\n");
    let mut before = pieces.next().unwrap().to_owned();
    let mut blocks = Vec::new();
    for block in pieces {
        let (source, after) = block.split_once("\n```").unwrap();
        let path = Path::new("md/requirements/authoring.md");
        if source.contains("[evidence]") {
            WorkspaceConfig::parse(source, path).unwrap();
        } else {
            UserConfig::parse(source, path).unwrap();
        }
        // The prose before the example, or the paragraph right after it.
        let intro = format!(
            "{}{}",
            before.rsplit("```").next().unwrap(),
            after.trim_start().split("\n\n").next().unwrap()
        );
        let intro = intro.split_whitespace().collect::<Vec<_>>().join(" ");
        let target = if source.contains("[evidence]") || source.contains(".credentials]") {
            "`habeas.toml`"
        } else {
            "user `config.toml`"
        };
        assert!(
            intro.contains(target),
            "missing target file: {intro}\n{source}"
        );
        if source.contains("[authoring.projects.") {
            assert!(
                intro.contains("valid only in the user file, never in a workspace file"),
                "{intro}"
            );
        }
        let every_uppercase = intro.contains("replace every uppercase placeholder");
        for placeholder in ["MODEL_ID", "MODEL_TAG", "OPENAI_API_KEY_VALUE"] {
            if source.contains(placeholder) {
                assert!(
                    every_uppercase || intro.contains(&format!("`{placeholder}`")),
                    "{placeholder} is not identified:\n{intro}\n{source}"
                );
            }
        }
        if source.contains(".credentials]") {
            assert!(every_uppercase, "{intro}");
        }
        for (placeholder, instruction) in [
            ("research", "`research` with your AWS profile name"),
            ("us-east-1", "`us-east-1` with your region"),
            (
                "workstation:11434",
                "`workstation` in the URL with your server",
            ),
            (
                "/absolute/path/to/project",
                "`/absolute/path/to/project` with the canonical path to your checkout",
            ),
            (
                "generated",
                "Replace `generated` and `generated/private` with your own paths",
            ),
        ] {
            if source.contains(placeholder) {
                assert!(intro.contains(instruction), "{placeholder}: {intro}");
            }
        }
        blocks.push(source.to_owned());
        before = after.to_owned();
    }
    let any_block = |needle: &str| blocks.iter().any(|block| block.contains(needle));
    assert!(chapter.contains("Create the user file at the [shared configuration location]"));
    assert!(chapter.contains("For workspace settings, create `habeas.toml`"));
    // Each backend's example, a default, a remote Ollama server, and a
    // project selection.
    assert!(any_block("backend = \"bedrock\""));
    assert!(any_block("backend = \"ollama\""));
    let openai = blocks
        .iter()
        .find(|block| block.contains("backend = \"openai\""))
        .expect("authoring documentation must include a complete OpenAI example");
    assert!(openai.contains("api_key_env = \"OPENAI_API_KEY\""));
    assert!(any_block("[authoring]\ndefault = "));
    assert!(any_block("endpoint = \"http://workstation:11434\""));
    assert!(any_block("[authoring.projects."));
    for placeholder in [
        "`research`",
        "`us-east-1`",
        "`workstation`",
        "`/absolute/path/to/project`",
        "`OPENAI_API_KEY_VALUE`",
    ] {
        assert!(chapter.contains(placeholder), "{placeholder}");
    }
    // Invocation selection and editing or removing selections by hand.
    for phrase in [
        "Add `--config local`",
        "Edit `authoring.default` to change the user default",
        "Delete the corresponding field or\nproject table to remove a selection",
        "To remove a named configuration, delete its\ntable and update any selections naming it",
    ] {
        assert!(chapter.contains(phrase), "{phrase}");
    }
    let records = fs::read_to_string(root.join("md/requirements/authoring.md")).unwrap();
    assert!(records.contains("Each assessment MUST have a separate JSON usage record"));
    assert!(
        records.contains("identify its format version, run, project root, subject kind and full")
    );
    // Backend-specific options and credential-source references.
    for phrase in [
        "`[authoring.configs.<name>.options]`",
        "`api_key_env = \"OLLAMA_API_KEY\"`",
        "Omit `aws_profile` or `region` to use AWS SDK defaults",
        "`reasoning = ",
        "`max_output_tokens = ",
    ] {
        assert!(chapter.contains(phrase), "{phrase}");
    }
    assert!(reference.contains("[authoring.configs.cloud.options]"));
    assert!(reference.contains("`num_ctx`"));
    let chapter = chapter.split_whitespace().collect::<Vec<_>>().join(" ");
    for phrase in [
        "Bedrock and OpenAI default to the available logical CPU count; Ollama defaults to one",
        "OpenAI defaults to `policy = \"once\"`",
        "Other backends continue to default to `confirm`",
        "The default model is `gpt-6.1-sol`, with low reasoning effort and an output-token limit of 16,384",
        "OpenAI uses the Responses API at `https://api.openai.com/v1`; `endpoint` overrides that base URL",
        "You may omit `api_key_env` to use `OPENAI_API_KEY` implicitly",
        "set `OPENAI_API_KEY` to your API key outside the file",
        "Do not combine `credentials` with `aws_profile`, or `api_key` with `api_key_env`",
    ] {
        assert!(chapter.contains(phrase), "{phrase}");
    }
    let reference = fs::read_to_string(root.join("md/reference.md"))
        .unwrap()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    for phrase in [
        "Ollama defaults to `http://localhost:11434`",
        "except `maxTokens`: without it, each Bedrock request asks for at most 16,384 output tokens",
    ] {
        assert!(reference.contains(phrase), "{phrase}");
    }
}
Input 13: outline tests/configuration.rs fn[base_directories_must_be_absolute_and_nonempty]
// {test}`requirements.configuration.user_location`
// {test}`requirements.configuration.state_location`
#[test]
fn base_directories_must_be_absolute_and_nonempty() {
    use std::ffi::OsString;
    let only = |name: &'static str, value: &'static str| {
        move |key: &str| (key == name).then(|| OsString::from(value))
    };
    for (platform, variable) in [
        (ConfigPlatform::Unix, "HOME"),
        (ConfigPlatform::Windows, "APPDATA"),
    ] {
        for value in ["", "relative/home"] {
            let error = user_config_path_from(platform, only(variable, value)).unwrap_err();
            assert!(error.to_string().contains(variable), "{error}");
        }
    }
    for (platform, variable) in [
        (ConfigPlatform::Unix, "HOME"),
        (ConfigPlatform::Windows, "LOCALAPPDATA"),
    ] {
        for value in ["", "relative/home"] {
            let error = state_root_from(platform, only(variable, value)).unwrap_err();
            assert!(error.to_string().contains(variable), "{error}");
        }
    }
    // A relative XDG value falls back to an absolute HOME.
    let lookup = |key: &str| match key {
        "XDG_CONFIG_HOME" | "XDG_STATE_HOME" => Some(OsString::from("relative")),
        "HOME" => Some(OsString::from("/home/user")),
        _ => None,
    };
    assert_eq!(
        user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
        std::path::PathBuf::from("/home/user/.config/habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
        std::path::PathBuf::from("/home/user/.local/state/habeas")
    );
}

Other sources

Input 1: requirements selection requirements.configuration.state_location
:::{req} state_location
Habeas MUST store persistent per-user activity state under
`$XDG_STATE_HOME/habeas` on Unix when XDG_STATE_HOME is an absolute, nonempty path,
otherwise under `$HOME/.local/state/habeas`. On Windows it MUST use
`%LOCALAPPDATA%/habeas/state`. `HOME` and `LOCALAPPDATA` MUST likewise be
absolute, nonempty paths to be used. Features MUST use a named subdirectory under that
state root and document their record formats and locations.

State MUST persist across invocations and MUST NOT be stored in the project
repository, the configuration file, or a disposable cache directory. Habeas MUST
create the required directories when recording state. If it cannot determine or
write the state location, the operation requiring that state MUST report the
failure and MUST NOT claim that its history was recorded.
:::