requirements.authoring.rig_configuration_mapping
Requirements index · View definition
Requirement
Habeas MUST resolve its saved configuration before constructing Rig provider clients and completion models. The Habeas data structures MUST remain the saved format. Rig model references MAY be reused internally without discarding the connection settings they do not represent.
The Bedrock adapter MUST pass the chosen AWS profile and region through AWS SDK configuration, or use explicitly configured credentials. The Ollama adapter MUST use the chosen server, exact model ID, and optional authentication; the server MAY be local or remote. The OpenAI adapter MUST use the Responses API, selected endpoint, exact model ID, and resolved API key. All adapters MUST supply the same tools and initial prompt.
Rationale
The reviewed tests cover every obligation in requirements.authoring.rig_configuration_mapping.
-
Saved config resolved first, and the saved format stays intact.
tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]runs the CLI with an environment-resolved key and asserts that the user config file is byte-identical afterwards.tests/authoring_cli.rs#fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]asserts the same for the workspace config files. It also asserts that the workspace model and key reach the request.tests/configuration.rs#fn[explicit_project_and_default_selections_choose_whole_configs]checks that resolution picks whole configs and yields the backend structures.
-
Bedrock.
tests/authoring_cli.rs#fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]configures a named profile and a region. The profile’s own region differs from the configured one, and a wrongdefaultprofile exists. It asserts that:- the request is signed with the profile’s access key;
- the signature scope uses the configured region
us-west-2; - the wrong default key is absent;
- the model ID appears in the Converse path.
src/authoring/providers.rs#mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain]asserts that explicit credentials and the region reach the SDK config.tests/authoring_cli.rs#fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections]covers the SDK default chain when no profile or region is set.
-
Ollama.
tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]asserts the chosen endpoint path, the exact model, and the Bearer authorization resolved from the environment.tests/authoring_cli.rs#fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]asserts a literal key reaches the request headers and not the body.tests/authoring_cli.rs#fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections]asserts that no authorization header is sent when none is configured.- Local or remote servers are a MAY, so nothing is required there.
-
OpenAI.
tests/authoring_cli.rs#fn[openai_responses_replays_tool_calls_and_records_usage]asserts thePOST /responsespath, the configured endpoint, the exact model, and the Bearer key resolved fromapi_key_env.tests/authoring_cli.rs#fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections]asserts the same for the defaultOPENAI_API_KEYvariable.
-
Same tools and initial prompt for all adapters. In
tests/authoring_cli.rs#fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections],prompt_and_toolsstrips only the provider envelope. The test then asserts that the Ollama, Bedrock and OpenAI prompt and tool name/description/schema triples are equal, that there are 10 tools, and that the evidence documents are identical. The per-backend tests also assert the 10-tool set. -
Unit tests. The
providers.rsunit tests (bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted,typed_client_calls_preserve_order_and_native_historyandmalformed_typed_client_calls_are_reported) add native option and call-history handling. This supports the mapping but is not strictly required by the text.
I found no untested obligation, so there is no adequacy gap.
Inputs
Tests
Input 2: outline src/authoring/providers.rs mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain]
- File:
src/authoring/providers.rs - Selector:
mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain] - Kind:
fn src/authoring/providers.rs:711–728
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_precedence`
#[tokio::test]
async fn explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain() {
let config: BedrockConfig = toml::from_str("model = 'test'\nregion = 'us-west-2'\n[credentials]\naccess_key_id = 'TEST_ACCESS'\nsecret_access_key = 'test-secret'\nsession_token = 'test-session'\n").unwrap();
let sdk = bedrock_sdk_config(&config).await;
let credentials = sdk
.credentials_provider()
.unwrap()
.provide_credentials()
.await
.unwrap();
assert_eq!(credentials.access_key_id(), "TEST_ACCESS");
assert_eq!(credentials.secret_access_key(), "test-secret");
assert_eq!(credentials.session_token(), Some("test-session"));
assert_eq!(sdk.region().unwrap().as_ref(), "us-west-2");
}
Input 3: outline src/authoring/providers.rs mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted]
- File:
src/authoring/providers.rs - Selector:
mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted] - Kind:
fn src/authoring/providers.rs:806–831
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted() {
let mut request = CompletionRequest::new("prompt");
let mut options = Map::from_iter([("top_k".into(), json!(12))]);
apply_bedrock_options(&mut request, &mut options).unwrap();
assert!(request.temperature.is_none());
assert_eq!(request.max_tokens, Some(16_384));
assert!(request.options.is_default());
assert_eq!(options["top_k"], 12);
for value in [
json!({"temperature":"hot"}),
json!({"maxTokens":-1}),
json!({"maxTokens":2147483648_u64}),
json!({"topP":true}),
json!({"stopSequences":"stop"}),
json!({"inferenceConfig":{}}),
] {
let mut options = value.as_object().unwrap().clone();
assert!(
apply_bedrock_options(&mut CompletionRequest::new("prompt"), &mut options).is_err()
);
}
}
Input 4: outline src/authoring/providers.rs mod[tests]/fn[typed_client_calls_preserve_order_and_native_history]
- File:
src/authoring/providers.rs - Selector:
mod[tests]/fn[typed_client_calls_preserve_order_and_native_history] - Kind:
fn src/authoring/providers.rs:868–943
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
#[test]
fn typed_client_calls_preserve_order_and_native_history() {
let typed = json!({"toolUse":{
"type":"tool_use", "toolUseId":"client-1", "name":"habeas",
"input":{"file":"src/lib.rs","line_start":1}
}});
let reasoning = AssistantContent::Reasoning(Reasoning::new("Inspect the source."))
.with_native(json!({"reasoningContent":{"reasoningText":{
"text":"Inspect the source.","signature":"original-signature"
}}}));
let content = vec![
reasoning,
AssistantContent::Opaque(Opaque {
item: typed.clone(),
replay: true,
}),
AssistantContent::Text(Text::new("Then submit the judgment.")),
AssistantContent::Opaque(Opaque {
item: json!({"toolUse":{"type":"server_tool_use","toolUseId":"server-1","name":"server","input":{}}}),
replay: true,
}),
AssistantContent::Opaque(Opaque {
item: json!({"toolUse":{"type":"future_tool_use","toolUseId":"future-1","name":"future","input":{}}}),
replay: true,
}),
AssistantContent::ToolCall(ToolCall::from_wire(
"client-2",
ToolFunction::new(ToolName::new("list_files").unwrap(), json!({})),
)),
];
let origin = Origin::new(
"bedrock.converse",
"aws_bedrock",
"us.anthropic.claude-sonnet-5-5",
);
let raw = json!({"original":"provider response"});
let mut response = CompletionResponse::new(
content.clone(),
Usage::default(),
origin.clone(),
raw.clone(),
)
.with_finish_reason(FinishReason::ToolCalls);
response.provider_request_id = Some("request-1".into());
normalize_bedrock_client_calls(&mut response).unwrap();
assert_eq!(response.choice.len(), content.len());
for index in [0, 2, 3, 4, 5] {
assert_eq!(response.choice[index], content[index]);
}
let calls = response.tool_calls().collect::<Vec<_>>();
assert_eq!(calls.len(), 2);
assert_eq!(
calls[0].id,
rig_core::message::CallId::from_wire("client-1")
);
assert_eq!(calls[0].function.name.as_str(), "habeas");
assert_eq!(
calls[0].function.arguments,
typed["toolUse"]["input"].as_object().unwrap().clone()
);
assert_eq!(response.choice[1].native_item(), Some(&typed));
assert_eq!(
calls[1].id,
rig_core::message::CallId::from_wire("client-2")
);
assert_eq!(response.raw, raw);
assert_eq!(response.origin, origin);
assert_eq!(response.provider_request_id.as_deref(), Some("request-1"));
assert_eq!(response.finish_reason(), Some(FinishReason::ToolCalls));
let normalized = response.clone();
normalize_bedrock_client_calls(&mut response).unwrap();
assert_eq!(response, normalized);
}
Input 5: outline src/authoring/providers.rs mod[tests]/fn[malformed_typed_client_calls_are_reported]
- File:
src/authoring/providers.rs - Selector:
mod[tests]/fn[malformed_typed_client_calls_are_reported] - Kind:
fn src/authoring/providers.rs:945–965
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
#[test]
fn malformed_typed_client_calls_are_reported() {
for call in [
json!({"type":"tool_use","name":"habeas","input":{}}),
json!({"type":"tool_use","toolUseId":"id","input":{}}),
json!({"type":"tool_use","toolUseId":"id","name":"habeas","input":[]}),
] {
let mut response = CompletionResponse::new(
vec![AssistantContent::Opaque(Opaque {
item: json!({"toolUse":call}),
replay: true,
})],
Usage::default(),
Origin::new("bedrock.converse", "aws_bedrock", "model"),
Value::Null,
);
assert!(normalize_bedrock_client_calls(&mut response).is_err());
}
}
Input 6: outline tests/authoring_cli.rs fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]
- File:
tests/authoring_cli.rs - Selector:
fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] - Kind:
fn tests/authoring_cli.rs:366–676
// {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 7: outline tests/authoring_cli.rs fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]
- File:
tests/authoring_cli.rs - Selector:
fn[authoring_uses_nearest_workspace_configuration_without_a_user_file] - Kind:
fn tests/authoring_cli.rs:724–797
// {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 8: outline tests/authoring_cli.rs fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]
- File:
tests/authoring_cli.rs - Selector:
fn[bedrock_cli_uses_selected_profile_region_and_converse_tools] - Kind:
fn tests/authoring_cli.rs:1727–1920
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_cli_uses_selected_profile_region_and_converse_tools() {
for typed in [false, true] {
let mut read_call = json!({"toolUseId":"bedrock-read","name":"habeas",
"input":{"file":"extra.txt","line_start":1,"line_end":2}});
let mut submit_call = json!({"toolUseId":"bedrock-submit","name":"submit_judgment",
"input":{"determination":true,"rationale":"The supplied sources support the subject."}});
if typed {
read_call["type"] = json!("tool_use");
submit_call["type"] = json!("tool_use");
}
let first_message = json!({"role":"assistant","content":[
{"text":"Reading source."},{"toolUse":read_call}
]});
let server = Server::start(vec![
json!({
"output":{"message":first_message.clone()},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":submit_call}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
]);
let fixture = Fixture::new(&server.endpoint);
let credentials = fixture.temp.path().join("aws-credentials");
let aws_config = fixture.temp.path().join("aws-config");
fs::write(&credentials, "[default]\naws_access_key_id = WRONG_DEFAULT_ACCESS_KEY\naws_secret_access_key = wrong-default-secret\n[habeas-test]\naws_access_key_id = FAKE_PROFILE_ACCESS_KEY\naws_secret_access_key = fake-profile-secret-for-local-test-only\n").unwrap();
fs::write(&aws_config, "[profile habeas-test]\nregion = eu-west-1\n").unwrap();
fs::write(fixture.config.join("habeas/config.toml"), "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'fixture-bedrock-model'\naws_profile = 'habeas-test'\nregion = 'us-west-2'\n[authoring.configs.cloud.options]\ntemperature = 0.25\nmaxTokens = 321\ntopP = 0.75\nstopSequences = ['END']\ntop_k = 12\n").unwrap();
let mut command = fixture.command();
for key in [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_SECURITY_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_PROFILE",
"AWS_REGION",
"AWS_DEFAULT_REGION",
"AWS_ENDPOINT_URL",
"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
"AWS_BEARER_TOKEN_BEDROCK",
] {
command.env_remove(key);
}
let output = command
.env("AWS_CONFIG_FILE", aws_config)
.env("AWS_SHARED_CREDENTIALS_FILE", credentials)
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
.env("AWS_EC2_METADATA_DISABLED", "true")
.args(["author-evidence", SUBJECT])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].body["messages"][1], first_message);
let result = &requests[1].body["messages"][2]["content"][0]["toolResult"];
assert_eq!(result["toolUseId"], "bedrock-read");
let delivered = result["content"][0]["text"].as_str().unwrap();
assert!(delivered.contains("extra.txt") && delivered.contains("context line 1"));
assert!(
requests[0]
.headers
.starts_with("POST /model/fixture-bedrock-model/converse HTTP/1.1\r\n")
);
assert!(
requests[0]
.headers
.contains("Credential=FAKE_PROFILE_ACCESS_KEY/")
);
assert!(
requests[0]
.headers
.contains("/us-west-2/bedrock/aws4_request")
);
assert!(!requests[0].headers.contains("WRONG_DEFAULT_ACCESS_KEY"));
let body = &requests[0].body;
assert_eq!(
body["inferenceConfig"],
json!({"temperature":0.25,"maxTokens":321,"topP":0.75,"stopSequences":["END"]})
);
// A configured maxTokens is used as given on every request.
assert_eq!(requests[1].body["inferenceConfig"]["maxTokens"], 321);
assert_eq!(body["additionalModelRequestFields"], json!({"top_k":12}));
let prompt = prompt_text(body);
assert!(
prompt.contains("Assess whether a project's tests adequately check")
&& prompt.contains(REQUIREMENT)
);
let tool_specs = body["toolConfig"]["tools"].as_array().unwrap();
for tool in tool_specs {
let schema = &tool["toolSpec"]["inputSchema"]["json"];
assert_eq!(schema["type"], "object");
for unsupported in ["oneOf", "allOf", "anyOf"] {
assert!(
schema.get(unsupported).is_none(),
"Bedrock rejects {unsupported} at the root of {}'s input schema",
tool["toolSpec"]["name"]
);
}
}
let habeas_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "habeas")
.unwrap()["toolSpec"]["inputSchema"]["json"];
assert_eq!(habeas_schema["additionalProperties"], false);
for field in ["file", "item", "requirements", "definition"] {
assert_eq!(habeas_schema["properties"][field]["type"], "string");
}
for field in ["line_start", "line_end"] {
assert_eq!(habeas_schema["properties"][field]["type"], "integer");
assert_eq!(habeas_schema["properties"][field]["minimum"], 1);
}
let judgment_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "submit_judgment")
.unwrap()["toolSpec"]["inputSchema"]["json"]["properties"]["determination"];
let outcomes = judgment_schema["oneOf"].as_array().unwrap();
assert!(outcomes.iter().any(|outcome| outcome["type"] == "boolean"));
let fixme = &outcomes
.iter()
.find(|outcome| outcome["type"] == "object")
.unwrap()["properties"]["FIXME"];
assert_eq!(fixme["type"], "array");
assert_eq!(fixme["minItems"], 1);
assert_eq!(fixme["items"]["type"], "string");
assert_eq!(fixme["items"]["minLength"], 1);
let mut tools = tool_specs
.iter()
.map(|tool| tool["toolSpec"]["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 evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], true);
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.filter(|input| input["file"] == "extra.txt")
.collect::<Vec<_>>()
== habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 1, 2)
.unwrap()
.iter()
.collect::<Vec<_>>()
);
let usage = fixture.usage();
assert_eq!(usage["backend"], "bedrock");
assert_eq!(usage["model"], "fixture-bedrock-model");
assert_eq!(usage["tokens"]["input"], 38);
assert_eq!(usage["tokens"]["output"], 10);
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tool_calls"]["habeas"], 1);
assert_eq!(usage["tool_calls"]["submit_judgment"], 1);
assert_eq!(usage["outcome"], "completed");
}
}
Input 9: outline tests/authoring_cli.rs fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections]
- File:
tests/authoring_cli.rs - Selector:
fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections] - Kind:
fn tests/authoring_cli.rs:2481–2628
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.configuration_precedence`
#[test]
fn all_adapters_preserve_prompt_tools_and_evidence_with_default_connections() {
let submit =
json!({"determination":true,"rationale":"The supplied sources support the subject."});
// Ollama with no authentication configured sends no credential.
let server = Server::start(vec![reply(vec![call(
"submit",
"submit_judgment",
submit.clone(),
)])]);
let fixture = Fixture::new(&server.endpoint);
fs::write(
fixture.config.join("habeas/config.toml"),
format!(
"version = 1\n[authoring]\ndefault = 'local'\n[authoring.configs.local]\npolicy = 'once'\nbackend = 'ollama'\nmodel = '{MODEL}'\nendpoint = '{}'\n",
server.endpoint
),
)
.unwrap();
let output = fixture.run(&["author", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 1);
assert!(
!requests[0]
.headers
.to_ascii_lowercase()
.contains("authorization:")
);
assert_eq!(requests[0].body["model"], MODEL);
let ollama = prompt_and_tools(&requests[0].body);
let ollama_evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
// Bedrock without a profile or region uses the SDK default chain.
let server = Server::start(vec![json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":
{"toolUseId":"submit","name":"submit_judgment","input":submit.clone()}}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":1,"outputTokens":1,"totalTokens":2},
"metrics":{"latencyMs":1}
})]);
let fixture = Fixture::new(&server.endpoint);
fs::write(
fixture.config.join("habeas/config.toml"),
"version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'default-chain-model'\n",
)
.unwrap();
let mut command = fixture.command();
for key in [
"AWS_SESSION_TOKEN",
"AWS_SECURITY_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_PROFILE",
"AWS_DEFAULT_REGION",
"AWS_ENDPOINT_URL",
"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
"AWS_BEARER_TOKEN_BEDROCK",
] {
command.env_remove(key);
}
let output = command
.env("AWS_CONFIG_FILE", fixture.temp.path().join("no-aws-config"))
.env(
"AWS_SHARED_CREDENTIALS_FILE",
fixture.temp.path().join("no-aws-credentials"),
)
.env("AWS_ACCESS_KEY_ID", "DEFAULT_CHAIN_ACCESS_KEY")
.env("AWS_SECRET_ACCESS_KEY", "default-chain-secret")
.env("AWS_REGION", "ap-south-1")
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
.env("AWS_EC2_METADATA_DISABLED", "true")
.args(["author", SUBJECT])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 1);
let headers = &requests[0].headers;
assert!(headers.starts_with("POST /model/default-chain-model/converse HTTP/1.1\r\n"));
assert!(headers.contains("Credential=DEFAULT_CHAIN_ACCESS_KEY/"));
assert!(headers.contains("/ap-south-1/bedrock/aws4_request"));
let bedrock = prompt_and_tools(&requests[0].body);
let bedrock_evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
// OpenAI uses its default credential environment variable.
let server = Server::start(vec![json!({
"id":"resp_submit", "object":"response", "status":"completed",
"model":"fixture-openai", "output":[{
"type":"function_call", "id":"fc_submit", "call_id":"submit",
"name":"submit_judgment", "arguments":submit.to_string(), "status":"completed"
}],
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
})]);
let fixture = Fixture::new(&server.endpoint);
fs::write(
fixture.config.join("habeas/config.toml"),
format!("version = 1\n[authoring]\ndefault = 'api'\n[authoring.configs.api]\npolicy = 'once'\nbackend = 'openai'\nmodel = 'fixture-openai'\nendpoint = '{}'\n", server.endpoint),
).unwrap();
let output = fixture
.command()
.env("OPENAI_API_KEY", AUTH)
.args(["author", SUBJECT])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 1);
assert!(
requests[0]
.headers
.starts_with("POST /responses HTTP/1.1\r\n")
);
assert!(requests[0].headers.contains(&format!("Bearer {AUTH}")));
assert_eq!(requests[0].body["model"], "fixture-openai");
let openai = prompt_and_tools(&requests[0].body);
let openai_evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
// Identical projects and submissions must preserve both request semantics
// and the entire evidence document, including inputs and reference hashes.
assert_eq!(ollama, bedrock);
assert_eq!(ollama, openai);
assert_eq!(ollama.1.len(), 10);
assert_eq!(ollama_evidence["requirement"], REQUIREMENT);
assert_eq!(ollama_evidence["determination"], true);
assert_eq!(ollama_evidence["rationale"], submit["rationale"]);
assert_eq!(ollama_evidence, bedrock_evidence);
assert_eq!(ollama_evidence, openai_evidence);
}
Input 10: outline tests/authoring_cli.rs fn[openai_responses_replays_tool_calls_and_records_usage]
- File:
tests/authoring_cli.rs - Selector:
fn[openai_responses_replays_tool_calls_and_records_usage] - Kind:
fn tests/authoring_cli.rs:5173–5284
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.cache_checkpoints`
#[test]
// {test}`requirements.authoring.usage_storage`
fn openai_responses_replays_tool_calls_and_records_usage() {
fn assert_no_checkpoints(value: &Value) {
match value {
Value::Object(fields) => {
for (key, value) in fields {
assert!(
!matches!(key.as_str(), "cachePoint" | "cache_control"),
"explicit cache checkpoint: {key}"
);
if key == "type" {
assert!(
!matches!(value.as_str(), Some("cache_point" | "cache_checkpoint")),
"explicit cache checkpoint block: {value}"
);
}
assert_no_checkpoints(value);
}
}
Value::Array(values) => {
for value in values {
assert_no_checkpoints(value);
}
}
_ => {}
}
}
let response = |id: &str, name: &str, arguments: Value| {
json!({
"id": format!("resp_{id}"), "object":"response", "status":"completed",
"model":"fixture-openai", "output":[{
"type":"function_call", "id":format!("fc_{id}"), "call_id":id,
"name":name, "arguments":arguments.to_string(), "status":"completed"
}],
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
"input_tokens_details":{"cached_tokens":3},
"output_tokens_details":{"reasoning_tokens":2}}
})
};
let server = Server::start(vec![
response(
"read",
"habeas",
json!({"file":"extra.txt","line_start":10}),
),
response(
"submit",
"submit_judgment",
json!({"determination":false,"rationale":"Missing implementation."}),
),
]);
let fixture = Fixture::new(&server.endpoint);
fs::write(fixture.config.join("habeas/config.toml"), format!(
"version = 1\n[authoring]\ndefault = 'mock'\n[authoring.configs.mock]\nbackend = 'openai'\nmodel = 'fixture-openai'\npolicy = 'once'\nendpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.mock.options]\nmax_output_tokens = 1024\nreasoning = {{ effort = 'low' }}\n", server.endpoint)).unwrap();
let output = fixture.run(&["author-evidence", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
for request in &requests {
assert!(request.headers.starts_with("POST /responses HTTP/1.1\r\n"));
assert!(request.headers.contains(&format!("Bearer {AUTH}")));
assert_eq!(request.body["model"], "fixture-openai");
assert_eq!(request.body["max_output_tokens"], 1024);
assert_eq!(request.body["reasoning"]["effort"], "low");
assert_eq!(request.body["tools"].as_array().unwrap().len(), 10);
assert_no_checkpoints(&request.body);
}
assert!(
!requests[0].body["instructions"]
.as_str()
.unwrap()
.is_empty()
);
assert_eq!(
requests[0].body["instructions"],
requests[1].body["instructions"]
);
assert_eq!(requests[0].body["tools"], requests[1].body["tools"]);
let initial_input = requests[0].body["input"].as_array().unwrap();
let history = requests[1].body["input"].as_array().unwrap();
assert_eq!(history.len(), initial_input.len() + 2);
assert_eq!(&history[..initial_input.len()], initial_input.as_slice());
assert_eq!(history[initial_input.len()]["type"], "function_call");
assert_eq!(history[initial_input.len()]["call_id"], "read");
assert_eq!(
history[initial_input.len() + 1]["type"],
"function_call_output"
);
assert_eq!(history[initial_input.len() + 1]["call_id"], "read");
let usage = fixture.usage();
assert_eq!(usage["backend"], "openai");
assert_eq!(usage["outcome"], "completed");
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tokens"]["input"], 22);
assert_eq!(usage["tokens"]["output"], 14);
assert_eq!(usage["tokens"]["cached_input"], 6);
assert_eq!(usage["tokens"]["reasoning"], 4);
assert!(!usage.to_string().contains(AUTH));
}
Input 11: outline tests/configuration.rs fn[explicit_project_and_default_selections_choose_whole_configs]
- File:
tests/configuration.rs - Selector:
fn[explicit_project_and_default_selections_choose_whole_configs] - Kind:
fn tests/configuration.rs:261–336
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.structure`
#[test]
// {test}`requirements.authoring.configuration_structure`
fn explicit_project_and_default_selections_choose_whole_configs() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let config_path = root.join("config.toml");
let mut config = UserConfig::parse(
r#"
version = 1
[authoring]
default = "default"
[authoring.configs.default]
backend = "bedrock"
model = "cloud-id"
aws_profile = "named"
[authoring.configs.project]
backend = "ollama"
model = "project:tag"
endpoint = "http://server:11434"
[authoring.configs.explicit]
backend = "ollama"
model = "explicit:tag"
"#,
&config_path,
)
.unwrap();
assert_eq!(
resolve_authoring_from(&config_path, Some(&config), &root, None)
.unwrap()
.name,
"default"
);
config.authoring.as_mut().unwrap().projects.insert(
root.clone(),
habeas::config::ProjectSelection {
config: "project".to_owned(),
},
);
let project =
resolve_authoring_from(&config_path, Some(&config), &root.join("."), None).unwrap();
assert_eq!(project.name, "project");
assert_eq!(project.project_root, root);
let BackendConfig::Ollama(ollama) = project.backend else {
panic!("wrong backend")
};
assert_eq!(ollama.endpoint(), "http://server:11434");
let explicit =
resolve_authoring_from(&config_path, Some(&config), &root, Some("explicit")).unwrap();
let BackendConfig::Ollama(ollama) = explicit.backend else {
panic!("wrong backend")
};
assert_eq!(ollama.model, "explicit:tag");
assert_eq!(ollama.endpoint, None);
let error = resolve_authoring_from(&config_path, Some(&config), &root, Some("DEFAULT"))
.unwrap_err()
.to_string();
assert!(error.contains("DEFAULT"));
assert!(error.contains("config.toml"));
assert!(error.contains("editing-the-file"));
// Missing configuration names the file and points to documented examples.
let missing = resolve_authoring_from(&config_path, None, &root, None)
.unwrap_err()
.to_string();
assert!(missing.contains("no authoring configuration"), "{missing}");
assert!(
missing.contains(&config_path.display().to_string()),
"{missing}"
);
assert!(missing.contains("editing-the-file"), "{missing}");
}
Other sources
Input 1: requirements selection requirements.authoring.rig_configuration_mapping
requirements.authoring.rig_configuration_mapping:md/requirements/authoring.md:1901–1912
:::{req} rig_configuration_mapping
Habeas MUST resolve its saved configuration before constructing Rig provider
clients and completion models. The Habeas data structures MUST remain the saved
format. Rig model references MAY be reused internally without discarding the
connection settings they do not represent.
The Bedrock adapter MUST pass the chosen AWS profile and region through AWS SDK
configuration, or use explicitly configured credentials. The Ollama adapter MUST use the chosen server, exact model ID,
and optional authentication; the server MAY be local or remote. The OpenAI adapter MUST use the Responses API, selected endpoint, exact model
ID, and resolved API key. All adapters
MUST supply the same tools and initial prompt.
:::
Input 12: outline tests/authoring_cli.rs fn[prompt_and_tools]
- File:
tests/authoring_cli.rs - Selector:
fn[prompt_and_tools] - Kind:
fn tests/authoring_cli.rs:2451–2479
/// Returns the first request's prompt and sorted tool definitions, removing
/// only the provider-specific envelopes around each definition.
// {test}`requirements.authoring.prompt_parts`
fn prompt_and_tools(body: &Value) -> (String, Vec<(String, String, Value)>) {
let tools = body
.get("toolConfig")
.map_or(&body["tools"], |config| &config["tools"]);
let mut tools = tools
.as_array()
.unwrap()
.iter()
.map(|tool| {
let spec = tool
.get("toolSpec")
.or_else(|| tool.get("function"))
.unwrap_or(tool);
let parameters = spec
.get("inputSchema")
.map_or(&spec["parameters"], |schema| &schema["json"]);
(
spec["name"].as_str().unwrap().to_owned(),
spec["description"].as_str().unwrap().to_owned(),
parameters.clone(),
)
})
.collect::<Vec<_>>();
tools.sort_by(|left, right| left.0.cmp(&right.0));
(prompt_text(body), tools)
}