Merge origin/main (a4cc320, brokkr-ctl) into the agent turn

Conflict: docs/live-collab-target.md add/add; kept the live-2 wording of the single-primitive paragraph (failed-after-write pushes one labelled step).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 20:23:13 +01:00
commit 50fe9c1aa1
8 changed files with 1117 additions and 2 deletions

12
Cargo.lock generated
View file

@ -47,6 +47,18 @@ dependencies = [
"generic-array",
]
[[package]]
name = "brokkr-ctl"
version = "0.1.0"
dependencies = [
"anyhow",
"cultcache-rs",
"rmp-serde",
"serde_json",
"tempfile",
"uuid",
]
[[package]]
name = "brokkr-daemon"
version = "0.1.0"

View file

@ -1,6 +1,10 @@
[workspace]
resolver = "2"
members = [
"brokkr-daemon"
"brokkr-daemon",
"brokkr-ctl",
]
[workspace.dependencies]
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }

15
brokkr-ctl/Cargo.toml Normal file
View file

@ -0,0 +1,15 @@
[package]
name = "brokkr-ctl"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
anyhow = "1"
cultcache-rs = { workspace = true }
rmp-serde = "1.3"
serde_json = "1"
uuid = { version = "1", features = ["v7"] }
[dev-dependencies]
tempfile = "3"

654
brokkr-ctl/src/blender.rs Normal file
View file

