brokkr-ctl: host rows from the host snapshot in validate, send --help and status

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 06:11:51 +01:00
commit 7b47fa5b83
3 changed files with 240 additions and 15 deletions

View file

@ -2,7 +2,9 @@
//! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads
//! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by
//! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still
//! decided by the add-on.
//! decided by the add-on. Host add-ons' rows (`brokkr.blender.host_actions.v0`) are not embedded: they come
//! from the add-on's host snapshot (`hostActions`), are searched after the built-ins, and are pinned by
//! `surfaces/blender/tests/host_action_cases.json`; a stale snapshot can only make ctl refuse early.
use serde_json::{Map, Value};
use std::sync::LazyLock;
@ -20,8 +22,12 @@ fn actions() -> &'static [Value] {
table()["actions"].as_array().map_or(&[], Vec::as_slice)
}
fn entry(name: &str) -> Option<&'static Value> {
actions().iter().find(|a| a["name"] == name)
/// The built-in row of that name, else the first host row of that name.
fn entry<'a>(name: &str, host: &'a [Value]) -> Option<&'a Value> {
actions()
.iter()
.chain(host)
.find(|a| a["name"] == name)
}
/// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them.
@ -66,9 +72,9 @@ pub fn number_text(value: f64) -> String {
}
/// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults).
pub fn validate(command: &Map<String, Value>) -> Result<(), String> {
pub fn validate(command: &Map<String, Value>, host: &[Value]) -> Result<(), String> {
let action = command.get("action").and_then(Value::as_str).unwrap_or("");
let Some(row) = entry(action) else {
let Some(row) = entry(action, host) else {
return Err(format!("Unsupported Blender command action: {action}"));
};
let present: Map<String, Value> = command
@ -286,8 +292,13 @@ fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> {
/// The actions section of `send --help`: every action with its fields, built from the table.
pub fn help() -> String {
help_rows(actions())
}
/// The help body for any rows: the built-ins, or the host rows a snapshot carries.
pub fn help_rows(rows: &[Value]) -> String {
let mut text = String::new();
for action in actions() {
for action in rows {
text.push_str(&format!(
" {}: {}\n",
action["name"].as_str().unwrap_or(""),
@ -408,7 +419,7 @@ mod tests {
for case in &cases {
let mut command = case["fields"].as_object().unwrap().clone();
command.insert("action".into(), case["action"].clone());
let got = validate(&command).err().unwrap_or_else(|| "ok".to_string());
let got = validate(&command, &[]).err().unwrap_or_else(|| "ok".to_string());
if Some(got.as_str()) != case["expect"].as_str() {
wrong.push(format!(
"{} {} expected {} got {got}",
@ -425,12 +436,50 @@ mod tests {
);
}
/// The host rows a fixture add-on publishes, run through the same validator as the add-on's
/// HostTableTests: one set of messages for host rows too.
#[test]
fn the_host_parity_fixture_yields_the_add_ons_messages() {
let file: Value = serde_json::from_str(include_str!(
"../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json"
))
.unwrap();
let host = file["actions"].as_array().unwrap().clone();
let cases: Vec<Value> = serde_json::from_str(include_str!(
"../../surfaces/blender/tests/host_action_cases.json"
))
.unwrap();
assert!(cases.len() >= 15, "{} cases", cases.len());
let mut wrong = Vec::new();
for case in &cases {
let mut command = case["fields"].as_object().unwrap().clone();
command.insert("action".into(), case["action"].clone());
let got = validate(&command, &host)
.err()
.unwrap_or_else(|| "ok".to_string());
if Some(got.as_str()) != case["expect"].as_str() {
wrong.push(format!(
"{} {} expected {} got {got}",
case["action"], case["fields"], case["expect"]
));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
// Without the snapshot's rows the same host action is unsupported: ctl never invents rows.
let mut command = Map::new();
command.insert("action".into(), "brokkr_host_fixture.report".into());
assert_eq!(
validate(&command, &[]).unwrap_err(),
"Unsupported Blender command action: brokkr_host_fixture.report"
);
}
#[test]
fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() {
let mut command = Map::new();
command.insert("action".into(), Value::from(3));
assert_eq!(
validate(&command).unwrap_err(),
validate(&command, &[]).unwrap_err(),
"Unsupported Blender command action: "
);
assert_eq!(

View file

@ -115,7 +115,7 @@ pub fn run(args: &[String]) -> Result<i32> {
}
let options = parse(rest)?;
if options.help {
print!("{}", if sub == "send" { send_help() } else { group_help() });
print!("{}", if sub == "send" { send_help(&options) } else { group_help() });
return Ok(0);
}
match sub.as_str() {
@ -214,6 +214,7 @@ fn build_intent(
requested_by: &str,
note: &str,
sets: &[String],
host: &[Value],
) -> Result<Value> {
let mut map = Map::new();
for set in sets {
@ -232,7 +233,7 @@ fn build_intent(
map.insert("action".into(), action.into());
map.insert("requestedBy".into(), requested_by.into());
map.insert("note".into(), note.into());
actions::validate(&map).map_err(|message| anyhow!(message))?;
actions::validate(&map, host).map_err(|message| anyhow!(message))?;
Ok(Value::Object(map))
}
@ -240,7 +241,8 @@ fn send(options: &Options, action: &str) -> Result<i32> {
let requested_by = requested_by(options)?;
let mut store = open_store(options)?;
let command_id = uuid::Uuid::now_v7().simple().to_string();
let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?;
let (host, _) = host_rows(&store)?;
let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets, &host)?;
store.push(&CultCacheEnvelope {
key: format!("{INTENT_PREFIX}{command_id}"),
r#type: INTENT_SCHEMA.to_string(),
@ -339,6 +341,27 @@ fn receipts(store: &SingleFileMessagePackBackingStore, last: Option<usize>) -> R
Ok(0)
}
/// The host snapshot as the add-on last published it, if any.
fn snapshot(store: &SingleFileMessagePackBackingStore) -> Result<Option<Value>> {
for envelope in store.pull_all()? {
if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA {
return Ok(Some(decode(&envelope)?));
}
}
Ok(None)
}
/// The host rows the add-on published and when (`observedAt`); empty before any snapshot. A display and
/// early-refusal copy: the add-on admits or denies the intent itself.
fn host_rows(store: &SingleFileMessagePackBackingStore) -> Result<(Vec<Value>, String)> {
let Some(snapshot) = snapshot(store)? else {
return Ok((Vec::new(), String::new()));
};
let rows = snapshot["hostActions"].as_array().cloned().unwrap_or_default();
let observed = snapshot["observedAt"].as_str().unwrap_or("").to_string();
Ok((rows, observed))
}
fn status(store: &SingleFileMessagePackBackingStore) -> Result<i32> {
for envelope in store.pull_all()? {
if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA {
@ -358,6 +381,20 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result<i32> {
print_field(key, value);
}
}
let names: Vec<&str> = snapshot["hostActions"]
.as_array()
.into_iter()
.flatten()
.filter_map(|row| row["name"].as_str())
.collect();
println!("hostActions: {}", names.join(", "));
for error in snapshot["hostActionErrors"].as_array().into_iter().flatten() {
println!(
"hostActionErrors: {}: {}",
error["host"].as_str().unwrap_or(""),
error["error"].as_str().unwrap_or("")
);
}
return Ok(0);
}
}
@ -378,6 +415,10 @@ fn print_fields(value: &Value) {
fn print_field(key: &str, value: &Value) {
match value {
Value::String(text) if text.contains('\n') => {
println!("{key}:");
text.lines().for_each(|line| println!(" {line}"));
}
Value::String(text) => println!("{key}: {text}"),
other => println!("{key}: {other}"),
}
@ -433,7 +474,9 @@ the add-on decides the rest and its refusal comes back in the receipt.
.to_string()
}
pub fn send_help() -> String {
/// `send --help`: the built-ins, then, when a store is named (--store or $BROKKR_BLENDER_STORE), the host
/// rows its snapshot carries. It never fails for lack of a store.
fn send_help(options: &Options) -> String {
let mut text = String::from(
"\
brokkr-ctl blender send <action> [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs]
@ -446,9 +489,31 @@ actions:
",
);
text.push_str(&actions::help());
text.push_str(&host_help(options));
text
}
fn host_help(options: &Options) -> String {
let named = options.store.is_some() || std::env::var_os("BROKKR_BLENDER_STORE").is_some();
if !named {
return "\nhost actions: add --store <path> (or set BROKKR_BLENDER_STORE) to list the actions host add-ons publish.\n"
.to_string();
}
match open_store(options).and_then(|store| host_rows(&store)) {
Err(error) => format!("\nhost actions: unavailable ({error}).\n"),
Ok((_, observed)) if observed.is_empty() => {
"\nhost actions: the store holds no host snapshot yet.\n".to_string()
}
Ok((rows, observed)) if rows.is_empty() => {
format!("\nhost actions (published by the add-on at {observed}): none.\n")
}
Ok((rows, observed)) => format!(
"\nhost actions (published by the add-on at {observed}):\n{}",
actions::help_rows(&rows)
),
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -462,17 +527,17 @@ mod tests {
#[test]
fn intent_carries_reserved_fields_and_refuses_overrides() {
let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()];
let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap();
let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets, &[]).unwrap();
assert_eq!(intent["requestedBy"], "nibu/hands");
assert_eq!(intent["objectType"], "MESH");
assert_eq!(intent["location"][2], 1);
for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] {
assert!(
build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(),
build_intent("createObject", "abc", "a/b", "", &[bad.to_string()], &[]).is_err(),
"{bad}"
);
}
assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err());
assert!(build_intent("../x", "abc", "a/b", "", &[], &[]).is_err());
}
#[test]

View file

@ -502,3 +502,114 @@ fn a_json_payload_is_refused_not_guessed() {
let output = ctl(&path, &["wait", "j", "--timeout", "1"], None);
assert_eq!(output.status.code(), Some(1));
}
/// A store whose snapshot carries the fixture add-on's rows the way the add-on publishes them, plus one refused file.
fn host_store(dir: &Path) -> PathBuf {
let path = store_with_receipts(dir, &[("seed", "accepted")]);
let file: Value = serde_json::from_str(include_str!(
"../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json"
))
.unwrap();
let rows: Vec<Value> = file["actions"]
.as_array()
.unwrap()
.iter()
.map(|row| {
let mut row = row.clone();
row["host"] = json!("brokkr_host_fixture");
row
})
.collect();
let snapshot = json!({
"observedAt": "2026-11-28T10:00:00.000000+00:00", "mode": "OBJECT",
"hostActions": rows,
"hostActionErrors": [{"host": "broken_addon", "error": "brokkr_actions.json: host schema must be brokkr.blender.host_actions.v0"}],
});
push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]);
path
}
fn help_text(args: &[&str], store: Option<&Path>) -> String {
let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"));
command.arg("blender").args(args).env_remove("BROKKR_BLENDER_STORE");
if let Some(store) = store {
command.arg("--store").arg(store);
}
stdout(&command.output().unwrap())
}
#[test]
fn send_help_with_a_store_lists_the_host_rows_with_their_bounds() {
let dir = tempfile::tempdir().unwrap();
let path = host_store(dir.path());
let text = help_text(&["send", "--help"], Some(&path));
assert!(text.contains("host actions (published by the add-on at 2026-11-28T10:00:00.000000+00:00):"), "{text}");
for needle in ["brokkr_host_fixture.add_empty", "size: number 0.1..10", "name: string", "brokkr_host_fixture.report"] {
assert!(text.contains(needle), "{needle} in {text}");
}
assert!(!text.contains("brokkr_host_fixture.apply"), "human-only is absence");
assert!(text.contains("createObject"), "the built-ins are still listed");
}
#[test]
fn send_help_without_a_store_says_host_actions_need_one_and_with_no_snapshot_says_so() {
let text = help_text(&["send", "--help"], None);
assert!(text.contains("host actions: add --store"), "{text}");
assert!(text.contains("createObject"));
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
assert!(help_text(&["send", "--help"], Some(&path)).contains("the store holds no host snapshot yet"));
}
#[test]
fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() {
let dir = tempfile::tempdir().unwrap();
let path = host_store(dir.path());
let before = std::fs::read(&path).unwrap();
let cases: [(&[&str], &str); 3] = [
(&["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=99"], "size must be between 0.1 and 10."),
(&["send", "brokkr_host_fixture.add_empty"], "name is required."),
(&["send", "brokkr_host_fixture.report", "--set", "x=1"], "has no field 'x'"),
];
for (args, message) in cases {
let mut args = args.to_vec();
args.extend(["--agent", "hands", "--no-wait"]);
let output = ctl(&path, &args, Some("nibu"));
assert_eq!(output.status.code(), Some(1), "{args:?}");
assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}");
assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store");
}
}
#[test]
fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() {
let dir = tempfile::tempdir().unwrap();
let path = host_store(dir.path());
let before = std::fs::read(&path).unwrap();
let output = ctl(&path, &["send", "brokkr_host_fixture.apply", "--agent", "hands", "--no-wait"], Some("nibu"));
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("Unsupported Blender command action: brokkr_host_fixture.apply"));
assert_eq!(std::fs::read(&path).unwrap(), before);
let sent = ctl(&path, &["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=2", "--agent", "hands", "--no-wait"], Some("nibu"));
assert_eq!(sent.status.code(), Some(0), "{}", String::from_utf8_lossy(&sent.stderr));
let id = stdout(&sent).trim().strip_prefix("commandId: ").unwrap().to_string();
let store = SingleFileMessagePackBackingStore::new(&path);
let intent = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap();
let value: Value = rmp_serde::from_slice(&intent.payload).unwrap();
assert_eq!((value["action"].as_str(), value["size"].as_i64()), (Some("brokkr_host_fixture.add_empty"), Some(2)));
}
#[test]
fn status_names_the_host_actions_and_each_refused_file_and_a_multiline_result_prints_indented() {
let dir = tempfile::tempdir().unwrap();
let path = host_store(dir.path());
let text = stdout(&ctl(&path, &["status"], None));
assert!(text.contains("hostActions: brokkr_host_fixture.add_empty, brokkr_host_fixture.report"), "{text}");
assert!(text.contains("hostActionErrors: broken_addon: brokkr_actions.json: host schema must be"), "{text}");
push(
&path,
&[envelope_at(RECEIPT, "blender/receipts/h", &json!({"commandId": "h", "status": "accepted", "hostResult": "objects: 3\nscenes: 1", "observedAt": "2026-11-28T10:00:01+00:00"}))],
);
let receipt = stdout(&ctl(&path, &["wait", "h"], None));
assert!(receipt.contains("hostResult:\n objects: 3\n scenes: 1\n"), "{receipt}");
}