Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 2 additions & 38 deletions crates/candler-core/src/resolve/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,42 +532,6 @@ fn covers(kind: Kind, root: &FieldPath, path: &FieldPath) -> bool {
}
}

/// A text no variant of `T` names, refused at `path` with the accepted spellings.
fn unnamed(path: &FieldPath, text: &str, accepted: &[&str]) -> DriverError {
DriverError::InvalidValue {
path: path.clone(), // BORROW: the error owns the path
detail: format!(
"is `{text}`; the accepted texts are {}",
accepted.join(", ")
),
}
}

/// The effort level the cell holds at `path`, refusing text that names no level. The cell keeps
/// the text; [`Cell::effort`] maps the text checked here.
fn effort_at(cell: &Cell<'_>, path: &FieldPath) -> Result<Option<EffortLevel>, DriverError> {
cell.text(path)?
.map(|text| {
EffortLevel::from_text(text)
.ok_or_else(|| unnamed(path, text, &EffortLevel::ALL.map(EffortLevel::as_str)))
})
.transpose()
}

/// The permission mode the cell holds at `path`, refusing text that names no mode, or `None` when
/// the cell sets none. The cell keeps the text; [`Cell::permission_mode`] maps the text checked
/// here. A cell that sets no mode asks nothing of the driver: what the harness does then is its
/// [`candler_harness::spec::DriverFact::UnsetPermissionMode`].
fn mode_at(cell: &Cell<'_>, path: &FieldPath) -> Result<Option<PermissionMode>, DriverError> {
cell.text(path)?
.map(|text| {
PermissionMode::from_text(text).ok_or_else(|| {
unnamed(path, text, &PermissionMode::ALL.map(PermissionMode::as_str))
})
})
.transpose()
}

