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
104 changes: 104 additions & 0 deletions __reports__/diet/leaves/pages_v0.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/candler-harness-claude-code/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ impl HarnessDriver for ClaudeCodeDriver {
reason: "tools run in the child process",
},
DriverFact::Census => Answer::Mapped {
construct: "the tool list of the `system/init` event",
construct: "Claude Code's `system/init` event lists the tools",
},
DriverFact::UnsetPermissionMode => Answer::Mapped {
construct: "`--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it",
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 @@ -174,7 +174,7 @@ impl HarnessDriver for OpenCodeDriver {
construct: "tools run in the `serve` child, which the stop interrupts first",
},
DriverFact::Census => Answer::Candler {
how: "the gateway's first model request with tools",
how: "the tools the gateway offered the model in its first request",
},
DriverFact::UnsetPermissionMode => Answer::Candler {
how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode",
Expand Down
32 changes: 25 additions & 7 deletions crates/candler/tests/it/contract_pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ fn versions() -> Versions {
Versions::read(&repo_root()).expect("the manifests are readable")
}

/// Compares a file with its generated text, or writes it when blessing.
/// Compares a file with its generated text, or writes it when blessing. The panic names the first
/// differing line, and when it is a row of a table, its first cell: the row of a Fields table
/// (a path, a capability label or a code), so a driver whose answer changed is followed to the row
/// at fault.
fn settle(name: &str, generated: &str) {
let path = docs_dir().join(name);
let current = fs::read_to_string(&path).ok();
Expand All @@ -45,14 +48,25 @@ fn settle(name: &str, generated: &str) {
panic!("docs/contract/{name} does not exist; regenerate with CANDLER_BLESS_CONTRACT=1")
}
Some(current) => {
let at = current
let line = current
.lines()
.zip(generated.lines())
.position(|(a, b)| a != b)
.unwrap_or(current.lines().count().min(generated.lines().count()));
.unwrap_or(current.lines().count().min(generated.lines().count()))
+ 1;
let current_line = current.lines().nth(line - 1).unwrap_or_default();
let generated_line = generated.lines().nth(line - 1).unwrap_or_default();
let row = current_line
.strip_prefix("| ")
.and_then(|rest| rest.split(" | ").next())
.map(|label| label.trim_end_matches(' '))
.filter(|label| !label.is_empty())
.map_or_else(
|| "a line of the surface outside a table".to_owned(),
|label| format!("the `{label}` row"),
);
panic!(
"docs/contract/{name} differs from the generated page at line {}; regenerate with CANDLER_BLESS_CONTRACT=1",
at + 1
"docs/contract/{name} differs at line {line} in {row}: committed `{current_line}` vs generated `{generated_line}`; regenerate with CANDLER_BLESS_CONTRACT=1"
);
}
}
Expand Down Expand Up @@ -98,8 +112,12 @@ fn d1_regenerating_the_pages_changes_nothing() {
)
.expect("the capability page is rendered");
settle("harness-capabilities.md", &capabilities);
let paths = render_paths(&versions, existing("configuration-paths.md").as_deref())
.expect("the configuration paths page is rendered");
let paths = render_paths(
registry,
&versions,
existing("configuration-paths.md").as_deref(),
)
.expect("the configuration paths page is rendered");
settle("configuration-paths.md", &paths);
let file_page = render_file_page(&versions, existing("config-file.md").as_deref())
.expect("the configuration file page is rendered");
Expand Down
258 changes: 76 additions & 182 deletions crates/candler/tests/it/support/contract_pages/capabilities.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
//! The capability page: what a run can expect of each driver the binary registers, one column per
//! driver and one row per capability.
//! driver and one row per setting, per fact and per typed spec.
//!
//! Each row has one mapping from what a driver declares to the words of its cell, so a reader never
//! meets two spellings of one fact.
//! The rows come from `AgentSetting::ALL` and `DriverFact::ALL`, one row per entry, plus the rows a
//! driver does not declare words for (gateway route, authoritative trace), which read the driver's
//! typed specs. Each cell of a setting or fact row is [`answer_words`] of the driver's `answer` or
//! `fact`; a reader never meets one fact in two spellings.

use std::fmt::Write;
use std::path::Path;
use std::str::FromStr as _;
use std::sync::Arc;

use candler_harness::driver::HarnessDriver;
use candler_harness::spec::{Action, AgentSetting, Answer, DriverFact, StopSignal, StopSpec};
use candler_schemas::execution::{GitCommit, TreatmentRef};
use candler_schemas::primitives::Name;
use candler_harness::spec::{AgentSetting, DriverFact};

use super::harness::{HarnessPage, assemble, cell, version_section};
use super::refusals::{Entry, catalogue_entries};
use super::versions::Versions;
use super::{answer_words, setting_label};
use crate::drivers::Registry;

/// The page of the capabilities of the registered drivers.
Expand All @@ -34,117 +33,34 @@ const CAPABILITY_CODES: [&str; 2] = [
"experiment.setting_unsupported",
];

/// A cell of the capability table, from one driver.
type Mapping = fn(&str, &Arc<dyn HarnessDriver>, &Registry) -> Result<String, String>;

/// The rows of the capability table: the row's name and the one mapping that words its cells.
const ROWS: [(&str, Mapping); 9] = [
("gateway route", gateway_route),
("census source", census_source),
("session mode", session_mode),
("turn cap", turn_cap),
("cost cap", cost_cap),
("stop", stop),
("authoritative trace", authoritative_trace),
("skills layout", skills_layout),
("permission mode when none is set", unset_permission_mode),
];
/// The label of the row a driver fact words.
const fn fact_label(fact: DriverFact) -> &'static str {
match fact {
DriverFact::GracefulStop => "graceful stop",
DriverFact::LiveEvents => "live events",
DriverFact::InHarnessGuard => "in-harness guard",
DriverFact::ExecutionOutsideChild => "execution outside the child",
DriverFact::Census => "census source",
DriverFact::UnsetPermissionMode => "permission mode when none is set",
}
}

fn gateway_route(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
/// The cell of one driver for its gateway variables.
///
/// # Errors
/// `Err` when the driver names no gateway variables; no registered driver fails this.
fn gateway_route(driver: &Arc<dyn HarnessDriver>) -> Result<String, String> {
let env = driver
.gateway()
.ok_or("a registered driver names its gateway variables")?;
Ok(format!("Candler: gateway, address in `{}`", env.base_url))
}

fn census_source(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
match (
!driver.fact(DriverFact::Census).is_refused(),
driver.census_stream(),
) {
(true, Some(_)) => Ok("Candler: gateway, first request with tools".to_owned()),
(true, None) => Ok("yes".to_owned()),
(false, _) => Err("a registered driver without a census has no cell wording".to_owned()),
}
}

#[expect(
clippy::unnecessary_wraps,
reason = "every row of the table has the one mapping type"
)]
fn session_mode(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
Ok(cap(driver.answer(AgentSetting::SessionMode)))
}

/// A cap the harness or Candler enforces is `yes`; one nobody enforces is refused.
fn cap(answer: Answer) -> String {
if answer.is_refused() {
"no (refused)".to_owned()
} else {
"yes".to_owned()
}
}

#[expect(
clippy::unnecessary_wraps,
reason = "every row of the table has the one mapping type"
)]
fn turn_cap(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
Ok(cap(driver.answer(AgentSetting::TurnBudget)))
}

#[expect(
clippy::unnecessary_wraps,
reason = "every row of the table has the one mapping type"
)]
fn cost_cap(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
Ok(cap(driver.answer(AgentSetting::CostBudget)))
}

fn unset_permission_mode(
_: &str,
driver: &Arc<dyn HarnessDriver>,
_: &Registry,
) -> Result<String, String> {
match driver.fact(DriverFact::UnsetPermissionMode) {
Answer::Mapped { construct } => Ok(construct.to_owned()), // BORROW: .to_owned() makes the owned cell text
Answer::Candler { how } => Ok(format!("Candler: {how}")),
Answer::Refused { .. } => {
Err("a registered driver has a mode for a cell that sets none".to_owned())
}
}
}

fn signal(spec: &StopSpec) -> Result<&'static str, String> {
match spec.signal {
StopSignal::Term => Ok("SIGTERM"),
StopSignal::Int => Ok("SIGINT"),
StopSignal::Hup => Ok("SIGHUP"),
_ => Err("a stop signal has no wording".to_owned()),
}
}

fn stop(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
let spec = driver.stop();
let signal = signal(&spec)?;
match (
&spec.pre_stop,
!driver.fact(DriverFact::GracefulStop).is_refused(),
) {
(None, true) => Ok("yes".to_owned()),
(Some(Action::Exec(_)), _) => Ok(format!(
"Candler: interrupt command in the container, then {signal}"
)),
(Some(Action::Command(_)), _) => Ok(format!(
"Candler: interrupt command on the host, then {signal}"
)),
(Some(Action::Http { .. }), _) => Ok(format!("Candler: interrupt request, then {signal}")),
(None, false) | (Some(_), _) => {
Err("a registered driver's stop has no cell wording".to_owned())
}
}
}

