persona: a line is said to her only when it is not for another Mind; the simulator runs the drain's Interpreter step

A human's line in her own room wakes her but was headed 'Said to her' even when it named, tagged or replied to another Mind
(address::others_addressed, the one derivation, also behind persona::addressees). The Interpreter's call, apply and put move
to projection::interpret (heard_of, interpret_and_put, put_applied) so the drain and the simulator take the same step; the
simulator runs it after each wake on an in-run copy of her state and reports deltas by family, intentions, identity changes
and guard refusals per wake, and its header no longer claims a speech or a state commit it did not run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-01 16:16:18 +01:00
commit 50852da101
8 changed files with 400 additions and 205 deletions

View file

@ -63,6 +63,28 @@ pub(crate) fn is_for(own: &Addressee, delivery: &ChatDelivery) -> bool {
(delivery.form == Form::Message && (delivery.is_direct || matches!(delivery.basis, Some(Basis::Direct | Basis::Tag | Basis::Reply | Basis::FollowUp)))) || addresses(own, delivery)
}
/// The other Minds a delivery is for, by Matrix id: those its mentions hold, those of `roster` it names (`addresses`), and the
/// sender of the line it replies to when that is neither `own` nor the sender (a reply answers someone). The one derivation of
/// who else a line is for; a line that is for `own` too is still for her (`is_for`), and one that is for others and not her is
/// said in her room, not to her.
pub(crate) fn others_addressed<'a>(own: &Addressee, roster: &'a [Addressee], delivery: &'a ChatDelivery) -> Vec<&'a str> {
let mut ids: Vec<&str> = delivery.mentions.iter().map(String::as_str).filter(|id| *id != own.matrix_id() && *id != delivery.sender).collect();
for row in roster {
let id = row.matrix_id();
if id != own.matrix_id() && id != delivery.sender && !ids.contains(&id) && addresses(row, delivery) {
ids.push(id);
}
}
if let Some(quote) = delivery.reply_to.quote()
&& quote.sender != own.matrix_id()
&& quote.sender != delivery.sender
&& !ids.contains(&quote.sender.as_str())
{
ids.push(quote.sender.as_str());
}
ids
}
/// The chat names of one stewarded repo. Listed names are exactly those, each matched exactly as the steward wrote it (capitalization
/// tells a project from a common word). With none listed: the repo's name after the org, matched exactly as the repo spells it
/// (`Thing`, not `thing`), and that name split at `-`, `_`, `.` and where a lower-case letter or digit meets a capital, when the split

View file