/// The settings `cell` sets, each with the path of the row that reaches it and with the value the
/// cell gives it, in the order of [`CONFIGURATION_PATHS`]. The rows are the only place a path
/// meets a setting. The skills and the session mode are not read here: the treatment holds the
Expand All @@ -592,10 +556,10 @@ pub fn settings_set_by(cell: &Cell<'_>) -> Result<Vec<(AgentSetting, FieldPath)>
for family in families {
match family {
AgentSetting::Effort(_) => {
found.extend(effort_at(cell, &path)?.map(AgentSetting::Effort));
found.extend(cell.effort_at(&path)?.map(AgentSetting::Effort));
}
AgentSetting::PermissionMode(_) => {
found.extend(mode_at(cell, &path)?.map(AgentSetting::PermissionMode));
found.extend(cell.mode_at(&path)?.map(AgentSetting::PermissionMode));
}
// The three keys of a server are read together, from the transport's entry.
AgentSetting::McpTransport(_) => {
Expand Down
8 changes: 4 additions & 4 deletions crates/candler-harness-claude-code/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub(crate) enum Launch {
/// cell sets.
pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result<Vec<String>, DriverError> {
let model = cell.model()?;
let mode = cell.permission_mode();
let mode = cell.permission_mode()?;
// BORROW: .to_owned() makes the owned arguments the command keeps
let mut argv = vec![PROGRAM.to_owned(), "--print".to_owned()];
// Each launch keeps the order of its recorded command line.
Expand All @@ -114,7 +114,7 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result<Vec<String>, Drive
]
.map(str::to_owned), // BORROW: str::to_owned makes the owned arguments
);
if let Some(effort) = cell.effort() {
if let Some(effort) = cell.effort()? {
argv.extend(["--effort", effort.as_str()].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments
}
if let Some(turns) = cap_text(cell, paths::BUDGET_PER_RUN_TURNS, true)? {
Expand All @@ -125,7 +125,7 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result<Vec<String>, Drive
argv.push("--max-budget-usd".to_owned()); // BORROW: .to_owned() makes the owned argument
argv.push(cost);
}
if prepare::mcp_servers(cell)?.is_some() {
if candler_harness::mcp::servers(cell)?.is_some() {
// Only the servers of the cell: no other MCP configuration reaches the agent.
argv.extend(["--mcp-config", prepare::MCP_FILE, "--strict-mcp-config"].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments
}
Expand Down Expand Up @@ -320,7 +320,7 @@ impl HarnessDriver for ClaudeCodeDriver {
fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> {
cap_text(cell, paths::BUDGET_PER_RUN_TURNS, true)?;
cap_text(cell, paths::BUDGET_PER_RUN_MAX_COST_USD, false)?;
prepare::mcp_servers(cell).map(|_| ())
candler_harness::mcp::servers(cell).map(|_| ())
}

fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError> {
Expand Down
11 changes: 1 addition & 10 deletions crates/candler-harness-claude-code/src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
//!
//! Nothing here touches the file system or runs a process.

use std::collections::BTreeMap;
use std::str::FromStr as _;

use candler_harness::driver::DriverError;
Expand Down Expand Up @@ -88,14 +87,6 @@ pub fn render_settings(cell: &Cell<'_>) -> Result<PreparedFile, DriverError> {
/// The file the MCP configuration is written to, and that the agent command names.
pub(crate) const MCP_FILE: &str = ".mcp.json";

/// The servers of a cell, by the name the agent sees: see [`candler_harness::mcp::servers`].
///
/// # Errors
/// [`DriverError`] when a value of the cell cannot be used, or a server name is refused.
pub fn mcp_servers(cell: &Cell<'_>) -> Result<Option<BTreeMap<String, McpServer>>, DriverError> {
candler_harness::mcp::servers(cell)
}

/// One server as Claude Code's `.mcp.json` documents it: `stdio` with `command`, `args` and `env`,
/// `http` or `sse` with `url` and `headers`. A `local` server is written as `stdio` and a `remote`
/// one as `http`.
Expand Down Expand Up @@ -143,7 +134,7 @@ fn mcp_entry(name: &str, server: &McpServer) -> Result<Value, DriverError> {
/// # Errors
/// [`DriverError`] when a value of the cell cannot be used.
pub fn render_mcp(cell: &Cell<'_>) -> Result<Option<PreparedFile>, DriverError> {
let Some(servers) = mcp_servers(cell)? else {
let Some(servers) = candler_harness::mcp::servers(cell)? else {
return Ok(None);
};
let entries = servers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use candler_harness::spec::{Cell, CollectSpec, EnvValue, Observed, StopSignal, W
use candler_harness_claude_code::driver::ClaudeCodeDriver;
use candler_schemas::execution::{GitCommit, TreatmentRef};
use candler_schemas::primitives::{FieldPath, Name};
use candler_schemas::refusal::Refusal;
use candler_schemas::values::{JsonValue, ResolvedValue};
use serde_json::json;

Expand Down Expand Up @@ -140,6 +141,38 @@ fn b21_reference_command_line() -> Res<()> {
Ok(())
}

/// Guards: a stored cell, which replays without going through resolve, that holds a permission mode
/// or an effort no mode or level names is refused by the driver with `experiment.cell_value_invalid`
/// at the field, as a fresh cell is, and is not run as the default mode or without an effort.
/// Oracle: the code and the field pointers written by hand.
/// Bite: read the text with a `from_text` that falls back to the default or to unset.
#[test]
fn a_stored_cell_with_an_unnamed_mode_or_effort_is_refused_at_its_field() -> Res<()> {
let driver = ClaudeCodeDriver::new();
let root = Path::new("/work/run");
for (path, pointer) in [
("permission_mode", "/permission_mode"),
("model.effort", "/model/effort"),
] {
let mut stored = values("plan")?;
stored.retain(|value| value.path().as_str() != path);
stored.push(ResolvedValue::recorded(
FieldPath::from_str(path)?,
JsonValue::new(json!("nonsense"))?,
));
let Err(error) = driver.plan(&Cell::new(&stored), &Workspace::new(root)) else {
return Err(format!("{path}: an unnamed text planned").into());
};
assert_eq!(
Refusal::code(&error).as_str(),
"experiment.cell_value_invalid",
"{path}"
);
assert_eq!(Refusal::path(&error).as_deref(), Some(pointer), "{path}");
}
Ok(())
}

/// One regular file of a ustar archive: the header, then the contents padded to a block.
fn tar_entry(path: &str, contents: &[u8]) -> Vec<u8> {
let mut header = vec![0_u8; 512];
Expand Down
2 changes: 1 addition & 1 deletion crates/candler-harness-opencode/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ impl HarnessDriver for OpenCodeDriver {

fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> {
prepare::settings(cell)?;
let names: Vec<String> = prepare::mcp_servers(cell)?
let names: Vec<String> = candler_harness::mcp::servers(cell)?
.map(|servers| servers.into_keys().collect())
.unwrap_or_default();
ambiguous_prefixes(&names)
Expand Down
16 changes: 2 additions & 14 deletions crates/candler-harness-opencode/src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use candler_schemas::execution::paths::{
use candler_schemas::primitives::{FieldPath, RelPath};
use candler_schemas::servers::{McpServer, McpServerKind};
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;

/// The provider's id in the configuration and in `-m <provider>/<model>`.
pub(crate) const PROVIDER: &str = "candler";
Expand Down Expand Up @@ -438,7 +437,7 @@ fn claude_info(id: &str) -> Option<ClaudeInfo> {
/// `OpenCode` would give no such variant (see `EFFORT_MODEL`) is refused here, not left to fail
/// or be ignored at run time.
fn effort_variant(cell: &Cell<'_>) -> Result<Option<(String, Value)>, DriverError> {
let Some(level) = cell.effort() else {
let Some(level) = cell.effort()? else {
return Ok(None);
};
let accepted = claude_info(model_id(cell)?).is_some_and(|info| {
Expand Down Expand Up @@ -481,17 +480,6 @@ pub(crate) fn settings(cell: &Cell<'_>) -> Result<Settings, DriverError> {
})
}

/// The servers of the cell by the name the agent sees, read from the `mcp.servers.*` leaves as the
/// resolver gives them (see [`candler_harness::mcp::servers`]). `None` when the cell sets no server.
///
/// # Errors
/// [`DriverError::InvalidValue`] when a value cannot be used or a server name is refused.
pub(crate) fn mcp_servers(
cell: &Cell<'_>,
) -> Result<Option<BTreeMap<String, McpServer>>, DriverError> {
candler_harness::mcp::servers(cell)
}

/// The `opencode.json` of the run: the provider, the model, the effort variant and the
/// permission rows of `settings`, and the MCP servers. `config_dir` is the home-relative directory
/// that `XDG_CONFIG_HOME` names.
Expand Down Expand Up @@ -525,7 +513,7 @@ pub(crate) fn render_config(
"models": models,
} }),
);
if let Some(servers) = mcp_servers(cell)? {
if let Some(servers) = candler_harness::mcp::servers(cell)? {
let mut translated = Map::new();
for (name, entry) in &servers {
translated.insert(name.clone(), server(entry)); // BORROW: .clone() copies the name
Expand Down
78 changes: 60 additions & 18 deletions crates/candler-harness/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,17 @@ pub struct Cell<'a> {
values: &'a [ResolvedValue],
}

/// A text no variant names, refused at `path` with the accepted spellings.
fn unnamed(path: &FieldPath, text: &str, accepted: &[&str]) -> DriverError {
DriverError::InvalidValue {
path: path.clone(), // BORROW: the error owns the path
detail: format!(
"is `{text}`; the accepted texts are {}",
accepted.join(", ")
),
}
}

impl<'a> Cell<'a> {
/// A view of the resolved values of a cell.
#[must_use]
Expand Down Expand Up @@ -1496,27 +1507,58 @@ impl<'a> Cell<'a> {
self.required_text(&field_path!(paths::MODEL_ID))
}

/// The effort level the cell holds at `path`, or `None` when the cell sets none. The one place
/// effort text becomes a level: resolve and [`Cell::effort`] both read it here, so a stored cell
/// that replays without resolve is refused as a fresh one is.
///
/// # Errors
/// [`DriverError::InvalidValue`] at `path` when the value is not text or names no level.
pub fn effort_at(&self, path: &FieldPath) -> Result<Option<EffortLevel>, DriverError> {
self.text(path)?
.map(|text| {
EffortLevel::from_text(text)
.ok_or_else(|| unnamed(path, text, &EffortLevel::ALL.map(EffortLevel::as_str)))
})
.transpose()
}

/// The permission mode the cell holds at `path`, or `None` when the cell sets none. The one
/// place mode text becomes a mode: resolve and [`Cell::permission_mode`] both read it here. A
/// cell that sets no mode asks nothing of the driver: what the harness does then is its
/// [`DriverFact::UnsetPermissionMode`].
///
/// # Errors
/// [`DriverError::InvalidValue`] at `path` when the value is not text or names no mode.
pub fn mode_at(&self, path: &FieldPath) -> Result<Option<PermissionMode>, DriverError> {
self.text(path)?
.map(|text| {
PermissionMode::from_text(text).ok_or_else(|| {
unnamed(path, text, &PermissionMode::ALL.map(PermissionMode::as_str))
})
})
.transpose()
}

/// The permission mode the cell sets, or [`PermissionMode::Default`] when it sets none, which
/// is the mode Claude Code's command line carries for a cell without one. The cell holds the
/// text; resolve refuses text that names no mode, and this maps the text it checked. Text that
/// never went through resolve and names no mode reads as [`PermissionMode::Default`]. No driver
/// is asked about an unset mode: [`DriverFact::UnsetPermissionMode`] states it.
#[must_use]
pub fn permission_mode(&self) -> PermissionMode {
self.value(&field_path!(paths::PERMISSION_MODE))
.and_then(Value::as_str)
.and_then(PermissionMode::from_text)
.unwrap_or(PermissionMode::Default)
/// is the mode Claude Code's command line carries for a cell without one. No driver is asked
/// about an unset mode: [`DriverFact::UnsetPermissionMode`] states it.
///
/// # Errors
/// [`DriverError::InvalidValue`] at `permission_mode` when the value is not text or names no
/// mode, as [`Cell::mode_at`] returns it.
pub fn permission_mode(&self) -> Result<PermissionMode, DriverError> {
Ok(self
.mode_at(&field_path!(paths::PERMISSION_MODE))?
.unwrap_or(PermissionMode::Default))
}

/// The reasoning effort, if the cell sets one. The cell holds the text; resolve refuses text
/// that names no level, and this maps the text it checked. Text that never went through resolve
/// and names no level reads as unset.
#[must_use]
pub fn effort(&self) -> Option<EffortLevel> {
self.value(&field_path!(paths::MODEL_EFFORT))
.and_then(Value::as_str)
.and_then(EffortLevel::from_text)
/// The reasoning effort, if the cell sets one.
///
/// # Errors
/// [`DriverError::InvalidValue`] at `model.effort` when the value is not text or names no
/// level, as [`Cell::effort_at`] returns it.
pub fn effort(&self) -> Result<Option<EffortLevel>, DriverError> {
self.effort_at(&field_path!(paths::MODEL_EFFORT))
}

/// The prompt: the cell's template, filled by [`render_prompt`] from its values.
Expand Down