/// The cell of one driver for its authoritative trace: the offline stream the registry collects,
/// or the driver's live reader when it streams events itself.
///
/// # Errors
/// `Err` when the driver's trace has no cell wording; no registered driver fails this.
fn authoritative_trace(
name: &str,
driver: &Arc<dyn HarnessDriver>,
Expand All @@ -159,67 +75,33 @@ fn authoritative_trace(
Err("a registered driver's trace has no cell wording".to_owned())
}

/// A treatment whose tree the driver's skill layout is asked about.
fn probe_treatment() -> Result<TreatmentRef, String> {
let name = Name::from_str("probe").map_err(|e| e.to_string())?;
let mut treatment = TreatmentRef::new(name);
treatment.commit = Some(GitCommit::from_str(&"0".repeat(40)).map_err(|e| e.to_string())?);
Ok(treatment)
}

/// A tar archive with one regular file `path` that holds `x`.
fn tar_of(path: &str) -> Vec<u8> {
let mut header = [0_u8; 512];
header[..path.len()].copy_from_slice(path.as_bytes());
header[100..107].copy_from_slice(b"0000644");
header[124..135].copy_from_slice(b"00000000001");
header[136..147].copy_from_slice(b"00000000000");
header[156] = b'0';
header[257..263].copy_from_slice(b"ustar\0");
header[148..156].copy_from_slice(b" ");
let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum();
header[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
let mut out = header.to_vec();
let mut data = [0_u8; 512];
data[0] = b'x';
out.extend_from_slice(&data);
out.extend_from_slice(&[0_u8; 1024]);
out
}

fn skills_layout(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> {
let treatment = probe_treatment()?;
let skills = driver.skills();
let archive = skills
.archive_command(&treatment, Path::new("/probe"))
.map_err(|e| e.to_string())?;
let subtree = archive
.argv()
.last()
.ok_or("the archive command has no pathspec")?
.clone();
let files = skills
.files(&treatment, &tar_of(&format!("{subtree}/SKILL.md")))
.map_err(|e| e.to_string())?;
let first = files
.first()
.map(|file| file.path.as_str())
.ok_or("the layout places no file")?;
let tree = first
.strip_suffix("/SKILL.md")
.ok_or("the layout does not place SKILL.md")?;
if tree == subtree {
Ok("yes".to_owned())
} else {
Ok(format!(
"Candler: places the tree at `{}`",
tree.replace("probe", "<name>")
))
/// Writes one row: the label and each driver's cell.
///
/// # Errors
/// [`CliError`](crate::commands::CliError) of the registry, when no registered driver has the
/// name; no registered driver fails a cell.
fn write_row(
out: &mut String,
label: &str,
names: &[String],
registry: &Registry,
cells: impl Fn(&str, &Arc<dyn HarnessDriver>) -> Result<String, String>,
) -> Result<(), String> {
let _ = write!(out, "| {label} |");
for name in names {
let driver = registry
.driver(name)
.map_err(|_| format!("no driver for `{name}`"))?;
let text = cells(name, &driver).map_err(|e| format!("{label} of `{name}`: {e}"))?;
let _ = write!(out, " {} |", cell(&text));
}
out.push('\n');
Ok(())
}

/// The capability table: one row per capability, one column per registered driver.
fn capability_fields(registry: &Registry) -> Result<String, String> {
/// The capability table: one row per setting, per typed spec or per fact, one column per
/// registered driver.
fn fields_table(registry: &Registry) -> Result<String, String> {
let names = registry.names();
let mut out = String::from("| Capability |");
for name in &names {
Expand All @@ -230,17 +112,29 @@ fn capability_fields(registry: &Registry) -> Result<String, String> {
out.push_str("---|");
}
out.push('\n');
for (label, mapping) in ROWS {
let _ = write!(out, "| {label} |");
for name in &names {
let driver = registry
.driver(name)
.map_err(|_| format!("no driver for `{name}`"))?;
let text = mapping(name, &driver, registry)
.map_err(|e| format!("{label} of `{name}`: {e}"))?;
let _ = write!(out, " {} |", cell(&text));
}
out.push('\n');
for setting in AgentSetting::ALL {
write_row(
&mut out,
setting_label(setting),
&names,
registry,
|_, driver| Ok(answer_words(driver.answer(setting))),
)?;
}
write_row(&mut out, "gateway route", &names, registry, |_, driver| {
gateway_route(driver)
})?;
write_row(
&mut out,
"authoritative trace",
&names,
registry,
|name, driver| authoritative_trace(name, driver, registry),
)?;
for fact in DriverFact::ALL {
write_row(&mut out, fact_label(fact), &names, registry, |_, driver| {
Ok(answer_words(driver.fact(fact)))
})?;
}
Ok(out)
}
Expand All @@ -266,7 +160,7 @@ pub fn render_capabilities(
&CAPABILITY_PAGE,
CAPABILITY_SURFACE,
&version_section(versions)?,
&capability_fields(registry)?,
&fields_table(registry)?,
&refusals,
existing,
))
Expand Down
Loading