brokkr-ctl blender: the agent's command client #12

Merged
eureka merged 7 commits from nibu/live-4-brokkr-ctl into main 2026-11-27 19:21:58 +00:00
12 changed files with 1755 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"

290
docs/live-collab-target.md Normal file
View file

@ -0,0 +1,290 @@
# Brokkr live collaboration: target
Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base
`origin/main` 5e279b2. This document holds the rationale, the design truths the
campaign produces, and the identity, lifecycle and authority table. The typed
`target` in the mind holds the labelled invariants and the not-in-scope list; the
text below is their source. Revision 2 adds phase two (the authoring surface) and
takes in the operator's rulings of 2026-11-27.
Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`,
`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`,
`:cc-is-hull-authority-scene-pushes-deltas`.
## Why
Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender
scene I'm looking at, enabling live collaboration work". Her original vision for it:
"use Blender as an authoring environment, since it exposes typed access to all of the
assets we need over CultMesh. Certain collections within the Blender scene would
mirror their data into the exact documents Aetheria needs for its ships."
So the campaign has two phases. **Phase one** makes the live session a collaboration:
the agent's edits are undoable and attributed, she can stop it, and it sees what she
sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene
collections map to the ship's records, the scene opens from the `.cc` at a known
revision, and pushes go back through AetherDb.
Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler
publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains
command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`).
What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`);
nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an
agent only by unticking a preference; the agent sees names and counts, not the viewport
or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since
`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed,
validated actions with no free-form Python, path confinement, loopback bind and an
optional session token (`.brokkr-security`).
## Prior art the design stands on
- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what
the human did between its actions. We keep the idea as snapshot fields, without a
trajectory log.
- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop
button, visible turns and an undo receipt, no approval gate. Its Stop cannot
interrupt a blocking native call; ours cannot either.
- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party.
We show presence in a panel; human-to-human replication is theirs.
- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`):
viewport screenshots as perception. Their arbitrary-code path is refused here
(`no-free-form-python`).
- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a
typed vocabulary can be wide.
- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on
`nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price,
product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc`
through the game's own types; `tools/blender/package_hull.py` drives the
`aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py`
reads and writes `ship.cc` envelopes directly, with a layout revision hash for its
layout write.
- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7,
`src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`;
`CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria
`Assets/Scripts/ServerShared/ItemData.cs:648`).
## What probing established
Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick.
Scripts in `docs/research/live-collab/`. Research notes
`brokkr-live:research:live-collab-probes.*`.
1. **An unpushed write from a timer is not an undo step and survives undo**; the next
push absorbs it, so it is misattributed (`.timer-undo`, case A).
2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo
walk it (case B).
3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they
push none, and one explicit push covers several (cases C, E). This is how one intent
becomes one step.
4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also
left the Edit Mode the agent had entered (case D).
5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long
sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`).
6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at
1574x888, about 609 KB, popups included; Edit Mode selection reads live without
leaving Edit Mode (`.look-capture`).
7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name
indirect dependents; after an undo every object is listed and only the transform and
geometry flags show what changed (`.depsgraph-timing`).
8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a
live cultmesh-py node pulls Rust writes**; no runtime has a directory store
(`.rust-store-writer`).
Not yet probed, owed before the cut that depends on it: the latency of one AetherDb
`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a
resident service on that number); reading a record's stored version through AetherDb.
## Phase one: the live session
**One agent turn primitive.** Every agent mutation in Blender goes through one function
in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and
valid), run the action with every operator called `undo=False`, push exactly one undo
step labelled `Brokkr <requestedBy>: <action> <commandId[:8]>`, write the receipt. A
refusal or a failure pushes nothing and leaves the scene unchanged. There is no second
writer and no script action (`no-free-form-python`): what the typed actions do not
cover waits for a new typed action.
**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without
asking. Blender's one linear undo stack is the shared history; agent steps sit in it,
labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls
`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent.
**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies
even if she changed the scene since the agent looked. Her edit is never lost: it stays
in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back.
This is scene-level only; the `.cc` keeps its revision refusal (phase two).
**Stop is one control, and only the human holds it.** Stop turns the command sink off
and gives every pending intent a `stopped` receipt without running it. An action
already running finishes as one undo step, so Stop plus Ctrl+Z always returns her
scene. No intent can turn the sink on; intents queued before Stop never run.
**The agent sees her view and her edits.** `look` is a read intent: it captures her 3D
view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`)
and returns the path. The snapshot gains the Edit Mode selection, a Blender session id,
and human-edit sequence numbers (a session counter and, per object, the last sequence
at which she changed it, from depsgraph updates outside agent turns and flagged
transform, geometry or shading). These tell the agent what she did since it last
looked; they gate nothing.
**Presence is derived.** The panel shows active agents, the running or last intent with
its one-line `note`, and recent receipts with their undo labels, read from the intent
and receipt documents.
**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust
binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and
reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain
text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`,
`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its
tree commands to the same binary later.
## Phase two: the authoring surface
**The `.cc` is the authority; the scene is a surface over it**
(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`:
`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product
records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be
bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an
edit buffer that opens from the store and pushes back to it.
**Collections carry roles.** Scene collections are tagged with the role they author:
hull shape (the hull source and its raster), hardpoint rows (one object per row,
carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint,
rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on
the binding. These are the fields the packager manifest already names
(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one
vocabulary.
**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read
the three records and their stored versions, builds the tagged collections, and records
on the binding the version of each record it read. Nothing reads a `.cc` by scraping
envelopes (operator 2026-11-17).
**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring
state of its tagged collections (the manifest vocabulary, plus the record versions it
opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push <ship.cc>`,
as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written
to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request
describes, validates them, and prints the per-record, per-field changes; nothing is
written. With `apply` it does the same and writes under compare-exchange on each
record's stored version (`Expect`). One CLI call per push is the starting shape; a
resident service is built only if the measured latency of that call demands it.
**A stale revision is refused, never merged.** If any record changed in the store since
the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push
is refused with the records named; the surface reopens and the author re-applies. On a
successful apply the binding takes the new versions.
**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's
own types) is the only code that derives `HullData`, `ShipAuthoring` and product records
from authoring input, and the only writer of `.cc` stores. The packager and the
authoring surface both call it. The direct envelope writes in
`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and
the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are
demoted: `ship_cc.py` keeps no write path and no revision of its own, and
`package_hull.py`'s Save Layout steps become push calls. Whether the request is
the delta of the ruling, or a whole-record replace, is fork Q5 below.
**The agent's hands reach the surface through typed actions.** Open, push dry-run and
push apply are typed Brokkr actions like any other, admitted by the same primitive; a
push changes no scene state and so pushes no undo step. Whether an agent may apply,
not only dry-run, is fork Q7.
### Variants and CultNet deltas: not the push primitive today
The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas,
are the primitive for the push.
- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored
as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride`
with `Set`/`Insert`/`Remove` at slot plus element-id paths,
`src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a
plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`).
It describes a second document defined against a base, not a change to the base. Its
nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`,
C2b), C# alone resolves it, and Aetheria catalog content is out of its scope.
- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and
`document-put-raw`, `document-delete`, and `database-change-raw` (added, updated,
removed, with the whole document and a commit id). There is no delta message. The
"delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660`
is a client-side reconciliation diff (predicted minus canonical, per top-level slot,
numeric subtraction) handed to the caller to smooth a prediction; it is never sent.
- **One mechanism?** Not today. They are two unrelated things that share a word. The
operator's recollection matches the plan, not the code: variants' fork ruling 4
(`cultnet-deltas`) says variants travel on CultNet as deltas, and
`variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until
that cut (C5) lands. When it does, the override vocabulary will be both the stored
variant and the wire delta.
- **Consequence for the push.** The push invents no delta format. Its addressing is the
variants override vocabulary (slot plus element id; `HardpointData.Id` is already a
`[CultElementId]`) when CultLib can apply overrides to a record in place; until then
it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5.
## Authority map
- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent
intent changes the live scene; Blender owns scene truth and the undo stack; the human
owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship;
AetherDb's ship-authoring code alone derives and writes its records.
- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections,
the binding's opened versions and the stdin dump (phase two).
- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the
refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write.
- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped
collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state).
- **Forbidden writers.** `execute_command` called around the primitive; operators run
with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from
add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents
(`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything;
`ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision`
as a revision.
- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ
intents and replayed intents use the one primitive. The packager, the authoring
surface's buttons and an agent's push intent use the one AetherDb push.
- **Deletion line.** The debug-mirror intent import goes before the primitive lands;
`drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write
functions and `layout_revision` go when the push lands.
## Identity, lifecycle and authority
| Persistent kind | What names it | What happens to it over time | Who decides |
|---|---|---|---|
| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. |
| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. |
| Agent identity `requestedBy` | `<mind>/<agent>` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. |
| Agent undo step | Blender undo entry `Brokkr <requestedBy>: <action> <commandId[:8]>` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. |
| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. |
| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. |
| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. |
| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. |
| Look PNG | `<scratch>/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. |
| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods/<ship id>/ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. |
| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. |
| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. |
| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. |
| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. |
## Not in scope
Human-to-human replication or several Blender instances in one session. Agents on
another host reaching the operator's Blender. Per-user or selective undo. An approval
gate (`act-then-undo`). Stale-action refusal inside the live scene
(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view
presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary,
Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit.
Asset libraries and generators. An MCP server. Records outside a ship package
(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format.
## Open forks (draft questions; Self admits)
- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b)
variants override paths applied in place, after CultLib builds in-place apply and
C2b; (c) (a) now with the request shaped so (b) replaces it without changing the
surface. Recommend (c).
- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring
and products today; loadouts are catalog records. Recommend not in r2.
- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z.
Recommend dry-run for agents, apply by her button.
- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria,
with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains
Aetheria vocabulary. Recommend (a).

View file

@ -0,0 +1,134 @@
"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name?
blender --factory-startup --python probe_depsgraph_timing.py -- <out.json>
Each case runs in its own timer tick. AGENT is True only while the timer callback
runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value,
the tick that was current, and the ids depsgraph.updates names.
"""
import json
import sys
import time
import traceback
import bpy
OUT = sys.argv[sys.argv.index("--") + 1]
log = {"blender": bpy.app.version_string, "events": []}
AGENT = False
TICK = "setup"
T0 = time.perf_counter()
def ev(kind, **kw):
log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT,
"ms": round((time.perf_counter() - T0) * 1000, 1), **kw})
@bpy.app.handlers.persistent
def on_depsgraph(scene, depsgraph):
ups = []
for u in depsgraph.updates:
ups.append(f"{type(u.id).__name__}:{u.id.name}"
f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}")
ev("depsgraph", updates=ups)
@bpy.app.handlers.persistent
def on_undo(scene, *_):
ev("undo_post")
@bpy.app.handlers.persistent
def on_redo(scene, *_):
ev("redo_post")
def win_ctx():
win = bpy.context.window_manager.windows[0]
area = next(a for a in win.screen.areas if a.type == "VIEW_3D")
region = next(r for r in area.regions if r.type == "WINDOW")
return bpy.context.temp_override(window=win, area=area, region=region)
def setup():
# B follows A through a Copy Location constraint: an indirect dependent of A.
a = bpy.data.objects["Cube"]
with win_ctx():
bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0))
b = bpy.context.active_object
b.name = "Follower"
c = b.constraints.new("COPY_LOCATION")
c.target = a
c.use_y = False
with win_ctx():
bpy.ops.ed.undo_push(message="setup")
def agent(fn, flush):
global AGENT
AGENT = True
ev("turn_begin", flush=flush)
fn()
with win_ctx():
bpy.ops.ed.undo_push(message=f"agent {TICK}")
if flush:
bpy.context.view_layer.update()
ev("turn_end")
AGENT = False
def move_a(x):
return lambda: setattr(bpy.data.objects["Cube"].location, "x", x)
def add_op():
with win_ctx():
bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0))
def undo_once():
with win_ctx():
bpy.ops.ed.undo()
cases = [
("setup", setup),
("idle1", lambda: None),
("rna-noflush", lambda: agent(move_a(1.0), False)),
("idle2", lambda: None),
("rna-flush", lambda: agent(move_a(2.0), True)),
("idle3", lambda: None),
("op-noflush", lambda: agent(add_op, False)),
("idle4", lambda: None),
("op-flush", lambda: agent(add_op, True)),
("idle5", lambda: None),
("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn)
("idle6", lambda: None),
]
i = 0
def tick():
global i, TICK
if i < len(cases):
TICK, fn = cases[i]
try:
fn()
except Exception:
ev("error", error=traceback.format_exc())
TICK = f"after:{TICK}"
i += 1
with open(OUT, "w") as f:
json.dump(log, f, indent=1)
return 0.5
with open(OUT, "w") as f:
json.dump(log, f, indent=1)
bpy.ops.wm.quit_blender()
return None
bpy.app.handlers.depsgraph_update_post.append(on_depsgraph)
bpy.app.handlers.undo_post.append(on_undo)
bpy.app.handlers.redo_post.append(on_redo)
bpy.app.timers.register(tick, first_interval=2.0)

View file

@ -0,0 +1,68 @@
"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection?
blender --factory-startup --python probe_look.py -- <out.json> <png_dir>
"""
import json
import os
import statistics
import sys
import time
import traceback
import bmesh
import bpy
args = sys.argv[sys.argv.index("--") + 1:]
OUT, PNG_DIR = args[0], args[1]
log = {"blender": bpy.app.version_string}
def ctx():
win = bpy.context.window_manager.windows[0]
area = next(a for a in win.screen.areas if a.type == "VIEW_3D")
region = next(r for r in area.regions if r.type == "WINDOW")
return win, area, region
def run():
win, area, region = ctx()
log["view3d_px"] = [region.width, region.height]
times = []
for n in range(7):
path = os.path.join(PNG_DIR, f"look-{n}.png")
t = time.perf_counter()
with bpy.context.temp_override(window=win, area=area, region=region):
r = bpy.ops.screen.screenshot_area(filepath=path)
times.append((time.perf_counter() - t) * 1000)
log.setdefault("results", []).append(list(r))
log["screenshot_ms"] = [round(x, 1) for x in times]
log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1)
log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png"))
# Edit Mode selection read, live, without leaving Edit Mode.
with bpy.context.temp_override(window=win, area=area, region=region):
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="DESELECT")
bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data)
bm.verts.ensure_lookup_table()
bm.verts[0].select = True
bm.verts[3].select = True
bm.select_flush_mode()
t = time.perf_counter()
sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select]
log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3)
log["edit_selected_verts"] = sel
log["mode_after_read"] = bpy.context.mode
def tick():
try:
run()
except Exception:
log["error"] = traceback.format_exc()
with open(OUT, "w") as f:
json.dump(log, f, indent=1)
bpy.ops.wm.quit_blender()
return None
bpy.app.timers.register(tick, first_interval=3.0)

