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