diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 40f152e..824643d 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -8,7 +8,7 @@ //! //! What the module holds for that turn 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 -//! her rooms (`render_tail`) and the turn trace's store (`FileTrace`). Items no start calls yet carry an +//! her rooms (`render_tail`) and the turn records' store (`FileTrace`). Items no start calls yet carry an //! `allow(dead_code)` that the first caller removes. use std::collections::BTreeMap; @@ -19,7 +19,7 @@ use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, Utc}; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; use eureka_pipeline::{MemoryOrigin, Slug}; -use serde::{Deserialize, Serialize}; +use serde_json::Value; use crate::address::{Addressee, addresses, is_for, localpart}; use crate::chat_client::{Basis, ChatDelivery, TailLine}; @@ -127,36 +127,21 @@ impl Config { } } -/// Where a turn's record goes. +/// Where a turn's record goes: the record itself, the shape `projection::outcome::outcome_of` reads, keyed `-t`. +/// Her last outcome, her recent selections, her exchange records and her last wake are read back from it +/// (`projection::turn::history`); nothing else holds them. pub trait Trace { - fn record(&self, trace: &TurnTrace) -> Result<()>; + fn record(&self, key: &str, record: &Value) -> Result<()>; + /// Every record, oldest first. + fn records(&self) -> Result>; } -/// One item of a trace with the provenance it came in under: `operator`, -/// `member`, `persona` for what she was shown; `her own` for what she produced. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct TraceItem { - pub provenance: String, - pub room: String, - pub text: String, -} - -/// The record of one turn: what went in, what came out, how it ended. -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "eureka.persona.turn_trace.v1", schema = "PersonaTurnTrace")] -pub struct TurnTrace { +/// One stored record: the turn's record, whole. +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "eureka.persona.turn_record.v1", schema = "PersonaTurnRecord")] +pub struct TurnRecord { #[cultcache(key = 0)] - pub run: String, - #[cultcache(key = 1)] - pub turn: u32, - #[cultcache(key = 2)] - pub at: DateTime, - #[cultcache(key = 3)] - pub inputs: Vec, - #[cultcache(key = 4)] - pub outputs: Vec, - #[cultcache(key = 5)] - pub outcome: String, + pub value: Value, } /// The trace in a CultCache single-file store under the unit's state directory. @@ -168,17 +153,27 @@ impl FileTrace { pub fn new(path: impl Into) -> Self { Self { path: path.into() } } + + fn open(&self) -> Result { + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?; + cache.pull_all_backing_stores()?; + Ok(cache) + } } impl Trace for FileTrace { - fn record(&self, trace: &TurnTrace) -> Result<()> { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?; - cache.pull_all_backing_stores()?; - cache.put(format!("{}-{}", trace.run, trace.turn), trace)?; + fn record(&self, key: &str, record: &Value) -> Result<()> { + self.open()?.put(key.to_owned(), &TurnRecord { value: record.clone() })?; Ok(()) } + + fn records(&self) -> Result> { + let mut rows: Vec<(String, String, Value)> = self.open()?.get_all_with_keys::()?.into_iter().map(|(key, row)| (row.value["at"].as_str().unwrap_or_default().to_owned(), key, row.value)).collect(); + rows.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1))); + Ok(rows.into_iter().map(|(_, _, value)| value).collect()) + } } /// What a start did. Every outcome is an answer. diff --git a/crates/mind-body/src/persona/tests.rs b/crates/mind-body/src/persona/tests.rs index 56795c3..3b5a986 100644 --- a/crates/mind-body/src/persona/tests.rs +++ b/crates/mind-body/src/persona/tests.rs @@ -171,23 +171,16 @@ fn her_own_row_is_in_the_addressing_exactly_once_whatever_the_table_holds() { } #[test] -fn the_trace_store_keeps_each_turn_under_its_run_and_turn() { +fn the_trace_store_keeps_each_record_under_its_key_and_lists_them_oldest_first() { let dir = TempDir::new().unwrap(); - let path = dir.path().join("persona-trace.cc"); - let trace = TurnTrace { - run: "mind-1".into(), - turn: 2, - at: at(0), - inputs: vec![TraceItem { provenance: "member".into(), room: "swarm".into(), text: "hi".into() }], - outputs: vec![], - outcome: "answered".into(), - }; - FileTrace::new(&path).record(&trace).unwrap(); - let mut cache = CultCache::new(); - cache.register_entry_type::().unwrap(); - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); - cache.pull_all_backing_stores().unwrap(); - assert_eq!(cache.get::("mind-1-2").unwrap(), Some(trace)); + let trace = FileTrace::new(dir.path().join("persona-trace.cc")); + let record = |turn: u32, minute: i64| serde_json::json!({ "at": at(minute).to_rfc3339(), "posted": [], "turn": turn }); + trace.record("mind-1-t10", &record(10, 3)).unwrap(); + trace.record("mind-1-t2", &record(2, 1)).unwrap(); + trace.record("mind-1-t3", &record(3, 2)).unwrap(); + let turns: Vec = trace.records().unwrap().iter().map(|record| record["turn"].as_u64().unwrap()).collect(); + assert_eq!(turns, [2, 3, 10], "oldest first by when, not by key"); + assert_eq!(trace.records().unwrap()[0], record(2, 1), "the record is stored whole"); } #[test] diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 6171994..96b09da 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -31,6 +31,7 @@ mod select; mod simulate; mod span; mod tuning; +mod turn; use std::path::PathBuf; @@ -214,22 +215,19 @@ pub struct Request { pub through: Through, /// When she last heard from people (Matrix id, unix ms) beyond the room's tail: a fixture's table. Empty live. pub last_heard: Vec<(String, u64)>, - /// The ids each earlier projection selected, oldest first, for freshness: a simulation's earlier turns of hers. - /// Empty live until trace v2 (C3c) carries them. + /// The ids each earlier projection selected, oldest first, for freshness: read from her records (`turn::history`). pub recent: Vec>, /// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet. pub own_rooms: Vec, /// The record of her last turn, which her packet opens with what came of (`outcome::outcome_of`): the Interpreter's - /// decision under `interpreter` and the receipts of the lines that went out under `posted`, or `failed`. A - /// simulation carries each turn's to her next; a harness run takes a fixture's (`--last-outcome`). None live until - /// the commit's trace (C3c) carries it. + /// decision under `interpreter` and the receipts of the lines that went out under `posted`, or `failed`. Read from her + /// records (`turn::history`); a harness run takes a fixture's (`--last-outcome`). pub last_outcome: Option, - /// When she last woke: her domain's window opens there, held to at least a day and at most a week (map 16.22.2). A - /// simulation carries each Mind's; none, as live until the commit's trace (C3c) carries it, is a week. + /// When she last woke: her domain's window opens there, held to at least a day and at most a week (map 16.22.2). Read + /// from her records (`turn::history`); none is a week. pub last_wake: Option>, - /// Her earlier turn records, oldest first (the commit's trace live, once C3c writes it; a simulation's own): what she - /// has said and read in this conversation is read from them (`exchange::exchange_of`, map 16.24.1). Empty live until - /// the trace exists. + /// Her earlier turn records, oldest first: her trace live, the run's list simulated, both read by `turn::history`. What + /// she has said and read in this conversation is read from them (`exchange::exchange_of`, map 16.24.1). pub records: Vec, } diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 89381ea..24aa4a1 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -19,7 +19,7 @@ pub(crate) fn control() -> Value { serde_json::from_str(&std::fs::read_to_string(fixtures().join("states/control.json")).unwrap()).unwrap() } -fn room(name: &str) -> Fixture { +pub(crate) fn room(name: &str) -> Fixture { Fixture::load(&fixtures().join("rooms").join(name)).unwrap() } @@ -100,7 +100,7 @@ impl PersonaSource for NeverAsked { } } -fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> { +pub(crate) fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> { Harness { instance: "eureka".into(), persona, model, tuning: dir.join("persona-tuning.toml") } } diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 340a180..03fd0a2 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -200,6 +200,8 @@ enum EditRefusal { NotFound, NotHers, TooLong, + /// The mouth carries no edit (map 16.36.2, item 7): a line said there stays as it went. + NoEditAtTheMouth, } /// One thing that came of her last turn, by its typed reason. A part that reached the room carries the receipt that says @@ -643,6 +645,7 @@ impl Part { EditRefusal::NotFound => "the line is gone.".to_owned(), EditRefusal::NotHers => format!("the line is not {poss}."), EditRefusal::TooLong => "the line would be too long.".to_owned(), + EditRefusal::NoEditAtTheMouth => "a line cannot be added to once it is said here.".to_owned(), }; format!(" {why}{}", drafted(added)) } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index f82a960..d49e977 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -12,9 +12,9 @@ //! her again next round: no line is seen without a turn that read it. The turns of a round go in an order drawn from //! the seed, each against the room as it stands at that turn. //! -//! What came of each of her turns opens her next packet (map 16.16): the simulator keeps each turn's record as the commit's -//! trace will (the Interpreter's decision and the lines the room appended for her), and passes it as her next turn's -//! `last_outcome`; a failed turn's record is a failure. When she adds to a line of hers (map 16.17), the room is the +//! What came of each of her turns opens her next packet (map 16.16): the run keeps each turn's record, as her trace live +//! (`turn::take`: the Interpreter's decision and the lines the room appended for her), and her next turn reads her +//! `last_outcome` from them (`turn::history`); a failed turn's record is a failure. When she adds to a line of hers (map 16.17), the room is the //! actuator, as the mouth will be live (B1): it appends `EDIT_MARK` and her draft to that line itself, wakes no one, and //! records a receipt in her turn's record. When a line of hers replies to another (map 16.20.8 (D), K20), the room records //! the relation by the replied line's event, as the mouth will live (Bifrost B3), and refuses one not in the line's room; @@ -24,6 +24,7 @@ //! from her turn's record and its receipts, as live C3c's commit will apply them: the memories she writes and settles //! (map 16.35.4). The report lists them per turn, and counts them per Mind with her short-term size at the run's end. +use std::cell::{Cell, RefCell}; use std::collections::BTreeMap; use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -33,13 +34,13 @@ use chrono::{DateTime, Duration, Utc}; use serde::Deserialize; use serde_json::{Value, json}; -use super::commit; use super::narrate::MAX_OUTPUT_TOKENS; use super::read::{self, ReadFailure, ReadRequest}; use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::select::Draw; use super::tuning; -use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind, project}; +use super::turn::{self, Actuator, Edited, Sent, history, last_wake}; +use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind}; use crate::address::{Addressee, is_for, localpart}; use crate::chat_client::ChatPending; use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, wakes}; @@ -164,7 +165,7 @@ fn unseen(seen: &Seen, lines: &[Line], at: usize) -> bool { /// One persona's view of the room at her turn: the lines she has not seen are new. struct View<'a> { - lines: &'a [Line], + lines: &'a RefCell>, viewer: &'a str, rooms: &'a [String], seen: &'a Seen, @@ -172,7 +173,49 @@ struct View<'a> { impl MouthReader for View<'_> { fn pending(&self) -> Result { - Ok(pending_for(self.lines, self.viewer, self.rooms, |at| unseen(self.seen, self.lines, at))) + let lines = self.lines.borrow(); + Ok(pending_for(&lines, self.viewer, self.rooms, |at| unseen(self.seen, &lines, at))) + } +} + +/// The simulated room as the turn's actuator, as the mouth will be live (B1, B3): a send appends a line from her, by its +/// index, which serves as its event, and an event not in the room's lines refuses the reply; an edit composes the new body +/// from the line as it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line, +/// so it wakes no one, and every view after it reads the amended text. +struct SimRoom<'a> { + lines: &'a RefCell>, + her: &'a str, + name: &'a str, + /// The room of the turn, and when she was woken by a direct message, whom it answers. + here: &'a str, + dm_to: Option, + cast: &'a [String], + operators: &'a [String], + now: DateTime, + sent: Cell, +} + +impl Actuator for SimRoom<'_> { + fn send(&self, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String]) -> Sent { + let offset = self.sent.replace(self.sent.get() + 1); + let mut lines = self.lines.borrow_mut(); + let reply_to = match in_reply_to { + None => None, + Some(event) => match replied(&lines, event, room) { + Some(at) => Some(at), + None => return Sent::Refused("reply_target_not_in_room".to_owned()), + }, + }; + let mentions = mentions.iter().filter(|id| self.cast.contains(*id) || self.operators.contains(*id)).cloned().collect(); + let at_ms = u64::try_from(self.now.timestamp_millis()).unwrap_or_default() + offset; + let dm_to = if room == self.here { self.dm_to.clone() } else { None }; + let event = lines.len().to_string(); + lines.push(Line { from: self.her.to_owned(), name: self.name.to_owned(), room: room.to_owned(), at_ms, says: text.to_owned(), mentions, dm_to, follow_up: false, reply_to, new: false }); + Sent::Posted(event) + } + + fn edit(&self, event: &str, added: &str) -> Edited { + edit(&mut self.lines.borrow_mut(), self.her, event, added) } } @@ -378,12 +421,9 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) scripted(0, &mut lines, &mut rounds_of, &mut causes)?; let opening = lines.len(); let mut seen: Vec = vec![Seen::new(); members.len()]; - let mut last_turn: Vec>> = vec![None; members.len()]; let mut last_beat = plan.start; - let mut recent: Vec>> = vec![Vec::new(); members.len()]; - // Each persona's last turn's record, as the commit's trace will hold it: what came of it opens her next packet. - let mut last: Vec> = vec![None; members.len()]; - // Every turn record of hers, oldest first: what she has said and read in a conversation is read from them (K26). + // Every turn record of hers, oldest first: the run's trace, which her last outcome, her recent selections, her exchange + // and her last wake are read from (`turn::history`). let mut records: Vec> = vec![Vec::new(); members.len()]; let mut turns = Vec::new(); // Every note to Self the run's turns left, oldest first: what Self's inbox reader (C5) will list from the traces. @@ -403,8 +443,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) .map(|(at, member)| Standing { slug: localpart(&member.entry.id).to_owned(), eligible: !woke.iter().any(|(woken, _)| *woken == at), - waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), - last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()), + waited_s: last_wake(&records[at]).map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), + last_turn_ms: last_wake(&records[at]).map(|turn| turn.timestamp_millis()), topic_permille: 0, addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries), }) @@ -426,6 +466,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.clone()); let kind = if fresh.iter().any(|line| line.room == here) { TurnKind::Chat } else { TurnKind::Beat }; let now = round_at + Duration::seconds(30 + counter as i64); + let past = history(&records[at]); let request = Request { instance: localpart(&id).to_owned(), kind, @@ -440,96 +481,47 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) tuning: harness.tuning.clone(), through: Through::Interpreter, last_heard: vec![], - recent: recent[at].clone(), + recent: past.recent, own_rooms: member.entry.own_rooms.clone(), - last_outcome: last[at].take(), - last_wake: last_turn[at], - records: records[at].clone(), + last_outcome: past.last_outcome, + last_wake: past.last_wake, + records: past.records, }; - let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: &seen[at] }; - let names = Names(&member.addressee); - let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); - let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; - let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); // What the room held when she read it, before her own lines go in. let read_to = lines.len(); - let render = &report["renders"][0]; - if let Some(selected) = render["selected"].as_array() { - recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect()); - } - // A failed call is a failure, never a silence. - let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + let key = format!("r{}-t{counter}", repeat + 1); + let room = RefCell::new(std::mem::take(&mut lines)); + let taken = { + let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] }; + let names = Names(&member.addressee); + let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); + let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; + let actuator = SimRoom { lines: &room, her: &id, name: &member.entry.name, here: &here, dm_to, cast: &cast, operators: &plan.operators, now, sent: Cell::new(0) }; + turn::take(&organs, &request, &actuator, &key, now) + }; + lines = room.into_inner(); + let cause = cause_word(why.as_ref().map(|why| why.cause)); + rounds_of.resize(lines.len(), round); + causes.resize(lines.len(), Some(cause)); + held_to_schema(&member.entry.name, &id, &taken.state, &key)?; + let failed = taken.record["failed"].as_str().map(str::to_owned); // A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake // sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is // acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands. if failed.is_none() { seen[at].insert(here.clone(), read_to); - last_turn[at] = Some(now); } - // What she says is the Interpreter's decision alone; who it wakes is its structured mentions and the line it replies to. - let said: Vec = if failed.is_some() { vec![] } else { render["interpreter"]["said"].as_array().cloned().unwrap_or_default() }; - let cause = cause_word(why.as_ref().map(|why| why.cause)); - let mut spoken: Vec = Vec::new(); - // The room's receipts: each line it appended, by its index, which serves as its event. - let mut posted: Vec = Vec::new(); - let mut refused_sends: Vec = Vec::new(); - for (offset, decided) in said.iter().enumerate() { - let room = decided["room"].as_str().unwrap_or(&here).to_owned(); - let says = decided["text"].as_str().unwrap_or_default().to_owned(); - let mentions: Vec = decided["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).filter(|id| cast.contains(&(*id).to_owned()) || plan.operators.contains(&(*id).to_owned())).map(str::to_owned).collect()).unwrap_or_default(); - // The room is the reply's actuator, as the mouth will be (B3): an event not in this room refuses the send, so - // nothing reached the room and no receipt is written. - let reply_to = match decided["in_reply_to"]["event"].as_str() { - None => None, - Some(event) => match replied(&lines, event, &room) { - Some(at) => Some(at), - None => { - refused_sends.push(json!({ "room": room, "text": says, "in_reply_to": event, "refusal": "reply_target_not_in_room" })); - continue; - } - }, - }; - let at_ms = u64::try_from(now.timestamp_millis()).unwrap_or_default() + offset as u64; - let to = if room == here { dm_to.clone() } else { None }; - posted.push(json!({ "event": lines.len().to_string(), "room": room, "text": says })); - lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room, at_ms, says: says.clone(), mentions, dm_to: to, follow_up: false, reply_to, new: false }); - rounds_of.push(round); - causes.push(Some(cause)); - spoken.push(says); - } - // The room is the amendment's actuator, as the mouth will be live (B1): it composes the new body from the line as - // it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line, so it - // wakes no one, and every view after it reads the amended text. - let mut edited: Vec = Vec::new(); - for amended in render["interpreter"]["amended"].as_array().into_iter().flatten().filter(|_| failed.is_none()) { - let event = amended["event"].as_str().unwrap_or_default(); - let refusal = edit(&mut lines, &id, event, amended["added"].as_str().unwrap_or_default()); - edited.push(json!({ "event": event, "refusal": refusal })); - } - for (index, note) in render["interpreter"]["suggestions"].as_array().into_iter().flatten().filter(|_| failed.is_none()).enumerate() { + for (index, note) in taken.report["renders"][0]["interpreter"]["suggestions"].as_array().into_iter().flatten().filter(|_| failed.is_none()).enumerate() { inbox.push(json!({ "key": format!("r{}-t{counter}-s{index}", repeat + 1), "mind": localpart(&id), "round": round, "at": now.to_rfc3339(), "kind": note["kind"], "about": note["about"], "room": note["room"], "text": note["text"] })); } - let mut record = match &failed { - Some(failed) => json!({ "failed": failed }), - None => json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited, "refused_sends": refused_sends }), - }; - // A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided - // before it went out, and she is told the rest broke off. - if let Some(step) = ["continuation_failed", "later_failed"].into_iter().find(|step| render["interpreter"].get(*step).is_some()) { - record["broke_after"] = json!(step); - } - // The commit: her turn's proposals applied to her in-run state on the receipts above, as C3c's will be live, and - // what it did kept in the record her next outcome reads. - let (state, applied) = commit::apply(&members[at].state, &record, &format!("r{}-t{counter}", repeat + 1), now); - held_to_schema(&member.entry.name, &id, &state, &format!("r{}-t{counter}", repeat + 1))?; - record["committed"] = json!(applied); - last[at] = Some(record.clone()); - records[at].push(record.clone()); + let spoken: Vec<&str> = taken.record["posted"].as_array().into_iter().flatten().filter_map(|receipt| receipt["text"].as_str()).collect(); let line = (!spoken.is_empty()).then(|| spoken.join(" / ")); let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" }; let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by)); - let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "edited": edited, "committed": record["committed"], "report": report }); - members[at].state = state; + let edited = taken.record.get("edited").cloned().unwrap_or_else(|| json!([])); + let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "edited": edited, "committed": taken.record["committed"], "report": taken.report }); + records[at].push(taken.record); + members[at].state = taken.state; turns.push(turn); } } diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index cb61b17..8f29896 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1057,3 +1057,50 @@ fn t4_x5_timeline_the_note_carries_and_nothing_gates_the_welcome() { assert!(libby_state["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().any(|entry| entry["id"] == id), "the note stays in her state"); assert_eq!(run["metrics"]["personas"]["Libby"]["memories"]["written"], 1, "{}", run["metrics"]["personas"]); } + +#[test] +fn t_l1_sim_and_mouth_records_same_shape() { + use crate::projection::harness::fixture_request; + use crate::projection::harness::tests::{harness, room}; + use crate::projection::outcome::outcome_of; + use crate::projection::select::forms; + use crate::projection::turn::{Mouth, take}; + let dir = tempfile::tempdir().unwrap(); + let model = Scripted::new(|_| "He smiles at the screen, then types. Missed you too, friend.".into()); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&model)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); + let lines = RefCell::new(Vec::new()); + let sim = SimRoom { lines: &lines, her: TOBIAH, name: "Tobiah", here: "!dm-meta:gamecult.org", dm_to: None, cast: &[], operators: &[], now: fixture.now, sent: Cell::new(0) }; + let simulated = take(&organs, &request, &sim, "r1-t1", fixture.now); + struct Chat1; + impl crate::chat_client::Chat for Chat1 { + fn pending(&self, _: u64) -> Result { + bail!("unused") + } + fn send(&self, request: &crate::chat_client::ChatSendRequest) -> Result { + Ok(crate::chat_client::ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some("$0".into()), refusal: None, newer: vec![] }) + } + fn open_direct(&self, _: &crate::chat_client::ChatOpenDirectRequest) -> Result { + bail!("unused") + } + fn fetch(&self, _: &crate::chat_client::ChatFetchRequest) -> Result { + bail!("unused") + } + fn ack(&self, _: u64) -> Result<()> { + bail!("unused") + } + fn read(&self, _: &crate::chat_client::ChatRead) -> Result<()> { + bail!("unused") + } + } + let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), key: "r1-t1".into(), basis: None, sent: Cell::new(0) }; + let live = take(&organs, &request, &mouth, "r1-t1", fixture.now); + let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::>(); + assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live"); + assert_eq!(lines.borrow().len(), 1, "the room appended her line"); + assert_eq!(simulated.record["posted"][0]["text"], live.record["posted"][0]["text"]); + let told = |taken: &crate::projection::turn::Taken| outcome_of(&taken.record).unwrap().lines(forms(&taken.state)); + assert_eq!(told(&simulated), told(&live), "she is told the same of either"); +} diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs new file mode 100644 index 0000000..5938c65 --- /dev/null +++ b/crates/mind-body/src/projection/turn.rs @@ -0,0 +1,152 @@ +//! One turn (map 16.36.2, items 2 and 6): the packet, the decision, the actuation, the commit and the record. The +//! simulator's room and the live mouth are the two actuators; `take` is the one turn they share, so the simulator tests +//! the turn the Minds take on chat. Her records are her trace: what she last did, what she showed lately, what she has +//! said in this conversation and when she last woke are read back from them (`history`), and kept nowhere else. + +use std::cell::Cell; + +use chrono::{DateTime, Utc}; +use serde_json::{Value, json}; + +use super::commit; +use super::{Organs, Request, project}; +use crate::chat_client::{Chat, ChatSendRequest, SendBasis}; + +/// How many of her earlier projections freshness remembers, and how many of her records a packet reads. +const RECENT: usize = 5; +const RECORDS: usize = 50; + +/// How an actuator answered a send: the event it made, or why it made none (the refusal's name). +pub(crate) enum Sent { + Posted(String), + Refused(String), +} + +/// The refusal that kept an amendment out of the room, or none when it was made. +pub(crate) type Edited = Option<&'static str>; + +/// What a turn's decision reaches the world through. A refusal is an answer the record keeps, never a fault. +pub(crate) trait Actuator { + /// Say `text` in `room`, replying to the line `in_reply_to` and waking `mentions`, where the actuator carries them. + fn send(&self, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String]) -> Sent; + /// Add `added` to her line `event`. + fn edit(&self, event: &str, added: &str) -> Edited; +} + +/// The mouth as the actuator. `chat_send_request.v2` carries no mentions and no reply link, so her line goes out plain and +/// the receipt records the text that went, not the decision; the mouth has no edit, so an amendment is refused +/// `no_edit_at_the_mouth` and told to her as not amended. Each send is its own transaction, `{key}:s{index}`, so the +/// same turn sent again is the same send. +#[allow(dead_code, reason = "the live drain (map 16.36.5, cut L2) is its first caller")] +pub(crate) struct Mouth<'a> { + pub chat: &'a dyn Chat, + pub persona: String, + pub key: String, + /// The newest event of the room her input held, and when her process began. + pub basis: Option, + pub sent: Cell, +} + +impl Actuator for Mouth<'_> { + fn send(&self, room: &str, text: &str, _in_reply_to: Option<&str>, _mentions: &[String]) -> Sent { + let index = self.sent.replace(self.sent.get() + 1); + let request = ChatSendRequest { request_id: format!("{}:s{index}", self.key), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: self.basis.clone() }; + match self.chat.send(&request) { + Ok(receipt) => match (receipt.event_id, receipt.refusal) { + (_, Some(refusal)) => Sent::Refused(refusal.name().to_owned()), + (Some(event), None) => Sent::Posted(event), + (None, None) => Sent::Refused("no_event".to_owned()), + }, + Err(_) => Sent::Refused("unreachable".to_owned()), + } + } + + fn edit(&self, _event: &str, _added: &str) -> Edited { + Some("no_edit_at_the_mouth") + } +} + +/// One turn taken: what `project` reported, her record of it (the commit's work under `committed`) and her state after it. +pub(crate) struct Taken { + pub report: Value, + pub record: Value, + pub state: Value, +} + +/// One turn: `project` through the Interpreter, each said line through `actuator.send`, each amendment through +/// `actuator.edit`, the record of what happened, and the commit's application of her proposals to her state. `key` names +/// the turn (`-t`). A failed turn sends nothing, amends nothing and applies nothing. +pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime) -> Taken { + let report = project(organs, request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); + let render = &report["renders"][0]; + let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + let here = request.room.clone().unwrap_or_default(); + let mut record = match &failed { + Some(failed) => json!({ "failed": failed }), + None => { + // What she says is the Interpreter's decision alone. + let (mut posted, mut refused_sends, mut edited) = (Vec::new(), Vec::new(), Vec::new()); + for decided in render["interpreter"]["said"].as_array().into_iter().flatten() { + let room = decided["room"].as_str().unwrap_or(&here); + let text = decided["text"].as_str().unwrap_or_default(); + let mentions: Vec = decided["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); + let reply = decided["in_reply_to"]["event"].as_str(); + match actuator.send(room, text, reply, &mentions) { + Sent::Posted(event) => posted.push(json!({ "event": event, "room": room, "text": text })), + Sent::Refused(refusal) => refused_sends.push(match reply { + Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": refusal }), + None => json!({ "room": room, "text": text, "refusal": refusal }), + }), + } + } + for amended in render["interpreter"]["amended"].as_array().into_iter().flatten() { + let event = amended["event"].as_str().unwrap_or_default(); + edited.push(json!({ "event": event, "refusal": actuator.edit(event, amended["added"].as_str().unwrap_or_default()) })); + } + json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited, "refused_sends": refused_sends }) + } + }; + // A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided + // before it went out, and she is told the rest broke off. + if let Some(step) = ["continuation_failed", "later_failed"].into_iter().find(|step| render["interpreter"].get(*step).is_some()) { + record["broke_after"] = json!(step); + } + let (state, applied) = commit::apply(request.state.as_ref().unwrap_or(&Value::Null), &record, key, now); + record["committed"] = json!(applied); + if render["selected"].is_array() { + record["selected"] = render["selected"].clone(); + } + record["at"] = json!(now.to_rfc3339()); + Taken { report, record, state } +} + +/// What her records say of her: her last turn's record, the ids her last projections selected, her last records and +/// when she last woke. The one reader, over a run's list or her trace. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct Past { + pub last_outcome: Option, + pub recent: Vec>, + pub records: Vec, + pub last_wake: Option>, +} + +/// Her `records`, oldest first, read. +pub(crate) fn history(records: &[Value]) -> Past { + let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::>()); + let mut recent: Vec> = records.iter().filter_map(selected).collect(); + recent.drain(..recent.len().saturating_sub(RECENT)); + Past { + last_outcome: records.last().cloned(), + recent, + records: records[records.len().saturating_sub(RECORDS)..].to_vec(), + last_wake: last_wake(records), + } +} + +/// When she last woke: the last record that is no failure. A wake is a turn whose record carries a decision. +pub(crate) fn last_wake(records: &[Value]) -> Option> { + records.iter().rev().find(|record| record.get("failed").is_none()).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs new file mode 100644 index 0000000..b47e0db --- /dev/null +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -0,0 +1,146 @@ +use std::cell::RefCell; + +use anyhow::{Result, bail}; +use chrono::Duration; +use serde_json::json; + +use super::*; +use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal}; +use crate::projection::commit::Applied; +use crate::projection::harness::fixture_request; +use crate::projection::harness::tests::{Scripted, control, harness, room}; +use crate::projection::narrate::PROJECTOR_OPENING; +use crate::projection::outcome::outcome_of; +use crate::projection::select::forms; +use crate::projection::{Answer, Failed, Model, Organs, Through}; + +/// A mouth that records each send and answers it as `answer` says; it does nothing else. +struct FakeChat { + sent: RefCell>, + refusal: Option, +} + +impl FakeChat { + fn new(refusal: Option) -> Self { + Self { sent: RefCell::default(), refusal } + } +} + +impl Chat for FakeChat { + fn pending(&self, _: u64) -> Result { + bail!("a turn reads the room through its organs, not the actuator") + } + fn send(&self, request: &ChatSendRequest) -> Result { + self.sent.borrow_mut().push(request.clone()); + let event_id = self.refusal.is_none().then(|| format!("$sent-{}", self.sent.borrow().len())); + Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id, refusal: self.refusal, newer: vec![] }) + } + fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result { + bail!("a turn opens no conversation") + } + fn fetch(&self, _: &ChatFetchRequest) -> Result { + bail!("a turn fetches nothing") + } + fn ack(&self, _: u64) -> Result<()> { + bail!("a turn acks nothing") + } + fn read(&self, _: &ChatRead) -> Result<()> { + bail!("a turn reports no read") + } +} + +fn mouth(chat: &FakeChat) -> Mouth<'_> { + Mouth { chat, persona: "eureka".into(), key: "run-t1".into(), basis: None, sent: Cell::new(0) } +} + +/// One turn from the operator-warm fixture, she saying one line in reply, through `actuator`. +fn warm_turn(actuator: &dyn Actuator) -> Taken { + let dir = tempfile::tempdir().unwrap(); + let model = Scripted::new(|_| "He smiles at the screen, then types. Missed you too, friend.".into()); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&model)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); + take(&organs, &request, actuator, "run-t1", fixture.now) +} + +#[test] +fn t_l1_mouth_sends_the_text_that_went_and_records_the_receipt() { + let chat = FakeChat::new(None); + let taken = warm_turn(&mouth(&chat)); + let sent = chat.sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!((sent[0].request_id.as_str(), sent[0].persona.as_str(), sent[0].room_alias.as_str(), sent[0].text.as_str()), ("run-t1:s0", "eureka", "!dm-meta:gamecult.org", "Missed you too, friend.")); + assert_eq!(taken.record["posted"], json!([{ "event": "$sent-1", "room": "!dm-meta:gamecult.org", "text": "Missed you too, friend." }])); +} + +#[test] +fn t_l1_mouth_refusal_is_a_refused_send_and_no_posted_row() { + let chat = FakeChat::new(Some(Refusal::RoomMoved)); + let taken = warm_turn(&mouth(&chat)); + assert_eq!(taken.record["posted"], json!([])); + assert_eq!(taken.record["refused_sends"][0]["refusal"], "RoomMoved"); + assert_eq!(taken.record["refused_sends"][0]["text"], "Missed you too, friend."); +} + +#[test] +fn t_l1_mouth_edit_told() { + assert_eq!(mouth(&FakeChat::new(None)).edit("$sent-1", "I could not."), Some("no_edit_at_the_mouth")); + let record = json!({ + "interpreter": { "said": [{ "room": "!r:x", "text": "I will send it." }], "amended": [{ "event": "$sent-1", "added": "I could not.", "room": "!r:x" }] }, + "posted": [{ "event": "$sent-1", "room": "!r:x", "text": "I will send it." }], + "edited": [{ "event": "$sent-1", "refusal": "no_edit_at_the_mouth" }], + "refused_sends": [], + }); + let told = outcome_of(&record).expect("a record she can be told of"); + let told = told.lines(forms(&control())).join("\n"); + assert!(told.contains("a line cannot be added to once it is said here"), "{told}"); + assert!(told.contains("Nothing changed"), "{told}"); +} + +struct FailingPersona; + +impl Model for FailingPersona { + fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { + if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: None }) } + } +} + +#[test] +fn t_l1_failed_turn_record() { + let dir = tempfile::tempdir().unwrap(); + let chat = FakeChat::new(None); + let fixture = room("operator-warm.toml"); + let harness = harness(dir.path(), None, Some(&FailingPersona)); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; + let state = control(); + let request = fixture_request(&harness, &fixture, Some(state.clone()), 3, Some(1), Through::Interpreter); + let taken = take(&organs, &request, &mouth(&chat), "run-t1", fixture.now); + assert!(chat.sent.borrow().is_empty(), "a failed turn sends nothing"); + assert_eq!(taken.record["failed"].as_str(), Some("the provider failed the call: Overloaded")); + let mut keys: Vec<&str> = taken.record.as_object().unwrap().keys().map(String::as_str).collect(); + keys.retain(|key| !matches!(*key, "selected" | "at" | "committed")); + assert_eq!(keys, ["failed"], "the record holds the failure alone beside what every record carries"); + assert_eq!(taken.state, state, "a failed turn applies nothing"); + assert_eq!(taken.record["committed"], json!(Applied::default())); +} + +#[test] +fn t_l1_history_from_records() { + let at = |minute: i64| (chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339(); + let turn = |minute: i64, ids: &[&str]| json!({ "interpreter": {}, "selected": ids, "at": at(minute) }); + let mut records: Vec = (0..7).map(|at| turn(at, &[&format!("m{at}")])).collect(); + assert_eq!(history(&[]), Past::default()); + let past = history(&records); + assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first"); + assert_eq!(past.last_outcome.as_ref(), records.last()); + assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6))); + records.push(json!({ "failed": "Overloaded", "selected": ["m7"], "at": at(7) })); + let past = history(&records); + assert_eq!(past.last_outcome.as_ref().map(|last| last["failed"].clone()), Some(json!("Overloaded")), "her last outcome is the failure"); + assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed turn is no wake"); + assert_eq!(past.recent.last(), Some(&vec!["m7".to_owned()]), "a failed turn still showed what it selected"); + let long: Vec = (0..60).map(|at| turn(at, &[])).collect(); + assert_eq!(history(&long).records.len(), 50); + assert_eq!(history(&long).records[0]["at"], json!(at(10)), "her last fifty, oldest first"); +} diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 1cd8d5b..3d85d43 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -230,11 +230,10 @@ mind_body::persona: impl FileTrace: fn new (path : impl Into < PathBuf >) -> Sel mind_body::persona: impl Sender mind_body::persona: impl Trace for FileTrace mind_body::persona: impl fmt :: Display for Outcome -mind_body::persona: pub trait Trace { fn record (& self , trace : & TurnTrace) -> Result < () > ; } +mind_body::persona: pub trait Trace { fn record (& self , key : & str , record : & Value) -> Result < () > ; 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 FileTrace pub-fields[] -mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String] -mind_body::persona: struct TurnTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[run: String, turn: u32, at: DateTime < Utc >, inputs: Vec < TraceItem >, outputs: Vec < TraceItem >, outcome: String] +mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value] mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , Interpreter , } mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value > mind_body::projection: impl Affordance @@ -332,6 +331,7 @@ mind_body::projection::select: impl Section mind_body::projection::select: impl std :: fmt :: Display for Who mind_body::projection::select: impl< 'a > Inputs < 'a > mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String > +mind_body::projection::simulate: impl Actuator for SimRoom < '_ > mind_body::projection::simulate: impl HeartbeatView for Names < '_ > mind_body::projection::simulate: impl MouthReader for View < '_ > mind_body::projection::simulate: impl ReadSource for CastReads < '_ > @@ -354,6 +354,7 @@ mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , Partia mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize] mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >] +mind_body::projection::turn: impl Actuator for Mouth < '_ > mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held > mind_body::queue: impl Held mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool diff --git a/docs/eureka-body-map.md b/docs/eureka-body-map.md index 81462a5..1eeeed3 100644 --- a/docs/eureka-body-map.md +++ b/docs/eureka-body-map.md @@ -137,7 +137,7 @@ Nothing that acts for a Persona writes her Mind. Since C1 the host enforces that | Heartbeat (`mind-heartbeat.service`; `heartbeat.rs`, `tempo.rs`, `bin/mind-heartbeat.rs`) | Huginn `mind-body`. The one process deciding which Persona wakes and when. Sole writer of `heartbeat.cc`. | Swarm envelope and each Persona's brake (`read_effective`); each Persona's pending chat from Bifrost's mouth (`chat.pending`, read only, never acked, at most 16 pages); the unit table through `Launcher::alive`; `stewardships_of` on her Mind; `HEARTBEAT_PERSONAS`, `MIND_PERSONA_OPERATOR`, `HEARTBEAT_POLL_S` (20), `HEARTBEAT_BEAT_S` (1800), `BIFROST_CHAT_ENDPOINT`, `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY`. It holds no connector key. | `systemctl start mind-persona@` through `SystemdLauncher`; `heartbeat.cc` (state, addressing table, poll traces). No run, no brief, no Self-run launch. | Off the beat: the operator, or another Mind of the roster, naming her wakes her once per message (`handled_mentions`, 64 kept). On the beat: when `beat_s` has passed since `last_beat_at`, `tempo::pick` over idle, released Minds by wait since the heartbeat last woke each, bent by a member addressing her. Busy is systemd's: an active unit is busy and a start is a no-op. | Her Mind (a Persona wake is a unit start); `heartbeat.cc` by anything but the heartbeat; the brakes. | `heartbeat.cc` under the unit's `STATE_DIRECTORY`, world-readable: Personas read the addressing table through `HeartbeatView`. `mind-heartbeat timeline` prints the latest poll. | C2 deleted the claimable-brief and Self-run branch, tempo votes and the PID fallback (`tally`, `fallback_beat`), the urgency pulse, `sleep.rs` (no night wake until C4) and `attachment.rs`. It kept `tempo::pick` and `score`. `vote_beat_s` in `InstanceTrace` is retired and always none, kept so old trace records decode. A `heartbeat.cc` holding an older document is refused by name and never migrated. | `heartbeat/tests.rs`: `a_mind_whose_self_holds_briefs_gets_a_persona_wake_and_no_self_run`, `no_poll_admits_anything_to_any_mind_whatever_it_wakes`, the mention and beat tests. | | Self-run actuator (`mind-self@`; `self_run.rs`, `bin/mind-self-run.rs`) | Huginn `mind-body`. Carries the one in-force Self run of its instance. | The run document (the grant), the lease socket, the Mind, the clock. | One `claude` child, its flush, its stop. | Request prefix, session id (UUIDv5 of the run id), kept transcript. | Nothing launches it. `launch::open_and_launch`, the work queue and the repetition breaker are gone (tag `parked/self-run-launch`). No organ opens a Self run, so `mind-self-run` with no open run exits 3. | The run slot in the Mind; `/var/lib/gamecult/minds//` state. | Left in place on purpose (C2 keep list): C3b's Interpreter reuses its spawn and sandbox and `lease_client`. `inbox` still reads briefs admitted by agent `mind-persona`; nothing admits them now. | `tests/self_run.rs` (ignored lane: the real binary against the real daemon with a fake `claude`); `self_run/tests.rs`. | | Persona state (`gamecult.persona_state.v0`, one per mind, `personaId` = instance) | The Persona. No organ of Huginn writes it today. Target writers (ruling `persona-only-state-writers-self-and-life`): her commit step (C3c), and Self and Life on Starfire through `mind-persona edit`. | `PersonaGet`, `PersonaPut` on the daemon. | A receipt per put. | None stored. | The Projector, the Persona stage and the Interpreter never put. A raw `huginn persona put` is detected and recorded `unexplained`, not sanctioned. | The Mind store; reached by `PersonaGet` and `PersonaPut` at the persona door (C1, live), the only listener a Persona uid can reach. | `huginn-mind/src/persona.rs` keeps the document and its CAS. C2 removed the organ that was its only writer. | `huginn-mind` persona tests; `serve.rs` tests that the persona door answers her persona and refuses `Admit`. | -| Persona turn trace (`eureka.persona.turn_trace.v1`, `FileTrace`) | The Persona organ, when C3 lands. | Nothing writes it today. | None. | None. | Any Mind writer; any model. | The unit's state directory. | Kept for C3c (trace v2 with `outside_put` and `tuning_changed`). Deltas are read from it over ssh (`persona-only-deltas-from-trace`). | `persona/tests.rs` `the_trace_store_keeps_each_turn_under_its_run_and_turn`. | +| Persona turn trace (`eureka.persona.turn_record.v1`, `FileTrace`: the turn record itself, the shape `outcome_of` reads) | The Persona organ, when C3 lands. | Nothing writes it today. | None. | None. | Any Mind writer; any model. | The unit's state directory. | Kept for C3c (the record gains `outside_put` and `tuning_changed`). Deltas are read from it over ssh (`persona-only-deltas-from-trace`). | `persona/tests.rs` `the_trace_store_keeps_each_record_under_its_key_and_lists_them_oldest_first`. | | Brake and the stop on hold | Operator. `mind-control brake hold` writes the brake, then stops the instance's units. | The operator's word. | `control.cc`; a blocking `systemctl stop`. | `read_effective` is the one reader. | Every organ of hers. | `/etc/gamecult/minds//`, `swarm.cc`. | `StopScope` still names three templates: `mind-self@`, `mind-persona@` and `mind-stream@`. The stream organ is parked; its unit name stays on the stop list so a host that still has it installed is stopped. | `tests/cli.rs` and the `launch.rs` stop tests (they spell `mind-stream@`). | | Parked and deleted organs | Tags on the forge, not main. | n/a | n/a | n/a | Main must not regrow them without a ruling. | n/a | `parked/divergence-stream` holds `stream.rs` and `bin/mind-stream` (ruling `persona-only-divergence-parked`; return condition: measured narrations converge, judged by the eval of the design map's section 3.4; its Projector code is reused by C3a). `parked/self-run-launch` holds `open_and_launch`, the work queue and its breaker (a future spend owner may restore Self runs on address). `sleep.rs` and `attachment.rs` are deleted, not parked: consolidation returns in C4 as a retarget onto `thoughtMemory`. | The C2 negative greps: `start_self_run`, `WORK_QUESTION`, `WAKE_ASK`, `TURN_INSTRUCTION`, `Pulse`, `tempo_vote` absent from `crates/mind-body/src`. | @@ -607,7 +607,7 @@ pipeline kinds are in Huginn `docs/eureka-substrate-map.md`. | Connector request and transcript items | Request: `(caller_runtime_id, request_id)`, the replay key the daemon already keeps (`replay.cc`). Items: UserText, AssistantText, ToolCall, ToolResult, plus `ReasoningState { provider, model, opaque }` (ruling `connector-opaque-state-item`). Contract ids become provider-neutral `gamecult.model.*.v3` (follow-up `connector-contract-untyped`); the connector serves Ghostlight too, so not `eureka.*`. | Invocation expires at `expires_at_unix_ms`; replay record per key; restart-era `Indeterminate`. The caller stores the transcript and replays it verbatim; foreign-tagged reasoning state inside an in-flight tool exchange is refused typed; completed-turn foreign state is settled per provider in the connector cut (follow-up `connector-reasoning-state-cheap-providers`). | The connector produces, reads or refuses reasoning bytes; callers never branch on provider. | | Connector spend ledger | The reservation lives in the replay record itself (cut connector-spend, F33): integer micro-USD, windowed per caller (ruling `connector-spend-caller-window-ceiling`). | Reserve before the provider runs, settle to actual; refusals `CostBound` (the invocation's own `max_cost_micro_usd`) and `SpendCeiling` (the caller's window); a ledger that cannot be written refuses the request. | The kit's `ProviderCall::charge` is the one billing owner; a backend reports usage or `None` (bills the reservation). The root caller config sets the ceiling. | | Claude connector backend (B4a, landed `200933f`; the Persona does not use this backend, it borrows a lease like the Self) | `ClaudeCodeBackend` in `crates/claude-connector`, provider tag `claude-code`: one `claude -p` child per call in its own process group, tool-less, system prompt in a private temp file; reasoning state is a named-MessagePack `ClaudeCodeHandle { session_id, instance, prefix_sha256 }`; usage is `model_usage_since_last_result` summed over models, in list-price units from B4b's price table (ruling `claude-code-plan-quota-fuse-2`). | A handle resumes (always `--fork-session`) only when it decodes, names this instance, its session file exists and its digest matches the request's instructions, model and earlier items; anything else re-seeds from the caller's transcript (ruling `claude-code-handle-reseeds`). The CLI's session store under `config_dir` is a cache; the caller's transcript is the truth. A refusal at the door with explicitly empty usage bills zero; unknown usage, a crash or a deadline bills the reservation. | The backend owns the argv, env, process and stream mapping. It never reads `total_cost_usd`, never forwards `ANTHROPIC_API_KEY`, never retries, never spawns twice per execute. Forbidden: `--bare`, `--fallback-model`, `--mcp-config` and `--dangerously-skip-permissions` (B4d changes the MCP line, by spec). Her organs hold none of it: the subscription token lives in the connector's own environment. | -| Persona turn traces | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** `FileTrace` exists; nothing writes it until C3c. **Empty: question `persona-trace-retention`.** Candidate: per turn, the request digest, the transcript items and the typed output, keyed by the turn's run. | Empty: how long they are kept, whether Discord-sourced content may enter a training export (F14). | Empty: who may export them. Unconfirmed 2026-11-02: `FileTrace`/`TurnTrace` exist in `persona.rs`; whether they are the retention answer is not checked against the question's state. | +| Persona turn traces | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** `FileTrace` exists; nothing writes it until C3c. **Empty: question `persona-trace-retention`.** Candidate: per turn, the request digest, the transcript items and the typed output, keyed by the turn's run. | Empty: how long they are kept, whether Discord-sourced content may enter a training export (F14). | Empty: who may export them. Unconfirmed 2026-11-02: `FileTrace` exists in `persona.rs`; whether they are the retention answer is not checked against the question's state. | | Persona state | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No organ writes it; target writers are her commit step, Self and Life (`persona-only-state-writers-self-and-life`). `gamecult.persona_state.v0`, one per mind, `personaId` = instance (cut-huginn-persona-state r2, eureka-substrate). | Replaced whole under CAS with a receipt; she may rewrite any field (`identity-write-all-visible`). | The Persona organ is the only writer. | | Persona session | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** No `claude` session runs in `mind-persona@`; the organ is inert. The three-stage turn replaces it (C3). Process `claude` under bwrap in `mind-persona@`; id uuid5(run, `p`); one conversation per process | Ends at cache TTL, near the 4 h cap minus `ROTATE_MARGIN_S`, at the context ceiling's flush, or when another conversation's delivery is the oldest unanswered; next process rehydrates from the mind | The Persona organ (lifetime, input, acks); the mind is truth; heartbeat only starts units | | Persona sandbox | **Superseded by C2 (Huginn `66b85c8`; see "The persona-only body").** Nothing writes it now; C3b decides the Interpreter's sandbox. `/var/lib/mind-/sandbox` | Kept between processes; the only place her tools write (besides the fresh config dir) | Her; nobody else reads it. Not a source of truth for anything. |