diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 6171994..742a4af 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -31,6 +31,7 @@ mod select; mod simulate; mod span; mod tuning; +mod turn; use std::path::PathBuf; diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 89381ea..24aa4a1 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -19,7 +19,7 @@ pub(crate) fn control() -> Value { serde_json::from_str(&std::fs::read_to_string(fixtures().join("states/control.json")).unwrap()).unwrap() } -fn room(name: &str) -> Fixture { +pub(crate) fn room(name: &str) -> Fixture { Fixture::load(&fixtures().join("rooms").join(name)).unwrap() } @@ -100,7 +100,7 @@ impl PersonaSource for NeverAsked { } } -fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> { +pub(crate) fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> { Harness { instance: "eureka".into(), persona, model, tuning: dir.join("persona-tuning.toml") } } diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 340a180..03fd0a2 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -200,6 +200,8 @@ enum EditRefusal { NotFound, NotHers, TooLong, + /// The mouth carries no edit (map 16.36.2, item 7): a line said there stays as it went. + NoEditAtTheMouth, } /// One thing that came of her last turn, by its typed reason. A part that reached the room carries the receipt that says @@ -643,6 +645,7 @@ impl Part { EditRefusal::NotFound => "the line is gone.".to_owned(), EditRefusal::NotHers => format!("the line is not {poss}."), EditRefusal::TooLong => "the line would be too long.".to_owned(), + EditRefusal::NoEditAtTheMouth => "a line cannot be added to once it is said here.".to_owned(), }; format!(" {why}{}", drafted(added)) } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index f82a960..7a10c77 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -24,6 +24,7 @@ //! from her turn's record and its receipts, as live C3c's commit will apply them: the memories she writes and settles //! (map 16.35.4). The report lists them per turn, and counts them per Mind with her short-term size at the run's end. +use std::cell::{Cell, RefCell}; use std::collections::BTreeMap; use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -33,12 +34,12 @@ use chrono::{DateTime, Duration, Utc}; use serde::Deserialize; use serde_json::{Value, json}; -use super::commit; use super::narrate::MAX_OUTPUT_TOKENS; use super::read::{self, ReadFailure, ReadRequest}; use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::select::Draw; use super::tuning; +use super::turn::{self, Actuator, Edited, Sent, history, last_wake}; use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind, project}; use crate::address::{Addressee, is_for, localpart}; use crate::chat_client::ChatPending; @@ -164,7 +165,7 @@ fn unseen(seen: &Seen, lines: &[Line], at: usize) -> bool { /// One persona's view of the room at her turn: the lines she has not seen are new. struct View<'a> { - lines: &'a [Line], + lines: &'a RefCell>, viewer: &'a str, rooms: &'a [String], seen: &'a Seen, @@ -172,7 +173,49 @@ struct View<'a> { impl MouthReader for View<'_> { fn pending(&self) -> Result { - Ok(pending_for(self.lines, self.viewer, self.rooms, |at| unseen(self.seen, self.lines, at))) + let lines = self.lines.borrow(); + Ok(pending_for(&lines, self.viewer, self.rooms, |at| unseen(self.seen, &lines, at))) + } +} + +/// The simulated room as the turn's actuator, as the mouth will be live (B1, B3): a send appends a line from her, by its +/// index, which serves as its event, and an event not in the room's lines refuses the reply; an edit composes the new body +/// from the line as it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line, +/// so it wakes no one, and every view after it reads the amended text. +struct SimRoom<'a> { + lines: &'a RefCell>, + her: &'a str, + name: &'a str, + /// The room of the turn, and when she was woken by a direct message, whom it answers. + here: &'a str, + dm_to: Option, + cast: &'a [String], + operators: &'a [String], + now: DateTime, + sent: Cell, +} + +impl Actuator for SimRoom<'_> { + fn send(&self, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String]) -> Sent { + let offset = self.sent.replace(self.sent.get() + 1); + let mut lines = self.lines.borrow_mut(); + let reply_to = match in_reply_to { + None => None, + Some(event) => match replied(&lines, event, room) { + Some(at) => Some(at), + None => return Sent::Refused("reply_target_not_in_room".to_owned()), + }, + }; + let mentions = mentions.iter().filter(|id| self.cast.contains(*id) || self.operators.contains(*id)).cloned().collect(); + let at_ms = u64::try_from(self.now.timestamp_millis()).unwrap_or_default() + offset; + let dm_to = if room == self.here { self.dm_to.clone() } else { None }; + let event = lines.len().to_string(); + lines.push(Line { from: self.her.to_owned(), name: self.name.to_owned(), room: room.to_owned(), at_ms, says: text.to_owned(), mentions, dm_to, follow_up: false, reply_to, new: false }); + Sent::Posted(event) + } + + fn edit(&self, event: &str, added: &str) -> Edited { + edit(&mut self.lines.borrow_mut(), self.her, event, added) } } @@ -378,12 +421,9 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) scripted(0, &mut lines, &mut rounds_of, &mut causes)?; let opening = lines.len(); let mut seen: Vec = vec![Seen::new(); members.len()]; - let mut last_turn: Vec>> = vec![None; members.len()]; let mut last_beat = plan.start; - let mut recent: Vec>> = vec![Vec::new(); members.len()]; - // Each persona's last turn's record, as the commit's trace will hold it: what came of it opens her next packet. - let mut last: Vec> = vec![None; members.len()]; - // Every turn record of hers, oldest first: what she has said and read in a conversation is read from them (K26). + // Every turn record of hers, oldest first: the run's trace, which her last outcome, her recent selections, her exchange + // and her last wake are read from (`turn::history`). let mut records: Vec> = vec![Vec::new(); members.len()]; let mut turns = Vec::new(); // Every note to Self the run's turns left, oldest first: what Self's inbox reader (C5) will list from the traces. @@ -403,8 +443,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) .map(|(at, member)| Standing { slug: localpart(&member.entry.id).to_owned(), eligible: !woke.iter().any(|(woken, _)| *woken == at), - waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), - last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()), + waited_s: last_wake(&records[at]).map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), + last_turn_ms: last_wake(&records[at]).map(|turn| turn.timestamp_millis()), topic_permille: 0, addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries), }) @@ -426,6 +466,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.clone()); let kind = if fresh.iter().any(|line| line.room == here) { TurnKind::Chat } else { TurnKind::Beat }; let now = round_at + Duration::seconds(30 + counter as i64); + let past = history(&records[at]); let request = Request { instance: localpart(&id).to_owned(), kind, @@ -440,96 +481,47 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) tuning: harness.tuning.clone(), through: Through::Interpreter, last_heard: vec![], - recent: recent[at].clone(), + recent: past.recent, own_rooms: member.entry.own_rooms.clone(), - last_outcome: last[at].take(), - last_wake: last_turn[at], - records: records[at].clone(), + last_outcome: past.last_outcome, + last_wake: past.last_wake, + records: past.records, }; - let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: &seen[at] }; - let names = Names(&member.addressee); - let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); - let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; - let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); // What the room held when she read it, before her own lines go in. let read_to = lines.len(); - let render = &report["renders"][0]; - if let Some(selected) = render["selected"].as_array() { - recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect()); - } - // A failed call is a failure, never a silence. - let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + let key = format!("r{}-t{counter}", repeat + 1); + let room = RefCell::new(std::mem::take(&mut lines)); + let taken = { + let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] }; + let names = Names(&member.addressee); + let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); + let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; + let actuator = SimRoom { lines: &room, her: &id, name: &member.entry.name, here: &here, dm_to, cast: &cast, operators: &plan.operators, now, sent: Cell::new(0) }; + turn::take(&organs, &request, &actuator, &key, now) + }; + lines = room.into_inner(); + let cause = cause_word(why.as_ref().map(|why| why.cause)); + rounds_of.resize(lines.len(), round); + causes.resize(lines.len(), Some(cause)); + held_to_schema(&member.entry.name, &id, &taken.state, &key)?; + let failed = taken.failed().map(str::to_owned); // A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake // sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is // acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands. if failed.is_none() { seen[at].insert(here.clone(), read_to); - last_turn[at] = Some(now); } - // What she says is the Interpreter's decision alone; who it wakes is its structured mentions and the line it replies to. - let said: Vec = if failed.is_some() { vec![] } else { render["interpreter"]["said"].as_array().cloned().unwrap_or_default() }; - let cause = cause_word(why.as_ref().map(|why| why.cause)); - let mut spoken: Vec = Vec::new(); - // The room's receipts: each line it appended, by its index, which serves as its event. - let mut posted: Vec = Vec::new(); - let mut refused_sends: Vec = Vec::new(); - for (offset, decided) in said.iter().enumerate() { - let room = decided["room"].as_str().unwrap_or(&here).to_owned(); - let says = decided["text"].as_str().unwrap_or_default().to_owned(); - let mentions: Vec = decided["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).filter(|id| cast.contains(&(*id).to_owned()) || plan.operators.contains(&(*id).to_owned())).map(str::to_owned).collect()).unwrap_or_default(); - // The room is the reply's actuator, as the mouth will be (B3): an event not in this room refuses the send, so - // nothing reached the room and no receipt is written. - let reply_to = match decided["in_reply_to"]["event"].as_str() { - None => None, - Some(event) => match replied(&lines, event, &room) { - Some(at) => Some(at), - None => { - refused_sends.push(json!({ "room": room, "text": says, "in_reply_to": event, "refusal": "reply_target_not_in_room" })); - continue; - } - }, - }; - let at_ms = u64::try_from(now.timestamp_millis()).unwrap_or_default() + offset as u64; - let to = if room == here { dm_to.clone() } else { None }; - posted.push(json!({ "event": lines.len().to_string(), "room": room, "text": says })); - lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room, at_ms, says: says.clone(), mentions, dm_to: to, follow_up: false, reply_to, new: false }); - rounds_of.push(round); - causes.push(Some(cause)); - spoken.push(says); - } - // The room is the amendment's actuator, as the mouth will be live (B1): it composes the new body from the line as - // it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line, so it - // wakes no one, and every view after it reads the amended text. - let mut edited: Vec = Vec::new(); - for amended in render["interpreter"]["amended"].as_array().into_iter().flatten().filter(|_| failed.is_none()) { - let event = amended["event"].as_str().unwrap_or_default(); - let refusal = edit(&mut lines, &id, event, amended["added"].as_str().unwrap_or_default()); - edited.push(json!({ "event": event, "refusal": refusal })); - } - for (index, note) in render["interpreter"]["suggestions"].as_array().into_iter().flatten().filter(|_| failed.is_none()).enumerate() { + for (index, note) in taken.report["renders"][0]["interpreter"]["suggestions"].as_array().into_iter().flatten().filter(|_| failed.is_none()).enumerate() { inbox.push(json!({ "key": format!("r{}-t{counter}-s{index}", repeat + 1), "mind": localpart(&id), "round": round, "at": now.to_rfc3339(), "kind": note["kind"], "about": note["about"], "room": note["room"], "text": note["text"] })); } - let mut record = match &failed { - Some(failed) => json!({ "failed": failed }), - None => json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited, "refused_sends": refused_sends }), - }; - // A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided - // before it went out, and she is told the rest broke off. - if let Some(step) = ["continuation_failed", "later_failed"].into_iter().find(|step| render["interpreter"].get(*step).is_some()) { - record["broke_after"] = json!(step); - } - // The commit: her turn's proposals applied to her in-run state on the receipts above, as C3c's will be live, and - // what it did kept in the record her next outcome reads. - let (state, applied) = commit::apply(&members[at].state, &record, &format!("r{}-t{counter}", repeat + 1), now); - held_to_schema(&member.entry.name, &id, &state, &format!("r{}-t{counter}", repeat + 1))?; - record["committed"] = json!(applied); - last[at] = Some(record.clone()); - records[at].push(record.clone()); + let spoken: Vec<&str> = taken.record["posted"].as_array().into_iter().flatten().filter_map(|receipt| receipt["text"].as_str()).collect(); let line = (!spoken.is_empty()).then(|| spoken.join(" / ")); let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" }; let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by)); - let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "edited": edited, "committed": record["committed"], "report": report }); - members[at].state = state; + let edited = taken.record.get("edited").cloned().unwrap_or_else(|| json!([])); + let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "edited": edited, "committed": taken.record["committed"], "report": taken.report }); + records[at].push(taken.record); + members[at].state = taken.state; turns.push(turn); } } diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index fbe42e0..4a0b124 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1059,3 +1059,50 @@ fn t4_x5_timeline_the_note_carries_and_nothing_gates_the_welcome() { assert!(libby_state["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().any(|entry| entry["id"] == id), "the note stays in her state"); assert_eq!(run["metrics"]["personas"]["Libby"]["memories"]["written"], 1, "{}", run["metrics"]["personas"]); } + +#[test] +fn t_l1_sim_and_mouth_records_same_shape() { + use crate::projection::harness::fixture_request; + use crate::projection::harness::tests::{harness, room}; + use crate::projection::outcome::outcome_of; + use crate::projection::select::forms; + use crate::projection::turn::{Mouth, take}; + let dir = tempfile::tempdir().unwrap(); + let model = Scripted::new(|_| "He smiles at the screen, then types. Missed you too, friend.".into()); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&model)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); + let lines = RefCell::new(Vec::new()); + let sim = SimRoom { lines: &lines, her: TOBIAH, name: "Tobiah", here: "!dm-meta:gamecult.org", dm_to: None, cast: &[], operators: &[], now: fixture.now, sent: Cell::new(0) }; + let simulated = take(&organs, &request, &sim, "r1-t1", fixture.now); + struct Chat1; + impl crate::chat_client::Chat for Chat1 { + fn pending(&self, _: u64) -> Result { + bail!("unused") + } + fn send(&self, request: &crate::chat_client::ChatSendRequest) -> Result { + Ok(crate::chat_client::ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some("$0".into()), refusal: None, newer: vec![] }) + } + fn open_direct(&self, _: &crate::chat_client::ChatOpenDirectRequest) -> Result { + bail!("unused") + } + fn fetch(&self, _: &crate::chat_client::ChatFetchRequest) -> Result { + bail!("unused") + } + fn ack(&self, _: u64) -> Result<()> { + bail!("unused") + } + fn read(&self, _: &crate::chat_client::ChatRead) -> Result<()> { + bail!("unused") + } + } + let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), key: "r1-t1".into(), basis: None, sent: Cell::new(0) }; + let live = take(&organs, &request, &mouth, "r1-t1", fixture.now); + let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::>(); + assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live"); + assert_eq!(lines.borrow().len(), 1, "the room appended her line"); + assert_eq!(simulated.record["posted"][0]["text"], live.record["posted"][0]["text"]); + let told = |taken: &crate::projection::turn::Taken| outcome_of(&taken.record).unwrap().lines(forms(&taken.state)); + assert_eq!(told(&simulated), told(&live), "she is told the same of either"); +} diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs new file mode 100644 index 0000000..9498c83 --- /dev/null +++ b/crates/mind-body/src/projection/turn.rs @@ -0,0 +1,160 @@ +//! One turn (map 16.36.2, items 2 and 6): the packet, the decision, the actuation, the commit and the record. The +//! simulator's room and the live mouth are the two actuators; `take` is the one turn they share, so the simulator tests +//! the turn the Minds take on chat. Her records are her trace: what she last did, what she showed lately, what she has +//! said in this conversation and when she last woke are read back from them (`history`), and kept nowhere else. + +use std::cell::Cell; + +use chrono::{DateTime, Utc}; +use serde_json::{Value, json}; + +use super::commit::{self, Applied}; +use super::{Organs, Request, project}; +use crate::chat_client::{Chat, ChatSendRequest, SendBasis}; + +/// How many of her earlier projections freshness remembers, and how many of her records a packet reads. +const RECENT: usize = 5; +const RECORDS: usize = 50; + +/// How an actuator answered a send: the event it made, or why it made none (the refusal's name). +pub(crate) enum Sent { + Posted(String), + Refused(String), +} + +/// The refusal that kept an amendment out of the room, or none when it was made. +pub(crate) type Edited = Option<&'static str>; + +/// What a turn's decision reaches the world through. A refusal is an answer the record keeps, never a fault. +pub(crate) trait Actuator { + /// Say `text` in `room`, replying to the line `in_reply_to` and waking `mentions`, where the actuator carries them. + fn send(&self, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String]) -> Sent; + /// Add `added` to her line `event`. + fn edit(&self, event: &str, added: &str) -> Edited; +} + +/// The mouth as the actuator. `chat_send_request.v2` carries no mentions and no reply link, so her line goes out plain and +/// the receipt records the text that went, not the decision; the mouth has no edit, so an amendment is refused +/// `no_edit_at_the_mouth` and told to her as not amended. Each send is its own transaction, `{key}:s{index}`, so the +/// same turn sent again is the same send. +#[allow(dead_code, reason = "the live drain (map 16.36.5, cut L2) is its first caller")] +pub(crate) struct Mouth<'a> { + pub chat: &'a dyn Chat, + pub persona: String, + pub key: String, + /// The newest event of the room her input held, and when her process began. + pub basis: Option, + pub sent: Cell, +} + +impl Actuator for Mouth<'_> { + fn send(&self, room: &str, text: &str, _in_reply_to: Option<&str>, _mentions: &[String]) -> Sent { + let index = self.sent.replace(self.sent.get() + 1); + let request = ChatSendRequest { request_id: format!("{}:s{index}", self.key), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: self.basis.clone() }; + match self.chat.send(&request) { + Ok(receipt) => match (receipt.event_id, receipt.refusal) { + (_, Some(refusal)) => Sent::Refused(refusal.name().to_owned()), + (Some(event), None) => Sent::Posted(event), + (None, None) => Sent::Refused("no_event".to_owned()), + }, + Err(_) => Sent::Refused("unreachable".to_owned()), + } + } + + fn edit(&self, _event: &str, _added: &str) -> Edited { + Some("no_edit_at_the_mouth") + } +} + +/// One turn taken: what `project` reported, her record of it, her state after the commit and what the commit did. +pub(crate) struct Taken { + pub report: Value, + pub record: Value, + pub state: Value, + pub applied: Applied, +} + +impl Taken { + /// The reason the turn failed, when it did: a failed call is a failure, never a silence. + pub(crate) fn failed(&self) -> Option<&str> { + self.record["failed"].as_str() + } +} + +/// One turn: `project` through the Interpreter, each said line through `actuator.send`, each amendment through +/// `actuator.edit`, the record of what happened, and the commit's application of her proposals to her state. `key` names +/// the turn (`-t`). A failed turn sends nothing, amends nothing and applies nothing. +pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime) -> Taken { + let report = project(organs, request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); + let render = &report["renders"][0]; + let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + let here = request.room.clone().unwrap_or_default(); + let mut record = match &failed { + Some(failed) => json!({ "failed": failed }), + None => { + // What she says is the Interpreter's decision alone. + let (mut posted, mut refused_sends, mut edited) = (Vec::new(), Vec::new(), Vec::new()); + for decided in render["interpreter"]["said"].as_array().into_iter().flatten() { + let room = decided["room"].as_str().unwrap_or(&here); + let text = decided["text"].as_str().unwrap_or_default(); + let mentions: Vec = decided["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); + let reply = decided["in_reply_to"]["event"].as_str(); + match actuator.send(room, text, reply, &mentions) { + Sent::Posted(event) => posted.push(json!({ "event": event, "room": room, "text": text })), + Sent::Refused(refusal) => refused_sends.push(match reply { + Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": refusal }), + None => json!({ "room": room, "text": text, "refusal": refusal }), + }), + } + } + for amended in render["interpreter"]["amended"].as_array().into_iter().flatten() { + let event = amended["event"].as_str().unwrap_or_default(); + edited.push(json!({ "event": event, "refusal": actuator.edit(event, amended["added"].as_str().unwrap_or_default()) })); + } + json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited, "refused_sends": refused_sends }) + } + }; + // A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided + // before it went out, and she is told the rest broke off. + if let Some(step) = ["continuation_failed", "later_failed"].into_iter().find(|step| render["interpreter"].get(*step).is_some()) { + record["broke_after"] = json!(step); + } + let (state, applied) = commit::apply(request.state.as_ref().unwrap_or(&Value::Null), &record, key, now); + record["committed"] = json!(applied); + if render["selected"].is_array() { + record["selected"] = render["selected"].clone(); + } + record["at"] = json!(now.to_rfc3339()); + Taken { report, record, state, applied } +} + +/// What her records say of her: her last turn's record, the ids her last projections selected, her last records and +/// when she last woke. The one reader, over a run's list or her trace. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct Past { + pub last_outcome: Option, + pub recent: Vec>, + pub records: Vec, + pub last_wake: Option>, +} + +/// Her `records`, oldest first, read. +pub(crate) fn history(records: &[Value]) -> Past { + let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::>()); + let mut recent: Vec> = records.iter().filter_map(selected).collect(); + recent.drain(..recent.len().saturating_sub(RECENT)); + Past { + last_outcome: records.last().cloned(), + recent, + records: records[records.len().saturating_sub(RECORDS)..].to_vec(), + last_wake: last_wake(records), + } +} + +/// When she last woke: the last record that is no failure. A wake is a turn whose record carries a decision. +pub(crate) fn last_wake(records: &[Value]) -> Option> { + records.iter().rev().find(|record| record.get("failed").is_none()).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs new file mode 100644 index 0000000..20e5aec --- /dev/null +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -0,0 +1,145 @@ +use std::cell::RefCell; + +use anyhow::{Result, bail}; +use chrono::Duration; +use serde_json::json; + +use super::*; +use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal}; +use crate::projection::harness::fixture_request; +use crate::projection::harness::tests::{Scripted, control, harness, room}; +use crate::projection::narrate::PROJECTOR_OPENING; +use crate::projection::outcome::outcome_of; +use crate::projection::select::forms; +use crate::projection::{Answer, Failed, Model, Organs, Through}; + +/// A mouth that records each send and answers it as `answer` says; it does nothing else. +struct FakeChat { + sent: RefCell>, + refusal: Option, +} + +impl FakeChat { + fn new(refusal: Option) -> Self { + Self { sent: RefCell::default(), refusal } + } +} + +impl Chat for FakeChat { + fn pending(&self, _: u64) -> Result { + bail!("a turn reads the room through its organs, not the actuator") + } + fn send(&self, request: &ChatSendRequest) -> Result { + self.sent.borrow_mut().push(request.clone()); + let event_id = self.refusal.is_none().then(|| format!("$sent-{}", self.sent.borrow().len())); + Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id, refusal: self.refusal, newer: vec![] }) + } + fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result { + bail!("a turn opens no conversation") + } + fn fetch(&self, _: &ChatFetchRequest) -> Result { + bail!("a turn fetches nothing") + } + fn ack(&self, _: u64) -> Result<()> { + bail!("a turn acks nothing") + } + fn read(&self, _: &ChatRead) -> Result<()> { + bail!("a turn reports no read") + } +} + +fn mouth(chat: &FakeChat) -> Mouth<'_> { + Mouth { chat, persona: "eureka".into(), key: "run-t1".into(), basis: None, sent: Cell::new(0) } +} + +/// One turn from the operator-warm fixture, she saying one line in reply, through `actuator`. +fn warm_turn(actuator: &dyn Actuator) -> Taken { + let dir = tempfile::tempdir().unwrap(); + let model = Scripted::new(|_| "He smiles at the screen, then types. Missed you too, friend.".into()); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&model)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); + take(&organs, &request, actuator, "run-t1", fixture.now) +} + +#[test] +fn t_l1_mouth_sends_the_text_that_went_and_records_the_receipt() { + let chat = FakeChat::new(None); + let taken = warm_turn(&mouth(&chat)); + let sent = chat.sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!((sent[0].request_id.as_str(), sent[0].persona.as_str(), sent[0].room_alias.as_str(), sent[0].text.as_str()), ("run-t1:s0", "eureka", "!dm-meta:gamecult.org", "Missed you too, friend.")); + assert_eq!(taken.record["posted"], json!([{ "event": "$sent-1", "room": "!dm-meta:gamecult.org", "text": "Missed you too, friend." }])); +} + +#[test] +fn t_l1_mouth_refusal_is_a_refused_send_and_no_posted_row() { + let chat = FakeChat::new(Some(Refusal::RoomMoved)); + let taken = warm_turn(&mouth(&chat)); + assert_eq!(taken.record["posted"], json!([])); + assert_eq!(taken.record["refused_sends"][0]["refusal"], "RoomMoved"); + assert_eq!(taken.record["refused_sends"][0]["text"], "Missed you too, friend."); +} + +#[test] +fn t_l1_mouth_edit_told() { + assert_eq!(mouth(&FakeChat::new(None)).edit("$sent-1", "I could not."), Some("no_edit_at_the_mouth")); + let record = json!({ + "interpreter": { "said": [{ "room": "!r:x", "text": "I will send it." }], "amended": [{ "event": "$sent-1", "added": "I could not.", "room": "!r:x" }] }, + "posted": [{ "event": "$sent-1", "room": "!r:x", "text": "I will send it." }], + "edited": [{ "event": "$sent-1", "refusal": "no_edit_at_the_mouth" }], + "refused_sends": [], + }); + let told = outcome_of(&record).expect("a record she can be told of"); + let told = told.lines(forms(&control())).join("\n"); + assert!(told.contains("a line cannot be added to once it is said here"), "{told}"); + assert!(told.contains("Nothing changed"), "{told}"); +} + +struct FailingPersona; + +impl Model for FailingPersona { + fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { + if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: None }) } + } +} + +#[test] +fn t_l1_failed_turn_record() { + let dir = tempfile::tempdir().unwrap(); + let chat = FakeChat::new(None); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&FailingPersona)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let state = control(); + let request = fixture_request(&harness, &fixture, Some(state.clone()), 3, Some(1), Through::Interpreter); + let taken = take(&organs, &request, &mouth(&chat), "run-t1", fixture.now); + assert!(chat.sent.borrow().is_empty(), "a failed turn sends nothing"); + assert_eq!(taken.failed(), Some("the provider failed the call: Overloaded")); + let mut keys: Vec<&str> = taken.record.as_object().unwrap().keys().map(String::as_str).collect(); + keys.retain(|key| !matches!(*key, "selected" | "at" | "committed")); + assert_eq!(keys, ["failed"], "the record holds the failure alone beside what every record carries"); + assert_eq!(taken.state, state, "a failed turn applies nothing"); + assert_eq!(taken.applied, Applied::default()); +} + +#[test] +fn t_l1_history_from_records() { + let at = |minute: i64| (chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339(); + let turn = |minute: i64, ids: &[&str]| json!({ "interpreter": {}, "selected": ids, "at": at(minute) }); + let mut records: Vec = (0..7).map(|at| turn(at, &[&format!("m{at}")])).collect(); + assert_eq!(history(&[]), Past::default()); + let past = history(&records); + assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first"); + assert_eq!(past.last_outcome.as_ref(), records.last()); + assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6))); + records.push(json!({ "failed": "Overloaded", "selected": ["m7"], "at": at(7) })); + let past = history(&records); + assert_eq!(past.last_outcome.as_ref().map(|last| last["failed"].clone()), Some(json!("Overloaded")), "her last outcome is the failure"); + assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed turn is no wake"); + assert_eq!(past.recent.last(), Some(&vec!["m7".to_owned()]), "a failed turn still showed what it selected"); + let long: Vec = (0..60).map(|at| turn(at, &[])).collect(); + assert_eq!(history(&long).records.len(), 50); + assert_eq!(history(&long).records[0]["at"], json!(at(10)), "her last fifty, oldest first"); +}