@ -0,0 +1,654 @@
//! `brokkr-ctl blender`: a caller of the Blender add-on's store. It writes one intent
//! document per `send` and reads receipts and the host snapshot. The add-on decides.
use anyhow::{Context, Result, anyhow, bail};
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore};
use serde_json::{Map, Value};
use std::path::PathBuf;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
pub const INTENT_SCHEMA: &str = "brokkr.blender.command_intent.v0";
pub const RECEIPT_SCHEMA: &str = "brokkr.blender.command_receipt.v0";
pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0";
const INTENT_PREFIX: &str = "blender/commands/";
const RECEIPT_PREFIX: &str = "blender/receipts/";
const SNAPSHOT_KEY: &str = "blender/host/current";
const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"];
const DEFAULT_TIMEOUT_SECS: u64 = 60;
const POLL: Duration = Duration::from_millis(200);
const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600);
/// Even when the file looks unchanged, read it again this often.
const RECHECK: Duration = Duration::from_secs(5);
/// What a receipt (or its absence) says; the exit code derives from it and from nothing else.
pub enum Outcome {
Accepted,
Failed,
Stopped,
Timeout,
}
impl Outcome {
pub fn code(&self) -> i32 {
match self {
Outcome::Accepted => 0,
Outcome::Failed => 2,
Outcome::Stopped => 3,
Outcome::Timeout => 4,
}
}
pub fn from_status(status: &str) -> Outcome {
match status {
"accepted" => Outcome::Accepted,
"stopped" => Outcome::Stopped,
_ => Outcome::Failed, // denied, failed, and any status this tool does not know
}
}
}
#[derive(Default)]
struct Options {
store: Option<PathBuf>,
agent: Option<String>,
note: String,
sets: Vec<String>,
no_wait: bool,
timeout: Option<Duration>,
help: bool,
last: Option<usize>,
positional: Vec<String>,
}
fn parse(args: &[String]) -> Result<Options> {
let mut options = Options::default();
let mut iter = args.iter();
while let Some(arg) = iter.next() {
let mut value = |name: &str| {
iter.next()
.cloned()
.ok_or_else(|| anyhow!("{name} needs a value"))
};
match arg.as_str() {
"--store" => options.store = Some(PathBuf::from(value("--store")?)),
"--agent" => options.agent = Some(value("--agent")?),
"--note" => options.note = value("--note")?,
"--set" => options.sets.push(value("--set")?),
"--no-wait" => options.no_wait = true,
"--help" | "-h" => options.help = true,
"--timeout" => {
let raw = value("--timeout")?;
let secs: f64 = raw
.parse()
.map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?;
options.timeout = Some(
Duration::try_from_secs_f64(secs)
.ok()
.filter(|limit| *limit <= MAX_TIMEOUT)
.ok_or_else(|| {
anyhow!("--timeout wants seconds between 0 and {}", MAX_TIMEOUT.as_secs())
})?,
);
}
"--last" => {
let raw = value("--last")?;
options.last = Some(
raw.parse()
.map_err(|_| anyhow!("--last wants a count, got {raw:?}"))?,
);
}
flag if flag.starts_with("--") => bail!("unknown option {flag}"),
_ => options.positional.push(arg.clone()),
}
}
Ok(options)
}
/// Runs one `blender` subcommand and returns the process exit code.
pub fn run(args: &[String]) -> Result<i32> {
let Some((sub, rest)) = args.split_first() else {
print!("{}", group_help());
return Ok(1);
};
if matches!(sub.as_str(), "--help" | "-h" | "help") {
print!("{}", group_help());
return Ok(0);
}
let options = parse(rest)?;
if options.help {
print!("{}", if sub == "send" { send_help() } else { group_help() });
return Ok(0);
}
match sub.as_str() {
"send" => send(&options),
"wait" => {
let id = one_positional(&options, "wait <commandId>")?;
let store = open_store(&options)?;
wait_for_receipt(&store, id, timeout(&options))
}
"receipts" => receipts(&open_store(&options)?, options.last),
"status" => status(&open_store(&options)?),
other => bail!("unknown subcommand {other:?}; try `brokkr-ctl blender --help`"),
}
}
fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> {
match options.positional.as_slice() {
[one] => Ok(one),
_ => bail!("usage: brokkr-ctl blender {usage}"),
}
}
fn timeout(options: &Options) -> Duration {
options.timeout.unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
}
/// The add-on creates its store; naming a path that is not there is a typo, not a request
/// to make a second store.
fn open_store(options: &Options) -> Result<SingleFileMessagePackBackingStore> {
let path = options
.store
.clone()
.or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from))
.ok_or_else(|| anyhow!("no store: pass --store <path> or set BROKKR_BLENDER_STORE"))?;
// The add-on resolves its store against the blend file; ctl cannot know that, so it takes none.
if !path.is_absolute() {
bail!("store {} must be an absolute path", path.display());
}
// A staged replace swaps the path itself, which would turn a link into a diverged copy.
let meta = std::fs::symlink_metadata(&path)
.map_err(|_| anyhow!("store {} does not exist; the add-on creates it", path.display()))?;
if meta.file_type().is_symlink() || !meta.is_file() {
bail!("store {} must be the add-on's regular file, not a link", path.display());
}
Ok(SingleFileMessagePackBackingStore::new(path))
}
fn requested_by(options: &Options) -> Result<String> {
let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default();
let agent = options
.agent
.clone()
.or_else(|| std::env::var("BROKKR_AGENT").ok())
.unwrap_or_default();
if instance.trim().is_empty() || agent.trim().is_empty() {
bail!("an intent must be attributed: set EUREKA_INSTANCE and pass --agent or set BROKKR_AGENT");
}
Ok(format!("{}/{}", instance.trim(), agent.trim()))
}
fn build_intent(
action: &str,
command_id: &str,
requested_by: &str,
note: &str,
sets: &[String],
) -> Result<Value> {
if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) {
bail!("action must be letters and digits, e.g. createObject");
}
let mut map = Map::new();
for set in sets {
let (key, raw) = set
.split_once('=')
.ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?;
if key.is_empty() || RESERVED.contains(&key) {
bail!("--set cannot name {key:?}: it is written by brokkr-ctl");
}
let value: Value = serde_json::from_str(raw)
.with_context(|| format!("--set {key}: {raw:?} is not JSON (strings need quotes)"))?;
map.insert(key.to_string(), value);
}
map.insert("schema".into(), INTENT_SCHEMA.into());
map.insert("commandId".into(), command_id.into());
map.insert("action".into(), action.into());
map.insert("requestedBy".into(), requested_by.into());
map.insert("note".into(), note.into());
Ok(Value::Object(map))
}
fn send(options: &Options) -> Result<i32> {
let action = one_positional(options, "send <action> [--set key=json]...")?;
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)?;
store.push(&CultCacheEnvelope {
key: format!("{INTENT_PREFIX}{command_id}"),
r#type: INTENT_SCHEMA.to_string(),
payload: rmp_serde::to_vec(&intent)?,
stored_at: iso_now(),
schema_id: Some(INTENT_SCHEMA.to_string()),
})?;
println!("commandId: {command_id}");
if options.no_wait {
return Ok(0);
}
wait_for_receipt(&store, &command_id, timeout(options))
}
fn read_receipt(store: &SingleFileMessagePackBackingStore, id: &str) -> Result<Option<Value>> {
let key = format!("{RECEIPT_PREFIX}{id}");
for envelope in store.pull_all()? {
if envelope.key == key && envelope.r#type == RECEIPT_SCHEMA {
return Ok(Some(decode(&envelope)?));
}
}
Ok(None)
}
fn wait_for_receipt(
store: &SingleFileMessagePackBackingStore,
id: &str,
limit: Duration,
) -> Result<i32> {
let started = Instant::now();
let mut gate = ChangeGate::new(store.path());
loop {
if !gate.should_read() {
if started.elapsed() >= limit {
println!("status: timeout");
return Ok(Outcome::Timeout.code());
}
thread::sleep(POLL);
continue;
}
if let Some(receipt) = read_receipt(store, id)? {
print_fields(&receipt);
let status = receipt.get("status").and_then(Value::as_str).unwrap_or("");
return Ok(Outcome::from_status(status).code());
}
if started.elapsed() >= limit {
println!("status: timeout");
return Ok(Outcome::Timeout.code());
}
thread::sleep(POLL);
}
}
/// Polling must not hold the store: a read takes the shared lock and an open handle, and on
/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store
/// is read only after it changed (and every RECHECK as a backstop).
pub struct ChangeGate {
path: PathBuf,
seen: Option<(u64, Option<SystemTime>)>,
last_read: Option<Instant>,
}
impl ChangeGate {
pub fn new(path: &std::path::Path) -> Self {
Self { path: path.to_path_buf(), seen: None, last_read: None }
}
pub fn should_read(&mut self) -> bool {
let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok()));
let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK);
if self.seen.is_none() || stamp != self.seen || stale {
self.seen = stamp;
self.last_read = Some(Instant::now());
return true;
}
false
}
}
fn receipts(store: &SingleFileMessagePackBackingStore, last: Option<usize>) -> Result<i32> {
let mut found = Vec::new();
for envelope in store.pull_all()? {
if envelope.key.starts_with(RECEIPT_PREFIX) && envelope.r#type == RECEIPT_SCHEMA {
found.push(decode(&envelope)?);
}
}
found.sort_by_key(|receipt| {
receipt
.get("observedAt")
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
});
let skip = last.map_or(0, |n| found.len().saturating_sub(n));
for (index, receipt) in found.iter().skip(skip).enumerate() {
if index > 0 {
println!();
}
print_fields(receipt);
}
Ok(0)
}
fn status(store: &SingleFileMessagePackBackingStore) -> Result<i32> {
for envelope in store.pull_all()? {
if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA {
let snapshot = decode(&envelope)?;
for key in [
"observedAt",
"blenderVersion",
"projectPath",
"mode",
"activeScene",
"activeObjectName",
"selectedObjectNames",
"objectCount",
"sink",
] {
if let Some(value) = snapshot.get(key) {
print_field(key, value);
}
}
return Ok(0);
}
}
bail!("the store holds no host snapshot yet; is the add-on's server running?")
}
fn decode(envelope: &CultCacheEnvelope) -> Result<Value> {
cultcache_rs::decode_payload::<Value>(&envelope.payload)
.with_context(|| format!("{} is not one MessagePack value", envelope.key))
}
fn print_fields(value: &Value) {
match value.as_object() {
Some(map) => map.iter().for_each(|(key, value)| print_field(key, value)),
None => println!("value: {value}"),
}
}
fn print_field(key: &str, value: &Value) {
match value {
Value::String(text) => println!("{key}: {text}"),
other => println!("{key}: {other}"),
}
}
/// UTC, microseconds, `+00:00`: the form the Python node stamps.
fn iso_now() -> String {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
iso_from(now.as_secs() as i64, now.subsec_micros())
}
fn iso_from(secs: i64, micros: u32) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
// Howard Hinnant's civil_from_days.
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00",
rem / 3_600,
rem % 3_600 / 60,
rem % 60
)
}
pub fn group_help() -> String {
"\
brokkr-ctl blender: send typed intents to the live Blender add-on and read what it did.
send <action> [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs]
Write one intent, then wait for its receipt and print it. `send --help` lists actions.
wait <commandId> [--timeout secs] Wait for a receipt and print it.
receipts [--last n] Print stored receipts, oldest first.
status Print the host snapshot summary.
Every command needs --store <path> or $BROKKR_BLENDER_STORE (the add-on's .ccmp).
send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '<instance>/<agent>'.
Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout,
1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and
its refusal comes back in the receipt.
"
.to_string()
}
pub fn send_help() -> String {
let mut text = String::from(
"\
brokkr-ctl blender send <action> [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs]
--set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema,
commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the
add-on reads; it validates them and refuses in the receipt. Targets also accept objectName.
actions:
",
);
for (action, fields) in ACTIONS {
text.push_str(&format!(" {action}\n"));
for (name, kind, note) in *fields {
text.push_str(&format!(" {name}: {kind} {note}\n"));
}
}
text
}
type Field = (&'static str, &'static str, &'static str);
/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit.
const ACTIONS: &[(&str, &[Field])] = &[
(
"createObject",
&[
("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"),
("name", "string", ""),
("location", "[x,y,z]", ""),
("size", "number", "MESH"),
("meshType", "string", "CUBE"),
("lightType", "string", "LIGHT"),
("emptyDisplayType", "string", "EMPTY"),
],
),
("deleteObject", &[("targetObjectName", "string", "")]),
(
"setObjectTransform",
&[
("targetObjectName", "string", ""),
("location", "[x,y,z]", ""),
("rotationEuler", "[x,y,z]", "radians"),
("scale", "[x,y,z]", ""),
],
),
(
"setObjectVisibility",
&[("targetObjectName", "string", ""), ("visible", "bool", "")],
),
(
"setObjectParent",
&[
("targetObjectName", "string", ""),
("parentObjectName", "string", "empty clears the parent"),
],
),
(
"setObjectCustomProperty",
&[
("targetObjectName", "string", ""),
("propertyName", "string", ""),
("value", "json", ""),
],
),
(
"selectObject",
&[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")],
),
(
"assignMaterial",
&[
("targetObjectName", "string", ""),
("materialName", "string", ""),
("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"),
],
),
(
"importGltf",
&[("filepath", "string", "inside the add-on's import directory")],
),
(
"exportGltf",
&[
("filepath", "string", ".glb or .gltf inside the add-on's output directory"),
("extras", "bool", ""),
("yUp", "bool", ""),
("applyModifiers", "bool", ""),
("selection", "[string]", "object names"),
],
),
(
"setCamera",
&[
("targetObjectName", "string", ""),
("lens", "number", "mm"),
("cameraType", "string", ""),
("orthoScale", "number", ""),
("clipStart", "number", ""),
("clipEnd", "number", ""),
("panoramaType", "string", ""),
("active", "bool", "make it the scene camera"),
],
),
(
"setLight",
&[
("targetObjectName", "string", ""),
("energy", "number", ""),
("color", "[r,g,b]", "linear, 0..1"),
("lightType", "string", ""),
],
),
(
"setWorld",
&[
("worldName", "string", ""),
("color", "[r,g,b]", "linear, 0..1"),
("strength", "number", ""),
],
),
(
"renderStill",
&[
("outputPath", "string", "inside the add-on's output directory"),
("engine", "string", ""),
("resolutionX", "integer", ""),
("resolutionY", "integer", ""),
("cameraName", "string", ""),
],
),
(
"createNodeGroup",
&[
("treeKey", "string", ""),
("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"),
],
),
(
"addNode",
&[
("treeKey", "string", ""),
("id", "string", "brokkr's key for the node"),
("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"),
("location", "[x,y]", ""),
("label", "string", ""),
("properties", "object", "enum, bool, int or float node settings"),
("inputs", "object", "unlinked input defaults"),
],
),
("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]),
(
"linkSockets",
&[
("treeKey", "string", ""),
("fromNode", "string", ""),
("fromSocket", "string", ""),
("toNode", "string", ""),
("toSocket", "string", ""),
],
),
(
"unlinkSockets",
&[
("treeKey", "string", ""),
("toNode", "string", ""),
("toSocket", "string", ""),
("fromNode", "string", "optional"),
("fromSocket", "string", "optional"),
],
),
(
"addModifier",
&[
("objectName", "string", ""),
("treeKey", "string", ""),
("modifierName", "string", "default Brokkr GeoNodes"),
],
),
(
"removeModifier",
&[("objectName", "string", ""), ("modifierName", "string", "")],
),
(
"setModifierInput",
&[
("objectName", "string", ""),
("modifierName", "string", ""),
("socket", "string", "identifier or unique interface name"),
("value", "json", "Float, Int, Bool or Vector"),
],
),
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso_matches_the_python_form() {
assert_eq!(iso_from(0, 0), "1970-01-01T00:00:00.000000+00:00");
assert_eq!(iso_from(1_795_800_558, 813_099), "2026-11-27T17:29:18.813099+00:00");
}
#[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();
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(),
"{bad}"
);
}
assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err());
}
#[test]
fn the_gate_reads_first_then_only_after_the_file_changes() {
let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("s.ccmp");
std::fs::write(&file, b"one").unwrap();
let mut gate = ChangeGate::new(&file);
assert!(gate.should_read());
assert!(!gate.should_read());
assert!(!gate.should_read());
std::fs::write(&file, b"three").unwrap();
assert!(gate.should_read());
assert!(!gate.should_read());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn statuses_map_to_exit_codes() {
for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] {
assert_eq!(Outcome::from_status(status).code(), code, "{status}");
}
assert_eq!(Outcome::Timeout.code(), 4);
}
}

