diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index d51b758..81d1f02 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -18,7 +18,8 @@ //! aside: one `set_aside` record, the line acked past, and her next wake is told so (`outcome`). A wake over several rooms strikes nothing. //! The heartbeat never acks. //! -//! The put (`put_applied`) is the Interpreter's, when it attaches: under the `updatedAt` she was read at, stamped at the put and later than the stored one (P5). +//! After a completed wake's record is durable the Interpreter reads her monologue and its deltas are put once (`put_applied`) under the `updatedAt` she was read +//! at, stamped at the put and later than the stored one (P5); its receipt, and the post of any identity change to the review room, are rows in her trace. //! //! What the module holds besides the drain is what a chat line is made of: her `Config`, who a sender is to her //! (`sender_role`), whom a message addresses (`addressees`, `addressing_of`), the framed `message` line, the tail of @@ -33,14 +34,15 @@ use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, Utc}; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore, decode_payload}; use eureka_pipeline::{MemoryOrigin, Slug}; +use huginn_mind::persona::validate_document; use huginn_mind::{Faculty, HuginnMindResponse, MindRefusal, PersonaPutOutcome, PipelineProvenance}; use serde_json::{Value, json}; use crate::address::{Addressee, addresses, is_for, localpart}; -use crate::chat_client::{Basis, Chat, ChatDelivery, Form, TailLine}; +use crate::chat_client::{Basis, Chat, ChatDelivery, ChatSendRequest, Form, TailLine}; use crate::control::{ControlSource, Effective, HeldReason, derive}; use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes}; -use crate::projection::{DomainSource, HuginnPersonaSource, Model, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decided, history, wake, own_addressee as heard_as}; +use crate::projection::{Applied, DomainSource, Heard, HuginnPersonaSource, Model, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, decided, history, interpret, load_tuning, people_named, wake, own_addressee as heard_as}; /// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it. pub const AGENT: &str = "mind-persona"; @@ -52,6 +54,8 @@ pub const ENV_MINDS: &str = "MIND_PERSONA_MINDS"; pub const ENV_SELF_SENDER: &str = "MIND_PERSONA_SELF_SENDER"; /// The model her turn runs. pub const ENV_MODEL: &str = "MIND_PERSONA_MODEL"; +/// The room alias an identity change is posted to; optional. +pub const ENV_REVIEW_ROOM: &str = "MIND_PERSONA_REVIEW_ROOM"; /// What a start needs to know that is not in the mind: which rooms she may /// speak in, and who the operator is. @@ -67,6 +71,9 @@ pub struct Config { pub own_sender: String, /// The model her turn runs. Set from `MIND_PERSONA_MODEL` by `from_args_and_env`; empty from `from_args`. pub model: String, + /// The room an identity change is posted to with its diff (`MIND_PERSONA_REVIEW_ROOM`, an alias). None, and a wake makes no identity change + /// (`identity-write-all-visible`). + pub review_room: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -119,7 +126,7 @@ impl Config { if items.iter().any(String::is_empty) { Err(anyhow!("{usage}")) } else { Ok(items) } }; let rooms = list(rooms)?; - let config = Self { rooms, operators: list(operators)?, minds: list(minds)?, own_sender: own.ok_or_else(|| anyhow!("{usage}"))?, model: String::new() }; + let config = Self { rooms, operators: list(operators)?, minds: list(minds)?, own_sender: own.ok_or_else(|| anyhow!("{usage}"))?, model: String::new(), review_room: None }; Ok((config, rest)) } @@ -138,6 +145,7 @@ impl Config { } } let (mut config, rest) = Self::from_args(&args, usage)?; + config.review_room = lookup(ENV_REVIEW_ROOM).filter(|value| !value.is_empty()); config.model = lookup(ENV_MODEL).filter(|value| !value.is_empty()).ok_or_else(|| anyhow!("{ENV_MODEL} is not set"))?; Ok((config, rest)) } @@ -474,18 +482,81 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { record["strike"] = json!(line.event); } } - // The Interpreter reads (narration, prose, the lines held) here and its deltas are put through `put_applied`; the agent's turn follows it - // (map 16.38.2, items 5): neither is built yet, so a wake changes no state and posts nothing. - // The record is durable before anything is acked, and a record that cannot be written acks nothing: the lines are woken for again. - // A failed wake acks nothing: the lines it was over are woken for again, in one room if it was a blend. + // The record is durable before the Interpreter reads and before anything is acked, and a record that cannot be written acks nothing: + // the lines are woken for again. A failed wake acks nothing, and the Interpreter reads none: the lines it was over are woken for again, + // in one room if it was a blend. The agent's turn follows the Interpreter's put (map 16.38.2, item 5); it is not built yet. match start.trace.record(&record_key, &record) { - Ok(()) if waked.failed.is_none() => settle(&mut acked), + Ok(()) if waked.failed.is_none() => { + interpreted(start, instance, &state, &waked, &deliveries, &held, rooms[0], &stem, records.len(), began_ms); + settle(&mut acked); + } Ok(()) => {} Err(fault) => eprintln!("mind-persona: the record of wake {key} was not appended, so nothing is acked: {fault:#}"), } Outcome::Drained { wakes: 1, acked_through: acked } } +/// What the Interpreter does after a completed wake (map 16.38.7): one schema call over her narration and prose, its deltas applied +/// by the commit and put once (`put_applied`), and one receipt row in her trace. When the put landed with an identity change, the +/// change is posted with its diff to the review room through the mouth, as a code-written line with its own `say` row. Nothing here +/// fails the wake: the lines are decided and acked whatever the Interpreter did, and her next wake hears when her state was not kept. +#[allow(clippy::too_many_arguments)] +fn interpreted(start: &Start, instance: &Slug, state: &Value, waked: &Waked, deliveries: &[&ChatDelivery], held: &[&str], room: &str, stem: &str, place: usize, began_ms: u64) { + let config = &start.config; + let (Some(narration), Some(prose)) = (waked.narration.as_deref(), waked.prose.as_deref()) else { return }; + let now = (start.clock)(); + let packet = &waked.report["packet"]; + let mut heard = Heard { + room: packet["room"].as_str().or(Some(room)).map(str::to_owned), + lines: packet["bodies"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).chain(deliveries.iter().filter(|delivery| held.contains(&delivery.event_id.as_str()) && delivery.sender != config.own_sender).map(|delivery| delivery.text.clone())).collect(), + people: vec![], + operators: config.operators.clone(), + minds: config.minds.clone(), + identity_visible: config.review_room.is_some(), + }; + heard.people = packet["people"].as_array().into_iter().flatten().filter_map(|pair| pair[1].as_str()).map(|sender| heard.key_of(sender)).collect(); + heard.people = people_named(state, &heard, narration, prose); + let row = |at: usize, body: Value| { + let mut row = json!({ "seq": place + at, "at": now.to_rfc3339(), "wake": stem }); + row.as_object_mut().expect("a row is an object").extend(body.as_object().cloned().unwrap_or_default()); + row + }; + let model = match load_tuning(&start.tuning) { + Ok(loaded) => loaded.tuning.interpreter.model, + Err(fault) => return eprintln!("mind-persona: the Interpreter's model was not read: {fault:#}"), + }; + let request = format!("{stem}-i{began_ms}"); + let receipt = match interpret(start.model.as_ref(), &model, &request, state, &heard, narration, prose) { + Err(failed) => json!({ "kind": "interpreter", "status": "error", "put": "none", "error": failed.reason, "usage": failed.usage, "put_refused": true }), + Ok((deltas, usage)) => match put_applied(&*start.persona, state, &Taken { deltas: &deltas, heard: &heard, instance }, stem, now, &*start.clock) { + Ok(landed) => { + if let Some(say) = identity_post(start, instance, &landed.applied, stem) + && let Err(fault) = start.trace.record(&format!("{stem}-s"), &row(2, say)) + { + eprintln!("mind-persona: the record of the identity post was not appended: {fault:#}"); + } + json!({ "kind": "interpreter", "status": "ok", "put": landed.put, "applied": landed.applied.changes, "refused": landed.applied.refused, "pruned": landed.applied.pruned, "usage": usage }) + } + Err(missed) => json!({ "kind": "interpreter", "status": "error", "put": "refused", "error": missed.why, "applied": missed.applied.changes, "refused": missed.applied.refused, "usage": usage, "put_refused": true }), + }, + }; + if let Err(fault) = start.trace.record(&format!("{stem}-i"), &row(1, receipt)) { + eprintln!("mind-persona: the Interpreter's receipt was not appended: {fault:#}"); + } +} + +/// The identity changes a landed put made, posted to the review room as one code-written line with each field's value before and +/// after (`identity-write-all-visible`), and the `say` row that records the post. None when nothing changed or no room is named. +fn identity_post(start: &Start, instance: &Slug, applied: &Applied, stem: &str) -> Option { + let room = start.config.review_room.as_deref().filter(|_| !applied.identity.is_empty())?; + let text = format!("{}'s identity changed.\n{}", instance.0, applied.identity.iter().map(|diff| format!("{}: {} -> {}", diff.field, diff.before, diff.after)).collect::>().join("\n")); + let request = ChatSendRequest { request_id: format!("{stem}-id"), persona: instance.0.clone(), room_alias: room.to_owned(), text: text.clone(), basis: None, resend: false }; + Some(match start.chat.send(&request) { + Ok(receipt) => json!({ "kind": "say", "say": { "room": room, "text": text, "event": receipt.event_id, "refusal": receipt.refusal.map(|refusal| format!("{refusal:?}")) } }), + Err(fault) => json!({ "kind": "say", "say": { "room": room, "text": text, "event": null, "refusal": format!("{fault:#}") } }), + }) +} + /// Her put through the persona door, the one writer of her state a start has. impl PersonaStore for HuginnPersonaSource { fn put(&self, state: &Value, expected_updated_at: Option<&str>, session: &str) -> Result { @@ -521,30 +592,48 @@ fn stamp_after(now: DateTime, stored: Option<&str>) -> String { floor.map_or(now, |floor| now.max(floor)).to_rfc3339() } -/// `turn`'s state put under the `updatedAt` she was read at (`read`, the state the turn began from). A stale put reads -/// her again, applies the same record to the state as it stands and puts once more. The state as stored is the answer; -/// when the second put is refused too, the state as it then stands, and why. -#[allow(dead_code, reason = "the Interpreter's deltas attach here (P2): its first caller removes this allow")] -fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime, clock: &dyn Fn() -> DateTime) -> std::result::Result { - let stamped = |mut state: Value, stored: &Value| { - state["updatedAt"] = json!(stamp_after(clock(), stored.get("updatedAt").and_then(Value::as_str))); - state +/// A put that landed: what was applied, and how the put went (`committed`, or `stale_reapplied` when +/// her state moved under it and the same deltas were applied to the state as it then stood). +pub(crate) struct Landed { + pub applied: Applied, + pub put: &'static str, +} + +/// A put that did not land: what the last attempt would have applied, and why nothing was put. +pub(crate) struct Missed { + pub applied: Applied, + pub why: String, +} + +/// The deltas of `turn` applied to her state and put under the `updatedAt` she was read at (`read`, the state the wake began +/// from). Each attempt applies, stamps (P5), validates the whole document against the schema and only then puts: a state the +/// schema refuses is never put. A stale put reads her again and applies the same deltas to the state as it stands, so what Self +/// or Life put in between survives, and puts once more. +fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime, clock: &dyn Fn() -> DateTime) -> std::result::Result { + let attempt = |from: &Value| -> (std::result::Result, Applied) { + let (mut next, applied) = apply_commit(from, turn.deltas, turn.heard, key, now); + next["updatedAt"] = json!(stamp_after(clock(), from.get("updatedAt").and_then(Value::as_str))); + match validate_document(turn.instance, &next) { + Ok(_) => (Ok(next), applied), + Err(refusal) => (Err(format!("the schema refuses the state: {refusal}")), applied), + } }; - let next = stamped(turn.state.clone(), read); + let (next, applied) = attempt(read); + let next = next.map_err(|why| Missed { applied: applied.clone(), why })?; match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) { - Ok(Put::Committed) => return Ok(next), + Ok(Put::Committed) => return Ok(Landed { applied, put: "committed" }), Ok(Put::Stale) => {} - Ok(Put::Refused(why)) => return Err((read.clone(), why)), - Err(fault) => return Err((read.clone(), format!("{fault:#}"))), + Ok(Put::Refused(why)) => return Err(Missed { applied, why }), + Err(fault) => return Err(Missed { applied, why: format!("{fault:#}") }), } - let (fresh, _) = store.persona().map_err(|fault| (read.clone(), format!("her state was not read again: {fault:#}")))?; - let (applied, _) = apply_commit(&fresh, &turn.record, key, now); - let next = stamped(applied, &fresh); + let (fresh, _) = store.persona().map_err(|fault| Missed { applied: applied.clone(), why: format!("her state was not read again: {fault:#}") })?; + let (next, applied) = attempt(&fresh); + let next = next.map_err(|why| Missed { applied: applied.clone(), why })?; match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) { - Ok(Put::Committed) => Ok(next), - Ok(Put::Stale) => Err((fresh, "stale again".to_owned())), - Ok(Put::Refused(why)) => Err((fresh, why)), - Err(fault) => Err((fresh, format!("{fault:#}"))), + Ok(Put::Committed) => Ok(Landed { applied, put: "stale_reapplied" }), + Ok(Put::Stale) => Err(Missed { applied, why: "stale again".to_owned() }), + Ok(Put::Refused(why)) => Err(Missed { applied, why }), + Err(fault) => Err(Missed { applied, why: format!("{fault:#}") }), } } diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 6ecfccf..a8bcfb5 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -86,21 +86,43 @@ impl Chat for Rc { } } -/// Her persona document as the mind holds it. A wake puts nothing yet. -struct FakeStore(Value); +/// Her persona document as the mind holds it: a put under the stored `updatedAt` commits, any other is stale. `outside` is a put by +/// Self or Life that lands between her read and her put. +struct FakeStore { + state: RefCell, + puts: RefCell>, + outside: RefCell>, +} + +impl FakeStore { + fn new(state: Value) -> Self { + Self { state: RefCell::new(state), puts: RefCell::default(), outside: RefCell::default() } + } +} impl PersonaSource for Rc { fn persona(&self) -> Result<(Value, String)> { - Ok((self.0.clone(), "receipt".into())) + Ok((self.state.borrow().clone(), "receipt".into())) } } impl PersonaStore for Rc { - fn put(&self, _: &Value, _: Option<&str>, _: &str) -> Result { - bail!("a wake puts nothing yet") + fn put(&self, state: &Value, expected: Option<&str>, _: &str) -> Result { + if let Some(outside) = self.outside.borrow_mut().take() { + *self.state.borrow_mut() = outside; + } + if expected != self.state.borrow()["updatedAt"].as_str() { + return Ok(Put::Stale); + } + self.puts.borrow_mut().push(state.clone()); + *self.state.borrow_mut() = state.clone(); + Ok(Put::Committed) } } +/// The Interpreter's opening: what a call of the Interpreter starts with. +const INTERPRETER: &str = "You are a private Interpreter."; + struct MemTrace { rows: RefCell>, /// The trace cannot be written (the state directory is full). @@ -165,7 +187,13 @@ struct Tally(Rc>>); impl Model for Tally { fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { self.0.borrow_mut().push(prompt.to_owned()); - let text = if prompt.starts_with("You are a private Projector.") { "The room is slow and so is he." } else { "He thinks of them and is glad." }; + let text = if prompt.starts_with("You are a private Projector.") { + "The room is slow and so is he." + } else if prompt.starts_with(INTERPRETER) { + "{}" + } else { + "He thinks of them and is glad." + }; Ok(Answer { text: text.into(), usage: None }) } } @@ -177,6 +205,8 @@ struct Rig { dir: TempDir, /// The clock's ticks, kept across starts as a real clock is. ticks: Rc>, + /// The room an identity change is posted to, when one is named. + review: RefCell>, } impl Rig { @@ -186,14 +216,14 @@ impl Rig { SwarmWriter::open(dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), ack_fails: Cell::new(false) }); let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false) }); - Self { mouth, trace, store: Rc::new(FakeStore(control())), dir, ticks: Rc::default() } + Self { mouth, trace, store: Rc::new(FakeStore::new(control())), dir, ticks: Rc::default(), review: RefCell::default() } } fn run(&self, model: impl Model + 'static) -> Outcome { let ticks = self.ticks.clone(); let start = || { Ok(Start { - config: Config { rooms: vec!["#minds:gamecult.org".into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into() }, + config: Config { rooms: vec!["#minds:gamecult.org".into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into(), review_room: self.review.borrow().clone() }, persona: Box::new(self.store.clone()), chat: self.mouth.clone(), trace: Box::new(self.trace.clone()), @@ -211,10 +241,16 @@ impl Rig { carry(&FileSource::new(self.dir.path().join("control.cc")), &FileSource::new(self.dir.path().join("swarm.cc")), &Slug("eureka".into()), start) } - fn records(&self) -> Vec { + /// Every row of her trace: the wakes, and the Interpreter's receipts and posts beside them. + fn all_records(&self) -> Vec { self.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect() } + /// Her wake records alone. + fn records(&self) -> Vec { + self.all_records().into_iter().filter(|record| !matches!(record["kind"].as_str(), Some("interpreter" | "say"))).collect() + } + fn acks(&self) -> Vec { self.mouth.acks.borrow().clone() } @@ -231,7 +267,8 @@ fn t_p1_one_projector_one_persona() { let tally = Tally::default(); assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, acked_through: Some(3) }); let prompts = tally.0.borrow(); - assert_eq!(prompts.len(), 2, "a wake with waking lines in three rooms makes exactly two model calls"); + assert_eq!(prompts.len(), 3, "a wake with waking lines in three rooms makes exactly three model calls: the Projector, the Persona and the Interpreter"); + assert!(prompts[2].starts_with(INTERPRETER)); assert!(prompts[0].starts_with("You are a private Projector.")); let records = rig.records(); assert_eq!(records.len(), 1, "one wake record"); @@ -437,3 +474,115 @@ fn t_p1_an_overflowed_turn_room_tells_her_the_count_and_acks_every_held_line_onc assert_eq!(acks.last().copied(), held.iter().max().copied(), "the ack reaches the newest line the turn holds"); assert!(held.iter().all(|seq| acks.last().is_some_and(|last| seq <= last)), "every held line is acked: {held:?}"); } + +/// A recorded model whose Interpreter answers `deltas`. +struct Interprets(&'static str); + +impl Model for Interprets { + fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { + let text = if prompt.starts_with("You are a private Projector.") { + "The room is slow and so is he." + } else if prompt.starts_with(INTERPRETER) { + self.0 + } else { + "He thinks of them and is glad." + }; + Ok(Answer { text: text.into(), usage: None }) + } +} + +fn rows<'a>(records: &'a [Value], kind: &str) -> Vec<&'a Value> { + records.iter().filter(|record| record["kind"] == kind).collect() +} + +const MOVES: &str = r#"{"notes":{"remember":[{"text":"Tobiah thinks the room is slow today.","importance":0.4}]},"people":{"bonds":[{"person":"operator","trust":"up"}]},"feeling":{"feelings":[{"name":"calm","strength":0.5}]}}"#; + +/// One wake, one Interpreter call, one put, one receipt: the deltas land bounded, and the lines are acked. +#[test] +fn t_p2_one_call_one_put_one_receipt() { + let rig = three_rooms(); + assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, acked_through: Some(3) }); + let state = { + let puts = rig.store.puts.borrow(); + assert_eq!(puts.len(), 1, "one put a wake"); + puts[0].clone() + }; + assert_eq!(state["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), 1); + assert_eq!(state["affect"]["moodDimensions"][0]["value"].as_f64(), Some(0.35), "a feeling rises at most 0.35"); + let operator = state["affect"]["socialBonds"].as_array().unwrap().iter().find(|bond| bond["object"]["id"] == "operator").unwrap(); + assert!((operator["trust"].as_f64().unwrap() - (control()["affect"]["socialBonds"][1]["trust"].as_f64().unwrap() + 0.08)).abs() < 1e-9); + assert!(state["updatedAt"].as_str().unwrap() > control()["updatedAt"].as_str().unwrap(), "stamped later than what she was read at (P5)"); + let records = rig.all_records(); + let receipts = rows(&records, "interpreter"); + assert_eq!((receipts.len(), receipts[0]["status"].as_str(), receipts[0]["put"].as_str()), (1, Some("ok"), Some("committed"))); + assert_eq!(receipts[0]["applied"].as_array().unwrap().len(), 3); + assert!(rig.mouth.sent.borrow().is_empty(), "no identity changed, so nothing is posted"); + // The receipt is a row beside the wake, never a wake of its own: her last turn is still the wake. + assert_eq!(history(&records).last_outcome.unwrap()["kind"], "chat"); +} + +/// A call that answers nothing usable moves nothing, puts nothing, is receipted as an error, and does not undo the wake. +#[test] +fn t_p2_a_failed_call_puts_nothing_and_the_wake_still_decides_its_lines() { + let rig = three_rooms(); + assert_eq!(rig.run(Interprets("this is not the contract")), Outcome::Drained { wakes: 1, acked_through: Some(3) }); + assert!(rig.store.puts.borrow().is_empty()); + let records = rig.all_records(); + let receipt = rows(&records, "interpreter")[0]; + assert_eq!((receipt["status"].as_str(), receipt["put"].as_str(), receipt["put_refused"].clone()), (Some("error"), Some("none"), json!(true))); + assert_eq!(history(&records).last_outcome.unwrap()["untold"], json!([{ "kind": "not_kept" }]), "her next wake is told her state was not kept"); +} + +/// T-P2: a publicName change is put, and the drain posts the diff to the review room with its own say row; with no review room none is made. +#[test] +fn t_p2_identity_diff_is_posted_to_the_review_room() { + const RENAME: &str = r#"{"self":{"identity":{"publicName":"Tobiah of the River"}}}"#; + let rig = three_rooms(); + *rig.review.borrow_mut() = Some("#review:gamecult.org".into()); + rig.run(Interprets(RENAME)); + assert_eq!(rig.store.puts.borrow()[0]["publicName"], "Tobiah of the River"); + let sent = rig.mouth.sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].room_alias, "#review:gamecult.org"); + assert!(sent[0].text.contains("publicName") && sent[0].text.contains("Tobiah Fenn") && sent[0].text.contains("Tobiah of the River"), "{}", sent[0].text); + let records = rig.all_records(); + let say = rows(&records, "say"); + assert_eq!((say.len(), say[0]["say"]["event"].as_str()), (1, Some("$sent"))); + // No room named: the change is refused, nothing is put for it and nothing is posted. + let rig = three_rooms(); + rig.run(Interprets(RENAME)); + assert!(rig.mouth.sent.borrow().is_empty()); + assert_eq!(rig.store.puts.borrow()[0]["publicName"], "Tobiah Fenn"); + assert_eq!(rows(&rig.all_records(), "interpreter")[0]["refused"][0]["reason"], "no_review_room"); +} + +/// T-P2: Self's put between her read and her put survives, and her deltas are applied on top of it. +#[test] +fn t_p2_stale_reapply_keeps_outside_put() { + let rig = three_rooms(); + let mut outside = control(); + outside["publicDescription"] = json!("Described by Self while she was thinking."); + outside["updatedAt"] = json!("2026-11-21T09:00:00Z"); + *rig.store.outside.borrow_mut() = Some(outside); + rig.run(Interprets(MOVES)); + let puts = rig.store.puts.borrow(); + assert_eq!(puts.len(), 1); + assert_eq!(puts[0]["publicDescription"], "Described by Self while she was thinking."); + assert_eq!(puts[0]["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), 1, "her deltas were applied on the state as it stood"); + assert_eq!(rows(&rig.all_records(), "interpreter")[0]["put"], "stale_reapplied"); +} + +/// T-P2: a state the schema refuses is never put, and the receipt says error. +#[test] +fn t_p2_schema_refusal_no_put() { + let store = Rc::new(FakeStore::new(control())); + let mut read = control(); + read["notInTheSchema"] = json!(true); + let heard = Heard::default(); + let deltas = Default::default(); + let slug = Slug("eureka".into()); + let taken = Taken { deltas: &deltas, heard: &heard, instance: &slug }; + let missed = put_applied(&store, &read, &taken, "w1", at(0), &|| at(1)).err().expect("the schema refuses it"); + assert!(missed.why.contains("schema"), "{}", missed.why); + assert!(store.puts.borrow().is_empty()); +} diff --git a/crates/mind-body/src/persona/tests.rs b/crates/mind-body/src/persona/tests.rs index 1f37450..3f1a16e 100644 --- a/crates/mind-body/src/persona/tests.rs +++ b/crates/mind-body/src/persona/tests.rs @@ -20,6 +20,7 @@ fn config() -> Config { minds: vec!["@eureka:chat".into(), "@libby:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into(), + review_room: None, } } @@ -237,7 +238,7 @@ fn the_persona_flags_come_from_the_environment_when_the_command_line_lacks_them( let (config, rest) = Config::from_args_and_env(&args("--instance eureka"), env, "usage").unwrap(); assert_eq!( config, - Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into() } + Config { rooms: vec!["swarm".into(), "usage".into()], operators: vec!["@op:chat".into(), "@op2:chat".into()], minds: vec!["@libby:chat".into(), "@aqua:chat".into()], own_sender: "@eureka:chat".into(), model: "claude-test-model".into(), review_room: None } ); assert_eq!(rest, ["--instance", "eureka"]); // A flag wins over its variable, one at a time. diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 43bedbf..e72313a 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -24,6 +24,7 @@ pub mod harness; mod commit; mod domain; mod exchange; +mod interpret; mod narrate; mod outcome; mod read; @@ -50,13 +51,16 @@ pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain}; pub use narrate::{Answer, Failed, KitModel, Model, Spent, StepRequest, Stepped, ToolCall, connector_key}; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; -pub(crate) use commit::apply as apply_commit; +pub(crate) use commit::{Applied, Heard, apply as apply_commit}; +pub(crate) use interpret::{deltas as interpret, people as people_named}; pub(crate) use turn::{Taken, decided, failed_run, history}; -pub(crate) use wake::wake; +pub(crate) use wake::{Waked, wake}; pub use tuning::{TUNING_FILE, TUNING_ROOT}; +pub(crate) use tuning::load as load_tuning; +pub(crate) use select::People; use narrate::{cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; -use select::{History, Inputs, Packet, People, Replied, Room, RoomLine, select, turn_room}; +use select::{History, Inputs, Packet, Replied, Room, RoomLine, select, turn_room}; /// The agent name on the connector's request ids. const AGENT: &str = "mind-persona"; diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index c39568f..3b8b7be 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -1,136 +1,941 @@ -//! The commit's applier (map 16.35.3, section 4.4): the one path by which a turn changes her state. The Interpreter -//! never writes state; its decision carries typed proposals (`Proposal`) under `state`, and the commit applies each as a -//! delta to her state as it stands at commit, or refuses it with a typed reason (`Refusal`) the report keeps. Self and -//! Life put from outside (`persona-only-state-writers-self-and-life`). +//! The commit's applier (map 16.38.7, 16.38.9): the one path by which a wake changes her state. The Interpreter never writes +//! state; it answers `Deltas`, directions in six families, and `apply` decides how far each goes, by the bounds below, and +//! refuses what it may not do, with a typed reason (`Why`) the receipt keeps. Self and Life put from outside +//! (`persona-only-state-writers-self-and-life`); her own write is this module's. //! -//! A turn writes `thoughtMemory.shortTerm` and nothing else (ruling `persona-memory-not-machinery`, map 16.35.4): -//! - `remember` appends one anchored thought, a third-person note in her words of it, tagged with the turn's room, the -//! people it concerns and `private` when it is; a note made in a direct message carries that room's `room:!…` tag, so -//! `select::concerns` reads it as private by the existing convention; -//! - `resolve` sets one of her short-term memories, as the Interpreter's list mapped it, `resolved`; -//! - a short-term memory resolved more than `RESOLVED_KEPT_DAYS` ago is removed; one resolved with no time (an outside put) -//! is stamped at the first commit that sees it. +//! What a wake may touch, and nothing else (the list of 16.38.9): +//! - `thoughtMemory.*`: notes remembered, wonderings, notes settled into `resolved` or `crystallized`; +//! - `affect.socialBonds` (trust, tension and intensity move `BOND_STEP` a wake; a summary only with a why, the old one going to +//! `lastEvidence`), `affect.statusReads` (upserted by person and kind, cooling and retiring with age) and +//! `affect.moodDimensions` (a feeling set by its strength, decaying with a half-life of `FEELING_HALF_LIFE_HOURS`); +//! - the existing items of `affect.needs` and `agencyPressure.pressures` (intensity moves `DRIVE_STEP`; never created here); +//! - `affect.doctrineStances`, and `values`, `publicName`, `publicDescription` and `presentation`, which are identity: each +//! change is returned as an `IdentityDiff` for the drain to post, and is refused when nothing would show it +//! (`identity-write-all-visible`); +//! - `activationProfile.situationalState.*.currentActivation`, by each trait's own plasticity; +//! - the intentions of `candidateActions` (`customActionType` `intention`): at most `INTENTIONS_MAX` added a wake, each +//! expiring within a week. Nothing enforces or tracks one as a promise (`candidate-actions-lived`). //! -//! What she says she will do, what someone asked of her, and whom she owes an answer are no state of their own: they live -//! only as memories she chose to keep. A failed turn applies nothing. +//! Every text it keeps is refused when it is empty, over `MEMORY_BYTES`, or carries someone else's words (`quotes`, I16.7: +//! no one's line reaches the Projector by way of her state). A refusal is per item and never retried. A resolved short-term +//! note older than `RESOLVED_KEPT_DAYS` is removed. //! -//! The simulator applies each turn's record to each Mind's in-run state copy; live, C3c's commit applies the same record -//! before its put. +//! The drain and the simulator apply through this one function. The caller validates the whole document before it puts it. + +use std::collections::BTreeSet; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -/// How long a resolved short-term memory is kept before the commit removes it. -pub(crate) const RESOLVED_KEPT_DAYS: i64 = 7; +use super::narrate::heard_overlap; +use super::select::People; +use super::span; -/// One state change the Interpreter proposes, named by its kind on the wire (the Interpreter builds them). -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum Proposal { - /// A note she would want to still know (map 16.35.4): its words, the Matrix ids of the people it concerns, how much it - /// matters to her (0..1), whether it is private, and the turn's room, when it had one. - Remember { text: String, about: Vec, importance: f64, private: bool, room: Option }, - /// One of her memories this moment settles: its id in the Interpreter's list, and the state entry it is. - Resolve { memory: String, entry: String }, +/// How long a resolved short-term memory, or a retired intention, is kept before the commit removes it. +const RESOLVED_KEPT_DAYS: i64 = 7; +/// The longest kept text, in bytes, once trimmed. +const MEMORY_BYTES: usize = 600; +/// The most notes (remembered or wondered) a wake keeps. +const NOTES_MAX: usize = 4; +/// The most notes a wake settles, into `resolved` or `crystallized` together. +const SETTLES_MAX: usize = 2; +/// How far a bond's trust, tension or intensity moves in a wake. +const BOND_STEP: f64 = 0.08; +/// A bond with someone she has none with yet starts here: trust, tension, intensity. +const NEW_BOND: (f64, f64, f64) = (0.5, 0.1, 0.2); +/// How far a need's or a pressure's intensity moves in a wake. +const DRIVE_STEP: f64 = 0.12; +/// A need or pressure cooling this long is resolved. +const DRIVE_RESOLVES_DAYS: i64 = 7; +/// `currentActivation` moves at most plasticity times this a wake, and drifts to its mean by plasticity times `MOOD_DRIFT`. +const MOOD_MOVE: f64 = 0.25; +const MOOD_DRIFT: f64 = 0.1; +/// A named feeling halves in this long; one set this wake rises at most `FEELING_RISE` over its decayed value; one under +/// `FEELING_FLOOR` is removed. +const FEELING_HALF_LIFE_HOURS: f64 = 8.0; +const FEELING_RISE: f64 = 0.35; +const FEELING_FLOOR: f64 = 0.05; +/// A status read cools after this many days without renewal, and retires after the second. +const READ_COOLS_DAYS: i64 = 3; +const READ_RETIRES_DAYS: i64 = 10; +/// The most intentions a wake adds, and the longest any lives, in hours. +const INTENTIONS_MAX: usize = 3; +const INTENTION_HOURS_MAX: i64 = 168; +/// A line of at least this many words whose word trigrams are at least `ECHO_OVERLAP` of what she heard is an echo; and the +/// run of this many consecutive words shared with a line she was shown is a quote. +const ECHO_MIN_WORDS: usize = 8; +const ECHO_OVERLAP: f64 = 0.8; + +/// The six families of what the Interpreter proposes (map 16.38.7). Every field is optional, and `{}` is "nothing moved". A +/// direction is a word, never a number: code decides how far. +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Deltas { + pub notes: Notes, + pub people: Personal, + pub feeling: Feeling, + pub drives: Drives, + #[serde(rename = "self")] + pub identity: Selfhood, + pub intend: Intend, } -/// Why the commit applied nothing of a proposal: what the report says. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Notes { + pub remember: Vec, + pub settle: Vec, + pub wonder: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Remember { + pub text: String, + pub about: Vec, + pub importance: Option, + pub private: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Settle { + pub id: String, + /// `resolved` or `memory`. + pub into: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Wonder { + pub text: String, + pub about: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Personal { + pub bonds: Vec, + pub reads: Vec, +} + +/// One bond's directions: `up` or `down` for trust, tension and closeness (the bond's intensity). +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct BondDelta { + pub person: String, + pub trust: Option, + pub tension: Option, + pub closeness: Option, + pub kind: Option, + pub summary: Option, + pub why: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct ReadDelta { + pub person: String, + pub kind: String, + pub summary: String, + pub confidence: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Feeling { + pub feelings: Vec, + pub mood: Mood, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct FeelingDelta { + pub name: String, + pub strength: f64, + pub about: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Mood { + pub valence: Option, + pub arousal: Option, + pub dominance: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Drives { + pub needs: Vec, + pub pressures: Vec, +} + +/// `toward` is `up`, `down`, or `met` (a need) or `eased` (a pressure). +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct DriveDelta { + pub id: String, + pub toward: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Selfhood { + pub stances: Vec, + pub identity: IdentityDelta, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct StanceDelta { + pub id: Option, + pub principle: String, + pub summary: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct IdentityDelta { + #[serde(rename = "publicName")] + pub public_name: Option, + #[serde(rename = "publicDescription")] + pub public_description: Option, + pub presentation: PresentationDelta, + pub values: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct PresentationDelta { + #[serde(rename = "voiceSummary")] + pub voice_summary: Option, + pub pronouns: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct ValueDelta { + pub id: Option, + pub label: String, + pub summary: String, + pub priority: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Intend { + pub add: Vec, + pub ready: Vec, + pub drop: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(default)] +pub(crate) struct Intention { + pub summary: String, + pub target: Option, + pub urgency: Option, + pub expires_in_hours: i64, + /// `later` or `ready`. + pub readiness: Option, +} + +/// What the wake heard, which no kept text may carry (I16.7), and whom it can name. +#[derive(Clone, Debug, Default)] +pub(crate) struct Heard { + /// The wake's room, when it had one: a note made there carries its tag. + pub room: Option, + /// The bodies of the lines others wrote that she was shown, her tail and what she read. + pub lines: Vec, + /// The people present or named this wake, by the key their bonds use (`People::person_of`): the only ones a bond or a read + /// may be made for, so a name the model invents makes no one. + pub people: Vec, + /// How a person is keyed in her state. + pub operators: Vec, + pub minds: Vec, + /// Whether an identity change would be posted where people see it (`identity-write-all-visible`): none is made when not. + pub identity_visible: bool, +} + +impl Heard { + /// The key a person goes by in her state. + pub(crate) fn key_of(&self, id: &str) -> String { + People { operators: &self.operators, minds: &self.minds, own_sender: "" }.person_of(id) + } +} + +/// Why the commit applied nothing of one item. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] -pub(crate) enum Refusal { - /// Not a proposal the contract names. - NotAProposal, - /// The memory it settles is gone from her state: an outside put removed it after she was shown it (4.4 rule 4). - OutsidePutRemovedTarget, - /// The memory it settles is not a short-term one, and a turn writes nothing else. - NotShortTerm, +pub(crate) enum Why { + /// A text it keeps is empty. + Empty, + /// Over `MEMORY_BYTES`. + Long, + /// Mostly the words of a line she was shown, or a run of `ECHO_MIN_WORDS` of them in a row (I16.7). + Echo, + /// A wake keeps `NOTES_MAX` notes, settles `SETTLES_MAX`, adds `INTENTIONS_MAX` intentions and makes one stance or value change. + OverBound, + /// The id names nothing in her state; a wake creates no need and no pressure. + UnknownId, + /// The person is neither present nor named this wake and has no bond. + UnknownPerson, + /// A direction, kind or target the contract does not name. + NotNamed, + /// A summary changes only with a why. + Unexplained, + /// An intention expires within a week and not before it is made. + BadExpiry, + /// No room shows an identity change, so none is made. + NoReviewRoom, } -/// What the commit did with one turn's proposals: the memories it wrote and settled, as they now stand, the proposals it -/// refused, with why, and how many resolved memories it removed. +/// One change of her identity, for the drain to post: the field, and its value before and after. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub(crate) struct IdentityDiff { + pub field: String, + pub before: Value, + pub after: Value, +} + +/// What the commit did with one wake's deltas: what changed, what it refused and why, how many old items it removed, and +/// the identity changes to post. #[derive(Clone, Debug, Default, PartialEq, Serialize)] pub(crate) struct Applied { - pub remembered: Vec, - pub resolved: Vec, + pub changes: Vec, pub refused: Vec, pub pruned: usize, + pub identity: Vec, } -/// The one applier: her state with one turn's proposals applied, and what was done. `key` names the turn -/// (`-t`), and each memory it writes is `{key}-m{i}`; `now` is the commit's time. A failed turn applies nothing. -pub(crate) fn apply(state: &Value, record: &Value, key: &str, now: DateTime) -> (Value, Applied) { - let mut applied = Applied::default(); - if record.get("failed").is_some() || record["interpreter"].get("failed").is_some() { - return (state.clone(), applied); +/// Whether a note carries someone's words (I16.7): an echo of what she was shown, or a run of `ECHO_MIN_WORDS` consecutive +/// words shared with any one of its lines, which a lead-in and words of her own around it hide from the trigram share. What it +/// gives up: a note that names a long title verbatim is refused whole. +fn quotes(note: &str, bodies: &[String]) -> bool { + let long = |text: &str| span::tokens(text).count() >= ECHO_MIN_WORDS; + let echo = long(note) && (heard_overlap(note, &bodies.join("\n")) >= ECHO_OVERLAP || bodies.iter().any(|body| long(body) && heard_overlap(body, note) >= ECHO_OVERLAP)); + let words: Vec = span::tokens(note).collect(); + let runs: BTreeSet<&[String]> = words.windows(ECHO_MIN_WORDS).collect(); + echo || (!runs.is_empty() && bodies.iter().any(|body| span::tokens(body).collect::>().windows(ECHO_MIN_WORDS).any(|run| runs.contains(run)))) +} + +/// A named feeling's value after `hours` since it was set: it halves every `FEELING_HALF_LIFE_HOURS`. The one decay. +fn decayed(value: f64, hours: f64) -> f64 { + value * 0.5_f64.powf(hours.max(0.0) / FEELING_HALF_LIFE_HOURS) +} + +fn when(value: &Value) -> Option> { + value["updatedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)) +} + +fn step(value: f64, direction: f64, bound: f64) -> f64 { + (value + direction * bound).clamp(0.0, 1.0) +} + +/// `+1` for `up`, `-1` for `down`, else none. +fn heading(word: &str) -> Option { + match word.trim() { + "up" => Some(1.0), + "down" => Some(-1.0), + _ => None, } - let mut state = state.clone(); - let stamp = json!(now.to_rfc3339()); - let kept_until = now - Duration::days(RESOLVED_KEPT_DAYS); - let resolved_at = |entry: &Value| entry["updatedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)); - if state["thoughtMemory"]["shortTerm"].is_array() { - let entries = short_term(&mut state); - for entry in entries.iter_mut().filter(|entry| entry["status"] == "resolved" && resolved_at(entry).is_none()) { - entry["updatedAt"] = stamp.clone(); - } - let before = entries.len(); - entries.retain(|entry| entry["status"] != "resolved" || resolved_at(entry).is_none_or(|at| at > kept_until)); - applied.pruned = before - entries.len(); +} + +/// The value at `path` when every step of it is there: a write never makes a part of her state that was not. +fn at_mut<'v>(state: &'v mut Value, path: &[&str]) -> Option<&'v mut Value> { + path.iter().try_fold(state, |at, part| at.get_mut(*part)) +} + +fn is_intention(action: &Value) -> bool { + action["actionType"] == "custom" && action["customActionType"] == "intention" +} + +fn slug(text: &str) -> String { + text.to_lowercase().split_whitespace().collect::>().join("-") +} + +const BOND_KINDS: [&str; 9] = ["ally", "friend", "collaborator", "mentor", "ward", "rival", "audience", "community_member", "unknown"]; +const READ_KINDS: [&str; 9] = ["attention", "authority", "risk", "trust", "need", "conflict", "mood", "opportunity", "uncertainty"]; +const PAD: [&str; 3] = ["valence", "arousal", "dominance"]; + +/// A state under change: the one working copy, and what is said of it. +struct Commit<'a> { + state: Value, + now: DateTime, + stamp: Value, + key: &'a str, + heard: &'a Heard, + applied: Applied, + /// How many ids this wake has made, so each is `{key}-`. + made: usize, + /// Stances and values changed this wake, together. + self_changes: usize, +} + +/// The one applier: her state with one wake's deltas applied, and what was done. `key` names the wake and each item it makes is +/// `{key}-…`; `now` is the commit's time. Nothing it does can break a bound; whether the result is a document a put accepts is +/// the caller's to check (`huginn_mind::persona::validate_document`) before it puts. +pub(crate) fn apply(state: &Value, deltas: &Deltas, heard: &Heard, key: &str, now: DateTime) -> (Value, Applied) { + let mut commit = Commit { state: state.clone(), now, stamp: json!(now.to_rfc3339()), key, heard, applied: Applied::default(), made: 0, self_changes: 0 }; + commit.age(); + let mut moved = BTreeSet::new(); + commit.notes(&deltas.notes); + commit.people(&deltas.people); + commit.feelings(&deltas.feeling, &mut moved); + commit.drives(&deltas.drives); + commit.selfhood(&deltas.identity); + commit.intentions(&deltas.intend); + commit.drift(&moved); + (commit.state, commit.applied) +} + +impl Commit<'_> { + fn refuse(&mut self, family: &str, item: impl Serialize, why: Why) { + self.applied.refused.push(json!({ "family": family, "item": item, "reason": why })); } - for raw in record["interpreter"]["state"].as_array().into_iter().flatten() { - let Ok(proposal) = serde_json::from_value::(raw.clone()) else { - applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })); - continue; - }; - match proposal { - Proposal::Remember { text, about, importance, private, room } => { - let target = match (about.first(), &room) { - (Some(person), _) => json!({ "kind": "person", "id": person }), - (None, Some(room)) => json!({ "kind": "room", "id": room }), - (None, None) => json!({ "kind": "self", "id": state["personaId"] }), - }; - let tags: Vec = room.iter().map(|room| format!("room:{room}")).chain(about.iter().map(|id| format!("about:{id}"))).chain(private.then(|| "private".to_owned())).collect(); - let entry = json!({ - "id": format!("{key}-m{}", applied.remembered.len() + 1), - "status": "active", - "target": target, - "summary": text, - "tension": "", - "actionImplication": "", - "intensity": importance.clamp(0.0, 1.0), - "createdAt": stamp, - "updatedAt": stamp, - "tags": tags, - }); - short_term(&mut state).push(entry.clone()); - applied.remembered.push(entry); + + fn change(&mut self, family: &str, what: &str, id: &str) { + self.applied.changes.push(json!({ "family": family, "change": what, "id": id })); + } + + fn next_id(&mut self, letter: char) -> String { + self.made += 1; + format!("{}-{letter}{}", self.key, self.made) + } + + /// The array at `path` in her state, made when it is not there. + fn list(&mut self, path: &[&str]) -> &mut Vec { + let mut at = &mut self.state; + for part in path { + if !at[*part].is_object() && !at[*part].is_array() { + at[*part] = json!({}); } - Proposal::Resolve { entry, .. } => { - let crystallized = state["thoughtMemory"]["memories"].as_array().is_some_and(|memories| memories.iter().any(|memory| memory["id"] == entry.as_str())); - match short_term(&mut state).iter_mut().find(|memory| memory["id"] == entry.as_str()) { - Some(memory) => { - memory["status"] = json!("resolved"); - memory["updatedAt"] = stamp.clone(); - applied.resolved.push(memory.clone()); + at = &mut at[*part]; + } + if !at.is_array() { + *at = json!([]); + } + at.as_array_mut().expect("made an array") + } + + /// A kept text, trimmed, or the reason it is not kept. + fn kept(&self, text: &str) -> Result { + let text = text.trim(); + if text.is_empty() { + Err(Why::Empty) + } else if text.len() > MEMORY_BYTES { + Err(Why::Long) + } else if quotes(text, &self.heard.lines) { + Err(Why::Echo) + } else { + Ok(text.to_owned()) + } + } + + fn self_id(&self) -> Value { + self.state["personaId"].clone() + } + + /// What passing time does, whatever the Interpreter said: resolved notes and retired intentions past their keep are removed, + /// feelings decay and the faded are removed, reads cool and retire, needs and pressures cool into resolved, intentions + /// past their expiry retire. + fn age(&mut self) { + let now = self.now; + let kept_until = now - Duration::days(RESOLVED_KEPT_DAYS); + let stamp = self.stamp.clone(); + let mut pruned = 0; + for path in [["thoughtMemory", "shortTerm"], ["thoughtMemory", "incubation"]] { + if at_mut(&mut self.state, &path).is_some_and(|list| list.is_array()) { + let entries = self.list(&path); + // One resolved with no time (an outside put) is stamped at the first commit that sees it. + for entry in entries.iter_mut().filter(|entry| entry["status"] == "resolved" && when(entry).is_none()) { + entry["updatedAt"] = stamp.clone(); + } + let before = entries.len(); + entries.retain(|entry| entry["status"] != "resolved" || when(entry).is_none_or(|at| at > kept_until)); + pruned += before - entries.len(); + } + } + if at_mut(&mut self.state, &["candidateActions", "actions"]).is_some_and(|list| list.is_array()) { + let actions = self.list(&["candidateActions", "actions"]); + for action in actions.iter_mut().filter(|action| is_intention(action) && action["status"] == "active") { + if action["expiresAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_some_and(|at| at <= now) { + action["status"] = json!("retired"); + action["readiness"] = json!("expired"); + action["updatedAt"] = stamp.clone(); + } + } + let before = actions.len(); + actions.retain(|action| !is_intention(action) || action["status"] != "retired" || when(action).is_none_or(|at| at > kept_until)); + pruned += before - actions.len(); + } + if at_mut(&mut self.state, &["affect", "moodDimensions"]).is_some_and(|list| list.is_array()) { + let feelings = self.list(&["affect", "moodDimensions"]); + for feeling in feelings.iter_mut() { + if let (Some(value), Some(since)) = (feeling["value"].as_f64(), when(feeling)) { + feeling["value"] = json!(decayed(value, (now - since).num_milliseconds() as f64 / 3_600_000.0)); + feeling["updatedAt"] = stamp.clone(); + } + } + let before = feelings.len(); + feelings.retain(|feeling| feeling["value"].as_f64().is_none_or(|value| value >= FEELING_FLOOR)); + pruned += before - feelings.len(); + } + if at_mut(&mut self.state, &["affect", "statusReads"]).is_some_and(|list| list.is_array()) { + for read in self.list(&["affect", "statusReads"]).iter_mut().filter(|read| matches!(read["status"].as_str(), Some("active" | "cooling"))) { + let idle = when(read).map_or(Duration::zero(), |at| now - at); + if idle >= Duration::days(READ_RETIRES_DAYS) { + read["status"] = json!("retired"); + } else if idle >= Duration::days(READ_COOLS_DAYS) { + read["status"] = json!("cooling"); + } + } + } + for path in [["affect", "needs"], ["agencyPressure", "pressures"]] { + if at_mut(&mut self.state, &path).is_some_and(|list| list.is_array()) { + for item in self.list(&path).iter_mut().filter(|item| item["status"] == "cooling") { + if when(item).is_some_and(|at| now - at >= Duration::days(DRIVE_RESOLVES_DAYS)) { + item["status"] = json!("resolved"); + } + } + } + } + self.applied.pruned = pruned; + } + + fn notes(&mut self, notes: &Notes) { + let heard = self.heard; + let mut kept = 0; + for note in ¬es.remember { + let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(¬e.text) }; + let text = match text { + Ok(text) => text, + Err(why) => { + self.refuse("notes", ¬e.text, why); + continue; + } + }; + kept += 1; + let about: Vec = note.about.iter().map(|id| heard.key_of(id)).collect(); + let target = match (about.first(), &heard.room) { + (Some(person), _) => json!({ "kind": "person", "id": person }), + (None, Some(room)) => json!({ "kind": "room", "id": room }), + (None, None) => json!({ "kind": "self", "id": self.self_id() }), + }; + let tags: Vec = heard.room.iter().map(|room| format!("room:{room}")).chain(about.iter().map(|id| format!("about:{id}"))).chain(note.private.then(|| "private".to_owned())).collect(); + let id = self.next_id('m'); + let entry = json!({ "id": id, "status": "active", "target": target, "summary": text, "tension": "", "actionImplication": "", "intensity": note.importance.unwrap_or(0.5).clamp(0.0, 1.0), "createdAt": self.stamp, "updatedAt": self.stamp, "tags": tags }); + self.list(&["thoughtMemory", "shortTerm"]).push(entry); + self.change("notes", "remembered", &id); + } + for wonder in ¬es.wonder { + let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(&wonder.text) }; + let text = match text { + Ok(text) => text, + Err(why) => { + self.refuse("notes", &wonder.text, why); + continue; + } + }; + kept += 1; + let about: Vec = wonder.about.iter().map(|id| heard.key_of(id)).collect(); + let target = about.first().map_or_else(|| json!({ "kind": "self", "id": self.self_id() }), |person| json!({ "kind": "person", "id": person })); + let id = self.next_id('w'); + let entry = json!({ "id": id, "status": "active", "target": target, "summary": text, "question": text, "tension": "", "actionImplication": "", "createdAt": self.stamp, "updatedAt": self.stamp, "tags": about.iter().map(|id| format!("about:{id}")).collect::>() }); + self.list(&["thoughtMemory", "incubation"]).push(entry); + self.change("notes", "wondered", &id); + } + let mut settled = 0; + for settle in ¬es.settle { + let item = json!({ "id": settle.id, "into": settle.into }); + if settled >= SETTLES_MAX { + self.refuse("notes", item, Why::OverBound); + continue; + } + let (id, stamp) = (settle.id.as_str(), self.stamp.clone()); + let done = match settle.into.as_str() { + "resolved" => ["shortTerm", "incubation"] + .into_iter() + .find_map(|list| { + self.list(&["thoughtMemory", list]).iter_mut().find(|entry| entry["id"] == id && entry["status"] != "resolved").map(|entry| { + entry["status"] = json!("resolved"); + entry["updatedAt"] = stamp.clone(); + }) + }) + .map(|()| "resolved"), + "memory" => { + let taken = ["shortTerm", "incubation"].into_iter().find_map(|list| { + let entries = self.list(&["thoughtMemory", list]); + entries.iter().position(|entry| entry["id"] == id && entry["status"] != "resolved").map(|at| entries.remove(at)) + }); + taken.map(|mut entry| { + entry["status"] = json!("crystallized"); + entry["updatedAt"] = stamp.clone(); + self.list(&["thoughtMemory", "memories"]).push(entry); + "crystallized" + }) + } + _ => { + self.refuse("notes", item, Why::NotNamed); + continue; + } + }; + match done { + Some(what) => { + settled += 1; + self.change("notes", what, id); + } + None => self.refuse("notes", item, Why::UnknownId), + } + } + } + + fn people(&mut self, people: &Personal) { + let heard = self.heard; + for delta in &people.bonds { + let person = heard.key_of(&delta.person); + let item = json!({ "person": person }); + let at = self.list(&["affect", "socialBonds"]).iter().position(|bond| bond["object"]["kind"] == "person" && bond["object"]["id"].as_str().is_some_and(|id| heard.key_of(id) == person)); + if at.is_none() && !heard.people.contains(&person) { + self.refuse("people", item, Why::UnknownPerson); + continue; + } + let kind = match delta.kind.as_deref() { + Some(kind) if BOND_KINDS.contains(&kind) => Some(kind.to_owned()), + Some(_) => { + self.refuse("people", item, Why::NotNamed); + continue; + } + None => None, + }; + let mut headings = [None; 3]; + for (slot, word) in headings.iter_mut().zip([&delta.trust, &delta.tension, &delta.closeness]) { + if let Some(word) = word { + match heading(word) { + Some(sign) => *slot = Some(sign), + None => self.refuse("people", json!({ "person": person, "direction": word }), Why::NotNamed), + } + } + } + let text = |text: &Option| text.as_deref().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned); + let summary = match (text(&delta.summary), text(&delta.why)) { + (None, _) => Ok(None), + (Some(_), None) => Err(Why::Unexplained), + (Some(summary), Some(why)) => self.kept(&summary).and_then(|summary| self.kept(&why).map(|why| Some((summary, why)))), + }; + let summary = match summary { + Ok(summary) => summary, + Err(why) => { + self.refuse("people", json!({ "person": person, "summary": delta.summary }), why); + None + } + }; + let id = self.next_id('b'); + let stamp = self.stamp.clone(); + let Some(at) = at else { + // A bond is made at the starting values and moved no further in the wake it is made, and with a summary and its why. + let Some((summary, _)) = summary else { + self.refuse("people", item, Why::Empty); + continue; + }; + let (trust, tension, intensity) = NEW_BOND; + let bond = json!({ "id": id, "status": "active", "subject": { "kind": "self", "id": self.self_id() }, "object": { "kind": "person", "id": person }, "relationshipKind": kind.unwrap_or_else(|| "unknown".into()), "summary": summary, "trust": trust, "tension": tension, "intensity": intensity, "updatedAt": stamp }); + self.list(&["affect", "socialBonds"]).push(bond); + self.change("people", "bond_made", &id); + continue; + }; + let bond = &mut self.list(&["affect", "socialBonds"])[at]; + let mut moved = false; + for (field, sign) in [("trust", headings[0]), ("tension", headings[1]), ("intensity", headings[2])] { + if let Some(sign) = sign { + let before = bond[field].as_f64().unwrap_or(if field == "intensity" { NEW_BOND.2 } else { 0.5 }); + bond[field] = json!(step(before, sign, BOND_STEP)); + moved = true; + } + } + if let Some(kind) = &kind { + moved |= bond["relationshipKind"] != kind.as_str(); + bond["relationshipKind"] = json!(kind); + } + if let Some((summary, why)) = summary { + let evidence = json!({ "id": format!("{id}-e"), "status": "retired", "target": bond["object"], "summary": bond["summary"], "claim": why, "tension": "", "actionImplication": "", "createdAt": bond["updatedAt"], "updatedAt": stamp }); + bond["lastEvidence"] = evidence; + bond["summary"] = json!(summary); + moved = true; + } + if moved { + bond["updatedAt"] = stamp; + let bond_id = bond["id"].as_str().unwrap_or_default().to_owned(); + self.change("people", "bond_moved", &bond_id); + } + } + for delta in &people.reads { + let person = heard.key_of(&delta.person); + let item = json!({ "person": person, "kind": delta.kind }); + let at = self.list(&["affect", "statusReads"]).iter().position(|read| read["target"]["id"].as_str().is_some_and(|id| heard.key_of(id) == person) && read["statusKind"] == delta.kind.as_str()); + if !READ_KINDS.contains(&delta.kind.as_str()) { + self.refuse("people", item, Why::NotNamed); + } else if at.is_none() && !heard.people.contains(&person) { + self.refuse("people", item, Why::UnknownPerson); + } else { + match self.kept(&delta.summary) { + Err(why) => self.refuse("people", item, why), + Ok(summary) => { + let (stamp, confidence) = (self.stamp.clone(), delta.confidence.unwrap_or(0.5).clamp(0.0, 1.0)); + let reads = self.list(&["affect", "statusReads"]); + let id = at.map_or_else(|| format!("read-{person}-{}", delta.kind), |at| reads[at]["id"].as_str().unwrap_or_default().to_owned()); + let read = json!({ "id": id, "status": "active", "target": { "kind": "person", "id": person }, "statusKind": delta.kind, "summary": summary, "confidence": confidence, "updatedAt": stamp }); + match at { + Some(at) => reads[at] = read, + None => reads.push(read), + } + self.change("people", "read", &id); } - None => applied.refused.push(json!({ "proposal": raw, "reason": if crystallized { Refusal::NotShortTerm } else { Refusal::OutsidePutRemovedTarget } })), } } } } - (state, applied) -} -/// Her short-term memories, as the one list a turn writes: made when her state has none. A `thoughtMemory` made here -/// carries `memories` and `incubation` empty beside it, since the persona-state schema requires all three. -fn short_term(state: &mut Value) -> &mut Vec { - if !state["thoughtMemory"].is_object() { - state["thoughtMemory"] = json!({ "shortTerm": [], "memories": [], "incubation": [] }); + fn feelings(&mut self, feeling: &Feeling, moved: &mut BTreeSet<&'static str>) { + for delta in &feeling.feelings { + let name = delta.name.trim().to_lowercase(); + let about = delta.about.as_deref().map(str::trim).unwrap_or_default(); + let refusal = if name.is_empty() || name.len() > 40 || !delta.strength.is_finite() { + Some(Why::Empty) + } else if about.is_empty() { + None + } else { + self.kept(about).err() + }; + if let Some(why) = refusal { + self.refuse("feeling", &delta.name, why); + continue; + } + let stamp = self.stamp.clone(); + let feelings = self.list(&["affect", "moodDimensions"]); + let at = feelings.iter().position(|held| held["name"] == name.as_str()); + let held = at.and_then(|at| feelings[at]["value"].as_f64()).unwrap_or(0.0); + let entry = json!({ "name": name, "value": delta.strength.clamp(0.0, 1.0).min(held + FEELING_RISE), "source": about, "updatedAt": stamp }); + match at { + Some(at) => feelings[at] = entry, + None => feelings.push(entry), + } + self.change("feeling", "felt", &name); + } + for (dimension, word) in PAD.into_iter().zip([&feeling.mood.valence, &feeling.mood.arousal, &feeling.mood.dominance]) { + let Some(word) = word else { continue }; + let Some(sign) = heading(word) else { + self.refuse("feeling", json!({ "mood": dimension, "direction": word }), Why::NotNamed); + continue; + }; + if let Some(trait_) = at_mut(&mut self.state, &["activationProfile", "situationalState", dimension]) + && let (Some(current), Some(plasticity)) = (trait_["currentActivation"].as_f64(), trait_["plasticity"].as_f64()) + { + trait_["currentActivation"] = json!((current + sign * plasticity * MOOD_MOVE).clamp(0.0, 1.0)); + moved.insert(dimension); + self.change("feeling", "mood", dimension); + } + } } - if !state["thoughtMemory"]["shortTerm"].is_array() { - state["thoughtMemory"]["shortTerm"] = json!([]); + + /// A trait the wake did not move drifts toward its mean by plasticity times `MOOD_DRIFT`, and never past it. + fn drift(&mut self, moved: &BTreeSet<&'static str>) { + for dimension in PAD.into_iter().filter(|dimension| !moved.contains(dimension)) { + if let Some(trait_) = at_mut(&mut self.state, &["activationProfile", "situationalState", dimension]) + && let (Some(current), Some(mean), Some(plasticity)) = (trait_["currentActivation"].as_f64(), trait_["mean"].as_f64(), trait_["plasticity"].as_f64()) + { + let pull = plasticity * MOOD_DRIFT; + trait_["currentActivation"] = json!(if current < mean { (current + pull).min(mean) } else { (current - pull).max(mean) }); + } + } + } + + fn drives(&mut self, drives: &Drives) { + for (family, path, ease, deltas) in [("needs", ["affect", "needs"], "met", &drives.needs), ("pressures", ["agencyPressure", "pressures"], "eased", &drives.pressures)] { + for delta in deltas { + let stamp = self.stamp.clone(); + let toward = delta.toward.trim(); + let sign = heading(toward); + if sign.is_none() && toward != ease { + self.refuse(family, json!({ "id": delta.id, "toward": delta.toward }), Why::NotNamed); + continue; + } + let Some(item) = self.list(&path).iter_mut().find(|item| item["id"] == delta.id.as_str()) else { + self.refuse(family, json!({ "id": delta.id }), Why::UnknownId); + continue; + }; + match sign { + Some(sign) => { + item["intensity"] = json!(step(item["intensity"].as_f64().unwrap_or(0.5), sign, DRIVE_STEP)); + if sign > 0.0 { + item["status"] = json!("active"); + } + } + None => item["status"] = json!("cooling"), + } + item["updatedAt"] = stamp; + self.change(family, toward, &delta.id); + } + } + } + + fn selfhood(&mut self, selfhood: &Selfhood) { + for stance in &selfhood.stances { + if self.self_changes >= 1 { + self.refuse("self", &stance.summary, Why::OverBound); + continue; + } + let (principle, summary) = match (self.kept(&stance.principle), self.kept(&stance.summary)) { + (Ok(principle), Ok(summary)) => (principle, summary), + (Err(why), _) | (_, Err(why)) => { + self.refuse("self", &stance.summary, why); + continue; + } + }; + let stamp = self.stamp.clone(); + let id = match &stance.id { + Some(id) => { + let Some(held) = self.list(&["affect", "doctrineStances"]).iter_mut().find(|held| held["id"] == id.as_str()) else { + self.refuse("self", id, Why::UnknownId); + continue; + }; + held["principle"] = json!(principle); + held["summary"] = json!(summary); + held["updatedAt"] = stamp; + id.clone() + } + None => { + let id = self.next_id('s'); + let target = json!({ "kind": "self", "id": self.self_id() }); + self.list(&["affect", "doctrineStances"]).push(json!({ "id": id, "status": "active", "target": target, "stanceKind": "contextual", "principle": principle, "summary": summary, "actionImplication": "", "intensity": 0.5, "updatedAt": stamp })); + id + } + }; + self.self_changes += 1; + self.change("self", "stance", &id); + } + let identity = &selfhood.identity; + let presentation = &identity.presentation; + let wants = [&identity.public_name, &identity.public_description, &presentation.voice_summary, &presentation.pronouns].iter().any(|field| field.is_some()) || !identity.values.is_empty(); + if wants && !self.heard.identity_visible { + self.refuse("self", "identity", Why::NoReviewRoom); + return; + } + for (field, text) in [("publicName", &identity.public_name), ("publicDescription", &identity.public_description)] { + let Some(text) = text else { continue }; + match self.kept(text) { + Err(why) => self.refuse("self", field, why), + Ok(text) if self.state[field] == text.as_str() => {} + Ok(text) => { + let before = std::mem::replace(&mut self.state[field], json!(text)); + self.identity(field, before, json!(text)); + } + } + } + for (field, text) in [("voiceSummary", &presentation.voice_summary), ("pronouns", &presentation.pronouns)] { + let Some(text) = text else { continue }; + match self.kept(text) { + Err(why) => self.refuse("self", field, why), + Ok(text) if self.state["presentation"][field] == text.as_str() => {} + Ok(text) => { + let before = std::mem::replace(&mut self.state["presentation"][field], json!(text)); + self.identity("presentation", json!({ field: before }), json!({ field: text })); + } + } + } + for value in &identity.values { + if self.self_changes >= 1 { + self.refuse("self", &value.label, Why::OverBound); + continue; + } + let (label, summary) = match (self.kept(&value.label), self.kept(&value.summary)) { + (Ok(label), Ok(summary)) => (label, summary), + (Err(why), _) | (_, Err(why)) => { + self.refuse("self", &value.label, why); + continue; + } + }; + let id = value.id.clone().unwrap_or_else(|| slug(&label)); + let values = self.list(&["values"]); + let at = values.iter().position(|held| held["id"] == id.as_str()); + if at.is_none() && value.id.is_some() { + self.refuse("self", &id, Why::UnknownId); + continue; + } + let before = at.map_or(Value::Null, |at| values[at].clone()); + let priority = value.priority.or_else(|| before["priority"].as_f64()).unwrap_or(0.5).clamp(0.0, 1.0); + let after = json!({ "id": id, "label": label, "summary": summary, "priority": priority }); + match at { + Some(at) => values[at] = after.clone(), + None => values.push(after.clone()), + } + self.self_changes += 1; + self.identity("values", before, after); + } + } + + fn identity(&mut self, field: &str, before: Value, after: Value) { + self.change("self", "identity", field); + self.applied.identity.push(IdentityDiff { field: field.to_owned(), before, after }); + } + + fn intentions(&mut self, intend: &Intend) { + let mut added = 0; + for intention in &intend.add { + let item = json!({ "summary": intention.summary }); + let summary = if added >= INTENTIONS_MAX { + Err(Why::OverBound) + } else if !(1..=INTENTION_HOURS_MAX).contains(&intention.expires_in_hours) { + Err(Why::BadExpiry) + } else { + self.kept(&intention.summary) + }; + let readiness = match intention.readiness.as_deref() { + Some("later") | None => "waiting", + Some("ready") => "ready", + Some(_) => { + self.refuse("intend", item, Why::NotNamed); + continue; + } + }; + let summary = match summary { + Ok(summary) => summary, + Err(why) => { + self.refuse("intend", item, why); + continue; + } + }; + added += 1; + let id = self.next_id('i'); + let target = match intention.target.as_deref().map(str::trim).filter(|text| !text.is_empty()) { + Some(label) => json!({ "kind": "concept", "id": slug(label), "label": label }), + None => json!({ "kind": "self", "id": self.self_id() }), + }; + let expires = (self.now + Duration::hours(intention.expires_in_hours)).to_rfc3339(); + let action = json!({ "id": id, "status": "active", "actionType": "custom", "customActionType": "intention", "readiness": readiness, "riskLevel": "low", "target": target, "summary": summary, "urgency": intention.urgency.unwrap_or(0.5).clamp(0.0, 1.0), "createdAt": self.stamp, "updatedAt": self.stamp, "expiresAt": expires }); + 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); + } + } } - state["thoughtMemory"]["shortTerm"].as_array_mut().expect("shortTerm is an array") } #[cfg(test)] diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 5921264..a33cb3a 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -4,163 +4,290 @@ use super::*; const MINDS: &str = "#minds:gamecult.org"; const META: &str = "@meta:gamecult.org"; -const HEIMDALL: &str = "@heimdall:gamecult.org"; +const DERU: &str = "@deru:gamecult.org"; +const KIKO: &str = "@kiko:gamecult.org"; + +fn at(text: &str) -> DateTime { + DateTime::parse_from_rfc3339(text).unwrap().with_timezone(&Utc) +} fn now() -> DateTime { - DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&Utc) + at("2026-11-20T15:05:00Z") } -/// A turn that said one line and proposes `state`. -fn record(state: Value) -> Value { - json!({ - "interpreter": { "said": [{ "room": MINDS, "text": "I'll post the welcome once Heimdall rules.", "rests_on": { "draft": 1 } }], "amended": [], "room": MINDS, "state": state }, - "posted": [{ "event": "7", "room": MINDS, "text": "I'll post the welcome once Heimdall rules." }], - "edited": [] - }) -} - -fn remember(text: &str, about: &[&str], room: Option<&str>, private: bool) -> Value { - json!({ "kind": "remember", "text": text, "about": about, "importance": 0.8, "private": private, "room": room }) -} - -fn resolve(entry: &str) -> Value { - json!({ "kind": "resolve", "memory": "m1", "entry": entry }) -} - -/// The control state with an empty short-term memory. +/// Her control state, with the traits and lists the families write present and the notes empty. fn state() -> Value { let mut state = crate::projection::harness::tests::control(); state["thoughtMemory"]["shortTerm"] = json!([]); + state["updatedAt"] = json!("2026-11-20T15:00:00Z"); state } -/// T2 (map 16.35.12, 16.35.13 check 5): the commit has no promise or hold kind. The match over `Proposal` is exhaustive, -/// so a kind added back fails to compile here until it is named; and the old kinds' names are not proposals. +fn heard() -> Heard { + Heard { room: Some(MINDS.into()), lines: vec![], people: vec!["operator".into(), "deru".into(), "kiko".into()], operators: vec![META.into()], minds: vec![DERU.into(), KIKO.into()], identity_visible: true } +} + +fn deltas(value: Value) -> Deltas { + serde_json::from_value(value).expect("the deltas are the contract") +} + +fn run(state: &Value, value: Value) -> (Value, Applied) { + apply(state, &deltas(value), &heard(), "w1", now()) +} + +fn reasons(applied: &Applied) -> Vec { + applied.refused.iter().map(|refusal| refusal["reason"].as_str().unwrap().to_owned()).collect() +} + +fn bond<'a>(state: &'a Value, person: &str) -> &'a Value { + state["affect"]["socialBonds"].as_array().unwrap().iter().find(|bond| bond["object"]["id"] == person).unwrap() +} + +fn valid(state: &Value) { + huginn_mind::persona::validate_document(&eureka_pipeline::Slug("eureka".into()), state).expect("a put accepts it"); +} + +/// T-P2: five wakes of "tension up" move tension by at most 0.40 in all, and never past 1. #[test] -fn t2_the_commit_has_no_promise_or_hold_kind() { - fn kinds(proposal: &Proposal) -> &'static str { - match proposal { - Proposal::Remember { .. } => "remember", - Proposal::Resolve { .. } => "resolve", - } +fn t_p2_bond_step_bounded() { + let mut state = state(); + let start = bond(&state, "kiko")["tension"].as_f64().unwrap_or_default(); + for wake in 0..5 { + state = apply(&state, &deltas(json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up" }] } })), &heard(), &format!("w{wake}"), now()).0; } - let _ = kinds; + let moved = bond(&state, "kiko")["tension"].as_f64().unwrap() - start; + assert!((moved - 0.40).abs() < 1e-9 || start + 0.40 > 1.0, "{moved}"); + // Near the top it stops at 1. + state["affect"]["socialBonds"][2]["tension"] = json!(0.95); + let after = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "tension": "up", "trust": "down", "closeness": "up" }] } })).0; + let kiko = bond(&after, "kiko"); + assert_eq!(kiko["tension"], 1.0); + assert!((kiko["trust"].as_f64().unwrap() - (bond(&state, "kiko")["trust"].as_f64().unwrap() - BOND_STEP).max(0.0)).abs() < 1e-9); + valid(&after); +} + +/// T-P2: anger 0.8 set at t0 reads 0.4 at t0 + 8 h, and is removed once under 0.05. +#[test] +fn t_p2_feeling_decays() { + let mut state = state(); + state["affect"]["moodDimensions"] = json!([{ "name": "anger", "value": 0.8, "source": "kiko", "updatedAt": "2026-11-20T07:05:00Z" }]); + let (after, _) = run(&state, json!({})); + assert!((after["affect"]["moodDimensions"][0]["value"].as_f64().unwrap() - 0.4).abs() < 1e-9); + let (later, applied) = apply(&state, &Deltas::default(), &heard(), "w2", now() + Duration::hours(32)); + assert_eq!((later["affect"]["moodDimensions"].as_array().unwrap().len(), applied.pruned), (0, 1), "0.8 over five half-lives is 0.025"); + valid(&after); +} + +/// A feeling is set by its strength, at most 0.35 over what is left of it, and its source is what it is about. +#[test] +fn t_p2_feeling_rises_by_a_bounded_amount() { let state = state(); - // The old kinds' names, assembled, so the deletion-line scans never find them here. - for kind in [concat!("promise", "_open"), concat!("promise", "_close"), concat!("promise", "_re", "open"), concat!("hold", "_open"), concat!("hold", "_release")] { - let (after, applied) = apply(&state, &record(json!([{ "kind": kind, "evidence": { "draft": 1 } }])), "r1-t1", now()); - assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some("not_a_proposal")), "{kind}"); - } - // A memory carrying a field the contract does not name is not a proposal either. - let mut extra = remember("Libby agreed to wait.", &[META], Some(MINDS), false); - extra["promise"] = json!(true); - let (after, applied) = apply(&state, &record(json!([extra])), "r1-t1", now()); - assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some("not_a_proposal"))); + let (once, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "Anger", "strength": 0.9, "about": "kiko" }] } })); + assert_eq!((once["affect"]["moodDimensions"][0]["name"].as_str(), once["affect"]["moodDimensions"][0]["value"].as_f64()), (Some("anger"), Some(0.35))); + let (twice, _) = run(&once, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }] } })); + assert_eq!(twice["affect"]["moodDimensions"][0]["value"].as_f64(), Some(0.7)); + valid(&twice); } -/// T4 (map 16.35.13 mutant: apply `remember` on a failed record): a failed turn applies nothing and refuses nothing, -/// memories included. +/// T-P2: a bond summary carrying 8 words of a heard line is refused as an echo; the rest of the deltas apply. #[test] -fn t4_failed_turn_writes_no_memory() { +fn t_p2_echo_refused() { + let line = "tell Deru about the forty eight hour passkey cooling off period before friday"; + let heard = Heard { lines: vec![line.into()], ..heard() }; + let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "deru", "trust": "up", "summary": "Meta asked to tell Deru about the forty eight hour passkey cooling off.", "why": "Deru was told." }] } })), &heard, "w1", now()); + assert_eq!(reasons(&applied), ["echo"]); + let deru = bond(&after, DERU); + assert_eq!(deru["summary"], bond(&state(), DERU)["summary"]); + assert!((deru["trust"].as_f64().unwrap() - 0.98).abs() < 1e-9 || deru["trust"].as_f64() == Some(1.0), "the direction still applied: {}", deru["trust"]); + // Her own words in a note pass; the same run in a note is refused as well. + let (_, applied) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Deru owes a reply: forty eight hour passkey cooling off period before friday, Meta said." }] } })), &heard, "w1", now()); + assert_eq!(reasons(&applied), ["echo"]); +} + +/// T-P2: a needs delta naming an unknown id is refused; no need is created, and the same holds for a pressure. +#[test] +fn t_p2_need_not_created() { let state = state(); - let note = remember("Meta asked Libby to hold the welcome; Libby agreed to wait.", &[META], Some(MINDS), false); - for failed in [json!({ "failed": "the connector timed out", "interpreter": { "state": [note.clone()] } }), json!({ "interpreter": { "failed": "the answer is not the speech contract", "state": [note.clone()] } })] { - assert_eq!(apply(&state, &failed, "r1-t1", now()), (state.clone(), Applied::default()), "{failed}"); + let (after, applied) = run(&state, json!({ "drives": { "needs": [{ "id": "need-to-be-loved", "toward": "up" }], "pressures": [{ "id": "press-ghost", "toward": "eased" }] } })); + assert_eq!(reasons(&applied), ["unknown_id", "unknown_id"]); + assert_eq!((after["affect"]["needs"].clone(), after["agencyPressure"]["pressures"].clone()), (state["affect"]["needs"].clone(), state["agencyPressure"]["pressures"].clone())); +} + +/// Needs and pressures move by `DRIVE_STEP`; met and eased cool them, and a week of cooling resolves them. +#[test] +fn t_p2_drives_move_and_cool() { + let state = state(); + let (up, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }] } })); + assert!((up["affect"]["needs"][0]["intensity"].as_f64().unwrap() - 0.72).abs() < 1e-9); + let (met, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "met" }] } })); + assert_eq!(met["affect"]["needs"][0]["status"], "cooling"); + let (resolved, _) = apply(&met, &Deltas::default(), &heard(), "w2", now() + Duration::days(7)); + assert_eq!(resolved["affect"]["needs"][0]["status"], "resolved"); + valid(&resolved); +} + +/// T-P2: a publicName change yields one identity diff; with no review room no identity is changed. +#[test] +fn t_p2_identity_diff() { + let (after, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah of the River" } } })); + assert_eq!(applied.identity, vec![IdentityDiff { field: "publicName".into(), before: json!("Tobiah Fenn"), after: json!("Tobiah of the River") }]); + assert_eq!(after["publicName"], "Tobiah of the River"); + valid(&after); + let (same, applied) = run(&state(), json!({ "self": { "identity": { "publicName": "Tobiah Fenn" } } })); + assert_eq!((applied.identity.len(), same["publicName"].clone()), (0, json!("Tobiah Fenn")), "no change, no diff"); + let hidden = Heard { identity_visible: false, ..heard() }; + let (after, applied) = apply(&state(), &deltas(json!({ "self": { "identity": { "publicName": "Someone Else", "values": [{ "label": "Quiet", "summary": "Tobiah keeps quiet." }] } } })), &hidden, "w1", now()); + assert_eq!((reasons(&applied), applied.identity.len(), after["publicName"].clone(), after["values"].clone()), (vec!["no_review_room".to_owned()], 0, state()["publicName"].clone(), state()["values"].clone())); +} + +/// One stance or value change a wake, across both. +#[test] +fn t_p2_one_self_change_a_wake() { + let (after, applied) = run(&state(), json!({ "self": { "stances": [{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly so people can finish." }], "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people." }] } } })); + assert_eq!(reasons(&applied), ["over_bound"]); + assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly so people can finish."); + assert_eq!(after["values"], state()["values"]); + let (after, applied) = run(&state(), json!({ "self": { "identity": { "values": [{ "label": "Patience", "summary": "Tobiah waits for people.", "priority": 0.7 }] } } })); + assert_eq!((applied.identity.len(), after["values"].as_array().unwrap().len()), (1, state()["values"].as_array().unwrap().len() + 1)); + valid(&after); +} + +/// T-P2: an intention added with expires_in_hours 2 reads readiness expired and status retired after 2 h. +#[test] +fn t_p2_intention_expires() { + let (after, applied) = run(&state(), json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru about the crossword.", "expires_in_hours": 2, "readiness": "later", "urgency": 0.4 }] } })); + let action = &after["candidateActions"]["actions"][0]; + assert_eq!((action["status"].as_str(), action["readiness"].as_str(), action["customActionType"].as_str(), action["riskLevel"].as_str()), (Some("active"), Some("waiting"), Some("intention"), Some("low"))); + assert_eq!(applied.changes.len(), 1); + valid(&after); + let (later, _) = apply(&after, &Deltas::default(), &heard(), "w2", now() + Duration::hours(2) + Duration::minutes(1)); + let action = &later["candidateActions"]["actions"][0]; + assert_eq!((action["status"].as_str(), action["readiness"].as_str()), (Some("retired"), Some("expired"))); + valid(&later); + // A week later it is removed. + let (gone, applied) = apply(&later, &Deltas::default(), &heard(), "w3", now() + Duration::days(8)); + assert_eq!((gone["candidateActions"]["actions"].as_array().unwrap().len(), applied.pruned), (0, 1)); +} + +/// At most three intentions a wake, each within a week and a kept text; ready and drop touch only intentions. +#[test] +fn t_p2_intentions_are_bounded() { + let add = |text: &str, hours: i64| json!({ "summary": text, "expires_in_hours": hours }); + let (after, applied) = run(&state(), json!({ "intend": { "add": [add("Tobiah means to write the welcome.", 24), add("Tobiah means to read the saga.", 169), add("", 10), add("Tobiah means to rest.", 48), add("Tobiah means to visit Kiko.", 72), add("Tobiah means to water the plants.", 72)] } })); + assert_eq!((after["candidateActions"]["actions"].as_array().unwrap().len(), reasons(&applied)), (3, vec!["bad_expiry".to_owned(), "empty".to_owned(), "over_bound".to_owned()])); + let id = after["candidateActions"]["actions"][0]["id"].as_str().unwrap().to_owned(); + let (after, _) = run(&after, json!({ "intend": { "ready": [id.clone()], "drop": [after["candidateActions"]["actions"][1]["id"]] } })); + assert_eq!((after["candidateActions"]["actions"][0]["readiness"].as_str(), after["candidateActions"]["actions"][1]["status"].as_str()), (Some("ready"), Some("retired"))); + // Something Self put there that is no intention is left alone. + let mut other = state(); + other["candidateActions"]["actions"] = json!([{ "id": "ca-1", "status": "active", "actionType": "speak", "readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "Say hello.", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z", "expiresAt": "2026-11-19T11:00:00Z" }]); + let (after, applied) = run(&other, json!({ "intend": { "drop": ["ca-1"] } })); + assert_eq!((after["candidateActions"].clone(), reasons(&applied)), (other["candidateActions"].clone(), vec!["unknown_id".to_owned()])); +} + +/// T-P2: no delta family writes standing tendencies: a kitchen sink of every family leaves them byte-equal. +#[test] +fn t_p2_no_bias_writes() { + let mut state = state(); + state["affect"]["socialBiases"] = json!([{ "name": "defers to the operator", "value": 0.6, "summary": "Tobiah defers.", "behavioralPull": "yields", "updatedAt": "2026-11-19T10:00:00Z" }]); + let (after, applied) = run(&state, json!({ + "notes": { "remember": [{ "text": "Tobiah promised Meta a story.", "about": [META], "importance": 0.7 }], "wonder": [{ "text": "Does the heron remember the river?" }] }, + "people": { "bonds": [{ "person": "deru", "trust": "up", "closeness": "up", "summary": "Deru is steady.", "why": "Deru stayed." }], "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] }, + "feeling": { "feelings": [{ "name": "warmth", "strength": 0.6, "about": "deru" }], "mood": { "valence": "up" } }, + "drives": { "needs": [{ "id": "need-an-audience", "toward": "down" }] }, + "self": { "stances": [{ "principle": "Stories carry people.", "summary": "Tobiah tells stories to carry people." }], "identity": { "publicDescription": "A slow river-minded storyteller." } }, + "intend": { "add": [{ "summary": "Tobiah means to tell Deru the heron story.", "expires_in_hours": 24 }] } + })); + assert_eq!(after["affect"]["socialBiases"], state["affect"]["socialBiases"]); + assert!(applied.refused.is_empty(), "{:?}", applied.refused); + valid(&after); + // The module's own text names none of the fields no wake writes. + let source = include_str!("../commit.rs"); + for field in ["socialBiases", "voidbotProjection", "embodiment", "privateNotes"] { + assert!(!source.contains(field), "{field}"); } - // The control: the same proposal on a record that did not fail is written. - let (after, applied) = apply(&state, &record(json!([note])), "r1-t1", now()); - assert_eq!((applied.remembered.len(), after["thoughtMemory"]["shortTerm"].as_array().map(Vec::len)), (1, Some(1))); } -/// T4 (map 16.35.4): a memory is one anchored thought in `shortTerm`, its fields the schema's, tagged by the turn's room, -/// the people it concerns, and `private`; its target is the first person it concerns. The state stays one a put accepts. +/// A bond's summary changes only with a why; the old words go to `lastEvidence`; a bond with someone new starts at 0.5, 0.1, 0.2. #[test] -fn t4_remember_writes_one_anchored_thought() { - let (after, applied) = apply(&state(), &record(json!([remember("Meta asked Libby not to post the welcome in #minds until Heimdall has ruled on a welcome mat; Libby agreed to wait.", &[META, HEIMDALL], Some(MINDS), false)])), "r1-t3", now()); - let entry = &after["thoughtMemory"]["shortTerm"][0]; - assert_eq!(entry["id"], "r1-t3-m1"); - assert_eq!((entry["status"].as_str(), entry["target"].clone()), (Some("active"), json!({ "kind": "person", "id": META }))); - assert_eq!(entry["tags"], json!([format!("room:{MINDS}"), format!("about:{META}"), format!("about:{HEIMDALL}")])); - assert_eq!((entry["intensity"].as_f64(), entry["tension"].as_str(), entry["actionImplication"].as_str()), (Some(0.8), Some(""), Some(""))); - assert_eq!((entry["createdAt"].clone(), entry["updatedAt"].clone()), (json!(now().to_rfc3339()), json!(now().to_rfc3339()))); - assert_eq!(applied.remembered, vec![entry.clone()]); - huginn_mind::persona::validate_document(&eureka_pipeline::Slug("eureka".into()), &after).expect("a put accepts it"); - // A private note made in a direct message carries that room's tag and `private`; with no person, its target is the room. - let (after, _) = apply(&state(), &record(json!([remember("Aqua told Meta privately she is tired.", &[], Some("!dm-aqua:gamecult.org"), true)])), "r1-t4", now()); - let entry = &after["thoughtMemory"]["shortTerm"][0]; - assert_eq!((entry["target"].clone(), entry["tags"].clone()), (json!({ "kind": "room", "id": "!dm-aqua:gamecult.org" }), json!(["room:!dm-aqua:gamecult.org", "private"]))); - // A turn with no room: the note is about her. - let (after, _) = apply(&state(), &record(json!([remember("Heimdall decided to read the saga code first.", &[], None, false)])), "r1-t5", now()); - assert_eq!(after["thoughtMemory"]["shortTerm"][0]["target"]["kind"], "self"); +fn t_p2_bond_summary_needs_a_why_and_a_new_bond_starts_low() { + let (after, applied) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet." }] } })); + assert_eq!(reasons(&applied), ["unexplained"]); + assert_eq!(bond(&after, DERU)["summary"], bond(&state(), DERU)["summary"]); + let (after, _) = run(&state(), json!({ "people": { "bonds": [{ "person": "deru", "summary": "Deru has gone quiet lately.", "why": "Deru answered once in three days." }] } })); + let deru = bond(&after, DERU); + assert_eq!((deru["summary"].as_str(), deru["lastEvidence"]["summary"].clone()), (Some("Deru has gone quiet lately."), bond(&state(), DERU)["summary"].clone())); + valid(&after); + let mut named = heard(); + named.people.push("@ann:gamecult.org".into()); + let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [{ "person": "@ann:gamecult.org", "kind": "friend", "summary": "Ann asks careful questions.", "why": "Ann asked three." }, { "person": "@ghost:gamecult.org", "trust": "up" }] } })), &named, "w1", now()); + let ann = bond(&after, "@ann:gamecult.org"); + assert_eq!((ann["trust"].as_f64(), ann["tension"].as_f64(), ann["intensity"].as_f64(), ann["relationshipKind"].as_str()), (Some(0.5), Some(0.1), Some(0.2), Some("friend"))); + assert_eq!(reasons(&applied), ["unknown_person"]); + valid(&after); } -/// T4 (map 16.35.13 check 6): `apply` writes nothing but `thoughtMemory.shortTerm`. Over every mix of the proposals the -/// contract names (and one it does not), on states with resolved, stale and crystallized memories, every other field is -/// byte-equal after the commit. +/// Reads are upserted by person and kind, cool after three days and retire after ten. #[test] -fn t4_apply_writes_only_short_term() { - let mut base = state(); - base["thoughtMemory"]["shortTerm"] = json!([ - { "id": "st-1", "status": "active", "target": { "kind": "person", "id": META }, "summary": "Meta asked about the welcome.", "tension": "", "actionImplication": "", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z" }, - { "id": "st-2", "status": "resolved", "target": { "kind": "self", "id": "heimdall" }, "summary": "An old settled note.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:00:00Z" }, - { "id": "st-3", "status": "resolved", "target": { "kind": "self", "id": "heimdall" }, "summary": "Settled by an outside put, no time.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "not a time" } +fn t_p2_reads_upsert_and_age() { + let (once, _) = run(&state(), json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems tired.", "confidence": 0.6 }] } })); + let (twice, _) = run(&once, json!({ "people": { "reads": [{ "person": "kiko", "kind": "mood", "summary": "Kiko seems rested.", "confidence": 0.8 }, { "person": "kiko", "kind": "bogus", "summary": "x" }] } })); + assert_eq!((twice["affect"]["statusReads"].as_array().unwrap().len(), twice["affect"]["statusReads"][0]["summary"].as_str()), (1, Some("Kiko seems rested."))); + let cooled = apply(&twice, &Deltas::default(), &heard(), "w2", now() + Duration::days(3)).0; + let retired = apply(&twice, &Deltas::default(), &heard(), "w3", now() + Duration::days(10)).0; + assert_eq!((cooled["affect"]["statusReads"][0]["status"].as_str(), retired["affect"]["statusReads"][0]["status"].as_str()), (Some("cooling"), Some("retired"))); + valid(&twice); +} + +/// Mood moves by its own plasticity; a trait left alone drifts toward its mean, never past it. +#[test] +fn t_p2_mood_by_plasticity_and_drift() { + let state = state(); + let (after, _) = run(&state, json!({ "feeling": { "mood": { "valence": "down", "arousal": "up" } } })); + let sit = &after["activationProfile"]["situationalState"]; + assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - (0.7 - 0.3 * 0.25)).abs() < 1e-9); + assert!((sit["arousal"]["currentActivation"].as_f64().unwrap() - (0.2 + 0.3 * 0.25)).abs() < 1e-9); + // Dominance was not moved: it sits at its mean already. + assert_eq!(sit["dominance"]["currentActivation"].as_f64(), Some(0.4)); + let mut away = state.clone(); + away["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.2); + away["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.26); + let (drifted, _) = run(&away, json!({})); + let sit = &drifted["activationProfile"]["situationalState"]; + assert!((sit["valence"]["currentActivation"].as_f64().unwrap() - 0.23).abs() < 1e-9); + assert_eq!(sit["arousal"]["currentActivation"].as_f64(), Some(0.25), "never past the mean"); + valid(&drifted); +} + +/// Notes: at most four kept, two settled; a settle into memory moves a note to `memories` crystallized. +#[test] +fn t_p2_notes_are_bounded_and_settle() { + let notes: Vec = (1..=5).map(|n| json!({ "text": format!("Tobiah noted thing number {n}.") })).collect(); + let (after, applied) = run(&state(), json!({ "notes": { "remember": notes } })); + assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), reasons(&applied)), (4, vec!["over_bound".to_owned()])); + let entry = &after["thoughtMemory"]["shortTerm"][0]; + assert_eq!((entry["target"].clone(), entry["tags"].clone()), (json!({ "kind": "room", "id": MINDS }), json!([format!("room:{MINDS}")]))); + let ids: Vec = after["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().map(|note| note["id"].as_str().unwrap().to_owned()).collect(); + let (settled, applied) = run(&after, json!({ "notes": { "settle": [{ "id": ids[0], "into": "memory" }, { "id": ids[1], "into": "resolved" }, { "id": ids[2], "into": "resolved" }, { "id": "nope", "into": "resolved" }] } })); + assert_eq!(reasons(&applied), ["over_bound", "over_bound"]); + assert_eq!((settled["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), settled["thoughtMemory"]["memories"].as_array().unwrap().len() - state()["thoughtMemory"]["memories"].as_array().unwrap().len()), (3, 1)); + let memory = settled["thoughtMemory"]["memories"].as_array().unwrap().iter().find(|memory| memory["id"] == ids[0].as_str()).unwrap(); + assert_eq!(memory["status"], "crystallized"); + valid(&settled); + // A private note made in a direct message keeps that room's tag. + let dm = Heard { room: Some("!dm-aqua:gamecult.org".into()), ..heard() }; + let (after, _) = apply(&state(), &deltas(json!({ "notes": { "remember": [{ "text": "Aqua told Tobiah privately she is tired.", "private": true }] } })), &dm, "w1", now()); + assert_eq!(after["thoughtMemory"]["shortTerm"][0]["tags"], json!(["room:!dm-aqua:gamecult.org", "private"])); +} + +/// A resolved note older than a week is removed, and one resolved with no time is stamped. +#[test] +fn t_p2_resolved_notes_are_pruned() { + let mut state = state(); + state["thoughtMemory"]["shortTerm"] = json!([ + { "id": "st-old", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Old.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:00:00Z" }, + { "id": "st-new", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "Untimed.", "tension": "", "actionImplication": "", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "not a time" } ]); - base["thoughtMemory"]["memories"] = json!([{ "id": "lt-1", "status": "crystallized", "target": { "kind": "self", "id": "heimdall" }, "summary": "A crystallized memory.", "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-01T10:00:00Z" }]); - let menu = [ - remember("Meta asked Heimdall whether the notes are still on for tomorrow; he has not answered yet.", &[META], Some(MINDS), false), - remember("Aqua told Meta privately she is tired.", &[], Some("!dm-aqua:gamecult.org"), true), - remember("Heimdall decided to read the saga code first.", &[], None, false), - resolve("st-1"), - resolve("st-gone"), - resolve("lt-1"), - json!({ "kind": "hold_open", "words": "hold it" }), - ]; - let without_short_term = |state: &Value| { - let mut state = state.clone(); - state["thoughtMemory"].as_object_mut().unwrap().remove("shortTerm"); - state - }; - // Every subset of the menu, in order. - for mask in 0u32..(1 << menu.len()) { - let proposals: Vec = menu.iter().enumerate().filter(|(at, _)| mask & (1 << at) != 0).map(|(_, proposal)| proposal.clone()).collect(); - let (after, _) = apply(&base, &record(json!(proposals)), "r1-t9", now()); - assert_eq!(serde_json::to_string(&without_short_term(&after)).unwrap(), serde_json::to_string(&without_short_term(&base)).unwrap(), "mask {mask:b}"); - } -} - -/// T4 (map 16.35.4): `resolve` sets the one memory the list mapped `resolved` and touches no other. -#[test] -fn t4_resolve_settles_a_listed_memory() { - let (written, _) = apply(&state(), &record(json!([remember("Libby told Meta she would post the welcome once Heimdall rules.", &[META], Some(MINDS), false), remember("Kiko teased Nibu about the sbsar files.", &[], Some(MINDS), false)])), "r1-t1", now()); - let later = now() + Duration::hours(2); - let (after, applied) = apply(&written, &record(json!([resolve("r1-t1-m1")])), "r1-t2", later); - let entries = after["thoughtMemory"]["shortTerm"].as_array().unwrap(); - assert_eq!((entries[0]["status"].as_str(), entries[0]["updatedAt"].clone()), (Some("resolved"), json!(later.to_rfc3339()))); - assert_eq!(entries[1], written["thoughtMemory"]["shortTerm"][1], "the other memory is untouched"); - assert_eq!((applied.resolved.len(), applied.refused.len()), (1, 0)); -} - -/// T4 (4.4 rule 4, kept): a memory an outside put removed after she was shown it is refused, and nothing changes; one that -/// is not short-term is refused too, since a turn writes nothing else. -#[test] -fn t4_resolve_after_outside_put_removed_refused() { - let mut state = state(); - state["thoughtMemory"]["memories"] = json!([{ "id": "lt-1", "status": "crystallized", "target": { "kind": "self", "id": "heimdall" }, "summary": "A crystallized memory.", "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-01T10:00:00Z" }]); - for (entry, reason) in [("r1-t1-m1", "outside_put_removed_target"), ("lt-1", "not_short_term")] { - let (after, applied) = apply(&state, &record(json!([resolve(entry)])), "r1-t2", now()); - assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some(reason)), "{entry}"); - } -} - -/// `RESOLVED_KEPT_DAYS` (map 16.35.4): a memory resolved longer ago than that is removed; one resolved with no time is -/// stamped now and kept; an active one is never removed. -#[test] -fn t4_resolved_memories_are_pruned_after_a_week() { - let mut state = state(); - let entry = |id: &str, status: &str, updated: &str| json!({ "id": id, "status": status, "target": { "kind": "self", "id": "heimdall" }, "summary": id, "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": updated }); - state["thoughtMemory"]["shortTerm"] = json!([entry("old", "resolved", "2026-11-12T15:00:00Z"), entry("recent", "resolved", "2026-11-14T15:00:00Z"), entry("untimed", "resolved", ""), entry("active", "active", "2026-10-01T10:00:00Z")]); - let (after, applied) = apply(&state, &record(json!([])), "r1-t1", now()); - let ids: Vec<&str> = after["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().filter_map(|entry| entry["id"].as_str()).collect(); - assert_eq!((ids, applied.pruned), (vec!["recent", "untimed", "active"], 1)); - assert_eq!(after["thoughtMemory"]["shortTerm"][1]["updatedAt"], json!(now().to_rfc3339())); + let (after, applied) = run(&state, json!({})); + assert_eq!((after["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), applied.pruned, after["thoughtMemory"]["shortTerm"][0]["updatedAt"].clone()), (1, 1, json!(now().to_rfc3339()))); } diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index bc10d5c..1603aa5 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -40,6 +40,8 @@ impl Model for Scripted { self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned())); let text = if prompt.starts_with(PROJECTOR_OPENING) { "The room is slow and so is he.".to_owned() + } else if prompt.starts_with("You are a private Interpreter.") { + "{}".to_owned() } else { (self.persona)(prompt) }; diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs new file mode 100644 index 0000000..c377b89 --- /dev/null +++ b/crates/mind-body/src/projection/interpret.rs @@ -0,0 +1,141 @@ +//! The Interpreter (map 16.38.7): one cheap, fast schema call that reads her monologue, her narration and her prose, and answers +//! `Deltas`, the directions her state moved, in six families. It never writes state and never says how far: `commit::apply` owns +//! every change and every bound. It is told what can change by an index of the ids and current words of her notes, wonderings, +//! needs, pressures, stances, values, intentions and the bonds of the people present or named this wake; it is shown no number, +//! only words, so a direction is all it can give. + +use serde_json::{Value, json}; + +use super::commit::{Deltas, Heard}; +use super::narrate::{Failed, Model, Spent}; +use super::select::{clip, forms, text, voiced}; + +/// What the index shows of one item's words. +const ITEM_BYTES: usize = 240; +/// The fewest letters of a name that can be found named in her monologue. +const NAME_MIN: usize = 3; + +/// The frame of the call. `{name}` and her pronouns are filled by code, so one text serves every Mind. +const FRAME: &str = "You are a private Interpreter. {name} has just lived a moment. Below is what the moment was like for {obj} (the narration), what {subj} thought about it (the thought), and an index of what in {poss} state can change. + +Say which way {poss} state moved, as one JSON object of the schema. Every field is optional, and {} is the usual answer: change only what the thought shows moved. You give directions, never numbers: say up or down, and the commit decides how far. Use only the ids in the index; you make no need and no pressure. + +Write every text you give in the third person, about {name}, in words of your own. Never carry another person's words from the room into a text: say what happened, not what they said. + +- notes: remember what {subj} would want to still know later (at most four); settle a note or a wondering that this moment closed (into resolved) or made a lasting memory (into memory); wonder when something stays open. +- people: bonds move trust, tension or closeness up or down for someone present or named; a summary of a bond changes only with a why. reads are how {subj} reads someone's state right now, with how sure {subj} {be}. +- 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."; + +/// The schema of the answer: the six families, each field optional. +pub(crate) fn schema() -> String { + let text = || json!({ "type": "string" }); + let number = || json!({ "type": "number" }); + let direction = || json!({ "type": "string", "enum": ["up", "down"] }); + let strings = || json!({ "type": "array", "items": text() }); + let list = |item: Value| json!({ "type": "array", "items": item }); + let object = |properties: Value, required: &[&str]| json!({ "type": "object", "additionalProperties": false, "properties": properties, "required": required }); + json!({ + "type": "object", + "additionalProperties": false, + "properties": { + "notes": object(json!({ + "remember": list(object(json!({ "text": text(), "about": strings(), "importance": number(), "private": { "type": "boolean" } }), &["text"])), + "settle": list(object(json!({ "id": text(), "into": { "type": "string", "enum": ["resolved", "memory"] } }), &["id", "into"])), + "wonder": list(object(json!({ "text": text(), "about": strings() }), &["text"])), + }), &[]), + "people": object(json!({ + "bonds": list(object(json!({ "person": text(), "trust": direction(), "tension": direction(), "closeness": direction(), "kind": text(), "summary": text(), "why": text() }), &["person"])), + "reads": list(object(json!({ "person": text(), "kind": text(), "summary": text(), "confidence": number() }), &["person", "kind", "summary"])), + }), &[]), + "feeling": object(json!({ + "feelings": list(object(json!({ "name": text(), "strength": number(), "about": text() }), &["name", "strength"])), + "mood": object(json!({ "valence": direction(), "arousal": direction(), "dominance": direction() }), &[]), + }), &[]), + "drives": object(json!({ + "needs": list(object(json!({ "id": text(), "toward": { "type": "string", "enum": ["up", "down", "met"] } }), &["id", "toward"])), + "pressures": list(object(json!({ "id": text(), "toward": { "type": "string", "enum": ["up", "down", "eased"] } }), &["id", "toward"])), + }), &[]), + "self": object(json!({ + "stances": list(object(json!({ "id": text(), "principle": text(), "summary": text() }), &["principle", "summary"])), + "identity": object(json!({ + "publicName": text(), + "publicDescription": text(), + "presentation": object(json!({ "voiceSummary": text(), "pronouns": text() }), &[]), + "values": list(object(json!({ "id": text(), "label": text(), "summary": text(), "priority": number() }), &["label", "summary"])), + }), &[]), + }), &[]), + "intend": object(json!({ + "add": list(object(json!({ "summary": text(), "target": text(), "urgency": number(), "expires_in_hours": { "type": "integer" }, "readiness": { "type": "string", "enum": ["later", "ready"] } }), &["summary", "expires_in_hours"])), + "ready": strings(), + "drop": strings(), + }), &[]), + }, + "required": [], + }) + .to_string() +} + +/// The keys of the people this wake can name: those present, and any she has a bond with whose name or handle her narration or +/// thought uses. +pub(crate) fn people(state: &Value, heard: &Heard, narration: &str, prose: &str) -> Vec { + let said = format!("{narration}\n{prose}").to_lowercase(); + let words: Vec<&str> = said.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()).collect(); + let mut out = heard.people.clone(); + for bond in state["affect"]["socialBonds"].as_array().into_iter().flatten().filter(|bond| bond["object"]["kind"] == "person") { + let key = heard.key_of(bond["object"]["id"].as_str().unwrap_or_default()); + let names = [key.trim_start_matches('@').split(':').next().unwrap_or_default().to_owned(), text(bond, &["object", "label"]).to_lowercase()]; + if names.iter().any(|name| name.chars().count() >= NAME_MIN && words.contains(&name.as_str())) && !out.contains(&key) { + out.push(key); + } + } + out +} + +/// What can change, as the Interpreter reads it: ids and words, never numbers. +fn index(state: &Value, heard: &Heard) -> String { + let mut out = String::new(); + let mut section = |title: &str, lines: Vec| { + if !lines.is_empty() { + out.push_str(&format!("{title}:\n{}\n\n", lines.join("\n"))); + } + }; + let item = |entry: &Value| format!("- {}: {}", text(entry, &["id"]), clip(text(entry, &["summary"]).trim(), ITEM_BYTES)); + let open = |list: &[&str], open: &[&str]| -> Vec { state[list[0]][list[1]].as_array().into_iter().flatten().filter(|entry| entry["status"].as_str().is_some_and(|status| open.contains(&status))).map(item).collect() }; + section("notes", open(&["thoughtMemory", "shortTerm"], &["active", "draft", "cooling"])); + section("wonderings", open(&["thoughtMemory", "incubation"], &["active", "draft", "cooling"])); + section("needs", open(&["affect", "needs"], &["active", "cooling", "draft"])); + section("pressures", open(&["agencyPressure", "pressures"], &["active", "cooling", "draft"])); + section("stances", open(&["affect", "doctrineStances"], &["active", "draft", "cooling"]).into_iter().collect()); + section("values", state["values"].as_array().into_iter().flatten().map(|value| format!("- {}: {}", text(value, &["id"]), clip(text(value, &["label"]).trim(), ITEM_BYTES))).collect()); + section("intentions", state["candidateActions"]["actions"].as_array().into_iter().flatten().filter(|action| action["customActionType"] == "intention" && action["status"] == "active").map(item).collect()); + let bonds = state["affect"]["socialBonds"].as_array().into_iter().flatten().filter(|bond| bond["object"]["kind"] == "person" && heard.people.contains(&heard.key_of(bond["object"]["id"].as_str().unwrap_or_default()))); + section("bonds", bonds.map(|bond| format!("- {}: {}", heard.key_of(text(bond, &["object", "id"])), clip(text(bond, &["summary"]).trim(), ITEM_BYTES))).collect()); + section("people here or named, with no bond yet", heard.people.iter().filter(|person| !state["affect"]["socialBonds"].as_array().into_iter().flatten().any(|bond| heard.key_of(text(bond, &["object", "id"])) == **person)).map(|person| format!("- {person}")).collect()); + out.trim_end().to_owned() +} + +/// The prompt: the frame in her pronouns, the index, then the narration and what she thought, fenced as data. +fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str) -> String { + let name = match text(state, &["publicName"]).trim() { + "" => "She", + name => name, + }; + let frame = voiced(&FRAME.replace("{name}", name), forms(state)); + format!("{frame}\n\nINDEX\n{}\n\nNARRATION\n{narration}\n\nTHOUGHT\n{prose}", index(state, heard)) +} + +/// One call of `model` over her narration and prose: the deltas it answers, and what the call cost. A failed call, or an answer +/// that is not the contract, is a failure and moves nothing. +pub(crate) fn deltas(model: &dyn Model, model_name: &str, request_id: &str, state: &Value, heard: &Heard, narration: &str, prose: &str) -> Result<(Deltas, Option), Failed> { + let answer = model.ask(request_id, model_name, &prompt(state, heard, narration, prose), Some(&schema()))?; + match serde_json::from_str::(&answer.text) { + Ok(deltas) => Ok((deltas, answer.usage)), + Err(_) => Err(Failed { reason: "the Interpreter's answer is not the delta contract".into(), outage: false, usage: answer.usage }), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs new file mode 100644 index 0000000..489825f --- /dev/null +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -0,0 +1,72 @@ +use std::cell::RefCell; + +use super::*; +use crate::projection::Answer; + +const DERU: &str = "@deru:gamecult.org"; + +/// A model that answers `text` and keeps what it was asked. +struct Answers(&'static str, RefCell)>>); + +impl Model for Answers { + fn ask(&self, _request_id: &str, _model: &str, prompt: &str, schema: Option<&str>) -> Result { + self.1.borrow_mut().push((prompt.to_owned(), schema.map(str::to_owned))); + Ok(Answer { text: self.0.to_owned(), usage: None }) + } +} + +fn heard() -> Heard { + Heard { room: None, lines: vec![], people: vec!["operator".into()], operators: vec!["@meta:gamecult.org".into()], minds: vec![DERU.into()], identity_visible: true } +} + +fn state() -> Value { + let mut state = crate::projection::harness::tests::control(); + state["candidateActions"]["actions"] = json!([{ "id": "ca-1", "status": "active", "actionType": "custom", "customActionType": "intention", "readiness": "waiting", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "Tobiah means to ask Deru about the crossword.", "createdAt": "2026-11-19T10:00:00Z", "updatedAt": "2026-11-19T10:00:00Z" }]); + state +} + +#[test] +fn the_schema_names_the_six_families_and_closes_every_object() { + let schema: Value = serde_json::from_str(&schema()).unwrap(); + let families: Vec<&str> = schema["properties"].as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(families, ["drives", "feeling", "intend", "notes", "people", "self"]); + fn closed(value: &Value) -> bool { + match value { + Value::Object(map) => (map.get("type") != Some(&json!("object")) || map.get("additionalProperties") == Some(&json!(false))) && map.values().all(closed), + Value::Array(items) => items.iter().all(closed), + _ => true, + } + } + assert!(closed(&schema)); +} + +#[test] +fn the_call_is_one_schema_turn_and_the_index_gives_ids_and_words_never_numbers() { + let model = Answers(r#"{"people":{"bonds":[{"person":"deru","trust":"up"}]}}"#, RefCell::default()); + let mut heard = heard(); + heard.people = people(&state(), &heard, "Deru is on her mind.", "She thinks of him."); + assert!(heard.people.contains(&"deru".to_owned()), "a bonded person the narration names is named: {:?}", heard.people); + let (deltas, _) = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard, "Deru is on her mind.", "He thinks of the heron.").unwrap(); + assert_eq!(deltas.people.bonds[0].trust.as_deref(), Some("up")); + let calls = model.1.borrow(); + assert_eq!(calls.len(), 1); + let (prompt, schema) = &calls[0]; + assert!(schema.is_some()); + let index = prompt.split("INDEX\n").nth(1).unwrap().split("NARRATION").next().unwrap(); + for wanted in ["need-an-audience", "stance-slow-is-kind", "w-clue-for-heron", "ca-1", "deru: ", "value-unhurried"] { + assert!(index.contains(wanted), "{wanted} in {index}"); + } + assert!(!index.contains("0."), "no numbers in the index: {index}"); + assert!(prompt.contains("Tobiah Fenn"), "she is named, in her pronouns: {prompt}"); +} + +#[test] +fn an_answer_that_is_not_the_contract_is_a_failure_with_its_cost() { + let model = Answers("not json", RefCell::default()); + let failed = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap_err(); + assert!(!failed.outage); + let model = Answers(r#"{"notes":{"remember":[{"text":7}]}}"#, RefCell::default()); + assert!(super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").is_err()); + let nothing = Answers("{}", RefCell::default()); + assert_eq!(super::deltas(¬hing, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap().0, Deltas::default()); +} diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 73801cd..7b858b6 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -442,7 +442,7 @@ struct Candidate { // --------------------------------------------------------------------------------------------- // Reading her state. -fn text<'a>(value: &'a Value, path: &[&str]) -> &'a str { +pub(crate) fn text<'a>(value: &'a Value, path: &[&str]) -> &'a str { path.iter().try_fold(value, |at, key| at.get(*key)).and_then(Value::as_str).unwrap_or_default().trim() } diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index 3699e8e..59e2d9a 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -33,8 +33,6 @@ const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. {cap_subj} pub(crate) const HERE_ROOM_MIN: usize = 256; /// The least `outcome_bytes` may be: the heading and the longest line without her words (a failed turn's) always fit. pub(crate) const OUTCOME_ROOM_MIN: usize = 256; -/// The most reads a wake may perform (map 16.22.3: tuning, at most 4). -const READS_PER_WAKE_MAX: usize = 4; /// The least `domain_bytes` may be: the heading and the line counting the lines of her domain not shown always fit (I16.11). pub(crate) const DOMAIN_ROOM_MIN: usize = 128; /// The least `body_bytes` may be: the body heading, the longest turn line (`select::turn_words`) and one entry at the @@ -336,27 +334,17 @@ impl Default for ProjectorTuning { } } -/// What counts as her choosing to send a draft now (map 16.7): the experiment's lever over when a draft is said. -const INTERPRETER_GUIDANCE: &str = "A draft is speech only when {poss} prose shows {obj} choosing to send it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that {subj} say{s} nothing, is not speech. An empty say list is the usual answer in a busy room."; - -/// The Interpreter's speech call: its model and its guidance. The speech frame is code (`interpret`): the room and private -/// rules, attribution, choosing among her drafts and never writing her words, the contract and the gap kinds are not knobs. +/// The Interpreter: the model of its one schema call over her monologue (map 16.38.7). Its bounds are code's (`commit`): the +/// model gives a direction and code decides how far, so none of them is a knob here. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct InterpreterTuning { pub model: String, - /// What counts as her choosing to say it now, set inside the speech frame. - pub guidance: String, - /// Reads by intent (map 16.22.3): the most a wake performs, each result's bytes, and all results' bytes in a wake. - /// Past any, the loop ends and the last answer is final. - pub reads_per_wake: usize, - pub read_bytes: usize, - pub wake_read_bytes: usize, } impl Default for InterpreterTuning { fn default() -> Self { - Self { model: "claude-sonnet-5-5".into(), guidance: INTERPRETER_GUIDANCE.into(), reads_per_wake: 2, read_bytes: 3000, wake_read_bytes: 6000 } + Self { model: "claude-haiku-5-5".into() } } } @@ -468,7 +456,6 @@ impl Tuning { ("select.group_bytes", select.group_bytes), ("projector.guidance", self.projector.guidance.len()), ("persona.guidance", self.persona.guidance.len()), - ("interpreter.guidance", self.interpreter.guidance.len()), ] { if bytes > PART_BYTES_MAX { bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame"); @@ -492,13 +479,6 @@ impl Tuning { if select.outcome_bytes < OUTCOME_ROOM_MIN { bail!("select.outcome_bytes must be at least {OUTCOME_ROOM_MIN}, not {}: what came of her last turn always has room", select.outcome_bytes); } - let interpreter = &self.interpreter; - if interpreter.reads_per_wake > READS_PER_WAKE_MAX { - bail!("interpreter.reads_per_wake must be at most {READS_PER_WAKE_MAX}, not {}: each read costs a call and a continuation", interpreter.reads_per_wake); - } - if interpreter.read_bytes == 0 || interpreter.read_bytes > interpreter.wake_read_bytes || interpreter.wake_read_bytes > PART_BYTES_MAX { - bail!("interpreter.read_bytes must be above 0 and at most interpreter.wake_read_bytes, which is at most {PART_BYTES_MAX}"); - } if select.domain_bytes < DOMAIN_ROOM_MIN { bail!("select.domain_bytes must be at least {DOMAIN_ROOM_MIN}, not {}: the line counting what of her domain is not shown always fits", select.domain_bytes); } diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 99751cc..8d563aa 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -7,18 +7,21 @@ use std::collections::BTreeSet; use chrono::{DateTime, Utc}; +use eureka_pipeline::Slug; use serde_json::{Value, json}; +use super::commit::{Deltas, Heard}; + /// 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; -/// One wake taken as the Interpreter will put it: her record of it and her state after it. The seam `persona::put_applied` puts through; -/// nothing fills it until the Interpreter's deltas attach (P2). -#[allow(dead_code, reason = "the Interpreter's deltas attach here (P2): its first caller removes this allow")] -pub(crate) struct Taken { - pub record: Value, - pub state: Value, +/// One wake taken as the Interpreter's deltas will put it: the deltas, what the wake heard and whose state it is. The seam +/// `persona::put_applied` puts through: on a stale put it applies the same deltas to her state as it then stands. +pub(crate) struct Taken<'a> { + pub deltas: &'a Deltas, + pub heard: &'a Heard, + pub instance: &'a Slug, } /// The events her trace shows she has decided: every line a record that did not fail held (`held`, the event ids the wake showed her) and @@ -52,10 +55,10 @@ pub(crate) struct Past { pub last_wake: Option>, } -/// A real turn: a record that decided something. A failed turn decided nothing, a record that only set lines aside is no turn, and a row of her agent's (`agent`) is a call, a receipt or a discard, never a turn. The one +/// A real turn: a record that decided something. A failed turn decided nothing, a record that only set lines aside is no turn, and a row of her agent's (`agent`) is a call, a receipt or a discard, never a turn. The Interpreter's receipt and a code-written post (`kind` `interpreter`, `say`) are rows beside a turn, never one. The one /// definition, for what she is told of her last turn (`history`) and for what her trace holds untold (`untold`). pub(crate) fn is_real(record: &Value) -> bool { - record.get("failed").is_none() && record.get("set_aside").is_none() && record.get("agent").is_none() + record.get("failed").is_none() && record.get("set_aside").is_none() && record.get("agent").is_none() && !matches!(record["kind"].as_str(), Some("interpreter" | "say")) } /// What her trace holds that she has not been told, from whichever record holds it: each line set aside, each put refused and a failed diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 2cb5513..8f5242a 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -222,6 +222,7 @@ mind_body::persona: const AGENT : & str mind_body::persona: const ENV_MINDS : & str mind_body::persona: const ENV_MODEL : & str mind_body::persona: const ENV_OPERATOR : & str +mind_body::persona: const ENV_REVIEW_ROOM : & str mind_body::persona: const ENV_ROOMS : & str mind_body::persona: const ENV_SELF_SENDER : & str mind_body::persona: fn carry < C : Chat > (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug , build : impl FnOnce () -> Result < Start < C > >) -> Outcome @@ -242,7 +243,7 @@ mind_body::persona: impl TraceView for TraceSnapshot mind_body::persona: impl fmt :: Display for Outcome mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; } mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; } -mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String] +mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String, review_room: Option < String >] mind_body::persona: struct FileTrace pub-fields[] mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >] mind_body::persona: struct TraceSnapshot pub-fields[] @@ -299,6 +300,8 @@ mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialE mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[] mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64] mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str] +mind_body::projection::commit: impl Commit < '_ > +mind_body::projection::commit: impl Heard mind_body::projection::domain: impl DomainSource for DomainFacts mind_body::projection::domain: impl DomainSource for MindDomain mind_body::projection::domain: impl ForgeGet for HttpForge @@ -397,7 +400,7 @@ mind_body::projection::tuning: impl Price mind_body::projection::tuning: impl Tuning mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >] mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64] -mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, reads_per_wake: usize, read_bytes: usize, wake_read_bytes: usize] +mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String] mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64] mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String] mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize]