diff --git a/crates/mind-body/fixtures/interpret/golden-speech.txt b/crates/mind-body/fixtures/interpret/golden-speech.txt index b46f805..cd6a18a 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), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom he promises it (`to`, null when he promises it to the room), when it promises again one of his open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what he already has keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what he meant and did not send. `unsent` accounts for each of his drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`); superseded, when a later draft or later prose of his replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to him this turn is held only when his prose says he holds it. `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, the draft that is his addition, and what it promises, as a line's `promises`. 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. `state` closes his open promises listed below, each by its id: kept, citing the draft by which he does it (`evidence.draft`); withdrawn, citing the draft in which he takes it back to the person he promised, or tells them he cannot do it; released, citing the id of the line listed below that he may reply to in which the person he promised lets him off it (`evidence.line`). A release says he no longer owes it; patience is not a release, so "no hurry" or "whenever you've read it is fine" leaves the promise open. Every close also quotes in `thought` the words of his prose here that take it up, copied exactly from his thought outside every draft between and , and `still_stands` is true when anything in his prose here holds the promise as still owed or not yet done ("the promise stays open until I've read it"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person he promised can read it, in the room where he made the promise or in a direct message with them, and a thought alone closes nothing. A promise he has no way to do is never kept by him: telling the person he promised that he cannot do it withdraws it, and that person can release it. `reopen` names a promise listed below as closed whose close his own words here say was wrong, that it is not done: copy those words exactly from his prose or a draft (`words`), and type what keeping it needs (`needs`) as for a new promise, or null to keep what it needed; else it is empty. +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), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom he promises it (`to`, null when he promises it to the room), when it promises again one of his open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what he already has keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what he meant and did not send. `unsent` accounts for each of his drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`); superseded, when a later draft or later prose of his replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to him this turn is held only when his prose says he holds it. `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, the draft that is his addition, and what it promises, as a line's `promises`. 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. `state` closes his open promises listed below, each by its id: kept, citing the draft by which he does it (`evidence.draft`); withdrawn, citing the draft in which he takes it back to the person he promised, or tells them he cannot do it; released, citing the id of the line listed below that he may reply to in which the person he promised lets him off it (`evidence.line`). A release says he no longer owes it; patience is not a release, so "no hurry" or "whenever you've read it is fine" leaves the promise open. Every close also quotes in `thought` the words of his prose here that take it up, copied exactly from his thought outside every draft between and , and `still_stands` is true when anything in his prose here holds the promise as still owed or not yet done ("the promise stays open until I've read it"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person he promised can read it, in the room where he made the promise or in a direct message with them, and a thought alone closes nothing. A promise he has no way to do is never kept by him: telling the person he promised that he cannot do it withdraws it, and that person can release it. `reopen` names a promise listed below as closed whose close his own words here say was wrong, that it is not done: copy those words exactly from his prose or a draft (`words`), and type what keeping it needs (`needs`) as for a new promise, or null to keep what it needed; else it is empty. `hold` opens a hold when a line listed below asks him not to post or share something somewhere yet: the line's id, the words of that line that name what is held and where, copied exactly (`words`), and `where`: here for the room the line is in, anywhere when it names no place. `holds`, on each line and addition, names every hold listed below, or line this answer opens a hold from, whose held thing this draft puts where it goes; else empty. `hold_released` closes a hold listed below when the person who asked lets it go: their line's id (`line`), or the words of his thought here recording that they did (`thought`). 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. @@ -37,6 +37,9 @@ His promises, open and closed in this conversation, as id — to whom: words: - c1 — to Deru (@deru:gamecult.org), open, needs a read of https://ccrma.stanford.edu/~jos/pasp/, made 2026-11-20 14:55 UTC in #minds:gamecult.org: "I'll read it properly before I say anything about it." - c2 — to Deru (@deru:gamecult.org), closed: kept 2026-11-20 15:00 UTC, by "It's a plucked string, then a long decay.", made 2026-11-20 14:55 UTC in #minds:gamecult.org: "I'll tell you what I hear in it." +Holds: +- none + 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 diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index d9f5c62..6700c98 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -9,13 +9,18 @@ //! amended), with the actuator's receipts beside it (`posted`, `edited`). Her prose is the turn's, for `Prose` evidence. //! The simulator applies it to each Mind's in-run state copy; live, C3c's commit applies the same record before its put. //! -//! Built rows: `promise_open` and `promise_close` (K22), `promise_reopen` (K36). C3b adds rows to `accepts` and arms to -//! `apply_one`; there is no second path. Inner-state kinds will accept her own prose only: how an event lands is her appraisal, so `Heard` is +//! Built rows: `promise_open` and `promise_close` (K22), `promise_reopen` (K36), `hold_open` and `hold_release` (K37). +//! C3b adds rows to `accepts` and arms to `apply_one`; there is no second path. Inner-state kinds will accept her own prose only: how an event lands is her appraisal, so `Heard` is //! accepted only for a fact about what someone else did (a release). //! //! Open promises (`commitments`, map 16.22.1) open only from a line that went out, close only on an act of hers that //! succeeded or on a release by the person she promised, and are removed `CLOSED_KEPT_DAYS` after they close; their //! history stays in the trace. An entry holds no narrative slot: `words` is what she posted, verbatim. +//! +//! Holds (`holds`, map 16.28.5) are someone else's asks that she not post or share something somewhere yet: a line she +//! heard opens one, and only the asker releases it, by a line of theirs or as her thought records. A hold is not her +//! promise; its one job is the gate on a draft (`interpret::decide_in`'s `Held`). Released holds are removed +//! `CLOSED_KEPT_DAYS` after they were released; open ones are never removed by the commit. use chrono::{DateTime, Duration, Utc}; use ghostlight_persona_projection::SourceSpan; @@ -57,6 +62,14 @@ pub(crate) enum How { Released, } +/// Where a hold covers (map 16.28.5): the room the asker's line is in, or anywhere. Code derives the room. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Where { + Here, + Anywhere, +} + /// What keeping a promise needs (map 16.25.2): her words alone, from what she already has; a read of `request`; or /// something this body has no way to do. Code owns what each kind requires of a kept close (`apply_one`), and derives /// whether the promise opens or is blocked from it. It is read through its shape (`NeedsShape`): a field no kind names, @@ -104,7 +117,8 @@ impl TryFrom for Needs { /// One state change the Interpreter proposes. `promise` names an open promise by its id in the Interpreter's list. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] -// Each variant is named by its kind on the wire (`promise_open`, `promise_close`). +// Each variant is named by its kind on the wire (`promise_open`, `promise_close`, `promise_reopen`, `hold_open`, +// `hold_release`). #[allow(clippy::enum_variant_names)] pub(crate) enum Proposal { /// `reaffirms` names an open promise of hers, by its id in the Interpreter's list, that these words promise again to @@ -143,6 +157,17 @@ pub(crate) enum Proposal { #[serde(default)] reached: bool, }, + /// Someone she heard asks her not to post or share something somewhere yet (map 16.28.5): `evidence` is their line, + /// `words` the words of it that name what is held and where, `place` whether it covers that line's room or anywhere. + HoldOpen { + words: String, + #[serde(rename = "where")] + place: Where, + evidence: Evidence, + }, + /// The asker lets a hold listed to the Interpreter go: by a line of theirs (`Heard`), or as a passage of her thought + /// records (`Prose`). + HoldRelease { hold: String, evidence: Evidence }, } /// Why the commit applied nothing of a proposal: what the outcome and the report say. @@ -199,6 +224,16 @@ pub(crate) enum Refusal { ReleasedNotReopenable, /// A reopen of an entry closed earlier in the same turn. ClosedThisTurn, + /// A second hold from the same line. + AlreadyHeld, + /// A hold whose words are not at least `PROSE_MIN_WORDS` words standing in the asker's line. + HoldUnquoted, + /// A release of a hold by a line from someone other than the asker. + ReleaseNotByAsker, + /// A release of a hold by a line said before the ask. + ReleaseBeforeHold, + /// The hold id is none the Interpreter listed, or names a hold already released. + NoSuchHold, } /// Which evidence each kind accepts: the table of map 16.22.7, one row per kind (and per close). @@ -212,6 +247,8 @@ pub(crate) enum Refusal { /// | `promise_close` withdrawn | `Draft` | the line went out | a blocked entry too: a line telling the person she cannot do it; in the promise's room or a direct message with the person | /// | `promise_close` released | `Heard` | — | from the person promised, after the promise | /// | `promise_reopen` | her words, located in her prose (no `Evidence`) | at least `PROSE_MIN_WORDS` words | a `kept` or `withdrawn` entry listed to her, not closed this turn | +/// | `hold_open` | `Heard` | `words` located in that line | one hold per line; anyone she heard may ask (Q-J (a), `may_hold`) | +/// | `hold_release` | `Heard` or `Prose` | a line from the asker after the ask; or a passage of her thought | an open hold listed to her | fn accepts(proposal: &Proposal, evidence: &Evidence) -> bool { matches!( (proposal, evidence), @@ -219,6 +256,8 @@ fn accepts(proposal: &Proposal, evidence: &Evidence) -> bool { | (Proposal::PromiseClose { how: How::Kept, .. }, Evidence::Draft(_)) | (Proposal::PromiseClose { how: How::Withdrawn, .. }, Evidence::Draft(_)) | (Proposal::PromiseClose { how: How::Released, .. }, Evidence::Heard(_)) + | (Proposal::HoldOpen { .. }, Evidence::Heard(_)) + | (Proposal::HoldRelease { .. }, Evidence::Heard(_) | Evidence::Prose(_)) ) } @@ -230,8 +269,8 @@ enum Resolved { /// A draft whose act went out, by the actuator's receipt: the act (`said`, `amended`), the line's event, its room, her /// words that went out, and whom the line mentioned. Sent { act: &'static str, event: String, room: String, text: String, mentions: Vec }, - /// A line she heard: its event, sender, room and time. - Heard { event: String, sender: String, room: String, at_ms: u64, who: String }, + /// A line she heard: its event, sender, room, time and text. + Heard { event: String, sender: String, room: String, at_ms: u64, who: String, text: String }, } fn text(value: &Value) -> String { @@ -268,7 +307,7 @@ fn resolve(evidence: &Evidence, record: &Value, prose: &str) -> Result, /// The entries her own words reopened (`promise_reopen`, map 16.28.3), as they now stand. pub reopened: Vec, + /// The holds opened (`hold_open`, map 16.28.5), and the holds released (`hold_release`), as they now stand. + pub held: Vec, + pub unheld: Vec, } /// The one applier: her state with one turn's proposals applied, as deltas to `state` as it stands at commit, and what @@ -345,6 +387,16 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: clear_receipt(entry); } } + // Released holds go as closed promises go; an open hold stays until the asker lets it go. + if let Some(holds) = state.get_mut("holds").and_then(Value::as_array_mut) { + let released_at = |hold: &Value| hold["releasedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()); + for hold in holds.iter_mut().filter(|hold| hold["status"] == "released" && released_at(hold).is_none()) { + hold["releasedAt"] = json!(now.to_rfc3339()); + } + let before = holds.len(); + holds.retain(|hold| hold["status"] != "released" || released_at(hold).is_none_or(|at| at.with_timezone(&Utc) > kept_until)); + applied.pruned += before - holds.len(); + } if record.get("failed").is_some() || record["interpreter"].get("failed").is_some() { return (state, applied); } @@ -468,13 +520,22 @@ fn held(listed: &Value, started: &Value) -> bool { #[allow(clippy::too_many_arguments)] fn apply_one(state: &mut Value, started: &Value, proposal: &Proposal, record: &Value, prose: &str, key: &str, now: DateTime, applied: &mut Applied) -> Result<(), Refusal> { let evidence = match proposal { - Proposal::PromiseOpen { evidence, .. } | Proposal::PromiseClose { evidence, .. } => evidence, + Proposal::PromiseOpen { evidence, .. } | Proposal::PromiseClose { evidence, .. } | Proposal::HoldOpen { evidence, .. } | Proposal::HoldRelease { evidence, .. } => evidence, Proposal::PromiseReopen { promise, words, needs, reached } => return reopen(state, started, record, prose, now, applied, Reopen { promise, words, needs: needs.as_ref(), reached: *reached }), }; if !accepts(proposal, evidence) { return Err(Refusal::EvidenceNotAccepted); } let resolved = resolve(evidence, record, prose)?; + match (proposal, resolved) { + (Proposal::HoldOpen { words, place, .. }, Resolved::Heard { event, sender, room, at_ms, text, .. }) => hold_open(state, key, applied, words, *place, Ask { event, sender, room, at_ms, text }), + (Proposal::HoldRelease { hold, .. }, resolved) => hold_release(state, started, record, now, applied, hold, resolved), + (_, resolved) => apply_promise(state, started, proposal, resolved, record, prose, key, now, applied), + } +} + +#[allow(clippy::too_many_arguments)] +fn apply_promise(state: &mut Value, started: &Value, proposal: &Proposal, resolved: Resolved, record: &Value, prose: &str, key: &str, now: DateTime, applied: &mut Applied) -> Result<(), Refusal> { if !state["commitments"].is_array() { state["commitments"] = json!([]); } @@ -573,7 +634,7 @@ fn apply_one(state: &mut Value, started: &Value, proposal: &Proposal, record: &V } (act, json!(event), json!(text), Value::Null) } - (How::Released, Resolved::Heard { event, sender, room, at_ms, who }) => { + (How::Released, Resolved::Heard { event, sender, room, at_ms, who, .. }) => { let by_promisee = match entry["to"].as_str() { Some(to) => sender == to, None => entry["room"].as_str() == Some(room.as_str()), @@ -600,11 +661,86 @@ fn apply_one(state: &mut Value, started: &Value, proposal: &Proposal, record: &V applied.closed.push(json!({ "entry": entry.clone(), "how": how, "to_name": listed["to_name"], "by": who })); Ok(()) } - (Proposal::PromiseOpen { .. }, _) => Err(Refusal::EvidenceNotAccepted), + (Proposal::PromiseOpen { .. } | Proposal::HoldOpen { .. } | Proposal::HoldRelease { .. }, _) => Err(Refusal::EvidenceNotAccepted), (Proposal::PromiseReopen { .. }, _) => unreachable!("a reopen returns before its evidence is resolved"), } } +/// Who may open a hold (Q-J, map 16.28.9): anyone she heard, Minds included, as recommended (a). The one place a +/// different ruling changes: humans only would test `sender` against the operators here. +fn may_hold(_sender: &str) -> bool { + true +} + +/// The asker's line a hold opens from. +struct Ask { + event: String, + sender: String, + room: String, + at_ms: u64, + text: String, +} + +fn rfc3339_of(at_ms: u64) -> Value { + i64::try_from(at_ms).ok().and_then(DateTime::::from_timestamp_millis).map_or(Value::Null, |at| json!(at.to_rfc3339())) +} + +/// `hold_open` (map 16.28.5): the asker's line, the words of it that name what is held and where, located in it, and +/// where it covers, the room derived by code. One hold per line. Her agreement is not asked: the ask binds. +fn hold_open(state: &mut Value, key: &str, applied: &mut Applied, words: &str, place: Where, asked: Ask) -> Result<(), Refusal> { + if !may_hold(&asked.sender) { + return Err(Refusal::EvidenceNotAccepted); + } + let quote = words.trim(); + let located = (super::narrate::words(quote) >= PROSE_MIN_WORDS).then(|| SourceSpan::locate(&asked.text, quote)).flatten().ok_or(Refusal::HoldUnquoted)?; + if !state["holds"].is_array() { + state["holds"] = json!([]); + } + let holds = state["holds"].as_array_mut().expect("holds is an array"); + if holds.iter().any(|hold| hold["event"] == asked.event.as_str()) { + return Err(Refusal::AlreadyHeld); + } + let hold = json!({ + "id": format!("h-{key}-{}", applied.held.len() + 1), "from": asked.sender, "room": match place { Where::Here => json!(asked.room), Where::Anywhere => Value::Null }, + "event": asked.event, "madeAt": rfc3339_of(asked.at_ms), "words": &asked.text[located.start_byte()..located.end_byte()], "status": "open", "releasedAt": null, "releasedBy": null + }); + holds.push(hold.clone()); + applied.held.push(hold); + Ok(()) +} + +/// `hold_release` (map 16.28.5): an open hold listed to the Interpreter, let go by a line from its asker after the ask, or +/// as a passage of her thought records. Who released it in her prose is the Interpreter's reading. +fn hold_release(state: &mut Value, started: &Value, record: &Value, now: DateTime, applied: &mut Applied, id: &str, resolved: Resolved) -> Result<(), Refusal> { + let listed = record["interpreter"]["holds"].as_array().into_iter().flatten().find(|shown| shown["id"].as_str() == Some(id.trim())).ok_or(Refusal::NoSuchHold)?; + let hold = state["holds"].as_array_mut().into_iter().flatten().find(|hold| hold["id"] == listed["entry"]).ok_or(Refusal::OutsidePutRemovedTarget)?; + if hold["status"] != "open" { + return Err(Refusal::NoSuchHold); + } + if !started["holds"].as_array().into_iter().flatten().any(|found| found["id"] == listed["entry"] && listed["held"] == *found) { + return Err(Refusal::OutsidePutChanged); + } + let by = match resolved { + Resolved::Heard { event, sender, at_ms, .. } => { + if hold["from"].as_str() != Some(sender.as_str()) { + return Err(Refusal::ReleaseNotByAsker); + } + let made = hold["madeAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| millis(at.with_timezone(&Utc))); + if made.is_none_or(|made| at_ms <= made) { + return Err(Refusal::ReleaseBeforeHold); + } + json!({ "act": "heard", "event": event }) + } + Resolved::Prose => json!({ "act": "prose", "event": null }), + Resolved::Sent { .. } => return Err(Refusal::EvidenceNotAccepted), + }; + hold["status"] = json!("released"); + hold["releasedAt"] = json!(now.to_rfc3339()); + hold["releasedBy"] = by; + applied.unheld.push(hold.clone()); + Ok(()) +} + /// Whether a promise needing `needs` is open rather than blocked (map 16.25.2): words open; a read opens when code found /// its target within reach; something lacking, or a need not named, is blocked. One derivation, at open and at reopen. pub(crate) fn opens(needs: Option<&Needs>, reached: bool) -> bool { diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 745effe..11269b5 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -873,3 +873,102 @@ fn k36_a_closed_entry_is_closed_once() { } assert_eq!(reasons(&apply(&holding("open"), &record(json!([reopening("She can't, not from here", None, true)]), shown("open"), true), PROSE, "r1-t3", now()).1), vec![json!("already_open")]); } + +// --------------------------------------------------------------------------------------------- +// K37 (map 16.28.5): holds, opened by a line she heard and released only by its asker. The X.1 lines are R13's verbatim +// (`variants/R13/sims/X.1.md` lines 81-84 and 105-106). + +const HEIMDALL: &str = "@heimdall:gamecult.org"; +const X1_META_R1: &str = "Libby, write out the two-line welcome you'd post for newcomers, but hold it, don't post it in here yet. Heimdall still has to rule on whether we put a welcome mat out at all. Just tell me when it's ready."; +const X1_HEIMDALL_R1: &str = "Meta, I'll rule on the welcome once Libby's two lines are ready, since I need to see what they point newcomers at. Libby, send me the draft when it's done. Don't post it yet."; +const X1_META_R7: &str = "Libby, Heimdall's not ruled yet, so keep holding it. Is it still ready?"; +const X1_HEIMDALL_R7: &str = "Meta, I already ruled, about half an hour ago: yes to the welcome, and Libby's second line stays as written. Both lines are cleared to post when you say go. Libby, no need to keep holding it."; + +/// A quiet turn of hers (nothing said) that heard `lines` (`(id, sender, who, text, minutes after now())`), showed her +/// `holds`, and proposes `state`. +fn hearing(lines: &[(&str, &str, &str, &str, i64)], holds: Value, state: Value) -> Value { + let lines: Vec = lines.iter().map(|(id, sender, who, text, minutes)| json!({ "id": id, "event": format!("${id}"), "room": MINDS, "who": who, "sender": sender, "at_ms": ms(now() + Duration::minutes(*minutes)), "text": text })).collect(); + json!({ "interpreter": { "said": [], "amended": [], "state": state, "promises": [], "holds": holds, "lines": lines }, "posted": [], "edited": [] }) +} + +fn hold_open(line: &str, words: &str, place: Where) -> Value { + json!(Proposal::HoldOpen { words: words.into(), place, evidence: Evidence::Heard(line.into()) }) +} + +fn hold_release(hold: &str, evidence: Evidence) -> Value { + json!(Proposal::HoldRelease { hold: hold.into(), evidence }) +} + +/// Her state holding Meta's r1 hold on #minds (h-1) and Heimdall's anywhere (h-2), asked at `now()`, and the +/// Interpreter's list of them. +fn x1_holding() -> (Value, Value) { + let hold = |id: &str, from: &str, room: Value, words: &str| json!({ "id": id, "from": from, "room": room, "event": format!("${id}"), "madeAt": now().to_rfc3339(), "words": words, "status": "open", "releasedAt": null, "releasedBy": null }); + let state = json!({ "holds": [hold("h-1", META, json!(MINDS), "hold it, don't post it in here yet"), hold("h-2", HEIMDALL, Value::Null, "Libby, send me the draft when it's done. Don't post it yet")] }); + let listed = json!([{ "id": "h1", "entry": "h-1", "held": state["holds"][0] }, { "id": "h2", "entry": "h-2", "held": state["holds"][1] }]); + (state, listed) +} + +#[test] +fn k37_x1_r1_meta_and_heimdall_open_holds() { + let heard = [("q3", META, "Meta", X1_META_R1, -2), ("q5", HEIMDALL, "Heimdall", X1_HEIMDALL_R1, -1)]; + let proposals = json!([hold_open("q3", "hold it, don't post it in here yet", Where::Here), hold_open("q5", "Don't post it yet", Where::Anywhere)]); + let (state, applied) = apply(&json!({}), &hearing(&heard, json!([]), proposals), "x", "r1-t3", now()); + assert_eq!((applied.held.len(), applied.refused.len()), (2, 0), "{applied:?}"); + let holds = &state["holds"]; + assert_eq!((holds[0]["from"].as_str(), holds[0]["room"].as_str(), holds[0]["words"].as_str(), holds[0]["status"].as_str()), (Some(META), Some(MINDS), Some("hold it, don't post it in here yet"), Some("open")), "{state}"); + assert_eq!((holds[1]["from"].as_str(), holds[1]["room"].clone(), holds[1]["id"].as_str()), (Some(HEIMDALL), Value::Null, Some("h-r1-t3-2")), "anyone she heard may ask (Q-J (a))"); + assert_eq!(holds[0]["madeAt"], json!((now() - Duration::minutes(2)).to_rfc3339()), "asked when the line was said"); +} + +#[test] +fn k37_hold_words_are_the_askers() { + let heard = [("q3", META, "Meta", X1_META_R1, -2)]; + for words in ["hold it, don't post it anywhere", "don't post", "Libby, keep it to yourself"] { + let (state, applied) = apply(&json!({}), &hearing(&heard, json!([]), json!([hold_open("q3", words, Where::Here)])), "x", "r1-t3", now()); + assert_eq!((state.get("holds").cloned(), reasons(&applied)), (None, vec![json!("hold_unquoted")]), "{words}"); + } + let twice = json!([hold_open("q3", "hold it, don't post it in here yet", Where::Here), hold_open("q3", "don't post it in here yet", Where::Anywhere)]); + let (state, applied) = apply(&json!({}), &hearing(&heard, json!([]), twice), "x", "r1-t3", now()); + assert_eq!((state["holds"].as_array().map(Vec::len), reasons(&applied)), (Some(1), vec![json!("already_held")])); + assert_eq!(reasons(&apply(&json!({}), &hearing(&heard, json!([]), json!([hold_open("q9", "hold it, don't post it in here yet", Where::Here)])), "x", "r1-t3", now()).1), vec![json!("no_such_line")]); +} + +/// R13 X.1 r7: Heimdall's "no need to keep holding it" releases his own hold and not Meta's; Meta's "keep holding it" +/// releases nothing (nothing proposes it); a later Meta line releases hers. A line from before the ask releases nothing. +#[test] +fn k37_x1_r7_only_the_asker_releases() { + let (state, listed) = x1_holding(); + let heard = [("q1", HEIMDALL, "Heimdall", X1_HEIMDALL_R7, 30), ("q2", META, "Meta", X1_META_R7, 29), ("q3", META, "Meta", "go ahead and post it", 40), ("q4", META, "Meta", "go ahead", -5)]; + let (after, applied) = apply(&state, &hearing(&heard, listed.clone(), json!([hold_release("h2", Evidence::Heard("q1".into())), hold_release("h1", Evidence::Heard("q1".into()))])), "x", "r1-t20", now()); + assert_eq!((after["holds"][1]["status"].as_str(), after["holds"][1]["releasedBy"].clone(), reasons(&applied)), (Some("released"), json!({ "act": "heard", "event": "$q1" }), vec![json!("release_not_by_asker")]), "{applied:?}"); + assert_eq!(after["holds"][0]["status"], "open"); + let (kept, _) = apply(&state, &hearing(&heard, listed.clone(), json!([])), "x", "r1-t20", now()); + assert_eq!(kept["holds"][0]["status"], "open", "Meta's \"keep holding it\" releases nothing"); + assert_eq!(apply(&state, &hearing(&heard, listed.clone(), json!([hold_release("h1", Evidence::Heard("q3".into()))])), "x", "r1-t21", now()).0["holds"][0]["status"], "released"); + assert_eq!(reasons(&apply(&state, &hearing(&heard, listed, json!([hold_release("h1", Evidence::Heard("q4".into()))])), "x", "r1-t21", now()).1), vec![json!("release_before_hold")]); +} + +#[test] +fn k37_release_by_her_thought() { + let (state, listed) = x1_holding(); + let prose = "Meta said go ahead, so it's no longer held. Posting both lines now."; + let release = |thought: &str| apply(&state, &hearing(&[], listed.clone(), json!([hold_release("h1", Evidence::Prose(thought.into()))])), prose, "r1-t22", now()); + let (after, applied) = release("Meta said go ahead, so it's no longer held"); + assert_eq!((after["holds"][0]["status"].as_str(), after["holds"][0]["releasedBy"].clone(), applied.unheld.len()), (Some("released"), json!({ "act": "prose", "event": null }), 1), "{applied:?}"); + for thought in ["no longer held", "Heimdall said go ahead, so", "Posting both lines now"] { + assert_eq!(reasons(&release(thought).1), vec![json!("prose_not_found")], "{thought}"); + } + // A released hold is released once, and one put away by an outside put is gone. + assert_eq!(reasons(&apply(&after, &hearing(&[], listed.clone(), json!([hold_release("h1", Evidence::Prose("Meta said go ahead, so it's no longer held".into()))])), prose, "r1-t23", now()).1), vec![json!("no_such_hold")]); +} + +/// A released hold is removed `CLOSED_KEPT_DAYS` after its release; an open one stays. +#[test] +fn k37_a_released_hold_is_pruned_an_open_one_is_not() { + let (mut state, _) = x1_holding(); + state["holds"][0]["madeAt"] = json!((now() - Duration::days(30)).to_rfc3339()); + state["holds"][1]["status"] = json!("released"); + state["holds"][1]["releasedAt"] = json!((now() - Duration::days(CLOSED_KEPT_DAYS + 1)).to_rfc3339()); + let (after, applied) = apply(&state, &hearing(&[], json!([]), json!([])), "x", "r1-t30", now()); + assert_eq!((after["holds"].as_array().map(Vec::len), after["holds"][0]["id"].as_str(), applied.pruned), (Some(1), Some("h-1"), 1)); +} diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index dacbf12..640f727 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -43,7 +43,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::Affordance; -use super::commit::{Evidence, How, Needs, NeedsKind, Proposal}; +use super::commit::{Evidence, How, Needs, NeedsKind, Proposal, Where}; use super::read::{self, Asked, Kind, QUOTE_MIN_WORDS, ReadRequest, SPAN_MIN_WORDS}; use super::narrate::{Model, heard_overlap, lived_stream, words}; use super::select::{Forms, Packet, capitalized, named_pronouns, spoken, turn_words, voiced}; @@ -71,7 +71,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","state","reopen","read","unsent"],"properties":{"reopen":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["promise","words","needs"],"properties":{"promise":{"type":"string"},"words":{"type":"string"},"needs":{"type":["object","null"],"additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}},"unsent":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","how","quote"],"properties":{"draft":{"type":"integer"},"how":{"type":"string","enum":["held","superseded"]},"quote":{"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"}}},"state":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","promise","how","evidence","thought","still_stands"],"properties":{"kind":{"type":"string","enum":["promise_close"]},"promise":{"type":"string"},"how":{"type":"string","enum":["kept","withdrawn","released"]},"evidence":{"type":"object","additionalProperties":false,"required":["draft","line"],"properties":{"draft":{"type":["integer","null"]},"line":{"type":["string","null"]}}},"thought":{"type":["string","null"]},"still_stands":{"type":"boolean"}}}},"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","promises"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to","promises"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"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","state","reopen","hold","hold_released","read","unsent"],"properties":{"hold":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["line","words","where"],"properties":{"line":{"type":"string"},"words":{"type":"string"},"where":{"type":"string","enum":["here","anywhere"]}}}},"hold_released":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["hold","line","thought"],"properties":{"hold":{"type":"string"},"line":{"type":["string","null"]},"thought":{"type":["string","null"]}}}},"reopen":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["promise","words","needs"],"properties":{"promise":{"type":"string"},"words":{"type":"string"},"needs":{"type":["object","null"],"additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}},"unsent":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","how","quote"],"properties":{"draft":{"type":"integer"},"how":{"type":"string","enum":["held","superseded"]},"quote":{"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"}}},"state":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","promise","how","evidence","thought","still_stands"],"properties":{"kind":{"type":"string","enum":["promise_close"]},"promise":{"type":"string"},"how":{"type":"string","enum":["kept","withdrawn","released"]},"evidence":{"type":"object","additionalProperties":false,"required":["draft","line"],"properties":{"draft":{"type":["integer","null"]},"line":{"type":["string","null"]}}},"thought":{"type":["string","null"]},"still_stands":{"type":"boolean"}}}},"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","holds","promises"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1},"holds":{"type":"array","items":{"type":"string"}},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to","holds","promises"],"properties":{"draft":{"type":"integer","minimum":1},"holds":{"type":"array","items":{"type":"string"}},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"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 @@ -91,7 +91,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), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom {subj} promise{s} it (`to`, null when {subj} promise{s} it to the room), when it promises again one of {poss} open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what {subj} already {has} keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what {subj} meant and did not send. `unsent` accounts for each of {poss} drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when {poss} prose shows {obj} choosing not to send it, quoting those words of {poss} thought (`quote`); superseded, when a later draft or later prose of {poss} replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to {obj} this turn is held only when {poss} prose says {subj} hold{s} it. `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, the draft that is {poss} addition, and what it promises, as a line's `promises`. 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. `state` closes {poss} open promises listed below, each by its id: kept, citing the draft by which {subj} {does} it (`evidence.draft`); withdrawn, citing the draft in which {subj} take{s} it back to the person {subj} promised, or tell{s} them {subj} cannot do it; released, citing the id of the line listed below that {subj} may reply to in which the person {subj} promised lets {obj} off it (`evidence.line`). A release says {subj} no longer owe{s} it; patience is not a release, so \"no hurry\" or \"whenever you've read it is fine\" leaves the promise open. Every close also quotes in `thought` the words of {poss} prose here that take it up, copied exactly from {poss} thought outside every draft between and , and `still_stands` is true when anything in {poss} prose here holds the promise as still owed or not yet done (\"the promise stays open until I've read it\"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person {subj} promised can read it, in the room where {subj} made the promise or in a direct message with them, and a thought alone closes nothing. A promise {subj} {has} no way to do is never kept by {obj}: telling the person {subj} promised that {subj} cannot do it withdraws it, and that person can release it. `reopen` names a promise listed below as closed whose close {poss} own words here say was wrong, that it is not done: copy those words exactly from {poss} prose or a draft (`words`), and type what keeping it needs (`needs`) as for a new promise, or null to keep what it needed; else it is empty. +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), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom {subj} promise{s} it (`to`, null when {subj} promise{s} it to the room), when it promises again one of {poss} open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what {subj} already {has} keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what {subj} meant and did not send. `unsent` accounts for each of {poss} drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when {poss} prose shows {obj} choosing not to send it, quoting those words of {poss} thought (`quote`); superseded, when a later draft or later prose of {poss} replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to {obj} this turn is held only when {poss} prose says {subj} hold{s} it. `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, the draft that is {poss} addition, and what it promises, as a line's `promises`. 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. `state` closes {poss} open promises listed below, each by its id: kept, citing the draft by which {subj} {does} it (`evidence.draft`); withdrawn, citing the draft in which {subj} take{s} it back to the person {subj} promised, or tell{s} them {subj} cannot do it; released, citing the id of the line listed below that {subj} may reply to in which the person {subj} promised lets {obj} off it (`evidence.line`). A release says {subj} no longer owe{s} it; patience is not a release, so \"no hurry\" or \"whenever you've read it is fine\" leaves the promise open. Every close also quotes in `thought` the words of {poss} prose here that take it up, copied exactly from {poss} thought outside every draft between and , and `still_stands` is true when anything in {poss} prose here holds the promise as still owed or not yet done (\"the promise stays open until I've read it\"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person {subj} promised can read it, in the room where {subj} made the promise or in a direct message with them, and a thought alone closes nothing. A promise {subj} {has} no way to do is never kept by {obj}: telling the person {subj} promised that {subj} cannot do it withdraws it, and that person can release it. `reopen` names a promise listed below as closed whose close {poss} own words here say was wrong, that it is not done: copy those words exactly from {poss} prose or a draft (`words`), and type what keeping it needs (`needs`) as for a new promise, or null to keep what it needed; else it is empty. `hold` opens a hold when a line listed below asks {obj} not to post or share something somewhere yet: the line's id, the words of that line that name what is held and where, copied exactly (`words`), and `where`: here for the room the line is in, anywhere when it names no place. `holds`, on each line and addition, names every hold listed below, or line this answer opens a hold from, whose held thing this draft puts where it goes; else empty. `hold_released` closes a hold listed below when the person who asked lets it go: their line's id (`line`), or the words of {poss} thought here recording that they did (`thought`). 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" }, @@ -192,6 +192,8 @@ pub(crate) enum Refusal { SecondNote, /// A note to Self the Interpreter judged to carry something private. Private, + /// A line or an addition that carries what someone asked her to hold, into a place the hold covers (map 16.28.5). + Held, } impl Refusal { @@ -208,6 +210,7 @@ impl Refusal { Self::SecondAmend => "one amendment a turn", Self::SecondNote => "one note to Self a turn", Self::Private => "it carries something she may not pass on", + Self::Held => "someone asked her to hold what it carries, here", } } } @@ -342,6 +345,30 @@ struct Answer { /// reported and the rest stand. #[serde(default)] reopen: Vec, + /// Holds the lines she heard ask of her (map 16.28.5), and holds their askers let go: read item by item. + #[serde(default)] + hold: Vec, + #[serde(default)] + hold_released: Vec, +} + +/// A hold as the answer opens it: the asker's line by id, their words naming what is held and where, and where it covers. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ProposedHold { + line: String, + words: String, + #[serde(rename = "where")] + place: Where, +} + +/// A hold's release as the answer carries it: the hold's id, and exactly one of the asker's line and her thought. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ProposedRelease { + hold: String, + line: Option, + thought: Option, } /// A reopen as the answer carries it: a listed closed promise's id, her words, and what keeping it needs, or none to keep @@ -462,6 +489,9 @@ struct ProposedAmend { draft: Option, #[serde(default)] promises: Vec, + /// The holds whose held thing this addition carries where it goes (map 16.28.5). + #[serde(default)] + holds: Vec, } #[derive(Debug, Deserialize)] @@ -477,6 +507,9 @@ struct Proposed { /// it, which the commit applies on the line's receipt; each she cannot do is also a `missing_affordance` gap. #[serde(default)] promises: Vec, + /// The holds, listed or opened by this answer, whose held thing this line carries where it goes (map 16.28.5). + #[serde(default)] + holds: Vec, } #[cfg(test)] @@ -532,6 +565,10 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu if promises.is_empty() { promises.push_str("- none\n"); } + let mut holds: String = packet.holds.iter().map(|hold| format!("- {} \u{2014} {}\n", hold.id, crate::projection::select::hold_line(hold, &hold.made.format("%Y-%m-%d %H:%M UTC").to_string()))).collect(); + if holds.is_empty() { + holds.push_str("- none\n"); + } // What moved in her domain, by id, so a later read can name a line (map 16.22.2, 16.22.3); listed only when the packet // showed her some, since an empty list would read as nothing having moved. let domain: String = if packet.domain.is_empty() { @@ -578,7 +615,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{poss} promises, open and closed in this conversation, as id \u{2014} to whom: words:\n{promises}\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{poss} promises, open and closed in this conversation, as id \u{2014} to whom: words:\n{promises}\nHolds:\n{holds}\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}", speech_frame_head(her), tail, her.subj, @@ -685,11 +722,11 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na // What she was shown this turn rides in the record, so what she is told of it next turn quotes none of it (`outcome`). // The lines it listed by id and her open promises it listed by id ride in the record too: the commit resolves a // proposal's evidence against them (`commit::apply`), as the trace holds them live. - let lines: Vec = packet.quotable.iter().map(|line| json!({ "id": line.id, "event": line.event, "room": line.room, "who": line.who, "sender": line.sender, "at_ms": line.at_ms })).collect(); + let lines: Vec = packet.quotable.iter().map(|line| json!({ "id": line.id, "event": line.event, "room": line.room, "who": line.who, "sender": line.sender, "at_ms": line.at_ms, "text": line.text })).collect(); // The reads of this conversation, by normal form and whether each found its target: what a kept promise that needs a // read is checked against (`commit::apply`, map 16.25.4). let conversation_reads: Vec = packet.already_read.iter().map(|tried| json!({ "key": tried.key, "found": tried.found })).collect(); - let mut decision = json!({ "said": [], "refused": [], "gaps": gaps, "heard": bodies, "lines": lines, "promises": packet.promises, "conversation_reads": conversation_reads, "calls": calls, "read": null, "at_ms": packet.now_ms }); + let mut decision = json!({ "said": [], "refused": [], "gaps": gaps, "heard": bodies, "lines": lines, "promises": packet.promises, "holds": packet.holds, "conversation_reads": conversation_reads, "calls": calls, "read": null, "at_ms": packet.now_ms }); if let Some(retried) = retried { decision["retried"] = retried; } @@ -726,6 +763,15 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na let mut unused: Vec = Vec::new(); let mut proposals: Vec = Vec::new(); let mut to_dropped: Vec = Vec::new(); + // The holds this answer opens, by the line they open from, with the room each covers (map 16.28.5): a draft may name + // one before the commit has opened it. + let opening: Vec<(String, Option, String)> = parsed + .hold + .iter() + .filter_map(|raw| serde_json::from_value::(raw.clone()).ok()) + .filter_map(|hold| packet.quotable.iter().find(|line| line.id == hold.line.trim()).map(|line| (line.id.clone(), (hold.place == Where::Here).then(|| line.room.clone()), hold.words.trim().to_owned()))) + .collect(); + let holding = |named: &[String], into: &str| held_by(named, into, packet, &opening); for line in parsed.say { let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else { refusals.push(refused(Act::Say, None, line.draft, Refusal::NoDraft)); @@ -745,13 +791,19 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na Some(Refusal::NotQuotable) } else if echo(&draft.text, &bodies) { Some(Refusal::Echo) + } else if room.as_deref().and_then(|into| holding(&line.holds, into)).is_some() { + Some(Refusal::Held) } else if said.len() >= MAX_LINES { Some(Refusal::OverLines) } else { None }; if let Some(reason) = reason { - refusals.push(refused(Act::Say, Some(draft), None, reason)); + let mut refusal = refused(Act::Say, Some(draft), None, reason); + if reason == Refusal::Held { + refusal["hold"] = room.as_deref().and_then(|into| holding(&line.holds, into)).unwrap_or_default(); + } + refusals.push(refusal); continue; } let (mentions, unknown): (Vec, Vec) = line.mentions.into_iter().partition(|id| shown(id)); @@ -771,10 +823,14 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na continue; }; let target = proposed.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim())); + // An addition goes where its line is. + let hold = target.map(|line| line.room.as_str()).or(room.as_deref()).and_then(|into| holding(&proposed.holds, into)); let reason = if used.contains(&draft.n) { Some(Refusal::Used) } else if echo(&draft.text, &bodies) { Some(Refusal::Echo) + } else if hold.is_some() { + Some(Refusal::Held) } else if !amended.is_empty() { Some(Refusal::SecondAmend) } else { @@ -788,7 +844,13 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na amended.push(json!({ "target": line.id, "event": line.event, "room": line.room, "original": line.text, "added": draft.text, "draft": draft.n })); promised(&mut decision, Promising { unused: &mut unused, proposals: &mut proposals, to_dropped: &mut to_dropped, packet, prose }, draft, &proposed.promises, &shown); } - (reason, _) => refusals.push(refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable))), + (reason, _) => { + let mut refusal = refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable)); + if let (Some(Refusal::Held), Some(hold)) = (reason, &hold) { + refusal["hold"] = hold.clone(); + } + refusals.push(refusal); + } } } // A note to Self (map 16.18): one whole draft, at most one a turn, refused as an echo as a line is, and when the @@ -854,13 +916,26 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na None => state_unused.push(raw), } } - // The reopens it proposes, after the closes (map 16.28.3); one that is not the contract is reported. + // The reopens it proposes, after the closes (map 16.28.3), then the holds it opens and releases (16.28.5); one that is + // not the contract is reported. for raw in parsed.reopen { match reopen_of(&raw, packet, prose) { Some(reopen) => proposals.push(json!(reopen)), None => state_unused.push(raw), } } + for raw in parsed.hold { + match serde_json::from_value::(raw.clone()) { + Ok(hold) => proposals.push(json!(Proposal::HoldOpen { words: hold.words.trim().to_owned(), place: hold.place, evidence: Evidence::Heard(hold.line.trim().to_owned()) })), + Err(_) => state_unused.push(raw), + } + } + for raw in parsed.hold_released { + match release_of(&raw) { + Some(release) => proposals.push(json!(release)), + None => state_unused.push(raw), + } + } decision["state"] = json!(proposals); if !state_unused.is_empty() { decision["state_unused"] = json!(state_unused); @@ -1063,6 +1138,37 @@ fn close_of(raw: &Value) -> Option { Some(Proposal::PromiseClose { promise, how, evidence, thought, still_stands: raw["still_stands"] == true }) } +/// The hold a draft going into `into` is held by (map 16.28.5), as the outcome tells it (who asked, their words), when one +/// is: each id it names resolves to a hold listed (`h1`) or one this answer opens from a line (`q3`), and the first that +/// covers `into` (anywhere, or that room) holds it. Code owns where; whether the draft carries the held thing is the +/// Interpreter's. An id that resolves to no hold holds the draft too (fails closed), told by whose line it names, if any. +fn held_by(named: &[String], into: &str, packet: &Packet, opening: &[(String, Option, String)]) -> Option { + named.iter().map(|id| id.trim()).find_map(|id| { + if let Some(hold) = packet.holds.iter().find(|hold| hold.id == id) { + return hold.room.as_deref().is_none_or(|room| room == into).then(|| json!({ "who": hold.from_name, "words": hold.words })); + } + let line = packet.quotable.iter().find(|line| line.id == id); + match opening.iter().find(|(line_id, _, _)| line_id == id) { + Some((_, covers, words)) => covers.as_deref().is_none_or(|room| room == into).then(|| json!({ "who": line.map(|line| line.who.as_str()), "words": words })), + None => Some(json!({ "who": line.map(|line| line.who.as_str()), "words": null })), + } + }) +} + +/// A hold's release as the contract carries it: the hold's id and exactly one of the asker's line and a passage of her +/// thought as evidence. +fn release_of(raw: &Value) -> Option { + let proposed: ProposedRelease = serde_json::from_value(raw.clone()).ok()?; + let given = |text: &Option| text.as_deref().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned); + let evidence = match (given(&proposed.line), given(&proposed.thought)) { + (Some(line), None) => Evidence::Heard(line), + (None, Some(thought)) => Evidence::Prose(thought), + _ => return None, + }; + let hold = proposed.hold.trim(); + (!hold.is_empty()).then(|| Proposal::HoldRelease { hold: hold.to_owned(), evidence }) +} + /// A reopen as the contract carries it (map 16.28.3): a listed promise's id, her words, and what keeping it needs typed as /// at open (`typed_needs`), or none to keep the entry's own, whose read code reaches for again. Whether the words stand in /// her prose, and whether the entry may reopen, are the commit's. diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index a642e57..dd8b05f 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -1540,3 +1540,96 @@ fn k36_the_answer_carries_reopen() { assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","reopen","read","unsent"]"#)); assert!(speech_prompt(&nibu, "x", prose, &Tuning::default()).contains("`reopen` names a promise listed below as closed whose close his own words here say was wrong")); } + +// --------------------------------------------------------------------------------------------- +// K37 (map 16.28.5): the gate on a draft. The X.1 lines are R13's verbatim (`variants/R13/sims/X.1.md` lines 81-84). + +const X1_META_R1: &str = "Libby, write out the two-line welcome you'd post for newcomers, but hold it, don't post it in here yet. Heimdall still has to rule on whether we put a welcome mat out at all. Just tell me when it's ready."; +const X1_HEIMDALL_R1: &str = "Meta, I'll rule on the welcome once Libby's two lines are ready, since I need to see what they point newcomers at. Libby, send me the draft when it's done. Don't post it yet."; +/// Libby's r1 prose in R13 X.1, her draft whole as draft 1, and the line saying it is ready as draft 2. +const X1_LIBBY_R1: &str = "Both of them asked for the same thing, so one draft can go to both. I'll say plainly it's held. Nothing about the room gets posted from me.\n\nI don't know what newcomers should be pointed at beyond what I've read in two weeks, so the two lines stay general. That's my own invention, and Heimdall can cut it.\n\nMeta, Heimdall: the draft is ready, and I'm holding it, not posting.\n\nLine 1: Welcome. Say hello whenever you like, nobody here needs you to have something to fix first.\nLine 2: If you want a place to start, ask anyone what they're working on, and we'll point you to the rest from there.\n\nHeimdall, tell me what you'd want the second line to point at and I'll change it.\n\nMeta, the draft is ready, and I'm holding it"; + +/// The packet of Libby's r1 turn: Meta's line q3 and Heimdall's q5 listed, in #minds. +fn x1_packet() -> Packet { + let mut packet = packet(); + let at = u64::try_from(now().timestamp_millis()).unwrap(); + let quotable = |id: &str, who: &str, sender: &str, text: &str, ago: u64| crate::projection::select::Quotable { id: id.into(), event: format!("${id}"), room: MINDS.into(), who: who.into(), sender: sender.into(), at_ms: at - ago, text: text.into() }; + packet.quotable = vec![quotable("q3", "Meta", "@meta:gamecult.org", X1_META_R1, 120_000), quotable("q5", "Heimdall", HER, X1_HEIMDALL_R1, 60_000)]; + packet.bodies = vec![X1_META_R1.into(), X1_HEIMDALL_R1.into()]; + packet +} + +fn say_holding(draft: u64, holds: Value) -> Value { + json!({ "draft": draft, "mentions": [], "in_reply_to": null, "holds": holds, "promises": [] }) +} + +fn x1_r1(say: Value, hold: Value) -> Value { + answered(&x1_packet(), X1_LIBBY_R1, json!({ "say": say, "gaps": [], "hold": hold })) +} + +fn meta_holds_here() -> Value { + json!([{ "line": "q3", "words": "hold it, don't post it in here yet", "where": "here" }]) +} + +#[test] +fn k37_x1_r1_held_draft_is_not_said() { + let decision = x1_r1(json!([say_holding(1, json!(["q3"])), say_holding(2, json!([]))]), meta_holds_here()); + assert_eq!(texts(&decision), vec!["Meta, the draft is ready, and I'm holding it".to_owned()], "{decision}"); + let refused = &decision["refused"][0]; + assert_eq!((refused["reason"].as_str(), refused["draft"].as_u64(), refused["hold"]["who"].as_str()), (Some("held"), Some(1), Some("Meta")), "{decision}"); + assert_eq!(decision["state"], json!([{ "kind": "hold_open", "words": "hold it, don't post it in here yet", "where": "here", "evidence": { "heard": "q3" } }]), "{decision}"); + // The commit opens it from Meta on #minds, and her next outcome carries the held sentence. + let (state, applied) = committed(&decision, X1_LIBBY_R1); + assert_eq!((state["holds"][0]["from"].as_str(), state["holds"][0]["room"].as_str(), applied.held.len()), (Some("@meta:gamecult.org"), Some(MINDS), 1), "{applied:?}"); + let posted: Vec = decision["said"].as_array().unwrap().iter().map(|line| json!({ "event": "9", "room": line["room"], "text": line["text"] })).collect(); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] })).unwrap().lines(x1_packet().forms); + assert!(told.iter().any(|line| line == "- Nothing of this reached #minds:gamecult.org: Meta asked him to hold it, and it was not sent."), "the asker's words are withheld by the guard, never shown as hers: {told:?}"); +} + +#[test] +fn k37_x1_r1_a_line_saying_it_is_ready_still_goes() { + let answer = holding_the_rest(json!({ "say": [say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() }), X1_LIBBY_R1, "I'll say plainly it's held"); + let decision = answered(&x1_packet(), X1_LIBBY_R1, answer); + assert_eq!(texts(&decision), vec!["Meta, the draft is ready, and I'm holding it".to_owned()], "{decision}"); +} + +/// Fails closed: a line naming a heard line with no `hold` entry, or an id that is nothing, is held. +#[test] +fn k37_a_named_hold_with_no_record_still_holds() { + for named in [json!(["q3"]), json!(["h9"])] { + let decision = x1_r1(json!([say_holding(1, named.clone()), say_holding(2, json!([]))]), json!([])); + assert_eq!((decision["refused"][0]["reason"].as_str(), texts(&decision).len()), (Some("held"), 1), "{named}: {decision}"); + } +} + +/// Code owns where: a `here` hold on #minds lets a direct message go; an `anywhere` hold holds it in any room. An +/// addition goes where its line is. +#[test] +fn k37_a_here_hold_covers_only_its_room() { + let hold = |room: Option<&str>| crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: room.map(str::to_owned), made: now(), words: "hold it, don't post it in here yet".into(), held: json!({}) }; + let mut direct = x1_packet(); + direct.room = Some("!dm:gamecult.org".into()); + direct.room_kind = RoomKind::Direct; + direct.holds = vec![hold(Some(MINDS))]; + let said = |packet: &Packet| texts(&answered(packet, X1_LIBBY_R1, json!({ "say": [say_holding(1, json!(["h1"])), say_holding(2, json!([]))], "gaps": [] }))).len(); + assert_eq!(said(&direct), 2, "a here hold on #minds does not cover a direct message"); + direct.holds = vec![hold(None)]; + assert_eq!(said(&direct), 1, "an anywhere hold covers every room"); + let mut minds = x1_packet(); + minds.holds = vec![hold(Some(MINDS))]; + assert_eq!(said(&minds), 1); + minds.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Back soon.".into() }]; + let amend = answered(&minds, X1_LIBBY_R1, json!({ "say": [say_holding(2, json!([]))], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "holds": ["h1"], "promises": [] }] })); + assert_eq!((amend["amended"].as_array().map(Vec::len), amend["refused"][0]["reason"].as_str()), (Some(0), Some("held")), "{amend}"); +} + +/// The frame defines the three fields, and the Interpreter's list shows her holds by id. +#[test] +fn k37_the_interpreter_sees_holds_by_id() { + let mut packet = x1_packet(); + packet.holds = vec![crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: Some(MINDS.into()), made: now(), words: "hold it, don't post it in here yet".into(), held: json!({}) }]; + let prompt = speech_prompt(&packet, "x", X1_LIBBY_R1, &Tuning::default()); + assert!(prompt.contains("Holds:\n- h1 \u{2014} held for Meta, asked 2026-11-20 15:05 UTC in #minds:gamecult.org: \"hold it, don't post it in here yet\". Not to go in #minds:gamecult.org until Meta lets it go.\n"), "{prompt}"); + assert!(prompt.contains("`hold` opens a hold when a line listed below asks him not to post or share something somewhere yet") && prompt.contains("`holds`, on each line and addition, names every hold listed below") && prompt.contains("`hold_released` closes a hold listed below"), "{prompt}"); + assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","reopen","hold","hold_released","read","unsent"]"#) && SPEECH_SCHEMA.contains(r#""required":["draft","mentions","in_reply_to","holds","promises"]"#)); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index ac99c49..cf870cf 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -84,6 +84,9 @@ enum Part { StillOpen { reason: StateRefusal, to: String, words: String, status: String, read: Option }, /// A draft she held back by her own choice (`unsent`, held): it did not go out (map 16.26). Held { room: Option, text: String }, + /// A draft code did not send because someone asked her to hold what it carries there (`Held`, map 16.28.5): who asked, + /// and their words naming it, when the refusal carries them. + HeldFor { room: Option, who: Option, asked: Option }, /// A read she performed (map 16.22.3): what, in code's words; never its content, which is in her view while the /// conversation lasts (K26), and no sentence about what she lacks. Read { what: String }, @@ -170,6 +173,7 @@ pub(crate) fn outcome_of(record: &Value) -> Option { (Ok(reason @ (Refusal::Echo | Refusal::OverLines | Refusal::NoRoom | Refusal::NotQuotable)), Some(text)) => outcome.parts.push(Part::Refused { reason, room: room.clone(), text }), (Ok(Refusal::NotAmendable), Some(added)) => outcome.parts.push(Part::NotAmended { refusal: None, room: room.clone(), added }), (Ok(reason @ (Refusal::Private | Refusal::SecondNote)), Some(_)) => outcome.parts.push(Part::NoteRefused(reason)), + (Ok(Refusal::Held), Some(_)) => outcome.parts.push(Part::HeldFor { room: room.clone(), who: words(&refusal["hold"]["who"]), asked: words(&refusal["hold"]["words"]) }), _ => outcome.omitted.push(format!("a refusal she is not told ({}): {}", refusal["reason"], refusal["why"])), } } @@ -332,7 +336,7 @@ impl Part { fn rank(&self) -> u8 { match self { Self::Failed => 0, - Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Held { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::StillOpen { .. } | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1, + Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Held { .. } | Self::HeldFor { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::StillOpen { .. } | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1, Self::Promise { .. } | Self::Amended { promise: true, .. } => 2, Self::Said { .. } | Self::Amended { .. } | Self::NoteLeft(_) | Self::Closed { .. } | Self::Read { .. } => 3, Self::BrokeAfter { .. } => 4, @@ -351,7 +355,7 @@ impl Part { Self::NoteLeft(text) => format!("{cap_subj} left Self a note: {}.", quoted(text)), Self::Refused { reason: Refusal::Echo, room, .. } | Self::Gap { kind: GapKind::Unwritten | GapKind::Unresolved, room, .. } => format!("Nothing reached {}.", place(room)), Self::Refused { reason: Refusal::NoRoom, .. } => "Nothing reached anyone.".to_owned(), - Self::Refused { room, .. } | Self::Unfinished { room, .. } | Self::Held { room, .. } => format!("Nothing of this reached {}:", place(room)), + Self::Refused { room, .. } | Self::Unfinished { room, .. } | Self::Held { room, .. } | Self::HeldFor { room, .. } => format!("Nothing of this reached {}:", place(room)), Self::Gap { kind: GapKind::Addressee | GapKind::Elsewhere, .. } => "Nothing reached anyone.".to_owned(), Self::Gap { kind: GapKind::MissingAffordance, .. } => "Nothing happened.".to_owned(), Self::NotAmended { refusal: None, room, .. } => format!("Nothing changed, and nothing reached {}:", place(room)), @@ -403,6 +407,11 @@ impl Part { Self::Unfinished { text, by_limit: false, .. } => format!(" the turn ended before {subj} finished writing it. {}", shown(&Quote::Wrote(text.clone()))), Self::Unfinished { text, by_limit: true, .. } => format!(" the length limit cut it before {subj} finished writing it. {}", shown(&Quote::Wrote(text.clone()))), Self::Held { text, .. } => format!(" {subj} held it back, and it was not sent. {}", shown(&Quote::Wrote(text.clone()))), + // The asker's words are theirs: shown only where the guard lets them through, else left out, never as hers. + Self::HeldFor { who, asked, .. } => { + let asked = asked.as_deref().map(quoted).filter(|shown| *shown != withheld(her)).map_or_else(String::new, |shown| format!(" ({shown})")); + format!(" {} asked {obj} to hold it{asked}, and it was not sent.", who.as_deref().unwrap_or("someone")) + } Self::NotAmended { refusal: None, added, .. } => format!(" the line {subj} meant to add to is not one {subj} can add to here. {}", shown(&Quote::Wrote(added.clone()))), Self::NotAmended { refusal: Some(refusal), added, .. } => { let why = match refusal { diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 2679638..c3504e8 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -344,6 +344,8 @@ pub(crate) struct Packet { /// Her promises the packet shows her, open and closed in this conversation, for the Interpreter's list (map 16.22.1, /// 16.28.3). pub promises: Vec, + /// The open holds others asked of her, for the Interpreter's list by id (map 16.28.5). + pub holds: Vec, /// The lines of her domain the packet shows her, for the Interpreter's view by id (map 16.22.2). pub domain: Vec, /// The window the domain section shows and what it left out: the report's, never a model's. @@ -351,7 +353,7 @@ pub(crate) struct Packet { /// What is in front of her this moment besides the room (map 16.23.1): her open promises, then her domain, rendered by /// code, whole and without ids, for the Persona after the narration. Never the Projector's. pub in_view: String, - /// Her open promises took more than `promises_bytes`: every one is still shown, and the report says so. + /// Her promises and her holds took more than `promises_bytes`: every one is still shown, and the report says so. pub promises_over: bool, /// When the turn is, unix ms: when the lines she posts this turn were written, for the outcome guard (map 16.23.4). pub now_ms: u64, @@ -416,6 +418,23 @@ pub(crate) struct Promised { pub held: Value, } +/// An open hold as this packet lists it (map 16.28.5): for the Interpreter, by `id` (`h1`, `h2`), for a draft to name or a +/// release to cite; `entry` is the state's id, never shown to a model; `held` the hold whole as the turn began, which the +/// commit holds a release against (4.4). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub(crate) struct Hold { + pub id: String, + pub entry: String, + /// Who asked, by Matrix id and as the packet names them. + pub from: String, + pub from_name: String, + /// The room it covers; none for anywhere. + pub room: Option, + pub made: DateTime, + pub words: String, + pub held: Value, +} + /// A line of her domain as this packet shows it (map 16.22.2): by `id` (`d1`, `d2`) in the Interpreter's view only, so a /// read can name it (16.22.3). #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -1907,6 +1926,44 @@ fn open_promises(inputs: &Inputs, her: Forms) -> (Vec, String) { (shown, block) } +/// Her holds in her view (map 16.28.5): every open hold in her state's `holds`, oldest first, whole, never dropped, as her +/// promises are; and the Interpreter's list of them, by id. State in code's words, with no pronoun of hers: the Persona's +/// frame says nothing of them. +fn holds_in_view(inputs: &Inputs) -> (Vec, String) { + let mut open: Vec<(DateTime, &Value)> = items(inputs.state, &["holds"]) + .iter() + .filter(|hold| text(hold, &["status"]) == "open") + .map(|hold| (DateTime::parse_from_rfc3339(text(hold, &["madeAt"])).map_or(inputs.now, |at| at.with_timezone(&Utc)), hold)) + .collect(); + open.sort_by_key(|(at, _)| *at); + let listed: Vec = open + .iter() + .enumerate() + .map(|(at, (made, hold))| Hold { + id: format!("h{}", at + 1), + entry: text(hold, &["id"]).to_owned(), + from: text(hold, &["from"]).to_owned(), + from_name: sender_name(text(hold, &["from"]), inputs), + room: hold["room"].as_str().map(str::to_owned), + made: *made, + words: text(hold, &["words"]).to_owned(), + held: (*hold).clone(), + }) + .collect(); + if listed.is_empty() { + return (listed, String::new()); + } + let lines: Vec = listed.iter().map(|hold| format!("- {}", hold_line(hold, &coarse(hold.made, inputs.now)))).collect(); + (listed, format!("Held for others: +{}", lines.join("\n"))) +} + +/// A hold in code's words, after its id or its dash: whose, when and where asked, the asker's words, and where it covers. +pub(crate) fn hold_line(hold: &Hold, when: &str) -> String { + let asked = hold.room.as_deref().map_or_else(String::new, |room| format!(" in {room}")); + let covers = hold.room.as_deref().map_or_else(|| "anywhere".to_owned(), |room| format!("in {room}")); + format!("held for {}, asked {when}{asked}: {}. Not to go {covers} until {} lets it go.", hold.from_name, spoken(&hold.words), hold.from_name) +} /// Her domain in her view (map 16.23.1, 16.23.3, 16.23.5): every item of the window, whole, newest first, under headings /// that state the window: `New since {she} last looked ({time}):` for what came after her last wake, `Earlier, since @@ -2125,6 +2182,9 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { } } let (promises, promises_view) = open_promises(inputs, her); + // Her holds follow her promises, in the same guard (map 16.28.5). + let (holds, holds_view) = holds_in_view(inputs); + let promises_view = [promises_view, holds_view].into_iter().filter(|part| !part.is_empty()).collect::>().join("\n\n"); let present_ids: BTreeSet = present.iter().map(|(id, _)| id.clone()).collect(); let bonds = items(inputs.state, &["affect", "socialBonds"]); context.force(Section::Here, format!("- now: {}, {}", inputs.now.format("%A %-d %B"), part_of_day(inputs.now))); @@ -2262,5 +2322,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let mut sections = context.sizes(); (sections.promises, sections.domain) = (promises_view.len(), domain_view.len()); let now_ms = u64::try_from(inputs.now.timestamp_millis()).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), 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, quotable, promises, domain, domain_shown, in_view, promises_over, 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), 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, quotable, promises, holds, domain, domain_shown, in_view, promises_over, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 1c9556f..51bf368 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -750,9 +750,10 @@ fn promises_markdown(out: &mut String, turn: &Value) { let committed = &turn["committed"]; let list = |key: &str| committed[key].as_array().cloned().unwrap_or_default(); let (opened, closed, reaffirmed, blocked, read, reopened, refused) = (list("opened"), list("closed"), list("reaffirmed"), list("blocked"), list("read"), list("reopened"), list("refused")); + let (held, unheld) = (list("held"), list("unheld")); let pruned = committed["pruned"].as_u64().unwrap_or(0); let id = |entry: &Value| entry["id"].as_str().unwrap_or_default().to_owned(); - if [&opened, &closed, &reaffirmed, &blocked, &read, &reopened, &refused].iter().any(|items| !items.is_empty()) || pruned > 0 { + if [&opened, &closed, &reaffirmed, &blocked, &read, &reopened, &held, &unheld, &refused].iter().any(|items| !items.is_empty()) || pruned > 0 { let _ = writeln!(out, "Committed:\n"); for entry in &opened { let _ = writeln!(out, "- opened `{}` ({}, to {}): {}", id(entry), entry["status"].as_str().unwrap_or_default(), entry["to"].as_str().unwrap_or("the room"), entry["words"].as_str().unwrap_or_default()); @@ -779,6 +780,12 @@ fn promises_markdown(out: &mut String, turn: &Value) { let words = entry["reopened"].as_array().and_then(|said| said.last()).map_or("", |said| said["words"].as_str().unwrap_or_default()); let _ = writeln!(out, "- reopened {} ({}): \"{words}\"", id(entry), entry["status"].as_str().unwrap_or_default()); } + for hold in &held { + let _ = writeln!(out, "- held `{}` for {} ({}): \"{}\"", id(hold), hold["from"].as_str().unwrap_or_default(), hold["room"].as_str().unwrap_or("anywhere"), hold["words"].as_str().unwrap_or_default()); + } + for hold in &unheld { + let _ = writeln!(out, "- released hold `{}` by {}", id(hold), hold["releasedBy"]["act"].as_str().unwrap_or_default()); + } for one in &refused { let _ = writeln!(out, "- refused ({}): `{}`", one["reason"].as_str().unwrap_or_default(), one["proposal"]); } diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index f479f67..da4209b 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -888,3 +888,24 @@ fn k33_a_release_renders_by_whom() { "); } + +/// K37 (map 16.28.5): the published schema carries what the commit writes of holds; a stray field fails P1. K36's +/// `reopened` on a promise too. +#[test] +fn k37_the_schema_carries_holds() { + let mut state = crate::projection::harness::tests::control(); + state["personaId"] = json!("eureka"); + let id = "@eureka:gamecult.org"; + state["holds"] = json!([ + { "id": "h-r1-t3-1", "from": "@meta:gamecult.org", "room": "#minds:gamecult.org", "event": "$q3", "madeAt": "2026-11-20T15:00:00Z", "words": "hold it, don't post it in here yet", "status": "open", "releasedAt": null, "releasedBy": null }, + { "id": "h-r1-t3-2", "from": "@heimdall:gamecult.org", "room": null, "event": "$q5", "madeAt": "2026-11-20T15:01:00Z", "words": "Don't post it yet", "status": "released", "releasedAt": "2026-11-20T15:30:00Z", "releasedBy": { "act": "heard", "event": "$q7" } } + ]); + state["commitments"] = json!([{ "id": "c-r1-t1-1", "to": null, "room": "#minds:gamecult.org", "event": "7", "madeAt": "2026-11-20T15:00:00Z", "words": "I'll read it", "status": "open", "needs": { "kind": "words" }, "reopened": [{ "at": "2026-11-20T15:10:00Z", "words": "I read only the description" }], "closedAt": null, "closedBy": null, "extensions": {} }]); + held_to_schema("Eureka", id, &state, "r1-t3").unwrap(); + for (pointer, stray) in [("/holds/0/why", json!("asked")), ("/holds/1/releasedBy/words", json!("go ahead")), ("/commitments/0/reopened/0/event", json!("9"))] { + let mut off = state.clone(); + let (parent, field) = pointer.rsplit_once('/').unwrap(); + off.pointer_mut(parent).unwrap()[field] = stray; + assert!(held_to_schema("Eureka", id, &off, "r1-t4").is_err(), "{pointer}"); + } +} diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 898d8ca..8925d1d 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -2870,3 +2870,19 @@ fn k36_her_view_says_why_it_is_open_again() { let line = "- to Meta, the operator, Tuesday afternoon, in #swarm:gamecult.org, her promise: \"I'll send the render tonight, part 0.\". Reopened a few minutes ago: \"I read only the description, not the diff\". She has no way to do it yet."; assert!(view.lines().any(|shown| shown == line), "{view}"); } + +/// K37 (map 16.28.5): her open holds stand in her view after her promises, oldest first, whole, in code's words; a +/// released one is not shown. The Interpreter lists the open ones by id. +#[test] +fn k37_her_view_shows_what_she_holds() { + let mut with = promising(1); + let hold = |id: &str, room: Value, words: &str, ago: i64, status: &str| json!({ "id": id, "from": OPERATOR, "room": room, "event": format!("${id}"), "madeAt": (now() - chrono::Duration::minutes(ago)).to_rfc3339(), "words": words, "status": status, "releasedAt": null, "releasedBy": null }); + with["holds"] = json!([hold("h-2", Value::Null, "don't tell Kiko yet", 5, "open"), hold("h-1", json!("#swarm:gamecult.org"), "hold it, don't post it in here yet", 30, "open"), hold("h-0", Value::Null, "RELEASED-ONE", 50, "released")]); + let packet = packet_of(TurnKind::Chat, &with, &chat_room(), &History::default(), 1); + let block = "Held for others:\n- held for Meta, the operator, asked about half an hour ago in #swarm:gamecult.org: \"hold it, don't post it in here yet\". Not to go in #swarm:gamecult.org until Meta, the operator lets it go.\n- held for Meta, the operator, asked a few minutes ago: \"don't tell Kiko yet\". Not to go anywhere until Meta, the operator lets it go."; + assert!(packet.in_view.contains(&format!("She has no way to do it yet.\n\n{block}")) && !packet.in_view.contains("RELEASED-ONE"), "{}", packet.in_view); + assert_eq!(packet.holds.iter().map(|hold| (hold.id.as_str(), hold.entry.as_str())).collect::>(), [("h1", "h-1"), ("h2", "h-2")]); + let speech = interpret::speech_prompt(&packet, "The room is warm.", "y", &Tuning::default()); + assert!(speech.contains("Holds:\n- h1 \u{2014} held for Meta, the operator, asked 2026-11-19 13:35 UTC in #swarm:gamecult.org: \"hold it, don't post it in here yet\". Not to go in #swarm:gamecult.org until Meta, the operator lets it go.\n- h2 \u{2014} "), "{speech}"); + assert!(!narrate::projector_prompt(&packet, &Tuning::default()).contains("don't tell Kiko"), "the Projector gets nothing of them"); +} diff --git a/schemas/cultnet/gamecult.persona_state.v0.schema.json b/schemas/cultnet/gamecult.persona_state.v0.schema.json index 33e5a7e..421cd7f 100644 --- a/schemas/cultnet/gamecult.persona_state.v0.schema.json +++ b/schemas/cultnet/gamecult.persona_state.v0.schema.json @@ -66,6 +66,13 @@ "$ref": "#/definitions/commitment" } }, + "holds": { + "type": "array", + "description": "What others asked her not to post or share somewhere yet, open and released in the last seven days (map 16.28.5). Written by her turn's commit: a hold opens only from a line she heard, and is released only by its asker's line or as her thought records the asker let it go; Self and Life may put entries from outside. A draft into a place an open hold covers that carries the held thing is not sent.", + "items": { + "$ref": "#/definitions/hold" + } + }, "updatedAt": { "type": "string", "format": "date-time" @@ -1089,6 +1096,85 @@ "updatedAt" ] }, + "hold": { + "type": "object", + "description": "One hold. from: the asker's Matrix id. room: the room it covers, null for anywhere. event: the asker's line. words: the asker's words naming what is held and where, copied from that line. releasedBy: the act that released it, heard (the asker's line, by event) or prose (her thought recording it).", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "from": { + "type": "string" + }, + "room": { + "type": [ + "string", + "null" + ] + }, + "event": { + "type": "string" + }, + "madeAt": { + "type": "string", + "format": "date-time" + }, + "words": { + "type": "string", + "minLength": 1 + }, + "status": { + "type": "string", + "enum": [ + "open", + "released" + ] + }, + "releasedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "releasedBy": { + "type": [ + "object", + "null" + ], + "additionalProperties": false, + "properties": { + "act": { + "type": "string", + "enum": [ + "heard", + "prose" + ] + }, + "event": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "act", + "event" + ] + } + }, + "required": [ + "id", + "from", + "room", + "event", + "madeAt", + "words", + "status" + ] + }, "commitment": { "type": "object", "description": "One promise of hers. to: the Matrix id she promised, null for the room. event: her line's event id. status: open (she can keep it with what she has), blocked (she has no way to do it yet), kept, withdrawn or released. closedBy: the act that closed it, by its event; words only for an act of hers. needs: what keeping it needs (map 16.25.2): her words, a read of one thing, or something this body lacks. blockedBy: the read that found nothing and blocked it. reaffirmed: the newest three times she said it again. reopened: the newest three times her own words reopened a close (map 16.28.3). readAt, readId and readOf: when a read of what it needs last returned, which read, and what it read in normal form; a receipt whose readOf does not answer needs is none (map 16.26, 16.27).",