24
brokkr-ctl/src/main.rs Normal file
View file

@ -0,0 +1,24 @@
//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces.
mod blender;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let code = match args.split_first() {
Some((group, rest)) if group == "blender" => blender::run(rest),
Some((flag, _)) if matches!(flag.as_str(), "--help" | "-h" | "help") => {
print!(
"brokkr-ctl <group> ...\n\ngroups:\n blender send intents to the live Blender add-on (`brokkr-ctl blender --help`)\n"
);
Ok(0)
}
_ => Err(anyhow::anyhow!("usage: brokkr-ctl blender <send|wait|receipts|status> ...")),
};
match code {
Ok(code) => std::process::exit(code),
Err(error) => {
eprintln!("error: {error:#}");
std::process::exit(1);
}
}
}

333
brokkr-ctl/tests/cli.rs Normal file
View file

@ -0,0 +1,333 @@
//! brokkr-ctl against a real single-file store, read back through cultcache-rs.
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
const INTENT: &str = "brokkr.blender.command_intent.v0";
const RECEIPT: &str = "brokkr.blender.command_receipt.v0";
fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope {
CultCacheEnvelope {
key: key.to_string(),
r#type: schema.to_string(),
payload: rmp_serde::to_vec(payload).unwrap(),
stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(),
schema_id: Some(schema.to_string()),
}
}
/// A store the way the add-on leaves it: a file that already exists, holding other records.
fn store_with_receipts(dir: &Path, statuses: &[(&str, &str)]) -> PathBuf {
let path = dir.join("blender-editor.ccmp");
let mut store = SingleFileMessagePackBackingStore::new(&path);
for (id, status) in statuses {
let receipt = json!({"schema": RECEIPT, "commandId": id, "status": status, "observedAt": "2026-11-27T00:00:00+00:00"});
store
.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt))
.unwrap();
}
path
}
fn ctl(store: &Path, args: &[&str], instance: Option<&str>) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"));
command
.arg("blender")
.args(args)
.arg("--store")
.arg(store)
.env_remove("BROKKR_AGENT")
.env_remove("BROKKR_BLENDER_STORE")
.env_remove("EUREKA_INSTANCE");
if let Some(instance) = instance {
command.env("EUREKA_INSTANCE", instance);
}
command.output().unwrap()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).into_owned()
}
#[test]
fn send_writes_a_pullable_intent() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
let output = ctl(
&path,
&["send", "createObject", "--set", "objectType=\"MESH\"", "--set", "location=[0,0,1]", "--note", "a cube", "--agent", "hands", "--no-wait"],
Some("nibu"),
);
assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr));
let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string();
assert_eq!(id.len(), 32);
let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap();
let intent = envelopes
.iter()
.find(|e| e.key == format!("blender/commands/{id}"))
.expect("intent key");
assert_eq!(intent.r#type, INTENT);
assert_eq!(intent.schema_id.as_deref(), Some(INTENT));
let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap();
assert_eq!(
payload,
json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands",
"note": "a cube", "objectType": "MESH", "location": [0, 0, 1]})
);
assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write");
}
#[test]
fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
let before = std::fs::read(&path).unwrap();
for (instance, agent) in [(None, Some("hands")), (Some("nibu"), None), (None, None), (Some(" "), Some("hands"))] {
let mut args = vec!["send", "createObject", "--no-wait"];
if let Some(agent) = agent {
args.extend(["--agent", agent]);
}
let output = ctl(&path, &args, instance);
assert_eq!(output.status.code(), Some(1), "{instance:?} {agent:?}");
}
assert_eq!(std::fs::read(&path).unwrap(), before);
}
#[test]
fn a_missing_store_is_not_created() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nope.ccmp");
let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu"));
assert_eq!(output.status.code(), Some(1));
assert!(!path.exists());
}
#[test]
fn exit_code_follows_the_receipt() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(
dir.path(),
&[("a", "accepted"), ("d", "denied"), ("f", "failed"), ("s", "stopped")],
);
for (id, code) in [("a", 0), ("d", 2), ("f", 2), ("s", 3)] {
let output = ctl(&path, &["wait", id, "--timeout", "5"], None);
assert_eq!(output.status.code(), Some(code), "{id}");
assert!(stdout(&output).contains(&format!("commandId: {id}")));
}
let output = ctl(&path, &["wait", "missing", "--timeout", "0.3"], None);
assert_eq!(output.status.code(), Some(4));
assert!(stdout(&output).contains("status: timeout"));
}
#[test]
fn receipts_lists_the_last_n_oldest_first() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted"), ("b", "failed")]);
let output = ctl(&path, &["receipts"], None);
assert_eq!(output.status.code(), Some(0));
let text = stdout(&output);
assert!(text.contains("commandId: a") && text.contains("commandId: b"));
let one = ctl(&path, &["receipts", "--last", "1"], None);
assert!(!stdout(&one).contains("commandId: a"));
}
#[test]
fn status_without_a_snapshot_is_a_store_error() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
assert_eq!(ctl(&path, &["status"], None).status.code(), Some(1));
}
#[test]
fn send_help_lists_the_actions() {
let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"))
.args(["blender", "send", "--help"])
.output()
.unwrap();
let text = stdout(&output);
for action in ["createObject", "renderStill", "setModifierInput", "exportGltf"] {
assert!(text.contains(action), "{action}");
}
}
fn envelope_at(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope {
envelope(schema, key, payload)
}
fn push(path: &Path, entries: &[CultCacheEnvelope]) {
let mut store = SingleFileMessagePackBackingStore::new(path);
for entry in entries {
store.push(entry).unwrap();
}
}
#[test]
fn intents_sent_in_order_sort_in_send_order() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
let mut sent = Vec::new();
for _ in 0..8 {
let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu"));
assert_eq!(output.status.code(), Some(0));
sent.push(format!("blender/commands/{}", stdout(&output).trim().strip_prefix("commandId: ").unwrap()));
}
let mut sorted = sent.clone();
sorted.sort();
assert_eq!(sent, sorted, "the add-on drains by sorted key");
}
#[test]
fn an_absurd_timeout_is_a_usage_error_not_a_panic() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
for value in ["1e300", "inf", "nan", "-1", "abc"] {
let output = ctl(&path, &["wait", "x", "--timeout", value], None);
assert_eq!(output.status.code(), Some(1), "{value}");
}
}
#[test]
fn help_words_as_option_values_do_not_swallow_the_command() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
let output = ctl(
&path,
&["send", "createObject", "--note", "-h", "--agent", "--help", "--no-wait"],
Some("nibu"),
);
assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr));
let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string();
let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap();
let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap();
let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap();
assert_eq!(payload["note"], "-h");
assert_eq!(payload["requestedBy"], "nibu/--help");
// a real help flag still prints help and sends nothing
let help = ctl(&path, &["send", "createObject", "--help"], Some("nibu"));
assert_eq!(help.status.code(), Some(0));
assert!(stdout(&help).contains("actions:"));
}
#[test]
fn a_relative_store_path_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"))
.current_dir(dir.path())
.args(["blender", "receipts", "--store", path.file_name().unwrap().to_str().unwrap()])
.output()
.unwrap();
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("absolute"));
}
#[test]
fn a_symlinked_store_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
let link = dir.path().join("link.ccmp");
#[cfg(windows)]
let made = std::os::windows::fs::symlink_file(&path, &link);
#[cfg(unix)]
let made = std::os::unix::fs::symlink(&path, &link);
if made.is_err() {
eprintln!("skipped: no symlink privilege");
return;
}
assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1));
}
#[test]
fn receipts_only_come_from_the_receipt_keys_and_type() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[("real", "accepted")]);
let fake = json!({"commandId": "fake", "status": "accepted"});
push(
&path,
&[
envelope_at(RECEIPT, "elsewhere/fake", &fake),
envelope_at(INTENT, "blender/receipts/wrongtype", &fake),
],
);
let listed = stdout(&ctl(&path, &["receipts"], None));
assert!(listed.contains("commandId: real"));
assert!(!listed.contains("fake"), "{listed}");
let waited = ctl(&path, &["wait", "wrongtype", "--timeout", "0.3"], None);
assert_eq!(waited.status.code(), Some(4));
}
#[test]
fn receipts_sort_by_observed_time_not_by_key() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[]);
push(
&path,
&[
envelope_at(RECEIPT, "blender/receipts/a", &json!({"commandId": "a", "observedAt": "2026-11-27T10:00:02+00:00"})),
envelope_at(RECEIPT, "blender/receipts/b", &json!({"commandId": "b", "observedAt": "2026-11-27T10:00:01+00:00"})),
],
);
let text = stdout(&ctl(&path, &["receipts"], None));
assert!(text.find("commandId: b").unwrap() < text.find("commandId: a").unwrap(), "{text}");
}
#[test]
fn status_prints_the_snapshot_summary() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[]);
let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}});
push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]);
let output = ctl(&path, &["status"], None);
assert_eq!(output.status.code(), Some(0));
let text = stdout(&output);
for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] {
assert!(text.contains(line), "{line} in {text}");
}
}
/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field
/// name is a string the add-on source mentions. The add-on has no machine-readable action table.
#[test]
fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() {
let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge");
let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"]
.iter()
.map(|file| std::fs::read_to_string(addon.join(file)).unwrap())
.collect();
let help = stdout(
&Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(),
);
let mut dispatched: Vec<String> = source
.lines()
.filter_map(|line| line.trim().strip_prefix("if action == \""))
.filter_map(|rest| rest.split('"').next())
.map(String::from)
.collect();
let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap();
dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from));
assert!(dispatched.len() >= 20, "{dispatched:?}");
let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect();
for action in &dispatched {
assert!(listed.contains(&action.as_str()), "help lacks {action}");
}
for action in &listed {
assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}");
}
for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) {
assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}");
}
}
#[test]
fn a_json_payload_is_refused_not_guessed() {
let dir = tempfile::tempdir().unwrap();
let path = store_with_receipts(dir.path(), &[]);
let mut json_receipt = envelope(RECEIPT, "blender/receipts/j", &json!({"commandId": "j", "status": "accepted"}));
json_receipt.payload = serde_json::to_vec(&json!({"commandId": "j", "status": "accepted"})).unwrap();
push(&path, &[json_receipt]);
let output = ctl(&path, &["wait", "j", "--timeout", "1"], None);
assert_eq!(output.status.code(), Some(1));
}

