From 1ae14ade13c0824939a03b93d2dd607571ba480f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 00:01:32 +0100 Subject: [PATCH] persona: the commit's bounds are per wake per target, merged by sum clamped to one step; labels are quote-checked; a made bond does not move Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/commit.rs | 128 +++++++++++++----- .../mind-body/src/projection/commit/tests.rs | 58 ++++++++ crates/mind-body/src/projection/turn.rs | 2 +- 3 files changed, 152 insertions(+), 36 deletions(-) diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 3b8b7be..205a547 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -56,6 +56,8 @@ const MOOD_DRIFT: f64 = 0.1; const FEELING_HALF_LIFE_HOURS: f64 = 8.0; const FEELING_RISE: f64 = 0.35; const FEELING_FLOOR: f64 = 0.05; +/// A feeling's name is a short label: longer is refused. +const FEELING_NAME_BYTES: usize = 24; /// A status read cools after this many days without renewal, and retires after the second. const READ_COOLS_DAYS: i64 = 3; const READ_RETIRES_DAYS: i64 = 10; @@ -360,6 +362,17 @@ const BOND_KINDS: [&str; 9] = ["ally", "friend", "collaborator", "mentor", "ward const READ_KINDS: [&str; 9] = ["attention", "authority", "risk", "trust", "need", "conflict", "mood", "opportunity", "uncertainty"]; const PAD: [&str; 3] = ["valence", "arousal", "dominance"]; +/// One person's bond entries of a wake, merged. The merge rule of every family: the bounds are per wake per target, never per +/// entry. The directions on one target are summed, `up` +1 and `down` -1, and the sum is clamped to one step, so two `up` +/// move it once and an `up` with a `down` cancel; a feeling named twice takes its largest strength and rises once; a stance or +/// value changes once a wake (`self_changes`). The last valid kind and summary win. +struct Wake { + person: String, + signs: [Option; 3], + kind: Option, + summary: Option<(String, String)>, +} + /// A state under change: the one working copy, and what is said of it. struct Commit<'a> { state: Value, @@ -434,6 +447,18 @@ impl Commit<'_> { } } + /// A label or id she keeps that is not a sentence (a note's `about`, an intention's target): refused when over `MEMORY_BYTES` + /// or carrying someone's words, like every kept text (I16.7). + fn clean(&self, text: &str) -> Result<(), Why> { + if text.len() > MEMORY_BYTES { + Err(Why::Long) + } else if quotes(text, &self.heard.lines) { + Err(Why::Echo) + } else { + Ok(()) + } + } + fn self_id(&self) -> Value { self.state["personaId"].clone() } @@ -509,7 +534,7 @@ impl Commit<'_> { let heard = self.heard; let mut kept = 0; for note in ¬es.remember { - let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(¬e.text) }; + let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(¬e.text).and_then(|text| note.about.iter().try_for_each(|id| self.clean(id)).map(|()| text)) }; let text = match text { Ok(text) => text, Err(why) => { @@ -531,7 +556,7 @@ impl Commit<'_> { self.change("notes", "remembered", &id); } for wonder in ¬es.wonder { - let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(&wonder.text) }; + let text = if kept >= NOTES_MAX { Err(Why::OverBound) } else { self.kept(&wonder.text).and_then(|text| wonder.about.iter().try_for_each(|id| self.clean(id)).map(|()| text)) }; let text = match text { Ok(text) => text, Err(why) => { @@ -594,11 +619,13 @@ impl Commit<'_> { fn people(&mut self, people: &Personal) { let heard = self.heard; + // Each person's entries are merged first: the bounds are per wake per person, never per entry (`Wake`). + let mut wakes: Vec = Vec::new(); for delta in &people.bonds { let person = heard.key_of(&delta.person); let item = json!({ "person": person }); - let at = self.list(&["affect", "socialBonds"]).iter().position(|bond| bond["object"]["kind"] == "person" && bond["object"]["id"].as_str().is_some_and(|id| heard.key_of(id) == person)); - if at.is_none() && !heard.people.contains(&person) { + let known = self.list(&["affect", "socialBonds"]).iter().any(|bond| bond["object"]["kind"] == "person" && bond["object"]["id"].as_str().is_some_and(|id| heard.key_of(id) == person)); + if !known && !heard.people.contains(&person) { self.refuse("people", item, Why::UnknownPerson); continue; } @@ -610,11 +637,17 @@ impl Commit<'_> { } None => None, }; - let mut headings = [None; 3]; - for (slot, word) in headings.iter_mut().zip([&delta.trust, &delta.tension, &delta.closeness]) { + let at = match wakes.iter().position(|wake| wake.person == person) { + Some(at) => at, + None => { + wakes.push(Wake { person: person.clone(), signs: [None; 3], kind: None, summary: None }); + wakes.len() - 1 + } + }; + for (slot, word) in [&delta.trust, &delta.tension, &delta.closeness].into_iter().enumerate() { if let Some(word) = word { match heading(word) { - Some(sign) => *slot = Some(sign), + Some(sign) => wakes[at].signs[slot] = Some(wakes[at].signs[slot].unwrap_or(0.0) + sign), None => self.refuse("people", json!({ "person": person, "direction": word }), Why::NotNamed), } } @@ -625,13 +658,18 @@ impl Commit<'_> { (Some(_), None) => Err(Why::Unexplained), (Some(summary), Some(why)) => self.kept(&summary).and_then(|summary| self.kept(&why).map(|why| Some((summary, why)))), }; - let summary = match summary { - Ok(summary) => summary, - Err(why) => { - self.refuse("people", json!({ "person": person, "summary": delta.summary }), why); - None - } - }; + match summary { + Ok(Some(summary)) => wakes[at].summary = Some(summary), + Ok(None) => {} + Err(why) => self.refuse("people", json!({ "person": person, "summary": delta.summary }), why), + } + if kind.is_some() { + wakes[at].kind = kind; + } + } + for Wake { person, signs, kind, summary } in wakes { + let item = json!({ "person": person }); + let at = self.list(&["affect", "socialBonds"]).iter().position(|bond| bond["object"]["kind"] == "person" && bond["object"]["id"].as_str().is_some_and(|id| heard.key_of(id) == person)); let id = self.next_id('b'); let stamp = self.stamp.clone(); let Some(at) = at else { @@ -648,8 +686,8 @@ impl Commit<'_> { }; let bond = &mut self.list(&["affect", "socialBonds"])[at]; let mut moved = false; - for (field, sign) in [("trust", headings[0]), ("tension", headings[1]), ("intensity", headings[2])] { - if let Some(sign) = sign { + for (field, sign) in [("trust", signs[0]), ("tension", signs[1]), ("intensity", signs[2])] { + if let Some(sign) = sign.map(|sum| sum.clamp(-1.0, 1.0)).filter(|sign| *sign != 0.0) { let before = bond[field].as_f64().unwrap_or(if field == "intensity" { NEW_BOND.2 } else { 0.5 }); bond[field] = json!(step(before, sign, BOND_STEP)); moved = true; @@ -699,25 +737,32 @@ impl Commit<'_> { } fn feelings(&mut self, feeling: &Feeling, moved: &mut BTreeSet<&'static str>) { + // A feeling named twice is one feeling: it takes the largest strength and the last source, and rises once. + let mut felt: Vec<(String, f64, String)> = Vec::new(); for delta in &feeling.feelings { let name = delta.name.trim().to_lowercase(); let about = delta.about.as_deref().map(str::trim).unwrap_or_default(); - let refusal = if name.is_empty() || name.len() > 40 || !delta.strength.is_finite() { - Some(Why::Empty) - } else if about.is_empty() { - None + let refusal = if name.is_empty() || name.len() > FEELING_NAME_BYTES || !delta.strength.is_finite() { + Some(if name.len() > FEELING_NAME_BYTES { Why::Long } else { Why::Empty }) } else { - self.kept(about).err() + self.kept(&name).err().or_else(|| if about.is_empty() { None } else { self.kept(about).err() }) }; if let Some(why) = refusal { self.refuse("feeling", &delta.name, why); continue; } + let strength = delta.strength.clamp(0.0, 1.0); + match felt.iter_mut().find(|(held, ..)| *held == name) { + Some(held) => *held = (name, held.1.max(strength), about.to_owned()), + None => felt.push((name, strength, about.to_owned())), + } + } + for (name, strength, about) in felt { let stamp = self.stamp.clone(); let feelings = self.list(&["affect", "moodDimensions"]); let at = feelings.iter().position(|held| held["name"] == name.as_str()); let held = at.and_then(|at| feelings[at]["value"].as_f64()).unwrap_or(0.0); - let entry = json!({ "name": name, "value": delta.strength.clamp(0.0, 1.0).min(held + FEELING_RISE), "source": about, "updatedAt": stamp }); + let entry = json!({ "name": name, "value": strength.min(held + FEELING_RISE), "source": about, "updatedAt": stamp }); match at { Some(at) => feelings[at] = entry, None => feelings.push(entry), @@ -754,29 +799,42 @@ impl Commit<'_> { fn drives(&mut self, drives: &Drives) { for (family, path, ease, deltas) in [("needs", ["affect", "needs"], "met", &drives.needs), ("pressures", ["agencyPressure", "pressures"], "eased", &drives.pressures)] { + // The entries naming one id are merged: their directions sum and clamp to one step, and any ease cools it. + let mut merged: Vec<(&str, f64, bool)> = Vec::new(); for delta in deltas { - let stamp = self.stamp.clone(); let toward = delta.toward.trim(); let sign = heading(toward); if sign.is_none() && toward != ease { self.refuse(family, json!({ "id": delta.id, "toward": delta.toward }), Why::NotNamed); continue; } - let Some(item) = self.list(&path).iter_mut().find(|item| item["id"] == delta.id.as_str()) else { - self.refuse(family, json!({ "id": delta.id }), Why::UnknownId); + let at = merged.iter().position(|(id, ..)| *id == delta.id).unwrap_or_else(|| { + merged.push((&delta.id, 0.0, false)); + merged.len() - 1 + }); + merged[at].1 += sign.unwrap_or(0.0); + merged[at].2 |= sign.is_none(); + } + for (id, sum, eased) in merged { + let stamp = self.stamp.clone(); + let Some(item) = self.list(&path).iter_mut().find(|item| item["id"] == id) else { + self.refuse(family, json!({ "id": id }), Why::UnknownId); continue; }; - match sign { - Some(sign) => { - item["intensity"] = json!(step(item["intensity"].as_f64().unwrap_or(0.5), sign, DRIVE_STEP)); - if sign > 0.0 { - item["status"] = json!("active"); - } + let sign = sum.clamp(-1.0, 1.0); + if sign != 0.0 { + item["intensity"] = json!(step(item["intensity"].as_f64().unwrap_or(0.5), sign, DRIVE_STEP)); + if sign > 0.0 { + item["status"] = json!("active"); } - None => item["status"] = json!("cooling"), } - item["updatedAt"] = stamp; - self.change(family, toward, &delta.id); + if eased { + item["status"] = json!("cooling"); + } + if sign != 0.0 || eased { + item["updatedAt"] = stamp; + self.change(family, if eased { ease } else if sign > 0.0 { "up" } else { "down" }, id); + } } } } @@ -890,7 +948,7 @@ impl Commit<'_> { } else if !(1..=INTENTION_HOURS_MAX).contains(&intention.expires_in_hours) { Err(Why::BadExpiry) } else { - self.kept(&intention.summary) + self.kept(&intention.summary).and_then(|summary| intention.target.as_deref().map_or(Ok(()), |label| self.clean(label)).map(|()| summary)) }; let readiness = match intention.readiness.as_deref() { Some("later") | None => "waiting", diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index a33cb3a..0d24550 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -291,3 +291,61 @@ fn t_p2_resolved_notes_are_pruned() { 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()))); } + +/// Soul s1: the bounds are per wake per target, never per entry. Three entries for one person move trust once, two for one need +/// move it once, and a feeling named three times rises once. +#[test] +fn t_p2_duplicate_entries_move_a_target_once() { + let state = state(); + let start = bond(&state, "kiko")["trust"].as_f64().unwrap(); + let (after, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "up" }] } })); + assert!((bond(&after, "kiko")["trust"].as_f64().unwrap() - (start + BOND_STEP).min(1.0)).abs() < 1e-9, "three ups are one step"); + let (cancelled, _) = run(&state, json!({ "people": { "bonds": [{ "person": "kiko", "trust": "up" }, { "person": "kiko", "trust": "down" }] } })); + assert!((bond(&cancelled, "kiko")["trust"].as_f64().unwrap() - start).abs() < 1e-9, "up and down cancel"); + let before = state["affect"]["needs"][0]["intensity"].as_f64().unwrap(); + let (after, _) = run(&state, json!({ "drives": { "needs": [{ "id": "need-an-audience", "toward": "up" }, { "id": "need-an-audience", "toward": "up" }] } })); + assert!((after["affect"]["needs"][0]["intensity"].as_f64().unwrap() - (before + DRIVE_STEP)).abs() < 1e-9, "two ups are one step"); + let (after, _) = run(&state, json!({ "feeling": { "feelings": [{ "name": "anger", "strength": 0.9 }, { "name": "Anger", "strength": 0.9 }, { "name": "anger", "strength": 0.8 }] } })); + assert_eq!((after["affect"]["moodDimensions"].as_array().unwrap().len(), after["affect"]["moodDimensions"][0]["value"].as_f64()), (1, Some(0.35))); + valid(&after); +} + +/// A bond made this wake is not moved this wake, whatever else the entries say. +#[test] +fn t_p2_a_bond_made_is_not_moved() { + let mut named = heard(); + named.people.push("@ann:gamecult.org".into()); + let made = json!({ "person": "@ann:gamecult.org", "summary": "Ann asks careful questions.", "why": "Ann asked three." }); + let (after, applied) = apply(&state(), &deltas(json!({ "people": { "bonds": [made, { "person": "@ann:gamecult.org", "trust": "up", "tension": "up", "closeness": "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()), (Some(0.5), Some(0.1), Some(0.2))); + assert_eq!(applied.changes.iter().filter(|change| change["family"] == "people").count(), 1); +} + +/// I16.7 on every kept label: an intention's target, a feeling's name, a note's about and its tag carry no run of heard words, and a +/// feeling's name is short. +#[test] +fn t_p2_labels_refuse_what_was_heard() { + let line = "tell Deru about the forty eight hour passkey cooling off period before friday"; + let said = "tell Deru about the forty eight hour passkey cooling off"; + let heard = Heard { lines: vec![line.into()], ..heard() }; + let go = |value: Value| apply(&state(), &deltas(value), &heard, "w1", now()); + let (after, applied) = go(json!({ "intend": { "add": [{ "summary": "Tobiah means to ask Deru something.", "target": said, "expires_in_hours": 5 }] } })); + assert_eq!((reasons(&applied), after["candidateActions"]["actions"].clone()), (vec!["echo".to_owned()], state()["candidateActions"]["actions"].clone())); + let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": said, "strength": 0.5 }] } })); + assert_eq!(reasons(&applied), ["long"], "a name is a short label"); + let (_, applied) = go(json!({ "feeling": { "feelings": [{ "name": "a b c d e f g h", "strength": 0.5 }] } })); + assert_eq!(reasons(&applied), Vec::::new(), "short labels pass"); + let (after, applied) = go(json!({ "notes": { "remember": [{ "text": "Deru owes Tobiah an answer.", "about": [said] }], "wonder": [{ "text": "Will Deru answer soon?", "about": [said] }] } })); + assert_eq!((reasons(&applied), after["thoughtMemory"]["shortTerm"].clone()), (vec!["echo".to_owned(), "echo".to_owned()], state()["thoughtMemory"]["shortTerm"].clone())); +} + +/// One stance or value change a wake: a second stance is over the bound, and the first stands. +#[test] +fn t_p2_two_stances_are_one_change() { + let stances = json!([{ "id": "stance-slow-is-kind", "principle": "Slow is kind.", "summary": "Tobiah answers slowly." }, { "principle": "Plain words.", "summary": "Tobiah keeps his words plain." }]); + let (after, applied) = run(&state(), json!({ "self": { "stances": stances } })); + assert_eq!(reasons(&applied), ["over_bound"]); + assert_eq!(after["affect"]["doctrineStances"].as_array().unwrap().len(), state()["affect"]["doctrineStances"].as_array().unwrap().len()); + assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly."); +} diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 8d563aa..c5147b7 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -58,7 +58,7 @@ pub(crate) struct Past { /// 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() && !matches!(record["kind"].as_str(), Some("interpreter" | "say")) + record.get("failed").is_none() && record.get("set_aside").is_none() && record.get("agent").is_none() && !matches!(record["kind"].as_str(), Some("interpreter" | "say" | "identity_diff")) } /// 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