@ -21,7 +21,7 @@
//! 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.
//!
//! After a completed agent turn, the Interpreter reads her monologue and its deltas are put once (`put_applied`) under the `updatedAt` she was read
//! After a completed agent turn, the Interpreter reads her monologue and its deltas are put once (`interpret::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.
//! Her agent acts from the same stream, never from the Interpreter's output (map 16.38.12). An Interpreter that fails after the agent acted fails nothing: its receipt says error and her state does not move. A failure of her agent's turn fails the
//! wake as any stage's does: an outage the connector typed (unavailable, timed out, rate-limited, refused for her credit) strikes nothing.
@ -40,11 +40,10 @@ 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::address::{Addressee, is_for, localpart, others_addressed};
use crate::chat_client::{Basis, Chat, ChatDelivery, Form, TailLine};
use crate::control::{ControlSource, Effective, HeldReason, derive};
use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes};
@ -53,7 +52,7 @@ use crate::projection::agent::request_tool::RequestTool;
use crate::projection::agent::say::{Say, Sent};
use crate::projection::agent::shell::Shell;
use crate::projection::agent::{Agent, Ended, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, Heard, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, decided, failed as record_failed, history, interpret, is_wake, load_tuning, people_named, settle_handed, wake, own_addressee as heard_as};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, 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";
@ -640,17 +639,8 @@ fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked:
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 held_lines = deliveries.iter().filter(|delivery| held.contains(&delivery.event_id.as_str()) && delivery.sender != config.own_sender).map(|delivery| delivery.text.clone());
let heard = heard_of(state, &waked.report["packet"], room, held_lines, &config.operators, &config.minds, config.review_room.is_some(), narration, prose);
// A row takes its place in her trace when it is first written, and keeps it when it is rewritten.
let row = |body: Value| {
let mut row = json!({ "seq": place(&*start.trace), "at": now.to_rfc3339(), "wake": stem });
@ -662,55 +652,50 @@ fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked:
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)) => {
// The diff is written to her trace before each put, so a change is never put that nothing recorded to show: the record
// the last attempt wrote, or void when a later attempt had no identity change.
let diff_key = format!("{stem}-d");
let written: RefCell<Option<Value>> = RefCell::new(None);
let ahead = |applied: &Applied| -> std::result::Result<(), String> {
let earlier = written.borrow().clone();
let record = match (identity_record(config, instance, applied, &diff_key), earlier) {
(Some(mut record), Some(earlier)) => {
record["seq"] = earlier["seq"].clone();
record["at"] = earlier["at"].clone();
record["wake"] = json!(stem);
record
}
(Some(record), None) => row(record),
(None, Some(mut earlier)) => {
earlier["status"] = json!("void");
earlier
}
(None, None) => return Ok(()),
};
start.trace.record(&diff_key, &record).map_err(|fault| format!("the identity change was not recorded first, so nothing was put: {fault:#}"))?;
*written.borrow_mut() = Some(record);
Ok(())
};
match put_applied(&*start.persona, state, &Taken { deltas: &deltas, heard: &heard, instance }, stem, now, &*start.clock, &ahead) {
Ok(landed) => {
if let Some(record) = written.borrow().clone().filter(|record| record["status"] == "pending") {
post_identity(start, mouth, record);
}
json!({ "kind": "interpreter", "status": "ok", "put": landed.put, "applied": landed.applied.changes, "refused": landed.applied.refused, "pruned": landed.applied.pruned, "usage": usage })
}
Err(missed) => {
// A put whose reply was lost may have committed: its record stays pending, and the next wake's `owed_identity`
// settles it from her state. Only a put known not to have landed is voided.
if let Some(mut record) = written.borrow().clone().filter(|record| record["status"] == "pending" && !missed.unknown) {
record["status"] = json!("void");
if let Err(fault) = start.trace.record(&diff_key, &record) {
eprintln!("mind-persona: the identity record {diff_key} was not voided: {fault:#}");
}
}
json!({ "kind": "interpreter", "status": "error", "put": "refused", "error": missed.why, "applied": missed.applied.changes, "refused": missed.applied.refused, "usage": usage, "put_refused": true })
// The diff is written to her trace before each put, so a change is never put that nothing recorded to show: the record
// the last attempt wrote, or void when a later attempt had no identity change.
let diff_key = format!("{stem}-d");
let written: RefCell<Option<Value>> = RefCell::new(None);
let ahead = |applied: &Applied| -> std::result::Result<(), String> {
let earlier = written.borrow().clone();
let record = match (identity_record(config, instance, applied, &diff_key), earlier) {
(Some(mut record), Some(earlier)) => {
record["seq"] = earlier["seq"].clone();
record["at"] = earlier["at"].clone();
record["wake"] = json!(stem);
record
}
(Some(record), None) => row(record),
(None, Some(mut earlier)) => {
earlier["status"] = json!("void");
earlier
}
(None, None) => return Ok(()),
};
start.trace.record(&diff_key, &record).map_err(|fault| format!("the identity change was not recorded first, so nothing was put: {fault:#}"))?;
*written.borrow_mut() = Some(record);
Ok(())
};
let made = interpret_and_put(start.model.as_ref(), &model, &request, &*start.persona, instance, state, &heard, narration, prose, stem, now, &*start.clock, &ahead);
match &made.put {
Some(Ok(_)) => {
if let Some(record) = written.borrow().clone().filter(|record| record["status"] == "pending") {
post_identity(start, mouth, record);
}
}
// A put whose reply was lost may have committed: its record stays pending, and the next wake's `owed_identity`
// settles it from her state. Only a put known not to have landed is voided.
Some(Err(missed)) => {
if let Some(mut record) = written.borrow().clone().filter(|record| record["status"] == "pending" && !missed.unknown) {
record["status"] = json!("void");
if let Err(fault) = start.trace.record(&diff_key, &record) {
eprintln!("mind-persona: the identity record {diff_key} was not voided: {fault:#}");
}
}
}
};
if let Err(fault) = start.trace.record(&format!("{stem}-i"), &row(receipt)) {
None => {}
}
if let Err(fault) = start.trace.record(&format!("{stem}-i"), &row(made.row)) {
eprintln!("mind-persona: the Interpreter's receipt was not appended: {fault:#}");
}
}
@ -809,63 +794,6 @@ fn speaker(config: &Config, delivery: &ChatDelivery) -> Speaker {
}
}
/// The `updatedAt` a put carries: the time of the put, and strictly later than the one stored, which the daemon requires
/// (P5). A write by Self or Life during her turn is stamped after the turn began, so the turn's own start time would be
/// refused.
fn stamp_after(now: DateTime<Utc>, stored: Option<&str>) -> String {
let floor = stored.and_then(|text| DateTime::parse_from_rfc3339(text).ok()).map(|at| at.with_timezone(&Utc) + chrono::Duration::milliseconds(1));
floor.map_or(now, |floor| now.max(floor)).to_rfc3339()
}
/// 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 put's own call failed, so whether the store committed is not known; a refusal or a stale answer is known not to have.
pub unknown: bool,
}
/// 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<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> std::result::Result<Landed, Missed> {
let attempt = |from: &Value| -> (std::result::Result<Value, String>, 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, applied) = attempt(read);
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => return Ok(Landed { applied, put: "committed" }),
Ok(Put::Stale) => {}
Ok(Put::Refused(why)) => return Err(Missed { applied, why, unknown: false }),
Err(fault) => return Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
}
let (fresh, _) = store.persona().map_err(|fault| Missed { applied: applied.clone(), why: format!("her state was not read again: {fault:#}"), unknown: false })?;
let (next, applied) = attempt(&fresh);
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => Ok(Landed { applied, put: "stale_reapplied" }),
Ok(Put::Stale) => Err(Missed { applied, why: "stale again".to_owned(), unknown: false }),
Ok(Put::Refused(why)) => Err(Missed { applied, why, unknown: false }),
Err(fault) => Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
}
}
/// The newest `last` records of her trace as JSON lines, oldest first. Read-only.
pub fn trace_lines(trace: &dyn TraceView, last: usize) -> Result<Vec<String>> {
let records = trace.records()?;
@ -913,13 +841,7 @@ struct Addressees {
#[allow(dead_code, reason = "kept for the three-stage turn (map C2 keep list): its first caller removes this allow")]
fn addressees(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery, names: &BTreeMap<&str, &str>) -> Addressees {
let to_you = is_for(own, delivery);
let mut ids: Vec<&str> = delivery.mentions.iter().map(String::as_str).filter(|id| *id != own.matrix_id()).collect();
for row in addressing {
let id = row.matrix_id();
if id != own.matrix_id() && id != delivery.sender && !ids.contains(&id) && addresses(row, delivery) {
ids.push(id);
}
}
let ids = others_addressed(own, addressing, delivery);
Addressees { to_you, others: ids.into_iter().map(|id| names.get(id).copied().unwrap_or(id).to_string()).collect() }
}

View file

@ -17,7 +17,7 @@ use model_connector::{InputItem, StopReason};
use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, ChatSendRequest, Form, Refusal};
use crate::control::{ControlWriter, FileSource, SwarmWriter};
use crate::projection::harness::tests::{Scripted, control};
use crate::projection::{Answer, Failed, PersonaSource, Spent, StepRequest, Stepped, ToolCall, failed_run, is_wake};
use crate::projection::{Answer, Failed, Heard, PersonaSource, Spent, StepRequest, Stepped, Taken, ToolCall, failed_run, is_wake, put_applied};
use crate::testkit::at;
const META: &str = "@meta:gamecult.org";

View file

@ -43,7 +43,7 @@ use eureka_state::HuginnClient;
use huginn_mind::HuginnMindResponse;
use serde_json::{Value, json};
use crate::address::{Addressee, is_for, localpart};
use crate::address::{Addressee, is_for, localpart, others_addressed};
use crate::chat_client::{Chat, ChatPending, Form, ReplyLink};
use crate::heartbeat::HeartbeatView;
@ -52,7 +52,7 @@ pub use narrate::{Answer, Failed, KitModel, Model, Spent, StepRequest, Stepped,
pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
pub use select::TurnKind;
pub(crate) use commit::{Applied, Heard, apply as apply_commit};
pub(crate) use interpret::{deltas as interpret, people as people_named};
pub(crate) use interpret::{heard_of, interpret_and_put, put_applied};
pub(crate) use turn::{DAY_CAP_HOLD, Taken, decided, failed, failed_run, history, is_wake};
pub(crate) use agent::say::{Mouth, settle_handed};
pub(crate) use wake::{Fault, Waked, wake};
@ -285,9 +285,21 @@ fn read_domain(source: Option<&dyn DomainSource>, last_wake: Option<DateTime<Utc
}
}
/// The other Minds of the swarm as her room names them: the heartbeat's row for each Mind of the request when its table holds one,
/// else the Mind by her Matrix id and localpart (`address::others_addressed` reads who a line is for from these). Not her.
fn roster_of(addressing: Option<&dyn HeartbeatView>, request: &Request, own: &Addressee) -> Vec<Addressee> {
let table = addressing.and_then(|view| view.addressing().ok().flatten()).map(|table| table.minds).unwrap_or_default();
request
.minds
.iter()
.filter(|id| id.as_str() != own.matrix_id())
.map(|id| table.iter().find(|row| row.matrix_id() == id).cloned().unwrap_or_else(|| Addressee::new(id, [localpart(id)])))
.collect()
}
/// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the
/// Select stage to drop. A refusal is reported, never hidden.
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) {
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee, roster: &[Addressee]) -> (Room, Value) {
let pending = match chat.pending() {
Ok(pending) => pending,
Err(fault) => return (Room { here: request.rooms.first().cloned(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })),
@ -308,11 +320,15 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo
display: delivery.sender_display.clone(),
text: delivery.text.clone(),
at_ms: delivery.at_unix_ms,
// The heartbeat's rule, the one that woke her: never a second opinion here. A human's line in
// her own room always wakes her, so it is to her, as a direct message is (the plan's or unit's `own_rooms`), and so
// is a line the heartbeat woke her for (an open hello she was picked to answer: `woken_for`).
// The heartbeat's rule, the one that woke her: never a second opinion here. A line that is for her (`is_for`) is to her.
// A human's line in her own room always wakes her (the plan's or unit's `own_rooms`), and so does a line the heartbeat
// woke her for (an open hello she was picked to answer: `woken_for`); it is to her unless it is for another Mind
// (`others_addressed`), when it is said in her room and not to her.
to_her: is_for(own, delivery)
|| (delivery.sender != request.own_sender && !request.minds.contains(&delivery.sender) && (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))),
|| (delivery.sender != request.own_sender
&& !request.minds.contains(&delivery.sender)
&& (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))
&& others_addressed(own, roster, delivery).is_empty()),
event: delivery.event_id.clone(),
reply: replied(&delivery.reply_to),
})
@ -460,7 +476,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned();
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
let (room, room_report) = match organs.chat {
Some(chat) => read_room(chat, request, &own),
Some(chat) => read_room(chat, request, &own, &roster_of(organs.addressing, request, &own)),
None => (Room { here: request.rooms.first().cloned(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })),
};
let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender };

View file

@ -4,11 +4,16 @@
//! 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 chrono::{DateTime, Utc};
use eureka_pipeline::Slug;
use huginn_mind::persona::validate_document;
use serde_json::{Value, json};
use super::commit::{Deltas, Heard};
use super::commit::{Applied, Deltas, Heard, apply as apply_commit};
use super::narrate::{Failed, Model, Spent};
use super::select::{clip, forms, text, voiced};
use super::turn::Taken;
use super::{PersonaStore, Put};
/// What the index shows of one item's words.
const ITEM_BYTES: usize = 240;
@ -137,5 +142,105 @@ pub(crate) fn deltas(model: &dyn Model, model_name: &str, request_id: &str, stat
}
}
/// The `updatedAt` a put carries: the time of the put, and strictly later than the one stored, which the daemon requires
/// (P5). A write by Self or Life during her turn is stamped after the turn began, so the turn's own start time would be
/// refused.
fn stamp_after(now: DateTime<Utc>, stored: Option<&str>) -> String {
let floor = stored.and_then(|text| DateTime::parse_from_rfc3339(text).ok()).map(|at| at.with_timezone(&Utc) + chrono::Duration::milliseconds(1));
floor.map_or(now, |floor| now.max(floor)).to_rfc3339()
}
/// 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 put's own call failed, so whether the store committed is not known; a refusal or a stale answer is known not to have.
pub unknown: bool,
}
/// 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.
pub(crate) fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> std::result::Result<Landed, Missed> {
let attempt = |from: &Value| -> (std::result::Result<Value, String>, 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, applied) = attempt(read);
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => return Ok(Landed { applied, put: "committed" }),
Ok(Put::Stale) => {}
Ok(Put::Refused(why)) => return Err(Missed { applied, why, unknown: false }),
Err(fault) => return Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
}
let (fresh, _) = store.persona().map_err(|fault| Missed { applied: applied.clone(), why: format!("her state was not read again: {fault:#}"), unknown: false })?;
let (next, applied) = attempt(&fresh);
let next = next.map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why, unknown: false })?;
match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => Ok(Landed { applied, put: "stale_reapplied" }),
Ok(Put::Stale) => Err(Missed { applied, why: "stale again".to_owned(), unknown: false }),
Ok(Put::Refused(why)) => Err(Missed { applied, why, unknown: false }),
Err(fault) => Err(Missed { applied, why: format!("{fault:#}"), unknown: true }),
}
}
/// What the Interpreter hears of a wake (`Heard`): the wake's room, the bodies of the lines her packet showed and any held lines
/// the caller adds, and the people present or named. The one derivation, the drain's and the simulator's alike.
#[allow(clippy::too_many_arguments)]
pub(crate) fn heard_of(state: &Value, packet: &Value, room: &str, held: impl IntoIterator<Item = String>, operators: &[String], minds: &[String], identity_visible: bool, narration: &str, prose: &str) -> Heard {
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(held).collect(),
people: vec![],
operators: operators.to_vec(),
minds: minds.to_vec(),
identity_visible,
};
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(state, &heard, narration, prose);
heard
}
/// One Interpreter step: the call over her narration and prose, its deltas applied and put once through `store` (`put_applied`),
/// and the receipt row's body. `put` is none when the call gave no deltas, so nothing was put. The drain writes the row to her
/// trace and posts an identity change; the simulator reports it and keeps the state its store holds.
#[allow(clippy::too_many_arguments)]
pub(crate) fn interpret_and_put(model: &dyn Model, model_name: &str, request: &str, store: &dyn PersonaStore, instance: &Slug, state: &Value, heard: &Heard, narration: &str, prose: &str, stem: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> Interpreted {
match deltas(model, model_name, request, state, heard, narration, prose) {
Err(failed) => Interpreted { row: json!({ "kind": "interpreter", "status": "error", "put": "none", "error": failed.reason, "usage": failed.usage, "put_refused": true }), put: None },
Ok((deltas, usage)) => {
let put = put_applied(store, state, &Taken { deltas: &deltas, heard, instance }, stem, now, clock, ahead);
let row = match &put {
Ok(landed) => 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 }),
};
Interpreted { row, put: Some(put) }
}
}
}
/// What `interpret_and_put` made.
pub(crate) struct Interpreted {
pub row: Value,
pub put: Option<std::result::Result<Landed, Missed>>,
}
#[cfg(test)]
mod tests;