View file

@ -6,7 +6,7 @@ publish = false
[dependencies]
anyhow = "1"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }
cultcache-rs = { workspace = true }
rmp-serde = "1.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View file

@ -0,0 +1,73 @@
"""brokkr-ctl writes an intent a cultmesh-py node pulls as the same dict, and reads a node's receipt.
No Blender. Needs CultLib's Python packages (CULTLIB_PACKAGES, the packages directory) and the built
binary (BROKKR_CTL, the path to brokkr-ctl or brokkr-ctl.exe); skipped when either is missing.
"""
from __future__ import annotations
import os
import subprocess
import sys
import tempfile
import types
import unittest
from pathlib import Path
ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge"
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(ADDON)]
sys.modules.setdefault("brokkr_bridge", package)
from brokkr_bridge import blender_target as bt # noqa: E402
PACKAGES = os.environ.get("CULTLIB_PACKAGES", "")
CTL = os.environ.get("BROKKR_CTL", "")
@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory")
@unittest.skipUnless(CTL and Path(CTL).is_file(), "set BROKKR_CTL to the built brokkr-ctl binary")
class BrokkrCtlInterop(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.store = str(Path(self.tmp.name) / "blender-editor.ccmp")
self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES)
self.node = self.cultmesh.CultMesh.start_node(self.store, runtime_id="addon")
self.intent = self.cultcache.define_document_type(bt.COMMAND_INTENT_SCHEMA)
self.receipt = self.cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA)
self.node.database.register_document(self.intent)
self.node.database.register_document(self.receipt)
# The add-on's own first write is what creates its store file.
self.node.database.put(self.receipt, "blender/receipts/seed", {
"schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "seed", "status": "accepted"})
def ctl(self, *args):
env = dict(os.environ, EUREKA_INSTANCE="nibu")
env.pop("BROKKR_AGENT", None)
return subprocess.run([CTL, "blender", *args, "--store", self.store], env=env,
capture_output=True, text=True, timeout=60)
def test_a_node_pulls_the_intent_as_the_dict_ctl_wrote(self):
sent = self.ctl("send", "createObject", "--set", 'objectType="MESH"', "--set", "location=[0,0,1]",
"--note", "a cube", "--agent", "hands", "--no-wait")
self.assertEqual(sent.returncode, 0, sent.stderr)
command_id = sent.stdout.split("commandId:")[1].split()[0]
self.node.database.pull()
got = self.node.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{command_id}"]
self.assertEqual(got, {
"schema": bt.COMMAND_INTENT_SCHEMA, "commandId": command_id, "action": "createObject",
"requestedBy": "nibu/hands", "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]})
# The node's own earlier record is still there after the Rust whole-store write.
self.assertIn("blender/receipts/seed", self.node.database.snapshot()[bt.COMMAND_RECEIPT_SCHEMA])
def test_ctl_reads_a_receipt_the_node_wrote(self):
self.node.database.put(self.receipt, "blender/receipts/r1", {
"schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "r1", "action": "createObject",
"status": "failed", "message": "refused"})
waited = self.ctl("wait", "r1", "--timeout", "5")
self.assertEqual(waited.returncode, 2, waited.stderr)
self.assertIn("message: refused", waited.stdout)
if __name__ == "__main__":
unittest.main()