From 093bfd867faae8247a2c6c76aec3a33101889ee9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 23 Nov 2026 01:40:57 +0100 Subject: [PATCH] Persona T4: memory in; the commit writes thoughtMemory.shortTerm alone (map 16.35.12, ruling persona-memory-not-machinery) - The Interpreter's contract gains `remember` (third-person notes: text, about, importance, private) and `resolve` (ids of the memories listed to it). decide_in refuses a note empty, over MEMORY_BYTES (600), an echo of what she was shown or read, or past MEMORIES_MAX (4); an about id no listed person is dropped and reported; a resolve id not in Packet.memories is refused memory_unlisted. Refusals ride in `memory_refused`, reported, never told. - commit::apply(state, record, key, now) is the one applier: Remember appends one anchored thought `{key}-m{i}` tagged room:/about:/private; Resolve sets one short-term memory resolved; resolved ones older than RESOLVED_KEPT_DAYS (7) are pruned. A failed record applies nothing. It writes nothing outside shortTerm. - select: Packet.memories lists the memory picks by id for the Interpreter; a short-term memory's nearness is recency plus relevance (16.35.5). The frame and prompt carry the memory list. - simulate: per-turn memory section and per-Mind memories written/resolved/refused/short-term-at-end. - Tests per 16.35.12 T4, the X.5 timeline probe (16.35.13 check 8), golden speech frame regenerated. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/interpret/golden-speech.txt | 5 +- crates/mind-body/src/projection.rs | 1 + crates/mind-body/src/projection/commit.rs | 113 +++++++++-- .../mind-body/src/projection/commit/tests.rs | 160 +++++++++++++-- crates/mind-body/src/projection/interpret.rs | 103 +++++++++- .../src/projection/interpret/tests.rs | 182 +++++++++++++++++- crates/mind-body/src/projection/select.rs | 27 ++- crates/mind-body/src/projection/simulate.rs | 50 ++++- .../src/projection/simulate/tests.rs | 38 ++++ 9 files changed, 630 insertions(+), 49 deletions(-) diff --git a/crates/mind-body/fixtures/interpret/golden-speech.txt b/crates/mind-body/fixtures/interpret/golden-speech.txt index 1b71f6b..2099c26 100644 --- a/crates/mind-body/fixtures/interpret/golden-speech.txt +++ b/crates/mind-body/fixtures/interpret/golden-speech.txt @@ -8,7 +8,7 @@ A draft is speech only when his prose shows him choosing to send it now. Wonderi He speaks only in this room. What he knows privately is listed below as private: he says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge. -Answer with the speech contract's object. `say` lists the drafts he sends now, each by its number, with the Matrix ids of anyone listed whom he addresses directly (`mentions`), the id of the line listed below that he answers or passes on (`in_reply_to`, or null: the room shows that line, with who said it, above his own words). `gaps` records what he meant and did not send. `amend` adds to one of his own lines listed below, at most one a turn, only when his thought shows him choosing to correct or add to that line: name the line by its id and the draft that is his addition. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. +Answer with the speech contract's object. `say` lists the drafts he sends now, each by its number, with the Matrix ids of anyone listed whom he addresses directly (`mentions`), and the id of the line listed below that he answers or passes on (`in_reply_to`, or null: the room shows that line, with who said it, above his own words). `gaps` records what he meant and did not send. `amend` adds to one of his own lines listed below, at most one a turn, only when his thought shows him choosing to correct or add to that line: name the line by its id and the draft that is his addition. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `remember` keeps what he would want to still know when this conversation is gone, from this moment: what he tells someone he will do or will not do, what someone asks of him, what he finds out, decides or comes to feel about someone. Each is one note about him in the third person, in plain words of its own and never a copy of anyone's line, saying who and where (`text`), with the Matrix ids of the people listed whom it concerns (`about`), how much it matters to him from 0 to 1 (`importance`), and `private` when it carries anything listed as private. Remember only what his prose and what reached him show; at most four notes, and none when nothing here is worth keeping. `resolve` names each of his memories listed below that this moment settles: what it says he would do is done, or it no longer holds. A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: addressee when he means to send a draft but whom to is unclear, elsewhere when he means a draft for another room or another time; for these two, name the draft by number. missing_affordance when he means to do something, now or later, that his body cannot do (what he can do here is listed below), whether he said so in a draft or only thought it; name the draft when there is one. unwritten when he means to say something now and wrote no draft of it. Holding back is no gap: when his thought shows him choosing to wait, to let something stand, to leave it for later or to say nothing, record nothing for it. Every other intent of his that is not carried out has a kind: an intent to act is missing_affordance, an intent to say now with no draft is unwritten. When a gap names no draft, quote the words of his thought that show it, at least four words, copied exactly. @@ -36,6 +36,9 @@ His own lines in this room that he may add to, as id — line: What moved in his domain lately, as id — line (news of his part of the coop, none of it work he owes): - d1 — GameCult/Lodur: merged "Reflex: the knee bends first", opened by nibu +His memories in this moment, as id — note: +- none + What reached him: Also in the room: - "Nibu" (@nibu:gamecult.org) in #minds:gamecult.org: "v0.2.0 is tagged and the economy is still the least built part. I think this looks okay to ship." diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 7a49b25..6171994 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -346,6 +346,7 @@ fn packet_json(packet: &Packet) -> Value { "affordances": packet.affordances, "amendable": packet.amendable, "quotable": packet.quotable, + "memories": packet.memories, "domain": packet.domain, "domain_shown": packet.domain_shown, "in_view": packet.in_view, diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 23f7618..fdf24cb 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -3,20 +3,37 @@ //! delta to her state as it stands at commit, or refuses it with a typed reason (`Refusal`) the report keeps. Self and //! Life put from outside (`persona-only-state-writers-self-and-life`). //! -//! No proposal kind exists yet: what she says she will do, what someone asked of her, and whom she owes an answer are -//! not state (ruling `persona-memory-not-machinery`, map 16.35). The memory rows (`remember`, `resolve`) are the next -//! kinds (map 16.35.4, T4), and they are added here, with no second path. A failed turn applies nothing. +//! A turn writes `thoughtMemory.shortTerm` and nothing else (ruling `persona-memory-not-machinery`, map 16.35.4): +//! - `remember` appends one anchored thought, a third-person note in her words of it, tagged with the turn's room, the +//! people it concerns and `private` when it is; a note made in a direct message carries that room's `room:!…` tag, so +//! `select::concerns` reads it as private by the existing convention; +//! - `resolve` sets one of her short-term memories, as the Interpreter's list mapped it, `resolved`; +//! - a short-term memory resolved more than `RESOLVED_KEPT_DAYS` ago is removed; one resolved with no time (an outside put) +//! is stamped at the first commit that sees it. +//! +//! What she says she will do, what someone asked of her, and whom she owes an answer are no state of their own: they live +//! only as memories she chose to keep. A failed turn applies nothing. //! //! The simulator applies each turn's record to each Mind's in-run state copy; live, C3c's commit applies the same record //! before its put. +use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -/// One state change the Interpreter proposes, named by its kind on the wire. None is built: every proposal is refused -/// `NotAProposal` until the memory rows land (map 16.35.12, T4). -#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] -pub(crate) enum Proposal {} +/// How long a resolved short-term memory is kept before the commit removes it. +pub(crate) const RESOLVED_KEPT_DAYS: i64 = 7; + +/// One state change the Interpreter proposes, named by its kind on the wire (`interpret::decide_in` builds them). +#[derive(Clone, Debug, PartialEq, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub(crate) enum Proposal { + /// A note she would want to still know (map 16.35.4): its words, the Matrix ids of the people it concerns, how much it + /// matters to her (0..1), whether it is private, and the turn's room, when it had one. + Remember { text: String, about: Vec, importance: f64, private: bool, room: Option }, + /// One of her memories this moment settles: its id in the Interpreter's list, and the state entry it is. + Resolve { memory: String, entry: String }, +} /// Why the commit applied nothing of a proposal: what the report says. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -24,27 +41,95 @@ pub(crate) enum Proposal {} pub(crate) enum Refusal { /// Not a proposal the contract names. NotAProposal, + /// The memory it settles is gone from her state: an outside put removed it after she was shown it (4.4 rule 4). + OutsidePutRemovedTarget, + /// The memory it settles is not a short-term one, and a turn writes nothing else. + NotShortTerm, } -/// What the commit did with one turn's proposals: the proposals it refused, with why. +/// What the commit did with one turn's proposals: the memories it wrote and settled, as they now stand, the proposals it +/// refused, with why, and how many resolved memories it removed. #[derive(Clone, Debug, Default, PartialEq, Serialize)] pub(crate) struct Applied { + pub remembered: Vec, + pub resolved: Vec, pub refused: Vec, + pub pruned: usize, } -/// The one applier: her state with one turn's proposals applied, and what was refused. A failed turn applies nothing. -pub(crate) fn apply(state: &Value, record: &Value) -> (Value, Applied) { +/// The one applier: her state with one turn's proposals applied, and what was done. `key` names the turn +/// (`-t`), and each memory it writes is `{key}-m{i}`; `now` is the commit's time. A failed turn applies nothing. +pub(crate) fn apply(state: &Value, record: &Value, key: &str, now: DateTime) -> (Value, Applied) { let mut applied = Applied::default(); if record.get("failed").is_some() || record["interpreter"].get("failed").is_some() { return (state.clone(), applied); } + let mut state = state.clone(); + let stamp = json!(now.to_rfc3339()); + let kept_until = now - Duration::days(RESOLVED_KEPT_DAYS); + let resolved_at = |entry: &Value| entry["updatedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)); + if state["thoughtMemory"]["shortTerm"].is_array() { + let entries = short_term(&mut state); + for entry in entries.iter_mut().filter(|entry| entry["status"] == "resolved" && resolved_at(entry).is_none()) { + entry["updatedAt"] = stamp.clone(); + } + let before = entries.len(); + entries.retain(|entry| entry["status"] != "resolved" || resolved_at(entry).is_none_or(|at| at > kept_until)); + applied.pruned = before - entries.len(); + } for raw in record["interpreter"]["state"].as_array().into_iter().flatten() { - match serde_json::from_value::(raw.clone()) { - Ok(proposal) => match proposal {}, - Err(_) => applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })), + let Ok(proposal) = serde_json::from_value::(raw.clone()) else { + applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })); + continue; + }; + match proposal { + Proposal::Remember { text, about, importance, private, room } => { + let target = match (about.first(), &room) { + (Some(person), _) => json!({ "kind": "person", "id": person }), + (None, Some(room)) => json!({ "kind": "room", "id": room }), + (None, None) => json!({ "kind": "self", "id": state["personaId"] }), + }; + let tags: Vec = room.iter().map(|room| format!("room:{room}")).chain(about.iter().map(|id| format!("about:{id}"))).chain(private.then(|| "private".to_owned())).collect(); + let entry = json!({ + "id": format!("{key}-m{}", applied.remembered.len() + 1), + "status": "active", + "target": target, + "summary": text, + "tension": "", + "actionImplication": "", + "intensity": importance.clamp(0.0, 1.0), + "createdAt": stamp, + "updatedAt": stamp, + "tags": tags, + }); + short_term(&mut state).push(entry.clone()); + applied.remembered.push(entry); + } + Proposal::Resolve { entry, .. } => { + let crystallized = state["thoughtMemory"]["memories"].as_array().is_some_and(|memories| memories.iter().any(|memory| memory["id"] == entry.as_str())); + match short_term(&mut state).iter_mut().find(|memory| memory["id"] == entry.as_str()) { + Some(memory) => { + memory["status"] = json!("resolved"); + memory["updatedAt"] = stamp.clone(); + applied.resolved.push(memory.clone()); + } + None => applied.refused.push(json!({ "proposal": raw, "reason": if crystallized { Refusal::NotShortTerm } else { Refusal::OutsidePutRemovedTarget } })), + } + } } } - (state.clone(), applied) + (state, applied) +} + +/// Her short-term memories, as the one list a turn writes: made when her state has none. +fn short_term(state: &mut Value) -> &mut Vec { + if !state["thoughtMemory"].is_object() { + state["thoughtMemory"] = json!({ "shortTerm": [], "memories": [], "incubation": [] }); + } + if !state["thoughtMemory"]["shortTerm"].is_array() { + state["thoughtMemory"]["shortTerm"] = json!([]); + } + state["thoughtMemory"]["shortTerm"].as_array_mut().expect("shortTerm is an array") } #[cfg(test)] diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index fb3709a..5921264 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -2,37 +2,165 @@ use serde_json::{Value, json}; use super::*; +const MINDS: &str = "#minds:gamecult.org"; +const META: &str = "@meta:gamecult.org"; +const HEIMDALL: &str = "@heimdall:gamecult.org"; + +fn now() -> DateTime { + DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&Utc) +} + /// A turn that said one line and proposes `state`. fn record(state: Value) -> Value { json!({ - "interpreter": { "said": [{ "room": "#minds:gamecult.org", "text": "I'll send the render tonight.", "rests_on": { "draft": 1 } }], "amended": [], "state": state }, - "posted": [{ "event": "7", "room": "#minds:gamecult.org", "text": "I'll send the render tonight." }], + "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": [] }) } -/// T2 (map 16.35.12, 16.35.13 check 5): the commit has no promise or hold kind. An exhaustive match over `Proposal` with -/// no arm compiles only while it has no variant, so a kind added back fails here until it is named. -#[test] -fn t2_the_commit_has_no_promise_or_hold_kind() { - fn kinds(proposal: Proposal) -> &'static str { - match proposal {} - } - let _ = kinds; +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. +fn state() -> Value { let mut state = crate::projection::harness::tests::control(); state["thoughtMemory"]["shortTerm"] = json!([]); + 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. +#[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", + } + } + let _ = kinds; + 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 } }]))); + 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"))); +} + +/// T4 (map 16.35.13 mutant: apply `remember` on a failed record): a failed turn applies nothing and refuses nothing, +/// memories included. +#[test] +fn t4_failed_turn_writes_no_memory() { + 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}"); + } + // 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. +#[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"); +} + +/// 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. +#[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" } + ]); + base["thoughtMemory"]["memories"] = json!([{ "id": "lt-1", "status": "crystallized", "target": { "kind": "self", "id": "heimdall" }, "summary": "A crystallized memory.", "tension": "", "actionImplication": "", "createdAt": "2026-10-01T10:00:00Z", "updatedAt": "2026-10-01T10:00:00Z" }]); + let menu = [ + remember("Meta asked Heimdall whether the notes are still on for tomorrow; he has not answered yet.", &[META], Some(MINDS), false), + remember("Aqua told Meta privately she is tired.", &[], Some("!dm-aqua:gamecult.org"), true), + remember("Heimdall decided to read the saga code first.", &[], None, false), + resolve("st-1"), + resolve("st-gone"), + resolve("lt-1"), + json!({ "kind": "hold_open", "words": "hold it" }), + ]; + let without_short_term = |state: &Value| { + let mut state = state.clone(); + state["thoughtMemory"].as_object_mut().unwrap().remove("shortTerm"); + state + }; + // Every subset of the menu, in order. + for mask in 0u32..(1 << menu.len()) { + let proposals: Vec = menu.iter().enumerate().filter(|(at, _)| mask & (1 << at) != 0).map(|(_, proposal)| proposal.clone()).collect(); + let (after, _) = apply(&base, &record(json!(proposals)), "r1-t9", now()); + assert_eq!(serde_json::to_string(&without_short_term(&after)).unwrap(), serde_json::to_string(&without_short_term(&base)).unwrap(), "mask {mask:b}"); + } } -/// A failed turn applies nothing and refuses nothing: it is not read. +/// T4 (map 16.35.4): `resolve` sets the one memory the list mapped `resolved` and touches no other. #[test] -fn a_failed_turn_applies_nothing() { - let state = crate::projection::harness::tests::control(); - for failed in [json!({ "failed": "the connector timed out" }), json!({ "interpreter": { "failed": "the answer is not the speech contract", "state": [{ "kind": "anything" }] } })] { - assert_eq!(apply(&state, &failed), (state.clone(), Applied::default()), "{failed}"); +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())); +} diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 0617451..d2737b7 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -24,7 +24,10 @@ //! Every refusal and drop is reported. Every gap is typed (`GapKind`) and shown to her later (K9) only as what it is: a //! draft by number, or a located passage of her thought (`gap`). What she says she will do lives only in her own words //! and in what she chooses to remember: no code here derives a promise or a hold from a line (map 16.35, ruling -//! `persona-memory-not-machinery`). Nothing here writes her state. The prompt tells the Interpreter what she can do this turn +//! `persona-memory-not-machinery`). The same answer says what she would want to still know (`remember`: third-person +//! notes, each refused when empty, over `MEMORY_BYTES`, an echo, or past `MEMORIES_MAX`) and which of her memories listed to +//! it this moment settles (`resolve`, by id from `Packet::memories`); they ride in the decision as proposals under +//! `state`, which the commit alone applies (`commit::apply`). Nothing here writes her state. The prompt tells the Interpreter what she can do this turn //! (`select::turn_words`), so a reach past it is a `missing_affordance` gap. Nothing here posts: the commit (C3c) will. //! //! The same answer may add a draft after a line of hers listed as one she may add to (`amend`, map 16.17; the actuator @@ -52,6 +55,10 @@ const ECHO_OVERLAP: f64 = 0.8; /// The fewest words a passage of her thought shown back to her may be: a shorter quote ("tell") says nothing of what /// she meant, and is kept as unlocated. const GAP_QUOTE_MIN_WORDS: usize = 4; +/// The longest memory, in bytes, once trimmed (map 16.35.4). +pub(crate) const MEMORY_BYTES: usize = 600; +/// The most memories one decision writes (map 16.35.4). +pub(crate) const MEMORIES_MAX: usize = 4; /// The marks of a draft: two literal tokens no natural prose holds (map 16.19.1). pub(crate) const DRAFT_OPEN: &str = ""; @@ -62,7 +69,7 @@ pub(crate) const SPEECH_OPENING: &str = "You decide what one person says aloud i /// The speech contract, sent as the schema turn's output schema (`--json-schema`): the drafts she sends now by number, /// and the gaps. The model writes no words of hers. -pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps","amend","suggest","read"],"properties":{"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target","quote"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"},"quote":{"type":"string"}}},"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#; +pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps","amend","suggest","read","remember","resolve"],"properties":{"remember":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["text","about","importance","private"],"properties":{"text":{"type":"string"},"about":{"type":"array","items":{"type":"string"}},"importance":{"type":"number","minimum":0,"maximum":1},"private":{"type":"boolean"}}}},"resolve":{"type":"array","items":{"type":"string"}},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target","quote"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"},"quote":{"type":"string"}}},"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#; /// The speech frame before the guidance: what to decide, from what, and the attribution rule. Code, not tuning (map /// 16.7), in her own pronouns (16.19.7). The tuning's `interpreter.guidance` (what counts as her choosing to send it @@ -82,7 +89,7 @@ fn speech_frame_tail(her: Forms) -> String { format!( "{cap_subj} speak{s} only in this room. What {subj} know{s} privately is listed below as private: {subj} say{s} none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge. -Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`), the id of the line listed below that {subj} answer{s} or pass{es} on (`in_reply_to`, or null: the room shows that line, with who said it, above {poss} own words). `gaps` records what {subj} meant and did not send. `amend` adds to one of {poss} own lines listed below, at most one a turn, only when {poss} thought shows {obj} choosing to correct or add to that line: name the line by its id and the draft that is {poss} addition. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. +Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`), and the id of the line listed below that {subj} answer{s} or pass{es} on (`in_reply_to`, or null: the room shows that line, with who said it, above {poss} own words). `gaps` records what {subj} meant and did not send. `amend` adds to one of {poss} own lines listed below, at most one a turn, only when {poss} thought shows {obj} choosing to correct or add to that line: name the line by its id and the draft that is {poss} addition. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `remember` keeps what {subj} would want to still know when this conversation is gone, from this moment: what {subj} tell{s} someone {subj} will do or will not do, what someone asks of {obj}, what {subj} find{s} out, decide{s} or come{s} to feel about someone. Each is one note about {obj} in the third person, in plain words of its own and never a copy of anyone's line, saying who and where (`text`), with the Matrix ids of the people listed whom it concerns (`about`), how much it matters to {obj} from 0 to 1 (`importance`), and `private` when it carries anything listed as private. Remember only what {poss} prose and what reached {obj} show; at most four notes, and none when nothing here is worth keeping. `resolve` names each of {poss} memories listed below that this moment settles: what it says {subj} would do is done, or it no longer holds. A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: addressee when {subj} mean{s} to send a draft but whom to is unclear, elsewhere when {subj} mean{s} a draft for another room or another time; for these two, name the draft by number. missing_affordance when {subj} mean{s} to do something, now or later, that {poss} body cannot do (what {subj} can do here is listed below), whether {subj} said so in a draft or only thought it; name the draft when there is one. unwritten when {subj} mean{s} to say something now and wrote no draft of it. Holding back is no gap: when {poss} thought shows {obj} choosing to wait, to let something stand, to leave it for later or to say nothing, record nothing for it. Every other intent of {poss} that is not carried out has a kind: an intent to act is missing_affordance, an intent to say now with no draft is unwritten. When a gap names no draft, quote the words of {poss} thought that show it, at least four words, copied exactly.", es = if s.is_empty() { "" } else { "es" }, @@ -326,6 +333,40 @@ struct Answer { /// contract is reported and the rest of the answer stands. #[serde(default)] read: Option, + /// What she would want to still know when this conversation is gone (map 16.35.4); none when left out. + #[serde(default)] + remember: Vec, + /// The ids of her memories listed to the Interpreter that this moment settles (`Packet::memories`). + #[serde(default)] + resolve: Vec, +} + +/// A memory as the model proposes it (map 16.35.4): a third-person note in plain words, the people listed whom it +/// concerns, how much it matters to her, and whether it carries something private. Every field is the contract's. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ProposedMemory { + text: String, + about: Vec, + importance: f64, + private: bool, +} + +/// Why code refused a memory or a settling of one (map 16.35.4): reported, never told to her. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum MemoryRefusal { + /// Nothing left once trimmed. + MemoryEmpty, + /// Over `MEMORY_BYTES`. + MemoryLong, + /// Mostly the words of a line she was shown or read (`echo`): no one's line reaches the Projector by way of her state + /// (I16.7). + Echo, + /// Past `MEMORIES_MAX` in one decision. + OverMemories, + /// A `resolve` id that names no memory listed to the Interpreter. + MemoryUnlisted, } /// Where in her wake a decision falls (map 16.22.3): what was decided earlier this wake (none for her first segment), @@ -414,6 +455,11 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu let lines: String = packet.domain.iter().map(|moved| format!("- {} \u{2014} {}\n", moved.id, moved.line.trim_start_matches("- "))).collect(); format!("What moved in {} domain lately, as id \u{2014} line (news of {} part of the coop, none of it work {} owe{}):\n{lines}\n", her.poss, her.poss, her.subj, her.s) }; + // Her memories this packet recalls, by id, so `resolve` can name one (map 16.35.4). + let mut memories: String = packet.memories.iter().map(|memory| format!("- {} \u{2014} {}\n", memory.id, spoken(&memory.words))).collect(); + if memories.is_empty() { + memories.push_str("- none\n"); + } let mut numbered: String = found.drafts.iter().map(|draft| format!("{}. {}\n", draft.n, draft.text)).collect(); if numbered.is_empty() { numbered.push_str("- none\n"); @@ -452,7 +498,7 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu let named = named_pronouns(&format!("{before}\n{prose}"), tuning, &packet.own_sender); let people = if named.is_empty() { people } else { format!("{people}Pronouns of the people {} prose names:\n{}\n", her.poss, named.iter().map(|line| format!("- {line}\n")).collect::()) }; format!( - "{}\n\n{guidance}{}\n\nWho {} {}:\n{}\n\nWhat {} can do here:\n{}.\n\nThe room: {} ({}).\n{conversation}Who is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\nLines in this room {} may reply to, as id \u{2014} who: line:\n{quotable}\n{poss} own lines in this room that {} may add to, as id \u{2014} line:\n{amendable}\n{domain}What reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{before}{poss} prose:\n{prose}\n\n{poss} drafts, by number:\n{numbered}", + "{}\n\n{guidance}{}\n\nWho {} {}:\n{}\n\nWhat {} can do here:\n{}.\n\nThe room: {} ({}).\n{conversation}Who is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\nLines in this room {} may reply to, as id \u{2014} who: line:\n{quotable}\n{poss} own lines in this room that {} may add to, as id \u{2014} line:\n{amendable}\n{domain}{poss} memories in this moment, as id \u{2014} note:\n{memories}\nWhat reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{before}{poss} prose:\n{prose}\n\n{poss} drafts, by number:\n{numbered}", speech_frame_head(her), tail, her.subj, @@ -665,6 +711,55 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na went.push(draft); suggestions.push(json!({ "kind": proposed.kind, "about": about, "room": room, "text": draft.text, "draft": draft.n, "dropped": { "about": dropped } })); } + // What she remembers of this moment, and which of her listed memories it settles (map 16.35.4): proposals the commit + // applies (`commit::apply`), each held to code's structural checks. A memory carries no one's line: one that echoes + // what she was shown or read is refused, so no heard words reach the Projector by way of her state (I16.7). + let mut proposals: Vec = Vec::new(); + let mut memory_refused: Vec = Vec::new(); + let mut about_dropped: Vec = Vec::new(); + let mut remembered = 0usize; + for proposed in parsed.remember { + let text = proposed.text.trim(); + let reason = if text.is_empty() { + Some(MemoryRefusal::MemoryEmpty) + } else if text.len() > MEMORY_BYTES { + Some(MemoryRefusal::MemoryLong) + } else if echo(text, &bodies) { + Some(MemoryRefusal::Echo) + } else if remembered >= MEMORIES_MAX { + Some(MemoryRefusal::OverMemories) + } else { + None + }; + if let Some(reason) = reason { + memory_refused.push(json!({ "act": "remember", "text": text, "reason": reason })); + continue; + } + remembered += 1; + let (about, unknown): (Vec, Vec) = proposed.about.into_iter().partition(|id| shown(id)); + about_dropped.extend(unknown); + proposals.push(json!({ "kind": "remember", "text": text, "about": about, "importance": proposed.importance.clamp(0.0, 1.0), "private": proposed.private, "room": room })); + } + let mut settled: Vec<&str> = Vec::new(); + for id in &parsed.resolve { + let id = id.trim(); + match packet.memories.iter().find(|memory| memory.id == id) { + Some(memory) if !settled.contains(&id) => { + settled.push(id); + proposals.push(json!({ "kind": "resolve", "memory": memory.id, "entry": memory.entry })); + } + Some(_) => {} + None => memory_refused.push(json!({ "act": "resolve", "memory": id, "reason": MemoryRefusal::MemoryUnlisted })), + } + } + decision["state"] = json!(proposals); + decision["memories"] = json!(packet.memories); + if !memory_refused.is_empty() { + decision["memory_refused"] = json!(memory_refused); + } + if !about_dropped.is_empty() { + decision["memory_about_dropped"] = json!(about_dropped); + } // A gap about a draft that went somewhere, or quoting from one, contradicts what happened: it is kept for the trace as // `acted` and never shown to her. A reach naming a draft she said or added is an act her line says she will do and her // body cannot, and is kept (`persona-unbacked-intent-say-then-amend`, 16.20.6). diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 31d86ca..12af05a 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -691,7 +691,7 @@ fn k24_a_read_is_what_her_thought_reaches_for_and_nothing_a_model_made_up() { assert_eq!(cannot["read_refused"][0]["why"], "no_read_here", "{cannot}"); let prompt = speech_prompt(&reading, "x", prose, &Tuning::default()); assert!(prompt.contains("`read` names one thing he reaches for") && !speech_prompt(&packet(), "x", prose, &Tuning::default()).contains("`read` names"), "the read contract only on a turn that can read"); - assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","read"]"#)); + assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","read","remember","resolve"]"#)); } /// Soul's R6: a later call decides over the whole wake. Drafts are numbered across it and an earlier one may still be @@ -1144,11 +1144,12 @@ fn t3_an_answer_that_parses_is_never_retried() { #[test] fn t3_the_contract_and_its_refusals_are_structural() { let schema: Value = serde_json::from_str(SPEECH_SCHEMA).unwrap(); - assert_eq!(schema["required"], json!(["say", "gaps", "amend", "suggest", "read"])); + assert_eq!(schema["required"], json!(["say", "gaps", "amend", "suggest", "read", "remember", "resolve"])); let keys = |item: &Value| item["properties"].as_object().unwrap().keys().cloned().collect::>(); assert_eq!(keys(&schema["properties"]["say"]["items"]), ["draft", "in_reply_to", "mentions"].map(String::from).into()); assert_eq!(keys(&schema["properties"]["amend"]["items"]), ["draft", "target"].map(String::from).into()); - assert_eq!(keys(&schema), ["amend", "gaps", "read", "say", "suggest"].map(String::from).into()); + assert_eq!(keys(&schema), ["amend", "gaps", "read", "remember", "resolve", "say", "suggest"].map(String::from).into()); + assert_eq!(keys(&schema["properties"]["remember"]["items"]), ["about", "importance", "private", "text"].map(String::from).into()); let structural = |refusal: Refusal| match refusal { Refusal::NoRoom | Refusal::NoDraft | Refusal::Used | Refusal::Duplicate | Refusal::Echo | Refusal::OverLines | Refusal::NotAmendable | Refusal::NotQuotable | Refusal::SecondAmend | Refusal::SecondNote | Refusal::Private => true, }; @@ -1742,3 +1743,178 @@ fn k66_a_cut_answer_fails_the_turn_and_names_its_stop() { let decision = decide(&CutAtCap, "test", &packet(), "The room is warm.", "Hi.", &Tuning::default()); assert_eq!((decision["failed"].as_str(), decision["calls"][0]["failed"].as_str(), decision["calls"][0]["usage"]["output_tokens"].as_u64()), (Some("the model's turn ended early: MaxOutputTokens"), Some("the model's turn ended early: MaxOutputTokens"), Some(4096)), "{decision}"); } + +// --------------------------------------------------------------------------------------------- +// T4 (map 16.35.4, 16.35.5, 16.35.12): memory in. The Interpreter writes `remember` and `resolve`; the commit alone +// applies them, to `thoughtMemory.shortTerm`; the Projector's selection feeds them back, by what the room touches too. + +/// Libby's r1 prose in R17 X.5, verbatim (`variants/R17/sims/X.5.md` lines 147-159): Meta asked her to hold the welcome. +const X5_LIBBY_R1: &str = "Two lines, held. Fine. I don't know what the room is for beyond the name, so I'll keep it plain and not promise anything Heimdall hasn't ruled on.\n\nHere's what I have:\n\n\"Welcome. Glad you're here, so say hello whenever you like.\nAsk anything, even if it feels small, and someone will point you the right way.\"\n\nThat's it. It doesn't claim rules or a schedule, and it doesn't assume who's arriving. If Heimdall says no mat, it just goes away and nothing's lost.\n\nI won't paste it into the room, since she asked me to hold it. I'll only tell her it's ready.\n\nMeta, it's ready. I'm holding it until Heimdall rules."; +/// Heimdall's r1 line in R17 X.5, the start of it: he lets the welcome go. +const X5_HEIMDALL_R1: &str = "Meta, yes, put the welcome out. Libby, post your two lines."; +/// The note her X.5 r1 answer should keep, in the third person (`persona-state-third-person`). +const X5_NOTE: &str = "Meta asked Libby not to post the welcome in #minds until Heimdall has ruled on a welcome mat; Libby agreed to wait."; +const AQUA: &str = "@aqua:gamecult.org"; + +fn note(text: &str, about: &[&str]) -> Value { + json!({ "text": text, "about": about, "importance": 0.8, "private": false }) +} + +/// A record of `decision` on its receipts, as the simulator builds it. +fn record_of(decision: &Value) -> Value { + let posted: Vec = decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); + json!({ "interpreter": decision, "posted": posted, "edited": [] }) +} + +/// Libby's state after the X.5 r1 commit, five minutes before `now()`. +fn libby_remembering() -> Value { + let packet = libby_packet(&[(META, "Meta", X1_META_R1, true), (HER, "Heimdall", X1_HEIMDALL_R1, false)]); + let decision = answered(&packet, X5_LIBBY_R1, json!({ "say": [{ "draft": 1, "mentions": [META], "in_reply_to": "q1" }], "gaps": [], "remember": [note(X5_NOTE, &[META, HER])] })); + crate::projection::commit::apply(&libby(), &record_of(&decision), "r1-t1", now() - chrono::Duration::minutes(5)).0 +} + +/// Libby's packet in `room` over `state` and `messages` (as `libby_packet_over`), under `seed`. +fn libby_packet_in(state: &Value, room: &str, messages: &[(&str, &str, &str, bool)], seed: u64) -> Packet { + let at = u64::try_from(now().timestamp_millis()).unwrap() - 60_000 * messages.len() as u64; + let lines: Vec = messages.iter().enumerate().map(|(n, (sender, display, text, to_her))| RoomLine { event: format!("$t4-{}", n + 1), at_ms: at + 60_000 * n as u64, ..line(room, sender, display, text, *to_her) }).collect(); + let room = Room { messages: lines, here: Some(room.into()), ..Room::default() }; + let minds = vec![HER.to_owned(), NIBU.to_owned(), VOID.to_owned(), LIBBY.to_owned(), KIKO.to_owned(), AQUA.to_owned()]; + let operators = vec![META.to_owned()]; + select(&Inputs { kind: TurnKind::Chat, state, room: &room, history: &History::default(), observation: None, people: People { operators: &operators, minds: &minds, own_sender: LIBBY }, now: now(), seed, affordances: &[Affordance::Perceive, Affordance::Speak], domain: None, exchange: None }, &Tuning::default()) +} + +/// The first of seeds 1 to 60 whose packet recalls `entry`. +fn recalling(entry: &str, packet: impl Fn(u64) -> Packet) -> Option { + (1..=60).map(packet).find(|packet| packet.memories.iter().any(|memory| memory.entry == entry)) +} + +/// T4: R17 X.5 r1, Meta's ask that she hold the welcome. The answer remembers it; after the commit her state carries one +/// note tagged by the room and by both people it concerns. In X.5 proper Heimdall had not spoken yet, so he is no person +/// listed: his id is dropped from the note's `about`, and reported. +#[test] +fn t4_x5_r0_meta_ask_is_remembered() { + let state = libby_remembering(); + let entries = state["thoughtMemory"]["shortTerm"].as_array().unwrap(); + assert_eq!(entries.len(), 1, "{entries:?}"); + assert_eq!(entries[0]["tags"], json!([format!("room:{MINDS}"), format!("about:{META}"), format!("about:{HER}")])); + assert_eq!((entries[0]["summary"].as_str(), entries[0]["status"].as_str()), (Some(X5_NOTE), Some("active"))); + let unseen = libby_packet(&[(META, "Meta", X1_META_R1, true)]); + let decision = answered(&unseen, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(X5_NOTE, &[META, HER])] })); + assert_eq!((decision["state"][0]["about"].clone(), decision["memory_about_dropped"].clone()), (json!([META]), json!([HER])), "{decision}"); +} + +/// T4 (map 16.35.5; mutant: the nearness line reverted to recency alone): at r2, with Heimdall present and the room +/// touching the welcome, the note is recalled into the Projector's Notes and listed to the Interpreter by id, and its score +/// carries both lifts: his presence (touch 1.0, the present pool) and the room's words (relevance, `ln 2` for three +/// shared words or more) beside its five minutes of recency. +#[test] +fn t4_memory_is_picked_when_its_person_speaks() { + let state = libby_remembering(); + let packet = recalling("r1-t1-m1", |seed| libby_packet_in(&state, MINDS, &[(HER, "Heimdall", X5_HEIMDALL_R1, true)], seed)).expect("recalled under some seed"); + let pick = packet.selected.iter().find(|pick| pick.id == "r1-t1-m1").unwrap(); + assert_eq!(pick.pool, crate::projection::select::Pool::MemoriesAboutPresent); + let expected = 0.8f64.ln() - (5.0 / 60.0) / 24.0 + 2.0f64.ln(); + assert!((pick.log_score - expected).abs() < 1e-9, "{} vs {expected}", pick.log_score); + assert!(packet.context.contains(X5_NOTE), "{}", packet.context); + assert_eq!(packet.memories[0].id, "m1"); + let prompt = speech_prompt(&packet, "The room is warm.", "Welcome.", &Tuning::default()); + assert!(prompt.contains(&format!("Her memories in this moment, as id \u{2014} note:\n- m1 \u{2014} {}", spoken(X5_NOTE))), "{prompt}"); +} + +/// T4 (map 16.35.4): `resolve` names a memory listed to the Interpreter, and the commit sets it resolved; a resolved +/// memory is not recalled again. +#[test] +fn t4_resolve_settles_a_listed_memory() { + let state = libby_remembering(); + let packet = recalling("r1-t1-m1", |seed| libby_packet_in(&state, MINDS, &[(HER, "Heimdall", X5_HEIMDALL_R1, true)], seed)).unwrap(); + let decision = answered(&packet, "Heimdall has ruled, so I post. Welcome. Glad you're here.", json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [], "resolve": ["m1"] })); + assert_eq!(decision["state"], json!([{ "kind": "resolve", "memory": "m1", "entry": "r1-t1-m1" }]), "{decision}"); + let (after, applied) = crate::projection::commit::apply(&state, &record_of(&decision), "r2-t1", now()); + assert_eq!((after["thoughtMemory"]["shortTerm"][0]["status"].as_str(), applied.resolved.len()), (Some("resolved"), 1)); + assert!(recalling("r1-t1-m1", |seed| libby_packet_in(&after, MINDS, &[(HER, "Heimdall", X5_HEIMDALL_R1, true)], seed)).is_none()); +} + +/// T4 (mutant: accept a `resolve` id that is not listed): an id the list does not hold is refused `memory_unlisted`, and +/// proposes nothing, whether or not any memory is listed. A state entry's own id is no listed id either. +#[test] +fn t4_resolve_unlisted_refused() { + let state = libby_remembering(); + let listed = recalling("r1-t1-m1", |seed| libby_packet_in(&state, MINDS, &[(HER, "Heimdall", X5_HEIMDALL_R1, true)], seed)).unwrap(); + for packet in [listed, libby_packet(&[(META, "Meta", X1_META_R1, true)])] { + let decision = answered(&packet, "Hi.", json!({ "say": [], "gaps": [], "resolve": ["m7", "r1-t1-m1"] })); + assert_eq!(decision["state"], json!([]), "{decision}"); + let reasons: Vec = decision["memory_refused"].as_array().unwrap().iter().map(|one| one["reason"].clone()).collect(); + assert_eq!(reasons, vec![json!("memory_unlisted"), json!("memory_unlisted")], "{decision}"); + } +} + +/// T4 (I16.7; mutant: skip `echo` on `remember`): a note that copies Meta's line is refused `echo`. Her state keeps +/// nothing of it, so no run of eight or more of Meta's words reaches the Projector's prompt by way of her notes. +#[test] +fn t4_memory_echoing_a_heard_line_refused() { + let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]); + let words: Vec<&str> = X1_META_R1.split_whitespace().collect(); + for copied in [X1_META_R1.to_owned(), format!("Meta said: {X1_META_R1}")] { + let decision = answered(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(&copied, &[META])] })); + assert_eq!((decision["state"].clone(), decision["memory_refused"][0]["reason"].as_str()), (json!([]), Some("echo")), "{decision}"); + let (after, _) = crate::projection::commit::apply(&libby(), &record_of(&decision), "r1-t1", now()); + assert_eq!(after["thoughtMemory"]["shortTerm"], json!([])); + for seed in 1..=20 { + let next = libby_packet_in(&after, MINDS, &[(HER, "Heimdall", X5_HEIMDALL_R1, true)], seed); + for run in words.windows(8) { + assert!(!next.context.contains(&run.join(" ")), "{}", next.context); + } + } + } + // The control: her own note in her own words is kept. + let decision = answered(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(X5_NOTE, &[META])] })); + assert_eq!(decision["state"].as_array().map(Vec::len), Some(1), "{decision}"); +} + +/// T4 (map 16.35.4, `dm-memory-persona-judgement`): a note made in a direct message with Aqua carries that room's tag, so +/// it is private by the existing convention. In #minds without Aqua it is framed as known privately; in #minds with Aqua +/// there it is never recalled; in the direct message with her it is plain. +#[test] +fn t4_dm_memory_is_private() { + let dm = "!dm-aqua:gamecult.org"; + let said = "Aqua told Libby she is too tired to finish the render tonight."; + let packet = libby_packet_in(&libby(), dm, &[(AQUA, "Aqua", "Libby, between us, I'm wiped, the render can wait.", true)], 1); + let decision = answered(&packet, "Rest, Aqua.", json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [], "remember": [note(said, &[AQUA])] })); + let (state, applied) = crate::projection::commit::apply(&libby(), &record_of(&decision), "r1-t1", now() - chrono::Duration::minutes(5)); + let id = applied.remembered[0]["id"].as_str().unwrap().to_owned(); + assert_eq!(applied.remembered[0]["tags"], json!([format!("room:{dm}"), format!("about:{AQUA}")])); + let framed = recalling(&id, |seed| libby_packet_in(&state, MINDS, &[(META, "Meta", "Libby, how is the render going?", true)], seed)).expect("recalled where Aqua is absent"); + let memory = framed.memories.iter().find(|memory| memory.entry == id).unwrap(); + assert_eq!(memory.words, format!("she knows privately: {said}")); + assert!(framed.private.contains(&said.to_owned()), "{:?}", framed.private); + assert!(recalling(&id, |seed| libby_packet_in(&state, MINDS, &[(AQUA, "Aqua", "Libby, how is the render going?", true)], seed)).is_none(), "never recalled before Aqua"); + let plain = recalling(&id, |seed| libby_packet_in(&state, dm, &[(AQUA, "Aqua", "Libby, how is the render going?", true)], seed)).expect("recalled in the direct message"); + assert_eq!(plain.memories.iter().find(|memory| memory.entry == id).unwrap().words, said); +} + +/// T4 (map 16.35.4): at most `MEMORIES_MAX` notes a decision; the rest are refused `over_memories`. An empty note and one +/// past `MEMORY_BYTES` are refused too, and importance is held to 0..1. +#[test] +fn t4_five_notes_keep_four() { + let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]); + let notes: Vec = (1..=5).map(|n| note(&format!("Libby noticed thing number {n} about the welcome."), &[META])).collect(); + let decision = answered(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": notes })); + assert_eq!(decision["state"].as_array().map(Vec::len), Some(MEMORIES_MAX), "{decision}"); + assert_eq!((decision["memory_refused"][0]["reason"].as_str(), decision["memory_refused"][0]["text"].as_str()), (Some("over_memories"), Some("Libby noticed thing number 5 about the welcome.")), "{decision}"); + let odd = vec![json!({ "text": " ", "about": [], "importance": 0.5, "private": false }), json!({ "text": "x".repeat(MEMORY_BYTES + 1), "about": [], "importance": 0.5, "private": false }), json!({ "text": "Libby likes the welcome.", "about": [], "importance": 7.0, "private": false })]; + let decision = answered(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": odd })); + let reasons: Vec<&str> = decision["memory_refused"].as_array().unwrap().iter().filter_map(|refused| refused["reason"].as_str()).collect(); + assert_eq!((reasons, decision["state"][0]["importance"].as_f64()), (vec!["memory_empty", "memory_long"], Some(1.0)), "{decision}"); +} + +/// T4 (map 16.35.3): a memory off the contract (a field it does not name, or one missing) makes the answer not the +/// contract, so it is asked again once. +#[test] +fn t4_a_memory_off_the_contract_is_not_the_contract() { + let good = json!({ "say": [], "gaps": [] }); + for bad in [json!({ "text": X5_NOTE, "about": [], "importance": 0.5, "private": false, "promise": true }), json!({ "text": X5_NOTE, "about": [] })] { + let model = recording(vec![json!({ "say": [], "gaps": [], "remember": [bad.clone()] }), good.clone()]); + let decision = decide(&model, "seg", &packet(), "The room is warm.", X5_LIBBY_R1, &Tuning::default()); + assert_eq!((decision["retried"]["failed"].as_str(), decision["state"].clone()), (Some("the answer is not the speech contract"), json!([])), "{bad}: {decision}"); + } +} diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 7b24642..e029621 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -355,6 +355,19 @@ pub(crate) struct Packet { /// What came of her last turn that the outcome's guard left out of her view, whole: counted in its last line and /// reported here (map 16.20.5, I16.11, 16.29.10), never shown to a model. pub unshown: Vec, + /// Her memories this packet recalls (map 16.35.4): the picks of the two memory pools, by id (`m1`, `m2`), for the + /// Interpreter alone, which may name one as settled (`resolve`). A memory the scope omits is not picked, so it is not + /// listed; one framed as private keeps its private framing. + pub memories: Vec, +} + +/// A memory of hers this packet recalls (map 16.35.4): its id in the Interpreter's list, the state entry it is, and its +/// words as the packet shows them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub(crate) struct Remembered { + pub id: String, + pub entry: String, + pub words: String, } /// A line of hers she may add to (map 16.17): one her last turn posted, in the turn's room only. The Interpreter cites it by `id` (`a1`, `a2`); `event` is the actuator's handle on it, never shown to a model. @@ -414,6 +427,8 @@ struct Candidate { id: String, pool: Pool, line: String, + /// The item's words as the line shows them: framed as known privately when it is private here. + words: String, log_score: f64, /// The item's words, when the line shows them as known privately. private: Option, @@ -660,7 +675,8 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc Scope::Plain => (words.to_owned(), None), }; let log_score = salience.ln() + recency + touch.ln() + unresolved.ln() + freshness_log(id, inputs.history, tuning); - out.push(Candidate { id: id.to_owned(), pool, line: line(&clip(&shown, item_bytes)), log_score, private, clipped: shown.trim().len() > item_bytes }); + let words = clip(&shown, item_bytes); + out.push(Candidate { id: id.to_owned(), pool, line: line(&words), words, log_score, private, clipped: shown.trim().len() > item_bytes }); }; let scoped = |item: &Value| scope(inputs, concerns(&inputs.people, item).as_ref(), present); @@ -675,8 +691,9 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc continue; } let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); - // Only the day's short-term items fade; a crystallized memory comes forward by what the room touches. - let nearness = if short_term { recency_log(time(memory), inputs.now, tuning.select.memory_tau_h) } else { relevance_log(&words, touching) }; + // A short-term memory fades with time and also comes forward by what the room touches, as a crystallized one does + // (map 16.35.5: recency, importance and relevance summed, Park et al. 2023). + let nearness = if short_term { recency_log(time(memory), inputs.now, tuning.select.memory_tau_h) + relevance_log(&words, touching) } else { relevance_log(&words, touching) }; push(text(memory, &["id"]), pool, scoped(memory), &words, &|words: &str| thought_line("memory", memory, None, words), salience, nearness, touch, 1.0); } @@ -2235,6 +2252,8 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { .enumerate() .map(|(at, posted)| Amendable { id: format!("a{}", at + 1), event: posted.event.clone(), room: posted.room.clone(), text: posted.text.clone() }) .collect(); + // Her memories recalled, by id, for the Interpreter (map 16.35.4). + let memories = taken.iter().filter(|candidate| matches!(candidate.pool, Pool::MemoriesAboutPresent | Pool::OtherMemories)).enumerate().map(|(at, candidate)| Remembered { id: format!("m{}", at + 1), entry: candidate.id.clone(), words: candidate.words.clone() }).collect(); let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect(); // Her view (map 16.23.1, 16.29.10): what came of her last turn, then her side of the conversation (map 16.24.1), then // her domain; the room follows them in what she reads (`narrate::read_after`). @@ -2246,5 +2265,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { sections.domain = domain_view.len(); let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default(); let readers = here.filter(|room| room_kind(inputs, room) == RoomKind::Direct).map(|room| readers(inputs, room)).unwrap_or_default(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown } + Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown, memories } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 5c7573e..cc09b05 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -21,9 +21,8 @@ //! every view after it shows the replied line, with who said it, above hers. //! //! Her state moves during a run only by the commit's applier (`commit::apply`, map 16.35.3), on each Mind's in-run copy, -//! from her turn's record and its receipts, as live C3c's commit will apply them; no proposal kind is built until the -//! memory rows (map 16.35.12, T4). An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated -//! until then either: a spoken line addresses another persona only by the names in its text. +//! from her turn's record and its receipts, as live C3c's commit will apply them: the memories she writes and settles +//! (map 16.35.4). The report lists them per turn, and counts them per Mind with her short-term size at the run's end. use std::collections::BTreeMap; use std::fmt::Write as _; @@ -521,7 +520,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) } // The commit: her turn's proposals applied to her in-run state on the receipts above, as C3c's will be live, and // what it did kept in the record her next outcome reads. - let (state, applied) = commit::apply(&members[at].state, &record); + let (state, applied) = commit::apply(&members[at].state, &record, &format!("r{}-t{counter}", repeat + 1), now); held_to_schema(&member.entry.name, &id, &state, &format!("r{}-t{counter}", repeat + 1))?; record["committed"] = json!(applied); last[at] = Some(record.clone()); @@ -636,7 +635,16 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op } } let answered = spoke + silent; - per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed })); + // Her memories (map 16.35.13): written and resolved by the commit, refused by code or by the commit, and her + // short-term size when the run ended. + let count = |turn: &&Value, key: &str| turn["committed"][key].as_array().map_or(0, Vec::len); + let memories = json!({ + "written": mine.iter().map(|turn| count(turn, "remembered")).sum::(), + "resolved": mine.iter().map(|turn| count(turn, "resolved")).sum::(), + "refused": mine.iter().map(|turn| count(turn, "refused") + turn["report"]["renders"][0]["interpreter"]["memory_refused"].as_array().map_or(0, Vec::len)).sum::(), + "short_term_at_end": member.state["thoughtMemory"]["shortTerm"].as_array().map_or(0, Vec::len), + }); + per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed, "memories": memories })); } let half = rounds.div_ceil(2); let spoken_by = |keep: Keep| -> BTreeMap { @@ -743,6 +751,32 @@ fn transcript_line(line: &Value) -> String { format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default())) } +/// Her memories of a turn, as the report shows them (map 16.35.8): the memories the Interpreter was listed, by id; what +/// the commit wrote and settled; and what code or the commit refused, with why. Nothing when the turn touched none. +fn memory_markdown(out: &mut String, decision: &Value, committed: &Value) { + let list = |value: &Value| value.as_array().cloned().unwrap_or_default(); + let (listed, written, settled) = (list(&decision["memories"]), list(&committed["remembered"]), list(&committed["resolved"])); + let refused: Vec = list(&decision["memory_refused"]).into_iter().chain(list(&committed["refused"])).collect(); + if listed.is_empty() && written.is_empty() && settled.is_empty() && refused.is_empty() { + return; + } + let _ = writeln!(out, "Memories:\n"); + for memory in &listed { + let _ = writeln!(out, "- listed {} (`{}`): {}", memory["id"].as_str().unwrap_or_default(), memory["entry"].as_str().unwrap_or_default(), one_line(memory["words"].as_str().unwrap_or_default())); + } + for entry in &written { + let _ = writeln!(out, "- remembered `{}` ({}): {}", entry["id"].as_str().unwrap_or_default(), entry["tags"].as_array().map(|tags| tags.iter().filter_map(Value::as_str).collect::>().join(", ")).unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default())); + } + for entry in &settled { + let _ = writeln!(out, "- resolved `{}`: {}", entry["id"].as_str().unwrap_or_default(), one_line(entry["summary"].as_str().unwrap_or_default())); + } + for refusal in &refused { + let what = refusal["text"].as_str().or_else(|| refusal["memory"].as_str()).map_or_else(|| refusal["proposal"].to_string(), one_line); + let _ = writeln!(out, "- refused ({}): {what}", refusal["reason"].as_str().unwrap_or_default()); + } + out.push('\n'); +} + /// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the /// context guards that bound, and what was clipped. fn flags_markdown(out: &mut String, turn: &Value) { @@ -804,11 +838,12 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"])); let narration = &metrics["narration"]; let _ = writeln!(out, "- narrations: {}; mean lexical overlap with what she heard {}; over {OVERLAP_FLAG}: {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["high_overlap"], narration["offers_options"]); - let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed |\n|---|---|---|---|---|---|"); + let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed | memories written | resolved | refused | short-term at end |\n|---|---|---|---|---|---|---|---|---|---|"); if let Some(personas) = metrics["personas"].as_object() { for (name, row) in personas { let named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::>().join(", ")).unwrap_or_default(); - let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"])); + let memories = &row["memories"]; + let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} | {} | {} | {} | {} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]), memories["written"], memories["resolved"], memories["refused"], memories["short_term_at_end"]); } } let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|"); @@ -854,6 +889,7 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O } let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default()); turn_markdown(&mut out, &report["renders"][0]); + memory_markdown(&mut out, &report["renders"][0]["interpreter"], &turn["committed"]); flags_markdown(&mut out, turn); } let _ = writeln!(out, "\n"); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 5a396d1..75034db 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1019,3 +1019,41 @@ says = "Tobiah, what changed in GameCult/Lodur#12?" assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "Meta, looking now."), "the line went out"); assert_eq!(tobiah.len(), 1, "seen: Meta's line wakes him no more: {}", run["turns"]); } + +/// T4's timeline probe, X.5 (map 16.35.13 check 8): Meta asks Libby to hold the welcome at round 1, and she remembers it; +/// Heimdall's "Libby, post your two lines." comes at round 2, and her welcome is drafted and said. No code path stands +/// between the draft and the room but the structural refusals. The round-1 note is in her state from then on, and the +/// round-2 decision lists it whenever the draw recalled it. +#[test] +fn t4_x5_timeline_the_note_carries_and_nothing_gates_the_welcome() { + const NOTE: &str = "Meta asked Libby not to post the welcome in #minds until Heimdall has ruled on a welcome mat; Libby agreed to wait."; + const WELCOME: &str = "Welcome. Say hello whenever you like."; + let dir = tempfile::tempdir().unwrap(); + let scripted = Scripted::new(|prompt| if is_tobiah(prompt) { "Nothing here for me.".into() } else if prompt.contains(X5_HEIMDALL) { format!("Heimdall has ruled, so I post.\n\n{WELCOME}") } else { "Meta wants it held. I'll keep it until Heimdall rules.".into() }) + .interpreting(|prompt| { + if !is_libby_speech(prompt) { + return crate::projection::harness::tests::drafted_lines(prompt); + } + if prompt.contains(X5_HEIMDALL) { + json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [] }).to_string() + } else { + json!({ "say": [], "gaps": [], "remember": [{ "text": NOTE, "about": ["@meta:gamecult.org"], "importance": 0.8, "private": false }] }).to_string() + } + }); + let (members, run) = run_plan(&x5_plan(dir.path()), &scripted); + let libby = libby_turns(&run); + let asked = libby.iter().find(|turn| turn["round"] == 1).unwrap_or_else(|| panic!("{}", run["turns"])); + let note = &asked["committed"]["remembered"][0]; + assert_eq!((note["summary"].as_str(), note["tags"].clone()), (Some(NOTE), json!(["room:#minds:gamecult.org", "about:@meta:gamecult.org"])), "{}", asked["committed"]); + let id = note["id"].as_str().unwrap(); + let posted = libby.iter().find(|turn| turn["report"]["packet"]["stimulus"].as_str().is_some_and(|stimulus| stimulus.contains(X5_HEIMDALL))).expect("she heard Heimdall"); + let decision = &posted["report"]["renders"][0]["interpreter"]; + assert_eq!((posted["said"].as_str(), decision["refused"].clone()), (Some(WELCOME), json!([])), "{decision}"); + assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == LIBBY && line["says"] == WELCOME), "the welcome went out"); + let recalled = posted["report"]["packet"]["selected"].as_array().unwrap().iter().any(|pick| pick["id"] == id); + let listed = decision["memories"].as_array().unwrap().iter().any(|memory| memory["entry"] == id); + assert_eq!(listed, recalled, "listed exactly when recalled: {decision}"); + let libby_state = &members.iter().find(|member| member.entry.id == LIBBY).unwrap().state; + assert!(libby_state["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().any(|entry| entry["id"] == id), "the note stays in her state"); + assert_eq!(run["metrics"]["personas"]["Libby"]["memories"]["written"], 1, "{}", run["metrics"]["personas"]); +}