View file

@ -1,6 +1,8 @@
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn
//! one `project` through the Persona stage, and each one's drafts the Interpreter sends join the room as from her Matrix id, so the
//! next one hears them.
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn one
//! wake (`wake`: the Projector and the Persona) and then the Interpreter step the drain takes after a completed wake
//! (`interpret_and_put`: one call over her narration and prose, its deltas applied and put once), against that Mind's in-run
//! copy of her state. Nothing speaks in a wake (her agent does, and none runs here), so the room holds only the script's lines;
//! the report counts what the Interpreter changed instead.
//!
//! Who wakes is the heartbeat's: `heartbeat::wakes` over each persona's addressee as the
//! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The
@ -12,17 +14,14 @@
//! 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 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
//! what she is told 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;
//! every view after it shows the replied line, with who said it, above hers.
//! What came of each of her turns opens her next packet (map 16.16): the run keeps each turn's record and the Interpreter's
//! receipt row, as her trace live, and her next turn reads what she is told from them (`turn::history`); a failed turn's
//! record is a failure, and an Interpreter that kept nothing is told as not kept.
//!
//! Her state moves during a run only by the commit's applier (`commit::apply`, map 16.35.3), on each Mind's in-run copy,
//! 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.
//! Her state moves during a run only by the Interpreter's deltas, applied by the commit's applier (`commit::apply`) and put to
//! her in-run copy (`InRun`, which refuses a stale put as the daemon does), as the drain puts them live. The review room
//! is taken as named, so identity changes are made as they would be where people see them; nothing is posted. The report
//! lists per wake the deltas by family, the intentions added or readied, the identity changes and what the guards refused.
use std::cell::RefCell;
use std::collections::BTreeMap;
@ -31,6 +30,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use chrono::{DateTime, Duration, Utc};
use eureka_pipeline::Slug;
use serde::Deserialize;
use serde_json::{Value, json};
@ -41,7 +41,7 @@ use super::select::Draw;
use super::tuning;
use super::turn::{history, last_wake};
use super::wake;
use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind};
use super::{DomainFacts, DomainSource, MouthReader, Organs, PersonaSource, PersonaStore, Put, ReadFixture, ReadSource, Request, Through, TurnKind, heard_of, interpret_and_put};
use crate::address::{Addressee, is_for, localpart};
use crate::chat_client::ChatPending;
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, claimed, floor_to, line_facts, wakes};
@ -170,14 +170,51 @@ impl MouthReader for View<'_> {
}
}
struct Names<'a>(&'a Addressee);
struct Names<'a>(&'a [Addressee]);
impl HeartbeatView for Names<'_> {
fn addressing(&self) -> Result<Option<Addressing>> {
Ok(Some(Addressing { minds: vec![self.0.clone()] }))
Ok(Some(Addressing { minds: self.0.to_vec() }))
}
}
/// One Mind's state in one run: the copy the Interpreter's put changes, refusing a put under a stale `updatedAt` as the daemon does.
struct InRun(RefCell<Value>);
impl PersonaSource for InRun {
fn persona(&self) -> Result<(Value, String)> {
let state = self.0.borrow().clone();
let receipt = state["updatedAt"].as_str().unwrap_or_default().to_owned();
Ok((state, receipt))
}
}
impl PersonaStore for InRun {
fn put(&self, state: &Value, expected_updated_at: Option<&str>, _session: &str) -> Result<Put> {
let mut held = self.0.borrow_mut();
if expected_updated_at != held["updatedAt"].as_str() {
return Ok(Put::Stale);
}
*held = state.clone();
Ok(Put::Committed)
}
}
/// What one Interpreter row did, as the report names it: the deltas by `family change`, her intentions it added, readied or
/// dropped with their words from her state after it, the identity fields it changed, and what the guards refused with why.
fn done(row: &Value, after: &Value) -> Value {
let changes = || row["applied"].as_array().into_iter().flatten();
let mut deltas: BTreeMap<String, usize> = BTreeMap::new();
for change in changes() {
*deltas.entry(format!("{} {}", change["family"].as_str().unwrap_or_default(), change["change"].as_str().unwrap_or_default())).or_insert(0) += 1;
}
let words = |id: &str| after["candidateActions"]["actions"].as_array().into_iter().flatten().find(|action| action["id"] == id).and_then(|action| action["summary"].as_str()).unwrap_or_default().to_owned();
let intentions: Vec<Value> = changes().filter(|change| change["family"] == "intend").map(|change| json!({ "change": change["change"], "id": change["id"], "words": words(change["id"].as_str().unwrap_or_default()) })).collect();
let identity: Vec<&Value> = changes().filter(|change| change["family"] == "self" && change["change"] == "identity").map(|change| &change["id"]).collect();
let refused: Vec<String> = row["refused"].as_array().into_iter().flatten().map(|refusal| format!("{}: {}", refusal["family"].as_str().unwrap_or_default(), refusal["reason"].as_str().map_or_else(|| refusal["reason"].to_string(), str::to_owned))).collect();
json!({ "status": row["status"], "deltas": deltas, "intentions": intentions, "identity": identity, "refused": refused })
}
fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker {
if line.from == member.entry.id {
Speaker::Her
@ -279,9 +316,9 @@ pub fn simulate(harness: &Harness, plan_path: &Path) -> Result<String> {
bail!("a simulation needs rounds, repeats, a room and a positive round_minutes");
}
let base = plan_path.parent().unwrap_or(Path::new("."));
let mut members = cast_of(&plan, base)?;
let members = cast_of(&plan, base)?;
let group_state = tuning::load(&harness.tuning).map(|loaded| loaded.tuning.select.group_state).ok();
let runs: Vec<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::<Result<_>>()?;
let runs: Vec<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &members, repeat)).collect::<Result<_>>()?;
Ok(markdown(plan_path, &plan, &members, group_state, &runs))
}
@ -327,9 +364,16 @@ fn cast_of(plan: &SimFile, base: &Path) -> Result<Vec<Member>> {
Ok(members)
}
fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) -> Result<Value> {
fn run(harness: &Harness, plan: &SimFile, members: &[Member], repeat: usize) -> Result<Value> {
let seed = plan.seed.wrapping_add(repeat as u64);
let cast: Vec<String> = members.iter().map(|member| member.entry.id.clone()).collect();
let addressees: Vec<Addressee> = members.iter().map(|member| member.addressee.clone()).collect();
// Each Mind's state as this run moves it: the one the wake reads and the Interpreter's put changes.
let held: Vec<InRun> = members.iter().map(|member| InRun(RefCell::new(member.state.clone()))).collect();
let interpreter = match harness.model {
Some(model) => Some((model, tuning::load(&harness.tuning)?.tuning.interpreter.model)),
None => None,
};
let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64);
let mut lines: Vec<Line> = Vec::new();
// Per line: the round, and the cause of the turn that spoke it (none for a script line).
@ -436,7 +480,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let request = Request {
instance: localpart(&id).to_owned(),
kind,
state: Some(member.state.clone()),
state: Some(held[at].0.borrow().clone()),
rooms: vec![here.clone()],
seed: seed.wrapping_mul(1_000_003).wrapping_add(counter),
renders: Some(1),
@ -461,7 +505,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let room = RefCell::new(std::mem::take(&mut lines));
let waked = {
let view = View { lines: &room, viewer: &id, rooms: &member.rooms, seen: &seen[at] };
let names = Names(&member.addressee);
let names = Names(&addressees);
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) };
wake(&organs, &request, now)?
@ -481,13 +525,30 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let line: Option<String> = None;
let outcome = if failed.is_some() { "failed" } 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, "report": waked.report });
let mut 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, "report": waked.report });
let seq = records[at].len();
records[at].push(json!({ "key": key, "seq": seq, "room": here, "held": [], "narration": waked.narration, "prose": waked.prose, "usage": waked.usage, "selected": waked.report["renders"][0]["selected"], "status": if failed.is_none() { "completed" } else { "failed" }, "failed": failed, "at": now.to_rfc3339() }));
// The Interpreter, as the drain takes it after a completed wake: the same call and put (`interpret_and_put`) against her
// in-run copy, its receipt a row of her trace that her next wake is told from (`outcome::told`).
if failed.is_none()
&& let (Some((model, model_name)), Some(narration), Some(prose)) = (interpreter.as_ref(), waked.narration.as_deref(), waked.prose.as_deref())
{
let before = held[at].0.borrow().clone();
let heard = heard_of(&before, &waked.report["packet"], &here, [], &plan.operators, &cast, true, narration, prose);
let made = interpret_and_put(*model, model_name, &format!("{key}-i"), &held[at], &Slug(localpart(&id).to_owned()), &before, &heard, narration, prose, &key, now, &|| now, &|_| Ok(()));
let mut row = made.row;
row["seq"] = json!(records[at].len());
row["at"] = json!(now.to_rfc3339());
row["wake"] = json!(key);
turn["did"] = done(&row, &held[at].0.borrow());
turn["interpreter"] = row.clone();
records[at].push(row);
}
turns.push(turn);
}
}
let metrics = metrics(members, &lines, &rounds_of, &causes, opening, &turns, plan.rounds);
let states: Vec<Value> = held.iter().map(|held| held.0.borrow().clone()).collect();
let metrics = metrics(members, &states, &lines, &rounds_of, &causes, opening, &turns, plan.rounds);
let transcript: Vec<Value> = lines.iter().zip(&rounds_of).zip(&causes).map(|((line, round), cause)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from), "woke": cause })).collect();
Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics }))
}
@ -545,11 +606,11 @@ fn reply_chains(lines: &[Line], causes: &[Option<&str>], opening: usize, cast: &
json!(out)
}
fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Option<&str>], opening: usize, turns: &[Value], rounds: usize) -> Value {
fn metrics(members: &[Member], states: &[Value], lines: &[Line], rounds_of: &[usize], causes: &[Option<&str>], opening: usize, turns: &[Value], rounds: usize) -> Value {
let cast: Vec<&str> = members.iter().map(|member| member.entry.id.as_str()).collect();
let outcome = |turn: &&Value, what: &str| turn["outcome"] == what;
let mut per = BTreeMap::new();
for member in members {
for (index, member) in members.iter().enumerate() {
let mine: Vec<&Value> = turns.iter().filter(|turn| turn["id"] == member.entry.id.as_str()).collect();
let (spoke, silent, failed) = (mine.iter().filter(|turn| outcome(turn, "spoke")).count(), mine.iter().filter(|turn| outcome(turn, "silent")).count(), mine.iter().filter(|turn| outcome(turn, "failed")).count());
let mut addressed = BTreeMap::new();
@ -561,16 +622,27 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op
}
}
let answered = spoke + silent;
// Her memories (map 16.35.13): written and resolved by the commit, refused by code or by the commit, and her
// short-term size when the run ended.
let count = |turn: &&Value, key: &str| turn["committed"][key].as_array().map_or(0, Vec::len);
let memories = json!({
"written": mine.iter().map(|turn| count(turn, "remembered")).sum::<usize>(),
"resolved": mine.iter().map(|turn| count(turn, "resolved")).sum::<usize>(),
"refused": mine.iter().map(|turn| count(turn, "refused") + turn["report"]["renders"][0]["interpreter"]["memory_refused"].as_array().map_or(0, Vec::len)).sum::<usize>(),
"short_term_at_end": member.state["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len),
// What the Interpreter did to her over the run: its calls and the ones that kept nothing, the deltas by `family change`,
// her intentions added and readied, her identity changes, the items the guards refused, and her short-term size at the end.
let interpreted: Vec<&Value> = mine.iter().map(|turn| &turn["did"]).filter(|did| did.is_object()).collect();
let mut deltas: BTreeMap<&str, u64> = BTreeMap::new();
for did in &interpreted {
for (what, count) in did["deltas"].as_object().into_iter().flatten() {
*deltas.entry(what.as_str()).or_insert(0) += count.as_u64().unwrap_or(0);
}
}
let intentions = |change: &str| interpreted.iter().flat_map(|did| did["intentions"].as_array().into_iter().flatten()).filter(|intention| intention["change"] == change).count();
let interpreter = json!({
"calls": mine.iter().filter(|turn| turn["interpreter"].is_object()).count(),
"kept_nothing": interpreted.iter().filter(|did| did["status"] != "ok").count(),
"deltas": deltas,
"intentions_added": intentions("added"),
"intentions_ready": intentions("ready"),
"identity_changes": interpreted.iter().map(|did| did["identity"].as_array().map_or(0, Vec::len)).sum::<usize>(),
"refused": interpreted.iter().map(|did| did["refused"].as_array().map_or(0, Vec::len)).sum::<usize>(),
"short_term_at_end": states[index]["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len),
});
per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "memories": memories }));
per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "interpreter": interpreter }));
}
let half = rounds.div_ceil(2);
let spoken_by = |keep: Keep| -> BTreeMap<String, String> {
@ -616,13 +688,7 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op
"narrations": overlaps.len(),
});
// Every Interpreter call of every wake, by its output (K66, map 16.34.4): how many came within a quarter of the cap.
let interpreter_calls: Vec<u64> = turns
.iter()
.flat_map(|turn| {
let decision = &turn["report"]["renders"][0]["interpreter"];
decision["calls"].as_array().into_iter().flatten().chain(decision["later_failed"]["calls"].as_array().into_iter().flatten()).map(|call| call["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect::<Vec<_>>()
})
.collect();
let interpreter_calls: Vec<u64> = turns.iter().filter(|turn| turn["interpreter"].is_object()).map(|turn| turn["interpreter"]["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect();
let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count();
json!({
"interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS },
@ -667,30 +733,22 @@ fn transcript_line(line: &Value) -> String {
format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default()))
}
/// Her memories of a turn, as the report shows them (map 16.35.8): the memories the Interpreter was listed, by id; what
/// the commit wrote and settled; and what code or the commit refused, with why. Nothing when the turn touched none.
fn memory_markdown(out: &mut String, decision: &Value, committed: &Value) {
let list = |value: &Value| value.as_array().cloned().unwrap_or_default();
let (listed, written, settled) = (list(&decision["memories"]), list(&committed["remembered"]), list(&committed["resolved"]));
let refused: Vec<Value> = list(&decision["memory_refused"]).into_iter().chain(list(&committed["refused"])).collect();
if listed.is_empty() && written.is_empty() && settled.is_empty() && refused.is_empty() {
return;
/// What the Interpreter did after one wake, in words: the deltas by family, the intentions added or readied with their words,
/// the identity fields changed and what the guards refused with why. Nothing when no Interpreter ran.
fn interpreter_words(did: &Value) -> Vec<String> {
let mut out = Vec::new();
let deltas: Vec<String> = did["deltas"].as_object().into_iter().flatten().map(|(what, count)| format!("{what} x{count}")).collect();
out.push(format!("deltas: {}", if deltas.is_empty() { "none".to_owned() } else { deltas.join(", ") }));
for intention in did["intentions"].as_array().into_iter().flatten() {
out.push(format!("intention {} (`{}`): {}", intention["change"].as_str().unwrap_or_default(), intention["id"].as_str().unwrap_or_default(), one_line(intention["words"].as_str().unwrap_or_default())));
}
let _ = writeln!(out, "Memories:\n");
for memory in &listed {
let _ = writeln!(out, "- listed {} (`{}`): {}", memory["id"].as_str().unwrap_or_default(), memory["entry"].as_str().unwrap_or_default(), one_line(memory["words"].as_str().unwrap_or_default()));
for field in did["identity"].as_array().into_iter().flatten() {
out.push(format!("identity changed: {}", field.as_str().unwrap_or_default()));
}
for entry in &written {
let _ = writeln!(out, "- remembered `{}` ({}): {}", entry["id"].as_str().unwrap_or_default(), entry["tags"].as_array().map(|tags| tags.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default()));
for refusal in did["refused"].as_array().into_iter().flatten() {
out.push(format!("guard refused {}", refusal.as_str().unwrap_or_default()));
}
for entry in &settled {
let _ = writeln!(out, "- resolved `{}`: {}", entry["id"].as_str().unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default()));
}
for refusal in &refused {
let what = refusal["text"].as_str().or_else(|| refusal["memory"].as_str()).map_or_else(|| refusal["proposal"].to_string(), one_line);
let _ = writeln!(out, "- refused ({}): {what}", refusal["reason"].as_str().unwrap_or_default());
}
out.push('\n');
out
}
/// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the
@ -715,7 +773,8 @@ fn flags_markdown(out: &mut String, turn: &Value) {
fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option<bool>, runs: &[Value]) -> String {
let mut out = String::new();
let _ = writeln!(out, "# Swarm simulation\n");
let _ = writeln!(out, "> **What came of her last turn opens her next packet.** Each persona's turn record (the Interpreter's decision and the lines the room appended for her) is carried to her next turn, as the commit's trace will carry it live; a turn's details show what she was told of it.\n");
let _ = writeln!(out, "> **What came of her last turn opens her next packet.** Each persona's turn record and the Interpreter's receipt row are carried to her next turn, as her trace carries them live; a turn's details show what she was told of it.
");
let _ = writeln!(out, "- plan: `{}`", plan_path.display());
let _ = writeln!(out, "- cast: {}", members.iter().map(|member| format!("{} (`{}`, `{}`, names from {})", member.entry.name, member.entry.id, member.entry.state.display(), member.names_from)).collect::<Vec<_>>().join(", "));
let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; she is in a room's exchange when she spoke there within {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_minutes);
@ -723,7 +782,7 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
let _ = writeln!(out, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") });
let _ = writeln!(out, "- wake: humans pace (`heartbeat::wakes`); beat: {}", if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) });
let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" });
let _ = writeln!(out, "- speech: the Interpreter's lines, each posted to its room; none is silence");
let _ = writeln!(out, "- the Interpreter runs after each wake that did not fail, the drain's call and put (`interpret_and_put`) against each Mind's in-run copy of her state, with the review room taken as named: its deltas move her state for the run's later wakes; nothing speaks in a wake, so the room holds the script's lines only");
let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text");
let _ = writeln!(out, "- silence rate is per woken turn that did not fail; a failed call is counted apart. Reply chains are per room: Mind lines spoken in turns another Mind's line woke, in a row");
let _ = writeln!(out, "- convergence is the mean pairwise cosine of speakers' word counts (lexical, cheap); work-talk share is a lexical heuristic over a fixed word list, not a classifier");
@ -753,14 +812,18 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"]));
let narration = &metrics["narration"];
let _ = writeln!(out, "- narrations: {}; mean lexical overlap with what she heard {}; over {OVERLAP_FLAG}: {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["high_overlap"], narration["offers_options"]);
let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed | memories written | resolved | refused | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|");
let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed | Interpreter calls | kept nothing | intentions added | intentions ready | identity changes | guard refusals | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|");
if let Some(personas) = metrics["personas"].as_object() {
for (name, row) in personas {
let named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::<Vec<_>>().join(", ")).unwrap_or_default();
let memories = &row["memories"];
let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), memories["written"], memories["resolved"], memories["refused"], memories["short_term_at_end"]);
let i = &row["interpreter"];
let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), i["calls"], i["kept_nothing"], i["intentions_added"], i["intentions_ready"], i["identity_changes"], i["refused"], i["short_term_at_end"]);
}
}
let _ = writeln!(out, "\n### Interpreter by wake\n\n| round | persona | woke | status | what it did |\n|---|---|---|---|---|");
for turn in run["turns"].as_array().into_iter().flatten().filter(|turn| turn["interpreter"].is_object()) {
let _ = writeln!(out, "| {} | {} | {} | {} | {} |", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; ").replace('|', "/"));
}
let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|");
for row in metrics["wakes_by_round"].as_array().into_iter().flatten() {
let causes = &row["causes"];
@ -795,7 +858,10 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
}
let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default());
turn_markdown(&mut out, &report["renders"][0]);
memory_markdown(&mut out, &report["renders"][0]["interpreter"], &turn["committed"]);
if turn["interpreter"].is_object() {
let _ = writeln!(out, "Interpreter ({}): {}
", turn["interpreter"]["status"].as_str().unwrap_or_default(), interpreter_words(&turn["did"]).join("; "));
}
flags_markdown(&mut out, turn);
}
let _ = writeln!(out, "</details>\n");

View file

@ -89,9 +89,9 @@ fn silent() -> Scripted {
fn run_plan(path: &Path, model: &dyn Model) -> (Vec<Member>, Value) {
let plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let base = path.parent().unwrap();
let mut members = cast_of(&plan, base).unwrap();
let members = cast_of(&plan, base).unwrap();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(model), tuning: base.join("persona-tuning.toml") };
let run = run(&harness, &plan, &mut members, 0).unwrap();
let run = run(&harness, &plan, &members, 0).unwrap();
(members, run)
}
@ -442,3 +442,39 @@ fn a_line_that_woke_her_is_said_to_her_in_the_packet_as_live_reads_it() {
let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default();
assert!(said.contains("hello everyone!"), "her exchange woke her; the line is said to her: {stimulus}");
}
/// A model whose Interpreter always answers with one intention.
struct Intends;
impl Model for Intends {
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
let text = if prompt.starts_with(PROJECTOR_OPENING) {
"The room is slow."
} else if prompt.starts_with("You are a private Interpreter.") {
r#"{"intend":{"add":[{"summary":"She means to say what the build did.","expires_in_hours":24,"readiness":"later"}]}}"#
} else {
"She watches the room."
};
Ok(Answer { text: text.into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 3, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
}
}
/// h6: the simulator takes the drain's Interpreter step after each wake that did not fail, moves her in-run state by its deltas,
/// and the report counts and quotes what it did.
#[test]
fn the_interpreter_runs_after_each_wake_and_the_report_says_what_it_did() {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), 3, "");
let (members, run) = run_plan(&path, &Intends);
let turns = run["turns"].as_array().unwrap();
assert!(!turns.is_empty() && turns.iter().all(|turn| turn["interpreter"]["status"] == "ok"), "every wake was interpreted: {turns:?}");
assert_eq!(turns[0]["did"]["intentions"][0]["change"], "added");
assert!(turns[0]["did"]["intentions"][0]["words"].as_str().unwrap().contains("what the build did"), "{}", turns[0]["did"]);
let personas = run["metrics"]["personas"].as_object().unwrap();
assert!(personas.values().all(|persona| persona["interpreter"]["calls"] == persona["turns"] && persona["interpreter"]["intentions_added"] == persona["turns"]), "{personas:?}");
let plan_file: SimFile = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
let report = markdown(&path, &plan_file, &members, None, &[run.clone()]);
assert!(report.contains("### Interpreter by wake") && report.contains("intention added") && report.contains("She means to say what the build did."), "{report}");
assert!(!report.contains("the Interpreter's lines, each posted"), "the header no longer claims a speech it does not run");
assert!(members.iter().all(|member| member.state["candidateActions"]["actions"].as_array().is_none_or(|actions| actions.iter().all(|action| action["customActionType"] != "intention"))), "a run moves its own copy, never the cast's");
}

View file

@ -2470,3 +2470,31 @@ fn the_body_lists_her_agents_tools() {
}
assert_eq!(select::turn_words(&affordances(true, &[]), select::forms(&state())), "this turn the room reaches her as typed lines");
}
/// h6: a line in her own room wakes her whoever it is for, and is said to her only when it is for her: one that names another
/// Mind, or replies to one, or answers someone else, is said in her room. The one derivation is `address::others_addressed`.
#[test]
fn a_line_in_her_own_room_is_said_to_her_only_when_it_is_not_for_another_mind() {
let room = "#swarm:gamecult.org";
let said_to_her = |delivery: ChatDelivery| {
let report = project_over(vec![delivery], vec![], |request| Request { own_rooms: vec![room.into()], ..request });
let packet = &report["packet"];
(stimulus_of(&report).starts_with("Said to her:"), packet["heard"].as_str().unwrap().to_owned(), packet["arrival"].as_str().unwrap().to_owned())
};
let meta = |text: &str| delivery(1, room, OPERATOR, "Meta", text, &[]);
let (to_her, _, _) = said_to_her(meta("the build is green"));
assert!(to_her, "the control: a human's line in her own room that names no one is to her");
let (to_her, heard, arrival) = said_to_her(meta("Give Libby a yes or no by tonight"));
assert!(!to_her, "a line naming another Mind is not said to her");
assert!(heard.starts_with("Meta, in #swarm:gamecult.org: \"Give Libby a yes or no"), "it is heard in the room: {heard}");
assert!(!arrival.contains("Meta"), "and no one turned to her: {arrival}");
let (to_her, _, _) = said_to_her(ChatDelivery { mentions: vec!["@kiko:gamecult.org".into()], ..meta("a playable file, please") });
assert!(!to_her, "a tag of another Mind");
let quoted = crate::chat_client::ReplyLink::Quote(crate::chat_client::ReplyTo { event_id: "$kikos".into(), sender: "@kiko:gamecult.org".into(), excerpt: Some("done".into()), at_cap: false });
let (to_her, _, _) = said_to_her(ChatDelivery { reply_to: quoted, ..meta("thanks, ship it") });
assert!(!to_her, "a reply to another Mind's line");
let (to_her, _, _) = said_to_her(meta("Eureka and Libby, a yes or no"));
assert!(to_her, "a line that names her and another is still to her");
let (to_her, _, _) = said_to_her(ChatDelivery { mentions: vec![OWN.into(), "@kiko:gamecult.org".into()], ..meta("both of you") });
assert!(to_her, "a tag of her and another is still to her");
}