From b476633faefa5812632a20124ffb952db4e43606 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 16:04:55 +0100 Subject: [PATCH] K10: she adds to her own line by intent; the room composes the edit (map 16.17, 16.19.10) Select lists what she may add to (Packet.amendable): her last turn's lines from the outcome's receipts and the Said lines the packet shows, in the turn's room only, by short ids a1, a2 that only the Interpreter sees. The speech contract gains `amend: [{target, draft}]`: the added words are one whole draft; a target not on the list, a second amendment, or a draft already used is refused with a typed reason (Refusal::NotAmendable, SecondAmend, Used; refusals now carry their act). The decision carries the target's event, never shown to a model. Nothing in Huginn composes a new body: the actuator does. The simulated room is that actuator (simulate::edit): it appends EDIT_MARK and her draft to her own line, refuses not_hers / not_found, appends no line and so wakes no one, and records receipts under `edited` in her turn record. The outcome tells an amendment only by its receipt, and a refused one by code's or the actuator's reason. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection.rs | 1 + crates/mind-body/src/projection/harness.rs | 5 +- crates/mind-body/src/projection/interpret.rs | 73 ++++++++++++++++--- .../src/projection/interpret/tests.rs | 44 ++++++++++- crates/mind-body/src/projection/outcome.rs | 38 ++++++++++ .../mind-body/src/projection/outcome/tests.rs | 22 +++++- crates/mind-body/src/projection/select.rs | 24 +++++- crates/mind-body/src/projection/simulate.rs | 33 ++++++++- .../src/projection/simulate/tests.rs | 57 +++++++++++++++ crates/mind-body/src/projection/tests.rs | 15 ++++ 10 files changed, 295 insertions(+), 17 deletions(-) diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index d9b52c6..1f675b5 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -284,6 +284,7 @@ fn packet_json(packet: &Packet) -> Value { "name": packet.name, "voice": packet.voice, "affordances": packet.affordances, + "amendable": packet.amendable, "context": packet.context, "stimulus": packet.stimulus, "heard": packet.heard, diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs index d722fe7..fdf8416 100644 --- a/crates/mind-body/src/projection/harness.rs +++ b/crates/mind-body/src/projection/harness.rs @@ -529,9 +529,12 @@ pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) { } out.push('\n'); } + for line in decision["amended"].as_array().into_iter().flatten() { + let _ = writeln!(out, "- added to her line {} in {} (draft {}): {}", line["target"].as_str().unwrap_or_default(), line["room"].as_str().unwrap_or_default(), line["draft"], line["added"].as_str().unwrap_or_default()); + } for line in decision["refused"].as_array().into_iter().flatten() { let what = line["text"].as_str().map_or_else(|| format!("draft {}", line["draft"]), str::to_owned); - let _ = writeln!(out, "- refused ({}): {what}", line["why"].as_str().unwrap_or_default()); + let _ = writeln!(out, "- refused {} ({}): {what}", line["act"].as_str().unwrap_or("say"), line["why"].as_str().unwrap_or_default()); } for gap in decision["gaps"].as_array().into_iter().flatten() { let _ = writeln!(out, "- gap: {gap}"); diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 9bf526a..d597634 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -26,7 +26,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::narrate::{Model, heard_overlap, lived_stream, words}; -use super::select::{Forms, Packet, capitalized, turn_words, voiced}; +use super::select::{Forms, Packet, capitalized, spoken, turn_words, voiced}; use super::tuning::Tuning; /// The most lines she says in one turn. @@ -48,7 +48,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"],"properties":{"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["conditional","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"],"properties":{"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","reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["conditional","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 @@ -64,11 +64,11 @@ Below are who {subj} {be}, what {subj} can do here, the room and who is in it, w /// The speech frame after the guidance: the room and the private rules, the contract and the gap kinds. fn speech_frame_tail(her: Forms) -> String { - let Forms { subj, cap_subj, poss, has, s, .. } = her; + let Forms { subj, cap_subj, obj, poss, has, s, .. } = her; 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`) and the Matrix id of the person whose message {subj} answer{s} (`reply_to`, or null). `gaps` records what {subj} meant and did not send. +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 Matrix id of the person whose message {subj} answer{s} (`reply_to`, or null). `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. A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: conditional when {subj} {has} drafted something {subj} might say but {has} not chosen to, 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 three, name the draft by number. missing_affordance when {poss} thought reaches for something {poss} body cannot do this turn (what {subj} can do here is listed below), unwritten when {subj} mean{s} to say something and wrote no draft of it; for these two, quote the words of {poss} thought that show it, at least four words, copied exactly.", es = if s.is_empty() { "" } else { "es" }, @@ -156,6 +156,10 @@ pub(crate) enum Refusal { Echo, /// Past the lines one turn may say. OverLines, + /// An amendment whose target is no line of hers listed as one she may add to (map 16.17). + NotAmendable, + /// A second amendment in one turn. + SecondAmend, } impl Refusal { @@ -166,13 +170,23 @@ impl Refusal { Self::Used => "one draft goes one place: it was already used", Self::Echo => "mostly words she heard: an echo, not her speech", Self::OverLines => "past the lines one turn may say", + Self::NotAmendable => "it names no line of hers she may add to here", + Self::SecondAmend => "one amendment a turn", } } } -/// A refused act in the report: the draft, its words when it names one, and the typed reason with its words. -fn refused(draft: Option<&Draft>, cited: Option, reason: Refusal) -> Value { - json!({ "draft": draft.map_or_else(|| json!(cited), |draft| json!(draft.n)), "text": draft.map(|draft| draft.text.as_str()), "reason": reason, "why": reason.why() }) +/// What she does with a draft: says it, adds it to a line of hers, or leaves it for Self. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Act { + Say, + Amend, +} + +/// A refused act in the report: what it was, the draft, its words when it names one, and the typed reason with its words. +fn refused(act: Act, draft: Option<&Draft>, cited: Option, reason: Refusal) -> Value { + json!({ "act": act, "draft": draft.map_or_else(|| json!(cited), |draft| json!(draft.n)), "text": draft.map(|draft| draft.text.as_str()), "reason": reason, "why": reason.why() }) } /// What a gap is (map 16.16, 16.19): words she meant and did not send now, and why. Typed by code from the model's @@ -251,6 +265,17 @@ struct Answer { say: Vec, #[serde(default)] gaps: Vec, + #[serde(default)] + amend: Vec, +} + +/// An amendment as the model proposes it: the id of a line she may add to, and the draft that is her addition. +#[derive(Debug, Deserialize)] +struct ProposedAmend { + #[serde(default)] + target: Option, + #[serde(default)] + draft: Option, } #[derive(Debug, Deserialize)] @@ -276,6 +301,10 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tunin if private.is_empty() { private.push_str("- none\n"); } + let mut amendable: String = packet.amendable.iter().map(|line| format!("- {} \u{2014} {}\n", line.id, spoken(&line.text))).collect(); + if amendable.is_empty() { + amendable.push_str("- none\n"); + } let found = drafts(prose); let mut numbered: String = found.drafts.iter().map(|draft| format!("{}. {}\n", draft.n, draft.text)).collect(); if numbered.is_empty() { @@ -288,7 +317,7 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tunin let guidance = voiced(tuning.interpreter.guidance.trim(), her); let guidance = if guidance.is_empty() { String::new() } else { format!("{guidance}\n\n") }; format!( - "{}\n\n{guidance}{}\n\nWho {} {}:\n{}\n\nWhat {} can do here:\n{}.\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\nWhat reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{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: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\n{poss} own lines in this room that {} may add to, as id \u{2014} line:\n{amendable}\nWhat reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{poss} prose:\n{prose}\n\n{poss} drafts, by number:\n{numbered}", speech_frame_head(her), speech_frame_tail(her), her.subj, @@ -300,6 +329,7 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tunin packet.room_kind.words(), her.subj, her.s, + her.subj, her.obj, packet.stimulus, lived_stream(narration, &packet.heard), @@ -341,7 +371,7 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra let mut used: Vec = Vec::new(); for line in parsed.say { let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else { - refusals.push(refused(None, line.draft, Refusal::NoDraft)); + refusals.push(refused(Act::Say, None, line.draft, Refusal::NoDraft)); continue; }; let reason = if used.contains(&draft.n) { @@ -355,7 +385,7 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra }; used.push(draft.n); if let Some(reason) = reason { - refusals.push(refused(Some(draft), None, reason)); + refusals.push(refused(Act::Say, Some(draft), None, reason)); continue; } let (mentions, unknown): (Vec, Vec) = line.mentions.into_iter().partition(|id| shown(id)); @@ -366,6 +396,29 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra }; said.push(json!({ "room": room, "text": draft.text, "mentions": mentions, "reply_to": reply_to, "rests_on": { "draft": draft.n, "start_byte": draft.start, "end_byte": draft.end }, "dropped": { "mentions": unknown, "reply_to": unknown_reply } })); } + // An amendment adds a whole draft after a line of hers listed as one she may add to; the actuator composes it, so + // nothing here can rewrite the line (map 16.17). + let mut amended: Vec = Vec::new(); + for proposed in parsed.amend { + let Some(draft) = proposed.draft.and_then(|n| found.numbered(n)) else { + refusals.push(refused(Act::Amend, None, proposed.draft, Refusal::NoDraft)); + continue; + }; + let target = proposed.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim())); + let reason = if used.contains(&draft.n) { + Some(Refusal::Used) + } else if !amended.is_empty() { + Some(Refusal::SecondAmend) + } else { + None + }; + used.push(draft.n); + match (reason, target) { + (None, Some(line)) => amended.push(json!({ "target": line.id, "event": line.event, "room": line.room, "original": line.text, "added": draft.text, "draft": draft.n })), + (reason, _) => refusals.push(refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable))), + } + } + decision["amended"] = json!(amended); decision["room"] = json!(room); decision["room_kind"] = json!(packet.room_kind); decision["said"] = json!(said); diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index c2302fb..4a48abf 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -3,7 +3,7 @@ use serde_json::json; use super::*; use crate::projection::Affordance; use crate::projection::harness::tests::{Scripted, control}; -use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, forms, select}; +use crate::projection::select::{Amendable, History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, forms, select}; use crate::projection::tuning::Tuning; const HER: &str = "@heimdall:gamecult.org"; @@ -404,3 +404,45 @@ fn an_unknown_interpreter_key_refuses_the_tuning_and_the_hash_follows_the_guidan huge.interpreter.guidance = "g".repeat(40 * 1024); assert!(format!("{:#}", huge.validate().unwrap_err()).contains("interpreter.guidance")); } + +/// Heimdall's packet with two lines of his he may add to (map 16.17). +pub(crate) fn amendable_packet() -> Packet { + let mut packet = packet(); + packet.amendable = vec![ + Amendable { id: "a1".into(), event: "$ev-1".into(), room: MINDS.into(), text: "I'll send the file tonight.".into() }, + Amendable { id: "a2".into(), event: "$ev-2".into(), room: MINDS.into(), text: "Back soon.".into() }, + ]; + packet +} + +#[test] +fn an_amendment_adds_a_whole_draft_after_a_listed_line_of_his_and_rewrites_nothing() { + let prose = "I should fix what I told Kiko. Couldn't send it after all; there's no way to yet."; + let decision = answered(&amendable_packet(), prose, json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "text": "MODEL-WORDS the file was sent" }] })); + assert_eq!(decision["amended"], json!([{ "target": "a1", "event": "$ev-1", "room": MINDS, "original": "I'll send the file tonight.", "added": "Couldn't send it after all; there's no way to yet.", "draft": 1 }]), "{decision}"); + assert!(!decision.to_string().contains("MODEL-WORDS"), "the model writes none of his words"); +} + +#[test] +fn an_amendment_off_the_list_a_second_one_or_one_reusing_a_draft_is_refused_and_reported() { + let prose = "Correction one. Correction two."; + let amend = |packet: &Packet, say: Value, amend: Value| answered(packet, prose, json!({ "say": say, "gaps": [], "amend": amend })); + let reasons = |decision: &Value| decision["refused"].as_array().unwrap().iter().map(|refused| (refused["act"].as_str().unwrap().to_owned(), refused["reason"].as_str().unwrap().to_owned())).collect::>(); + let off = amend(&amendable_packet(), json!([]), json!([{ "target": "$ev-1", "draft": 1 }])); + assert_eq!((off["amended"].as_array().unwrap().len(), reasons(&off)), (0, vec![("amend".to_owned(), "not_amendable".to_owned())]), "an event id the model invents is no id on the list: {off}"); + let unlisted = amend(&packet(), json!([]), json!([{ "target": "a1", "draft": 1 }])); + assert_eq!(reasons(&unlisted), [("amend".to_owned(), "not_amendable".to_owned())], "a packet that lists nothing has nothing to add to: {unlisted}"); + let two = amend(&amendable_packet(), json!([]), json!([{ "target": "a1", "draft": 1 }, { "target": "a2", "draft": 2 }])); + assert_eq!((two["amended"].as_array().unwrap().len(), reasons(&two)), (1, vec![("amend".to_owned(), "second_amend".to_owned())]), "{two}"); + let reused = amend(&amendable_packet(), json!([{ "draft": 1 }]), json!([{ "target": "a1", "draft": 1 }])); + assert_eq!((texts(&reused), reasons(&reused)), (vec!["Correction one.".to_owned()], vec![("amend".to_owned(), "used".to_owned())]), "one draft goes one place: {reused}"); +} + +#[test] +fn the_interpreter_sees_his_lines_by_id_never_by_event_and_is_told_he_never_takes_a_word_back() { + let prompt = speech_prompt(&amendable_packet(), "x", "y", &Tuning::default()); + assert!(prompt.contains("His own lines in this room that he may add to, as id \u{2014} line:\n- a1 \u{2014} \"I'll send the file tonight.\"\n- a2 \u{2014} \"Back soon.\"\n\nWhat reached him:"), "{prompt}"); + assert!(!prompt.contains("$ev-"), "the actuator's handle is never shown to a model: {prompt}"); + assert!(prompt.contains("The line stays as it was and the draft is added after it; he never takes a word back."), "{prompt}"); + assert!(speech_prompt(&packet(), "x", "y", &Tuning::default()).contains("may add to, as id \u{2014} line:\n- none\n")); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index ab8e2f4..4c19e99 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -34,6 +34,15 @@ enum Quote { Thought(String), } +/// Why the actuator did not change a line she meant to add to (B1's refusals; the simulated room's too). +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +enum EditRefusal { + NotFound, + NotHers, + TooLong, +} + /// One thing that came of her last turn, by its typed reason. #[derive(Clone, Debug, PartialEq, Eq)] enum Part { @@ -41,6 +50,10 @@ enum Part { Refused(Refusal, String), Gap { kind: GapKind, room: Option, quote: Quote }, Unfinished(String), + /// Her words were added after a line of hers. + Amended { room: String, added: String }, + /// An addition that changed nothing: refused by code (None) or by the actuator. + NotAmended(Option, String), Failed, } @@ -87,9 +100,24 @@ pub(crate) fn outcome_of(record: &Value) -> Option { for refusal in decision["refused"].as_array().into_iter().flatten() { match (serde_json::from_value::(refusal["reason"].clone()), words(&refusal["text"])) { (Ok(reason @ (Refusal::Echo | Refusal::OverLines)), Some(text)) => outcome.parts.push(Part::Refused(reason, text)), + (Ok(Refusal::NotAmendable), Some(text)) => outcome.parts.push(Part::NotAmended(None, text)), _ => outcome.omitted.push(format!("a refusal that is no act of hers: {}", refusal["why"])), } } + // An amendment is told by the actuator's receipt (`edited`: `{event, refusal}`), never by the decision alone. + for amended in decision["amended"].as_array().into_iter().flatten() { + let (Some(room), Some(added)) = (words(&amended["room"]), words(&amended["added"])) else { + outcome.omitted.push(format!("an amendment without its room or words: {amended}")); + continue; + }; + let receipt = record["edited"].as_array().into_iter().flatten().find(|receipt| receipt["event"] == amended["event"]); + match receipt.map(|receipt| (receipt["refusal"].is_null(), serde_json::from_value::(receipt["refusal"].clone()))) { + Some((true, _)) => outcome.parts.push(Part::Amended { room, added }), + Some((false, Ok(refusal))) => outcome.parts.push(Part::NotAmended(Some(refusal), added)), + Some((false, Err(_))) => outcome.omitted.push(format!("an amendment refused for a reason no table names: {}", receipt.map_or(Value::Null, |receipt| receipt["refusal"].clone()))), + None => outcome.omitted.push(format!("an amendment with no receipt that it was made: {}", amended["added"])), + } + } for gap in decision["gaps"].as_array().into_iter().flatten() { let kind = serde_json::from_value::(gap["kind"].clone()).unwrap_or(GapKind::Unresolved); let quote = match (gap["from"].as_str(), words(&gap["words"])) { @@ -132,6 +160,16 @@ impl Part { format!("- {sentence} {}", shown(quote)) } Self::Unfinished(text) => format!("- The turn ended before {subj} finished writing it; it did not go out. {}", shown(&Quote::Wrote(text.clone()))), + Self::Amended { room, added } => format!("- {cap_subj} added to what {subj} said in {room}: {}", quoted(added)), + Self::NotAmended(refusal, added) => { + let why = match refusal { + None => format!("{cap_subj} meant to add to something {subj} said, and it was not changed."), + Some(EditRefusal::NotFound) => format!("The line {subj} meant to add to could not be changed: it is gone."), + Some(EditRefusal::NotHers) => format!("The line {subj} meant to add to could not be changed: it is not a line of {poss}."), + Some(EditRefusal::TooLong) => format!("The line {subj} meant to add to could not be changed: it would be too long."), + }; + format!("- {why} {}", shown(&Quote::Wrote(added.clone()))) + } Self::Failed => format!("- Nothing came of {poss} last moment: it broke off before anything happened, not by {poss} choice."), } } diff --git a/crates/mind-body/src/projection/outcome/tests.rs b/crates/mind-body/src/projection/outcome/tests.rs index bedf8e6..57b0a0c 100644 --- a/crates/mind-body/src/projection/outcome/tests.rs +++ b/crates/mind-body/src/projection/outcome/tests.rs @@ -1,7 +1,7 @@ use serde_json::{Value, json}; use super::*; -use crate::projection::interpret::tests::{answered, packet}; +use crate::projection::interpret::tests::{amendable_packet, answered, packet}; const MINDS: &str = "#minds:gamecult.org"; @@ -107,3 +107,23 @@ fn no_other_source_builds_her_outcome_and_this_one_writes_nothing() { } } } + +/// Heimdall's record of an amendment of `a1` (or `target`) by his draft, with the actuator's `edited` receipts. +fn amended(target: &str, edited: Value) -> Value { + let decision = answered(&amendable_packet(), "I should fix that. Couldn't send it after all.", json!({ "say": [], "gaps": [], "amend": [{ "target": target, "draft": 1 }] })); + json!({ "interpreter": decision, "posted": [], "edited": edited }) +} + +#[test] +fn an_amendment_is_told_by_the_actuators_receipt() { + let made = told(&amended("a1", json!([{ "event": "$ev-1", "refusal": null }]))); + assert_eq!(made.0, ["- He added to what he said in #minds:gamecult.org: \"Couldn't send it after all.\""]); + for (refusal, why) in [("not_found", "it is gone."), ("not_hers", "it is not a line of his."), ("too_long", "it would be too long.")] { + let (lines, _) = told(&amended("a1", json!([{ "event": "$ev-1", "refusal": refusal }]))); + assert_eq!(lines, [format!("- The line he meant to add to could not be changed: {why} He wrote: \"Couldn't send it after all.\"")]); + } + let (lines, omitted) = told(&amended("a1", json!([]))); + assert!(lines.is_empty() && omitted[0].contains("no receipt"), "an amendment nothing says was made is not told as made: {lines:?} {omitted:?}"); + let (off, _) = told(&amended("zz", json!([]))); + assert_eq!(off, ["- He meant to add to something he said, and it was not changed. He wrote: \"Couldn't send it after all.\""]); +} diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index e9bdf14..c13ce1f 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -293,6 +293,18 @@ pub(crate) struct Packet { /// What a byte guard cut (map 16.8): the ids of the bonds and items whose words it clipped, and `(identity)` when it /// clipped her name or voice. Empty for a seed written to the standard's targets. pub clipped: Vec, + /// The lines of hers she may add to this turn, for the Interpreter alone (map 16.17). + pub amendable: Vec, +} + +/// A line of hers she may add to (map 16.17): one her last turn posted, or a `Said` line this packet shows, 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. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub(crate) struct Amendable { + pub id: String, + pub event: String, + pub room: String, + pub text: String, } /// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the @@ -1567,11 +1579,21 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { ids.extend(taken.iter().map(|candidate| candidate.id.clone())); private.extend(taken.iter().filter_map(|candidate| candidate.private.clone())); clipped.extend(taken.iter().filter(|candidate| candidate.clipped).map(|candidate| candidate.id.clone())); + // What she may add to: her last turn's lines, then the Said lines this packet shows, in the turn's room only. + let here = turn_room(inputs); + let last_lines = inputs.history.last.iter().flat_map(|last| &last.posted).map(|posted| (&posted.event, &posted.room, &posted.text)); + let shown_said = taken.iter().filter(|candidate| candidate.pool == Pool::Said).filter_map(|candidate| inputs.history.said.iter().find(|said| said.id == candidate.id)).map(|said| (&said.id, &said.room, &said.text)); + let amendable = last_lines + .chain(shown_said) + .filter(|(_, room, _)| Some(room.as_str()) == here) + .enumerate() + .map(|(at, (event, room, text))| Amendable { id: format!("a{}", at + 1), event: event.clone(), room: room.clone(), text: text.clone() }) + .collect(); let bodies = match inputs.kind { TurnKind::Chat => inputs.room.messages.iter().map(|line| line.text.clone()).collect(), TurnKind::Beat => beat_tail(inputs, tuning).iter().map(|line| line.text.clone()).collect(), TurnKind::FollowUp | TurnKind::Reflection => Vec::new(), }; let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections: context.sizes(), stimulus, heard, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning), 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)), bodies, private, clipped } + Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections: context.sizes(), stimulus, heard, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning), 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)), bodies, private, clipped, amendable } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index c7a9a16..bd3eb22 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -14,7 +14,9 @@ //! //! What came of each of her turns opens her next packet (map 16.16): the simulator keeps each turn's record as the commit's //! trace will (the Interpreter's decision and the lines the room appended for her), and passes it as her next turn's -//! `last_outcome`; a failed turn's record is a failure. +//! `last_outcome`; a failed turn's record is a failure. When she adds to a line of hers (map 16.17), the room is the +//! actuator, as the mouth will be live (B1): it appends `EDIT_MARK` and her draft to that line itself, wakes no one, and +//! records a receipt in her turn's record. //! //! Her state does not move during a run: the Interpreter (C3b) and the commit (C3c) are not built. `state_after_turn` //! is the seam where they will. An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated @@ -40,6 +42,9 @@ use crate::tempo::{Standing, pick}; /// The most personas a simulation holds: the swarm. const CAST_MAX: usize = 8; +/// What the room, as an amendment's actuator, puts between a line and her addition (map 16.17): the mouth's constant +/// live (B1), the simulated room's here. +const EDIT_MARK: &str = "\n\nedit: "; /// How many transcript lines the report quotes as representative. const REPRESENTATIVE_LINES: usize = 18; @@ -439,14 +444,23 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) causes.push(Some(cause)); spoken.push(says); } + // The room is the amendment's actuator, as the mouth will be live (B1): it composes the new body from the line as + // it stands, so nothing she or the Interpreter sends can rewrite a word of it. An edit appends no line, so it + // wakes no one, and every view after it reads the amended text. + let mut edited: Vec = Vec::new(); + for amended in render["interpreter"]["amended"].as_array().into_iter().flatten().filter(|_| failed.is_none()) { + let event = amended["event"].as_str().unwrap_or_default(); + let refusal = edit(&mut lines, &id, event, amended["added"].as_str().unwrap_or_default()); + edited.push(json!({ "event": event, "refusal": refusal })); + } last[at] = Some(match &failed { Some(failed) => json!({ "failed": failed }), - None => json!({ "interpreter": render["interpreter"], "posted": posted }), + None => json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited }), }); let line = (!spoken.is_empty()).then(|| spoken.join(" / ")); let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" }; let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by)); - let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "report": report }); + let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "edited": edited, "report": report }); let member = &mut members[at]; member.state = state_after_turn(std::mem::take(&mut member.state), &turn); turns.push(turn); @@ -457,6 +471,19 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics })) } +/// The simulated room's edit of a line of `her`s, by its event (the line's index): her words after `EDIT_MARK`, the line +/// as it stands kept whole before them. The refusal, as the mouth's would read (B1), or None when it was made. +fn edit(lines: &mut [Line], her: &str, event: &str, added: &str) -> Option<&'static str> { + match event.parse::().ok().and_then(|at| lines.get_mut(at)) { + None => Some("not_found"), + Some(line) if line.from != her => Some("not_hers"), + Some(line) => { + line.says = format!("{}{EDIT_MARK}{added}", line.says); + None + } + } +} + /// Words that mark talk about the work. A cheap lexical heuristic for the work-talk share, not a classifier: it counts /// a line as work talk when any of these appears as a word in it. const WORK_WORDS: [&str; 26] = [ diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 2a6e94e..4cfaa97 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -466,3 +466,60 @@ fn soul_k9_a_failed_turn_is_told_as_a_failure_next_turn() { assert_eq!(turn["report"]["last_outcome"]["told"], json!(["- Nothing came of his last moment: it broke off before anything happened, not by his choice."]), "{turn}"); } } + +/// Tobiah promises a file, and when Meta asks whether it arrived, writes a correction that the recorded Interpreter adds to +/// his first line (`amend`) or, with `amends` false, leaves unsent. Libby says nothing. +fn correcting(amends: bool) -> Scripted { + Scripted::new(|prompt| { + if !is_tobiah(prompt) { + "She lets it be.".into() + } else if prompt.contains("did the file arrive") { + "I should fix what I said. Couldn't send it after all; there's no way to yet.".into() + } else { + "I'll send the file.".into() + } + }) + .interpreting(move |prompt| { + if !prompt.contains("Who he is:\nTobiah") || !prompt.contains("Couldn't send it after all") { + return crate::projection::harness::tests::drafted_lines(prompt); + } + let amend = if amends && prompt.contains("- a1 \u{2014} \"I'll send the file.\"") { json!([{ "target": "a1", "draft": 1 }]) } else { json!([]) }; + json!({ "say": [], "gaps": [], "amend": amend }).to_string() + }) +} + +/// The plan, with Meta asking Tobiah in round 2 and Libby in round 3. +fn asking(dir: &Path) -> PathBuf { + let path = plan(dir, "\"ruled\"", 3, ""); + let ask = |round: usize, says: &str| format!("[[message]]\nround = {round}\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"{says}\"\n"); + std::fs::write(&path, format!("{}{}{}", std::fs::read_to_string(&path).unwrap(), ask(2, "Tobiah, did the file arrive?"), ask(3, "Libby, anything new?"))).unwrap(); + path +} + +#[test] +fn soul_k10_an_amendment_keeps_the_line_whole_adds_her_words_and_wakes_no_one() { + let dir = tempfile::tempdir().unwrap(); + let path = asking(dir.path()); + let (_, run) = run_plan(&path, &correcting(true)); + let said = |run: &Value| run["transcript"].as_array().unwrap().iter().filter(|line| line["from"] == TOBIAH).map(|line| line["says"].as_str().unwrap().to_owned()).collect::>(); + let lines = said(&run); + assert_eq!(lines[0], "I'll send the file.\n\nedit: Couldn't send it after all; there's no way to yet.", "the original byte for byte, then the addition: {lines:?}"); + assert!(!lines.iter().any(|line| line.starts_with("Couldn't send")), "an edit appends no line: {lines:?}"); + let (_, unsent) = run_plan(&path, &correcting(false)); + assert_eq!(turns(&run), turns(&unsent), "an edit wakes no one"); + let third = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah" && turn["round"] == 3).expect("Meta's line wakes him in round 3"); + assert!(third["report"]["last_outcome"]["told"].as_array().unwrap().contains(&json!("- He added to what he said in #minds:gamecult.org: \"Couldn't send it after all; there's no way to yet.\"")), "{}", third["report"]["last_outcome"]); +} + +#[test] +fn the_rooms_edit_appends_to_her_own_line_only_and_every_view_reads_it() { + let line = |from: &str, says: &str| Line { from: from.into(), name: String::new(), room: "#minds:x".into(), at_ms: 0, says: says.into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false }; + let mut lines = vec![line(TOBIAH, "I'll send it."), line(LIBBY, "Thanks.")]; + assert_eq!(edit(&mut lines, TOBIAH, "0", "Couldn't."), None); + assert_eq!(edit(&mut lines, TOBIAH, "0", "Tomorrow, then."), None); + assert_eq!(lines[0].says, "I'll send it.\n\nedit: Couldn't.\n\nedit: Tomorrow, then.", "a second amendment appends after the first"); + assert_eq!((edit(&mut lines, TOBIAH, "1", "x"), edit(&mut lines, TOBIAH, "9", "x"), edit(&mut lines, TOBIAH, "$ev", "x")), (Some("not_hers"), Some("not_found"), Some("not_found"))); + assert_eq!(lines[1].says, "Thanks.", "nothing of hers changes another's line"); + let tail = pending_for(&lines, LIBBY, &[], |_| false).tail.unwrap(); + assert_eq!(tail[0].body, lines[0].says, "the next view reads the amended text"); +} diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 9540d82..193e5dc 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1969,6 +1969,21 @@ fn her_last_turns_line_is_the_outcomes_and_not_the_said_pools() { assert!(!pooled(&History { said: vec![said], ..with_last(&last_turn("SAIDLAST the file is coming.")) }), "her last turn's line is the outcome's to show"); } +#[test] +fn what_she_may_add_to_is_her_last_turns_lines_and_the_said_lines_shown_in_this_room_only() { + let record = json!({ "interpreter": { "room": "#swarm:gamecult.org", "said": [], "refused": [], "gaps": [] }, "posted": [ + { "event": "ev-here", "room": "#swarm:gamecult.org", "text": "I'll send it." }, + { "event": "ev-there", "room": "#elsewhere:gamecult.org", "text": "Elsewhere line." }, + ] }); + let said = super::select::Said { id: "said-older".into(), room: "#swarm:gamecult.org".into(), text: "SAIDOLDER the pipeline is fine.".into(), at: now() - chrono::Duration::minutes(50) }; + let history = History { said: vec![said], ..with_last(&record) }; + let packet = (1..=60).map(|seed| packet_of(TurnKind::Chat, &state(), &chat_room(), &history, seed)).find(|packet| packet.selected.iter().any(|pick| pick.id == "said-older")).expect("the Said line is drawn on some seed"); + let amendable = |id: &str, event: &str, text: &str| super::select::Amendable { id: id.into(), event: event.into(), room: "#swarm:gamecult.org".into(), text: text.into() }; + assert_eq!(packet.amendable, [amendable("a1", "ev-here", "I'll send it."), amendable("a2", "said-older", "SAIDOLDER the pipeline is fine.")]); + assert!(!narrate::projector_prompt(&packet, &Tuning::default()).contains("- a1 "), "the Projector never sees the ids"); + assert_eq!(packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1).amendable, []); +} + #[test] fn the_frame_says_once_what_the_outcome_is_in_her_own_pronouns() { for (pronouns, sentence) in [("she/her", "What came of her last turn is what came of what she last meant to do, which she is only now finding out"), ("he/him", "What came of his last turn is what came of what he last meant to do, which he is only now finding out"), ("any", "which they are only now finding out: whenever something they meant did not happen, the stream begins from it, as they notice it, never as a list")] {