diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 61762ac..6ae1bb7 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -1001,3 +1001,25 @@ fn t_h5_a_newest_line_over_the_budget_is_kept_and_the_older_one_is_left_out() { assert!(input.contains("\n1 older line(s) were not shown, the oldest in room=\"!dm-1:gamecult.org\" at "), "{}", &input[..400.min(input.len())]); assert_eq!(input.matches("event=").count(), 1); } + +/// What her agent did in this wake reaches this wake's Interpreter: its shell command stands in the prompt's ACTS section, and a +/// wake whose agent made no call says so. +#[test] +fn t_a2_the_interpreter_reads_this_wakes_shell_command() { + let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]); + let call = ToolCall { call_id: "sh".into(), name: "shell".into(), arguments: json!({ "command": "ls /srv/commons" }).to_string() }; + rig.agent.answers.borrow_mut().push_back(Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent() })); + let model = Tally::default(); + rig.run(model.clone()); + let interpreted = model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).cloned().collect::>(); + assert!(!interpreted.is_empty()); + for prompt in &interpreted { + let acts = prompt.split("\nACTS\n").nth(1).unwrap_or_else(|| panic!("no ACTS section: {prompt}")).split("NARRATION").next().unwrap(); + assert!(acts.contains("shell") && acts.contains("\"ls /srv/commons\""), "{acts}"); + } + + let quiet = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]); + let model = Tally::default(); + quiet.run(model.clone()); + assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| prompt.contains("\nACTS\nHer agent made no tool call.\n")), "an earlier wake's commands do not leak into this one"); +} diff --git a/crates/mind-body/src/projection/agent/shell.rs b/crates/mind-body/src/projection/agent/shell.rs index 1407099..2418f84 100644 --- a/crates/mind-body/src/projection/agent/shell.rs +++ b/crates/mind-body/src/projection/agent/shell.rs @@ -12,7 +12,8 @@ use serde_json::{Value, json}; use super::{Executor, Receipt, Status, arguments}; use crate::projection::narrate::ToolCall; -use crate::sandbox::TIMEOUT_MAX_S; +use crate::projection::select::clip; +use crate::sandbox::{TAIL_BYTES, TIMEOUT_MAX_S}; /// How much longer than the command's own timeout the drain waits for the box's answer. const ANSWER_GRACE_S: u64 = 10; @@ -50,9 +51,9 @@ impl Executor for Shell { Ok(answer) => passed_through(&answer), Err(why) => Receipt::new("shell", Status::Error, json!({ "why": why })), }; - // The receipt names the command it answers, so what her trace holds says what was run, not only what came back. + // The receipt names the command it answers, so what her trace holds says what was run, not only what came back. It is bounded as its output is. let mut fields = receipt.fields().clone(); - fields.insert("command".to_owned(), json!(args.command)); + fields.insert("command".to_owned(), json!(clip(&args.command, TAIL_BYTES))); Receipt::new("shell", receipt.status(), Value::Object(fields)) } } diff --git a/crates/mind-body/src/projection/agent/tests.rs b/crates/mind-body/src/projection/agent/tests.rs index aa01b4a..3333026 100644 --- a/crates/mind-body/src/projection/agent/tests.rs +++ b/crates/mind-body/src/projection/agent/tests.rs @@ -854,3 +854,16 @@ fn t_a2_shell_via_box_socket() { let gone = shell::Shell { socket: dir.path().join("nobody.sock") }.run(&call); assert_eq!((gone.status(), &gone.fields()["why"]), (Status::Error, &json!("the box could not be reached"))); } + +/// The shell's receipt names the command it answers, answered or not, and holds no more of it than an output stream's tail: a +/// longer command is clipped to `TAIL_BYTES`. +#[test] +fn the_shell_receipt_names_its_command_within_the_tail_bound() { + let dir = tempfile::tempdir().unwrap(); + let shell = shell::Shell { socket: dir.path().join("nobody.sock") }; + let run = |command: &str| shell.run(&ToolCall { call_id: "c".into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() }); + assert_eq!(run("ls /srv/commons").fields()["command"], json!("ls /srv/commons")); + let long = format!("echo {}", "x".repeat(2 * crate::sandbox::TAIL_BYTES)); + let named = run(&long).fields()["command"].as_str().unwrap().to_owned(); + assert!(named.len() <= crate::sandbox::TAIL_BYTES && named.starts_with("echo xxx") && named.ends_with('…'), "{}", named.len()); +} diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 1d79b2c..957d5d2 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -944,6 +944,25 @@ impl Commit<'_> { } fn intentions(&mut self, intend: &Intend) { + // Ready and drop come first, so the list an add checks for its words is the list the batch leaves: dropping an intention and + // adding it again in the same words retires the old one and opens a fresh one. + let stamp = self.stamp.clone(); + for (ready, ids) in [(true, &intend.ready), (false, &intend.drop)] { + for id in ids { + let Some(action) = self.list(&["candidateActions", "actions"]).iter_mut().find(|action| action["id"] == id.as_str() && is_intention(action) && action["status"] == "active") else { + self.refuse("intend", id, Why::UnknownId); + continue; + }; + if ready { + action["readiness"] = json!("ready"); + } else { + action["status"] = json!("retired"); + action["readiness"] = json!("expired"); + } + action["updatedAt"] = stamp.clone(); + self.change("intend", if ready { "ready" } else { "dropped" }, id); + } + } let mut added = 0; for intention in &intend.add { let item = json!({ "summary": intention.summary }); @@ -972,8 +991,18 @@ impl Commit<'_> { // The one duplicate the code can tell without reading meaning: the same words as an open intention. A rewording is the model's to catch. let same = |text: &str| text.split_whitespace().map(str::to_lowercase).collect::>(); let wanted = same(&summary); - if self.list(&["candidateActions", "actions"]).iter().any(|action| is_intention(action) && action["status"] == "active" && same(action["summary"].as_str().unwrap_or_default()) == wanted) { - self.refuse("intend", item, Why::Duplicate); + let open = self.list(&["candidateActions", "actions"]).iter().find(|action| is_intention(action) && action["status"] == "active" && same(action["summary"].as_str().unwrap_or_default()) == wanted).map(|action| (action["id"].as_str().unwrap_or_default().to_owned(), action["readiness"] == "waiting")); + if let Some((id, waiting)) = open { + // The same words name the open intention: marked ready, the add makes that one ready rather than being lost. + if waiting && readiness == "ready" { + if let Some(action) = self.list(&["candidateActions", "actions"]).iter_mut().find(|action| action["id"] == id.as_str()) { + action["readiness"] = json!("ready"); + action["updatedAt"] = stamp.clone(); + } + self.change("intend", "ready", &id); + } else { + self.refuse("intend", item, Why::Duplicate); + } continue; } added += 1; @@ -987,23 +1016,6 @@ impl Commit<'_> { self.list(&["candidateActions", "actions"]).push(action); self.change("intend", "added", &id); } - let stamp = self.stamp.clone(); - for (ready, ids) in [(true, &intend.ready), (false, &intend.drop)] { - for id in ids { - let Some(action) = self.list(&["candidateActions", "actions"]).iter_mut().find(|action| action["id"] == id.as_str() && is_intention(action) && action["status"] == "active") else { - self.refuse("intend", id, Why::UnknownId); - continue; - }; - if ready { - action["readiness"] = json!("ready"); - } else { - action["status"] = json!("retired"); - action["readiness"] = json!("expired"); - } - action["updatedAt"] = stamp.clone(); - self.change("intend", if ready { "ready" } else { "dropped" }, id); - } - } } } diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 556369e..1f72915 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -370,3 +370,25 @@ fn an_intention_open_in_the_same_words_is_not_added_again() { let (meant_again, applied) = run(&dropped, add("Tobiah means to list the directory above the Aetheria path.")); assert_eq!((open(&meant_again), reasons(&applied)), (open(&dropped) + 1, vec![])); } + +/// A batch's own drops come first, so dropping an intention and adding it again in the same words retires the old one and opens a +/// fresh one; and an add in an open waiting intention's words, marked ready, makes that one ready rather than being refused. +#[test] +fn a_drop_frees_its_words_and_a_ready_re_add_readies_the_open_intention() { + let intentions = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["customActionType"] == "intention").cloned().collect::>(); + let words = "Tobiah means to list the directory above the Aetheria path."; + let (first, _) = run(&state(), json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24 }] } })); + let old = intentions(&first).last().unwrap().clone(); + let (swapped, applied) = run(&first, json!({ "intend": { "drop": [old["id"]], "add": [{ "summary": words, "expires_in_hours": 24 }] } })); + let after = intentions(&swapped); + let (retired, fresh) = (after.iter().find(|action| action["id"] == old["id"]).unwrap(), after.last().unwrap()); + assert_eq!((retired["status"].as_str(), fresh["status"].as_str(), fresh["summary"].as_str(), reasons(&applied)), (Some("retired"), Some("active"), Some(words), vec![])); + assert_ne!(fresh["id"], old["id"]); + + assert_eq!(old["readiness"], "waiting"); + let (readied, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words.to_uppercase(), "expires_in_hours": 24, "readiness": "ready" }] } })); + let after = intentions(&readied); + assert_eq!((after.len(), after.last().unwrap()["id"].clone(), after.last().unwrap()["readiness"].as_str(), reasons(&applied)), (intentions(&first).len(), old["id"].clone(), Some("ready"), vec![])); + let (still, applied) = run(&first, json!({ "intend": { "add": [{ "summary": words, "expires_in_hours": 24, "readiness": "later" }] } })); + assert_eq!((intentions(&still).last().unwrap()["readiness"].as_str(), reasons(&applied)), (Some("waiting"), vec!["duplicate".to_owned()]), "only a ready add readies"); +} diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index b3f5cd0..9be246d 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -33,7 +33,7 @@ Write every text you give in the third person, about {name}, in words of your ow - feeling: feelings are named feelings with a strength from 0 to 1 and what they are about; mood moves valence, arousal or dominance up or down. - drives: a need or pressure goes up, down, or met (need) or eased (pressure). - self: a stance or value changes only when the thought shows {obj} changing {poss} mind about who {subj} {be}; it is rare. -- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it. An act that carried out an intention, or failed at it, settles it: drop it by id. An intention already in the index is not added again in other words."; +- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it. An act that carried out an intention settles it: drop it by id. An intention already in the index is not added again in other words; to make an open intention ready, name its id under ready, do not add it again."; /// The sections each of the Interpreter's two calls answers. The API refuses a grammar that compiles too large, which all six /// sections in one schema are, so the answer is two strict calls whose halves together cover every `Deltas` section. diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 6e88eb9..5d5287c 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -233,7 +233,8 @@ fn the_prompt_carries_this_wakes_acts_and_her_open_intentions_with_their_ids() { assert_eq!(acts.trim_end(), "- shell ok: \"ls /opt/aetheria/..\" -> exit 0, \"Aetheria CultLib\"\n- read refused: \"repo\" \"Aetheria\" -> nothing can be read from here\n- say ok: \"minds\" \"Found it.\""); let index = asked.split("INDEX\n").nth(1).unwrap().split("ACTS").next().unwrap(); assert!(index.contains("intentions:\n- ca-1: Tobiah means to ask Deru about the crossword."), "{index}"); - assert!(asked.contains("An act that carried out an intention, or failed at it, settles it: drop it by id."), "{asked}"); + assert!(asked.contains("An act that carried out an intention settles it: drop it by id."), "{asked}"); + assert!(!asked.contains("failed at it") && asked.contains("name its id under ready, do not add it again"), "a failure alone retires nothing; a ready re-add goes by id: {asked}"); heard.acts = Some(vec![]); assert!(prompt(&state(), &heard, "n", "p", 1).contains("\nACTS\nHer agent made no tool call.\n\nNARRATION")); diff --git a/crates/mind-body/src/sandbox.rs b/crates/mind-body/src/sandbox.rs index 07ff949..94d95b8 100644 --- a/crates/mind-body/src/sandbox.rs +++ b/crates/mind-body/src/sandbox.rs @@ -21,7 +21,7 @@ pub const COMMONS_RW: [&str; 2] = ["/opt/commons/handoff", "/opt/commons/cast-ar /// The longest a command may run. pub(crate) const TIMEOUT_MAX_S: u64 = 120; /// How much of each output stream the receipt keeps: its tail. -const TAIL_BYTES: usize = 4096; +pub(crate) const TAIL_BYTES: usize = 4096; /// The most paths the receipt lists as written, and the most entries a walk for them visits. const WROTE_MAX: usize = 64; const WALK_MAX: usize = 20_000;