View file

@ -0,0 +1,146 @@
"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack?
Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- <out.json> [cases, e.g. AB]
Each step is its own timer tick so the event loop runs between steps, as it does
for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits.
"""
import json
import sys
import traceback
import bmesh
import bpy
OUT = sys.argv[sys.argv.index("--") + 1]
log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []}
def win_ctx():
win = bpy.context.window_manager.windows[0]
area = next(a for a in win.screen.areas if a.type == "VIEW_3D")
return bpy.context.temp_override(window=win, area=area, region=area.regions[-1])
def cube():
return bpy.data.objects.get("Cube")
def state(tag):
c = cube()
s = {
"tag": tag,
"cube_x": round(c.location.x, 3) if c else None,
"objects": sorted(o.name for o in bpy.data.objects),
"mode": bpy.context.mode,
"mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None,
}
if c and c.mode == "EDIT":
bm = bmesh.from_edit_mesh(c.data)
bm.verts.ensure_lookup_table()
s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3)
log["steps"].append(s)
return s
def push(msg):
with win_ctx():
r = bpy.ops.ed.undo_push(message=msg)
log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)})
def undo():
with win_ctx():
r = bpy.ops.ed.undo()
log["steps"].append({"tag": "undo", "result": list(r)})
def redo():
with win_ctx():
r = bpy.ops.ed.redo()
log["steps"].append({"tag": "redo", "result": list(r)})
# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step?
# Case B: RNA write then an explicit undo_push from the timer.
# Case C: an UNDO-flagged operator called from a timer, no explicit push.
# Case D: Edit Mode bmesh write from a timer then undo_push.
# Case E: two operators called with undo=False, then one explicit undo_push.
ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE"
steps = [
lambda: (push("baseline"), state("A0 baseline")),
lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")),
lambda: (undo(), state("A2 after one undo")),
lambda: (push("rebase-B"), state("B0")),
lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")),
lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")),
lambda: (undo(), state("B3 after undo (expect x=2)")),
lambda: (undo(), state("B4 after second undo (expect x=0)")),
lambda: (redo(), state("B5 after redo (expect x=2)")),
lambda: (push("rebase-C"), state("C0")),
lambda: (_add_sphere(), state("C1 op add sphere, no push")),
lambda: (undo(), state("C2 after undo (sphere gone?)")),
lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")),
lambda: (_edit_enter(), state("D1 edit mode")),
lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")),
lambda: (undo(), state("D3 after undo (expect v0 back)")),
lambda: (undo(), state("D4 after second undo")),
lambda: (_edit_exit(), push("rebase-E"), state("E0")),
lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")),
lambda: (undo(), state("E2 after one undo (expect both gone)")),
lambda: (undo(), state("E3 after second undo (expect no change)")),
]
def _add_sphere():
with win_ctx():
bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0))
def _edit_exit():
if bpy.context.mode != "OBJECT":
with win_ctx():
bpy.ops.object.mode_set(mode="OBJECT")
def _two_ops_one_step():
with win_ctx():
bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0))
bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0))
def _edit_enter():
with win_ctx():
bpy.ops.object.mode_set(mode="EDIT")
def _edit_write():
c = cube()
bm = bmesh.from_edit_mesh(c.data)
bm.verts.ensure_lookup_table()
bm.verts[0].co.z += 5.0
bmesh.update_edit_mesh(c.data)
i = 0
_all = steps
steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY]
def tick():
global i
if i < len(steps):
try:
steps[i]()
except Exception:
log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()})
i += 1
with open(OUT, "w") as f:
json.dump(log, f, indent=1)
return 0.3
with open(OUT, "w") as f:
json.dump(log, f, indent=1)
bpy.ops.wm.quit_blender()
return None
bpy.app.timers.register(tick, first_interval=2.0)

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()