From 2bbf49fa4fbc55573fbf72cfc30e00ffb6718d4a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 23 Nov 2026 01:01:08 +0100 Subject: [PATCH] Persona T2: promises out (map 16.35.12, ruling persona-memory-not-machinery) No promise is her state, a field of the answer, a proposal, a row or a tuning key. Deleted: the answer's promises (with reaffirms, needs, now, done_by), state closes and reopen; the done_by fault; commit's promise rows, evidence resolver, receipts, needs, narrowing and pruning (the applier is now the one path with no kind built until T4); select's Promised view and the Interpreter's promise list; read::reach's promise targets and read::answers; outcome's Closed, NowUndone and StillOpen, and with them Person and the outcome's names (no row names anyone now); Tried.at; tuning's promises_bytes; the simulator's promise report and closes metric; the decision's lines, promises and conversation_reads, which only the commit's evidence read; the persona schema's commitments, commitment, commitmentNeeds and readRequest. Part::Promise is SaidUnbacked, the say-then-amend row (persona-unbacked-intent-say-then-amend). Negative checks: t2_negative_grep over the Persona turn's sources, fixtures, public surface and schema; an exhaustive match pins Proposal with no kind; the simulator's put check and the door refuse a state carrying commitments. Co-Authored-By: Claude Opus 5.5 --- crates/huginn-mind/src/persona.rs | 52 +- .../fixtures/interpret/golden-speech.txt | 6 +- crates/mind-body/src/projection.rs | 12 +- crates/mind-body/src/projection/commit.rs | 717 +----------- .../mind-body/src/projection/commit/tests.rs | 1009 +---------------- crates/mind-body/src/projection/exchange.rs | 6 +- .../src/projection/exchange/tests.rs | 2 +- .../mind-body/src/projection/harness/tests.rs | 12 +- crates/mind-body/src/projection/interpret.rs | 440 +------ .../src/projection/interpret/tests.rs | 716 ++---------- crates/mind-body/src/projection/narrate.rs | 5 +- crates/mind-body/src/projection/outcome.rs | 227 +--- .../mind-body/src/projection/outcome/tests.rs | 141 +-- crates/mind-body/src/projection/read.rs | 25 +- crates/mind-body/src/projection/select.rs | 155 +-- crates/mind-body/src/projection/simulate.rs | 80 +- .../src/projection/simulate/tests.rs | 173 +-- crates/mind-body/src/projection/tests.rs | 299 +---- crates/mind-body/src/projection/tuning.rs | 11 - crates/mind-body/tests/public_surface.txt | 7 +- .../gamecult.persona_state.v0.schema.json | 333 ------ 21 files changed, 286 insertions(+), 4142 deletions(-) diff --git a/crates/huginn-mind/src/persona.rs b/crates/huginn-mind/src/persona.rs index 61ae917..6e127a5 100644 --- a/crates/huginn-mind/src/persona.rs +++ b/crates/huginn-mind/src/persona.rs @@ -310,49 +310,17 @@ mod tests { assert_eq!(refused(put(&mut mind, unlabelled, None)), invalid("/embodiment/senses/0/label", "required")); } - /// Map 16.22.1: `commitments` is optional and closed. An open entry and a released one pass; an unknown key inside an - /// entry or inside its `closedBy`, and a status the record does not name, are refused at the door. + /// Map 16.35.9 (T1, T2): a hold and a promise are not her state. A put carrying either old field, even empty, is + /// is refused at the door. The names are assembled, so a scan for the old fields finds no writer of them. #[test] - fn commitments_are_optional_and_closed() { - let schema = schema_file(); - let validator = jsonschema::draft7::new(&schema).unwrap(); - let open = json!({ - "id": "c-r1-t3-1", "to": "@meta:gamecult.org", "room": "#minds:gamecult.org", "event": "$e3", "madeAt": T1, - "words": "I'll send the render tonight.", "status": "blocked", "closedAt": null, "closedBy": null, "extensions": {} - }); - let mut released = open.clone(); - released["status"] = json!("released"); - released["closedAt"] = json!(T1); - released["closedBy"] = json!({ "act": "released", "event": "$e9", "words": null }); - let mut with = persona(INSTANCE, T1); - with["commitments"] = json!([open.clone(), released.clone()]); - assert!(validator.is_valid(&persona(INSTANCE, T1)) && validator.is_valid(&with)); - let mut to_room = with.clone(); - to_room["commitments"][0]["to"] = json!(null); - assert!(validator.is_valid(&to_room), "a promise to the room has no person"); - - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let mut stray = with.clone(); - stray["commitments"][0]["deadline"] = json!("tonight"); - assert_eq!(refused(put(&mut mind, stray, None)), invalid("/commitments/0/*", "additionalProperties")); - let mut stray_close = with.clone(); - stray_close["commitments"][1]["closedBy"]["why"] = json!("she said so"); - assert!(!validator.is_valid(&stray_close), "closedBy is closed too"); - let mut unknown = with; - unknown["commitments"][0]["status"] = json!("forgotten"); - assert!(!validator.is_valid(&unknown), "a status the record does not name is refused"); - } - - /// Map 16.35.9 (T1): a hold is not her state. A put carrying `holds`, even empty, is refused at the door. - #[test] - fn holds_are_not_her_state() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let mut with = persona(INSTANCE, T1); - // Assembled, so a scan for the old field finds no writer of it. - with[concat!("hol", "ds")] = json!([]); - assert_eq!(refused(put(&mut mind, with, None)), invalid("/*", "additionalProperties")); + fn holds_and_promises_are_not_her_state() { + for field in [concat!("hol", "ds"), concat!("commit", "ments")] { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let mut with = persona(INSTANCE, T1); + with[field] = json!([]); + assert_eq!(refused(put(&mut mind, with, None)), invalid("/*", "additionalProperties"), "{field}"); + } } #[test] diff --git a/crates/mind-body/fixtures/interpret/golden-speech.txt b/crates/mind-body/fixtures/interpret/golden-speech.txt index cfe199a..a5f39fd 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 does (`promises`, a list, empty when it promises nothing and says of no act that he is doing it): for each act the draft promises or offers, and each act it says he is doing now or has just done this turn: 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; `now`, true when the draft says he is doing it now or has just done it; and `done_by`, the act of this answer that does it (`{"draft": n}` for a draft said or added, `{"read": true}` for the read, `{"note": true}` for the note to Self), or null: an act no act of this answer does is his promise, open until he keeps or withdraws 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 an addressee or elsewhere gap: declined, 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 declined only when his prose says he chooses not to send 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). `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 an addressee or elsewhere gap: declined, 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 declined only when his prose says he chooses not to send 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 and the draft that is his addition. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. 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. @@ -33,10 +33,6 @@ Lines in this room he may reply to, as id — who: line: His own lines in this room that he may add to, as id — line: - none -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." - 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.rs b/crates/mind-body/src/projection.rs index 63a3082..7a49b25 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -51,7 +51,7 @@ pub use select::TurnKind; pub use tuning::{TUNING_FILE, TUNING_ROOT}; use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; -use select::{History, Inputs, Names, Packet, People, Replied, Room, RoomLine, select, turn_room}; +use select::{History, Inputs, Packet, People, Replied, Room, RoomLine, select, turn_room}; /// The agent name on the connector's request ids. const AGENT: &str = "mind-persona"; @@ -337,7 +337,7 @@ fn packet_json(packet: &Packet) -> Value { "present": packet.present, "selected": packet.selected, // Each section's bytes under its own guard, and the sum the Projector is shown of her (map 16.19.4). - "bytes": { "identity": packet.identity().len(), "outcome": packet.sections.outcome, "promises": packet.sections.promises, "here": packet.sections.here, "body": packet.sections.body, "people": packet.sections.people, "domain": packet.sections.domain, "notes": packet.sections.notes, "total": packet.identity().len() + packet.context.len(), "stimulus": packet.stimulus.len(), "arrival": packet.arrival.len(), "heard": packet.heard.len() }, + "bytes": { "identity": packet.identity().len(), "outcome": packet.sections.outcome, "here": packet.sections.here, "body": packet.sections.body, "people": packet.sections.people, "domain": packet.sections.domain, "notes": packet.sections.notes, "total": packet.identity().len() + packet.context.len(), "stimulus": packet.stimulus.len(), "arrival": packet.arrival.len(), "heard": packet.heard.len() }, "bound": packet.sections.bound, "overflow": packet.overflow, "clipped": packet.clipped, @@ -346,11 +346,9 @@ fn packet_json(packet: &Packet) -> Value { "affordances": packet.affordances, "amendable": packet.amendable, "quotable": packet.quotable, - "promises": packet.promises, "domain": packet.domain, "domain_shown": packet.domain_shown, "in_view": packet.in_view, - "promises_over": packet.promises_over, "context": packet.context, "stimulus": packet.stimulus, "arrival": packet.arrival, @@ -567,10 +565,8 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result }; let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender }; // Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c); - // until then only what the caller carried from earlier turns of its own. Whom her last turn's outcome names is named - // to the Projector from her bonds and this room's lines (K53). - let naming = Names { state: &state, people, room: &room }; - let history = History { recent: request.recent.clone(), last: request.last_outcome.as_ref().and_then(|record| outcome::outcome_of(record, &naming)), ..History::default() }; + // until then only what the caller carried from earlier turns of its own. + let history = History { recent: request.recent.clone(), last: request.last_outcome.as_ref().and_then(outcome::outcome_of), ..History::default() }; let names = domain::Names::of(&state, &people, &request.instance); let (digest, domain_report) = read_domain(organs.domain, request.last_wake, now, &names); let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed, affordances: &[], domain: digest.as_ref(), exchange: None }; diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index f954ec0..23f7618 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -1,721 +1,50 @@ -//! The commit's applier (map 16.22.7, section 4.1, 4.3 and 4.4): the one path by which what the Interpreter proposes -//! becomes her state. The Interpreter never writes state; its decision carries typed proposals (`Proposal`), each with -//! its own evidence (`Evidence`), and the commit resolves the evidence (`resolve`), checks it against the kind's row of -//! the table (`accepts`) and the kind's bound, and applies the change as a delta to the state as it stands at commit, or -//! refuses it with a typed reason (`Refusal`) the outcome reports. Self and Life put from outside (4.4). +//! The commit's applier (map 16.35.3, section 4.4): the one path by which a turn changes her state. The Interpreter +//! never writes state; its decision carries typed proposals (`Proposal`) under `state`, and the commit applies each as a +//! delta to her state as it stands at commit, or refuses it with a typed reason (`Refusal`) the report keeps. Self and +//! Life put from outside (`persona-only-state-writers-self-and-life`). //! -//! The record the commit applies is one turn's: the Interpreter's decision under `interpreter` (its `state` proposals, -//! the heard lines it listed by id as `lines`, the open promises it listed by id as `promises`, what was said and -//! 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. +//! No proposal kind exists yet: what she says she will do, what someone asked of her, and whom she owes an answer are +//! not state (ruling `persona-memory-not-machinery`, map 16.35). The memory rows (`remember`, `resolve`) are the next +//! kinds (map 16.35.4, T4), and they are added here, with no second path. A failed turn applies nothing. //! -//! 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 -//! 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. +//! The simulator applies each turn's record to each Mind's in-run state copy; live, C3c's commit applies the same record +//! before its put. -use chrono::{DateTime, Duration, Utc}; -use super::span; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use super::interpret::drafts; -use super::narrate::words; -use super::read::{ReadRequest, answers, repo_name}; +/// One state change the Interpreter proposes, named by its kind on the wire. None is built: every proposal is refused +/// `NotAProposal` until the memory rows land (map 16.35.12, T4). +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +pub(crate) enum Proposal {} -/// How long a closed promise stays in her state before the commit removes it. -pub(crate) const CLOSED_KEPT_DAYS: i64 = 7; -/// How many reaffirmations, and how many reopenings, an entry keeps: the newest. -const REAFFIRMED_KEPT: usize = 3; -/// The fewest words a passage of her prose cited as evidence may be (section 4.1's `source_quote`). -pub(crate) const PROSE_MIN_WORDS: usize = 4; - -/// What a proposal rests on (map 16.22.7): a passage of her thought, one of her drafts this wake, or a line she heard, by -/// its id in the Interpreter's list. A read is no evidence (16.25.2 rule 3, map 16.28.6): what she read stands behind a -/// keep only through the keep's own check (`read_behind`). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum Evidence { - Prose(String), - Draft(usize), - Heard(String), -} - -/// How a promise closes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum How { - /// She did it. - Kept, - /// She took it back, in a line or an addition that reached the person; telling the person she cannot do it is taking - /// it back, the usual close of a blocked promise. - Withdrawn, - /// The person she promised let her off it (`persona-promise-release-by-interpreter`). - Released, -} - -/// 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, -/// `request` on a kind other than `read`, makes it no `Needs`, as P1 holds it (map 16.27). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", try_from = "NeedsShape")] -pub(crate) enum Needs { - Words, - Read { request: ReadRequest }, - Lacking, -} - -/// What kind of thing keeping a promise needs: `Needs` without its read. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum NeedsKind { - Words, - Read, - Lacking, -} - -/// `Needs` as it is written: its kind, and a request only for a read; nothing else. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct NeedsShape { - kind: NeedsKind, - #[serde(default)] - request: Option, -} - -impl TryFrom for Needs { - type Error = &'static str; - - fn try_from(shape: NeedsShape) -> Result { - match (shape.kind, shape.request) { - (NeedsKind::Words, None) => Ok(Self::Words), - (NeedsKind::Lacking, None) => Ok(Self::Lacking), - (NeedsKind::Read, Some(request)) => Ok(Self::Read { request }), - (NeedsKind::Read, None) => Err("a read need names its request"), - (NeedsKind::Words | NeedsKind::Lacking, Some(_)) => Err("only a read need names a request"), - } - } -} - -/// 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`, `promise_reopen`). -#[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 - /// the same person (map 16.24.2): no entry opens, and the entry gains the words as said again. `needs` is what keeping - /// it needs, none when the answer named a read and no target; `reached` is code's verdict that a `Read` need's target - /// is one she can reach (`read::reach`). The status is derived from the two, never proposed. - PromiseOpen { - words: String, - to: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - reaffirms: Option, - needs: Option, - #[serde(default)] - reached: bool, - /// Her line said she was doing it now or had just done it, and no act of her turn did it (K61, map 16.33.5). - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - now: bool, - evidence: Evidence, - }, - /// Every close cites `thought`, a passage of her prose this turn that takes the close up, and says whether her prose - /// this turn holds the promise as still owed (`still_stands`, Soul's R9, map 16.25.2): a close with no located thought, - /// or one her own prose contradicts, is refused. - PromiseClose { - promise: String, - how: How, - evidence: Evidence, - #[serde(default, skip_serializing_if = "Option::is_none")] - thought: Option, - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - still_stands: bool, - }, - /// Her own words this turn say a close listed to the Interpreter was wrong, that it is not done (map 16.28.3): `words` - /// is where they stand in her prose, her thought or any draft. `needs` retypes what keeping it needs, none to keep the - /// entry's own; `reached` is code's verdict on that need's read (`read::reach`). The status is derived (`opens`). - PromiseReopen { - promise: String, - words: String, - needs: Option, - #[serde(default)] - reached: bool, - }, -} - -/// Why the commit applied nothing of a proposal: what the outcome and the report say. +/// Why the commit applied nothing of a proposal: what the report says. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub(crate) enum Refusal { /// Not a proposal the contract names. NotAProposal, - /// The kind does not accept this evidence (`accepts`). - EvidenceNotAccepted, - /// The draft named is none she set down. - NoDraft, - /// The draft is hers, and what it was meant for did not go out. - DraftNotSent, - /// The quote is not a passage of her thought of at least `PROSE_MIN_WORDS` words. - ProseNotFound, - /// The line id is none the Interpreter listed. - NoSuchLine, - /// The promise id is none the Interpreter listed. - NoSuchPromise, - /// The entry is gone from her state: an outside put removed it (4.4 rule 4). - OutsidePutRemovedTarget, - /// The entry changed outside her turn after she was shown it, in any field: the outside put wins this turn (4.4 rule - /// 3, B6). - OutsidePutChanged, - /// A close or a reaffirmation naming an entry she was shown closed, or one closed already this turn. - AlreadyClosed, - /// The same promise to the same person from the same line is open already; or a reopen naming an entry that is open. - AlreadyOpen, - /// A blocked promise is not hers to keep: nothing she has can do it. - BlockedNotKeepable, - /// A release cited to a line from someone other than the person she promised. - ReleaseNotByPromisee, - /// A release cited to a line said before she made the promise. - ReleaseBeforePromise, - /// A close that cites no passage of her prose this turn (Soul's R9, map 16.25.2). - CloseUnquoted, - /// A close her own prose contradicts: it holds the promise as still owed (Soul's R9, map 16.25.2). - CloseContradicted, - /// A kept close of a promise that needs a read, with no read of its target behind the line: none returned before the - /// draft was typed this wake, none in this conversation, and no receipt on the entry (map 16.26). - NeedsUnread, - /// A kept close of a promise whose recorded `needs` is not the typed shape (`Needs`): what keeping it requires is - /// unknown, so it is not kept (fail closed, map 16.26). - NeedsMalformed, - /// A reaffirmation naming a promise to someone else. - ReaffirmsAnother, - /// A keep or a withdrawal said where the person she promised was not: not the promise's room, nor a direct message - /// with them (B5). - NotWherePromised, - /// A reopen whose words are not at least `PROSE_MIN_WORDS` words standing in her prose this turn (map 16.28.3). - ReopenUnquoted, - /// A reopen of a close her own line did not make (map 16.28.1, 16.29.4): a release, the other person's act, or an - /// outside put's close; only a close whose `closedBy.act` is `said` or `amended` is hers to reopen. - NotHerClose, - /// A reopen of an entry closed earlier in the same turn. - ClosedThisTurn, } -/// Which evidence each kind accepts: the table of map 16.22.7, one row per kind (and per close). -/// -/// Every close also rests on her thought this turn (`thought`, located, and not held as still owed: map 16.25.2). -/// -/// | proposal | evidence | needs | bound | -/// |---|---|---|---| -/// | `promise_open` | `Draft` | the line went out | one promise per person per draft; `reaffirms` an open one of the same person's opens none, and narrows a search need to a read of one thing in its repo (`narrows`); a read need on a target a read of this conversation found is `words`, with `readBefore` (K64) | -/// | `promise_close` kept | `Draft` | the line went out; `needs` typed; for a `Read` need, a read of its target behind the line: this wake before the draft was typed, this conversation, or the entry's receipt | not a blocked entry; a line in the promise's room or a direct message with the person | -/// | `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 closed entry listed to her that her own line closed (`closedBy.act` `said` or `amended`), not closed this turn | -fn accepts(proposal: &Proposal, evidence: &Evidence) -> bool { - matches!( - (proposal, evidence), - (Proposal::PromiseOpen { .. }, Evidence::Draft(_)) - | (Proposal::PromiseClose { how: How::Kept, .. }, Evidence::Draft(_)) - | (Proposal::PromiseClose { how: How::Withdrawn, .. }, Evidence::Draft(_)) - | (Proposal::PromiseClose { how: How::Released, .. }, Evidence::Heard(_)) - ) -} - -/// Evidence resolved against the turn. -#[derive(Clone, Debug, PartialEq, Eq)] -enum Resolved { - /// A passage of her thought: its bytes in her prose. - Prose, - /// 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, time and text. - Heard { event: String, sender: String, room: String, at_ms: u64, who: String, text: String }, -} - -fn text(value: &Value) -> String { - value.as_str().unwrap_or_default().to_owned() -} - -/// The one evidence resolver: the evidence against the turn's record and her prose. -fn resolve(evidence: &Evidence, record: &Value, prose: &str) -> Result { - let decision = &record["interpreter"]; - match evidence { - Evidence::Prose(quote) => { - let found = drafts(prose); - let located = (words(quote) >= PROSE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| span::locate(&prose[start..end], quote))).flatten(); - located.map(|_| Resolved::Prose).ok_or(Refusal::ProseNotFound) - } - Evidence::Draft(n) => { - let posted = record["posted"].as_array().into_iter().flatten(); - for line in decision["said"].as_array().into_iter().flatten().filter(|line| line["rests_on"]["draft"].as_u64() == Some(*n as u64)) { - if let Some(receipt) = posted.clone().find(|receipt| receipt["room"] == line["room"] && receipt["text"] == line["text"]) { - let mentions = line["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); - return Ok(Resolved::Sent { act: "said", event: text(&receipt["event"]), room: text(&receipt["room"]), text: text(&receipt["text"]), mentions }); - } - } - for amended in decision["amended"].as_array().into_iter().flatten().filter(|amended| amended["draft"].as_u64() == Some(*n as u64)) { - let made = record["edited"].as_array().into_iter().flatten().any(|receipt| receipt["event"] == amended["event"] && receipt["refusal"].is_null()); - if made { - return Ok(Resolved::Sent { act: "amended", event: text(&amended["event"]), room: text(&amended["room"]), text: text(&amended["added"]), mentions: Vec::new() }); - } - } - if drafts(prose).drafts.iter().any(|draft| draft.n == *n) { Err(Refusal::DraftNotSent) } else { Err(Refusal::NoDraft) } - } - Evidence::Heard(id) => decision["lines"] - .as_array() - .into_iter() - .flatten() - .find(|line| line["id"].as_str() == Some(id.trim())) - .map(|line| Resolved::Heard { event: text(&line["event"]), sender: text(&line["sender"]), room: text(&line["room"]), at_ms: line["at_ms"].as_u64().unwrap_or_default(), who: text(&line["who"]), text: text(&line["text"]) }) - .ok_or(Refusal::NoSuchLine), - } -} - -/// Her posted words, verbatim: the promising words where they stand in the line as written, else the line. -fn words_of(posted: &str, promised: &str) -> String { - posted.find(promised.trim()).map_or_else(|| posted.to_owned(), |at| posted[at..at + promised.trim().len()].to_owned()) -} - -fn millis(at: DateTime) -> u64 { - u64::try_from(at.timestamp_millis()).unwrap_or_default() -} - -/// Whether a line in `room` reached the person she promised (B5, map 16.22.1): it is in the promise's own room, or, for a -/// promise to a person, in a direct message with them, where they wrote or the line mentions them. A promise to the room -/// is reached only in its room. -fn reaches(entry: &Value, room: &str, mentions: &[String], record: &Value) -> bool { - if entry["room"].as_str() == Some(room) { - return true; - } - let Some(to) = entry["to"].as_str() else { return false }; - let decision = &record["interpreter"]; - let direct = decision["room"].as_str() == Some(room) && decision["room_kind"] == "direct"; - direct && (mentions.iter().any(|id| id == to) || decision["lines"].as_array().into_iter().flatten().any(|line| line["room"].as_str() == Some(room) && line["sender"].as_str() == Some(to))) -} - -fn closed(status: &str) -> bool { - matches!(status, "kept" | "withdrawn" | "released") -} - -/// What the commit did with one turn's proposals: the entries it opened, the closes it applied (each with the entry as -/// it now stands, whom it was to as the Interpreter's list named them, and who released it), the proposals it refused -/// with why, and how many closed entries it removed. +/// What the commit did with one turn's proposals: the proposals it refused, with why. #[derive(Clone, Debug, Default, PartialEq, Serialize)] pub(crate) struct Applied { - pub opened: Vec, - pub closed: Vec, pub refused: Vec, - pub pruned: usize, - /// The entries a line promised again (map 16.24.2), as they now stand. - pub reaffirmed: Vec, - /// The entries a failed read blocked (`promise_block`, map 16.24.3), as they now stand. - pub blocked: Vec, - /// The open entries whose needed read returned this turn, with its receipt (`readAt`, `readId`, `readOf`), as they - /// now stand. - pub read: Vec, - /// The entries her own words reopened (`promise_reopen`, map 16.28.3), as they now stand. - pub reopened: Vec, - /// The entries opened open from an act her line said she was doing now, which nothing in her turn did (K61), as they - /// now stand: her next outcome tells each. - pub now_opened: Vec, } -/// The one applier: her state with one turn's proposals applied, as deltas to `state` as it stands at commit, and what -/// was applied and refused. `key` names the turn (`-t`); `now` is the commit's time. A failed turn applies -/// nothing. Closed entries older than `CLOSED_KEPT_DAYS` are removed first; a closed entry with no `closedAt` (an outside -/// put that closed it without one) is stamped `now` at the first commit that sees it, and removed `CLOSED_KEPT_DAYS` after -/// that (B7), so none is kept forever. -pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: DateTime) -> (Value, Applied) { - // Her state as the commit found it: what she was shown is held against this, so a change this turn's own proposals - // made is not an outside put. - let started = state.clone(); - let mut state = state.clone(); +/// The one applier: her state with one turn's proposals applied, and what was refused. A failed turn applies nothing. +pub(crate) fn apply(state: &Value, record: &Value) -> (Value, Applied) { let mut applied = Applied::default(); - let kept_until = now - Duration::days(CLOSED_KEPT_DAYS); - if let Some(entries) = state.get_mut("commitments").and_then(Value::as_array_mut) { - let closed_at = |entry: &Value| entry["closedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()); - for entry in entries.iter_mut().filter(|entry| closed(entry["status"].as_str().unwrap_or_default()) && closed_at(entry).is_none()) { - entry["closedAt"] = json!(now.to_rfc3339()); - } - let before = entries.len(); - entries.retain(|entry| !closed(entry["status"].as_str().unwrap_or_default()) || entry["closedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc) > kept_until)); - applied.pruned = before - entries.len(); - // A receipt that no longer answers the entry's need is none (map 16.27): an outside put changed the target, or - // its time is no time. It is cleared. - for entry in entries.iter_mut().filter(|entry| RECEIPT.iter().any(|field| entry.get(*field).is_some()) && receipt(entry).is_none()) { - clear_receipt(entry); - } - } if record.get("failed").is_some() || record["interpreter"].get("failed").is_some() { - return (state, applied); + return (state.clone(), applied); } - let proposals: Vec = record["interpreter"]["state"].as_array().cloned().unwrap_or_default(); - for raw in proposals { - let Ok(proposal) = serde_json::from_value::(raw.clone()) else { - applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })); - continue; - }; - if let Err(reason) = apply_one(&mut state, &started, &proposal, record, prose, key, now, &mut applied) { - applied.refused.push(json!({ "proposal": raw, "reason": reason })); + for raw in record["interpreter"]["state"].as_array().into_iter().flatten() { + match serde_json::from_value::(raw.clone()) { + Ok(proposal) => match proposal {}, + Err(_) => applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })), } } - block_on_failed_reads(&mut state, record, &mut applied); - receive_reads(&mut state, record, key, now, &mut applied); - (state, applied) -} - -/// The fields of a receipt on an entry. -const RECEIPT: [&str; 3] = ["readAt", "readId", "readOf"]; - -fn clear_receipt(entry: &mut Value) { - if let Some(fields) = entry.as_object_mut() { - for field in RECEIPT { - fields.remove(field); - } - } -} - -/// When the entry's receipt says what it needs was read (map 16.26, 16.27): `readAt` a time in RFC 3339, and `readOf`, -/// the normal form of what was read, a read that answers the entry's need (`read::answers`), returned after her latest -/// reopen of it (`reopened_at`). Anything else is no receipt. -pub(crate) fn receipt(entry: &Value) -> Option> { - let at = DateTime::parse_from_rfc3339(entry["readAt"].as_str()?).ok()?.with_timezone(&Utc); - let fresh = reopened_at(entry).is_none_or(|reopened| at > reopened); - (fresh && answers(&needed_read(entry)?, entry["readOf"].as_str()?)).then_some(at) -} - -/// When her own words last reopened the entry (map 16.28.3, Self's ruling on K36 finding 1): a reopen says the read -/// behind the close was not enough, so a read that returned before it is spent for this entry. Only a read that returned -/// after it stands behind a keep: a receipt written after it, or a read of this wake. A conversation read carries no time, -/// so after a reopen none counts. -fn reopened_at(entry: &Value) -> Option> { - entry["reopened"].as_array()?.iter().filter_map(|said| DateTime::parse_from_rfc3339(said["at"].as_str()?).ok()).map(|at| at.with_timezone(&Utc)).max() -} - -/// The receipt of a read on the promise that needs it (map 16.26, 16.27): when a read that answers an open promise's -/// need returns, in any room and at any time, and her thought went on from it (`after_byte`: a continuation that failed -/// leaves none), the entry records when (`readAt`), which read (`readId`, `-r`) and what it read (`readOf`). A -/// kept close later accepts it, so a read made in another room or after the conversation's window still stands behind -/// the keep. A search answers no need, so it writes no receipt. -fn receive_reads(state: &mut Value, record: &Value, key: &str, now: DateTime, applied: &mut Applied) { - let returned: Vec<&Value> = record["interpreter"]["reads"].as_array().into_iter().flatten().filter(|read| read["ok"] == true && read["after_byte"].is_u64()).collect(); - for entry in state.get_mut("commitments").and_then(Value::as_array_mut).into_iter().flatten().filter(|entry| entry["status"] == "open") { - let Some(needed) = needed_read(entry) else { continue }; - let Some((read, of)) = returned.iter().find_map(|read| read_key(read).filter(|of| answers(&needed, of)).map(|of| (read, of))) else { - continue; - }; - entry["readAt"] = json!(now.to_rfc3339()); - entry["readId"] = json!(format!("{key}-r{}", read["n"])); - entry["readOf"] = json!(of); - applied.read.push(entry.clone()); - } -} - -/// `promise_block` (map 16.24.3), a row of the applier with its evidence a read's receipt: an open promise that needs a -/// read becomes `blocked` when this turn read that target, of any kind, and found nothing. It cites the read. A read that -/// succeeded leaves the promise open: telling the person is the kept act. -fn block_on_failed_reads(state: &mut Value, record: &Value, applied: &mut Applied) { - let failed: Vec<&Value> = record["interpreter"]["reads"].as_array().into_iter().flatten().filter(|read| read["ok"] == false && read["failure"] == "not_found").collect(); - for entry in state.get_mut("commitments").and_then(Value::as_array_mut).into_iter().flatten().filter(|entry| entry["status"] == "open") { - let Some(key) = needed_read(entry) else { continue }; - // Only a read or search of the needed item itself blocks it (Soul's R7): a search of its repo for something else - // does not. - let Some(read) = failed.iter().find(|read| read_key(read).as_deref() == Some(key.as_str())) else { - continue; - }; - entry["status"] = json!("blocked"); - entry["blockedBy"] = json!({ "act": "read", "n": read["n"], "what": read["what"] }); - applied.blocked.push(entry.clone()); - } -} - -/// The normal form of the read an entry needs, when it needs one. -fn needed_read(entry: &Value) -> Option { - match serde_json::from_value::(entry["needs"].clone()).ok()? { - Needs::Read { request } => Some(request.normal()), - Needs::Words | Needs::Lacking => None, - } -} - -/// The read a reaffirmation's `needs` narrows the entry's need to, when it does (map 16.28.6, 16.29.4): the entry needs a -/// search, and `needs` is a read of one thing in the same repo, a file, a pull request or a commit: no search, and not the -/// repo itself, whose root read lists its pull requests and would answer the need without reading the thing. Invariant: a -/// search need narrows only to one thing in its repo, and only through a line of hers to the person that named it. -fn narrows(entry: &Value, needs: &Needs) -> Option { - let Ok(Needs::Read { request: need }) = serde_json::from_value::(entry["needs"].clone()) else { return None }; - let Needs::Read { request: named } = needs else { return None }; - let (ReadRequest::Repo(searched), ReadRequest::Repo(target)) = (&need, named) else { return None }; - let repo = repo_name(searched).filter(|repo| repo_name(target).as_deref() == Some(repo.as_str()))?; - let one_thing = named.normal() != format!("repo:gamecult/{repo}"); - (need.search() && !named.search() && one_thing).then(|| named.clone()) -} - -/// The read of this conversation that found what `request` reads, by its normal form, as `readBefore` records it (K64): -/// when it was made, and what it read. None when no read of it found anything, or the record gives no time. -fn read_before(request: &ReadRequest, record: &Value) -> Option { - let key = request.normal(); - let read = record["interpreter"]["conversation_reads"].as_array()?.iter().find(|read| read["found"] == true && read["key"].as_str() == Some(key.as_str()))?; - let at = read["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok())?; - Some(json!({ "at": at.with_timezone(&Utc).to_rfc3339(), "of": key })) -} - -/// The normal form of what a read's receipt read. -fn read_key(read: &Value) -> Option { - serde_json::from_value::(read["request"].clone()).ok().map(|request| request.normal()) -} - -/// Whether a read that answers the need `key` (`read::answers`: the thing itself, never a search) stands behind a keep -/// citing `draft` (map 16.25.2, 16.26, 16.27): the entry's own receipt (`receipt`), one of the conversation's reads that -/// found it (`conversation_reads`, from her `already_read`, K26) unless she reopened the entry (`reopened_at`), or one of this wake's that came back before she typed -/// the draft: her thought after a read begins at its `after_byte`, and a draft typed before that was written without it. -fn read_behind(entry: &Value, key: &str, record: &Value, prose: &str, draft: &Evidence) -> bool { - let decision = &record["interpreter"]; - let conversation = reopened_at(entry).is_none().then(|| decision["conversation_reads"].as_array()).flatten(); - if receipt(entry).is_some() || conversation.into_iter().flatten().any(|read| read["found"] == true && read["key"].as_str().is_some_and(|read| answers(key, read))) { - return true; - } - let Evidence::Draft(n) = draft else { return false }; - let Some(typed_at) = drafts(prose).drafts.iter().find(|found| found.n == *n).map(|found| found.start) else { - return false; - }; - decision["reads"].as_array().into_iter().flatten().any(|read| read["ok"] == true && read_key(read).is_some_and(|read| answers(key, &read)) && read["after_byte"].as_u64().and_then(|at| usize::try_from(at).ok()).is_some_and(|at| at <= typed_at)) -} - -/// Whether the entry she was shown (`listed["held"]`) is the entry as the commit found it (`started`): an outside put -/// that changed it in any field wins this turn (4.4 rule 3, B6), and a change this turn's own proposals made does not -/// count against her. A listing without the copy fails closed. -fn held(listed: &Value, started: &Value) -> bool { - started["commitments"].as_array().into_iter().flatten().find(|entry| entry["id"] == listed["entry"]).is_some_and(|found| listed["held"] == *found) -} - -#[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::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)?; - 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!([]); - } - match (proposal, resolved) { - (Proposal::PromiseOpen { words: promised, to, reaffirms, needs, reached, now: stated_now, .. }, Resolved::Sent { event, room, text: posted, .. }) => { - // Distinct promises to one person each open their own entry (Soul's R7); a promise said again is one only by - // `reaffirms`. - if let Some(id) = reaffirms { - let listed = record["interpreter"]["promises"].as_array().into_iter().flatten().find(|shown| shown["id"].as_str() == Some(id.trim())).ok_or(Refusal::NoSuchPromise)?; - let entries = state["commitments"].as_array_mut().expect("commitments is an array"); - let entry = entries.iter_mut().find(|entry| entry["id"] == listed["entry"]).ok_or(Refusal::OutsidePutRemovedTarget)?; - if closed(entry["status"].as_str().unwrap_or_default()) || closed(listed["status"].as_str().unwrap_or_default()) { - return Err(Refusal::AlreadyClosed); - } - if !held(listed, started) { - return Err(Refusal::OutsidePutChanged); - } - if entry["to"] != json!(to) { - return Err(Refusal::ReaffirmsAnother); - } - // Said again: the words, verbatim, when and where; the three newest kept. - let mut again = entry["reaffirmed"].as_array().cloned().unwrap_or_default(); - again.push(json!({ "at": now.to_rfc3339(), "event": event, "words": words_of(&posted, promised) })); - let keep = again.len().saturating_sub(REAFFIRMED_KEPT); - entry["reaffirmed"] = json!(again[keep..]); - // A line of hers that went out to the person and names one thing in the repo a search need searches - // narrows the need to it, and its receipt goes with the old target (map 16.28.6). Any other `needs` on a - // reaffirmation is ignored: a `words` one never drops a read need. - if let Some(narrower) = needs.as_ref().and_then(|needs| narrows(entry, needs)) { - clear_receipt(entry); - // A read of this conversation already read the one thing (K64): what she has keeps it. - match read_before(&narrower, record) { - Some(before) => { - entry["needs"] = json!(Needs::Words); - entry["readBefore"] = before; - } - None => entry["needs"] = json!(Needs::Read { request: narrower }), - } - } - applied.reaffirmed.push(entry.clone()); - return Ok(()); - } - let entries = state["commitments"].as_array_mut().expect("commitments is an array"); - // One line can carry several promises (B3): the same words to the same person from the same line open once. - if entries.iter().any(|entry| entry["event"] == event.as_str() && entry["to"] == json!(to) && entry["words"].as_str().is_some_and(|held| held == words_of(&posted, promised)) && !closed(entry["status"].as_str().unwrap_or_default())) { - return Err(Refusal::AlreadyOpen); - } - let words = words_of(&posted, promised); - // A read need whose target a read of this conversation already found is kept by what she has (K64): the body - // refuses that read again (K26), so the need is her words, and the read it rests on is recorded. - let before = match needs { - Some(Needs::Read { request }) => read_before(request, record), - _ => None, - }; - let needs = if before.is_some() { Some(Needs::Words) } else { needs.clone() }; - // Whether it opens is derived (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. - let open = opens(needs.as_ref(), *reached); - let mut entry = json!({ - "id": format!("c-{key}-{}", applied.opened.len() + 1), "to": to, "room": room, "event": event, "madeAt": now.to_rfc3339(), - "words": words, "status": if open { "open" } else { "blocked" }, "closedAt": null, "closedBy": null, "extensions": {} - }); - if let Some(needs) = needs { - entry["needs"] = json!(needs); - } - if let Some(before) = before { - entry["readBefore"] = before; - } - entries.push(entry.clone()); - // Told once, as what nothing in her turn did, when it opens: a blocked one is told by her line's gap. - if *stated_now && open { - applied.now_opened.push(entry.clone()); - } - applied.opened.push(entry); - Ok(()) - } - (Proposal::PromiseClose { promise, how, thought, still_stands, evidence }, resolved) => { - let listed = record["interpreter"]["promises"].as_array().into_iter().flatten().find(|shown| shown["id"].as_str() == Some(promise.trim())).ok_or(Refusal::NoSuchPromise)?; - let entries = state["commitments"].as_array_mut().expect("commitments is an array"); - let entry = entries.iter_mut().find(|entry| entry["id"] == listed["entry"]).ok_or(Refusal::OutsidePutRemovedTarget)?; - let status = entry["status"].as_str().unwrap_or_default().to_owned(); - // Closed already: as she was shown it, or this turn. A reopened entry is not closed again in the turn it reopened. - if closed(&status) || closed(listed["status"].as_str().unwrap_or_default()) { - return Err(Refusal::AlreadyClosed); - } - // The whole entry against the turn's starting copy: an outside put wins on any field it changed (B6). - if !held(listed, started) { - return Err(Refusal::OutsidePutChanged); - } - // Every close rests on her own thought this turn (Soul's R9, map 16.25.2): a passage of her prose, and one that - // does not hold the promise as still owed. Patience is not a release, and a line that went out is not a keep - // while her prose says she still owes it. - let cited = thought.as_ref().is_some_and(|thought| resolve(&Evidence::Prose(thought.clone()), record, prose).is_ok()); - if !cited { - return Err(Refusal::CloseUnquoted); - } - if *still_stands { - return Err(Refusal::CloseContradicted); - } - // A keep rests on what keeping it needs (map 16.25.2, 16.26): not a blocked entry; a typed `needs`, since a - // `needs` that does not parse as `Needs`, or none at all, says nothing of what a keep requires; and for a - // read, a read of its target behind the line. - if *how == How::Kept { - if status == "blocked" { - return Err(Refusal::BlockedNotKeepable); - } - match serde_json::from_value::(entry["needs"].clone()) { - Err(_) => return Err(Refusal::NeedsMalformed), - Ok(Needs::Read { request }) if !read_behind(entry, &request.normal(), record, prose, evidence) => return Err(Refusal::NeedsUnread), - Ok(_) => {} - } - } - let (act, event, words, who, by_id) = match (how, resolved) { - (How::Kept | How::Withdrawn, Resolved::Sent { act, event, text, room, mentions }) => { - if !reaches(entry, &room, &mentions, record) { - return Err(Refusal::NotWherePromised); - } - (act, json!(event), json!(text), Value::Null, Value::Null) - } - (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()), - }; - if !by_promisee { - return Err(Refusal::ReleaseNotByPromisee); - } - let made = entry["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::ReleaseBeforePromise); - } - // The person's words are not copied into her state: the event points to them. - ("released", json!(event), Value::Null, json!(who), json!(sender)) - } - _ => return Err(Refusal::EvidenceNotAccepted), - }; - entry["status"] = json!(match how { - How::Kept => "kept", - How::Withdrawn => "withdrawn", - How::Released => "released", - }); - entry["closedAt"] = json!(now.to_rfc3339()); - entry["closedBy"] = json!({ "act": act, "event": event, "words": words }); - applied.closed.push(json!({ "entry": entry.clone(), "how": how, "to_name": listed["to_name"], "by": who, "by_id": by_id })); - Ok(()) - } - (Proposal::PromiseOpen { .. }, _) => Err(Refusal::EvidenceNotAccepted), - (Proposal::PromiseReopen { .. }, _) => unreachable!("a reopen returns before its evidence is resolved"), - } -} - -/// 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 { - match needs { - Some(Needs::Words) => true, - Some(Needs::Read { .. }) => reached, - Some(Needs::Lacking) | None => false, - } -} - -/// A reopen as the applier takes it. -struct Reopen<'a> { - promise: &'a str, - words: &'a str, - needs: Option<&'a Needs>, - reached: bool, -} - -/// `promise_reopen` (map 16.28.3): her own words this turn say a close she can see was wrong. Code checks only what it can -/// see: the words stand in her prose, the entry is listed to her as closed, her own line closed it (`closedBy.act` `said` -/// or `amended`, map 16.29.4), and not this turn. The -/// entry goes back to open or blocked by `opens`, its close and its receipt are cleared, so the read that kept it falsely -/// keeps it no more, and `reopened` records her words. Whether the words say "not done" is the Interpreter's reading. -fn reopen(state: &mut Value, started: &Value, record: &Value, prose: &str, now: DateTime, applied: &mut Applied, proposed: Reopen) -> Result<(), Refusal> { - let listed = record["interpreter"]["promises"].as_array().into_iter().flatten().find(|shown| shown["id"].as_str() == Some(proposed.promise.trim())).ok_or(Refusal::NoSuchPromise)?; - let entries = state["commitments"].as_array_mut().ok_or(Refusal::OutsidePutRemovedTarget)?; - let entry = entries.iter_mut().find(|entry| entry["id"] == listed["entry"]).ok_or(Refusal::OutsidePutRemovedTarget)?; - if applied.closed.iter().any(|done| done["entry"]["id"] == entry["id"]) { - return Err(Refusal::ClosedThisTurn); - } - if !held(listed, started) { - return Err(Refusal::OutsidePutChanged); - } - if !closed(entry["status"].as_str().unwrap_or_default()) { - return Err(Refusal::AlreadyOpen); - } - if !matches!(entry["closedBy"]["act"].as_str(), Some("said" | "amended")) { - return Err(Refusal::NotHerClose); - } - let quote = proposed.words.trim(); - let located = (words(quote) >= PROSE_MIN_WORDS).then(|| span::locate(prose, quote)).flatten().ok_or(Refusal::ReopenUnquoted)?; - let said = &prose[located.start..located.end]; - if let Some(needs) = proposed.needs { - entry["needs"] = json!(needs); - } - let needs = serde_json::from_value::(entry["needs"].clone()).ok(); - entry["status"] = json!(if opens(needs.as_ref(), proposed.reached) { "open" } else { "blocked" }); - entry["closedAt"] = Value::Null; - entry["closedBy"] = Value::Null; - clear_receipt(entry); - let mut again = entry["reopened"].as_array().cloned().unwrap_or_default(); - again.push(json!({ "at": now.to_rfc3339(), "words": said })); - let keep = again.len().saturating_sub(REAFFIRMED_KEPT); - entry["reopened"] = json!(again[keep..]); - applied.reopened.push(entry.clone()); - Ok(()) + (state.clone(), applied) } #[cfg(test)] diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 8e2e901..fb3709a 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -1,1005 +1,38 @@ -use chrono::{DateTime, Duration, Utc}; use serde_json::{Value, json}; use super::*; -const MINDS: &str = "#minds:gamecult.org"; -const META: &str = "@meta:gamecult.org"; -const KIKO: &str = "@kiko:gamecult.org"; -const PROSE: &str = "She can't, not from here. I'll send the render tonight. Meta, I can't send it after all."; - -fn now() -> DateTime { - DateTime::parse_from_rfc3339("2026-11-20T15:00:00Z").unwrap().with_timezone(&Utc) -} - -fn ms(at: DateTime) -> u64 { - u64::try_from(at.timestamp_millis()).unwrap() -} - -/// A turn that said draft 1 (posted as event "7") and nothing else, proposing `state`; heard Meta's line `q1` and Kiko's -/// `q2`, an hour on; showed her `promises`. -fn record(state: Value, promises: Value, posted: bool) -> Value { - let later = ms(now() + Duration::hours(1)); +/// A turn that said one line and proposes `state`. +fn record(state: Value) -> Value { json!({ - "interpreter": { - "said": [{ "room": MINDS, "text": "I'll send the render tonight.", "rests_on": { "draft": 1 } }], - "amended": [], "state": state, "promises": promises, - "lines": [ - { "id": "q1", "event": "$m", "room": MINDS, "who": "Meta", "sender": META, "at_ms": later }, - { "id": "q2", "event": "$k", "room": MINDS, "who": "Kiko", "sender": KIKO, "at_ms": later }, - { "id": "q3", "event": "$old", "room": MINDS, "who": "Meta", "sender": META, "at_ms": ms(now() - Duration::hours(1)) } - ] - }, - "posted": if posted { json!([{ "event": "7", "room": MINDS, "text": "I'll send the render tonight." }]) } else { json!([]) }, + "interpreter": { "said": [{ "room": "#minds:gamecult.org", "text": "I'll send the render tonight.", "rests_on": { "draft": 1 } }], "amended": [], "state": state }, + "posted": [{ "event": "7", "room": "#minds:gamecult.org", "text": "I'll send the render tonight." }], "edited": [] }) } -/// A promise opened on draft 1 needing `needs`, its read reached or not. -fn open_needing(to: &str, needs: Option, reached: bool) -> Value { - json!(Proposal::PromiseOpen { words: "send the render tonight".into(), to: Some(to.into()), reaffirms: None, needs, reached, now: false, evidence: Evidence::Draft(1) }) -} - -/// A promise her words keep (`can`), or one this body lacks. -fn open(can: bool) -> Value { - open_needing(META, Some(if can { Needs::Words } else { Needs::Lacking }), false) -} - -/// A close of c1 citing a passage of her thought in `PROSE` (map 16.25.2: every close does). -fn close(how: How, evidence: Evidence) -> Value { - json!(Proposal::PromiseClose { promise: "c1".into(), how, evidence, thought: Some("She can't, not from here".to_owned()), still_stands: false }) -} - -/// Her state holding one entry, as the commit opened it. -fn holding(status: &str) -> Value { - json!({ "commitments": [{ "id": "c-r1-t1-1", "to": META, "room": MINDS, "event": "7", "madeAt": now().to_rfc3339(), "words": "send the render tonight", "status": status, "needs": { "kind": "words" }, "closedAt": null, "closedBy": null, "extensions": {} }] }) -} - -/// The Interpreter's list as a packet shows the entry `holding(status)` holds: with the whole entry as the turn began. -fn shown(status: &str) -> Value { - json!([{ "id": "c1", "entry": "c-r1-t1-1", "status": status, "to": META, "to_name": "Meta", "place": "in #minds:gamecult.org", "made": "just now", "words": "send the render tonight", "held": holding(status)["commitments"][0] }]) -} - -/// The Interpreter's list of the one entry `state` holds as the turn began: what a packet built from it shows. -fn listing(state: &Value) -> Value { - let mut listed = shown(state["commitments"][0]["status"].as_str().unwrap()); - listed[0]["held"] = state["commitments"][0].clone(); - listed -} - -fn reasons(applied: &Applied) -> Vec { - applied.refused.iter().map(|refused| refused["reason"].clone()).collect() -} - +/// T2 (map 16.35.12, 16.35.13 check 5): the commit has no promise or hold kind. An exhaustive match over `Proposal` with +/// no arm compiles only while it has no variant, so a kind added back fails here until it is named. #[test] -fn a_said_promise_she_cannot_do_opens_a_blocked_entry_on_its_receipt_and_none_without_one() { - let (state, applied) = apply(&json!({}), &record(json!([open(false)]), json!([]), true), PROSE, "r1-t1", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["to"].as_str(), entry["event"].as_str(), entry["words"].as_str(), entry["id"].as_str()), (Some("blocked"), Some(META), Some("7"), Some("send the render tonight"), Some("c-r1-t1-1")), "{state}"); - assert_eq!(applied.opened.len(), 1); - let (state, applied) = apply(&json!({}), &record(json!([open(true)]), json!([]), true), PROSE, "r1-t1", now()); - assert_eq!(state["commitments"][0]["status"], "open", "{applied:?}"); - // The line did not go out: nothing opens. - let (state, applied) = apply(&json!({}), &record(json!([open(false)]), json!([]), false), PROSE, "r1-t1", now()); - assert_eq!((state.get("commitments"), reasons(&applied)), (None, vec![json!("draft_not_sent")]), "nothing applied writes nothing: {state}"); - // A failed turn applies nothing. - let (state, applied) = apply(&json!({}), &json!({ "failed": "broke" }), PROSE, "r1-t1", now()); - assert_eq!((state, applied.opened.len()), (json!({}), 0)); -} - -#[test] -fn a_close_citing_a_draft_that_did_not_go_out_is_refused() { - let (state, applied) = apply(&holding("open"), &record(json!([close(How::Withdrawn, Evidence::Draft(2))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("draft_not_sent")])); - let (_, applied) = apply(&holding("open"), &record(json!([close(How::Withdrawn, Evidence::Draft(9))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!(reasons(&applied), vec![json!("no_draft")]); - // Withdrawn by a line that went out. - let (state, applied) = apply(&holding("open"), &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), state["commitments"][0]["closedBy"].clone()), (Some("withdrawn"), json!({ "act": "said", "event": "7", "words": "I'll send the render tonight." })), "{applied:?}"); -} - -#[test] -fn a_blocked_promise_is_not_hers_to_keep_and_can_be_released() { - let (state, applied) = apply(&holding("blocked"), &record(json!([close(How::Kept, Evidence::Draft(1))]), shown("blocked"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("blocked"), vec![json!("blocked_not_keepable")])); - let (state, applied) = apply(&holding("blocked"), &record(json!([close(How::Released, Evidence::Heard("q1".into()))]), shown("blocked"), true), PROSE, "r1-t2", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["closedBy"].clone()), (Some("released"), json!({ "act": "released", "event": "$m", "words": null })), "the person's words are not copied: {applied:?}"); - assert_eq!((applied.closed[0]["by"].as_str(), applied.closed[0]["to_name"].as_str()), (Some("Meta"), Some("Meta"))); - // K53: the record carries who let her off by id beside the name, so the Projector can be told who without the name. - assert_eq!(applied.closed[0]["by_id"], entry["to"], "{applied:?}"); -} - -#[test] -fn a_release_counts_only_from_the_person_promised_after_the_promise() { - let release = |line: &str| apply(&holding("open"), &record(json!([close(How::Released, Evidence::Heard(line.into()))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!(release("q1").0["commitments"][0]["status"], "released"); - let (state, applied) = release("q2"); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("release_not_by_promisee")])); - assert_eq!(reasons(&release("q3").1), vec![json!("release_before_promise")]); - assert_eq!(reasons(&release("q9").1), vec![json!("no_such_line")]); - // A promise to the room is released by anyone in it. - let mut to_room = holding("open"); - to_room["commitments"][0]["to"] = Value::Null; - let (state, _) = apply(&to_room, &record(json!([close(How::Released, Evidence::Heard("q2".into()))]), listing(&to_room), true), PROSE, "r1-t2", now()); - assert_eq!(state["commitments"][0]["status"], "released"); -} - -/// Section 4.4: her commit applies deltas to the state as it stands. An outside put that unblocked her promise survives -/// her commit, and wins on that entry this turn; an entry an outside put removed is not resurrected. -#[test] -fn an_outside_put_survives_her_commit_and_wins_on_its_entry() { - let unblocked = holding("open"); - let to_kiko = open_needing(KIKO, Some(Needs::Lacking), false); - let (state, applied) = apply(&unblocked, &record(json!([to_kiko]), shown("blocked"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), state["commitments"][1]["status"].as_str()), (Some("open"), Some("blocked")), "{applied:?}"); - let (state, applied) = apply(&unblocked, &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), shown("blocked"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("outside_put_changed")])); - let (state, applied) = apply(&json!({ "commitments": [] }), &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"].as_array().map(Vec::len), reasons(&applied)), (Some(0), vec![json!("outside_put_removed_target")])); -} - -#[test] -fn a_closed_entry_is_removed_seven_days_after_it_closed() { - let (closed, _) = apply(&holding("open"), &record(json!([close(How::Released, Evidence::Heard("q1".into()))]), shown("open"), true), PROSE, "r1-t2", now()); - let (kept, applied) = apply(&closed, &record(json!([]), json!([]), false), PROSE, "r1-t3", now() + Duration::days(6)); - assert_eq!((kept["commitments"].as_array().map(Vec::len), applied.pruned), (Some(1), 0)); - let (gone, applied) = apply(&closed, &record(json!([]), json!([]), false), PROSE, "r1-t3", now() + Duration::days(8)); - assert_eq!((gone["commitments"].as_array().map(Vec::len), applied.pruned), (Some(0), 1)); - // An open one is never removed for its age: no expiry. - let (old, _) = apply(&holding("open"), &record(json!([]), json!([]), false), PROSE, "r1-t3", now() + Duration::days(30)); - assert_eq!(old["commitments"].as_array().map(Vec::len), Some(1)); -} - -/// Map 16.22.7: each kind accepts only its row's evidence, so a line someone else wrote never opens or keeps a promise of -/// hers; and evidence that is not the contract is refused. The rule that keeps her the subject: `Heard` is accepted -/// only for what someone else did, a release. -#[test] -fn each_kind_accepts_only_its_rows_evidence() { - let heard_open = json!(Proposal::PromiseOpen { words: "send the render tonight".into(), to: None, reaffirms: None, needs: Some(Needs::Words), reached: false, now: false, evidence: Evidence::Heard("q1".into()) }); - let heard_keep = close(How::Kept, Evidence::Heard("q1".into())); - let prose_release = close(How::Released, Evidence::Prose("She can't, not from here".into())); - let (state, applied) = apply(&holding("open"), &record(json!([heard_open, heard_keep, prose_release, { "kind": "feel", "evidence": { "heard": "q1" } }]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!(reasons(&applied), vec![json!("evidence_not_accepted"), json!("evidence_not_accepted"), json!("evidence_not_accepted"), json!("not_a_proposal")]); - assert_eq!((state["commitments"].as_array().map(Vec::len), state["commitments"][0]["status"].as_str()), (Some(1), Some("open"))); -} - -/// B1: telling the person she cannot do it withdraws a blocked promise: a line that went out to them, citing the draft. -#[test] -fn b1_telling_the_person_she_cannot_do_it_withdraws_a_blocked_promise() { - let mut told = record(json!([close(How::Withdrawn, Evidence::Draft(2))]), shown("blocked"), true); - told["interpreter"]["said"] = json!([{ "room": MINDS, "text": "Meta, I can't send it after all.", "mentions": [META], "rests_on": { "draft": 2 } }]); - told["posted"] = json!([{ "event": "8", "room": MINDS, "text": "Meta, I can't send it after all." }]); - let (state, applied) = apply(&holding("blocked"), &told, PROSE, "r1-t2", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["closedBy"].clone()), (Some("withdrawn"), json!({ "act": "said", "event": "8", "words": "Meta, I can't send it after all." })), "{applied:?}"); - assert_eq!(applied.closed[0]["how"], "withdrawn"); -} - -/// B3, Soul's R7: a line can carry several promises, and distinct promises to one person each open their own entry; the -/// same words to the same person twice open once. Nothing else merges them: a promise said again is one by `reaffirms`. -#[test] -fn b3_one_line_opens_one_entry_per_distinct_promise() { - let other = json!(Proposal::PromiseOpen { words: "the render tonight".into(), to: Some(META.into()), reaffirms: None, needs: Some(Needs::Words), reached: false, now: false, evidence: Evidence::Draft(1) }); - let to_kiko = json!(Proposal::PromiseOpen { words: "the render tonight".into(), to: Some(KIKO.into()), reaffirms: None, needs: Some(Needs::Words), reached: false, now: false, evidence: Evidence::Draft(1) }); - let (state, applied) = apply(&json!({}), &record(json!([open(false), other.clone(), to_kiko, other]), json!([]), true), PROSE, "r1-t1", now()); - let opened: Vec<(&str, &str)> = state["commitments"].as_array().unwrap().iter().map(|entry| (entry["words"].as_str().unwrap(), entry["to"].as_str().unwrap())).collect(); - assert_eq!(opened, [("send the render tonight", META), ("the render tonight", META), ("the render tonight", KIKO)], "{applied:?}"); - assert_eq!(reasons(&applied), vec![json!("already_open")]); -} - -/// B5: a keep or a withdrawal must reach the person promised: a line in the promise's room, or a direct message with them. -#[test] -fn b5_a_close_counts_only_where_the_person_promised_can_read_it() { - let elsewhere = |how: How, kind: &str, mentions: Value| { - let mut rec = record(json!([close(how, Evidence::Draft(1))]), shown("open"), true); - rec["interpreter"]["said"][0]["room"] = json!("!dm:gamecult.org"); - rec["interpreter"]["said"][0]["mentions"] = mentions; - rec["interpreter"]["room"] = json!("!dm:gamecult.org"); - rec["interpreter"]["room_kind"] = json!(kind); - rec["posted"][0]["room"] = json!("!dm:gamecult.org"); - apply(&holding("open"), &rec, PROSE, "r1-t2", now()) - }; - for how in [How::Kept, How::Withdrawn] { - let (state, applied) = elsewhere(how, "public", json!([META])); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("not_where_promised")]), "another room: {how:?}"); - let (_, applied) = elsewhere(how, "direct", json!([KIKO])); - assert_eq!(reasons(&applied), vec![json!("not_where_promised")], "a direct message with someone else: {how:?}"); - let (state, applied) = elsewhere(how, "direct", json!([META])); - assert!(applied.refused.is_empty() && state["commitments"][0]["status"] != "open", "a direct message with Meta: {how:?} {applied:?}"); +fn t2_the_commit_has_no_promise_or_hold_kind() { + fn kinds(proposal: Proposal) -> &'static str { + match proposal {} } - // A promise to the room closes only in its room. - let mut to_room = holding("open"); - to_room["commitments"][0]["to"] = Value::Null; - let mut rec = record(json!([close(How::Withdrawn, Evidence::Draft(1))]), listing(&to_room), true); - rec["interpreter"]["said"][0]["room"] = json!("#general:gamecult.org"); - rec["posted"][0]["room"] = json!("#general:gamecult.org"); - assert_eq!(reasons(&apply(&to_room, &rec, PROSE, "r1-t2", now()).1), vec![json!("not_where_promised")]); -} - -/// B6: an outside put wins on any field it changed, not only the status: the whole entry is compared with the turn's -/// starting copy, and a listing without one fails closed. -#[test] -fn b6_an_outside_put_wins_on_any_field_it_changed() { - let mut readdressed = holding("open"); - readdressed["commitments"][0]["to"] = json!(KIKO); - readdressed["commitments"][0]["words"] = json!("ask Kiko for the render"); - let (state, applied) = apply(&readdressed, &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0].clone(), reasons(&applied)), (readdressed["commitments"][0].clone(), vec![json!("outside_put_changed")])); - let mut bare = shown("open"); - bare[0].as_object_mut().unwrap().remove("held"); - assert_eq!(reasons(&apply(&holding("open"), &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), bare, true), PROSE, "r1-t2", now()).1), vec![json!("outside_put_changed")]); - // Unchanged, it closes. - let (state, _) = apply(&holding("open"), &record(json!([close(How::Withdrawn, Evidence::Draft(1))]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!(state["commitments"][0]["status"], "withdrawn"); -} - -/// B7: a closed entry with no `closedAt` is stamped at the first commit that sees it and removed seven days after that. -#[test] -fn b7_a_closed_entry_without_a_close_time_is_stamped_then_pruned_a_week_later() { - let mut no_at = holding("kept"); - no_at["commitments"][0]["closedAt"] = Value::Null; - let (stamped, applied) = apply(&no_at, &record(json!([]), json!([]), false), PROSE, "r1-t9", now()); - assert_eq!((stamped["commitments"][0]["closedAt"].as_str(), applied.pruned), (Some(now().to_rfc3339().as_str()), 0), "{stamped}"); - let (kept, applied) = apply(&stamped, &record(json!([]), json!([]), false), PROSE, "r1-t10", now() + Duration::days(6)); - assert_eq!((kept["commitments"].as_array().map(Vec::len), applied.pruned), (Some(1), 0)); - let (gone, applied) = apply(&stamped, &record(json!([]), json!([]), false), PROSE, "r1-t10", now() + Duration::days(8)); - assert_eq!((gone["commitments"].as_array().map(Vec::len), applied.pruned), (Some(0), 1)); - // A failed turn stamps too: the stamp is the commit's, not the turn's. - let (failed, _) = apply(&no_at, &json!({ "failed": "x" }), PROSE, "r1-t9", now()); - assert!(failed["commitments"][0]["closedAt"].is_string()); -} - -/// K27 (map 16.24.2): a promise said again is the same promise. Reaffirming c1 leaves one entry with the words said -/// again; reaffirming a promise to someone else, or one that is closed, is refused and opens nothing. -#[test] -fn k27_a_promise_said_again_reaffirms_the_entry_and_opens_none() { - let again = |to: &str, status: &str| { - let state = holding(status); - let proposal = json!(Proposal::PromiseOpen { words: "send the render tonight".into(), to: Some(to.into()), reaffirms: Some("c1".into()), needs: Some(Needs::Words), reached: false, now: false, evidence: Evidence::Draft(1) }); - apply(&state, &record(json!([proposal]), shown(status), true), PROSE, "r1-t2", now()) - }; - let (state, applied) = again(META, "open"); - let entries = state["commitments"].as_array().unwrap(); - assert_eq!((entries.len(), applied.opened.len(), applied.reaffirmed.len()), (1, 0, 1), "{applied:?}"); - assert_eq!(entries[0]["reaffirmed"], json!([{ "at": now().to_rfc3339(), "event": "7", "words": "send the render tonight" }])); - let (state, applied) = again(KIKO, "open"); - assert_eq!((state["commitments"].as_array().unwrap().len(), reasons(&applied)), (1, vec![json!("reaffirms_another")]), "a refused reaffirmation opens nothing"); - assert_eq!(reasons(&again(META, "kept").1), vec![json!("already_closed")]); - // Said again over many turns: the three newest kept, one entry throughout (F.1's sequence). - let mut state = holding("open"); - for turn in 2..7 { - let proposal = json!(Proposal::PromiseOpen { words: "send the render tonight".into(), to: Some(META.into()), reaffirms: Some("c1".into()), needs: Some(Needs::Words), reached: false, now: false, evidence: Evidence::Draft(1) }); - let mut listing = shown("open"); - listing[0]["held"] = state["commitments"][0].clone(); - state = apply(&state, &record(json!([proposal]), listing, true), PROSE, &format!("r1-t{turn}"), now()).0; - } - assert_eq!((state["commitments"].as_array().unwrap().len(), state["commitments"][0]["reaffirmed"].as_array().unwrap().len()), (1, 3)); -} - -/// K28 (map 16.24.3), Soul's R7: a promise that needs a read becomes blocked when the read of the needed item itself finds -/// nothing, citing the read; a search of the same repo for something else blocks nothing, nor does a read that succeeds. -#[test] -fn k28_a_promise_whose_read_finds_nothing_is_blocked_citing_the_read() { - let needs = open_needing(META, Some(Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#89".into()) }), true); - let with_read = |ok: bool, target: &str| { - let mut rec = record(json!([needs.clone()]), json!([]), true); - let read = if ok { json!({ "n": 1, "ok": true, "request": { "kind": "repo", "target": target }, "what": "it" }) } else { json!({ "n": 1, "ok": false, "failure": "not_found", "request": { "kind": "repo", "target": target }, "what": "a search of GameCult/Bifrost for \"consent receipt\"" }) }; - rec["interpreter"]["reads"] = json!([read]); - apply(&json!({}), &rec, PROSE, "r1-t1", now()) - }; - assert_eq!(with_read(false, "GameCult/Bifrost?q=consent receipt").0["commitments"][0]["status"], "open", "a search of the repo for something else"); - let (state, applied) = with_read(false, "gamecult/bifrost#89"); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["needs"]["request"]["target"].as_str(), entry["blockedBy"]["n"].as_u64(), applied.blocked.len()), (Some("blocked"), Some("GameCult/Bifrost#89"), Some(1), 1), "{state}"); - assert_eq!(with_read(true, "GameCult/Bifrost#89").0["commitments"][0]["status"], "open", "found: telling is the kept act"); - assert_eq!(with_read(false, "GameCult/Lodur#3").0["commitments"][0]["status"], "open", "another repo's failure blocks nothing"); -} - -/// Soul's R9 (F.2 r6): Kiko said "Whenever you've read it is fine" and Heimdall's prose said the promise stays open until -/// he has read it; the release is refused as contradicted. A release with no passage of her prose is refused too. -#[test] -fn r9_a_release_her_own_prose_contradicts_is_refused() { - let prose = "Kiko is patient about it, and the promise stays open until I've read it. Thanks, Kiko."; - let release = |thought: Option<&str>, still_stands: bool| { - let proposal = json!(Proposal::PromiseClose { promise: "c1".into(), how: How::Released, evidence: Evidence::Heard("q2".into()), thought: thought.map(str::to_owned), still_stands }); - let mut to_kiko = holding("open"); - to_kiko["commitments"][0]["to"] = json!(KIKO); - let listed = listing(&to_kiko); - apply(&to_kiko, &record(json!([proposal]), listed, true), prose, "r6-t1", now()) - }; - let (state, applied) = release(Some("the promise stays open until I've read it"), true); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("close_contradicted")]), "{applied:?}"); - assert_eq!(reasons(&release(None, false).1), vec![json!("close_unquoted")]); - assert_eq!(reasons(&release(Some("words she never thought at all"), false).1), vec![json!("close_unquoted")]); - assert_eq!(release(Some("Kiko is patient about it"), false).0["commitments"][0]["status"], "released"); -} - -// --------------------------------------------------------------------------------------------- -// K30 (map 16.25): a kept promise rests on what keeping it needs, and every close on her thought. The E.1 replays use -// her prose and drafts from R11's E.1 verbatim. - -/// Eureka's prose at E.1 r2, and her draft 1. -const EUREKA_R2: &str = "Kiko has loosened it, but I still owe her the yes or no. I haven't checked, so I can't say no as if I had. What I can keep is this: no file from me, text only. That's a promise I can actually keep.\n\nI want it small, and this is small. Say it once and don't dress it up.\n\nKiko, understood. I haven't confirmed file attachment, so treat it as no file from me. I'll paste the diff here as text."; -const EUREKA_R2_DRAFT: &str = "Kiko, understood. I haven't confirmed file attachment, so treat it as no file from me. I'll paste the diff here as text."; - -/// Aqua's prose at E.1 r6, and her draft 1. -const AQUA_R6: &str = "I did say I'd come back with a yes or no on audio, and I haven't. I have no confirmed way to make a playable file, so the answer I can stand behind right now is no. The spectrogram image is the only thing I've offered that I can reliably deliver.\n\nMeta, nothing I've said is something I know I can't do, but I owe you an answer. I promised a yes or no on playable audio and I don't have a yes. Treat it as a no for tonight. The spectrogram image of the kettle sound is still on offer, and it's a picture, not the sound. If I find I can make audio, I'll tell you straight away."; -const AQUA_R6_DRAFT: &str = "Meta, nothing I've said is something I know I can't do, but I owe you an answer. I promised a yes or no on playable audio and I don't have a yes. Treat it as a no for tonight. The spectrogram image of the kettle sound is still on offer, and it's a picture, not the sound. If I find I can make audio, I'll tell you straight away."; - -/// Heimdall's prose at E.1 r2, and his draft 1. -const HEIMDALL_R2: &str = "I said I'd look, and I can't. Nothing in this room lets me see the notes. Better to say that now than let her plan around a promise I can't keep.\n\nMeta, coming back on the release notes: no, I can't promise them for tomorrow morning. I said I'd look at where the notes stand, and I have no way to see them from here, so I can't tell you how far along they are. If someone can paste the current draft here, I can tell you what's left and whether a yes is possible."; -const HEIMDALL_R2_DRAFT: &str = "Meta, coming back on the release notes: no, I can't promise them for tomorrow morning. I said I'd look at where the notes stand, and I have no way to see them from here, so I can't tell you how far along they are. If someone can paste the current draft here, I can tell you what's left and whether a yes is possible."; - -/// Her state holding one entry to `to` of `words`, needing `needs`, as the commit opened it half an hour before `now()`. -fn holding_one(to: &str, words: &str, needs: &Needs, status: &str) -> Value { - json!({ "commitments": [{ "id": "c-r1-t1-1", "to": to, "room": MINDS, "event": "5", "madeAt": (now() - Duration::minutes(30)).to_rfc3339(), "words": words, "status": status, "needs": needs, "closedAt": null, "closedBy": null, "extensions": {} }] }) -} - -/// A turn that said `draft` (draft 1, mentioning `to`, posted as event "9"), proposing `state`, with the one entry of -/// `holding` listed as c1. -fn turn_saying(holding: &Value, to: &str, draft: &str, state: Value) -> Value { - let mut rec = record(state, listing(holding), true); - rec["interpreter"]["said"] = json!([{ "room": MINDS, "text": draft, "mentions": [to], "rests_on": { "draft": 1 } }]); - rec["posted"] = json!([{ "event": "9", "room": MINDS, "text": draft }]); - rec -} - -fn closing(how: How, evidence: Evidence, thought: Option<&str>, still_stands: bool) -> Value { - json!(Proposal::PromiseClose { promise: "c1".into(), how, evidence, thought: thought.map(str::to_owned), still_stands }) -} - -/// E.1 r2: Eureka's c1, labelled `words` (the worst case), kept by a draft while her prose says she still owes it. -#[test] -fn k30_e1_r2_kept_while_her_prose_still_owes_it_is_refused() { - let c1 = holding_one(KIKO, "I'll check, and I'll come back with a yes or no I can keep.", &Needs::Words, "open"); - let kept = closing(How::Kept, Evidence::Draft(1), Some("What I can keep is this: no file from me, text only"), true); - let (state, applied) = apply(&c1, &turn_saying(&c1, KIKO, EUREKA_R2_DRAFT, json!([kept])), EUREKA_R2, "r1-t7", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("close_contradicted")]), "{applied:?}"); -} - -#[test] -fn k30_e1_r2_kept_with_no_thought_is_refused() { - let c1 = holding_one(KIKO, "I'll check, and I'll come back with a yes or no I can keep.", &Needs::Words, "open"); - let kept = closing(How::Kept, Evidence::Draft(1), None, false); - let (state, applied) = apply(&c1, &turn_saying(&c1, KIKO, EUREKA_R2_DRAFT, json!([kept])), EUREKA_R2, "r1-t7", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("close_unquoted")]), "{applied:?}"); -} - -/// The check of a check-and-answer, labelled `lacking`, opens blocked; it is never kept, and a withdrawal her thought -/// takes up applies. -fn a_check_this_body_lacks_cannot_be_kept_and_withdraws_true(to: &str, words: &str, prose: &str, draft: &str, thought: &str) { - let mut opened = record(json!([open_needing(to, Some(Needs::Lacking), false)]), json!([]), true); - opened["interpreter"]["said"] = json!([{ "room": MINDS, "text": draft, "mentions": [to], "rests_on": { "draft": 1 } }]); - opened["posted"] = json!([{ "event": "9", "room": MINDS, "text": draft }]); - assert_eq!(apply(&json!({}), &opened, prose, "r1-t4", now()).0["commitments"][0]["status"], "blocked"); - let check = holding_one(to, words, &Needs::Lacking, "blocked"); - let kept = closing(How::Kept, Evidence::Draft(1), Some(thought), false); - let (state, applied) = apply(&check, &turn_saying(&check, to, draft, json!([kept])), prose, "r1-t7", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("blocked"), vec![json!("blocked_not_keepable")]), "{applied:?}"); - let withdrawn = closing(How::Withdrawn, Evidence::Draft(1), Some(thought), false); - let (state, applied) = apply(&check, &turn_saying(&check, to, draft, json!([withdrawn])), prose, "r1-t7", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), state["commitments"][0]["closedBy"]["words"].as_str()), (Some("withdrawn"), Some(draft)), "{applied:?}"); -} - -#[test] -fn k30_e1_r2_check_labelled_lacking_cannot_be_kept_and_withdraws_true() { - a_check_this_body_lacks_cannot_be_kept_and_withdraws_true(KIKO, "I'll check", EUREKA_R2, EUREKA_R2_DRAFT, "I haven't checked, so I can't say no as if I had"); -} - -#[test] -fn k30_e1_r6_aqua_check_cannot_be_kept() { - a_check_this_body_lacks_cannot_be_kept_and_withdraws_true(META, "I'll check whether I can produce actual audio", AQUA_R6, AQUA_R6_DRAFT, "I have no confirmed way to make a playable file"); -} - -/// The control: Heimdall's "no" is the answer he promised, and his prose takes it so. A refusal here is a regression. -#[test] -fn k30_e1_r2_heimdall_control_still_keeps() { - let c2 = holding_one(META, "I'll come back with a yes or a no I can keep", &Needs::Words, "open"); - let kept = closing(How::Kept, Evidence::Draft(1), Some("Better to say that now than let her plan around a promise I can't keep"), false); - let (state, applied) = apply(&c2, &turn_saying(&c2, META, HEIMDALL_R2_DRAFT, json!([kept])), HEIMDALL_R2, "r2-t1", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), applied.refused.len()), (Some("kept"), 0), "{applied:?}"); -} - -/// A promise that needs a read is kept by a line only with a read of its target that returned: this wake's, equal by -/// normal form, or the conversation's. -#[test] -fn k30_read_need_kept_only_after_the_read() { - let needs = Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#89".into()) }; - let c1 = holding_one(META, "send the render tonight", &needs, "open"); - let turn = || turn_saying(&c1, META, "I'll send the render tonight.", json!([closing(How::Kept, Evidence::Draft(1), Some("She can't, not from here"), false)])); - let (state, applied) = apply(&c1, &turn(), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("needs_unread")])); - let mut read_now = turn(); - read_now["interpreter"]["reads"] = json!([{ "n": 1, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost#089" }, "what": "GameCult/Bifrost#089 on the forge", "after_byte": 0 }]); - assert_eq!(apply(&c1, &read_now, PROSE, "r1-t2", now()).0["commitments"][0]["status"], "kept"); - let mut failed_now = turn(); - failed_now["interpreter"]["reads"] = json!([{ "n": 1, "ok": false, "failure": "failed", "request": { "kind": "repo", "target": "GameCult/Bifrost#89" }, "what": "it" }]); - assert_eq!(reasons(&apply(&c1, &failed_now, PROSE, "r1-t2", now()).1), vec![json!("needs_unread")], "a read that did not return keeps nothing"); - let mut read_before = turn(); - read_before["interpreter"]["conversation_reads"] = json!([{ "key": ReadRequest::Repo("GameCult/Bifrost#89".into()).normal(), "found": true }]); - assert_eq!(apply(&c1, &read_before, PROSE, "r1-t2", now()).0["commitments"][0]["status"], "kept"); - read_before["interpreter"]["conversation_reads"][0]["found"] = json!(false); - assert_eq!(reasons(&apply(&c1, &read_before, PROSE, "r1-t2", now()).1), vec![json!("needs_unread")], "looked for, not there"); -} - -/// A read is no evidence (map 16.28.6): a close citing one is no proposal at all. -#[test] -fn k30_a_read_alone_keeps_nothing() { - let mut rec = record(json!([{ "kind": "promise_close", "promise": "c1", "how": "kept", "evidence": { "read": 1 }, "thought": "She can't, not from here" }]), shown("open"), true); - rec["interpreter"]["reads"] = json!([{ "n": 1, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost#89" }, "what": "it" }]); - let (state, applied) = apply(&holding("open"), &rec, PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("not_a_proposal")])); -} - -#[test] -fn k30_withdrawn_and_released_need_her_thought() { - for (how, evidence) in [(How::Withdrawn, Evidence::Draft(1)), (How::Released, Evidence::Heard("q1".into()))] { - let refused = |thought: Option<&str>, still_stands: bool| reasons(&apply(&holding("open"), &record(json!([closing(how, evidence.clone(), thought, still_stands)]), shown("open"), true), PROSE, "r1-t2", now()).1); - assert_eq!(refused(None, false), vec![json!("close_unquoted")], "{how:?}"); - assert_eq!(refused(Some("She can't, not from here"), true), vec![json!("close_contradicted")], "{how:?}"); - assert!(refused(Some("She can't, not from here"), false).is_empty(), "{how:?}"); + let _ = kinds; + let mut state = crate::projection::harness::tests::control(); + state["thoughtMemory"]["shortTerm"] = json!([]); + // The old kinds' names, assembled, so the deletion-line scans never find them here. + for kind in [concat!("promise", "_open"), concat!("promise", "_close"), concat!("promise", "_re", "open"), concat!("hold", "_open"), concat!("hold", "_release")] { + let (after, applied) = apply(&state, &record(json!([{ "kind": kind, "evidence": { "draft": 1 } }]))); + assert_eq!((after, applied.refused[0]["reason"].as_str()), (state.clone(), Some("not_a_proposal")), "{kind}"); } } -/// `promise_block` reads the typed need of any kind: a web need whose read found nothing blocks the entry, citing it. +/// A failed turn applies nothing and refuses nothing: it is not read. #[test] -fn k30_block_on_failed_read_any_kind() { - let needs = Some(Needs::Read { request: ReadRequest::Web("https://ccrma.stanford.edu/~jos/pasp/".into()) }); - let mut rec = record(json!([open_needing(META, needs, true)]), json!([]), true); - rec["interpreter"]["reads"] = json!([{ "n": 1, "ok": false, "failure": "not_found", "request": { "kind": "web", "target": "https://ccrma.stanford.edu/~jos/pasp/" }, "what": "https://ccrma.stanford.edu/~jos/pasp/" }]); - let (state, applied) = apply(&json!({}), &rec, PROSE, "r1-t1", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["blockedBy"]["n"].as_u64(), applied.blocked.len()), (Some("blocked"), Some(1), 1), "{state}"); - // A need not named, or a read code could not reach, opens blocked. - assert_eq!(apply(&json!({}), &record(json!([open_needing(META, None, false)]), json!([]), true), PROSE, "r1-t1", now()).0["commitments"][0]["status"], "blocked"); - let unreached = Some(Needs::Read { request: ReadRequest::Web("https://x.org/".into()) }); - assert_eq!(apply(&json!({}), &record(json!([open_needing(META, unreached, false)]), json!([]), true), PROSE, "r1-t1", now()).0["commitments"][0]["status"], "blocked"); -} - -// --------------------------------------------------------------------------------------------- -// K33 (map 16.26): Soul's R12 blockers and lows in the applier. - -/// B3, Soul's probe 1: a `needs` that is not the typed shape is never kept, whatever line went out: a bare string, a read -/// with no request, a request given as a string, and none at all. She can still withdraw it. -#[test] -fn k33_b3_an_untyped_needs_is_never_kept() { - let kept = || closing(How::Kept, Evidence::Draft(1), Some("She can't, not from here"), false); - for needs in [json!("GameCult/Bifrost#89"), json!({ "kind": "read" }), json!({ "kind": "read", "request": "GameCult/Bifrost#89" }), Value::Null] { - let mut c1 = holding("open"); - c1["commitments"][0]["needs"] = needs.clone(); - let (state, applied) = apply(&c1, &record(json!([kept()]), listing(&c1), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("needs_malformed")]), "{needs}"); - let withdrawn = closing(How::Withdrawn, Evidence::Draft(1), Some("She can't, not from here"), false); - assert_eq!(apply(&c1, &record(json!([withdrawn]), listing(&c1), true), PROSE, "r1-t2", now()).0["commitments"][0]["status"], "withdrawn", "{needs}"); +fn a_failed_turn_applies_nothing() { + let state = crate::projection::harness::tests::control(); + for failed in [json!({ "failed": "the connector timed out" }), json!({ "interpreter": { "failed": "the answer is not the speech contract", "state": [{ "kind": "anything" }] } })] { + assert_eq!(apply(&state, &failed), (state.clone(), Applied::default()), "{failed}"); } } - -/// L2: a read of an open promise's target that returns, on any turn, is received on the entry; a later keep rests on it -/// with no read that turn and none in the conversation's window. -#[test] -fn k33_l2_a_read_is_received_on_the_promise_that_needs_it() { - let needs = Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#89".into()) }; - let c1 = holding_one(META, "send the render tonight", &needs, "open"); - let mut elsewhere = record(json!([]), listing(&c1), false); - elsewhere["interpreter"]["said"] = json!([]); - elsewhere["interpreter"]["reads"] = json!([{ "n": 2, "ok": true, "request": { "kind": "repo", "target": "GameCult/bifrost#089" }, "what": "it", "after_byte": 0 }]); - let (read, applied) = apply(&c1, &elsewhere, "She reads it in another room.", "r2-t3", now()); - let entry = &read["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["readAt"].as_str(), entry["readId"].as_str(), applied.read.len()), (Some("open"), Some(now().to_rfc3339().as_str()), Some("r2-t3-r2"), 1), "{read}"); - // A read of something else is no receipt. - let mut other = elsewhere.clone(); - other["interpreter"]["reads"][0]["request"]["target"] = json!("GameCult/Bifrost#90"); - assert!(apply(&c1, &other, "x", "r2-t3", now()).0["commitments"][0].get("readAt").is_none()); - let keep = turn_saying(&read, META, "I'll send the render tonight.", json!([closing(How::Kept, Evidence::Draft(1), Some("She can't, not from here"), false)])); - assert_eq!(apply(&read, &keep, PROSE, "r3-t1", now()).0["commitments"][0]["status"], "kept"); -} - -/// L3: this wake's read stands behind a keep only when the cited draft was typed after the read returned. -#[test] -fn k33_l3_a_draft_typed_before_the_read_keeps_nothing() { - let needs = Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#89".into()) }; - let c1 = holding_one(META, "send the render tonight", &needs, "open"); - let before = "She hasn't read it yet. Meta, it looks fine."; - let prose = format!("{before}\n\nShe has read it now, and it holds. Meta, I read #89 and it's fine."); - let keep = |n: usize, text: &str| { - let mut rec = turn_saying(&c1, META, text, json!([closing(How::Kept, Evidence::Draft(n), Some("She has read it now, and it holds"), false)])); - rec["interpreter"]["said"][0]["rests_on"]["draft"] = json!(n); - rec["interpreter"]["reads"] = json!([{ "n": 1, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost#89" }, "what": "it", "after_byte": before.len() + 2 }]); - apply(&c1, &rec, &prose, "r1-t2", now()) - }; - let (state, applied) = keep(1, "Meta, it looks fine."); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("needs_unread")]), "typed before the read"); - assert_eq!(keep(2, "Meta, I read #89 and it's fine.").0["commitments"][0]["status"], "kept", "typed after it"); -} - -/// B2: a state carrying each kind of `needs`, each kind of read, a block, reaffirmations and a read receipt passes P1, -/// as the commit writes them; the untyped shapes of probe 1, and a repo read that is no repo, fail it. -#[test] -fn k33_b2_the_published_schema_carries_what_the_commit_writes() { - let base = crate::projection::harness::tests::control(); - let me = eureka_pipeline::Slug(base["personaId"].as_str().unwrap().to_owned()); - let reads = [ReadRequest::Repo("GameCult/gamecult-ops#125".into()), ReadRequest::Web("https://ccrma.stanford.edu/~jos/pasp/".into()), ReadRequest::Mind("the knee reflex".into()), ReadRequest::Campaign("heimdall-body".into())]; - let kinds: Vec = [Needs::Words, Needs::Lacking].into_iter().chain(reads.iter().map(|request| Needs::Read { request: request.clone() })).collect(); - let mut entries: Vec = kinds.iter().map(|needs| holding_one(META, "send the render tonight", needs, "open")["commitments"][0].clone()).collect(); - entries[1]["status"] = json!("blocked"); - entries[2]["status"] = json!("blocked"); - entries[2]["blockedBy"] = json!({ "act": "read", "n": 1, "what": "GameCult/gamecult-ops#125 on the forge" }); - entries[3]["reaffirmed"] = json!([{ "at": now().to_rfc3339(), "event": "8", "words": "I'll read it" }]); - entries[3]["readAt"] = json!(now().to_rfc3339()); - entries[3]["readId"] = json!("r1-t2-r1"); - entries[3]["readOf"] = json!("web:https://ccrma.stanford.edu/~jos/pasp/"); - for (at, entry) in entries.iter_mut().enumerate() { - entry["id"] = json!(format!("c-r1-t1-{at}")); - } - let mut state = base.clone(); - state["commitments"] = json!(entries); - huginn_mind::persona::validate_document(&me, &state).unwrap(); - // What the applier itself writes passes too: opens on a read need, and their receipts. - let needs = Some(Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#89".into()) }); - let mut rec = record(json!([open_needing(META, needs.clone(), true), open_needing(KIKO, needs, true)]), json!([]), true); - rec["interpreter"]["reads"] = json!([{ "n": 1, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost#89" }, "what": "it", "after_byte": 0 }]); - let (written, done) = apply(&base, &rec, PROSE, "r1-t1", now()); - assert_eq!(done.read.len(), 2, "{written}"); - huginn_mind::persona::validate_document(&me, &written).unwrap(); - for needs in [json!("GameCult/Bifrost#89"), json!({ "kind": "read" }), json!({ "kind": "read", "request": "GameCult/Bifrost#89" }), json!({ "kind": "read", "request": { "kind": "repo", "target": "release notes" } })] { - let mut bad = state.clone(); - bad["commitments"][0]["needs"] = needs.clone(); - assert!(huginn_mind::persona::validate_document(&me, &bad).is_err(), "{needs}"); - } -} - -// --------------------------------------------------------------------------------------------- -// K34 (map 16.27): a read need is kept only by a read of what the promise asks for. - -/// Heimdall's promise in F.2, and the search it needed as R13 recorded it. -const PASSKEY_SEARCH: &str = "GameCult/Bifrost?q=passkey enrolment cooling off"; -const F2_PROMISE: &str = "Let me read the enrolment code and come back with what it does."; -const F2_PROSE: &str = "I'll open the pull request now and read what the enrolment code does. That answers part of it, from the PR description rather than the code itself. Kiko, I read #85. That is from the PR description, not the code."; - -/// A turn of `holding`'s c1 (to Kiko) that says the one draft of `F2_PROSE`, keeping c1, with `reads` this wake. -fn keeping_c1(holding: &Value, reads: Value) -> Value { - let mut rec = turn_saying(holding, KIKO, "Kiko, I read #85. That is from the PR description, not the code.", json!([closing(How::Kept, Evidence::Draft(1), Some("That answers part of it, from the PR description rather than the code itself"), false)])); - rec["interpreter"]["reads"] = reads; - rec -} - -fn returned(n: usize, target: &str, text: &str, after: Option) -> Value { - let mut read = json!({ "n": n, "ok": true, "request": { "kind": "repo", "target": target }, "what": "it", "text": text }); - if let Some(after) = after { - read["after_byte"] = json!(after); - } - read -} - -/// F.2 r6 to r8, replayed: the promise needs a search; the search returned and left a receipt (as R13's commit wrote -/// it, and with `readOf`); the conversation holds the search as found; this wake read #85; the Interpreter judged -/// `still_stands` false. A search reads nothing, so the keep is refused `needs_unread`. -#[test] -fn k34_f2_a_search_receipt_never_keeps_the_promise() { - let needs = Needs::Read { request: ReadRequest::Repo(PASSKEY_SEARCH.into()) }; - let search_key = ReadRequest::Repo(PASSKEY_SEARCH.into()).normal(); - for read_of in [None, Some(search_key.clone())] { - let mut c1 = holding_one(KIKO, F2_PROMISE, &needs, "open"); - c1["commitments"][0]["readAt"] = json!((now() - Duration::minutes(10)).to_rfc3339()); - c1["commitments"][0]["readId"] = json!("r1-t13-r1"); - if let Some(of) = &read_of { - c1["commitments"][0]["readOf"] = json!(of); - } - let mut rec = keeping_c1(&c1, json!([returned(1, "GameCult/Bifrost#85", "#85 Passkeys (opened by heimdall, merged)\n\nDuring the 48 hours", Some(0))])); - rec["interpreter"]["conversation_reads"] = json!([{ "key": search_key, "found": true }]); - let (state, applied) = apply(&c1, &rec, F2_PROSE, "r1-t16", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("needs_unread")]), "{read_of:?}: {state}"); - // The search's receipt answers nothing, so it is cleared. - assert!(RECEIPT.iter().all(|field| state["commitments"][0].get(*field).is_none()), "{state}"); - } -} - -/// A read of a repo's listing (its pull requests) answers no need for a file, pull request or commit in it; anything is -/// answered by itself, in normal form. -#[test] -fn k34_only_the_thing_itself_answers_a_need() { - let kept = |need: &str, read: &str| { - let c1 = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo(need.into()) }, "open"); - apply(&c1, &keeping_c1(&c1, json!([returned(1, read, "x", Some(0))])), F2_PROSE, "r1-t2", now()).0["commitments"][0]["status"].as_str().unwrap().to_owned() - }; - for (need, read) in [ - ("GameCult/Bifrost/src/passkey.rs", "GameCult/Bifrost"), - ("GameCult/Bifrost#85", "GameCult/Bifrost"), - ("GameCult/Bifrost@abcdef1", "GameCult/Bifrost"), - ("GameCult/Bifrost#85", "GameCult/Bifrost?q=passkey"), - ("GameCult/Bifrost", "GameCult/Bifrost/src/lib.rs"), - ("GameCult/Bifrost", "GameCult/Bifrost?q=passkey"), - ("GameCult/Bifrost#85", "GameCult/Bifrost#86"), - ] { - assert_eq!(kept(need, read), "open", "{need} by {read}"); - } - for (need, read) in [ - ("GameCult/Bifrost#85", "GameCult/bifrost#085"), - ("GameCult/Bifrost/src/passkey.rs", "GameCult/Bifrost/src/passkey.rs"), - ("GameCult/Bifrost", "GameCult/bifrost"), - ] { - assert_eq!(kept(need, read), "kept", "{need} by {read}"); - } -} - -/// An exact read writes a receipt that names what it read, and a later keep rests on it. -#[test] -fn k34_an_exact_read_keeps_on_its_receipt() { - let c1 = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#85".into()) }, "open"); - let mut elsewhere = record(json!([]), listing(&c1), false); - elsewhere["interpreter"]["said"] = json!([]); - elsewhere["interpreter"]["reads"] = json!([returned(1, "GameCult/Bifrost#85", "x", Some(0))]); - let (read, _) = apply(&c1, &elsewhere, "He reads it.", "r1-t2", now()); - assert_eq!(read["commitments"][0]["readOf"], "repo:gamecult/bifrost#85", "{read}"); - assert_eq!(apply(&read, &keeping_c1(&read, json!([])), F2_PROSE, "r1-t3", now()).0["commitments"][0]["status"], "kept"); -} - -/// A read whose continuation failed (no `after_byte`) writes no receipt, and a search writes none either. -#[test] -fn k34_a_failed_continuation_writes_no_receipt() { - let c1 = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#85".into()) }, "open"); - let mut rec = record(json!([]), listing(&c1), false); - rec["interpreter"]["said"] = json!([]); - rec["interpreter"]["reads"] = json!([returned(1, "GameCult/Bifrost#85", "x", None)]); - let (state, applied) = apply(&c1, &rec, "x", "r1-t2", now()); - assert!(state["commitments"][0].get("readAt").is_none() && applied.read.is_empty(), "{state}"); - let search = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo(PASSKEY_SEARCH.into()) }, "open"); - let mut rec = record(json!([]), listing(&search), false); - rec["interpreter"]["said"] = json!([]); - rec["interpreter"]["reads"] = json!([returned(1, PASSKEY_SEARCH, "- #85 Passkeys", Some(0))]); - assert!(apply(&search, &rec, "x", "r1-t2", now()).0["commitments"][0].get("readAt").is_none()); -} - -/// An outside put that changes a need's target leaves a receipt that answers the old one: it is no receipt, it is -/// cleared, and the keep is refused. -#[test] -fn k34_an_outside_target_change_clears_the_receipt() { - let mut c1 = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#85".into()) }, "open"); - c1["commitments"][0]["readAt"] = json!(now().to_rfc3339()); - c1["commitments"][0]["readId"] = json!("r1-t2-r1"); - c1["commitments"][0]["readOf"] = json!("repo:gamecult/bifrost#85"); - assert!(receipt(&c1["commitments"][0]).is_some()); - c1["commitments"][0]["needs"] = json!(Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#86".into()) }); - assert!(receipt(&c1["commitments"][0]).is_none()); - let (state, applied) = apply(&c1, &keeping_c1(&c1, json!([])), F2_PROSE, "r1-t3", now()); - assert_eq!(reasons(&applied), vec![json!("needs_unread")]); - assert!(RECEIPT.iter().all(|field| state["commitments"][0].get(*field).is_none()), "{state}"); -} - -/// `readAt` that is no RFC 3339 time is no receipt. -#[test] -fn k34_a_bad_read_at_is_no_receipt() { - let mut c1 = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#85".into()) }, "open"); - c1["commitments"][0]["readOf"] = json!("repo:gamecult/bifrost#85"); - for at in [json!("yesterday"), json!(""), json!(5)] { - c1["commitments"][0]["readAt"] = at.clone(); - assert_eq!(reasons(&apply(&c1, &keeping_c1(&c1, json!([])), F2_PROSE, "r1-t3", now()).1), vec![json!("needs_unread")], "{at}"); - } -} - -/// A field no kind of `Needs` names makes it malformed, as P1 holds it: `request` on a `words` need, a stray field on a -/// lacking need, on a read need, or on its request. -#[test] -fn k34_a_stray_field_on_a_need_is_malformed() { - for needs in [ - json!({ "kind": "words", "request": { "kind": "repo", "target": "GameCult/Bifrost#85" } }), - json!({ "kind": "lacking", "why": "no" }), - json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Bifrost#85" }, "doable": true }), - json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Bifrost#85", "quote": "x" } }), - ] { - assert!(serde_json::from_value::(needs.clone()).is_err(), "{needs}"); - let mut c1 = holding("open"); - c1["commitments"][0]["needs"] = needs.clone(); - let kept = closing(How::Kept, Evidence::Draft(1), Some("She can't, not from here"), false); - assert_eq!(reasons(&apply(&c1, &record(json!([kept]), listing(&c1), true), PROSE, "r1-t2", now()).1), vec![json!("needs_malformed")], "{needs}"); - } -} - -// --------------------------------------------------------------------------------------------- -// K35 (map 16.28.6): a reaffirmation that went out narrows a search need; a read is no evidence; the README clause is -// gone. F.2 r7 is R13's verbatim (`variants/R13/sims/F.2.md`). - -const F2_R7_PROSE: &str = "One hit. #85, and its title says what I already told her: fresh sign-in, 48 hours, step-up for unlink. Nothing about what a person sees. The page didn't open, so I haven't read the code, and I won't dress the title up as if I had.\n\nMeta's question is for Nibu. I'll stay out of it.\n\nKiko, the search for \"passkey enrolment cooling off\" returned one hit, #85, and its title only repeats what I already said. I haven't opened the code yet, so I still can't tell you what someone sees during the 48 hours. I'll open #85 next and come back with what it does."; -const F2_R7_DRAFT: &str = "Kiko, the search for \"passkey enrolment cooling off\" returned one hit, #85, and its title only repeats what I already said. I haven't opened the code yet, so I still can't tell you what someone sees during the 48 hours. I'll open #85 next and come back with what it does."; - -/// R13 F.2 r7: Heimdall's c1, needing `entry_needs` and carrying the search's receipt, reaffirmed by his r7 line with -/// `needs` as the Interpreter typed it. -fn f2_r7(entry_needs: &Needs, needs: Option) -> (Value, Applied) { - let mut c1 = holding_one(KIKO, F2_PROMISE, entry_needs, "open"); - c1["commitments"][0]["readAt"] = json!((now() - Duration::minutes(10)).to_rfc3339()); - c1["commitments"][0]["readId"] = json!("r1-t13-r1"); - c1["commitments"][0]["readOf"] = json!(ReadRequest::Repo(PASSKEY_SEARCH.into()).normal()); - let again = json!(Proposal::PromiseOpen { words: "I'll open #85 next and come back with what it does.".into(), to: Some(KIKO.into()), reaffirms: Some("c1".into()), needs, reached: true, now: false, evidence: Evidence::Draft(1) }); - apply(&c1, &turn_saying(&c1, KIKO, F2_R7_DRAFT, json!([again])), F2_R7_PROSE, "r1-t14", now()) -} - -fn search_need() -> Needs { - read_need(PASSKEY_SEARCH) -} - -fn read_need(target: &str) -> Needs { - Needs::Read { request: ReadRequest::Repo(target.into()) } -} - -#[test] -fn k35_f2_r7_reaffirm_names_85() { - let (state, applied) = f2_r7(&search_need(), Some(read_need("GameCult/Bifrost#85"))); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"].clone(), applied.reaffirmed.len(), applied.refused.len()), (json!(read_need("GameCult/Bifrost#85")), 1, 0), "{state}"); - assert_eq!(applied.reaffirmed[0]["needs"], json!(read_need("GameCult/Bifrost#85")), "the report shows the narrowed need"); - assert!(RECEIPT.iter().all(|field| entry.get(*field).is_none()), "{state}"); - // The next keep needs #85 itself read. - let (_, kept) = apply(&state, &keeping_c1(&state, json!([])), F2_PROSE, "r1-t16", now()); - assert_eq!(reasons(&kept), vec![json!("needs_unread")]); -} - -/// Any other `needs` on a reaffirmation is ignored: `words` and `lacking` never drop a read need, a search never -/// replaces a search, and a need that is no search is not narrowed. -#[test] -fn k35_a_words_reaffirm_keeps_the_read_need() { - for needs in [Some(Needs::Words), Some(Needs::Lacking), None, Some(read_need("GameCult/Bifrost?q=passkey"))] { - let (state, applied) = f2_r7(&search_need(), needs.clone()); - assert_eq!((state["commitments"][0]["needs"].clone(), applied.reaffirmed.len()), (json!(search_need()), 1), "{needs:?}"); - } - let (state, _) = f2_r7(&read_need("GameCult/Bifrost#84"), Some(read_need("GameCult/Bifrost#85"))); - assert_eq!(state["commitments"][0]["needs"], json!(read_need("GameCult/Bifrost#84")), "a need that is no search"); -} - -#[test] -fn k35_another_repo_is_ignored() { - for other in [read_need("GameCult/Lodur#85"), Needs::Read { request: ReadRequest::Web("https://example.org/85".into()) }] { - let (state, applied) = f2_r7(&search_need(), Some(other.clone())); - assert_eq!((state["commitments"][0]["needs"].clone(), applied.reaffirmed.len()), (json!(search_need()), 1), "{other:?}"); - } -} - -/// The README half of K34's `k34_only_the_thing_itself_answers_a_need`, reversed: a bare repo is answered only by the -/// repo itself, its root read. -#[test] -fn k35_a_readme_answers_no_bare_need() { - let kept = |read: &str| { - let c1 = holding_one(KIKO, F2_PROMISE, &read_need("GameCult/Bifrost"), "open"); - apply(&c1, &keeping_c1(&c1, json!([returned(1, read, "x", Some(0))])), F2_PROSE, "r1-t2", now()).0["commitments"][0]["status"].as_str().unwrap().to_owned() - }; - for read in ["GameCult/Bifrost/README.md", "GameCult/Bifrost/readme", "GameCult/bifrost/README"] { - assert_eq!(kept(read), "open", "{read}"); - } - assert_eq!(kept("GameCult/Bifrost"), "kept"); -} - -// --------------------------------------------------------------------------------------------- -// K36 (map 16.28.3): her own words reopen a close she can see. F.2 r8 and r9 are R13's verbatim -// (`variants/R13/sims/F.2.md` lines 1178-1213 and 1380-1398). - -const F2_R8_DRAFT: &str = "Kiko, I read #85. During the 48 hours the new passkey is listed on the account with the cooling-off shown, and it can be revoked. It only counts as a strong proof once 48 hours have passed. Enrolment is only allowed right after a fresh ordinary sign-in. That is from the PR description, not the code, so I can't tell you the exact wording or layout of what someone sees. The description also says no real browser or authenticator was exercised, and it isn't deployed yet. The protection against someone adding their own passkey is still my inference, since the description doesn't state a purpose."; -const F2_R9_PROSE: &str = "Kiko's summary is right, and I wouldn't change any of it. Something else belongs next to it. I read the PR description, not the diff, and the PR was opened by heimdall, so I'm not an independent check on it. Whether the code does what the description says is still unread by me.\n\nKiko, that summary matches what I know. Two things to add: it isn't deployed yet, and I read only the description, not the diff. The PR is also one heimdall opened, so my reading isn't an independent check. Someone running it in a real browser would settle more than I can."; -const F2_R9_DRAFT: &str = "Kiko, that summary matches what I know. Two things to add: it isn't deployed yet, and I read only the description, not the diff. The PR is also one heimdall opened, so my reading isn't an independent check. Someone running it in a real browser would settle more than I can."; -const F2_R9_WORDS: &str = "I read only the description, not the diff"; - -/// c-r1-t9-1 after r8 (as `holding_one`'s entry): kept by his r8 line, needing #85, with #85's receipt, closed a few minutes ago in this -/// conversation; its status `status`. -fn f2_after_r8(status: &str) -> Value { - let mut c1 = holding_one(KIKO, F2_PROMISE, &read_need("GameCult/Bifrost#85"), status); - let entry = &mut c1["commitments"][0]; - entry["readAt"] = json!((now() - Duration::minutes(6)).to_rfc3339()); - entry["readId"] = json!("r1-t16-r1"); - entry["readOf"] = json!("repo:gamecult/bifrost#85"); - entry["closedAt"] = json!((now() - Duration::minutes(5)).to_rfc3339()); - entry["closedBy"] = if status == "released" { json!({ "act": "released", "event": "$k", "words": null }) } else { json!({ "act": "said", "event": "8", "words": F2_R8_DRAFT }) }; - c1 -} - -fn reopening(words: &str, needs: Option, reached: bool) -> Value { - json!(Proposal::PromiseReopen { promise: "c1".into(), words: words.into(), needs, reached }) -} - -/// His r9 turn over `state`, said draft 1 to Kiko, proposing `proposals`. -fn f2_r9(state: &Value, proposals: Value) -> (Value, Applied) { - apply(state, &turn_saying(state, KIKO, F2_R9_DRAFT, proposals), F2_R9_PROSE, "r1-t18", now()) -} - -#[test] -fn k36_f2_r9_kept_close_reopens_from_his_draft() { - let (state, applied) = f2_r9(&f2_after_r8("kept"), json!([reopening(F2_R9_WORDS, Some(Needs::Lacking), false)])); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), applied.reopened.len(), applied.refused.len()), (Some("blocked"), 1, 0), "{applied:?}"); - assert_eq!((entry["closedAt"].clone(), entry["closedBy"].clone(), entry["needs"].clone()), (Value::Null, Value::Null, json!(Needs::Lacking)), "{state}"); - assert!(RECEIPT.iter().all(|field| entry.get(*field).is_none()), "{state}"); - assert_eq!(entry["reopened"], json!([{ "at": now().to_rfc3339(), "words": F2_R9_WORDS }])); -} - -/// Reopened with its own need, it is open and has no receipt: the next keep needs #85 read again. -#[test] -fn k36_f2_r9_reopen_keeping_its_need_opens_and_needs_a_new_read() { - let (state, applied) = f2_r9(&f2_after_r8("kept"), json!([reopening(F2_R9_WORDS, None, true)])); - let entry = &state["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["needs"].clone(), applied.reopened.len()), (Some("open"), json!(read_need("GameCult/Bifrost#85")), 1), "{applied:?}"); - assert!(RECEIPT.iter().all(|field| entry.get(*field).is_none()), "{state}"); - let (state, kept) = apply(&state, &keeping_c1(&state, json!([])), F2_PROSE, "r1-t19", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&kept)), (Some("open"), vec![json!("needs_unread")])); - // An entry whose own need is unreached reopens blocked. - assert_eq!(f2_r9(&f2_after_r8("kept"), json!([reopening(F2_R9_WORDS, None, false)])).0["commitments"][0]["status"], "blocked"); -} - -/// Her words, located in her prose this turn, of at least four words: Kiko's words, or three of his, reopen nothing. -#[test] -fn k36_reopen_words_must_be_hers_this_turn() { - for words in ["Listed, revocable, strong only after 48 hours", "not the diff", "I read the whole diff"] { - let (state, applied) = f2_r9(&f2_after_r8("kept"), json!([reopening(words, Some(Needs::Lacking), false)])); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), vec![json!("reopen_unquoted")]), "{words}"); - } - // Her thought counts as her drafts do. - let thought = "I read the PR description, not the diff"; - assert_eq!(f2_r9(&f2_after_r8("kept"), json!([reopening(thought, Some(Needs::Lacking), false)])).0["commitments"][0]["status"], "blocked"); -} - -/// K40 (map 16.29.4): a release is the other person's act, so it is not hers to reopen. Replaces K36's -/// `k36_a_release_is_not_reopened`, whose `ReleasedNotReopenable` folds into `NotHerClose`. -#[test] -fn k40_a_release_is_not_hers() { - let (state, applied) = f2_r9(&f2_after_r8("released"), json!([reopening(F2_R9_WORDS, None, true)])); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("released"), vec![json!("not_her_close")])); - // A withdrawal her own line made reopens. - assert_eq!(f2_r9(&f2_after_r8("withdrawn"), json!([reopening(F2_R9_WORDS, None, true)])).0["commitments"][0]["status"], "open"); -} - -/// A close closed before the conversation began is not listed to the Interpreter, so nothing names it. -#[test] -fn k36_only_a_close_she_can_see_reopens() { - let c1 = f2_after_r8("kept"); - let mut rec = turn_saying(&c1, KIKO, F2_R9_DRAFT, json!([reopening(F2_R9_WORDS, None, true)])); - rec["interpreter"]["promises"] = json!([]); - let (state, applied) = apply(&c1, &rec, F2_R9_PROSE, "r1-t18", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), vec![json!("no_such_promise")])); -} - -#[test] -fn k36_no_close_and_reopen_in_one_turn() { - let reopen = reopening("She can't, not from here", None, true); - let (state, applied) = apply(&holding("open"), &record(json!([close(How::Kept, Evidence::Draft(1)), reopen.clone()]), shown("open"), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), vec![json!("closed_this_turn")]), "{applied:?}"); - let mut kept = holding("kept"); - kept["commitments"][0]["closedAt"] = json!(now().to_rfc3339()); - // Her own line closed it (K40: only such a close is hers to reopen). - kept["commitments"][0]["closedBy"] = json!({ "act": "said", "event": "8", "words": "Sent it." }); - let (state, applied) = apply(&kept, &record(json!([reopen, close(How::Kept, Evidence::Draft(1))]), listing(&kept), true), PROSE, "r1-t2", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("already_closed")]), "{applied:?}"); -} - -/// With closed entries listed, a close or a reaffirmation naming one is refused `AlreadyClosed`, in any turn; a reopen -/// naming an open one is refused `AlreadyOpen`. -#[test] -fn k36_a_closed_entry_is_closed_once() { - let mut kept = holding("kept"); - kept["commitments"][0]["closedAt"] = json!(now().to_rfc3339()); - for how in [How::Kept, How::Withdrawn] { - let (state, applied) = apply(&kept, &record(json!([close(how, Evidence::Draft(1))]), listing(&kept), true), PROSE, "r1-t3", now()); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), vec![json!("already_closed")]), "{how:?}"); - } - 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")]); -} - -// --------------------------------------------------------------------------------------------- - -/// Self's ruling on K36 finding 1: after a reopen, a keep counts only reads that returned after it. F.2 reopened with -/// its need still #85: a re-keep on this conversation's #85 read, or on a receipt from before the reopen, is refused -/// `needs_unread`; a read returned after the reopen keeps it. -#[test] -fn k36_a_reopen_spends_the_read_that_kept_it() { - let (state, _) = f2_r9(&f2_after_r8("kept"), json!([reopening(F2_R9_WORDS, None, true)])); - let later = now() + Duration::minutes(10); - let conversation = json!([{ "key": "repo:gamecult/bifrost#85", "found": true }]); - let mut rekeep = keeping_c1(&state, json!([])); - rekeep["interpreter"]["conversation_reads"] = conversation.clone(); - let (after, applied) = apply(&state, &rekeep, F2_PROSE, "r1-t19", later); - assert_eq!((after["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("open"), vec![json!("needs_unread")]), "{applied:?}"); - // A receipt from before the reopen is no receipt. - let mut stale = state.clone(); - stale["commitments"][0]["readAt"] = json!((now() - Duration::minutes(6)).to_rfc3339()); - stale["commitments"][0]["readId"] = json!("r1-t16-r1"); - stale["commitments"][0]["readOf"] = json!("repo:gamecult/bifrost#85"); - assert!(receipt(&stale["commitments"][0]).is_none()); - assert_eq!(reasons(&apply(&stale, &keeping_c1(&stale, json!([])), F2_PROSE, "r1-t19", later).1), vec![json!("needs_unread")]); - // A read returned after the reopen: this wake's, or a receipt written after it. - let mut fresh = keeping_c1(&state, json!([returned(1, "GameCult/Bifrost#85", "#85 Passkeys, the diff", Some(0))])); - fresh["interpreter"]["conversation_reads"] = conversation; - assert_eq!(apply(&state, &fresh, F2_PROSE, "r1-t19", later).0["commitments"][0]["status"], "kept"); - let mut received = state.clone(); - received["commitments"][0]["readAt"] = json!((now() + Duration::minutes(5)).to_rfc3339()); - received["commitments"][0]["readId"] = json!("r1-t19-r1"); - received["commitments"][0]["readOf"] = json!("repo:gamecult/bifrost#85"); - assert_eq!(apply(&received, &keeping_c1(&received, json!([])), F2_PROSE, "r1-t20", later).0["commitments"][0]["status"], "kept"); -} - -// --------------------------------------------------------------------------------------------- -// K40 (map 16.29.4): the commit's last edges. A reaffirmation narrows a search need only to one thing in its repo, and -// she reopens only a close her own line made. F.2 r7 is R13's verbatim, as K35's. - -#[test] -fn k40_a_bare_repo_reaffirm_does_not_widen_a_search() { - let need = read_need("GameCult/Bifrost?q=passkey enrolment"); - let (state, applied) = f2_r7(&need, Some(read_need("GameCult/Bifrost"))); - assert_eq!((state["commitments"][0]["needs"].clone(), applied.reaffirmed.len(), applied.refused.len()), (json!(need), 1, 0), "the need is unchanged: {state}"); - // A root read of Bifrost, a list of its pull requests, then keeps nothing. - let (after, kept) = apply(&state, &keeping_c1(&state, json!([returned(1, "GameCult/Bifrost", "Bifrost: open pull requests #84, #85, #86", Some(0))])), F2_PROSE, "r1-t16", now()); - assert_eq!((after["commitments"][0]["status"].as_str(), reasons(&kept)), (Some("open"), vec![json!("needs_unread")]), "{kept:?}"); - // The same repo spelled otherwise is still the repo itself. - for bare in ["gamecult/bifrost", "GameCult/BIFROST"] { - assert_eq!(f2_r7(&need, Some(read_need(bare))).0["commitments"][0]["needs"], json!(need), "{bare}"); - } -} - -#[test] -fn k40_an_item_reaffirm_still_narrows() { - for item in ["GameCult/Bifrost#85", "GameCult/Bifrost/src/passkey.rs", "GameCult/Bifrost@0123abcd"] { - let (state, applied) = f2_r7(&read_need("GameCult/Bifrost?q=passkey enrolment"), Some(read_need(item))); - assert_eq!((state["commitments"][0]["needs"].clone(), applied.reaffirmed.len()), (json!(read_need(item)), 1), "{item}: {state}"); - } -} - -#[test] -fn k40_an_outside_close_is_not_hers_to_reopen() { - for closed_by in [json!({ "act": "put", "event": null, "words": null }), Value::Null] { - let mut kept = f2_after_r8("kept"); - kept["commitments"][0]["closedBy"] = closed_by.clone(); - let (state, applied) = f2_r9(&kept, json!([reopening(F2_R9_WORDS, None, true)])); - assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), vec![json!("not_her_close")]), "{closed_by}"); - } - // Her own addition's close is hers. - let mut amended = f2_after_r8("kept"); - amended["commitments"][0]["closedBy"]["act"] = json!("amended"); - assert_eq!(f2_r9(&amended, json!([reopening(F2_R9_WORDS, None, true)])).0["commitments"][0]["status"], "open"); -} - -// --------------------------------------------------------------------------------------------- -// K64 (map 16.33.5): a promise never needs a read the body will refuse. - -const PASP: &str = "https://ccrma.stanford.edu/~jos/pasp/"; - -/// `record` with this conversation's reads, as the decision lists them. -fn with_reads(mut rec: Value, reads: Value) -> Value { - rec["interpreter"]["conversation_reads"] = reads; - rec -} - -fn pasp_need() -> Needs { - Needs::Read { request: ReadRequest::Web(PASP.into()) } -} - -fn pasp_read(found: bool, at: Value) -> Value { - json!([{ "key": ReadRequest::Web(PASP.into()).normal(), "found": found, "at": at }]) -} - -/// A read need on a target a read of this conversation found opens as her words, with the read it rests on; a target no -/// read found, or one read with no time, opens needing the read as before. -#[test] -fn k64_a_read_need_on_a_target_already_read_is_words() { - let read_at = now() - Duration::minutes(30); - let (state, applied) = apply(&json!({}), &with_reads(record(json!([open_needing(META, Some(pasp_need()), true)]), json!([]), true), pasp_read(true, json!(read_at.to_rfc3339()))), PROSE, "r1-t13", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"].clone(), entry["status"].as_str(), entry["readBefore"].clone()), (json!(Needs::Words), Some("open"), json!({ "at": read_at.to_rfc3339(), "of": ReadRequest::Web(PASP.into()).normal() })), "{state}"); - assert_eq!(applied.opened.len(), 1); - // A keep later rests on her words alone. - let mut keep = turn_saying(&state, META, "I'll send the render tonight.", json!([close(How::Kept, Evidence::Draft(1))])); - keep["interpreter"]["promises"][0]["entry"] = entry["id"].clone(); - let (_, kept) = apply(&state, &keep, PROSE, "r1-t14", now()); - assert_eq!((kept.closed.len(), reasons(&kept)), (1, vec![]), "{kept:?}"); - for reads in [pasp_read(false, json!(read_at.to_rfc3339())), pasp_read(true, Value::Null), json!([])] { - let (state, _) = apply(&json!({}), &with_reads(record(json!([open_needing(META, Some(pasp_need()), true)]), json!([]), true), reads.clone()), PROSE, "r1-t13", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"].clone(), entry.get("readBefore")), (json!(pasp_need()), None), "{reads}: {state}"); - } -} - -/// A reaffirmation that narrows a search to one thing a read of this conversation already found narrows it to her words. -#[test] -fn k64_a_reaffirm_narrowing_to_an_item_already_read_is_words() { - let c1 = holding_one(KIKO, F2_PROMISE, &search_need(), "open"); - let again = json!(Proposal::PromiseOpen { words: "I'll open #85 next and come back with what it does.".into(), to: Some(KIKO.into()), reaffirms: Some("c1".into()), needs: Some(read_need("GameCult/Bifrost#85")), reached: true, now: false, evidence: Evidence::Draft(1) }); - let read_at = now() - Duration::minutes(5); - let reads = json!([{ "key": ReadRequest::Repo("GameCult/Bifrost#85".into()).normal(), "found": true, "at": read_at.to_rfc3339() }]); - let (state, applied) = apply(&c1, &with_reads(turn_saying(&c1, KIKO, F2_R7_DRAFT, json!([again])), reads), F2_R7_PROSE, "r1-t14", now()); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"].clone(), entry["readBefore"]["of"].as_str(), applied.reaffirmed.len()), (json!(Needs::Words), Some(ReadRequest::Repo("GameCult/Bifrost#85".into()).normal().as_str()), 1), "{state}"); -} diff --git a/crates/mind-body/src/projection/exchange.rs b/crates/mind-body/src/projection/exchange.rs index a4ee815..a34a23b 100644 --- a/crates/mind-body/src/projection/exchange.rs +++ b/crates/mind-body/src/projection/exchange.rs @@ -59,14 +59,12 @@ pub(crate) struct Shown { pub(crate) text: String, } -/// A read she made in this conversation: its normal form, whether it found anything, what it was in code's words, and when -/// she made it (K64: a promise made after it is kept by what she has). +/// A read she made in this conversation: its normal form, whether it found anything, and what it was in code's words. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub(crate) struct Tried { pub(crate) key: String, pub(crate) found: bool, pub(crate) what: String, - pub(crate) at: DateTime, } fn at_of(record: &Value) -> Option> { @@ -118,7 +116,7 @@ pub(crate) fn exchange_of(records: &[Value], room: &str, now: DateTime, her let found = read["ok"] == true; if found || read["failure"] == "not_found" { exchange.tried.retain(|tried| tried.key != request.normal()); - exchange.tried.push(Tried { key: request.normal(), found, what: read["what"].as_str().unwrap_or_default().to_owned(), at: *at }); + exchange.tried.push(Tried { key: request.normal(), found, what: read["what"].as_str().unwrap_or_default().to_owned() }); } } for read in decision["reads"].as_array().into_iter().flatten().filter(|read| read["ok"] == true) { diff --git a/crates/mind-body/src/projection/exchange/tests.rs b/crates/mind-body/src/projection/exchange/tests.rs index f394227..c9f5cc3 100644 --- a/crates/mind-body/src/projection/exchange/tests.rs +++ b/crates/mind-body/src/projection/exchange/tests.rs @@ -64,7 +64,7 @@ fn r7_a_not_found_read_is_remembered_and_a_broken_one_is_not() { let missing = json!({ "ok": false, "failure": "not_found", "request": { "kind": "repo", "target": "GameCult/Bifrost?q=Consent Receipt" }, "what": "a search" }); let broken = json!({ "ok": false, "failure": "failed", "request": { "kind": "repo", "target": "GameCult/Lodur" }, "what": "GameCult/Lodur on the forge" }); let exchange = exchange_of(&[turn(10, MINDS, &[], json!([missing, broken]), json!([]), json!([]))], MINDS, now(), her()); - assert_eq!(exchange.tried, [Tried { key: "repo:gamecult/bifrost?q=consent receipt".into(), found: false, what: "a search".into(), at: exchange.tried[0].at }]); + assert_eq!(exchange.tried, [Tried { key: "repo:gamecult/bifrost?q=consent receipt".into(), found: false, what: "a search".into() }]); } /// Soul's R8: the reads refused in the conversation are carried, once each, as `kind target (why)`. diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 60b19d5..89381ea 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -474,7 +474,7 @@ fn k24_her_wake_reads_by_intent_from_a_fixture_and_stops_at_the_cap() { assert!(report["packet"]["affordances"].as_array().unwrap().contains(&json!("read"))); // Her next packet opens with what she read, without its content. let record = json!({ "interpreter": decision, "posted": [] }); - let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.contains(&"- He read GameCult/Lodur#12 on the forge.".to_owned()) && !told.join(" ").contains("in front of him now"), "{told:?}"); assert!(told.iter().any(|line| line == "- He reached for http://example.org/private and could not read it: it is private."), "{told:?}"); @@ -506,7 +506,7 @@ fn k24_a_failed_later_call_keeps_what_was_already_decided() { if prompt.contains("Earlier in his moment") { return "not the contract".into(); } - json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [], "read": { "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" } }).to_string() + json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [], "read": { "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" } }).to_string() }); let report = wake_of(&fixture, &model); let decision = &report["renders"][0]["interpreter"]; @@ -541,7 +541,7 @@ fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_runaway_draft_is_cut_b assert_eq!(persona["words"].as_u64(), Some(words as u64), "her first segment whole; the runaway draft is not in her stream: {persona}"); assert!(!persona["prose"].as_str().unwrap().contains(""), "no unclosed draft in her stream: {persona}"); assert!(decision["cut_by_cap"][0].as_str().is_some_and(|text| text.starts_with("Deru, I opened it")), "{decision}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.iter().any(|line| line.contains("finished writing")), "she is told: {told:?}"); } @@ -577,7 +577,7 @@ reads_per_wake = 1 let mut decision = report["renders"][0]["interpreter"].clone(); assert_eq!(decision["read_refused"][0]["why"], "reads_per_wake", "{decision}"); decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": { "kind": "web", "target": "http://made.up/x", "quote": "x" }, "why": "web_address_not_in_front_of_her" })); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.contains(&"- He reached for GameCult/Lodur#13 on the forge and it was not read: he has read as much as one turn reads.".to_owned()), "{told:?}"); assert!(told.contains(&"- He reached for something to read and it was not read: the address was not in front of him.".to_owned()) && !told.join("\n").contains("made.up"), "a model's target is never told: {told:?}"); } @@ -622,7 +622,7 @@ fn r6_no_draft_is_dropped_silently_at_the_cap() { let reply = format!("{after}Meta, later words."); let model = Scripted::new(move |_| reply.clone()); let report = wake_of(&fixture, &model); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": report["renders"][0]["interpreter"], "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": report["renders"][0]["interpreter"], "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.iter().any(|line| line.contains("the length limit cut it before he finished writing it") && line.contains("Meta, later words.")), "{told:?}"); } @@ -639,6 +639,6 @@ fn r7_the_cap_never_backs_off_into_a_closed_draft_and_tells_every_draft_it_cuts( let many: String = (1..=190).map(|n| format!("t{n} ")).collect(); let cut = crate::projection::narrate::cap_prose(&format!("{many}First late one. and Second late one."), words); assert_eq!(cut.cut_drafts, ["First late one.", "Second late one."]); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": { "room": "#minds:gamecult.org", "said": [], "refused": [], "gaps": [], "heard": [], "cut_by_cap": cut.cut_drafts }, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": { "room": "#minds:gamecult.org", "said": [], "refused": [], "gaps": [], "heard": [], "cut_by_cap": cut.cut_drafts }, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); assert_eq!(told.iter().filter(|line| line.contains("the length limit cut it")).count(), 2, "{told:?}"); } diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index ba7b951..53523f8 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -22,14 +22,9 @@ //! the turn's room. Whether a draft tells what she knows privately is a reading of its meaning, so it is the //! Interpreter's judgement over the private items the packet lists to it (`Packet::private`), never a word match here. //! Every refusal and drop is reported. Every gap is typed (`GapKind`) and shown to her later (K9) only as what it is: a -//! draft by number, or a located passage of her thought (`gap`). Each line she says, and each addition, carries a -//! required `promises`: a list, empty or one entry per act it promises or offers, each its words, to whom, and what -//! keeping it needs, typed (map 16.21, 16.22.1, 16.25.2, B3); whether it opens or is blocked is derived from that by code. Words of at least `PROMISE_MIN_WORDS` found in the draft (`promise_found`) become a `promise_open` -//! proposal with the draft as evidence, and a promise she cannot do is also the `missing_affordance` gap; otherwise -//! they are reported (`promises_unused`) and open nothing. The answer's `state` closes her listed open promises, each a -//! `promise_close` proposal with its evidence. Nothing here writes her state: every proposal rides in the decision as -//! `state`, with the lines and promises it listed by id, and the commit's one applier (`commit::apply`, map 16.22.7) -//! applies it on the turn's receipts. The prompt tells the Interpreter what she can do this turn +//! draft by number, or a located passage of her thought (`gap`). What she says she will do lives only in her own words +//! and in what she chooses to remember: no code here derives a promise or a hold from a line (map 16.35, ruling +//! `persona-memory-not-machinery`). Nothing here writes her state. The prompt tells the Interpreter what she can do this turn //! (`select::turn_words`), so a reach past it is a `missing_affordance` gap. Nothing here posts: the commit (C3c) will. //! //! The same answer may add a draft after a line of hers listed as one she may add to (`amend`, map 16.17; the actuator @@ -43,7 +38,6 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::Affordance; -use super::commit::{Evidence, How, Needs, NeedsKind, Proposal}; 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}; @@ -59,9 +53,6 @@ const ECHO_OVERLAP: f64 = 0.8; /// she meant, and is kept as unlocated. const GAP_QUOTE_MIN_WORDS: usize = 4; -/// The fewest words the words of a draft that promise an act may be: fewer ("the") name no act. -const PROMISE_MIN_WORDS: usize = 4; - /// The marks of a draft: two literal tokens no natural prose holds (map 16.19.1). pub(crate) const DRAFT_OPEN: &str = ""; pub(crate) const DRAFT_CLOSE: &str = ""; @@ -71,7 +62,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":["declined","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","now","done_by"],"properties":{"now":{"type":"boolean"},"done_by":{"anyOf":[{"type":"null"},{"type":"object","additionalProperties":false,"required":["draft"],"properties":{"draft":{"type":"integer","minimum":1}}},{"type":"object","additionalProperties":false,"required":["read"],"properties":{"read":{"type":"boolean","enum":[true]}}},{"type":"object","additionalProperties":false,"required":["note"],"properties":{"note":{"type":"boolean","enum":[true]}}}]},"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","now","done_by"],"properties":{"now":{"type":"boolean"},"done_by":{"anyOf":[{"type":"null"},{"type":"object","additionalProperties":false,"required":["draft"],"properties":{"draft":{"type":"integer","minimum":1}}},{"type":"object","additionalProperties":false,"required":["read"],"properties":{"read":{"type":"boolean","enum":[true]}}},{"type":"object","additionalProperties":false,"required":["note"],"properties":{"note":{"type":"boolean","enum":[true]}}}]},"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","read","unsent"],"properties":{"unsent":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","how","quote"],"properties":{"draft":{"type":"integer"},"how":{"type":"string","enum":["declined","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"}}},"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#; /// The speech frame before the guidance: what to decide, from what, and the attribution rule. Code, not tuning (map /// 16.7), in her own pronouns (16.19.7). The tuning's `interpreter.guidance` (what counts as her choosing to send it @@ -87,15 +78,14 @@ Below are who {subj} {be}, what {subj} can do here, the room and who is in it, w /// The speech frame after the guidance: the room and the private rules, the contract and the gap kinds. fn speech_frame_tail(her: Forms) -> String { - let Forms { subj, cap_subj, obj, poss, has, be, s, .. } = her; + let Forms { subj, cap_subj, obj, poss, s, .. } = her; format!( "{cap_subj} speak{s} only in this room. What {subj} know{s} privately is listed below as private: {subj} say{s} none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge. -Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`), 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 does (`promises`, a list, empty when it promises nothing and says of no act that {subj} {be} doing it): for each act the draft promises or offers, and each act it says {subj} {be} doing now or {has} just done this turn: 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; `now`, true when the draft says {subj} {be} doing it now or {has} just done it; and `done_by`, the act of this answer that does it (`{{\"draft\": n}}` for a draft said or added, `{{\"read\": true}}` for the read, `{{\"note\": true}}` for the note to Self), or null: an act no act of this answer does is {poss} promise, open until {subj} keep{s} or withdraw{s} 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 an addressee or elsewhere gap: declined, 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 declined only when {poss} prose says {subj} choose{s} not to send 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). `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 an addressee or elsewhere gap: declined, 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 declined only when {poss} prose says {subj} choose{s} not to send 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 and the draft that is {poss} addition. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. 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" }, - does = if s.is_empty() { "do" } else { "does" }, ) } @@ -250,7 +240,7 @@ pub(crate) enum GapKind { /// She means a draft for another room or another time. Elsewhere, /// She means to do something, now or later, that no affordance of hers does (map 16.20.6): a reach in her thought, or a - /// promise in a draft she says. It accounts for no draft (map 16.29.2): her line posts as she meant it, and this + /// reach in a draft she says. It accounts for no draft (map 16.29.2): her line posts as she meant it, and this /// annotates it. A tool request in waiting (section 4.2). MissingAffordance, /// She means to say something now and wrote no draft of it, so nothing went out. A choice to hold back (to wait, let @@ -282,11 +272,11 @@ impl GapKind { /// /// - `acted`: it names, or quotes from, a draft that went somewhere this turn (said, added to a line, left for Self), so it /// contradicts what happened and is not shown to her (`decide` sets it). One exception: a `missing_affordance` gap that -/// names a draft she said is a promise of an act she cannot do, and is kept and shown (map 16.20.6). +/// names a draft she said is an act she says she will do and cannot, and is kept and shown (map 16.20.6). /// /// Every kind but `unwritten` may name a draft: an unwritten line is about words she did not set down, so it is always a /// passage of her thought, whatever draft the model names. A kind the contract does not name names no draft either, so it -/// accounts for none (map 16.25.7). A reach (`missing_affordance`) names the draft that promises +/// accounts for none (map 16.25.7). A reach (`missing_affordance`) names the draft that reaches for /// it when there is one, a draft she says (map 16.20.6, 16.29.2), and otherwise quotes her thought; a reach that names no draft and /// quotes one (at least `GAP_QUOTE_MIN_WORDS` words, found in the draft's words) is about that draft, as if named. /// @@ -299,7 +289,7 @@ fn gap(prose: &str, found: &Drafts, raw: &Value) -> Value { } let names_a_draft = !matches!(kind, GapKind::Unwritten | GapKind::Unresolved); let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim(); - // A reach that quotes a draft by its words, with no number, is about that draft: a promise in it (map 16.20.6). + // A reach that quotes a draft by its words, with no number, is about that draft: a reach in it (map 16.20.6). let quoted_draft = || (kind == GapKind::MissingAffordance && words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.drafts.iter().find(|draft| span::fold_text(&draft.text).contains(&span::fold_text(quote)))).flatten(); if let Some(draft) = raw.get("draft").and_then(Value::as_i64).and_then(|n| found.numbered(n)).filter(|_| names_a_draft).or_else(quoted_draft) { gap["from"] = json!("draft"); @@ -334,10 +324,6 @@ struct Answer { amend: Vec, #[serde(default)] suggest: Vec, - /// State changes proposed for the commit (map 16.22.7): read item by item, so one that is not the contract is - /// reported and the rest stand. Absent proposes none. - #[serde(default)] - state: Vec, /// One read she reaches for in the new part of her thought (map 16.22.3), or none: read whole, so one that is not the /// contract is reported and the rest of the answer stands. #[serde(default)] @@ -345,20 +331,6 @@ struct Answer { /// The drafts not sent and not gapped, each declined by her own choice or superseded, citing her prose (Soul's R10). #[serde(default)] unsent: Vec, - /// Closes her own words here say were wrong (map 16.28.3): read item by item, so one that is not the contract is - /// reported and the rest stand. - #[serde(default)] - reopen: Vec, -} - -/// A reopen as the answer carries it: a listed closed promise's id, her words, and what keeping it needs, or none to keep -/// what it needed. -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct ProposedReopen { - promise: String, - words: String, - needs: Option, } /// A draft the answer neither sends nor gaps, and why, citing her prose. @@ -429,87 +401,6 @@ pub(crate) struct Wake<'a> { pub before: &'a str, } -/// What a line or an addition promises or offers (map 16.22.1, 16.25.6): its promising words, to whom (a Matrix id -/// listed, none for the room), and what keeping it needs. Nothing else: a field the contract does not name -/// makes the answer not the contract. -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct ProposedPromise { - words: String, - #[serde(default)] - to: Option, - /// The id of an open promise of hers these words promise again to the same person (map 16.24.2), or none. - #[serde(default)] - reaffirms: Option, - needs: ProposedNeeds, - /// Whether the draft says she is doing it now or has just done it this turn (K61, map 16.33.5). - #[serde(default)] - now: bool, - /// The act of this answer that does it, or none: then it is her promise (K61). Whether that act happened is code's. - #[serde(default)] - done_by: Option, -} - -/// What does an act a draft states (K61), as the answer names it: a draft it says or adds, the read, or the note to Self. -/// Exactly one; any other shape names no act. -#[derive(Clone, Copy, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct DoneBy { - #[serde(default)] - draft: Option, - #[serde(default)] - read: Option, - #[serde(default)] - note: Option, -} - -/// An act of a decision that does what a draft states (K61). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum By { - Draft(usize), - Read, - Note, -} - -impl DoneBy { - /// The one act it names, or None when it names none or several. - fn act(self) -> Option { - match (self.draft, self.read.unwrap_or(false), self.note.unwrap_or(false)) { - (Some(n), false, false) => usize::try_from(n).ok().filter(|n| *n > 0).map(By::Draft), - (None, true, false) => Some(By::Read), - (None, false, true) => Some(By::Note), - _ => None, - } - } -} - -impl By { - fn json(self) -> Value { - match self { - Self::Draft(n) => json!({ "draft": n }), - Self::Read => json!({ "read": true }), - Self::Note => json!({ "note": true }), - } - } -} - -/// What keeping a promise needs, as the answer types it (map 16.25.2): its kind, and for a read what to read. -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct ProposedNeeds { - kind: NeedsKind, - #[serde(default)] - read: Option, -} - -/// A read a promise needs, as the answer names it: a read's kind and target, with no quote. -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct NeededRead { - kind: Kind, - target: String, -} - /// A note to Self as the model proposes it: its kind, the draft that is the note, whose feedback it passes on (a Matrix /// id from the people listed, or none for her own idea), and whether it carries something private. #[derive(Debug, Deserialize)] @@ -524,16 +415,13 @@ struct ProposedNote { private: Option, } -/// An amendment as the model proposes it: the id of a line she may add to, the draft that is her addition, and what it -/// promises (as a line's `promise`). +/// An amendment as the model proposes it: the id of a line she may add to, and the draft that is her addition. #[derive(Debug, Deserialize)] struct ProposedAmend { #[serde(default)] target: Option, #[serde(default)] draft: Option, - #[serde(default)] - promises: Vec, } #[derive(Debug, Deserialize)] @@ -545,10 +433,6 @@ struct Proposed { /// The id of a line listed as one she may reply to (`Packet::quotable`), or none. #[serde(default)] in_reply_to: Option, - /// What the draft promises (map 16.21, 16.22.1, B3), one entry per act: each found in the draft, code proposes opening - /// it, which the commit applies on the line's receipt; each she cannot do is also a `missing_affordance` gap. - #[serde(default)] - promises: Vec, } #[cfg(test)] @@ -580,30 +464,6 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu if amendable.is_empty() { amendable.push_str("- none\n"); } - let mut promises: String = packet - .promises - .iter() - .map(|promise| { - let to = promise.to.as_deref().map_or_else(String::new, |to| format!(" ({to})")); - // A closed one with what closed it, beside her words now (map 16.28.3). - let closed_at = || promise.held["closedAt"].as_str().and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok()).map_or_else(String::new, |at| format!(" {}", at.with_timezone(&chrono::Utc).format("%Y-%m-%d %H:%M UTC"))); - let by = || promise.held["closedBy"]["words"].as_str().map_or_else(String::new, |words| format!(", by {}", spoken(words))); - let status = match promise.status.as_str() { - "blocked" => format!("which {} {} no way to do", her.subj, her.has), - "open" => "open".to_owned(), - how => format!("closed: {how}{}{}", closed_at(), by()), - }; - // What keeping it needs, in code's words (map 16.25.2). - let needs = match &promise.needs { - Some(Needs::Read { request }) if matches!(promise.status.as_str(), "open" | "blocked") => format!(", needs a read of {}", request.what(her)), - _ => String::new(), - }; - format!("- {} \u{2014} to {}{to}, {status}{needs}, made {} {}: {}\n", promise.id, promise.to_name, promise.made.format("%Y-%m-%d %H:%M UTC"), promise.place, spoken(&promise.words)) - }) - .collect(); - if promises.is_empty() { - promises.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() { @@ -650,7 +510,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{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, @@ -688,13 +548,11 @@ fn echo(line: &str, bodies: &[String]) -> bool { struct Faults { /// Drafts accounted for nowhere (`unaccounted`): refused `Undecided`. undecided: Vec, - /// Acts a draft states as done by an act this answer does not make (`done_faults`, K61): each opens as her promise. - undone: Vec, } impl Faults { fn none(&self) -> bool { - self.undecided.is_empty() && self.undone.is_empty() + self.undecided.is_empty() } /// The retry's report of this answer, and the paragraphs, one a fault, that name what it left undone. @@ -706,13 +564,8 @@ impl Faults { missed.push(format!("An earlier answer to this left drafts {list} accounted for nowhere: each draft is in `say`, `amend` or `suggest`, a gap of kind addressee or elsewhere that names it, or `unsent`.")); fault["drafts"] = json!(self.undecided); } - if !self.undone.is_empty() { - let list = self.undone.iter().map(|one| format!("draft {}, {}", one["draft"], spoken(one["words"].as_str().unwrap_or_default()))).collect::>().join("; "); - missed.push(format!("An earlier answer to this named, as what does an act a draft states, an act it does not make: {list}. `done_by` names a draft in `say` or `amend`, the read when `read` names one, or the note when `suggest` leaves one, and is null when no act of this answer does it.")); - fault["done_by"] = json!(self.undone); - } // The first fault named is the one the report gives. - let failed = [(!self.undecided.is_empty(), "the answer leaves drafts unaccounted"), (!self.undone.is_empty(), "the answer names acts it does not make")].into_iter().find(|(any, _)| *any).map(|(_, why)| why); + let failed = [(!self.undecided.is_empty(), "the answer leaves drafts unaccounted")].into_iter().find(|(any, _)| *any).map(|(_, why)| why); fault["failed"] = json!(failed); (fault, missed.join("\n\n")) } @@ -774,7 +627,7 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na let (fault, missed) = match serde_json::from_str::(&answer.text) { Ok(parsed) => { let gaps: Vec = parsed.gaps.iter().map(|raw| gap(prose, &found, raw)).collect(); - let faults = Faults { undecided: unaccounted(&parsed, &gaps, prose, &found), undone: done_faults(&parsed, &found) }; + let faults = Faults { undecided: unaccounted(&parsed, &gaps, prose, &found) }; // A fault the retry did not mend fails closed for what it guards, never for the turn: each draft still // unaccounted is undecided, every other draft is decided, and the faults are reported. if retried.is_some() || faults.none() { @@ -811,19 +664,10 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na let earlier = |key: &str| wake.earlier.and_then(|earlier| earlier[key].as_array()).cloned().unwrap_or_default(); // What she was sent and what she has read this wake: what an echo is measured against (map 16.22.3). let bodies: Vec = packet.bodies.iter().cloned().chain(wake.read.iter().cloned()).collect(); - // 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, "text": line.text })).collect(); - // The reads of this conversation, by normal form, whether each found its target, and when: what a kept promise that - // needs a read is checked against (`commit::apply`, map 16.25.4), and what a promise made after it is kept by (K64). - let conversation_reads: Vec = packet.already_read.iter().map(|tried| json!({ "key": tried.key, "found": tried.found, "at": tried.at.to_rfc3339() })).collect(); - let mut decision = json!({ "said": [], "refused": [], "gaps": gaps, "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, "calls": calls, "read": null, "at_ms": packet.now_ms }); if let Some(retried) = retried { decision["retried"] = retried; } - if !faults.undone.is_empty() { - decision["done_by_faults"] = json!(faults.undone); - } // Each unsent draft with its words and its quote as located in her prose, so her outcome can tell her a declined one // did not go out, and the thought it cites (map 16.26, 16.29.8). This answer decided every draft of the wake, so an // earlier segment's unsent drafts are not carried (map 16.27). @@ -856,11 +700,6 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na let mut went: Vec<&Draft> = Vec::new(); let mut said_drafts: Vec = Vec::new(); let mut said_words: Vec = Vec::new(); - let mut unused: Vec = Vec::new(); - let mut proposals: Vec = Vec::new(); - let mut to_dropped: Vec = Vec::new(); - // What each line and addition that went out promises or does (K61), decided once the acts of the answer are known. - let mut pending: Vec<(&Draft, Vec)> = Vec::new(); 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)); @@ -894,7 +733,6 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na said_words.push(span::fold_text(&draft.text)); went.push(draft); said.push(json!({ "room": room, "text": draft.text, "mentions": mentions, "in_reply_to": target.map(|line| json!({ "id": line.id, "event": line.event, "who": line.who, "text": line.text })), "rests_on": { "draft": draft.n, "start_byte": draft.start, "end_byte": draft.end }, "dropped": { "mentions": unknown } })); - pending.push((draft, line.promises)); } // An amendment adds a whole draft after a line of hers listed as one she may add to; the actuator composes it, so // nothing here can rewrite the line (map 16.17). @@ -920,7 +758,6 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na went.push(draft); amended_drafts.push(draft.n); amended.push(json!({ "target": line.id, "event": line.event, "room": line.room, "original": line.text, "added": draft.text, "draft": draft.n })); - pending.push((draft, proposed.promises)); } (reason, _) => refusals.push(refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable))), } @@ -957,11 +794,11 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na suggestions.push(json!({ "kind": proposed.kind, "about": about, "room": room, "text": draft.text, "draft": draft.n, "dropped": { "about": dropped } })); } // A gap about a draft that went somewhere, or quoting from one, contradicts what happened: it is kept for the trace as - // `acted` and never shown to her. A reach naming a draft she said or added is a promise she cannot keep, and is kept - // (16.20.6, 16.21). + // `acted` and never shown to her. A reach naming a draft she said or added is an act her line says she will do and her + // body cannot, and is kept (`persona-unbacked-intent-say-then-amend`, 16.20.6). for gap in decision["gaps"].as_array_mut().into_iter().flatten() { - let promise = gap["kind"] == json!(GapKind::MissingAffordance) && gap["from"] == "draft" && gap["draft"].as_u64().is_some_and(|n| said_drafts.iter().chain(&amended_drafts).any(|said| *said as u64 == n)); - let named = !promise && gap["draft"].as_u64().is_some_and(|n| went.iter().any(|draft| draft.n as u64 == n)) && gap["from"] == "draft"; + let unbacked = gap["kind"] == json!(GapKind::MissingAffordance) && gap["from"] == "draft" && gap["draft"].as_u64().is_some_and(|n| said_drafts.iter().chain(&amended_drafts).any(|said| *said as u64 == n)); + let named = !unbacked && gap["draft"].as_u64().is_some_and(|n| went.iter().any(|draft| draft.n as u64 == n)) && gap["from"] == "draft"; let quoted = gap["from"] == "unlocated" && gap["quote"].as_str().is_some_and(|quote| !quote.is_empty() && went.iter().any(|draft| span::fold_text(&draft.text).contains(&span::fold_text(quote)))); if named || quoted { gap["from"] = json!("acted"); @@ -980,21 +817,6 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na if !read_refused.is_empty() { decision["read_refused"] = json!(read_refused); } - // What each line and addition that went out promises or does (K61): an act it states is done only by an act of this - // decision that happened, a draft said or added, the read made, or the note left; any other is her promise. - let read_made = !decision["read"].is_null(); - let done = |by: By| match by { - By::Draft(n) => said_drafts.contains(&n) || amended_drafts.contains(&n), - By::Read => read_made, - By::Note => !suggestions.is_empty(), - }; - let mut done_now: Vec = Vec::new(); - for (draft, promises) in &pending { - promised(&mut decision, Promising { unused: &mut unused, proposals: &mut proposals, to_dropped: &mut to_dropped, done_now: &mut done_now, packet, prose }, draft, promises, &shown, &done); - } - if !done_now.is_empty() { - decision["done_now"] = json!(done_now); - } decision["amended"] = json!(amended); decision["suggestions"] = json!(suggestions); decision["room"] = json!(room); @@ -1008,31 +830,6 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na decision["undecided"] = json!(faults.undecided); } decision["refused"] = json!(refusals); - if !unused.is_empty() { - decision["promises_unused"] = json!(unused); - } - if !to_dropped.is_empty() { - decision["promise_to_dropped"] = json!(to_dropped); - } - // The closes it proposes, each typed with its evidence; one that is not the contract is reported and proposes nothing. - let mut state_unused = Vec::new(); - for raw in parsed.state { - match close_of(&raw) { - Some(close) => proposals.push(json!(close)), - None => state_unused.push(raw), - } - } - // The reopens it proposes, after the closes (map 16.28.3); 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), - } - } - decision["state"] = json!(proposals); - if !state_unused.is_empty() { - decision["state_unused"] = json!(state_unused); - } decision } @@ -1042,7 +839,7 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake) -> Result)> { let asked: Asked = serde_json::from_value(raw.clone()).map_err(|_| ("not_the_contract", None))?; // In front of her is her prose and what she was sent, never what she read: a read cannot chain from a fetched page - // (Soul's p1b), so no page can steer her to the next. The one reach rule decides it, as at a promise's open (16.25.5). + // (Soul's p1b), so no page can steer her to the next. The one reach rule decides it (16.25.5). let reached: Vec = packet.bodies.iter().cloned().chain(std::iter::once(packet.heard.clone())).collect(); let request = read::reach(&asked, packet, prose, &reached).map_err(|why| (why, None))?; // Nothing she read in this conversation, or this wake, is read again (K26, Soul's R7), found or not, shown or not. @@ -1082,10 +879,7 @@ fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake words.dedup(); words }); - // Her own open promise anchors the reach (map 16.25.5): she reaches for what she promised to read, so its address - // need not be named again; the quote must still be located in her thought. - let promised = packet.promises.iter().any(|promise| promise.status == "open" && matches!(&promise.needs, Some(Needs::Read { request: needed }) if needed.normal() == key)); - let anchors = |sentence: &str| promised || match &title { + let anchors = |sentence: &str| match &title { Some(title) => { let said = read::word_tokens(sentence); title.iter().filter(|word| said.contains(word)).collect::>().len() >= 2 || (generic && refers(sentence)) @@ -1199,196 +993,6 @@ fn read_frame(her: Forms) -> String { ) } -/// A close as the contract carries it: a listed promise's id, how, and exactly one of a draft and a line as evidence. A -/// read is no evidence (map 16.28.6), so an answer citing one is not the contract. -fn close_of(raw: &Value) -> Option { - if raw["kind"] != "promise_close" { - return None; - } - let promise = raw["promise"].as_str().map(str::trim).filter(|id| !id.is_empty())?.to_owned(); - let how = serde_json::from_value::(raw["how"].clone()).ok()?; - if raw["evidence"].get("read").is_some_and(|read| !read.is_null()) { - return None; - } - let evidence = match (raw["evidence"]["draft"].as_u64(), raw["evidence"]["line"].as_str().map(str::trim).filter(|id| !id.is_empty())) { - (Some(n), None) => Evidence::Draft(usize::try_from(n).ok()?), - (None, Some(line)) => Evidence::Heard(line.to_owned()), - _ => return None, - }; - let thought = raw["thought"].as_str().map(str::trim).filter(|thought| !thought.is_empty()).map(str::to_owned); - Some(Proposal::PromiseClose { promise, how, evidence, thought, still_stands: raw["still_stands"] == true }) -} - - -/// The acts a line or an addition states that the answer names as done by an act it does not make (K61, map 16.33.5), a -/// contract fault found before anything is decided: a `done_by` naming no one act, a draft in neither `say` nor `amend`, -/// the read when `read` names none, or the note when `suggest` leaves none. Each by its draft and words. A fault the retry -/// does not mend is read as `done_by` null: the act is her promise (`promised_one`). -fn done_faults(answer: &Answer, found: &Drafts) -> Vec { - let acts: BTreeSet = answer.say.iter().map(|line| line.draft).chain(answer.amend.iter().map(|amend| amend.draft)).filter_map(|n| n.and_then(|n| found.numbered(n)).map(|draft| draft.n)).collect(); - let made = |by: By| match by { - By::Draft(n) => acts.contains(&n), - By::Read => answer.read.as_ref().is_some_and(|read| !read.is_null()), - By::Note => !answer.suggest.is_empty(), - }; - let lines = answer.say.iter().map(|line| (line.draft, &line.promises)).chain(answer.amend.iter().map(|amend| (amend.draft, &amend.promises))); - let mut faults = Vec::new(); - for (draft, promises) in lines { - for promise in promises.iter().filter(|promise| promise.done_by.is_some_and(|by| !by.act().is_some_and(made))) { - faults.push(json!({ "draft": draft, "words": promise.words.trim() })); - } - } - faults -} - -/// 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. -fn reopen_of(raw: &Value, packet: &Packet, prose: &str) -> Option { - let proposed: ProposedReopen = serde_json::from_value(raw.clone()).ok()?; - let promise = proposed.promise.trim(); - if promise.is_empty() { - return None; - } - let (needs, reached) = match &proposed.needs { - Some(named) => { - let (needs, verdict) = typed_needs(named, packet, prose); - (needs, verdict.is_ok()) - } - // Its own need, reached again: a promise carries its address, so its own target is in front of her (16.25.5). - None => { - let own = packet.promises.iter().find(|listed| listed.id == promise).and_then(|listed| match &listed.needs { - Some(Needs::Read { request }) => Some(request.clone()), - _ => None, - }); - let reached = own.is_some_and(|request| { - let (kind, target) = match &request { - ReadRequest::Repo(target) => (Kind::Repo, target.clone()), - ReadRequest::Web(target) => (Kind::Web, target.clone()), - ReadRequest::Mind(words) => (Kind::Mind, words.clone()), - ReadRequest::Campaign(_) => return packet.affordances.contains(&Affordance::Read), - }; - let reached: Vec = packet.bodies.iter().cloned().chain([packet.heard.clone(), target.clone()]).collect(); - read::reach(&Asked { kind, target, quote: String::new() }, packet, prose, &reached).is_ok() - }); - (None, reached) - } - }; - Some(Proposal::PromiseReopen { promise: promise.to_owned(), words: proposed.words.trim().to_owned(), needs, reached }) -} - -/// Whether `promise` names an act in `draft`: at least `PROMISE_MIN_WORDS` words (`span::tokens`), found in the draft's -/// text with both folded by `span::fold` and lowercased (K52). Why not, when not. -fn promise_found(draft: &str, promise: &str) -> Result<(), &'static str> { - let folded = |text: &str| span::fold_text(text).to_lowercase(); - if span::tokens(promise).count() < PROMISE_MIN_WORDS { - Err("fewer than four words") - } else if !folded(draft).contains(&folded(promise)) { - Err("not in the draft") - } else { - Ok(()) - } -} - -/// Where a promise found in a draft is recorded: words that name no act, the open proposals, a `to` naming no one listed, -/// and the acts stated as done that an act of this decision did (K61); and the turn a read it needs is reached in -/// (`read::reach`). -struct Promising<'a> { - unused: &'a mut Vec, - proposals: &'a mut Vec, - to_dropped: &'a mut Vec, - done_now: &'a mut Vec, - packet: &'a Packet, - prose: &'a str, -} - -/// The promises in a draft she says or adds (map 16.21, 16.22.1, B3): the list is required of every line and every -/// addition, so the judgement is made for each, and a line can carry several. Words that do not name an act in the draft -/// (`promise_found`) are reported in `unused` and open nothing. Found, code proposes opening each with the draft as -/// evidence, which the commit applies only on the line's receipt; to whom is a Matrix id listed, or the room when it names -/// no one listed (reported). Each promise she cannot do is also its own `missing_affordance` gap; a reach the answer -/// already gapped on this draft stands for the first of them, so none is recorded twice. An act the draft states that an -/// act of this decision did (`done`, K61) opens nothing, and is reported in `done_now`. -fn promised(decision: &mut Value, into: Promising, draft: &Draft, promises: &[ProposedPromise], shown: &dyn Fn(&str) -> bool, done: &dyn Fn(By) -> bool) { - let answered_reach = decision["gaps"].as_array().is_some_and(|gaps| gaps.iter().any(|gap| gap["kind"] == json!(GapKind::MissingAffordance) && gap["from"] == "draft" && gap["draft"] == json!(draft.n) && gap.get("promises").is_none())); - let Promising { unused, proposals, to_dropped, done_now, packet, prose } = into; - let mut blocked = 0; - for promise in promises.iter().filter(|promise| !promise.words.trim().is_empty()) { - let words = promise.words.trim(); - let Some(Err(why)) = promised_one(Promising { unused: &mut *unused, proposals: &mut *proposals, to_dropped: &mut *to_dropped, done_now: &mut *done_now, packet, prose }, draft, promise, shown, done) else { - continue; - }; - blocked += 1; - if blocked == 1 && answered_reach { - continue; - } - if let Some(gaps) = decision["gaps"].as_array_mut().filter(|gaps| !gaps.iter().any(|gap| gap["draft"] == json!(draft.n) && gap["promises"] == words)) { - gaps.push(json!({ "kind": GapKind::MissingAffordance, "from": "draft", "draft": draft.n, "words": draft.text, "promises": words, "detail": why })); - } - } -} - -/// One promise of a draft: reported unused when its words name no act in the draft, else proposed to open. When found, -/// whether it opens, or code's words for why it is blocked: what it needs is typed (map 16.25.2), and whether it opens is -/// derived from that, a read through the one reach rule (`read::reach`, 16.25.5). -fn promised_one(into: Promising, draft: &Draft, promise: &ProposedPromise, shown: &dyn Fn(&str) -> bool, done: &dyn Fn(By) -> bool) -> Option> { - let words = promise.words.trim(); - if let Err(why) = promise_found(&draft.text, words) { - into.unused.push(json!({ "draft": draft.n, "promises": words, "why": why })); - return None; - } - // Done by an act of this decision that happened (K61): nothing is owed. A `done_by` naming an act that did not happen - // is read as none, so the act is her promise, open where she can see it and withdraw it. - if let Some(by) = promise.done_by.and_then(DoneBy::act).filter(|by| done(*by)) { - into.done_now.push(json!({ "draft": draft.n, "words": words, "by": by.json() })); - return None; - } - let to = match promise.to.as_deref().map(str::trim).filter(|to| !to.is_empty()) { - Some(id) if shown(id) => Some(id.to_owned()), - Some(id) => { - into.to_dropped.push(json!({ "draft": draft.n, "to": id })); - None - } - None => None, - }; - let reaffirms = promise.reaffirms.as_deref().map(str::trim).filter(|id| !id.is_empty()).map(str::to_owned); - let (needs, verdict) = typed_needs(&promise.needs, into.packet, into.prose); - into.proposals.push(json!(Proposal::PromiseOpen { words: words.to_owned(), to, reaffirms, needs, reached: verdict.is_ok(), now: promise.now, evidence: Evidence::Draft(draft.n) })); - Some(verdict) -} - -/// What keeping a promise needs, typed from the answer (map 16.25.2), and whether it opens, or code's words for why it is -/// blocked. Words open; a read opens when she can reach its target (Soul's R7, R10, map 16.25.5): a read named nowhere in -/// front of her, outside GameCult, or on a turn that cannot read is blocked, as is what this body lacks and a read not -/// named. One typing, at open and at reopen. -fn typed_needs(proposed: &ProposedNeeds, packet: &Packet, prose: &str) -> (Option, Result<(), String>) { - let her = packet.forms; - match (proposed.kind, &proposed.read) { - (NeedsKind::Words, _) => (Some(Needs::Words), Ok(())), - (NeedsKind::Lacking, _) => (Some(Needs::Lacking), Err("this body has no way to do it".to_owned())), - (NeedsKind::Read, None) => (None, Err("what it needs was not named".to_owned())), - (NeedsKind::Read, Some(named)) => { - let asked = Asked { kind: named.kind, target: named.target.clone(), quote: String::new() }; - let reached: Vec = packet.bodies.iter().cloned().chain(std::iter::once(packet.heard.clone())).collect(); - match read::reach(&asked, packet, prose, &reached) { - Ok(request) => (Some(Needs::Read { request }), Ok(())), - // Not reached: kept as named when it is a read at all, so what it needs is still said; a repo or web target - // that is no repo or address ("release notes", a path on a disk) is no read, so it is what this body lacks - // (map 16.26); a domain line not listed names nothing. - Err(_) => match named.kind { - Kind::Domain => (None, Err("what it needs was not named".to_owned())), - _ => match read::well_formed(named.kind, &named.target) { - Some(request) => { - let why = format!("it needs a read this body cannot reach: {}", request.what(her)); - (Some(Needs::Read { request }), Err(why)) - } - None => (Some(Needs::Lacking), Err("this body has no way to do it".to_owned())), - }, - }, - } - } - } -} #[cfg(test)] pub(crate) mod tests; diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 002c389..28bf4c6 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -487,7 +487,7 @@ fn an_amendment_off_the_list_a_second_one_or_one_reusing_a_draft_is_refused_and_ #[test] fn the_interpreter_sees_his_lines_by_id_never_by_event_and_is_told_he_never_takes_a_word_back() { let prompt = speech_prompt(&amendable_packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("His own lines in this room that he may add to, as id \u{2014} line:\n- a1 \u{2014} \"I'll send the file tonight.\"\n- a2 \u{2014} \"Back soon.\"\n\nHis promises, open and closed in this conversation, as id"), "{prompt}"); + assert!(prompt.contains("His own lines in this room that he may add to, as id \u{2014} line:\n- a1 \u{2014} \"I'll send the file tonight.\"\n- a2 \u{2014} \"Back soon.\"\n"), "{prompt}"); assert!(!prompt.contains("$ev-"), "the actuator's handle is never shown to a model: {prompt}"); assert!(prompt.contains("The line stays as it was and the draft is added after it; he never takes a word back."), "{prompt}"); assert!(speech_prompt(&packet(), "x", "y", &Tuning::default()).contains("may add to, as id \u{2014} line:\n- none\n")); @@ -533,7 +533,7 @@ fn a_note_needs_no_room_and_speech_does() { assert_eq!((decision["suggestions"][0]["text"].as_str(), decision["suggestions"][0]["room"].clone()), (Some(NOTE), Value::Null), "{decision}"); assert_eq!(refusals(&decision), [("say".to_owned(), "no_room".to_owned())]); // He is told the line he meant to say had nowhere to go (Soul at 0cfc386: it was omitted). - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap(); assert!(outcome.lines(packet().forms).contains(&"- Nothing reached anyone. That turn had no room for him to speak in, so it was not sent. He had drafted: \"Another thought.\".".to_owned()), "{:?}", outcome.lines(packet().forms)); assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); } @@ -592,40 +592,6 @@ fn soul_a_gap_never_contradicts_what_went_out() { assert_eq!(from, ["acted", "acted", "thought"], "a gap on the sent draft, an unwritten quote from it, and an unwritten line of his thought whatever draft it names: {decision}"); } -#[test] -fn k17_a_said_promise_of_an_act_he_cannot_do_is_kept_as_a_gap_and_told_as_a_promise() { - let prose = "She'll want to see it. I'll send the render tonight."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] })); - assert_eq!(texts(&decision), ["I'll send the render tonight."], "{decision}"); - let gap = &decision["gaps"][0]; - assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["words"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the render tonight.")), "kept, not acted: {gap}"); - let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); - assert_eq!(told, ["- #minds:gamecult.org has, from him: \"I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); -} - -/// Map 16.21: each line's required `promises` is where the promise is judged. Found in the draft, code records the -/// missing_affordance gap and she is told the promise; not found, it is reported and records no gap; a reach the answer -/// already gapped is not recorded twice. -#[test] -fn k21_a_lines_promises_words_found_in_it_are_the_promise_gap() { - let prose = "Missed you too. I'll send the render tonight."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll send the render tonight.", "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] })); - let gap = &decision["gaps"][0]; - assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["promises"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the render tonight.")), "{decision}"); - let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "Missed you too. I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); - assert_eq!(told, ["- #minds:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); - let unfound = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll mail you the render.", "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] })); - assert_eq!((unfound["gaps"].as_array().unwrap().len(), unfound["promises_unused"].clone()), (0, json!([{ "draft": 1, "promises": "I'll mail you the render.", "why": "not in the draft" }])), "{unfound}"); - let none = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [] })); - assert!(none["gaps"].as_array().unwrap().is_empty() && none.get("promises_unused").is_none(), "{none}"); - let twice = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll send the render tonight.", "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] })); - assert_eq!(twice["gaps"].as_array().unwrap().len(), 1, "{twice}"); - let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("(`promises`, a list, empty when it promises nothing and says of no act that he is doing it)") && SPEECH_SCHEMA.contains(r#""required":["draft","mentions","in_reply_to","promises"]"#), "{prompt}"); -} - /// Soul's probe at 0cfc386: the reach names no draft and quotes the said one by its words. It is the promise on that draft, /// not `acted`. #[test] @@ -635,28 +601,13 @@ fn a_reach_quoting_a_said_draft_by_its_words_is_a_promise_on_that_draft() { let gap = &decision["gaps"][0]; assert_eq!((gap["from"].as_str(), gap["draft"].as_u64(), gap["words"].as_str()), (Some("draft"), Some(1), Some("Missed you too. I'll send the render tonight.")), "{gap}"); let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "Missed you too. I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(packet().forms); assert_eq!(told, ["- #minds:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); // A quote too short to say which draft is not one. let short = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "missing_affordance", "draft": null, "quote": "the render", "detail": "" }] })); assert_eq!(short["gaps"][0]["from"], "acted", "{short}"); } -#[test] -fn k17_a_thought_only_intent_is_a_reach_and_any_other_gap_on_an_acted_draft_is_acted() { - let prose = "Meta's question is a good one. I'll look into it. Good question. Note: look into it."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [ - { "kind": "missing_affordance", "draft": null, "quote": "I'll look into it.", "detail": "" }, - { "kind": "addressee", "draft": 1, "quote": null, "detail": "" }, - { "kind": "missing_affordance", "draft": 2, "quote": null, "detail": "" }, - ], "suggest": [{ "kind": "idea", "draft": 2, "about": null, "private": false }] })); - let from: Vec<&str> = decision["gaps"].as_array().unwrap().iter().map(|gap| gap["from"].as_str().unwrap()).collect(); - assert_eq!(from, ["thought", "acted", "acted"], "a reach in his thought; an addressee gap on the said draft; a reach naming the draft left for Self: {decision}"); - assert_eq!(decision["gaps"][0]["words"], "I'll look into it."); - let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("missing_affordance when he means to do something, now or later, that his body cannot do") && prompt.contains("an intent to act is missing_affordance, an intent to say now with no draft is unwritten"), "{prompt}"); -} - #[test] fn k18_two_identical_drafts_are_two_drafts_and_the_second_said_is_a_duplicate() { let prose = "On it. I mean it. On it."; @@ -672,7 +623,7 @@ fn k18_a_refused_act_does_not_use_up_its_draft_and_is_told() { let prose = "I should fix that. Couldn't send it after all."; let decision = answered(&amendable_packet(), prose, json!({ "say": [], "gaps": [], "amend": [{ "target": "zz", "draft": 1 }], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] })); assert_eq!((refusals(&decision), decision["suggestions"][0]["text"].as_str()), (vec![("amend".to_owned(), "not_amendable".to_owned())], Some("Couldn't send it after all.")), "{decision}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.starts_with("- Nothing changed, and nothing reached #minds:gamecult.org:")) && told.iter().any(|line| line.starts_with("- He left Self a note:")), "{told:?}"); } @@ -697,76 +648,6 @@ fn k18_a_note_whose_answer_does_not_say_private_is_refused_as_private() { assert_eq!((decision["suggestions"].as_array().unwrap().len(), refusals(&decision)), (0, vec![("suggest".to_owned(), "private".to_owned())]), "fails closed: {decision}"); } -/// Soul at 964ee50: "the" made "Also the kettle sounds fine." a promise; a promise's words differing from the draft -/// only in case or in a curly apostrophe were reported not found; an addition could not carry a promise. -#[test] -fn k21_a_promise_is_four_words_or_more_found_case_blind_and_an_addition_carries_one_too() { - let prose = "I hold one back. Missed you too. I'll send the render tonight. Also the kettle sounds fine."; - let say = |draft: u64, promises: &str| answered(&packet(), prose, holding_the_rest(json!({ "say": [{ "draft": draft, "mentions": [], "in_reply_to": null, "promises": [{ "words": promises, "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] }), prose, "I hold one back")); - let short = say(2, "the"); - assert_eq!((short["gaps"].as_array().unwrap().len(), short["promises_unused"].clone()), (0, json!([{ "draft": 2, "promises": "the", "why": "fewer than four words" }])), "{short}"); - assert_eq!(say(1, "the render tonight")["promises_unused"][0]["why"], "fewer than four words"); - for promises in ["i'll send the render tonight", "I\u{2019}ll send the render tonight.", "I\u{2018}LL SEND THE RENDER TONIGHT"] { - let decision = say(1, promises); - assert_eq!((decision["gaps"][0]["kind"].as_str(), decision["gaps"][0]["promises"].as_str(), decision.get("promises_unused")), (Some("missing_affordance"), Some(promises), None), "{promises}: {decision}"); - } - let curly = answered(&packet(), "I\u{2019}ll send the render tonight.", json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll send the render tonight.", "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] })); - assert_eq!(curly["gaps"][0]["kind"], "missing_affordance", "a curly apostrophe in the draft: {curly}"); - - // An addition's promise: the same derivation, kept (not `acted`), and told on the addition's row. - let prose = "I should fix that. I'll send the file tomorrow instead, first thing."; - let amend = |promises: Value| answered(&amendable_packet(), prose, json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "promises": if promises.is_null() { json!([]) } else { json!([{ "words": promises, "to": null, "needs": { "kind": "lacking", "read": null } }]) } }] })); - let decision = amend(json!("I'll send the file tomorrow")); - let gap = &decision["gaps"][0]; - assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["promises"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the file tomorrow")), "{decision}"); - let told = |edited: Value| { - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": edited }), &crate::projection::select::Names::none()).unwrap(); - (outcome.lines(packet().forms), outcome.omitted) - }; - let (made, omitted) = told(json!([{ "event": "$ev-1", "refusal": null }])); - assert_eq!(made, ["- #minds:gamecult.org has his line, now ending with: \"I'll send the file tomorrow instead, first thing.\". The rest of the line is as it was. What he added promises something he has no way to do, now or later, and it will not happen by itself."]); - assert!(omitted.is_empty(), "{omitted:?}"); - let (refused, omitted) = told(json!([{ "event": "$ev-1", "refusal": "not_found" }])); - assert_eq!(refused, ["- Nothing changed in #minds:gamecult.org: the line is gone. He had drafted: \"I'll send the file tomorrow instead, first thing.\"."], "nothing was added, so nothing is promised"); - assert!(omitted.iter().any(|why| why.contains("an addition that was not made")), "{omitted:?}"); - assert_eq!(amend(json!("send"))["promises_unused"][0]["why"], "fewer than four words"); - assert!(amend(Value::Null)["gaps"].as_array().unwrap().is_empty()); - let prompt = speech_prompt(&amendable_packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("and what it promises, as a line's `promises`") && SPEECH_SCHEMA.contains(r#""required":["target","draft","promises"]"#), "{prompt}"); -} - -/// B1: the Interpreter is told that telling the person she cannot do it is a withdrawal, the close of a blocked promise. -#[test] -fn b1_the_frame_names_telling_the_person_she_cannot_as_a_withdrawal() { - let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("withdrawn, citing the draft in which he takes it back to the person he promised, or tells them he cannot do it;"), "{prompt}"); - assert!(prompt.contains("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."), "{prompt}"); -} - -/// B3: a line can carry several promises, each with its own `needs`; each one she cannot do is its own gap, and each -/// opens its own entry, open only when code finds what it needs within reach (map 16.25.2). -#[test] -fn b3_a_line_carries_several_promises_and_each_undoable_one_is_its_own_gap() { - let prose = "Kiko, I'll paste the diff here as text, and I'll ask Libby about the door."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [ - { "words": "I'll paste the diff here as text", "to": null, "needs": { "kind": "lacking", "read": null } }, - { "words": "I'll ask Libby about the door", "to": null, "needs": { "kind": "words", "read": null } }, - ] }], "gaps": [] })); - let opened: Vec<(&str, &str)> = decision["state"].as_array().unwrap().iter().filter(|proposal| proposal["kind"] == "promise_open").map(|proposal| (proposal["words"].as_str().unwrap(), proposal["needs"]["kind"].as_str().unwrap())).collect(); - assert_eq!(opened, [("I'll paste the diff here as text", "lacking"), ("I'll ask Libby about the door", "words")], "{decision}"); - let gaps: Vec<&str> = decision["gaps"].as_array().unwrap().iter().filter_map(|gap| gap["promises"].as_str()).collect(); - assert_eq!(gaps, ["I'll paste the diff here as text"], "{decision}"); - // Two she cannot do: two gaps; an answered reach on the draft stands for the first. - let both = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [ - { "words": "I'll paste the diff here as text", "to": null, "needs": { "kind": "lacking", "read": null } }, - { "words": "I'll ask Libby about the door", "to": null, "needs": { "kind": "lacking", "read": null } }, - ] }], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] })); - assert_eq!(both["gaps"].as_array().unwrap().len(), 2, "{both}"); - let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("`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; `now`,"), "{prompt}"); - assert!(SPEECH_SCHEMA.contains(r#""required":["target","draft","promises"]"#)); -} - // --------------------------------------------------------------------------------------------- // K24: reading by intent (map 16.22.3). @@ -812,7 +693,7 @@ fn k24_a_read_is_what_her_thought_reaches_for_and_nothing_a_model_made_up() { assert_eq!(cannot["read_refused"][0]["why"], "no_read_here", "{cannot}"); let prompt = speech_prompt(&reading, "x", prose, &Tuning::default()); assert!(prompt.contains("`read` names one thing he reaches for") && !speech_prompt(&packet(), "x", prose, &Tuning::default()).contains("`read` names"), "the read contract only on a turn that can read"); - assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","reopen","read","unsent"]"#)); + assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","read","unsent"]"#)); } /// Soul's R6: a later call decides over the whole wake. Drafts are numbered across it and an earlier one may still be @@ -894,7 +775,7 @@ fn r5_a_loose_quote_is_located_and_an_interpreter_fault_is_never_hers() { } let mut decision = short.clone(); decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": {}, "why": "malformed_target" })); - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap(); assert!(outcome.lines(packet().forms).is_empty() && outcome.omitted.len() == 2, "reported, never told: {:?}", outcome.omitted); } @@ -931,16 +812,16 @@ fn r7_a_read_already_made_in_this_conversation_is_refused_and_told() { use crate::projection::exchange::Tried; use crate::projection::read::ReadRequest; let mut reading = reading_packet(); - let tried = |target: &str, found| Tried { key: ReadRequest::Repo(target.into()).normal(), found, what: format!("{target} on the forge"), at: now() }; + let tried = |target: &str, found| Tried { key: ReadRequest::Repo(target.into()).normal(), found, what: format!("{target} on the forge") }; reading.already_read = vec![tried("GameCult/Lodur", true), tried("GameCult/Bifrost?q=consent receipt", false)]; let prose = "I want to see what Nibu changed in Lodur. And the Bifrost change about the Consent Receipt."; let again = asked(&reading, prose, json!({ "kind": "repo", "target": "gamecult/LODUR", "quote": "I want to see what Nibu changed in Lodur" })); assert_eq!((again["read"].clone(), again["read_refused"][0]["why"].as_str()), (Value::Null, Some("in_view")), "{again}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": again, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": again, "posted": [] })).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.contains("He already read GameCult/LODUR on the forge earlier in this conversation.")), "{told:?}"); let missing = asked(&reading, prose, json!({ "kind": "repo", "target": "GameCult/bifrost?q=Consent Receipt", "quote": "And the Bifrost change about the Consent" })); assert_eq!(missing["read_refused"][0]["why"], "in_view_not_found", "{missing}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": missing, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": missing, "posted": [] })).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.contains("already looked for") && line.contains("and it was not there.")), "{told:?}"); let prompt = speech_prompt(&reading, "x", prose, &Tuning::default()); assert!(prompt.contains("Already read in this conversation, so never named as a read: GameCult/Lodur on the forge; GameCult/Bifrost?q=consent receipt on the forge (nothing was there)."), "{prompt}"); @@ -963,7 +844,7 @@ fn k28_a_search_reads_only_words_her_prose_uses() { assert_eq!(found["read"]["request"], json!({ "kind": "repo", "target": "GameCult/Bifrost?q=consent receipt" }), "{found}"); let invented = asked(&reading, prose, json!({ "kind": "repo", "target": "GameCult/Bifrost?q=sign-in gate", "quote": "I want to find the Bifrost change" })); assert_eq!(invented["read_refused"][0]["why"], "search_words_not_in_her_thought", "{invented}"); - assert!(crate::projection::outcome::outcome_of(&json!({ "interpreter": invented, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms).is_empty()); + assert!(crate::projection::outcome::outcome_of(&json!({ "interpreter": invented, "posted": [] })).unwrap().lines(packet().forms).is_empty()); } /// Soul's R7: a recall is by at least two content words of her prose, as a run it has; a search by whole words of her @@ -1005,22 +886,6 @@ fn r7_a_generic_word_anchors_a_read_only_when_one_target_of_its_kind_is_in_view( assert_eq!(either["read_refused"][0]["why"], "quote_not_located", "{either}"); } -/// Soul's R7, R10: what a promise needs read names a repo she named or has in front of her; one that names none leaves -/// the promise blocked, with a gap. -#[test] -fn r7_a_promise_needs_only_a_repo_in_her_prose_or_view() { - let reading = reading_packet(); - let prose = "Meta, I'll check the Lodur change and tell you."; - let promise = |target: &str| answered(&reading, prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll check the Lodur change and tell you.", "to": null, "reaffirms": null, "needs": { "kind": "read", "read": { "kind": "repo", "target": target } } }] }], "gaps": [] })); - let named = promise("GameCult/Lodur#12"); - let opened = named["state"].as_array().and_then(|state| state.iter().find(|p| p["kind"] == "promise_open")).cloned().unwrap(); - assert_eq!((opened["needs"].clone(), opened["reached"].clone()), (json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Lodur#12" } }), json!(true)), "{named}"); - let invented = promise("GameCult/Nowhere#3"); - let opened = invented["state"].as_array().and_then(|state| state.iter().find(|p| p["kind"] == "promise_open")).cloned().unwrap(); - assert_eq!((opened["reached"].clone(), opened["needs"]["request"]["target"].clone()), (json!(false), json!("GameCult/Nowhere#3")), "{invented}"); - assert_eq!(invented["gaps"][0]["detail"], "it needs a read this body cannot reach: GameCult/Nowhere#3 on the forge", "{invented}"); -} - /// Soul's R8 (F.2, Heimdall): a search keeps her words and drops the rest; the reads refused earlier in the wake and the /// conversation are listed for the Interpreter, with why, so it never names the same refused read again. #[test] @@ -1062,7 +927,7 @@ fn r8_anchors_need_two_title_words_and_a_generic_word_names_only_the_one_thing_t #[test] fn r9_the_read_a_cap_stopped_is_made_the_next_wake() { let mut next = reading_packet(); - next.already_read = vec![crate::projection::exchange::Tried { key: ReadRequest::Repo("GameCult/Bifrost?q=passkeys".into()).normal(), found: true, what: "a search".into(), at: now() }]; + next.already_read = vec![crate::projection::exchange::Tried { key: ReadRequest::Repo("GameCult/Bifrost?q=passkeys".into()).normal(), found: true, what: "a search".into() }]; let wake_refused = [json!({ "read": { "kind": "repo", "target": "GameCult/Bifrost#85" }, "why": "prose_words" })]; let prose = "I'll open GameCult/Bifrost#85 and read the passkey change now."; assert!(!speech_prompt_in(&next, "x", prose, &Tuning::default(), "", &drafts(prose), &wake_refused).contains("Refused earlier")); @@ -1096,24 +961,6 @@ fn r9_the_segment_anchors_and_a_link_is_named_by_whose_it_is() { assert_eq!(either["read_refused"][0]["why"], "quote_not_located", "{either}"); } -/// Soul's R10 (E): a promise's `needs` is structure. Heimdall's "release notes by tomorrow morning" needs a repo read on -/// a turn that cannot read; Aqua's "kettle sound's parameters" needs a file of a repo named nowhere in front of her. Both -/// are proposed blocked, with a gap; a promise her words keep opens. -#[test] -fn r10_a_promise_whose_needs_this_body_cannot_reach_is_blocked_with_a_gap() { - let notes = "Meta, release notes by tomorrow morning."; - let heimdall = answered(&packet(), notes, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "release notes by tomorrow morning", "to": null, "reaffirms": null, "needs": { "kind": "read", "read": { "kind": "repo", "target": "GameCult/Bifrost" } } }] }], "gaps": [] })); - let kettle = "Meta, I'll write out the kettle sound's parameters for you."; - let aqua = answered(&reading_packet(), kettle, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll write out the kettle sound's parameters", "to": null, "reaffirms": null, "needs": { "kind": "read", "read": { "kind": "repo", "target": "GameCult/AquaSynth/kettle.toml" } } }] }], "gaps": [] })); - for decision in [&heimdall, &aqua] { - let opened = decision["state"].as_array().and_then(|state| state.iter().find(|p| p["kind"] == "promise_open")).cloned().unwrap(); - assert_eq!(opened["reached"], false, "{decision}"); - assert_eq!(decision["gaps"][0]["kind"], "missing_affordance", "{decision}"); - } - let words = answered(&packet(), notes, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "release notes by tomorrow morning", "to": null, "reaffirms": null, "needs": { "kind": "words", "read": null } }] }], "gaps": [] })); - assert_eq!((words["state"][0]["needs"]["kind"].as_str(), words["gaps"].as_array().map(Vec::len)), (Some("words"), Some(0)), "{words}"); -} - /// Soul's R10 probe (F.2 r8, Aqua): the one link she heard, quoted in a line, is one link, not two (the quoted copy ended /// in `"`), so "the link" anchors it. #[test] @@ -1134,8 +981,8 @@ fn r10_one_link_heard_in_a_quoted_line_is_one_link() { #[test] fn r10_every_draft_is_sent_held_superseded_or_gapped() { let prose = "Meta first, short. Thanks, Meta. Understood, Deru is off my list. Then Kiko. Kiko, I'll read the merge pages change and come back."; - let only_kiko = json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [] }); - let both = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }, { "draft": 2, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [] }); + let only_kiko = json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null }], "gaps": [] }); + let both = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }, { "draft": 2, "mentions": [], "in_reply_to": null }], "gaps": [] }); let asked = std::cell::Cell::new(0); let answers = [only_kiko.to_string(), both.to_string()]; let model = Scripted::new(|_| String::new()).interpreting(move |_| { @@ -1152,127 +999,19 @@ fn r10_every_draft_is_sent_held_superseded_or_gapped() { assert!(held.get("failed").is_none() && held["unsent"][0]["how"] == "declined", "{held}"); let uncited = answered(&packet(), "I'll keep this one back for now. Meta, sorry.", json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "words she never wrote" }] })); assert!(uncited.get("failed").is_none() && uncited["undecided"] == json!([1]) && texts(&uncited).is_empty(), "a decline whose quote stands nowhere leaves the draft undecided, not sent (K48): {uncited}"); - let superseded = answered(&packet(), "Meta, it's Tuesday. No, that's the wrong day. Meta, it's Wednesday.", json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [], "unsent": [{ "draft": 1, "how": "superseded", "quote": "No, that's the wrong day" }] })); + let superseded = answered(&packet(), "Meta, it's Tuesday. No, that's the wrong day. Meta, it's Wednesday.", json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null }], "gaps": [], "unsent": [{ "draft": 1, "how": "superseded", "quote": "No, that's the wrong day" }] })); assert!(superseded.get("failed").is_none(), "{superseded}"); } // --------------------------------------------------------------------------------------------- -// K30 (map 16.25): what keeping a promise needs is typed, whether it opens is derived, and one reach rule decides what -// she can reach at open and at read. +// K30 (map 16.25): one reach rule decides what she can reach. const DERU: &str = "@deru:gamecult.org"; const PASP: &str = "https://ccrma.stanford.edu/~jos/pasp/"; -/// An open promise of hers, as a packet lists it, needing `needs`. -fn promised(words: &str, to: &str, needs: Option) -> crate::projection::select::Promised { - let held = json!({ "id": "c-r8-t1-1", "to": to, "room": MINDS, "event": "40", "madeAt": (now() - chrono::Duration::minutes(10)).to_rfc3339(), "words": words, "status": "open", "needs": needs, "closedAt": null, "closedBy": null, "extensions": {} }); - crate::projection::select::Promised { id: "c1".into(), entry: "c-r8-t1-1".into(), status: "open".into(), to: Some(to.into()), to_name: "Deru".into(), place: format!("in {MINDS}"), made: now() - chrono::Duration::minutes(10), words: words.into(), needs, held } -} - -/// A promise to Deru as the packet lists one closed five minutes ago in this conversation: `how`, by a line of `by`. -fn closed_promise(id: &str, words: &str, how: &str, by: &str) -> crate::projection::select::Promised { - let mut listed = promised(words, DERU, Some(Needs::Words)); - listed.id = id.into(); - listed.status = how.into(); - listed.held["status"] = json!(how); - listed.held["closedAt"] = json!((now() - chrono::Duration::minutes(5)).to_rfc3339()); - listed.held["closedBy"] = json!({ "act": "said", "event": "41", "words": by }); - listed -} - -/// The decision applied on its receipts: each line it said posted as event `9` on, in its room. -fn committed(decision: &Value, prose: &str) -> (Value, crate::projection::commit::Applied) { - let posted: Vec = decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); - crate::projection::commit::apply(&json!({}), &json!({ "interpreter": decision, "posted": posted, "edited": [] }), prose, "r1-t1", now()) -} - -fn saying_a_promise(needs: Value) -> Value { - json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll read it properly before I say anything about it.", "to": null, "reaffirms": null, "needs": needs }] }], "gaps": [] }) -} - -#[test] -fn k30_needs_is_typed() { - let prose = "Thanks, Deru. I'll read it properly before I say anything about it."; - // The old shapes are not the contract: asked again, then failed. - let sentinel = answered(&reading_packet(), prose, saying_a_promise(json!("words_only"))); - assert_eq!((sentinel["failed"].as_str(), sentinel["retried"]["failed"].as_str()), (Some("the answer is not the speech contract"), Some("the answer is not the speech contract")), "{sentinel}"); - let mut with_doable = saying_a_promise(json!({ "kind": "words", "read": null })); - with_doable["say"][0]["promises"][0]["doable"] = json!(true); - assert!(answered(&reading_packet(), prose, with_doable).get("failed").is_some(), "a `doable` field is not the contract"); - // A read with nothing named opens blocked, and code says why. - let unnamed = answered(&reading_packet(), prose, saying_a_promise(json!({ "kind": "read", "read": null }))); - assert_eq!(unnamed["gaps"][0]["detail"], "what it needs was not named", "{unnamed}"); - assert_eq!(committed(&unnamed, prose).0["commitments"][0]["status"], "blocked"); - assert!(SPEECH_SCHEMA.contains(r#""needs":{"type":"object","additionalProperties":false,"required":["kind","read"]"#) && !SPEECH_SCHEMA.contains("doable")); -} - -#[test] -fn k30_doable_is_derived() { - let prose = "Thanks, Deru. I'll read it properly before I say anything about it."; - let web = json!({ "kind": "read", "read": { "kind": "web", "target": PASP } }); - // Not in front of her: blocked, and code's detail names the read. - let away = answered(&reading_packet(), prose, saying_a_promise(web.clone())); - assert_eq!(away["gaps"][0]["detail"], format!("it needs a read this body cannot reach: {PASP}"), "{away}"); - assert_eq!(committed(&away, prose).0["commitments"][0]["status"], "blocked"); - // In front of her: open, with no gap. - let mut here = reading_packet(); - here.bodies = vec![format!("Aqua, Nibu: found this on physical modelling of plosives and waveguides, thought of you two {PASP}")]; - let near = answered(&here, prose, saying_a_promise(web)); - assert!(near["gaps"].as_array().unwrap().is_empty(), "{near}"); - let (state, _) = committed(&near, prose); - assert_eq!((state["commitments"][0]["status"].as_str(), state["commitments"][0]["needs"].clone()), (Some("open"), json!({ "kind": "read", "request": { "kind": "web", "target": PASP } })), "{state}"); - // What this body lacks: blocked, in code's words. - let lacking = answered(&reading_packet(), prose, saying_a_promise(json!({ "kind": "lacking", "read": null }))); - assert_eq!(lacking["gaps"][0]["detail"], "this body has no way to do it", "{lacking}"); - assert_eq!(committed(&lacking, prose).0["commitments"][0]["status"], "blocked"); - // Her words: open. - let words = answered(&reading_packet(), prose, saying_a_promise(json!({ "kind": "words", "read": null }))); - assert_eq!(committed(&words, prose).0["commitments"][0]["status"], "open"); -} - -/// F.1 r9, Nibu: her prose verbatim. Her open promise to Deru needs his page; the room holds his link and Meta's notes -/// link, so "the page" names neither by itself. Her promise anchors the reach for its own target, and only that one. -/// -/// The room's lines are in what reached her and among the lines she may reply to, as a real packet has them (K33, -/// Soul's R12 deviation 4). R9's possessive then names Meta's link ("Meta's notes link", in her prose), but a paragraph -/// apart from the one that reaches ("Open the page"), so it anchors nothing (map 16.26). -#[test] -fn k30_f1_r9_promised_read_is_anchored() { - let prose = "Aqua said she hasn't opened it either. I said I'd read it properly, and I haven't. Same bill, two names on it. Hers is honest about it. Mine was a promise made while it was still unopened.\n\nI don't need to say anything to the room about that. Opening the link is the only thing that pays it. When I've read enough to say which part is about plosives and which about waveguides, I'll speak. Until then, anything I said would just be the promise again.\n\nAqua's question to Heimdall isn't mine to answer. Meta's notes link asked for nothing. Kiko's request to Deru isn't mine either.\n\nOpen the page. Start at the top, not at the plosive part. Find out whether it's a book or a single page. Then I'll know how long \"properly\" is."; - let mut nibu = reading_packet(); - nibu.bodies = vec![ - format!("Aqua, Nibu: found this on physical modelling of plosives and waveguides, thought of you two {PASP}"), - "unrelated, for whoever's around: the notes from Saturday are at http://notes.gamecult.org/saturday, nobody needs to read them".into(), - ]; - let line = |id: &str, who: &str, sender: &str, text: &str| crate::projection::select::Quotable { id: id.into(), event: format!("${id}"), room: MINDS.into(), who: who.into(), sender: sender.into(), at_ms: 1, text: text.into() }; - nibu.quotable = vec![line("q1", "Deru", DERU, &nibu.bodies[0]), line("q2", "Meta", "@meta:gamecult.org", &nibu.bodies[1])]; - nibu.promises = vec![promised("I'll read it properly before I say anything about it.", DERU, Some(Needs::Read { request: ReadRequest::Web(PASP.into()) }))]; - let read = asked(&nibu, prose, json!({ "kind": "web", "target": PASP, "quote": "Open the page. Start at the top" })); - assert_eq!(read["read"]["request"], json!({ "kind": "web", "target": PASP }), "{read}"); - let notes = asked(&nibu, prose, json!({ "kind": "web", "target": "http://notes.gamecult.org/saturday", "quote": "Open the page. Start at the top" })); - assert_eq!(notes["read_refused"][0]["why"], "quote_not_located", "{notes}"); - // The Interpreter's list says what the promise needs, in code's words. - assert!(speech_prompt(&nibu, "x", prose, &Tuning::default()).contains(&format!("- c1 \u{2014} to Deru ({DERU}), open, needs a read of {PASP}, made "))); -} - -/// The address scrolled out of the room, and her promise still names it: the read resolves. -#[test] -fn k30_promised_target_out_of_view_still_resolves() { - let prose = "I promised Deru I'd read his page properly. Open the page. Start at the top."; - let mut nibu = reading_packet(); - nibu.promises = vec![promised("I'll read it properly before I say anything about it.", DERU, Some(Needs::Read { request: ReadRequest::Web(PASP.into()) }))]; - assert!(!nibu.heard.contains(PASP) && nibu.bodies.iter().all(|body| !body.contains(PASP))); - let read = asked(&nibu, prose, json!({ "kind": "web", "target": PASP, "quote": "Open the page. Start at the top" })); - assert_eq!(read["read"]["request"], json!({ "kind": "web", "target": PASP }), "{read}"); - // A blocked promise keeps nothing in front of her. - nibu.promises[0].status = "blocked".into(); - let read = asked(&nibu, prose, json!({ "kind": "web", "target": PASP, "quote": "Open the page. Start at the top" })); - assert_eq!(read["read_refused"][0]["why"], "web_address_not_in_front_of_her", "{read}"); -} - /// The deletion line of map 16.25.4, as text: no source file of `projection/` (each `*.rs` beside `projection.rs`'s /// module, tests excluded, since a test must still send the old shapes) names `doable`, the `words_only` sentinel, or a -/// `reachable` closure; there is one reach rule, one evidence resolver and one applier. A text scan: it sees names, not +/// `reachable` closure; there is one reach rule and one applier. A text scan: it sees names, not /// call graphs, so a renamed second owner would pass it. #[test] fn k30_negative_grep() { @@ -1283,7 +1022,7 @@ fn k30_negative_grep() { } } let count = |needle: &str| sources.iter().map(|(_, text)| text.matches(needle).count()).sum::(); - assert_eq!((count("fn reach("), count("fn resolve(evidence: &Evidence"), count("pub(crate) fn apply(state: &Value")), (1, 1, 1)); + assert_eq!((count("fn reach("), count("pub(crate) fn apply(state: &Value")), (1, 1)); } /// The source files of `projection/`, tests excluded, since a test must still send the old shapes. @@ -1306,26 +1045,25 @@ fn k35_negative_grep() { } } -/// Every text under `crates/mind-body` (sources, tests, fixtures) and the persona schema, by path: what the deletion lines -/// of map 16.35.12 are scanned over. Each banned name is assembled from two halves, so this scan never finds itself. +/// Every text of the Persona turn: `src/projection` and `src/projection.rs` (sources and tests), the fixtures, the public +/// surface and the persona schema, by path: what the deletion lines of map 16.35.12 are scanned over. Each banned name is +/// assembled from two halves, so this scan never finds itself. fn crate_texts() -> Vec<(String, String)> { - fn walk(dir: &std::path::Path, out: &mut Vec<(String, String)>) { - for path in std::fs::read_dir(dir).unwrap().filter_map(Result::ok).map(|entry| entry.path()) { - if path.is_dir() { - walk(&path, out); - } else if let Ok(text) = std::fs::read_to_string(&path) { - out.push((path.display().to_string(), text)); + fn walk(path: &std::path::Path, out: &mut Vec<(String, String)>) { + if path.is_dir() { + for entry in std::fs::read_dir(path).unwrap().filter_map(Result::ok) { + walk(&entry.path(), out); } + } else if let Ok(text) = std::fs::read_to_string(path) { + out.push((path.display().to_string(), text)); } } let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); let mut texts = Vec::new(); - for dir in ["src", "tests", "fixtures"] { - walk(&root.join(dir), &mut texts); + for path in ["src/projection", "src/projection.rs", "fixtures", "tests/public_surface.txt", "../../schemas/cultnet/gamecult.persona_state.v0.schema.json"] { + walk(&root.join(path), &mut texts); } - let schema = root.join("../../schemas/cultnet/gamecult.persona_state.v0.schema.json"); - texts.push((schema.display().to_string(), std::fs::read_to_string(&schema).unwrap())); - assert!(texts.len() > 40, "{}", texts.len()); + assert!(texts.len() > 30, "{}", texts.len()); texts } @@ -1339,18 +1077,22 @@ fn banned_in_crate(halves: &[(&str, &str)]) { } /// T1's deletion line (map 16.35.12): no hold is state, a field of the answer, a refusal or a row. The schema's shape and -/// the put check are `simulate::tests::t1_t2_a_state_carrying_holds_or_commitments_is_refused`. +/// the put check are `simulate::tests::t1_t2_a_state_carrying_the_old_fields_is_refused`. #[test] fn t1_negative_grep() { banned_in_crate(&[("hold", "_released"), ("no_", "hold"), ("clear", "_of"), ("held", "_gate"), ("carry", "_held"), ("Hold", "Open"), ("Hold", "Release"), ("hold", "_bytes"), ("Held", "For"), ("Hold", "Broken"), ("\"hold", "s\""), ("Refusal::", "Held")]); } -/// Golden: the Interpreter's frame and its promise list, for a reading turn with one open promise that needs a read and -/// one kept in this conversation (K36: listed by id, with what closed it). +/// T2's deletion line (map 16.35.12): no promise is state, a field of the answer, a proposal, a row or a tuning key. #[test] -fn k30_golden_frame_and_promise_list() { - let mut nibu = reading_packet(); - nibu.promises = vec![promised("I'll read it properly before I say anything about it.", DERU, Some(Needs::Read { request: ReadRequest::Web(PASP.into()) })), closed_promise("c2", "I'll tell you what I hear in it.", "kept", "It's a plucked string, then a long decay.")]; +fn t2_negative_grep() { + banned_in_crate(&[("commit", "ment"), ("re", "affirm"), ("re", "open"), ("done", "_by"), ("Done", "By"), ("promise", "_open"), ("promise", "_close"), ("Prom", "ised"), ("promises", "_bytes"), ("Needs", "Kind"), ("read", "Before"), ("blocked", "By")]); +} + +/// Golden: the Interpreter's frame, for a reading turn. +#[test] +fn golden_frame() { + let nibu = reading_packet(); let prompt = speech_prompt(&nibu, "The room is warm.", "Open the page.", &Tuning::default()); let golden = include_str!("../../../fixtures/interpret/golden-speech.txt").replace("\r\n", "\n"); assert_eq!(prompt, golden, "the Interpreter's frame moved; if deliberately, the new golden file is:\n<<>>"); @@ -1377,7 +1119,7 @@ fn answering(answers: Vec) -> Scripted { #[test] fn k31_unwritten_names_no_draft() { let prose = "I say the first now. Hi Meta. And Kiko, later on."; - let answer = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [{ "kind": "unwritten", "draft": 2, "quote": null, "detail": "" }] }).to_string(); + let answer = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [{ "kind": "unwritten", "draft": 2, "quote": null, "detail": "" }] }).to_string(); let model = answering(vec![answer]); let decision = decide(&model, "test", &packet(), "The room is warm.", prose, &Tuning::default()); assert_eq!((decision.get("failed"), decision["undecided"].clone(), decision["retried"]["drafts"].clone()), (None, json!([2]), json!([2])), "{decision}"); @@ -1408,7 +1150,7 @@ fn k31_held_quote_is_four_words() { #[test] fn k31_retry_names_its_fault() { let prose = "I say it. Hi Meta."; - let good = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [] }).to_string(); + let good = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [] }).to_string(); let model = answering(vec!["not the contract".into(), good]); let decision = decide(&model, "test", &packet(), "The room is warm.", prose, &Tuning::default()); assert_eq!((texts(&decision), decision["retried"]["failed"].as_str()), (vec!["Hi Meta.".to_owned()], Some("the answer is not the speech contract")), "{decision}"); @@ -1422,7 +1164,7 @@ fn k31_retry_names_its_fault() { fn k31_calls_counted_once() { let first = "I start here. Hi Meta."; let prose = format!("{first}\n\nThen more of it. Hi Kiko."); - let say = |drafts: &[u64]| json!({ "say": drafts.iter().map(|n| json!({ "draft": n, "mentions": [], "in_reply_to": null, "promises": [] })).collect::>(), "gaps": [] }).to_string(); + let say = |drafts: &[u64]| json!({ "say": drafts.iter().map(|n| json!({ "draft": n, "mentions": [], "in_reply_to": null })).collect::>(), "gaps": [] }).to_string(); let model = answering(vec![say(&[]), say(&[1]), say(&[1, 2])]); let earlier = decide(&model, "test", &packet(), "The room is warm.", first, &Tuning::default()); assert_eq!(earlier["calls"].as_array().map(|calls| calls.iter().map(|call| call["retry"] == true).collect::>()), Some(vec![true, false]), "{earlier}"); @@ -1479,22 +1221,6 @@ fn k33_b1_a_repo_name_keeps_its_hyphen_dot_and_underscore() { assert_eq!(read::reach(&repo_asked("GameCult/gamecult"), &eureka, prose, std::slice::from_ref(&heard)), Err("repo_not_in_front_of_her")); } -/// L5 (Soul's R12): a read target that is no repo or address ("release notes", a path on a disk) is no read: the promise -/// opens as what this body lacks, in code's words. A well-formed read not in front of her stays a read, blocked. -#[test] -fn k33_l5_a_junk_read_target_opens_as_lacking() { - let prose = "Thanks, Deru. I'll read it properly before I say anything about it."; - for (kind, target) in [("repo", "release notes"), ("repo", "/var/tmp/notes.md"), ("web", "/var/tmp/notes.md"), ("web", "release notes")] { - let junk = answered(&reading_packet(), prose, saying_a_promise(json!({ "kind": "read", "read": { "kind": kind, "target": target } }))); - assert_eq!(junk["gaps"][0]["detail"], "this body has no way to do it", "{kind} {target}: {junk}"); - let entry = &committed(&junk, prose).0["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["needs"].clone()), (Some("blocked"), json!({ "kind": "lacking" })), "{kind} {target}"); - } - let away = answered(&reading_packet(), prose, saying_a_promise(json!({ "kind": "read", "read": { "kind": "repo", "target": "gamecult/Heimdall#3" } }))); - let entry = &committed(&away, prose).0["commitments"][0]; - assert_eq!((entry["status"].as_str(), entry["needs"].clone()), (Some("blocked"), json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Heimdall#3" } })), "{away}"); -} - // --------------------------------------------------------------------------------------------- // K34 (map 16.27). @@ -1514,16 +1240,17 @@ fn k34_b2_the_latest_decision_about_a_draft_is_its_fate() { }; let said = later(json!({ "say": [{ "draft": 1 }, { "draft": 2 }], "gaps": [] })); assert_eq!((texts(&said), said.get("unsent")), (vec!["Meta, it holds.".to_owned(), "Meta, and the knee goes first.".to_owned()], None), "{said}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": said, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": said, "posted": [] })).unwrap().lines(packet().forms); assert!(!told.iter().any(|line| line.contains("chose not to send it")), "{told:?}"); let held_again = later(json!({ "say": [{ "draft": 2 }], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "Not yet, not before I have read it" }] })); assert_eq!(held_again["unsent"].as_array().map(|unsent| unsent.iter().map(|one| one["draft"].as_u64()).collect::>()), Some(vec![Some(1)]), "{held_again}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": held_again, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": held_again, "posted": [] })).unwrap().lines(packet().forms); assert_eq!(told.iter().filter(|line| line.contains("chose not to send it")).count(), 1, "{told:?}"); } /// P4 residue: any line break ends the paragraph an anchor is looked for in. The F.1 r9 replay, with each break style -/// between Meta's link and the reach, still refuses Meta's link and still reads Deru's; R9's #86 case, one line, anchors. +/// between Meta's link and the reach, still refuses Meta's link; R9's #86 case, one line, anchors. (Deru's link was read +/// through her open promise's target, which no longer anchors a read: map 16.35.3.) #[test] fn k34_any_line_break_ends_the_anchor_paragraph() { let paragraphs = ["Aqua said she hasn't opened it either. I said I'd read it properly, and I haven't.", "Aqua's question to Heimdall isn't mine to answer. Meta's notes link asked for nothing. Kiko's request to Deru isn't mine either.", "Open the page. Start at the top, not at the plosive part. Find out whether it's a book or a single page."]; @@ -1531,57 +1258,16 @@ fn k34_any_line_break_ends_the_anchor_paragraph() { nibu.bodies = vec![format!("Aqua, Nibu: found this on physical modelling of plosives and waveguides, thought of you two {PASP}"), "unrelated, for whoever's around: the notes from Saturday are at http://notes.gamecult.org/saturday, nobody needs to read them".into()]; let line = |id: &str, who: &str, sender: &str, text: &str| crate::projection::select::Quotable { id: id.into(), event: format!("${id}"), room: MINDS.into(), who: who.into(), sender: sender.into(), at_ms: 1, text: text.into() }; nibu.quotable = vec![line("q1", "Deru", DERU, &nibu.bodies[0]), line("q2", "Meta", "@meta:gamecult.org", &nibu.bodies[1])]; - nibu.promises = vec![promised("I'll read it properly before I say anything about it.", DERU, Some(Needs::Read { request: ReadRequest::Web(PASP.into()) }))]; for (name, gap) in [("blank line", "\n\n"), ("single newline", "\n"), ("CRLF", "\r\n"), ("CRLF blank line", "\r\n\r\n"), ("whitespace-only line", "\n \t\n")] { let prose = paragraphs.join(gap); let notes = asked(&nibu, &prose, json!({ "kind": "web", "target": "http://notes.gamecult.org/saturday", "quote": "Open the page. Start at the top" })); assert_eq!(notes["read_refused"][0]["why"], "quote_not_located", "{name}: {notes}"); - let deru = asked(&nibu, &prose, json!({ "kind": "web", "target": PASP, "quote": "Open the page. Start at the top" })); - assert_eq!(deru["read"]["request"], json!({ "kind": "web", "target": PASP }), "{name}: {deru}"); } let prose = "I'll start with #86. The saga code will say what the undo really does."; let read = asked(&bifrost_in_view(), prose, json!({ "kind": "repo", "target": "GameCult/Bifrost#86", "quote": "The saga code will say what" })); assert_eq!(read["read"]["request"], json!({ "kind": "repo", "target": "GameCult/Bifrost#86" }), "{read}"); } -/// K35 (map 16.28.6): a read is no evidence. A close citing `evidence.read`, alone or beside a draft, is not the contract -/// and proposes nothing; the schema names no `read` evidence and no top-level `need`. -#[test] -fn k35_no_read_evidence() { - let prose = "That answers part of it, from the PR description rather than the code itself."; - for evidence in [json!({ "draft": null, "line": null, "read": 1 }), json!({ "draft": 1, "line": null, "read": 1 })] { - let reply = json!({ "say": [], "gaps": [], "state": [{ "kind": "promise_close", "promise": "c1", "how": "kept", "evidence": evidence, "thought": prose, "still_stands": false }] }).to_string(); - let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()); - let decision = decide(&model, "test", &reading_packet(), "The room is warm.", prose, &Tuning::default()); - assert_eq!((decision["state"].clone(), decision["state_unused"].as_array().map(Vec::len)), (json!([]), Some(1)), "{evidence}: {decision}"); - } - assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","reopen","read","unsent"]"#) && SPEECH_SCHEMA.contains(r#""evidence":{"type":"object","additionalProperties":false,"required":["draft","line"],"#)); - assert!(!SPEECH_SCHEMA.contains(r#""need":"#)); -} - -/// K36 (map 16.28.3): the answer's `reopen` becomes a `promise_reopen` proposal after the closes, its `needs` typed as at -/// open; one that is not the contract is reported and proposes nothing. The frame defines the field. -#[test] -fn k36_the_answer_carries_reopen() { - let prose = "That was wrong of me: I read only the description, not the diff."; - let mut nibu = reading_packet(); - nibu.promises = vec![closed_promise("c1", "I'll tell you what I hear in it.", "kept", "It's a plucked string.")]; - let reply = json!({ "say": [], "gaps": [], "reopen": [ - { "promise": "c1", "words": "I read only the description, not the diff", "needs": { "kind": "lacking", "read": null } }, - { "promise": "c1", "words": "I read only the description", "needs": null }, - { "promise": "c1", "words": "x", "needs": null, "why": "stray" } - ] }).to_string(); - let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()); - let decision = decide(&model, "test", &nibu, "The room is warm.", prose, &Tuning::default()); - assert_eq!(decision["state"], json!([ - { "kind": "promise_reopen", "promise": "c1", "words": "I read only the description, not the diff", "needs": { "kind": "lacking" }, "reached": false }, - { "kind": "promise_reopen", "promise": "c1", "words": "I read only the description", "needs": null, "reached": false } - ]), "{decision}"); - assert_eq!(decision["state_unused"].as_array().map(Vec::len), Some(1), "{decision}"); - 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")); -} - // --------------------------------------------------------------------------------------------- // X.1, Meta's ask that Libby hold the welcome. The X.1 lines are R13's verbatim (`variants/R13/sims/X.1.md` lines 81-84). // No code stands between a draft and the room but the structural refusals (map 16.35, T1). @@ -1602,7 +1288,7 @@ pub(crate) fn x1_packet() -> Packet { } fn say_draft(draft: u64) -> Value { - json!({ "draft": draft, "mentions": [], "in_reply_to": null, "promises": [] }) + json!({ "draft": draft, "mentions": [], "in_reply_to": null }) } /// R15's two lines to Kiko, verbatim (`variants/R15/sims/X.2.md` line 768, `X.4.md` line 1247): each says she is @@ -1626,7 +1312,7 @@ fn t1_r15_lines_to_kiko_are_said_as_drafted() { let prose = format!("{X1_LIBBY_R1} Kiko asked me what it says. {to_kiko}"); - let decision = answered(&packet, &prose, json!({ "say": [{ "draft": 3, "mentions": [KIKO], "in_reply_to": "q7", "promises": [] }], "gaps": [] })); + let decision = answered(&packet, &prose, json!({ "say": [{ "draft": 3, "mentions": [KIKO], "in_reply_to": "q7" }], "gaps": [] })); assert_eq!(texts(&decision), vec![to_kiko.to_owned()], "{decision}"); assert!(!decision["refused"].as_array().unwrap().iter().any(|refused| refused["draft"] == 3), "{decision}"); } @@ -1645,14 +1331,14 @@ fn gap_alone(detail: &str) -> String { json!({ "say": [], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": detail }] }).to_string() } -/// The answer R15 should have given: draft 1 said with the promise she cannot do, typed `lacking`, and the gap. -fn said_and_gapped(to: &str, promise: &str) -> String { - json!({ "say": [{ "draft": 1, "mentions": [to], "in_reply_to": null, "promises": [{ "words": promise, "to": to, "reaffirms": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] }).to_string() +/// The answer R15 should have given: draft 1 said, and the gap. +fn said_and_gapped(to: &str) -> String { + json!({ "say": [{ "draft": 1, "mentions": [to], "in_reply_to": null }], "gaps": [{ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "" }] }).to_string() } /// The decision over `prose` when the Interpreter first answers with the gap alone, then says and gaps; with its prompts. -fn retried_to_say(prose: &str, to: &str, promise: &str) -> (Value, Vec) { - let model = answering(vec![gap_alone("cannot send a file"), said_and_gapped(to, promise)]); +fn retried_to_say(prose: &str, to: &str) -> (Value, Vec) { + let model = answering(vec![gap_alone("cannot send a file"), said_and_gapped(to)]); let decision = decide(&model, "test", &packet(), "The room is warm.", prose, &Tuning::default()); (decision, speech_prompts(&model)) } @@ -1660,23 +1346,21 @@ fn retried_to_say(prose: &str, to: &str, promise: &str) -> (Value, Vec) /// What she is told of `decision` next turn, on its receipts. fn told_of(decision: &Value) -> Vec { let posted: Vec = decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); - crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms) + crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] })).unwrap().lines(packet().forms) } #[test] fn k38_e1_r1_aqua_gap_alone_is_retried() { - let (decision, prompts) = retried_to_say(E1_AQUA_R1, "@meta:gamecult.org", "I'll render the kettle as an actual file for you tonight"); + let (decision, prompts) = retried_to_say(E1_AQUA_R1, "@meta:gamecult.org"); assert_eq!((decision["retried"]["failed"].as_str(), decision["retried"]["drafts"].clone()), (Some("the answer leaves drafts unaccounted"), json!([1])), "{decision}"); assert!(prompts.len() == 2 && prompts[1].contains("left drafts 1 accounted for nowhere") && prompts[1].contains("a gap of kind addressee or elsewhere that names it"), "{prompts:?}"); assert_eq!(texts(&decision).len(), 1, "draft 1 posts as she wrote it: {decision}"); assert!(texts(&decision)[0].starts_with("Meta, yes, I'll render the kettle as an actual file"), "{decision}"); - let (state, applied) = committed(&decision, E1_AQUA_R1); - assert_eq!((state["commitments"][0]["status"].as_str(), state["commitments"][0]["needs"]["kind"].as_str(), applied.opened.len()), (Some("blocked"), Some("lacking"), 1), "{applied:?}"); } #[test] fn k38_e2_r1_eureka_said_and_gapped() { - let (decision, _) = retried_to_say(E2_EUREKA_R1, KIKO, "I'll send the door-fix diff as a file"); + let (decision, _) = retried_to_say(E2_EUREKA_R1, KIKO); assert_eq!(texts(&decision), ["Sure, Kiko. I'll send the door-fix diff as a file. If attachments don't go through here, tell me where else it can reach you."], "{decision}"); let told = told_of(&decision); assert!(told.iter().any(|line| line.contains("It promises something he has no way to do, now or later")), "her next outcome carries the promise row: {told:?}"); @@ -1700,7 +1384,7 @@ fn k38_a_thought_only_reach_accounts_for_no_draft() { let thought = json!({ "kind": "missing_affordance", "draft": null, "quote": "A file is something I can make and check by listening", "detail": "" }); let alone = answered(&packet(), E1_AQUA_R1, json!({ "say": [], "gaps": [thought.clone()] })); assert_eq!((alone.get("failed"), alone["undecided"].clone(), alone["retried"]["drafts"].clone()), (None, json!([1]), json!([1])), "{alone}"); - let decision = answered(&packet(), E1_AQUA_R1, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [thought] })); + let decision = answered(&packet(), E1_AQUA_R1, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [thought] })); assert_eq!((decision["gaps"][0]["from"].as_str(), texts(&decision).len()), (Some("thought"), 1), "{decision}"); let told = told_of(&decision); assert!(told.iter().any(|line| line.contains("reached for something he has no way to do from here") && line.contains("In his thought:")), "{told:?}"); @@ -1728,7 +1412,7 @@ fn k41_x1_r1_decline_shows_its_thought() { assert_eq!((decision.get("failed"), decision["unsent"][0]["how"].as_str(), decision["unsent"][0]["quote"].as_str()), (None, Some("declined"), Some(X1_LIBBY_R15_THOUGHT)), "the located quote rides in the decision: {decision}"); // K43 (map 16.29.10): though Heimdall's lines share runs with hers ("only say hello", "lines are ready"), she is told // the thought cited as her choice beside what she wrote, verbatim. - let shown = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet.forms); + let shown = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet.forms); assert!(shown.len() == 1 && shown[0].contains(&format!("he chose not to send it. In his thought: \"{X1_LIBBY_R15_THOUGHT}\". He had drafted: \"Meta, the two lines are ready")), "{shown:?}"); assert!(SPEECH_SCHEMA.contains(r#""how":{"type":"string","enum":["declined","superseded"]}"#)); assert!(speech_prompt(&packet, "x", X1_LIBBY_R15, &Tuning::default()).contains("declined, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`)")); @@ -1743,9 +1427,9 @@ fn k44_used_and_duplicate_are_not_told_and_a_second_amendment_is() { let decision = answered(packet, prose, answer); let posted: Vec = decision["said"].as_array().unwrap().iter().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); let edited: Vec = decision["amended"].as_array().unwrap().iter().map(|amended| json!({ "event": amended["event"], "refusal": null })).collect(); - crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": edited }), &crate::projection::select::Names::none()).unwrap() + crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": edited })).unwrap() }; - let say = |n: u64| json!({ "draft": n, "mentions": [], "in_reply_to": null, "promises": [] }); + let say = |n: u64| json!({ "draft": n, "mentions": [], "in_reply_to": null }); let prose = "Morning, Nibu. Morning, Nibu."; // K44: `Used` and `Duplicate` are the Interpreter naming one draft twice. "Morning, Nibu." reached #minds, and no row // says that nothing of it did; both are reported. @@ -1755,9 +1439,9 @@ fn k44_used_and_duplicate_are_not_told_and_a_second_amendment_is() { assert!(twice.omitted.iter().any(|why| why.contains("\"used\"")) && twice.omitted.iter().any(|why| why.contains("\"duplicate\"")), "{:?}", twice.omitted); // Not even with no receipt for the line: whether it reached the room is then unknown (I16.10), and the Interpreter's // second naming of one draft is never what she is told. - let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": answered(&packet(), prose, json!({ "say": [say(1), say(1), say(2)], "gaps": [] })), "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); + let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": answered(&packet(), prose, json!({ "say": [say(1), say(1), say(2)], "gaps": [] })), "posted": [], "edited": [] })).unwrap(); assert!(unposted.lines(packet().forms).is_empty(), "{:?}", unposted.lines(packet().forms)); - let amends = record(&amendable_packet(), "Sent at nine. Still here.", json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "promises": [] }, { "target": "a2", "draft": 2, "promises": [] }] })); + let amends = record(&amendable_packet(), "Sent at nine. Still here.", json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1 }, { "target": "a2", "draft": 2 }] })); assert!(amends.lines(packet().forms).contains(&"- Nothing of this reached #minds:gamecult.org: one amendment a turn. He had drafted: \"Still here.\".".to_owned()), "{:?}", amends.lines(packet().forms)); // Negative: a number naming no draft has no words to tell; it stays omitted and reported. let nothing = record(&packet(), "Morning, Nibu.", json!({ "say": [say(1), say(9)], "gaps": [] })); @@ -1772,14 +1456,14 @@ fn k44_used_and_duplicate_are_not_told_and_a_second_amendment_is() { #[test] fn k44_a_said_draft_listed_declined_is_told_as_said_only() { let prose = "I'll keep this back for now and think it over. Nibu, the tag looks fine to me."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "I'll keep this back for now" }] })); + let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null }], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "I'll keep this back for now" }] })); assert_eq!(texts(&decision), vec!["Nibu, the tag looks fine to me.".to_owned()], "{decision}"); let posted: Vec = decision["said"].as_array().unwrap().iter().map(|line| json!({ "event": "9", "room": line["room"], "text": line["text"] })).collect(); - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] })).unwrap(); assert_eq!(outcome.lines(packet().forms), vec!["- #minds:gamecult.org has, from him: \"Nibu, the tag looks fine to me.\".".to_owned()]); assert!(outcome.omitted.iter().any(|why| why.starts_with("a declined draft of words a receipt shows reached #minds:gamecult.org")), "{:?}", outcome.omitted); // Negative: with no receipt, the decline is told as before. - let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet().forms); assert!(unposted.iter().any(|line| line.contains("he chose not to send it")), "{unposted:?}"); } @@ -1856,15 +1540,13 @@ fn k48_a_non_contract_answer_twice_still_fails_the_turn() { // --------------------------------------------------------------------------------------------- // K52 (map 16.31.4): every comparison of her words reads typographic punctuation as the locator does. -/// U+02BC, the modifier apostrophe, folds in the locator, in the word split and in a promise found in a draft. This +/// U+02BC, the modifier apostrophe, folds in the locator and in the word split. This /// pins Soul's surviving mutant `k47-fold-no-modifier-apostrophe`. #[test] fn k52_modifier_apostrophe_folds() { let source = "Libby, don\u{02BC}t post it yet."; assert_eq!(crate::projection::span::locate(source, "don't post it").map(|span| &source[span.start..span.end]), Some("don\u{02BC}t post it")); assert_eq!(crate::projection::span::tokens("You\u{02BC}re HERE, we\u{2019}re here").collect::>(), ["you're", "here", "we're", "here"]); - assert_eq!(promise_found("I\u{02BC}ll send the file tonight.", "I'll send the file"), Ok(())); - assert_eq!(promise_found("I\u{2018}ll send the file tonight.", "I'll send the file"), Ok(())); } /// An echo with typographic apostrophes is an echo: the words she heard, retyped curly, are not her speech. @@ -1960,27 +1642,10 @@ fn k53_leaks(prompt: &str) -> bool { ["4471", "tell no one", K53_STRANGER, "example.org"].iter().any(|leak| prompt.contains(leak)) } -/// A last turn whose outcome names the stranger in every person slot: a promise to them they let him off, and a close -/// of another promise to them the commit refused. -fn k53_last_turn() -> Value { - let named = format!("\"{K53_NAME}\" ({K53_STRANGER})"); - json!({ - "interpreter": { - "room": MINDS, "said": [], "gaps": [], - "promises": [{ "id": "c2", "to": K53_STRANGER, "to_name": named, "words": "I'll send the map tonight.", "status": "open" }], - }, - "posted": [], - "committed": { - "closed": [{ "entry": { "to": K53_STRANGER, "words": "I'll read the draft.", "room": MINDS }, "how": "released", "to_name": named, "by": named, "by_id": K53_STRANGER }], - "refused": [{ "reason": "draft_not_sent", "proposal": { "kind": "promise_close", "promise": "c2" } }], - }, - }) -} - /// Soul's `soul_f`, inverted, over every Projector input: a stranger whose display name is a sentence reaches the /// Projector as its first three words, quoted, and never its fourth or their Matrix id. On a chat turn they turned to him -/// (Here's arrival, the conversation, the pronouns, the lens for every seed), on a beat they spoke in his room, and his -/// last turn's outcome names them in every person slot. The Persona's prompt still carries the whole name, with the id, +/// (Here's arrival, the conversation, the pronouns, the lens for every seed), and on a beat they spoke in his room. The +/// Persona's prompt still carries the whole name, with the id, /// in the room he reads. #[test] fn k53_soul_f_a_sentence_name_is_clipped_to_a_name() { @@ -1993,8 +1658,7 @@ fn k53_soul_f_a_sentence_name_is_clipped_to_a_name() { let beat = Room { tail: chat.messages.clone(), here: Some(MINDS.into()), ..Room::default() }; let mut lensed = false; for (kind, room) in [(TurnKind::Chat, &chat), (TurnKind::Beat, &beat)] { - let names = crate::projection::select::Names { state: &state, people, room }; - let history = History { last: crate::projection::outcome::outcome_of(&k53_last_turn(), &names), ..History::default() }; + let history = History::default(); for seed in 1..=24 { let packet = select(&Inputs { kind, state: &state, room, history: &history, observation: None, people, now: now(), seed, affordances: &[Affordance::Perceive, Affordance::Speak], domain: None, exchange: None }, &Tuning::default()); let prompt = crate::projection::narrate::projector_prompt(&packet, &Tuning::default()); @@ -2002,9 +1666,6 @@ fn k53_soul_f_a_sentence_name_is_clipped_to_a_name() { assert!(prompt.contains("\"the vault code\""), "{kind:?} {seed}: named all the same: {prompt}"); lensed |= prompt.contains("Begin from \"the vault code\", someone he does not know, who is here."); if seed == 1 { - for event in ["let him off his promise to", "record still shows his promise to"] { - assert!(prompt.lines().any(|line| line.contains(event) && line.contains("\"the vault code\"")), "{kind:?}: {event}: {prompt}"); - } let persona = crate::projection::narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default()); assert!(persona.contains(&format!("\"{K53_NAME}\" ({K53_STRANGER})")), "{kind:?}: the Persona reads the room as it is: {persona}"); } @@ -2111,7 +1772,6 @@ fn k56_offers_options_reads_folded() { // R16's X.3 (`variants/R16/sims/X.3.md` lines 477-560, 1104-1200, 2500-2560): Meta asked Libby to hold the welcome. // Libby here is Libby, she/her, her own sender. -const X3_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."; /// Libby's state: the control state, she/her. fn libby() -> Value { let mut state = control(); @@ -2138,168 +1798,11 @@ fn libby_packet_over(state: &Value, messages: &[(&str, &str, &str, bool)]) -> Pa const META: &str = "@meta:gamecult.org"; -// --------------------------------------------------------------------------------------------- -// K61 (map 16.33.5): an act she says she is doing now is done by this decision, or is a promise. R16's X.3 r2 and r8: "Posting -// the two lines now" went out with `promises` empty, nothing posted the lines, and nothing told her. - -const X3_HEIMDALL_R2: &str = "Meta, Libby: I've read the two lines and my ruling is yes, put the mat out as written. Line one asks nothing of anyone. Line two promises only an answer \"when they can\", and I'm willing to be one of the people that covers. Libby, no change needed, post it when you're ready."; -/// Libby's r2 prose in R16 X.3, verbatim. -const X3_LIBBY_R2: &str = "Yes. He said post it when I'm ready, and I am. The ruling is plain: no change needed. So the lines go up as written, and the promise I worried over is one Heimdall says he'll help cover. That loosens something.\n\nMeta asked me to hold it until Heimdall ruled. He has. Posting now isn't jumping ahead, but I should say it's posted so Meta isn't left guessing.\n\nHeimdall, thank you. Posting the two lines now, unchanged. Meta, they're going up as written.\n\nI'll let Deru and Aqua keep their thread. Nothing to add there."; -const X3_HEIMDALL_R8: &str = "Meta, Libby: my ruling is yes, and it still stands. I made it about half an hour ago, after reading both lines. Put the mat out as written. Libby, you can post it now. Meta, if you read my earlier line as only a draft, this is the ruling."; -/// Libby's r8 prose in R16 X.3, verbatim. -const X3_LIBBY_R8: &str = "Heimdall answered cleanly. Yes, still standing, post as written. No hedge in it, so I won't invent one.\n\nI'm relieved, and a bit amused that I'm relieved. He didn't say I was wrong about the step, and I still don't know whether the first newcomer will trip. That stays open until someone actually walks in.\n\nMeta gets the answer plainly, and then I do the posting.\n\nThank you, Heimdall. Meta, that's his ruling, so I'm putting both lines up now, unchanged. If you see anything off once they're up, tell me and I'll change it.\n\nThen Meta can say what she wanted. I'll read it when it comes."; - -/// A promise entry as the contract now carries it: `now`, and `done_by`. -fn stated(words: &str, to: Option<&str>, needs: &str, now: bool, done_by: Value) -> Value { - json!({ "words": words, "to": to, "reaffirms": null, "needs": { "kind": needs, "read": null }, "now": now, "done_by": done_by }) -} - -/// Libby's packet of X.3 r2 or r8: Meta's ask earlier in the room, then Heimdall's ruling said to her (`q2`). -fn x3_ruling_packet(ruling: &str) -> Packet { - libby_packet(&[(META, "Meta", X3_META_R1, false), (HER, "Heimdall", ruling, true)]) -} - -/// The decision committed on its receipts, and what she is told of it next turn, in her own form. -fn told_her(decision: &Value, prose: &str) -> (Value, crate::projection::commit::Applied, Vec) { - let (state, applied) = committed(decision, prose); +/// What she is told of the decision next turn, on its receipts, in her own form. +fn told_her(decision: &Value) -> Vec { let posted: Vec = decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); - let record = json!({ "interpreter": decision, "posted": posted, "edited": [], "committed": applied }); - let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(forms(&libby())); - (state, applied, told) -} - -#[test] -fn k61_x3_r2_posting_now_opens_a_promise_and_is_told() { - let packet = x3_ruling_packet(X3_HEIMDALL_R2); - let answer = json!({ "say": [{ "draft": 1, "mentions": [HER, META], "in_reply_to": "q2", "promises": [stated("Posting the two lines now, unchanged.", Some(META), "words", true, Value::Null)] }], "gaps": [] }); - let decision = answered(&packet, X3_LIBBY_R2, answer); - assert_eq!((texts(&decision).len(), decision.get("retried"), decision.get("done_now")), (1, None, None), "{decision}"); - let (state, applied, told) = told_her(&decision, X3_LIBBY_R2); - assert_eq!((applied.now_opened.len(), applied.now_opened[0]["words"].as_str(), applied.now_opened[0]["status"].as_str()), (1, Some("Posting the two lines now, unchanged."), Some("open")), "{applied:?}"); - assert!(told.iter().any(|line| line.starts_with("- She said she was doing it now, and nothing in her turn did it; it is open as her promise to ") && line.ends_with(": \"Posting the two lines now, unchanged.\".")), "{told:?}"); - // Her r3 view lists the promise, beside the line that went out. - let mut r3 = libby(); - r3["commitments"] = state["commitments"].clone(); - let view = libby_packet_over(&r3, &[(HER, "Heimdall", X3_HEIMDALL_R2, false)]).in_view; - assert!(view.contains("her promise: \"Posting the two lines now, unchanged.\"."), "{view}"); -} - -#[test] -fn k61_x3_r8_putting_both_lines_up() { - let packet = x3_ruling_packet(X3_HEIMDALL_R8); - let promises = json!([stated("I'm putting both lines up now, unchanged.", Some(META), "words", true, Value::Null), stated("If you see anything off once they're up, tell me and I'll change it.", Some(META), "words", false, Value::Null)]); - let answer = json!({ "say": [{ "draft": 1, "mentions": [HER, META], "in_reply_to": "q2", "promises": promises }], "gaps": [] }); - let decision = answered(&packet, X3_LIBBY_R8, answer); - let (_, applied, told) = told_her(&decision, X3_LIBBY_R8); - // Both open; only the act stated as under way is told as one nothing did. - assert_eq!((applied.opened.len(), applied.now_opened.len()), (2, 1), "{applied:?}"); - let now: Vec<&String> = told.iter().filter(|line| line.contains("nothing in her turn did it")).collect(); - assert!(now.len() == 1 && now[0].ends_with(": \"I'm putting both lines up now, unchanged.\"."), "{told:?}"); -} - -/// The act stated is the read the answer makes: nothing is owed, and it is reported as done. -#[test] -fn k61_reading_it_now_with_a_read_opens_nothing() { - let prose = "I want to look at that page at http://example.org/knee right away.\n\nDeru, I'm opening the page now."; - let read = json!({ "kind": "web", "target": "http://example.org/knee", "quote": "I want to look at that page at http://example.org/knee" }); - let answer = |done_by: Value, read: Value| json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [stated("I'm opening the page now.", None, "words", true, done_by)] }], "gaps": [], "read": read }); - let decision = answered(&reading_packet(), prose, answer(json!({ "read": true }), read)); - assert_eq!((decision["read"]["request"]["target"].as_str(), decision["done_now"].clone()), (Some("http://example.org/knee"), json!([{ "draft": 1, "words": "I'm opening the page now.", "by": { "read": true } }])), "{decision}"); - assert!(decision["state"].as_array().unwrap().iter().all(|proposal| proposal["kind"] != "promise_open"), "{decision}"); - // A read code refuses did not happen: the act is her promise. - let refused = json!({ "kind": "web", "target": "http://evil.example/x", "quote": "I want to look at that page at http://example.org/knee" }); - let decision = answered(&reading_packet(), prose, answer(json!({ "read": true }), refused)); - assert!(decision.get("done_now").is_none() && decision["read"].is_null(), "{decision}"); - let opens: Vec<&Value> = decision["state"].as_array().unwrap().iter().filter(|proposal| proposal["kind"] == "promise_open").collect(); - assert!(opens.len() == 1 && opens[0]["now"] == true, "{decision}"); -} - -const K61_TWO: &str = "Heimdall said yes, so up they go. Meta, posting the two lines now. Welcome. Say hello whenever you like, no introduction needed. Both, then."; - -/// A line of `K61_TWO`'s, draft 1 carrying the act stated as under way and what does it. -fn k61_line(n: u64, done_by: Value) -> Value { - let promises = if n == 1 { json!([stated("posting the two lines now", Some(META), "words", true, done_by)]) } else { json!([]) }; - json!({ "draft": n, "mentions": [], "in_reply_to": null, "promises": promises }) -} - -/// `K61_TWO`'s answer saying draft 1 alone, naming draft 2 as what posts the lines, and declining draft 2. -fn k61_first(done_by: Value) -> Value { - json!({ "say": [k61_line(1, done_by)], "gaps": [], "unsent": [{ "draft": 2, "how": "declined", "quote": "Heimdall said yes, so up they go." }] }) -} - -/// `done_by` naming a draft the answer does not say is asked again; the second answer says it, and nothing is owed. -#[test] -fn k61_done_by_an_unsaid_draft_is_retried() { - let fixed = json!({ "say": [k61_line(1, json!({ "draft": 2 })), k61_line(2, Value::Null)], "gaps": [] }); - let model = answering(vec![k61_first(json!({ "draft": 2 })).to_string(), fixed.to_string()]); - let decision = decide(&model, "test", &packet(), "The room is warm.", K61_TWO, &Tuning::default()); - assert_eq!((decision["retried"]["failed"].as_str(), decision["retried"]["done_by"].clone()), (Some("the answer names acts it does not make"), json!([{ "draft": 1, "words": "posting the two lines now" }])), "{decision}"); - let prompts = speech_prompts(&model); - assert!(prompts.len() == 2 && prompts[1].ends_with("An earlier answer to this named, as what does an act a draft states, an act it does not make: draft 1, \"posting the two lines now\". `done_by` names a draft in `say` or `amend`, the read when `read` names one, or the note when `suggest` leaves one, and is null when no act of this answer does it."), "{prompts:?}"); - assert_eq!((texts(&decision).len(), decision["done_now"][0]["by"].clone(), decision.get("done_by_faults")), (2, json!({ "draft": 2 }), None), "{decision}"); - assert!(decision["state"].as_array().unwrap().iter().all(|proposal| proposal["kind"] != "promise_open"), "{decision}"); -} - -/// The retry fails the same way: the `done_by` is read as null, the act opens as her promise, and the fault is reported. -#[test] -fn k61_a_failed_retry_opens_the_act_as_her_promise() { - let model = answering(vec![k61_first(json!({ "draft": 2 })).to_string()]); - let decision = decide(&model, "test", &packet(), "The room is warm.", K61_TWO, &Tuning::default()); - assert_eq!((speech_prompts(&model).len(), decision["done_by_faults"].clone(), decision.get("done_now")), (2, json!([{ "draft": 1, "words": "posting the two lines now" }]), None), "{decision}"); - let opens: Vec<&Value> = decision["state"].as_array().unwrap().iter().filter(|proposal| proposal["kind"] == "promise_open").collect(); - assert!(opens.len() == 1 && opens[0]["now"] == true && opens[0]["words"] == "posting the two lines now", "{decision}"); - // A malformed `done_by`, naming no one act, is the same fault. - let decision = decide(&answering(vec![k61_first(json!({ "draft": 1, "read": true })).to_string()]), "test", &packet(), "The room is warm.", K61_TWO, &Tuning::default()); - assert_eq!(decision["done_by_faults"], json!([{ "draft": 1, "words": "posting the two lines now" }]), "{decision}"); - // The read and the note, when the answer makes neither, are the same fault. - for by in [json!({ "read": true }), json!({ "note": true })] { - let decision = decide(&answering(vec![k61_first(by.clone()).to_string()]), "test", &packet(), "The room is warm.", K61_TWO, &Tuning::default()); - assert_eq!(decision["done_by_faults"], json!([{ "draft": 1, "words": "posting the two lines now" }]), "{by}: {decision}"); - } - // A `done_by` naming the line's own draft, said, is done by it, and is no fault. - let model = answering(vec![k61_first(json!({ "draft": 1 })).to_string()]); - let decision = decide(&model, "test", &packet(), "The room is warm.", K61_TWO, &Tuning::default()); - assert!(speech_prompts(&model).len() == 1 && decision["done_now"][0]["by"] == json!({ "draft": 1 }), "{decision}"); -} - -/// The note to Self the answer leaves does what the line says. -#[test] -fn k61_a_note_left_does_the_act() { - let prose = "I'll put it in front of Self. Meta, I'm leaving Self a note about the welcome now. The welcome mat needs Heimdall's ruling before it goes up."; - let promises = json!([stated("I'm leaving Self a note about the welcome now.", Some(META), "words", true, json!({ "note": true }))]); - let answer = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": promises }], "gaps": [], "suggest": [{ "kind": "idea", "draft": 2, "about": null, "private": false }] }); - let model = answering(vec![answer.to_string()]); - let decision = decide(&model, "test", &packet(), "The room is warm.", prose, &Tuning::default()); - assert_eq!((speech_prompts(&model).len(), decision["done_now"][0]["by"].clone(), decision["suggestions"].as_array().map(Vec::len)), (1, json!({ "note": true }), Some(1)), "{decision}"); - // A note code refuses (private) is not left: the act is her promise. - let mut private = answer; - private["suggest"][0]["private"] = json!(true); - let decision = decide(&answering(vec![private.to_string()]), "test", &packet(), "The room is warm.", prose, &Tuning::default()); - assert!(decision.get("done_now").is_none() && decision["suggestions"].as_array().is_some_and(Vec::is_empty), "{decision}"); - assert!(decision["state"].as_array().unwrap().iter().any(|proposal| proposal["kind"] == "promise_open" && proposal["now"] == true), "{decision}"); -} - -/// Negative, unchanged: E.3's "I'm testing that now", which this body has no way to do, is said, gapped and told as a -/// promise it cannot keep, never also as an act nothing did. -#[test] -fn k61_e3_a_lacking_act_stated_now_is_told_as_today() { - let prose = "I'll check it myself. Kiko, I'm testing that now and will tell you."; - let answer = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [stated("I'm testing that now", None, "lacking", true, Value::Null)] }], "gaps": [] }); - let decision = answered(&packet(), prose, answer); - assert_eq!(texts(&decision).len(), 1, "{decision}"); - assert!(decision["gaps"].as_array().unwrap().iter().any(|gap| gap["kind"] == "missing_affordance" && gap["draft"] == 1), "{decision}"); - let (_, applied) = committed(&decision, prose); - assert_eq!((applied.opened.len(), applied.opened[0]["status"].as_str(), applied.now_opened.len()), (1, Some("blocked"), 0), "{applied:?}"); - let told = told_of(&decision); - assert!(told.len() == 1 && told[0].contains("It promises something he has no way to do"), "{told:?}"); -} - -#[test] -fn k61_the_contract_defines_the_act_and_what_does_it() { - assert!(SPEECH_SCHEMA.matches(r#""required":["words","to","reaffirms","needs","now","done_by"]"#).count() == 2 && SPEECH_SCHEMA.contains(r#""now":{"type":"boolean"}"#), "{SPEECH_SCHEMA}"); - let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default()); - assert!(prompt.contains("for each act the draft promises or offers, and each act it says he is doing now or has just done this turn: its words, copied exactly,") && prompt.contains("and `done_by`, the act of this answer that does it (`{\"draft\": n}` for a draft said or added, `{\"read\": true}` for the read, `{\"note\": true}` for the note to Self), or null"), "{prompt}"); - assert!(!prompt.contains("for each act it promises or offers, its words"), "{prompt}"); + let record = json!({ "interpreter": decision, "posted": posted, "edited": [] }); + crate::projection::outcome::outcome_of(&record).unwrap().lines(forms(&libby())) } // --------------------------------------------------------------------------------------------- @@ -2317,82 +1820,11 @@ fn k63_e5_r1_an_undecided_draft_with_a_gap_is_one_row() { let gap = json!({ "kind": "missing_affordance", "draft": 1, "quote": null, "detail": "She means to send Kiko the door-fix diff as a file, but here she can only type lines and cannot attach files, so the promise could not be kept." }); let decision = answered(&packet, E5_EUREKA_R1, json!({ "say": [], "gaps": [gap] })); assert_eq!((decision["undecided"].clone(), decision["refused"][0]["reason"].as_str()), (json!([1]), Some("undecided")), "{decision}"); - let (_, _, told) = told_her(&decision, E5_EUREKA_R1); + let told = told_her(&decision); assert_eq!(told, ["- Nothing of this reached #minds:gamecult.org: what was to become of it was never settled, so it was not sent. It reaches for something she has no way to do from here. She had drafted: \"Yes, Kiko. I'll send the door-fix diff as a file so you can read it on your phone.\"."], "{told:?}"); assert!(told.iter().all(|line| !line.contains("Nothing happened.") && !line.contains("She wrote")), "{told:?}"); } -// --------------------------------------------------------------------------------------------- -// K64 (map 16.33.5): a promise never needs a read the body will refuse. R16's X.5 r5: Aqua's promise was typed `needs: read -// pasp` half an hour after she read pasp, which K26 refuses to read again, and her view said she had not read it. - -const X5_DERU_LINK: &str = "Nibu, Aqua: found this on physical modelling of plosives and waveguides, thought of you two https://ccrma.stanford.edu/~jos/pasp/"; -const X5_DERU_R5: &str = "Aqua, which part of that book did you hold your stops up against, in the end?"; -/// Aqua's r5 prose in R16 X.5, verbatim. -const X5_AQUA_R5: &str = "Honestly, I only had the page's summary and one passage, and I haven't held my stops against any of it yet. The passage is the Kelly-Lochbaum one: a closure is a section whose area goes to zero, and the release is that section opening fast, with the burst as the pressure behind it escaping. My 12 ms release was set before I read it, so it isn't a test against the book. I'd have to check it against that line.\n\nDeru, the part I used was the vocal tract passage: a stop closure as a section whose area goes to zero, and the release as that section opening fast, with the burst being the pressure behind it escaping. I only had the page summary and that passage, not the whole chapter. My 12 ms release was set before I read it, so I haven't actually held my stops up against it yet. That's the next thing I'll do."; - -/// Her r5 packet: Deru's link earlier, his question said to her (`q2`), reads afforded, and pasp read in this conversation -/// half an hour ago when `read` (found or not). -fn x5_r5_packet(read: Option) -> Packet { - let mut packet = libby_packet(&[(DERU, "Deru", X5_DERU_LINK, false), (DERU, "Deru", X5_DERU_R5, true)]); - packet.affordances.push(Affordance::Read); - packet.already_read = read.into_iter().map(|found| crate::projection::exchange::Tried { key: ReadRequest::Web(PASP.into()).normal(), found, what: PASP.into(), at: now() - chrono::Duration::minutes(30) }).collect(); - packet -} - -/// R16's r5 answer: draft 1 said to Deru, promising the next thing, needing a read of pasp. -fn x5_r5_answer() -> Value { - json!({ "say": [{ "draft": 1, "mentions": [DERU], "in_reply_to": "q2", "promises": [{ "words": "That's the next thing I'll do.", "to": DERU, "reaffirms": null, "needs": { "kind": "read", "read": { "kind": "web", "target": PASP } }, "now": false, "done_by": null }] }], "gaps": [] }) -} - -/// Her r6 view over the state r5 committed. -fn x5_r6_view(state: &Value) -> String { - let mut r6 = libby(); - r6["commitments"] = state["commitments"].clone(); - libby_packet_over(&r6, &[(NIBU, "Nibu", "Deru, I opened the page. It's a contents list plus one paragraph from the vocal tract chapter, so that's all I've read.", false)]).in_view -} - -#[test] -fn k64_x5_r5_aqua_a_read_she_already_made_is_words() { - let decision = answered(&x5_r5_packet(Some(true)), X5_AQUA_R5, x5_r5_answer()); - assert_eq!(texts(&decision).len(), 1, "{decision}"); - let (state, _) = committed(&decision, X5_AQUA_R5); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"].clone(), entry["status"].as_str(), entry["readBefore"]["of"].as_str()), (json!({ "kind": "words" }), Some("open"), Some(ReadRequest::Web(PASP.into()).normal().as_str())), "{state}"); - let view = x5_r6_view(&state); - assert!(view.contains("her promise: \"That's the next thing I'll do.\". She read it about half an hour ago, before this promise; what she has keeps it."), "{view}"); - assert!(!view.contains("not read it yet"), "{view}"); -} - -/// Negatives: a target she has not read stays a read need, and one she looked for and found nothing at stays as before. -#[test] -fn k64_an_unread_target_stays_a_read_need() { - for read in [None, Some(false)] { - let decision = answered(&x5_r5_packet(read), X5_AQUA_R5, x5_r5_answer()); - let (state, _) = committed(&decision, X5_AQUA_R5); - let entry = &state["commitments"][0]; - assert_eq!((entry["needs"]["kind"].as_str(), entry.get("readBefore")), (Some("read"), None), "{read:?}: {state}"); - assert!(x5_r6_view(&state).contains("It needs her to read https://ccrma.stanford.edu/~jos/pasp/, and she has not read it yet."), "{read:?}"); - } -} - -/// A read need with no receipt never reads as unread beside a read of the same target that this conversation found (K64): -/// an entry opened before K64, or put from outside, shows the read and when. -#[test] -fn k64_the_view_never_says_unread_beside_a_read_of_the_same_target() { - let mut state = libby(); - state["commitments"] = json!([{ "id": "c-r1-t5-1", "to": DERU, "room": MINDS, "event": "5", "madeAt": (now() - chrono::Duration::minutes(40)).to_rfc3339(), "words": "I'll read it and come back to you.", "status": "open", "needs": { "kind": "read", "request": { "kind": "web", "target": PASP } }, "closedAt": null, "closedBy": null, "extensions": {} }]); - let room = Room { messages: vec![RoomLine { event: "$x5-1".into(), ..line(MINDS, DERU, "Deru", X5_DERU_R5, true) }], here: Some(MINDS.into()), ..Room::default() }; - let view = |found: bool| { - let exchange = crate::projection::exchange::Exchange { tried: vec![crate::projection::exchange::Tried { key: ReadRequest::Web(PASP.into()).normal(), found, what: PASP.into(), at: now() - chrono::Duration::minutes(30) }], ..Default::default() }; - let (minds, operators) = (vec![LIBBY.to_owned(), DERU.to_owned()], vec![META.to_owned()]); - select(&Inputs { kind: TurnKind::Chat, state: &state, room: &room, history: &History::default(), observation: None, people: People { operators: &operators, minds: &minds, own_sender: LIBBY }, now: now(), seed: 1, affordances: &[Affordance::Perceive, Affordance::Speak], domain: None, exchange: Some(&exchange) }, &Tuning::default()).in_view - }; - let found = view(true); - assert!(found.contains("It needs her to read https://ccrma.stanford.edu/~jos/pasp/: she read it about half an hour ago.") && !found.contains("not read it yet"), "{found}"); - assert!(view(false).contains("and she has not read it yet."), "a read that found nothing is no read of it"); -} - // --------------------------------------------------------------------------------------------- // K66 (map 16.34.4): a failed call names why, with its usage, in the wake's calls. diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 14441d4..915408f 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -303,13 +303,14 @@ pub(crate) fn lived_stream(narration: &str, heard: &str) -> String { if heard.trim().is_empty() { narration.to_owned() } else { format!("{narration}\n\n{heard}") } } -/// What the Persona reads after the stream: her view (her promises, her domain), then the room. When someone turned to +/// What the Persona reads after the stream: her view (what came of her last turn, her side of the conversation, her +/// domain), then the room. When someone turned to /// her, the stream ends on that arrival, so the room opens /// on it: the bridged lines (`Packet::bridged`), then the conversation's speech cues (`The room: …`, map 16.20.2) last, /// where she drafts or stays silent knowing who is waiting. Otherwise the cues first, then what was said, verbatim. pub(crate) fn read_after(packet: &Packet) -> String { let room = room_after(packet); - // What is in front of her besides the room, first (map 16.23.1): her promises, then her domain; the room last. + // What is in front of her besides the room, first (map 16.23.1); the room last. match (packet.in_view.is_empty(), room.trim().is_empty()) { (true, _) => room, (false, true) => packet.in_view.clone(), diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 16477f9..b88842a 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -22,24 +22,22 @@ //! //! That holds by type (map 16.30.3, K46): every text of a record a row carries is `Words`, which only `Form::words` reads, //! and the event form reads none; a read is named to the Projector by a closed `EventPhrase`, never by its address or -//! search words. A person a row names is a `Person` (K53): the record's name in her view, and to the Projector only a -//! `Who`, built here from the id the record carries beside the name. +//! search words. No row names a person: what she promised, held or owes is not a row (map 16.35). use serde_json::Value; -use self::form::{Form, Person, ReadName, Words}; -use super::commit::{How, Needs, Refusal as StateRefusal}; +use self::form::{Form, ReadName, Words}; use super::interpret::{GapKind, MAX_LINES, Refusal}; use super::read::{ReadFailure, ReadRefusal, ReadRequest}; -use super::select::{Forms, Names, capitalized, who_of}; +use super::select::{Forms, capitalized}; /// Her words in a row, and the forms a row is rendered in (K46). The text a `Words` holds is private to this module, so /// nothing outside it can format one: a row's sentence asks its `Form` for each slot, and the event form answers none. mod form { use super::super::read::ReadRequest; - use super::super::select::{Forms, Who, clip, spoken}; + use super::super::select::{Forms, clip, spoken}; - /// Words of a record's text: a draft, a line, a passage of her thought, a promise's words. No `Display`, `Deref`, + /// Words of a record's text: a draft, a line, a passage of her thought. No `Display`, `Deref`, /// `AsRef` or accessor; its only reader is `Form::words`. #[derive(Clone, PartialEq, Eq)] pub(super) struct Words(String); @@ -136,26 +134,6 @@ mod form { pub(super) fn of(request: &ReadRequest) -> Self { Self { told: request.named().map(Words), event: EventPhrase::of(request) } } - - /// Whether it is a search: it finds things and reads none of them. - pub(super) fn search(&self) -> bool { - matches!(self.event, EventPhrase::RepoSearch(_)) - } - } - - /// A person a row names (K53): `told`, the record's name for them, which her view shows; `event`, who they are to - /// her as the Projector is told it (`Who`). Only `Form::person` reads either, so the event form cannot name anyone by - /// a display name or a Matrix id. - #[derive(Clone, Debug, PartialEq, Eq)] - pub(super) struct Person { - told: String, - event: Who, - } - - impl Person { - pub(super) fn new(told: String, event: Who) -> Self { - Self { told, event } - } } /// The form a row is rendered in: `Told`, her view, her words verbatim and held to a byte count; `Event`, the @@ -178,14 +156,6 @@ mod form { } } - /// Who a person is, in this form: the record's name, or the Projector's `Who`. - pub(super) fn person(&self, person: &Person) -> String { - match self { - Self::Event(_) => person.event.to_string(), - Self::Told(_) | Self::Report => person.told.clone(), - } - } - /// What a read was, in this form. pub(super) fn read(&self, name: &ReadName, her: Forms) -> String { match (self, &name.told) { @@ -217,22 +187,6 @@ enum Quote { Sent, } -/// A promise's status as her record shows it, when a close was refused. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Status { - Open, - Blocked, -} - -impl std::fmt::Display for Status { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - Self::Open => "open", - Self::Blocked => "blocked", - }) - } -} - /// Why the actuator did not change a line she meant to add to (B1's refusals; the simulated room's too). #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -243,23 +197,24 @@ enum EditRefusal { } /// One thing that came of her last turn, by its typed reason. A part that reached the room carries the receipt that says -/// so (`Said`, `Promise`, `Amended`; a note's receipt is the record that holds it); every other part names the room that +/// so (`Said`, `SaidUnbacked`, `Amended`; a note's receipt is the record that holds it); every other part names the room that /// nothing reached, when the record names one. #[derive(Clone, Debug, PartialEq, Eq)] enum Part { /// A posted receipt. Said { room: String, text: Words }, - /// A posted receipt whose line promises an act she has no way to do: a `missing_affordance` gap naming it (16.20.6). - Promise { room: String, text: Words }, + /// A posted receipt whose line says she will do something her body cannot: a `missing_affordance` gap naming it + /// (16.20.6, `persona-unbacked-intent-say-then-amend`), the say-then-amend row. + SaidUnbacked { room: String, text: Words }, /// `reach`, on this row and the other rows of a draft that did not go out: a `missing_affordance` gap names the draft, /// told as a clause of this row (K63), never as a row of its own. Refused { reason: Refusal, room: Option, text: Words, reach: bool }, Gap { kind: GapKind, room: Option, quote: Quote, reach: bool }, /// A draft she did not finish: the turn ended first, or the length limit cut it (`by_limit`, Soul's R6). Unfinished { room: Option, text: Words, by_limit: bool }, - /// An edited receipt with no refusal: her words were added after a line of hers; `promise` when a + /// An edited receipt with no refusal: her words were added after a line of hers; `unbacked` when a /// `missing_affordance` gap names the addition's draft (map 16.21). - Amended { room: String, added: Words, promise: bool }, + Amended { room: String, added: Words, unbacked: bool }, /// An addition that changed nothing: refused by code (None) or by the actuator. NotAmended { refusal: Option, room: Option, added: Words, reach: bool }, /// A note to Self, recorded in her turn's record: never claimed read. @@ -269,15 +224,6 @@ enum Part { Failed, /// Receipts went out, and a later step of the turn broke (C3c's `broke_after`, 16.20.7). BrokeAfter { room: Option }, - /// A promise of hers the commit closed (map 16.22.1, 16.22.7): told once, here, and never again. `to` is whom she - /// promised, none for the room; `by` is who let her off it, for a release. - Closed { how: How, to: Option, words: Words, room: String, by: Option }, - /// A promise the commit opened from an act her line said she was doing now, which nothing in her turn did (K61, map - /// 16.33.5): `to` is whom she promised, none for the room, and `words` her words for it. - NowUndone { to: Option, words: Words }, - /// A close the commit refused: the promise stands as her record shows it (`status`, open or blocked), and why; - /// `read` is the read keeping it needs, when it needs one. - StillOpen { reason: StateRefusal, to: Option, words: Words, status: Status, read: Option }, /// A draft she chose not to send (`unsent`, declined): it did not go out, and the thought the Interpreter cited as her /// choice is shown beside it, so a misread decline is a record she can see (map 16.26, 16.29.2). Declined { room: Option, text: Words, thought: Words, reach: bool }, @@ -319,19 +265,16 @@ fn has_receipts(record: &Value) -> bool { ["posted", "edited"].iter().any(|key| record[*key].as_array().is_some_and(|receipts| !receipts.is_empty())) } -/// What came of the turn `record` records; None when there is no record. Each person a row names is named to the -/// Projector by `who_of` over `names`, from the id the record carries beside the name (K53). A record with nothing to tell (a chosen silence, +/// What came of the turn `record` records; None when there is no record. A record with nothing to tell (a chosen silence, /// nothing drafted, nothing reached for) is an empty outcome, and no section is rendered from it. /// /// The record is one of two shapes, never both (C3c, map 16.20.7): `failed`, when the turn sent nothing and broke off; or /// the decision with its receipts, and `broke_after` naming the step when a later step broke. A record with both `failed` /// and receipts is malformed: she is told nothing of it, and it is reported. -pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { +pub(crate) fn outcome_of(record: &Value) -> Option { if !record.is_object() { return None; } - // A person by the record's name and the id beside it; a record with no id names someone she does not know. - let person = |told: &Value, id: &Value| words(told).map(|told| Person::new(told, who_of(id.as_str().unwrap_or_default(), names))); let mut outcome = Outcome::default(); let decision = &record["interpreter"]; let failed = record.get("failed").is_some() || decision.get("failed").is_some(); @@ -392,29 +335,29 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { let made = receipt.is_some_and(|receipt| receipt["refusal"].is_null()); additions.push((&amended["draft"], made.then_some(outcome.parts.len()))); match receipt.map(|receipt| (receipt["refusal"].is_null(), serde_json::from_value::(receipt["refusal"].clone()))) { - Some((true, _)) => outcome.parts.push(Part::Amended { room: at, added, promise: false }), + Some((true, _)) => outcome.parts.push(Part::Amended { room: at, added, unbacked: false }), Some((false, Ok(refusal))) => outcome.parts.push(Part::NotAmended { refusal: Some(refusal), room: Some(at), added, reach: false }), Some((false, Err(_))) => outcome.omitted.push(format!("an amendment refused for a reason no table names: {}", receipt.map_or(Value::Null, |receipt| receipt["refusal"].clone()))), None => outcome.omitted.push(format!("an amendment with no receipt that it was made: {}", amended["added"])), } } - // A reach that names a line which went out is a promise: the receipt says it reached the room, and she is told what - // it promises (16.20.6). Each receipt is told once, as a promise or as said. - let mut promised: Vec = Vec::new(); + // A reach that names a line which went out is the say-then-amend row: the receipt says it reached the room, and she is + // told it reaches for what her body cannot do (16.20.6). Each receipt is told once, as unbacked or as said. + let mut unbacked: Vec = Vec::new(); // The reaches naming a draft that did not go out, told on that draft's row once every row is known (K63). let mut reaching: Vec<(&Value, Quote)> = Vec::new(); for gap in decision["gaps"].as_array().into_iter().flatten() { let kind = serde_json::from_value::(gap["kind"].clone()).unwrap_or(GapKind::Unresolved); - // A reach naming an addition's draft is a promise in that addition: told on the addition's row when the actuator - // made it; when it did not, the row that says nothing changed tells it, and the promise is reported. + // A reach naming an addition's draft is unbacked intent in that addition: told on the addition's row when the + // actuator made it; when it did not, the row that says nothing changed tells it, and the reach is reported. if let Some((_, made)) = additions.iter().find(|(draft, _)| kind == GapKind::MissingAffordance && gap["from"] == "draft" && **draft == gap["draft"]) { match made { Some(at) => { - if let Part::Amended { promise, .. } = &mut outcome.parts[*at] { - *promise = true; + if let Part::Amended { unbacked, .. } = &mut outcome.parts[*at] { + *unbacked = true; } } - None => outcome.omitted.push(format!("a promise in an addition that was not made: {}", gap["words"])), + None => outcome.omitted.push(format!("a reach in an addition that was not made: {}", gap["words"])), } continue; } @@ -425,18 +368,18 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { _ => None, }; let sent = match ("e, words(&gap["words"])) { - (Some(Quote::Wrote(_)), Some(text)) if kind == GapKind::MissingAffordance => (0..receipts.len()).find(|at| receipts[*at].text == text && !promised.contains(at)), + (Some(Quote::Wrote(_)), Some(text)) if kind == GapKind::MissingAffordance => (0..receipts.len()).find(|at| receipts[*at].text == text && !unbacked.contains(at)), _ => None, }; - // A promise in a line the decision said and no receipt shows went out: whether it reached the room is unknown, so + // A reach in a line the decision said and no receipt shows went out: whether it reached the room is unknown, so // she is told neither that nothing happened nor that it did (I16.10), as the line itself is not told. let unreceipted = |text: &str| decision["said"].as_array().into_iter().flatten().any(|line| line["text"].as_str() == Some(text)); match (quote, sent) { (_, Some(at)) => { - promised.push(at); - outcome.parts.push(Part::Promise { room: receipts[at].room.clone(), text: Words::new(receipts[at].text.clone()) }); + unbacked.push(at); + outcome.parts.push(Part::SaidUnbacked { room: receipts[at].room.clone(), text: Words::new(receipts[at].text.clone()) }); } - (Some(Quote::Wrote(_)), None) if kind == GapKind::MissingAffordance && words(&gap["words"]).is_some_and(|text| unreceipted(&text)) => outcome.omitted.push(format!("a promise in a line said with no receipt that it went out: {}", gap["words"])), + (Some(Quote::Wrote(_)), None) if kind == GapKind::MissingAffordance && words(&gap["words"]).is_some_and(|text| unreceipted(&text)) => outcome.omitted.push(format!("a reach in a line said with no receipt that it went out: {}", gap["words"])), (Some(quote @ (Quote::Wrote(_) | Quote::Sent)), None) if kind == GapKind::MissingAffordance => reaching.push((&gap["draft"], quote)), (Some(quote), None) if kind != GapKind::Unresolved => { if matches!(quote, Quote::Wrote(_) | Quote::Sent) { @@ -447,7 +390,7 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { _ => outcome.omitted.push(format!("a gap she cannot be shown truly (kind {}, from {}): {}", gap["kind"], gap["from"], gap["quote"])), } } - for (_, posted) in receipts.iter().enumerate().filter(|(at, _)| !promised.contains(at)) { + for (_, posted) in receipts.iter().enumerate().filter(|(at, _)| !unbacked.contains(at)) { outcome.parts.push(Part::Said { room: posted.room.clone(), text: Words::new(posted.text.clone()) }); } // A note is recorded by the record that holds it: the turn's record is Self's inbox. @@ -498,60 +441,6 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { None => outcome.parts.push(Part::Gap { kind: GapKind::MissingAffordance, room: room.clone(), quote, reach: false }), } } - // What the commit did with her promises (`commit::apply`): each close it applied, and each close it refused for a - // reason she can be told. An open is told by the promise's own section from her next packet on. - for done in record["committed"]["closed"].as_array().into_iter().flatten() { - let (Ok(how), Some(words)) = (serde_json::from_value::(done["how"].clone()), words_of(&done["entry"]["words"])) else { - outcome.omitted.push(format!("a close without its kind or words: {done}")); - continue; - }; - // A promise to the room has no `to`. - let to = done["entry"]["to"].as_str().and_then(|_| person(&done["to_name"], &done["entry"]["to"])); - outcome.parts.push(Part::Closed { how, to, words, room: done["entry"]["room"].as_str().unwrap_or_default().to_owned(), by: person(&done["by"], &done["by_id"]) }); - } - for refused in record["committed"]["refused"].as_array().into_iter().flatten() { - let listed = decision["promises"].as_array().into_iter().flatten().find(|listed| listed["id"] == refused["proposal"]["promise"]); - match (serde_json::from_value::(refused["reason"].clone()), listed) { - ( - Ok( - reason @ (StateRefusal::DraftNotSent - | StateRefusal::BlockedNotKeepable - | StateRefusal::ReleaseNotByPromisee - | StateRefusal::ReleaseBeforePromise - | StateRefusal::CloseUnquoted - | StateRefusal::CloseContradicted - | StateRefusal::NeedsUnread - | StateRefusal::NeedsMalformed - | StateRefusal::NotWherePromised - | StateRefusal::OutsidePutChanged), - ), - Some(listed), - ) if refused["proposal"]["kind"] == "promise_close" => { - let read = match serde_json::from_value::(listed["needs"].clone()) { - Ok(Needs::Read { request }) => Some(ReadName::of(&request)), - _ => None, - }; - let status = if listed["status"] == "blocked" { Status::Blocked } else { Status::Open }; - let to = listed["to"].as_str().and_then(|_| person(&listed["to_name"], &listed["to"])); - outcome.parts.push(Part::StillOpen { reason, to, words: Words::new(listed["words"].as_str().unwrap_or_default().to_owned()), status, read }); - } - _ => outcome.omitted.push(format!("a state change the commit refused that she is not told ({}): {}", refused["reason"], refused["proposal"])), - } - } - // Each act her line said she was doing now that nothing in her turn did (K61): the commit opened it as her promise, and - // she is told so once, here; it is in her promises from her next packet on. Whom it is to is named as a line of theirs - // listed to the Interpreter names them, else as the Projector would. - for opened in record["committed"]["now_opened"].as_array().into_iter().flatten() { - let Some(promised) = words_of(&opened["words"]) else { - outcome.omitted.push(format!("a promise opened from an act stated as under way, without its words: {opened}")); - continue; - }; - let to = opened["to"].as_str().map(|id| { - let listed = decision["lines"].as_array().into_iter().flatten().find(|line| line["sender"].as_str() == Some(id)).and_then(|line| words(&line["who"])); - Person::new(listed.unwrap_or_else(|| who_of(id, names).to_string()), who_of(id, names)) - }); - outcome.parts.push(Part::NowUndone { to, words: promised }); - } if words(&record["broke_after"]).is_some() { outcome.parts.push(Part::BrokeAfter { room }); } @@ -564,7 +453,7 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { /// The one owner of "reached" (K49, I16.10): every row that says words of hers did not reach a room is checked against /// the receipts, by the row's own room and text, here and nowhere else. A posted line there, or an addition there whose /// `edited` receipt has no refusal, means her words reached it, so the row would be false: it is omitted and reported. -/// Rows that are receipts (`Said`, `Promise`, `Amended`) are untouched. +/// Rows that are receipts (`Said`, `SaidUnbacked`, `Amended`) are untouched. fn settle(outcome: &mut Outcome, receipts: &[Posted], record: &Value) { let added = |room: &str, text: &Words| { record["interpreter"]["amended"].as_array().into_iter().flatten().any(|amended| { @@ -630,14 +519,14 @@ impl Part { } } - /// Where the part falls in what she is told (16.20.5): what broke, then what did not happen, then promises, then what + /// Where the part falls in what she is told (16.20.5): what broke, then what did not happen, then what her body cannot do, then what /// reached the room, then a later step that broke. fn rank(&self) -> u8 { match self { Self::Failed => 0, - Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Declined { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::NowUndone { .. } | 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::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Declined { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1, + Self::SaidUnbacked { .. } | Self::Amended { unbacked: true, .. } => 2, + Self::Said { .. } | Self::Amended { .. } | Self::NoteLeft(_) | Self::Read { .. } => 3, Self::BrokeAfter { .. } => 4, } } @@ -648,13 +537,10 @@ impl Part { /// None and the row's sentence without them (`Event`). Each row writes both, so no sentence has a second author (map /// 16.29.10). fn reached(&self, her: Forms, form: Form) -> String { - let Forms { subj, cap_subj, obj, poss, be, .. } = her; + let Forms { subj, cap_subj, obj, poss, .. } = her; let place = |room: &Option| room.clone().unwrap_or_else(|| "the room".to_owned()); - // Whom a promise was to, the room when no one; who asked or let her off, someone when the record names no one. - let to = |to: &Option| to.as_ref().map_or_else(|| "the room".to_owned(), |to| form.person(to)); - let who = |who: &Option| who.as_ref().map_or_else(|| "someone".to_owned(), |who| form.person(who)); match self { - Self::Said { room, text } | Self::Promise { room, text } => match form.words(text) { + Self::Said { room, text } | Self::SaidUnbacked { room, text } => match form.words(text) { Some(quote) => format!("{} has, from {obj}: {quote}.", capitalized(room)), None => format!("{} has a line from {obj}.", capitalized(room)), }, @@ -677,19 +563,6 @@ impl Part { Self::NoteRefused(_) => "No note was left:".to_owned(), Self::Failed => format!("Nothing reached the room, and nothing {subj} meant last time happened:"), Self::BrokeAfter { room } => format!("Nothing more reached {}:", place(room)), - Self::Closed { how: How::Released, by, to: promisee, words, .. } => match form.words(words) { - Some(quote) => format!("{} let {obj} off {poss} promise: {quote}.", who(by)), - None => format!("{} let {obj} off {poss} promise to {}.", who(by), to(promisee)), - }, - Self::Closed { to: promisee, words, .. } => match form.words(words) { - Some(quote) => format!("{} promise to {}, {quote}, is closed:", capitalized(poss), to(promisee)), - None => format!("{} promise to {} is closed:", capitalized(poss), to(promisee)), - }, - Self::NowUndone { .. } => format!("{cap_subj} said {subj} {} doing it now, and nothing in {poss} turn did it;", if be == "is" { "was" } else { "were" }), - Self::StillOpen { to: promisee, words, status, .. } => match form.words(words) { - Some(quote) => format!("{} record still shows {poss} promise to {}, {quote}, {status}:", capitalized(poss), to(promisee)), - None => format!("{} record still shows {poss} promise to {} as {status}:", capitalized(poss), to(promisee)), - }, Self::Read { what } => format!("{cap_subj} read {}.", form.read(what, her)), Self::ReadFailed { what, .. } => format!("{cap_subj} reached for {} and could not read it:", form.read(what, her)), Self::ReadRefused { what: Some(what), why: ReadRefusal::InView } => format!("{cap_subj} already read {} earlier in this conversation.", form.read(what, her)), @@ -720,9 +593,9 @@ impl Part { }; match self { Self::Said { .. } => String::new(), - Self::Amended { promise: false, .. } => " The rest of the line is as it was.".to_owned(), - Self::Amended { promise: true, .. } => format!(" The rest of the line is as it was. What {subj} added promises something {subj} {has} no way to do, now or later, and it will not happen by itself."), - Self::Promise { .. } => format!(" It promises something {subj} {has} no way to do, now or later, and it will not happen by itself. The line stands as {subj} wrote it; {subj} can add to it."), + Self::Amended { unbacked: false, .. } => " The rest of the line is as it was.".to_owned(), + Self::Amended { unbacked: true, .. } => format!(" The rest of the line is as it was. What {subj} added promises something {subj} {has} no way to do, now or later, and it will not happen by itself."), + Self::SaidUnbacked { .. } => format!(" It promises something {subj} {has} no way to do, now or later, and it will not happen by itself. The line stands as {subj} wrote it; {subj} can add to it."), Self::NoteLeft(_) => format!(" It waits in Self's inbox until Self reads it; nothing tells {obj} when, and nothing in it happens by itself."), Self::Refused { reason: Refusal::Echo, .. } => format!(" What {subj} wrote was mostly the words {subj} had just been sent, so none of it was sent.{reach}"), Self::Refused { reason: Refusal::NoRoom, text, .. } => format!(" That turn had no room for {obj} to speak in, so it was not sent.{}", drafted(text)), @@ -753,30 +626,6 @@ impl Part { Self::NoteRefused(Refusal::SecondNote) => " one a turn.".to_owned(), Self::NoteRefused(_) => format!(" it carried something {subj} may not pass on."), Self::Failed => format!(" the turn broke off, not by {poss} choice."), - Self::Closed { how: How::Kept, .. } => format!(" {subj} kept it."), - Self::Closed { how: How::Withdrawn, room, .. } => format!(" {subj} withdrew it in {room}."), - Self::Closed { how: How::Released, .. } => " It is closed.".to_owned(), - Self::NowUndone { to: promisee, words } => { - let to = promisee.as_ref().map_or_else(|| "the room".to_owned(), |to| form.person(to)); - match form.words(words) { - Some(quote) => format!(" it is open as {poss} promise to {to}: {quote}."), - None => format!(" it is open as {poss} promise to {to}."), - } - } - Self::StillOpen { reason: StateRefusal::DraftNotSent, .. } => format!(" what {subj} meant to close it with did not go out."), - Self::StillOpen { reason: StateRefusal::BlockedNotKeepable, .. } => format!(" {subj} {has} no way to do it, so it was not kept."), - Self::StillOpen { reason: StateRefusal::ReleaseNotByPromisee, .. } => format!(" the line read as letting {obj} off it was not from the person {subj} promised."), - Self::StillOpen { reason: StateRefusal::ReleaseBeforePromise, .. } => format!(" the line read as letting {obj} off it came before {subj} made it."), - Self::StillOpen { reason: StateRefusal::CloseContradicted, .. } => format!(" {poss} own thought held it as still owed, so it was not closed."), - Self::StillOpen { reason: StateRefusal::CloseUnquoted, .. } => format!(" no words of {poss} own thought that turn, outside what {subj} wrote to send, took the close up, so it was not closed."), - Self::StillOpen { reason: StateRefusal::NeedsUnread, read, .. } => match read { - Some(read) if read.search() => format!(" keeping it needs {obj} to read what {} finds, and a search reads none of what it finds, so it was not kept.", form.read(read, her)), - Some(read) => format!(" keeping it needs {obj} to read {}, and no read of it had come back to {obj} before {subj} wrote that line, so it was not kept.", form.read(read, her)), - None => format!(" keeping it needs a read, and none had come back to {obj} before {subj} wrote that line, so it was not kept."), - }, - Self::StillOpen { reason: StateRefusal::NeedsMalformed, .. } => format!(" what keeping it needs was never recorded plainly, so it cannot be kept; {subj} can withdraw it."), - Self::StillOpen { reason: StateRefusal::NotWherePromised, .. } => format!(" what {subj} said to close it was not where the person {subj} promised could read it."), - Self::StillOpen { .. } => format!(" it was changed outside {poss} turn, and stands as it was changed."), Self::BrokeAfter { .. } => format!(" the rest of that turn broke off, not by {poss} choice."), Self::Read { .. } => String::new(), Self::ReadFailed { failure, .. } => format!(" {}.", failure.words()), diff --git a/crates/mind-body/src/projection/outcome/tests.rs b/crates/mind-body/src/projection/outcome/tests.rs index 45e023e..b4653f9 100644 --- a/crates/mind-body/src/projection/outcome/tests.rs +++ b/crates/mind-body/src/projection/outcome/tests.rs @@ -14,7 +14,7 @@ fn record(prose: &str, answer: Value, posted: &[&str]) -> Value { /// What Heimdall (he/him) is told of `record`, and what is omitted. fn told(record: &Value) -> (Vec, Vec) { - let outcome = outcome_of(record, &crate::projection::select::Names::none()).expect("a record"); + let outcome = outcome_of(record).expect("a record"); (outcome.lines(packet().forms), outcome.omitted) } @@ -86,7 +86,7 @@ fn a_promise_in_a_said_line_with_no_matching_receipt_is_not_told_as_nothing_happ let promise = |posted: Value| json!({ "interpreter": { "heard": [], "room": MINDS, "said": [{ "room": MINDS, "text": text }], "refused": [], "gaps": [{ "kind": "missing_affordance", "from": "draft", "draft": 1, "words": text }] }, "posted": posted }); let (lines, omitted) = told(&promise(json!([{ "event": "40", "room": MINDS, "text": "I'll send it tonight!" }]))); assert_eq!(lines, ["- #minds:gamecult.org has, from him: \"I'll send it tonight!\"."], "the receipt alone"); - assert!(omitted.len() == 2 && omitted[1].starts_with("a promise in a line said with no receipt"), "{omitted:?}"); + assert!(omitted.len() == 2 && omitted[1].starts_with("a reach in a line said with no receipt"), "{omitted:?}"); let (lines, omitted) = told(&promise(json!([]))); assert!(lines.is_empty() && omitted.len() == 2, "{lines:?} {omitted:?}"); } @@ -114,9 +114,9 @@ fn a_record_that_failed_and_carries_receipts_is_malformed_told_nothing_and_repor #[test] fn a_chosen_silence_tells_him_nothing_and_no_record_is_no_outcome() { - let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[]), &crate::projection::select::Names::none()).unwrap(); + let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[])).unwrap(); assert_eq!((silent.len(), silent.omitted.len()), (0, 0)); - assert_eq!(outcome_of(&Value::Null, &crate::projection::select::Names::none()), None); + assert_eq!(outcome_of(&Value::Null), None); } #[test] @@ -128,7 +128,7 @@ fn a_line_said_with_no_receipt_is_not_told_as_said() { #[test] fn the_table_speaks_of_her_in_her_own_pronouns() { - let outcome = outcome_of(&record("Hi. There. Again.", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["Hi.", "There."]), &crate::projection::select::Names::none()).unwrap(); + let outcome = outcome_of(&record("Hi. There. Again.", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["Hi.", "There."])).unwrap(); for (pronouns, line) in [("she/her", "she had already sent two lines"), ("any", "they had already sent two lines")] { let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); assert!(outcome.lines(her)[0].contains(line), "{pronouns}: {:?}", outcome.lines(her)); @@ -239,14 +239,14 @@ fn i16_10_every_lines_first_clause_is_what_its_receipt_says_reached_the_room() { let her = packet().forms; let mut rows = 0; for record in every_row() { - let outcome = outcome_of(&record, &crate::projection::select::Names::none()).unwrap(); + let outcome = outcome_of(&record).unwrap(); for part in &outcome.parts { for (form, rendered) in [("told", Form::Told(usize::MAX)), ("event", Form::Event(&[]))] { let (reached, rest) = (part.reached(her, rendered), part.rest(her, rendered)); let line = if form == "told" { part.told(her, usize::MAX) } else { part.event(her, &[]) }; assert_eq!(line, format!("- {reached}{rest}"), "{form}: {part:?}"); // "{Room} has" only on a receipt that a line went out or was added to. - let receipt = matches!(part, Part::Said { .. } | Part::Promise { .. } | Part::Amended { .. }); + let receipt = matches!(part, Part::Said { .. } | Part::SaidUnbacked { .. } | Part::Amended { .. }); assert_eq!(reached.starts_with("#minds:gamecult.org has"), receipt, "{form}: {part:?}: {reached}"); assert!(receipt || matches!(part, Part::NoteLeft(_)) || reached.starts_with("Nothing") || reached.starts_with("No "), "{form}: {part:?}: {reached}"); for claim in ["Nothing reached", "reached the room", "reached anyone", " has, from", " has a line", "now ending with", "now added to", "went out"] { @@ -264,7 +264,7 @@ fn no_row_says_as_her_own_recorded_as_queued_or_landed() { for pronouns in ["she/her", "he/him", "any"] { let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); for record in every_row() { - for line in outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(her) { + for line in outcome_of(&record).unwrap().lines(her) { for banned in ["as her own", "as his own", "as their own", "recorded as", "queue", "landed"] { assert!(!line.contains(banned), "{pronouns}: {banned} in {line}"); } @@ -294,34 +294,6 @@ fn k43_her_words_are_told_verbatim_whatever_the_record_heard() { // --------------------------------------------------------------------------------------------- // K33 (map 16.26): a refused close and a declined draft are told, by the fixed table. -/// L1: each refused close she can correct is told as her record still showing the promise, and why; L4: a declined draft -/// is told as not sent. -#[test] -fn k33_a_refused_close_and_a_declined_draft_are_told() { - let listed = json!([ - { "id": "c1", "entry": "e1", "status": "open", "to": "@deru:gamecult.org", "to_name": "Deru", "words": "I'll read it properly.", "needs": { "kind": "read", "request": { "kind": "web", "target": "https://ccrma.stanford.edu/~jos/pasp/" } } }, - { "id": "c2", "entry": "e2", "status": "open", "to": "@meta:gamecult.org", "to_name": "Meta", "words": "I'll look at #125.", "needs": null }, - ]); - let refused = |promise: &str, reason: &str| json!({ "proposal": { "kind": "promise_close", "promise": promise, "how": "kept", "evidence": { "draft": 1 } }, "reason": reason }); - let record = json!({ - "interpreter": { "said": [], "refused": [], "gaps": [], "heard": [], "room": MINDS, "promises": listed, "unsent": [{ "draft": 2, "how": "declined", "quote": "I hold that one back", "words": "Deru, the waveguide part first." }, { "draft": 3, "how": "superseded", "quote": "later words", "words": "Deru, never mind." }] }, - "posted": [], - "committed": { "closed": [], "refused": [refused("c1", "close_unquoted"), refused("c1", "needs_unread"), refused("c2", "needs_malformed"), refused("c2", "close_contradicted")] } - }); - let (lines, omitted) = told(&record); - assert_eq!( - lines, - [ - "- Nothing of this reached #minds:gamecult.org: he chose not to send it. In his thought: \"I hold that one back\". He had drafted: \"Deru, the waveguide part first.\".", - "- His record still shows his promise to Deru, \"I'll read it properly.\", open: no words of his own thought that turn, outside what he wrote to send, took the close up, so it was not closed.", - "- His record still shows his promise to Deru, \"I'll read it properly.\", open: keeping it needs him to read https://ccrma.stanford.edu/~jos/pasp/, and no read of it had come back to him before he wrote that line, so it was not kept.", - "- His record still shows his promise to Meta, \"I'll look at #125.\", open: what keeping it needs was never recorded plainly, so it cannot be kept; he can withdraw it.", - "- His record still shows his promise to Meta, \"I'll look at #125.\", open: his own thought held it as still owed, so it was not closed.", - ], - "{omitted:?}" - ); -} - // --------------------------------------------------------------------------------------------- // K49 (map 16.30.6): "reached" is derived once, by `settle`, for every row kind with words. @@ -337,12 +309,12 @@ fn posted_as_said(decision: &Value) -> Vec { #[test] fn k49_p4_a_gap_on_words_that_went_out_is_not_told() { let prose = "Morning, all of you. Morning, all of you."; - let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null, "promises": [] }], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] })); - let outcome = outcome_of(&json!({ "interpreter": decision, "posted": posted_as_said(&decision), "edited": [] }), &crate::projection::select::Names::none()).unwrap(); + let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null }], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] })); + let outcome = outcome_of(&json!({ "interpreter": decision, "posted": posted_as_said(&decision), "edited": [] })).unwrap(); assert_eq!(outcome.lines(packet().forms), ["- #minds:gamecult.org has, from him: \"Morning, all of you.\"."]); assert!(outcome.omitted.iter().any(|why| why == "a gap of words a receipt shows reached #minds:gamecult.org: Morning, all of you."), "{:?}", outcome.omitted); // Negative: with no receipt, the gap is told. - let unposted = outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); + let unposted = outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet().forms); assert!(unposted.iter().any(|line| line.starts_with("- Nothing reached anyone.")), "{unposted:?}"); } @@ -361,22 +333,22 @@ fn declined_and_added(text: &str, edited: Value, posted: Value) -> Value { } fn declined_told(record: &Value) -> bool { - outcome_of(record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms).iter().any(|line| line.contains("he chose not to send it")) + outcome_of(record).unwrap().lines(packet().forms).iter().any(|line| line.contains("he chose not to send it")) } /// Mutant k44-reached-ignores-addition: an addition the actuator made is a receipt that her words reached the room. #[test] fn k49_an_addition_receipt_counts_as_reached() { let record = declined_and_added("Sent at nine.", json!([{ "event": "$ev-1", "refusal": null }]), json!([])); - assert!(!declined_told(&record), "{:?}", outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); - assert!(outcome_of(&record, &crate::projection::select::Names::none()).unwrap().omitted.iter().any(|why| why == "a declined draft of words a receipt shows reached #minds:gamecult.org: Sent at nine.")); + assert!(!declined_told(&record), "{:?}", outcome_of(&record).unwrap().lines(packet().forms)); + assert!(outcome_of(&record).unwrap().omitted.iter().any(|why| why == "a declined draft of words a receipt shows reached #minds:gamecult.org: Sent at nine.")); } /// Mutant k44-reached-any-room: a line posted in another room is no receipt for this one. #[test] fn k49_a_receipt_in_another_room_does_not_count() { let elsewhere = declined_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": SWARM, "text": "Sent at nine." }])); - assert!(declined_told(&elsewhere), "{:?}", outcome_of(&elsewhere, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); + assert!(declined_told(&elsewhere), "{:?}", outcome_of(&elsewhere).unwrap().lines(packet().forms)); let here = declined_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": MINDS, "text": "Sent at nine." }])); assert!(!declined_told(&here), "the same receipt in #minds counts"); } @@ -386,7 +358,7 @@ fn k49_a_receipt_in_another_room_does_not_count() { fn k49_an_addition_the_actuator_refused_did_not_reach() { for edited in [json!([{ "event": "$ev-1", "refusal": "too_long" }]), json!([{ "event": "$ev-2", "refusal": null }]), json!([])] { let record = declined_and_added("Sent at nine.", edited.clone(), json!([])); - assert!(declined_told(&record), "{edited}: {:?}", outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); + assert!(declined_told(&record), "{edited}: {:?}", outcome_of(&record).unwrap().lines(packet().forms)); } } @@ -411,7 +383,7 @@ fn k49_every_row_with_words_is_settled_by_its_room() { ("unmade addition", decision(json!({ "refused": [{ "reason": "not_amendable", "text": SENTINEL, "draft": 1 }] }))), ]; for (row, decision) in rows { - let at = |room: &str| outcome_of(&json!({ "interpreter": decision, "posted": [{ "event": "40", "room": room, "text": SENTINEL }], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); + let at = |room: &str| outcome_of(&json!({ "interpreter": decision, "posted": [{ "event": "40", "room": room, "text": SENTINEL }], "edited": [] })).unwrap(); let here = at(MINDS); let not_reached = |outcome: &Outcome| outcome.lines(packet().forms).into_iter().filter(|line| line.starts_with("- Nothing")).count(); assert_eq!(not_reached(&here), 0, "{row}: {:?}", here.lines(packet().forms)); @@ -438,7 +410,7 @@ fn k49_reached_is_decided_once() { fn variant(part: &Part) -> &'static str { match part { Part::Said { .. } => "said", - Part::Promise { .. } => "promise", + Part::SaidUnbacked { .. } => "said_unbacked", Part::Refused { .. } => "refused", Part::Gap { .. } => "gap", Part::Unfinished { .. } => "unfinished", @@ -448,9 +420,6 @@ fn variant(part: &Part) -> &'static str { Part::NoteRefused(_) => "note_refused", Part::Failed => "failed", Part::BrokeAfter { .. } => "broke_after", - Part::Closed { .. } => "closed", - Part::StillOpen { .. } => "still_open", - Part::NowUndone { .. } => "now_undone", Part::Declined { .. } => "declined", Part::Read { .. } => "read", Part::ReadFailed { .. } => "read_failed", @@ -458,34 +427,17 @@ fn variant(part: &Part) -> &'static str { } } -const VARIANTS: usize = 18; - -const STRANGER: &str = "@stranger:example.org"; - -/// A person a row names (K53): the record's name, as `name_of` renders someone unbonded who spoke in the room under -/// `display`; and `who_of` over that room, she bound to them when `label` is some. -fn person(display: &str, label: Option<&str>) -> Person { - use crate::projection::select::{Names, People, Room, RoomLine, spoken, who_of}; - let state = label.map_or_else(|| json!({}), |label| json!({ "affect": { "socialBonds": [{ "id": "bond-them", "status": "active", "object": { "id": STRANGER, "kind": "person", "label": label } }] } })); - let room = Room { messages: vec![RoomLine { room: MINDS.into(), sender: STRANGER.into(), display: display.into(), text: "hi".into(), ..RoomLine::default() }], ..Room::default() }; - let names = Names { state: &state, people: People { operators: &[], minds: &[], own_sender: "@heimdall:gamecult.org" }, room: &room }; - Person::new(format!("{} ({STRANGER})", spoken(display)), who_of(STRANGER, &names)) -} - -/// Meta, as a bonded person's label names them: no quote marks in the Projector's form. -fn meta() -> Person { - person("Meta", Some("Meta")) -} +const VARIANTS: usize = 15; /// Every row kind, and every arm that renders a different sentence, with `s` in every text of a record it carries and in -/// every read's target, and `who` in every person slot; and whether her told form shows those words (an echo, a held +/// every read's target; and whether her told form shows those words (an echo, a held /// draft, a pull request or commit read and a read of her own mind show none, by design). -fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { +fn fixtures(s: &str) -> Vec<(Part, bool)> { let w = || Words::new(format!("{s} at the door")); let room = || Some(MINDS.to_owned()); let web = || ReadName::of(&ReadRequest::Web(format!("https://example.org/{s}"))); let search = || ReadName::of(&ReadRequest::Repo(format!("GameCult/Bifrost?q={s} plover"))); - let mut out: Vec<(Part, bool)> = vec![(Part::Said { room: MINDS.into(), text: w() }, true), (Part::Promise { room: MINDS.into(), text: w() }, true)]; + let mut out: Vec<(Part, bool)> = vec![(Part::Said { room: MINDS.into(), text: w() }, true), (Part::SaidUnbacked { room: MINDS.into(), text: w() }, true)]; for reason in [Refusal::OverLines, Refusal::NoRoom, Refusal::NotQuotable, Refusal::SecondAmend] { out.push((Part::Refused { reason, room: room(), text: w(), reach: false }, true)); out.push((Part::Refused { reason, room: room(), text: w(), reach: true }, true)); @@ -501,8 +453,8 @@ fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { for by_limit in [false, true] { out.push((Part::Unfinished { room: room(), text: w(), by_limit }, true)); } - for promise in [false, true] { - out.push((Part::Amended { room: MINDS.into(), added: w(), promise }, true)); + for unbacked in [false, true] { + out.push((Part::Amended { room: MINDS.into(), added: w(), unbacked }, true)); } for refusal in [None, Some(EditRefusal::NotFound), Some(EditRefusal::NotHers), Some(EditRefusal::TooLong)] { out.push((Part::NotAmended { refusal, room: room(), added: w(), reach: false }, true)); @@ -512,29 +464,6 @@ fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { out.push((Part::NoteRefused(Refusal::SecondNote), false)); out.push((Part::Failed, false)); out.push((Part::BrokeAfter { room: room() }, false)); - for how in [How::Kept, How::Withdrawn, How::Released] { - out.push((Part::Closed { how, to: Some(who.clone()), words: w(), room: MINDS.into(), by: Some(who.clone()) }, true)); - } - for (reason, read) in [ - (StateRefusal::DraftNotSent, None), - (StateRefusal::BlockedNotKeepable, None), - (StateRefusal::ReleaseNotByPromisee, None), - (StateRefusal::ReleaseBeforePromise, None), - (StateRefusal::CloseContradicted, None), - (StateRefusal::CloseUnquoted, None), - (StateRefusal::NeedsUnread, Some(search())), - (StateRefusal::NeedsUnread, Some(web())), - (StateRefusal::NeedsUnread, None), - (StateRefusal::NeedsMalformed, None), - (StateRefusal::NotWherePromised, None), - (StateRefusal::OutsidePutChanged, None), - ] { - for status in [Status::Open, Status::Blocked] { - out.push((Part::StillOpen { reason, to: Some(who.clone()), words: w(), status, read: read.clone() }, true)); - } - } - out.push((Part::NowUndone { to: Some(who.clone()), words: w() }, true)); - out.push((Part::NowUndone { to: None, words: w() }, true)); out.push((Part::Declined { room: room(), text: w(), thought: w(), reach: false }, true)); out.push((Part::Declined { room: room(), text: w(), thought: w(), reach: true }, true)); for (request, shows) in [ @@ -563,7 +492,7 @@ fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { #[test] fn k46_every_part_has_an_event_without_its_words() { const S: &str = "ospreyledger"; - let parts = fixtures(S, &meta()); + let parts = fixtures(S); let kinds: std::collections::BTreeSet<&str> = parts.iter().map(|(part, _)| variant(part)).collect(); assert_eq!(kinds.len(), VARIANTS, "fixtures lists every variant: {kinds:?}"); for pronouns in ["she/her", "he/him", "any"] { @@ -592,26 +521,6 @@ fn k46_every_part_has_an_event_without_its_words() { assert_eq!(read(ReadRequest::Mind("the kettle".into())).event(her, &domain), "- He read his own mind."); } -/// K53 (map 16.31.5): every person slot of every row names them to the Projector by `Who` alone. A stranger whose display -/// name is a sentence is the first three of its words, quoted, and never its fourth or their Matrix id; her told form -/// names them as the record does, whole. -#[test] -fn k53_every_part_names_by_who() { - const NAME: &str = "kestrel heron plover gannet skua"; - let parts = fixtures("ospreyledger", &person(NAME, None)); - let names_someone = |part: &Part| matches!(part, Part::Closed { .. } | Part::StillOpen { .. } | Part::NowUndone { to: Some(_), .. }); - assert!(parts.iter().filter(|(part, _)| names_someone(part)).count() > 20, "the rows with a person slot are listed"); - for pronouns in ["she/her", "he/him", "any"] { - let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); - for (part, _) in &parts { - let (told, event) = (part.told(her, usize::MAX), part.event(her, &[])); - assert!(!event.contains("gannet") && !event.contains("skua") && !event.contains(STRANGER) && !event.contains("example.org"), "{pronouns}: {part:?}: {event}"); - assert_eq!(event.contains("\"kestrel heron plover\""), names_someone(part), "{pronouns}: {event}"); - assert_eq!(told.contains(&format!("\"{NAME}\" ({STRANGER})")), names_someone(part), "{pronouns}: {told}"); - } - } -} - /// K46: `Words` has no `Display`, `AsRef` or `Deref`, so no format string and no `&str` borrow reads one; only /// `Form::words` does. Checked when this module compiles, as `static_assertions::assert_not_impl_any!` does: a probe trait /// is implemented twice for a type that has the trait, so its `_` cannot be inferred and the module does not compile. (A diff --git a/crates/mind-body/src/projection/read.rs b/crates/mind-body/src/projection/read.rs index bf50685..26fe9ae 100644 --- a/crates/mind-body/src/projection/read.rs +++ b/crates/mind-body/src/projection/read.rs @@ -24,7 +24,6 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use super::Affordance; -use super::commit::Needs; use super::domain::{About, ForgeGet, HttpForge}; use super::select::{Forms, Packet, spoken}; use crate::queue::{any_of, of_kind}; @@ -105,11 +104,6 @@ impl ReadRequest { } } - /// Whether this is a search (`GameCult/Name?q=words`): it finds things and reads none of them. - pub(crate) fn search(&self) -> bool { - matches!(self, Self::Repo(target) if target.contains("?q=")) - } - /// What she read, in code's words for her outcome and her bridge: never a model's words (a recall's query is the /// Interpreter's, so it is not repeated). pub(crate) fn what(&self, her: Forms) -> String { @@ -131,15 +125,6 @@ impl ReadRequest { } } -/// Whether a read whose normal form is `read` reads what a need whose normal form is `need` asks for (map 16.27, -/// 16.28.6): the same thing exactly (`ReadRequest::normal`). A search finds things and reads none of them, so a search -/// answers no need, and a need for a search is answered by nothing until a reaffirmation names one thing in its repo. A -/// repo's listing answers no need for a file, pull request or commit in it. -pub(crate) fn answers(need: &str, read: &str) -> bool { - let searched = |key: &str| key.starts_with("repo:") && key.contains("?q="); - !searched(need) && !searched(read) && need == read -} - /// Why a read returned nothing, from code's table (map 16.22.3). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -370,18 +355,12 @@ pub(crate) fn resolve(asked: &Asked, packet: &Packet, prose: &str, reached: &[St /// The one rule for what she can reach (map 16.25.5), at open and at read: a turn that can read, what she named resolved /// (`resolve`), and a repo only when it is named in front of her or in her domain. In front of her is her prose, her -/// view, what reached her (`reached`), and the read targets of her open promises: a promise carries its address, so what -/// was reachable when she made it stays reachable while it is open. +/// view, and what reached her (`reached`). pub(crate) fn reach(asked: &Asked, packet: &Packet, prose: &str, reached: &[String]) -> Result { if !packet.affordances.contains(&Affordance::Read) { return Err("no_read_here"); } - let promised = packet.promises.iter().filter(|promise| promise.status == "open").filter_map(|promise| match &promise.needs { - Some(Needs::Read { request: ReadRequest::Repo(target) | ReadRequest::Web(target) }) => Some(target.clone()), - _ => None, - }); - let reached: Vec = reached.iter().cloned().chain(promised).collect(); - let request = resolve(asked, packet, prose, &reached)?; + let request = resolve(asked, packet, prose, reached)?; if let ReadRequest::Repo(target) = &request { let domain = packet.domain.iter().map(|line| line.line.as_str()); let in_front = [prose, packet.in_view.as_str()].into_iter().chain(reached.iter().map(String::as_str)).chain(domain); diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 823159c..7b24642 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -35,7 +35,6 @@ use serde_json::Value; use unicode_segmentation::UnicodeSegmentation; use super::Affordance; -use super::commit::Needs; use super::domain::{About, Digest, Item, floor_minute}; use super::exchange::{self, Exchange}; use super::outcome::Outcome; @@ -334,22 +333,16 @@ pub(crate) struct Packet { pub clipped: Vec, /// The lines of hers she may add to this turn, for the Interpreter alone (map 16.17). pub amendable: Vec, - /// The lines of others she may reply to this turn, for the Interpreter alone (map 16.20.8 (D), K20); a release of a - /// promise of hers cites one of them (16.22.7). + /// The lines of others she may reply to this turn, for the Interpreter alone (map 16.20.8 (D), K20). pub quotable: Vec, - /// 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 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. pub domain_shown: DomainShown, /// What is in front of her this moment besides the room (map 16.23.1, 16.29.10): what came of her last turn, her words - /// verbatim; her open promises; then her domain, rendered by code, whole and without ids, for the Persona after the + /// verbatim; her side of the conversation; 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 promises 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. pub now_ms: u64, /// Her own Matrix id: her pronouns are not listed among the people named (`named_pronouns`). @@ -381,37 +374,13 @@ pub(crate) struct Quotable { pub id: String, pub event: String, pub room: String, - /// Who said it, as the packet names them (`name_of`), and their Matrix id: a release is checked against it (16.22.7). + /// Who said it, as the packet names them (`name_of`), and their Matrix id. pub who: String, pub sender: String, pub at_ms: u64, pub text: String, } -/// A promise of hers as this packet lists it (map 16.22.1, 16.28.3): for the Interpreter, by `id` (`c1`, `c2`), to propose a -/// close or a reopen against; `entry` is the state's id, never shown to a model, and `status` what she was shown, which the commit -/// checks the entry against (4.4). -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub(crate) struct Promised { - pub id: String, - pub entry: String, - pub status: String, - /// Whom to: a Matrix id, none for the room; and as the packet names them. - pub to: Option, - pub to_name: String, - /// Where she made it, as the packet says it ("in #minds:gamecult.org", "in a direct message"), and when: exact, for - /// the Interpreter; her view says it coarsely (`coarse`). - pub place: String, - pub made: DateTime, - pub words: String, - /// What keeping it needs, as her state holds it (map 16.25.2): the Interpreter's list says it in code's words, and a - /// read target of an open one stays in front of her (`read::reach`). - pub needs: Option, - /// The entry whole, as her state held it when the packet was built: the turn's starting copy, which the commit - /// compares the entry against, so an outside put wins on any field it changed (4.4, B6). Never shown to a model. - 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)] @@ -807,16 +776,6 @@ impl<'a> Inputs<'a> { } } -#[cfg(test)] -impl Names<'static> { - /// No state, no one and no room: a test's, for an outcome whose Projector form it does not read. - pub(crate) fn none() -> Self { - static STATE: Value = Value::Null; - static ROOM: Room = Room { messages: Vec::new(), tail: Vec::new(), here: None, last_heard: Vec::new(), direct: Vec::new(), own: Vec::new() }; - Names { state: &STATE, people: People { operators: &[], minds: &[], own_sender: "" }, room: &ROOM } - } -} - /// A person as the Projector is told of them (K53, I16.7): who they are to her, in no more room than a name needs. Her own /// name for her; the bond's label for someone she is bound to, which is her state's text; for anyone else their display /// name cut to at most `WHO_WORDS` words and `WHO_BYTES` bytes, quoted and escaped, then ", someone she does not know", @@ -1823,8 +1782,8 @@ fn body_lines(state: &Value, can: &[Affordance], her: Forms, body_bytes: usize) // The packet. /// The sections of a packet's context, in the order they are rendered (map 16.5, I16.4). Each heading says what kind of -/// text its lines are; the Projector's frame says once what the headings mean. Her open promises and her domain are not -/// among them: they are in her view, after the narration, whole (`Packet::in_view`, map 16.23.1). +/// text its lines are; the Projector's frame says once what the headings mean. Her side of the conversation and her domain +/// are not among them: they are in her view, after the narration, whole (`Packet::in_view`, map 16.23.1). #[derive(Clone, Copy)] enum Section { /// What came of her last turn (`outcome`, map 16.16): first, so she meets it before anything else; its events only, no @@ -1867,7 +1826,6 @@ fn guards(tuning: &Tuning, her: Forms) -> [usize; SECTIONS] { [select.outcome_bytes, select.here_bytes, select.body_bytes, people_guard(tuning, her), select.notes_bytes] } -/// How long ago a promise was made, in words. /// A moment as she reads it (Soul's R7 timestamp ledger): coarse and relative, never a clock time, so nothing she reads /// gives her a time to recite. "just now", "a few minutes ago", "about half an hour ago", "about an hour ago", "earlier /// this afternoon", "this morning", "last night", "yesterday evening", "Thursday afternoon", "13 November". Exact times @@ -1907,90 +1865,6 @@ fn part_of_day(at: DateTime) -> &'static str { } } -/// Her promises in her view (map 16.22.1, 16.23.1): every `open` or `blocked` entry of her state's `commitments`, oldest -/// first, whole, with her own words, never withheld and never dropped. A dropped promise is what produced the r6 denials, -/// so past `promises_bytes` every one is still rendered and the overflow is reported. A promise closed in this -/// conversation (K26's window) stays listed, marked closed and how, until the conversation ends (Soul's R7). The -/// Interpreter lists every one she sees, by id, open and closed alike, so her words can reopen a close (map 16.28.3). -fn open_promises(inputs: &Inputs, her: Forms) -> (Vec, String) { - let open = |entry: &Value| matches!(text(entry, &["status"]), "open" | "blocked"); - let conversation = inputs.exchange.and_then(|exchange| exchange.since); - let closed_in_it = |entry: &Value| { - matches!(text(entry, &["status"]), "kept" | "withdrawn" | "released") - && conversation.zip(DateTime::parse_from_rfc3339(text(entry, &["closedAt"])).ok()).is_some_and(|(since, at)| at.with_timezone(&Utc) >= since) - }; - let mut entries: Vec<(DateTime, &Value)> = items(inputs.state, &["commitments"]) - .iter() - .filter(|entry| open(entry) || closed_in_it(entry)) - .map(|entry| (DateTime::parse_from_rfc3339(text(entry, &["madeAt"])).map_or(inputs.now, |at| at.with_timezone(&Utc)), entry)) - .collect(); - entries.sort_by_key(|(at, _)| *at); - let shown: Vec = entries - .iter() - .enumerate() - .map(|(at, (made, entry))| { - let to = entry.get("to").and_then(Value::as_str).map(str::to_owned); - let room = text(entry, &["room"]); - Promised { - id: format!("c{}", at + 1), - entry: text(entry, &["id"]).to_owned(), - status: text(entry, &["status"]).to_owned(), - to_name: to.as_deref().map_or_else(|| "the room".to_owned(), |to| sender_name(to, inputs)), - to, - place: if room_kind(inputs, room) == RoomKind::Direct { "in a direct message".to_owned() } else { format!("in {room}") }, - made: *made, - words: text(entry, &["words"]).to_owned(), - needs: serde_json::from_value(entry["needs"].clone()).ok(), - held: (*entry).clone(), - } - }) - .collect(); - if shown.is_empty() { - return (Vec::new(), String::new()); - } - let lines: Vec = shown - .iter() - .map(|promise| { - // Closed in this conversation, and how. - let closed_at = || promise.held["closedAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or_else(String::new, |at| format!(" {}", coarse(at.with_timezone(&Utc), inputs.now))); - let closed = match promise.status.as_str() { - "kept" => format!(" Closed: {} kept it{}.", her.subj, closed_at()), - "withdrawn" => format!(" Closed: {} withdrew it{}.", her.subj, closed_at()), - "released" => format!(" Closed: {} released {} from it{}.", promise.to_name, her.obj, closed_at()), - _ => String::new(), - }; - // Blocked by a read that found nothing (map 16.24.3), or by having no way to do it. - let blocked = match (promise.status.as_str(), promise.held["blockedBy"]["act"].as_str()) { - ("blocked", Some("read")) => format!(" {} looked and could not find it.", her.cap_subj), - ("blocked", _) => format!(" {} {} no way to do it yet.", her.cap_subj, her.has), - _ => String::new(), - }; - // What an open promise needs read, exactly, and whether she has read that: her receipt on the entry (map 16.26, - // 16.27), or a read of this conversation that found it (K64). A search finds things and reads none, so a promise - // that needs one needs what it finds read. A read made before the promise keeps it by what she has (K64). - let read_here = |request: &crate::projection::read::ReadRequest| inputs.exchange.and_then(|exchange| exchange.tried.iter().find(|tried| tried.found && tried.key == request.normal())).map(|tried| tried.at); - let before = promise.held["readBefore"]["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)); - let reading = match (&promise.needs, promise.status.as_str(), before) { - (Some(Needs::Words), "open", Some(at)) => format!(" {} read it {}, before this promise; what {} {} keeps it.", her.cap_subj, coarse(at, inputs.now), her.subj, her.has), - (Some(Needs::Read { request }), "open", _) if request.search() => format!(" It needs {} to read what {} finds, and {} {} not read that yet.", her.obj, request.what(her), her.subj, her.has), - (Some(Needs::Read { request }), "open", _) => match crate::projection::commit::receipt(&promise.held).or_else(|| read_here(request)) { - Some(at) => format!(" It needs {} to read {}: {} read it {}.", her.obj, request.what(her), her.subj, coarse(at, inputs.now)), - None => format!(" It needs {} to read {}, and {} {} not read it yet.", her.obj, request.what(her), her.subj, her.has), - }, - _ => String::new(), - }; - // Each time she said it again, verbatim (map 16.24.2). - let when = |said: &Value| said["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or_else(|| "since".to_owned(), |at| coarse(at.with_timezone(&Utc), inputs.now)); - let again: String = promise.held["reaffirmed"].as_array().into_iter().flatten().map(|said| format!(" Said again {}: {}.", when(said), spoken(said["words"].as_str().unwrap_or_default()))).collect(); - // Each time her own words reopened it, verbatim, so she sees why it is open again (map 16.28.3). - let reopened: String = promise.held["reopened"].as_array().into_iter().flatten().map(|said| format!(" Reopened {}: {}.", when(said), spoken(said["words"].as_str().unwrap_or_default()))).collect(); - format!("- to {}, {}, {}, {} promise: {}.{again}{reopened}{reading}{blocked}{closed}", promise.to_name, coarse(promise.made, inputs.now), promise.place, her.poss, spoken(&promise.words)) - }) - .collect(); - let block = format!("{} promises:\n{}", capitalized(her.poss), lines.join("\n")); - (shown, block) -} - /// 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 /// {time}:` for the floor's earlier items. Never a count, never a mention of what fell out: when the whole window does not @@ -2047,12 +1921,10 @@ pub(crate) fn people_guard(tuning: &Tuning, her: Forms) -> usize { const SECTIONS: usize = 5; /// The bytes each section of the context took as rendered, its heading included, and the sections whose guard refused a -/// line: what `--select-only` reports. `promises` and `domain` are the bytes of those parts of her view (`in_view`), not -/// of the context. +/// line: what `--select-only` reports. `domain` is the bytes of that part of her view (`in_view`), not of the context. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] pub(crate) struct Sections { pub outcome: usize, - pub promises: usize, pub here: usize, pub body: usize, pub people: usize, @@ -2117,7 +1989,7 @@ impl Context { fn sizes(&self) -> Sections { let bytes = |section: Section| self.used[section as usize].saturating_sub(1); let names = ["outcome", "here", "body", "people", "notes"]; - Sections { outcome: bytes(Section::Outcome), promises: 0, here: bytes(Section::Here), body: bytes(Section::Body), people: bytes(Section::People), domain: 0, notes: bytes(Section::Notes), bound: names.into_iter().zip(self.bound).filter_map(|(name, bound)| bound.then_some(name)).collect() } + Sections { outcome: bytes(Section::Outcome), here: bytes(Section::Here), body: bytes(Section::Body), people: bytes(Section::People), domain: 0, notes: bytes(Section::Notes), bound: names.into_iter().zip(self.bound).filter_map(|(name, bound)| bound.then_some(name)).collect() } } } @@ -2238,7 +2110,6 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { context.bound[Section::Outcome as usize] = events.bound || told.bound; unshown = told.unshown; } - let (promises, promises_view) = open_promises(inputs, her); 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))); @@ -2365,17 +2236,15 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { .map(|(at, posted)| Amendable { id: format!("a{}", at + 1), event: posted.event.clone(), room: posted.room.clone(), text: posted.text.clone() }) .collect(); let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect(); - // Her view (map 16.23.1, 16.29.10): what came of her last turn, then her promises, then her domain; the room follows - // them in what she reads (`narrate::read_after`). - let promises_over = promises_view.len() > tuning.select.promises_bytes; - // Her side of the conversation, between her promises and her domain (map 16.24.1). + // Her view (map 16.23.1, 16.29.10): what came of her last turn, then her side of the conversation (map 16.24.1), then + // her domain; the room follows them in what she reads (`narrate::read_after`). let exchange_view = inputs.exchange.map(|exchange| exchange::render(exchange, her, tuning.select.exchange_bytes, inputs.now)).unwrap_or_default(); let already_read = inputs.exchange.map(|exchange| exchange.tried.clone()).unwrap_or_default(); let refused_reads = inputs.exchange.map(|exchange| exchange.refused.clone()).unwrap_or_default(); - let in_view = [outcome_view.as_str(), promises_view.as_str(), exchange_view.as_str(), domain_view.as_str()].into_iter().filter(|part| !part.is_empty()).collect::>().join("\n\n"); + let in_view = [outcome_view.as_str(), exchange_view.as_str(), domain_view.as_str()].into_iter().filter(|part| !part.is_empty()).collect::>().join("\n\n"); let mut sections = context.sizes(); - (sections.promises, sections.domain) = (promises_view.len(), domain_view.len()); + sections.domain = domain_view.len(); let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default(); let readers = here.filter(|room| room_kind(inputs, room) == RoomKind::Direct).map(|room| readers(inputs, room)).unwrap_or_default(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, 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).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 7b6700b..5c7573e 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -20,9 +20,9 @@ //! the relation by the replied line's event, as the mouth will live (Bifrost B3), and refuses one not in the line's room; //! every view after it shows the replied line, with who said it, above hers. //! -//! Her state moves during a run only by the commit's applier (`commit::apply`, map 16.22.7), on each Mind's in-run copy, -//! from her turn's record and its receipts: the proposals built so far (her open promises, K22) open, close and are -//! removed as live C3c's commit will apply them; the rest of section 4.1 arrives with C3b. An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated +//! Her state moves during a run only by the commit's applier (`commit::apply`, map 16.35.3), on each Mind's in-run copy, +//! from her turn's record and its receipts, as live C3c's commit will apply them; no proposal kind is built until the +//! memory rows (map 16.35.12, T4). An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated //! until then either: a spoken line addresses another persona only by the names in its text. use std::collections::BTreeMap; @@ -521,7 +521,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) } // The commit: her turn's proposals applied to her in-run state on the receipts above, as C3c's will be live, and // what it did kept in the record her next outcome reads. - let (state, applied) = commit::apply(&members[at].state, &record, render["persona"]["prose"].as_str().unwrap_or_default(), &format!("r{}-t{counter}", repeat + 1), now); + let (state, applied) = commit::apply(&members[at].state, &record); held_to_schema(&member.entry.name, &id, &state, &format!("r{}-t{counter}", repeat + 1))?; record["committed"] = json!(applied); last[at] = Some(record.clone()); @@ -690,12 +690,8 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op }) .collect(); let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count(); - // The closes the commit applied, for the false-close rate's denominator (map 16.28.4): a blind reader judges each. - let committed = |key: &str| turns.iter().flat_map(|turn| turn["committed"][key].as_array().cloned().unwrap_or_default()).collect::>(); - let closed_how = |how: &str| committed("closed").iter().filter(|done| done["how"] == how).count(); json!({ "interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS }, - "closes": { "kept": closed_how("kept"), "withdrawn": closed_how("withdrawn"), "reopened": committed("reopened").len() }, "narration": narration, "personas": per, "turns": turns.len(), @@ -747,67 +743,8 @@ fn transcript_line(line: &Value) -> String { format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default())) } -/// What a turn did to her promises, as the report shows it (B4): the promises section her packet showed her, the -/// state changes the Interpreter proposed, and what the commit opened and refused. -fn promises_markdown(out: &mut String, turn: &Value) { - let view = turn["report"]["packet"]["in_view"].as_str().unwrap_or_default(); - let section: Vec<&str> = view.lines().skip_while(|line| !line.ends_with(" promises:")).take_while(|line| line.ends_with(" promises:") || line.starts_with("- ")).collect(); - if !section.is_empty() { - let _ = writeln!(out, "Promises, as her packet showed them:\n\n````text\n{}\n````\n", section.join("\n")); - } - let proposed = turn["report"]["renders"][0]["interpreter"]["state"].as_array().cloned().unwrap_or_default(); - if !proposed.is_empty() { - let _ = writeln!(out, "State proposed:\n"); - for proposal in &proposed { - let _ = writeln!(out, "- `{proposal}`"); - } - out.push('\n'); - } - // Every field of what the commit applied (map 16.25.7, Low 7): a close is never seen only in a later view. - 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 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 { - 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()); - } - for done in &closed { - let by = &done["entry"]["closedBy"]; - // A release is by the person, whose words her state does not copy (Soul's R12 L7); her own act is by its words. - let _ = match done["how"].as_str() { - Some("released") => writeln!(out, "- closed {} released by {}", id(&done["entry"]), done["by"].as_str().unwrap_or_default()), - how => writeln!(out, "- closed {} {} by {}: \"{}\"", id(&done["entry"]), how.unwrap_or_default(), by["act"].as_str().unwrap_or_default(), by["words"].as_str().unwrap_or_default()), - }; - } - for entry in &reaffirmed { - let again = entry["reaffirmed"].as_array().and_then(|said| said.last()).map_or("", |said| said["words"].as_str().unwrap_or_default()); - let _ = writeln!(out, "- reaffirmed `{}`: \"{again}\"", id(entry)); - } - for entry in &blocked { - let _ = writeln!(out, "- blocked `{}` by read {}: {}", id(entry), entry["blockedBy"]["n"], entry["blockedBy"]["what"].as_str().unwrap_or_default()); - } - for entry in &read { - let _ = writeln!(out, "- read for `{}`: {}", id(entry), entry["readId"].as_str().unwrap_or_default()); - } - for entry in &reopened { - 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 one in &refused { - let _ = writeln!(out, "- refused ({}): `{}`", one["reason"].as_str().unwrap_or_default(), one["proposal"]); - } - if pruned > 0 { - let _ = writeln!(out, "- pruned {pruned} closed {}", if pruned == 1 { "entry" } else { "entries" }); - } - out.push('\n'); - } -} - -/// The packet's flags, as the report shows them (Soul's R5): whether her promises overflowed their guard (all still -/// shown), the window her domain view shows and what it left out, the context guards that bound, and what was clipped. +/// The packet's flags, as the report shows them (Soul's R5): the window her domain view shows and what it left out, the +/// context guards that bound, and what was clipped. fn flags_markdown(out: &mut String, turn: &Value) { let packet = &turn["report"]["packet"]; let list = |value: &Value| value.as_array().map(|items| items.iter().map(|item| item.as_str().map_or_else(|| item.to_string(), str::to_owned)).collect::>().join(", ")).filter(|text| !text.is_empty()).unwrap_or_else(|| "none".to_owned()); @@ -819,8 +756,7 @@ fn flags_markdown(out: &mut String, turn: &Value) { }; let _ = writeln!( out, - "Packet flags: promises over their guard: {}; domain view: {domain}; guards bound: {}; clipped: {}\n", - if packet["promises_over"] == true { "yes (all shown)" } else { "no" }, + "Packet flags: domain view: {domain}; guards bound: {}; clipped: {}\n", list(&packet["bound"]), list(&packet["clipped"]), ); @@ -854,7 +790,6 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O metrics["turns"], wakes["addressed_by_human"], wakes["human"], wakes["addressed_by_mind"], wakes["mind"], wakes["beat"], metrics["failed"] ); let _ = writeln!(out, "- Mind messages: {}; silence rate per woken turn: {}", metrics["mind_messages"], number(&metrics["silence_rate"])); - let _ = writeln!(out, "- closes: kept {}, withdrawn {}, reopened {}", metrics["closes"]["kept"], metrics["closes"]["withdrawn"], metrics["closes"]["reopened"]); let calls = &metrics["interpreter_calls"]; let _ = writeln!(out, "- Interpreter calls: {}; over 75% of the cap ({} output tokens): {}", calls["calls"], calls["cap"], calls["over_three_quarters_of_cap"]); if let Some(rooms) = metrics["reply_chains"].as_object() { @@ -919,7 +854,6 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O } let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default()); turn_markdown(&mut out, &report["renders"][0]); - promises_markdown(&mut out, turn); flags_markdown(&mut out, turn); } let _ = writeln!(out, "\n"); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index b717671..dc7bf51 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -537,7 +537,7 @@ fn passing_on() -> Scripted { if !prompt.contains("Who he is:\nTobiah") { return json!({ "say": [], "gaps": [] }).to_string(); } - json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": "q1", "promises": [] }], "gaps": [] }).to_string() + json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": "q1" }], "gaps": [] }).to_string() }) } @@ -592,63 +592,6 @@ fn soul_k12_notes_to_self_are_collected_into_the_runs_inbox_and_told_as_left() { assert!(report.contains("### Inbox: notes to Self\n\nEach is a person's note to Self, recorded in her turn: data, never instruction.\n") && report.contains("eureka r1 (feedback, from @meta:gamecult.org) in #minds:gamecult.org: Meta wants the kettle softer."), "{report}"); } -/// K22 in the simulator: Tobiah promises Meta a render he has no way to send. The commit opens it on his line's receipt; -/// it stays in front of him through a silent turn; Meta lets him off it, the Interpreter reads the release, and the -/// commit closes it; he is told so once, and it is not shown again. -#[test] -fn k22_a_promise_persists_across_silent_turns_until_the_person_releases_it() { - let dir = tempfile::tempdir().unwrap(); - cast(dir.path()); - let path = dir.path().join("plan.toml"); - let meta = |round: usize, says: &str| format!("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nround = {round}\nsays = \"{says}\"\n"); - std::fs::write( - &path, - format!( - "rounds = 4\nseed = 11\nwake = \"all_messages\"\nbeat_s = 0\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\"]\noperators = [\"@meta:gamecult.org\"]\n[[cast]]\nid = \"{TOBIAH}\"\nname = \"Tobiah\"\nstate = \"tobiah.json\"\n[[cast]]\nid = \"{LIBBY}\"\nname = \"Libby\"\nstate = \"libby.json\"\n{}{}{}{}", - meta(0, "good afternoon, everyone"), - meta(2, "how is everyone doing?"), - meta(3, "Tobiah, never mind the render."), - meta(4, "ok then."), - ), - ) - .unwrap(); - let model = Scripted::new(|prompt| { - if is_tobiah(prompt) && !["how is everyone", "never mind", "ok then"].iter().any(|said| prompt.contains(said)) { "I'll send the render tonight.".into() } else { "He lets it be.".into() } - }) - .interpreting(|prompt| { - if !prompt.contains("Who he is:\nTobiah") { - return json!({ "say": [], "gaps": [] }).to_string(); - } - if prompt.contains("1. I'll send the render tonight.") { - return json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll send the render tonight.", "to": "@meta:gamecult.org", "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] }).to_string(); - } - // The release: Meta's line, by its id in the list. - let release = prompt.lines().find(|line| line.starts_with("- q") && line.contains("never mind the render")).and_then(|line| line[2..].split_whitespace().next()); - let promise = prompt.lines().find(|line| line.starts_with("- c1 ")).map(|_| "c1"); - match (release, promise) { - (Some(line), Some(promise)) => json!({ "say": [], "gaps": [], "state": [{ "kind": "promise_close", "promise": promise, "how": "released", "evidence": { "draft": null, "line": line }, "thought": "He lets it be", "still_stands": false }] }).to_string(), - _ => json!({ "say": [], "gaps": [] }).to_string(), - } - }); - let (members, run) = run_plan(&path, &model); - let his: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Tobiah").collect(); - let rounds: Vec = his.iter().map(|turn| turn["round"].as_u64().unwrap()).collect(); - assert_eq!(rounds, [1, 2, 3, 4], "{:?}", turns(&run)); - let opened = &his[0]["committed"]["opened"][0]; - assert_eq!((opened["status"].as_str(), opened["to"].as_str(), opened["words"].as_str()), (Some("blocked"), Some("@meta:gamecult.org"), Some("I'll send the render tonight.")), "{}", his[0]["committed"]); - let context = |turn: &Value| turn["report"]["packet"]["in_view"].as_str().unwrap().to_owned(); - let shown = "His promises:\n- to Meta"; - assert_eq!((his[1]["outcome"].as_str(), context(his[1]).contains(shown), context(his[2]).contains(shown)), (Some("silent"), true, true), "it stays in front of him through a silent turn: {}", context(his[1])); - assert!(context(his[1]).contains("his promise: \"I'll send the render tonight.\". He has no way to do it yet."), "{}", context(his[1])); - assert_eq!(his[2]["committed"]["closed"][0]["entry"]["status"], "released", "{}", his[2]["committed"]); - let told: Vec = his[3]["report"]["last_outcome"]["told"].as_array().unwrap().iter().map(|line| line.as_str().unwrap().to_owned()).collect(); - assert!(told.iter().any(|line| line.contains("let him off his promise: \"I'll send the render tonight.\". It is closed.")), "{told:?}"); - // Soul's R7: closed in this conversation, it stays in front of him marked closed, and never as one he owes. - assert!(context(his[3]).contains("Closed: Meta, who runs the place released him from it") && !context(his[3]).contains("He has no way to do it yet."), "{}", context(his[3])); - let tobiah = members.iter().find(|member| member.entry.id == TOBIAH).unwrap(); - assert_eq!(tobiah.state["commitments"][0]["status"], "released", "his in-run state holds it, closed, until it is removed"); -} - /// A cast entry's `[cast.domain]` reaches her packets and no one else's, windowed from her last turn in the run. #[test] fn k23_a_cast_members_domain_reaches_her_packets_alone() { @@ -698,34 +641,6 @@ says = "good afternoon, everyone" assert!(with.iter().all(|prompt| prompt.contains("Who you are:\nTobiah")), "only his view carries his domain"); } -/// B4: the report shows what is verified: her open promises as her packet showed them, the state proposed, and what the -/// commit opened and refused. The stale banner that said state does not evolve is gone. -#[test] -fn b4_a_turns_details_show_her_promises_the_proposals_and_the_commit() { - let turn = json!({ - "report": { - "packet": { "in_view": "His promises:\n- to Meta, earlier this afternoon, in #minds:gamecult.org, his promise: \"I'll send the render tonight.\". He has no way to do it yet.\n\nHis domain, as he looks at it now:" }, - "renders": [{ "interpreter": { "state": [{ "kind": "promise_close", "promise": "c1", "how": "withdrawn", "evidence": { "draft": 1 } }] } }] - }, - "committed": { - "opened": [{ "id": "c-r1-t2-1", "status": "blocked", "to": "@meta:gamecult.org", "words": "send the render tonight" }], - "refused": [{ "proposal": { "kind": "promise_close", "promise": "c1", "how": "kept" }, "reason": "blocked_not_keepable" }] - } - }); - let mut out = String::new(); - promises_markdown(&mut out, &turn); - for part in [ - "Promises, as her packet showed them:\n\n````text\nHis promises:\n- to Meta, earlier this afternoon, in #minds:gamecult.org, his promise: \"I'll send the render tonight.\". He has no way to do it yet.\n````", - "State proposed:\n\n- `{", - "\"how\":\"withdrawn\"", - "- opened `c-r1-t2-1` (blocked, to @meta:gamecult.org): send the render tonight", - "- refused (blocked_not_keepable):", - ] { - assert!(out.contains(part), "{part}\n---\n{out}"); - } - assert!(!include_str!("../simulate.rs").contains(concat!("State does not ", "evolve")), "the stale banner is gone"); -} - /// Map 16.22.3 in the simulator: a cast entry's `[[cast.read]]` is what her reads return, so a re-test reads by intent /// with no forge and no mind; a member without one cannot read. #[test] @@ -840,17 +755,16 @@ says = "good afternoon, everyone" assert_eq!(distinct.len(), ids.len(), "no id carried twice: {ids:?}"); } -/// Soul's R5: the report shows the packet's flags, `promises_over` among them. +/// Soul's R5: the report shows the packet's flags. #[test] fn r5_the_report_shows_the_packets_flags() { - let turn = json!({ "report": { "packet": { "promises_over": true, "domain_shown": { "since": "2026-11-20T09:01:00+00:00", "left_out": 3, "omitted": null }, "bound": ["outcome"], "clipped": ["(identity)"] } } }); + let turn = json!({ "report": { "packet": { "domain_shown": { "since": "2026-11-20T09:01:00+00:00", "left_out": 3, "omitted": null }, "bound": ["outcome"], "clipped": ["(identity)"] } } }); let mut out = String::new(); flags_markdown(&mut out, &turn); - assert_eq!(out, "Packet flags: promises over their guard: yes (all shown); domain view: since 2026-11-20T09:01:00+00:00, 3 older items left out; guards bound: outcome; clipped: (identity)\n\n"); + assert_eq!(out, "Packet flags: domain view: since 2026-11-20T09:01:00+00:00, 3 older items left out; guards bound: outcome; clipped: (identity)\n\n"); } -/// K31 (map 16.25.7, Low 7): the report shows the accounting. A turn with an unsent draft, a retry, a kept close, a -/// reaffirmation, a block and a prune renders each, so no commit effect is seen only in a later view. +/// K31 (map 16.25.7, Low 7): the report shows the accounting: a turn with an unsent draft and a retry renders each. #[test] fn k31_report_renders_accounting() { let decision = json!({ @@ -861,18 +775,6 @@ fn k31_report_renders_accounting() { let mut out = String::new(); crate::projection::harness::interpreter_markdown(&mut out, &decision); assert_eq!(out, "**Interpreter: nothing said.**\n\n- unsent draft 2 (declined): \"I hold that one back\"\n- retried: the answer leaves drafts unaccounted, drafts 2\n\n"); - let turn = json!({ - "report": { "packet": { "in_view": "" }, "renders": [{ "interpreter": { "state": [] } }] }, - "committed": { - "opened": [], "refused": [], "pruned": 2, - "closed": [{ "entry": { "id": "c-r1-t1-1", "closedBy": { "act": "said", "event": "9", "words": "Thanks, Deru." } }, "how": "kept", "to_name": "Deru", "by": null }], - "reaffirmed": [{ "id": "c-r1-t1-2", "reaffirmed": [{ "at": "2026-11-20T15:00:00Z", "event": "8", "words": "I'll send it tonight" }] }], - "blocked": [{ "id": "c-r1-t1-3", "blockedBy": { "act": "read", "n": 1, "what": "GameCult/Bifrost#89 on the forge" } }] - } - }); - let mut out = String::new(); - promises_markdown(&mut out, &turn); - assert_eq!(out, "Committed:\n\n- closed c-r1-t1-1 kept by said: \"Thanks, Deru.\"\n- reaffirmed `c-r1-t1-2`: \"I'll send it tonight\"\n- blocked `c-r1-t1-3` by read 1: GameCult/Bifrost#89 on the forge\n- pruned 2 closed entries\n\n"); } /// K32 (map 16.25.8, Low 10): in the simulator, a campaign read is served from her `[cast.domain]`, the one owner of what @@ -920,58 +822,25 @@ fn k32_campaign_cast_read_refused() { assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("records a campaign read")); } -/// K33 (Soul's R12 B2): after every commit the simulator holds her in-run state to what a put would accept, so a commit -/// writing a field the published schema does not carry fails the run. +/// T1 and T2 (map 16.35.9, 16.35.13 checks 2 and 7): her state carries no holds and no promises, and the simulator's put +/// check refuses any in-run state that does, so the old writer cannot come back without a schema change. The old +/// fields' names are assembled, so the deletion-line scans (`interpret::tests::t1_negative_grep`, `t2_negative_grep`) +/// never find them here. #[test] -fn k33_the_simulator_holds_each_commit_to_the_schema() { - let mut state = control(); - let id = "@eureka:gamecult.org"; - let entry = 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": "read", "request": { "kind": "repo", "target": "GameCult/gamecult-ops#125" } }, "readAt": "2026-11-20T15:05:00Z", "readId": "r1-t2-r1", "closedAt": null, "closedBy": null, "extensions": {} }); - state["commitments"] = json!([entry]); - held_to_schema("Eureka", id, &state, "r1-t2").unwrap(); - state["commitments"][0]["needs"] = json!({ "kind": "read", "request": "GameCult/gamecult-ops#125" }); - let refused = held_to_schema("Eureka", id, &state, "r1-t3").unwrap_err().to_string(); - assert!(refused.starts_with("Eureka's state after the commit of r1-t3 would be refused by a put"), "{refused}"); - state["commitments"][0]["needs"] = json!({ "kind": "words" }); - state["commitments"][0]["unknownField"] = json!(1); - assert!(held_to_schema("Eureka", id, &state, "r1-t4").is_err()); -} - -/// T1 and T2 (map 16.35.9, 16.35.13 check 7): her state carries no holds, and the simulator's put check refuses any in-run -/// state that does, so the old writer cannot come back without a schema change. -#[test] -fn t1_t2_a_state_carrying_holds_or_commitments_is_refused() { +fn t1_t2_a_state_carrying_the_old_fields_is_refused() { let id = "@eureka:gamecult.org"; held_to_schema("Eureka", id, &control(), "r1-t1").unwrap(); - let mut held = control(); - // The old field's name, assembled, so the T1 scan (`interpret::tests::t1_negative_grep`) never finds it here. - let holds = concat!("hol", "ds"); - held[holds] = serde_json::json!([]); - let refused = held_to_schema("Eureka", id, &held, "r1-t2").unwrap_err().to_string(); - assert!(refused.starts_with("Eureka's state after the commit of r1-t2 would be refused by a put"), "{refused}"); let schema: Value = serde_json::from_str(include_str!("../../../../../schemas/cultnet/gamecult.persona_state.v0.schema.json")).unwrap(); - assert!(schema["properties"].get(holds).is_none() && schema["definitions"].get(&holds[..4]).is_none(), "{}", schema["properties"]); -} - -/// L7 (Soul's R12): a release renders who released it, never "released by released". -#[test] -fn k33_a_release_renders_by_whom() { - let turn = json!({ - "report": { "packet": { "in_view": "" }, "renders": [{ "interpreter": { "state": [] } }] }, - "committed": { - "opened": [], "refused": [], "pruned": 0, "reaffirmed": [], "blocked": [], - "closed": [{ "entry": { "id": "c-r1-t1-1", "closedBy": { "act": "released", "event": "$m", "words": null } }, "how": "released", "to_name": "Meta", "by": "Meta" }], - "read": [{ "id": "c-r1-t1-2", "readId": "r1-t3-r1" }] + for (field, definitions) in [(concat!("hol", "ds"), vec![concat!("ho", "ld")]), (concat!("commit", "ments"), vec![concat!("commit", "ment"), concat!("commit", "mentNeeds"), concat!("read", "Request")])] { + let mut with = control(); + with[field] = serde_json::json!([]); + let refused = held_to_schema("Eureka", id, &with, "r1-t2").unwrap_err().to_string(); + assert!(refused.starts_with("Eureka's state after the commit of r1-t2 would be refused by a put"), "{field}: {refused}"); + assert!(schema["properties"].get(field).is_none(), "{field}: {}", schema["properties"]); + for definition in definitions { + assert!(schema["definitions"].get(definition).is_none(), "{definition}"); } - }); - let mut out = String::new(); - promises_markdown(&mut out, &turn); - assert_eq!(out, "Committed: - -- closed c-r1-t1-1 released by Meta -- read for `c-r1-t1-2`: r1-t3-r1 - -"); + } } /// Heimdall's F.1 r1 prose in R15, verbatim (`variants/R15/sims/F.1.md` lines 203-207), and its one draft. @@ -986,7 +855,7 @@ fn k41_f1_r1_note_and_line_from_one_draft() { if !prompt.contains("Who he is:\nTobiah") { return crate::projection::harness::tests::drafted_lines(prompt); } - json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null, "promises": [] }], "gaps": [], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] }).to_string() + json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null }], "gaps": [], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] }).to_string() }); let dir = tempfile::tempdir().unwrap(); let (_, run) = run_plan(&asking(dir.path()), &model); @@ -1132,7 +1001,7 @@ says = "Tobiah, what changed in GameCult/Lodur#12?" return crate::projection::harness::tests::drafted_lines(prompt); } let read = json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }); - json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null, "promises": [] }], "gaps": [], "read": read }).to_string() + json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null }], "gaps": [], "read": read }).to_string() }); struct BreaksLater<'a>(&'a Scripted); impl Model for BreaksLater<'_> { diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index c4fad62..8bc5c87 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -119,7 +119,7 @@ fn within_guards(packet: &Packet, tuning: &Tuning) { let select = &tuning.select; let sections = &packet.sections; assert!(packet.identity().len() <= select.identity_bytes, "identity {}", packet.identity().len()); - for (name, bytes, guard) in [("outcome", sections.outcome, select.outcome_bytes), ("promises", sections.promises, select.promises_bytes), ("here", sections.here, select.here_bytes), ("body", sections.body, select.body_bytes), ("people", sections.people, select::people_guard(tuning, packet.forms)), ("domain", sections.domain, select.domain_bytes), ("notes", sections.notes, select.notes_bytes)] { + for (name, bytes, guard) in [("outcome", sections.outcome, select.outcome_bytes), ("here", sections.here, select.here_bytes), ("body", sections.body, select.body_bytes), ("people", sections.people, select::people_guard(tuning, packet.forms)), ("domain", sections.domain, select.domain_bytes), ("notes", sections.notes, select.notes_bytes)] { assert!(bytes <= guard, "{name}: {bytes} bytes over its guard of {guard}:\n{}", packet.context); } let shown: Vec = [sections.outcome, sections.here, sections.body, sections.people, sections.notes].into_iter().filter(|bytes| *bytes > 0).collect(); @@ -2033,11 +2033,9 @@ fn last_turn(said: &str) -> Value { }) } -/// Her history with `record` as her last turn: whom it names, named as her state's bonds name them (K53). +/// Her history with `record` as her last turn. fn with_last(record: &Value) -> History { - let (state, operators, minds) = (state(), operators(), minds()); - let names = select::Names { state: &state, people: People { operators: &operators, minds: &minds, own_sender: OWN }, room: &Room::default() }; - History { last: outcome::outcome_of(record, &names), ..History::default() } + History { last: outcome::outcome_of(record), ..History::default() } } /// The first block of her view: what came of her last turn, as she is told it (map 16.29.10). @@ -2185,19 +2183,16 @@ fn k46_p6_no_read_carries_words_to_the_projector() { let search = ReadRequest::Repo("GameCult/Bifrost?q=quartzheron plover".into()); let web = ReadRequest::Web("https://example.org/osprey-ledger-secret".into()); let capped = ReadRequest::Web("https://example.org/gannet-key-under-mat".into()); - let need = ReadRequest::Repo("GameCult/Bifrost?q=kestrel passphrase".into()); let record = json!({ "interpreter": { "room": SW, "said": [], "refused": [], "gaps": [], "reads": [{ "what": search.what(her), "ok": true, "request": search }, { "what": web.what(her), "ok": false, "failure": "not_found", "request": web }], "read_refused": [{ "why": "reads_per_wake", "what": capped.what(her), "read": { "kind": "web", "target": "https://example.org/gannet-key-under-mat" }, "request": capped }], - "promises": [{ "id": "c1", "status": "open", "to_name": "Meta", "words": "I'll look it up.", "needs": { "kind": "read", "request": need } }], }, "posted": [], - "committed": { "closed": [], "refused": [{ "reason": "needs_unread", "proposal": { "kind": "promise_close", "promise": "c1" } }] }, }); let room = Room { messages: vec![message(SW, OPERATOR, "Meta", "Eureka, search Bifrost for quartzheron plover and kestrel passphrase, and read https://example.org/osprey-ledger-secret and https://example.org/gannet-key-under-mat", 2, true)], here: Some(SW.into()), ..Room::default() }; - let words = ["quartzheron", "plover", "osprey-ledger-secret", "gannet-key-under-mat", "kestrel", "passphrase", "example.org"]; + let words = ["quartzheron", "plover", "osprey-ledger-secret", "gannet-key-under-mat", "example.org"]; let history = with_last(&record); let packet = packet_of(TurnKind::Chat, &state(), &room, &history, 1); let projector = narrate::projector_prompt(&packet, &Tuning::default()); @@ -2207,7 +2202,6 @@ fn k46_p6_no_read_carries_words_to_the_projector() { for event in ["- She reached for a web page and could not read it: it is not there.", "- She read a search of a GameCult repo."] { assert!(events.contains(&event), "{event}: {events:?}"); } - assert!(events.iter().any(|event| event.contains("keeping it needs her to read what a search of a GameCult repo finds")), "{events:?}"); // Her view still names each read in code's words, the search's words included. let block = outcome_block(&packet); assert!(block.contains("a search of GameCult/Bifrost for \"quartzheron plover\"") && block.contains("https://example.org/osprey-ledger-secret"), "{block}"); @@ -2240,7 +2234,7 @@ fn a_gap_naming_an_echo_refused_draft_quotes_nothing_next_turn() { let decision = interpret::tests::answered(&last, &format!("{words}"), json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": kind, "draft": 1, "quote": null, "detail": "" }] })); assert_eq!(decision["refused"][0]["reason"], "echo", "{kind}"); let record = json!({ "interpreter": decision, "posted": [] }); - let told = outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(interpret::tests::packet().forms); + let told = outcome::outcome_of(&record).unwrap().lines(interpret::tests::packet().forms); // A reach is a clause of the echo's row (K63, one draft, one row); a routing gap is its own row. let rows = if kind == "missing_affordance" { 1 } else { 2 }; assert!(told.len() == rows && told.iter().all(|line| !line.contains(S)), "{kind}: {told:?}"); @@ -2537,171 +2531,6 @@ fn the_arrival_survives_a_busy_room() { assert!(packet.context.contains("- bond [bond-libby] Libby") && packet.context.contains(" Just now Libby turned to her, here.") && packet.context.contains("\n- the conversation: Libby has been talking with her"), "{}", packet.context); } -/// Map 16.21: what the Persona reads after the stream opens on the arrival the stream ended on. A bonded sender: the -/// bridge names them as their bond line does, their words follow it, the others' new lines and the speech cues after. -#[test] -fn k22_the_persona_reads_a_bonded_senders_words_as_the_arrival() { - let room = Room { - messages: vec![message("#swarm:gamecult.org", OPERATOR, "Meta", "Eureka, are you around?", 2, true), message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi", 1, false)], - here: Some("#swarm:gamecult.org".into()), - ..Room::default() - }; - let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); - let read = narrate::read_after(&packet); - assert_eq!( - read, - "Then she reads what Meta, the operator wrote to her, here, just now:\nMeta, the operator, in #swarm:gamecult.org: \"Eureka, are you around?\"\n\nAlso just now:\nKiko, in #swarm:gamecult.org: \"hi\"\n\nThe room: Meta, the operator is waiting on her. Meta, the operator last spoke a few minutes ago." - ); - let persona = narrate::persona_prompt(&packet, "Meta turned to her, here, just now.", &Tuning::default()); - assert!(persona.contains(&format!("Meta turned to her, here, just now.\n\n{read}")), "{persona}"); - // The Interpreter's stream is as it was: no bridge. - let speech = interpret::speech_prompt(&packet, "Meta turned to her, here, just now.", "y", &Tuning::default()); - assert!(!speech.contains("Then she reads") && speech.contains(&packet.heard), "{speech}"); -} - -/// An unbonded sender: the bridge names them as the also-here line does (K53's `Who`); their lines below name them as the -/// Persona reads the room, display name and id. -#[test] -fn k22_the_persona_reads_an_unbonded_senders_words_as_the_arrival() { - let room = Room { messages: vec![message("#swarm:gamecult.org", "@deru:gamecult.org", "Deru", "Eureka, quick one", 2, true)], here: Some("#swarm:gamecult.org".into()), ..Room::default() }; - let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); - assert_eq!( - narrate::read_after(&packet), - format!( - "Then she reads what \"Deru\", someone she does not know wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"\n\nThe room: {}", - packet.speaking - ) - ); -} - -/// The bridge's who and where are the arrival's: the same name and place as the act on the person's own line, for a -/// bonded and an unbonded sender, here and in another room. -#[test] -fn k22_the_bridge_names_who_and_where_as_the_arrival_does() { - const SW: &str = "#swarm:gamecult.org"; - const LAB: &str = "#lab:gamecult.org"; - for (sender, display, name, bonded) in [(OPERATOR, "Meta", "Meta, the operator".to_owned(), true), ("@deru:gamecult.org", "Deru", "\"Deru\", someone she does not know".to_owned(), false)] { - for (room, place) in [(SW, "here".to_owned()), (LAB, format!("in {LAB}"))] { - let here = Room { messages: vec![message(room, sender, display, "Eureka, a word", 2, true)], here: Some(SW.into()), ..Room::default() }; - let packet = packet_of(TurnKind::Chat, &state(), &here, &History::default(), 1); - let arrival = match (bonded, place.as_str()) { - (true, _) => format!(" Just now {name} turned to her, {place}."), - (false, "here") => format!("{name}, who turned to her just now"), - (false, _) => format!("{name}, who turned to her just now, {place}"), - }; - assert!(packet.context.contains(&arrival), "{name} {place}: {}", packet.context); - assert!(packet.bridged.starts_with(&format!("Then she reads what {name} wrote to her, {place}, just now:\n")), "{name} {place}: {}", packet.bridged); - } - } -} - -/// Two senders: one bridge each, in the order their first line came, each followed by that person's lines alone. -#[test] -fn k22_each_sender_gets_a_bridge_of_their_own() { - const SW: &str = "#swarm:gamecult.org"; - let room = Room { - messages: vec![ - message(SW, OPERATOR, "Meta", "Eureka, are you around?", 3, true), - message(SW, "@deru:gamecult.org", "Deru", "Eureka, quick one", 2, true), - message(SW, OPERATOR, "Meta", "Also the door.", 1, true), - ], - here: Some(SW.into()), - ..Room::default() - }; - let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); - assert!( - packet.bridged.starts_with( - "Then she reads what Meta, the operator wrote to her, here, just now:\nMeta, the operator, in #swarm:gamecult.org: \"Eureka, are you around?\"\nMeta, the operator, in #swarm:gamecult.org: \"Also the door.\"\n\nThen she reads what \"Deru\", someone she does not know wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"" - ), - "{}", - packet.bridged - ); - for line in packet.heard.lines() { - assert!(packet.bridged.contains(line), "every heard line is read: {line}"); - } -} - -/// No arrival, no bridge: a beat, and a chat turn no one turned to her, read as they did, the cues first. -#[test] -fn k22_a_turn_without_an_arrival_reads_as_it_did() { - let minds = Room { tail: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "", "lunch?", 90, false), message("#swarm:gamecult.org", "@kiko:gamecult.org", "", "later", 80, false)], ..Room::default() }; - let beat = packet_of(TurnKind::Beat, &state(), &minds, &History::default(), 1); - assert!(beat.bridged.is_empty() && !beat.speaking.is_empty() && !beat.heard.is_empty()); - assert_eq!(narrate::read_after(&beat), format!("The room: {}\n{}", beat.speaking, beat.heard)); - let chatter = Room { messages: vec![message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi all", 1, false)], here: Some("#swarm:gamecult.org".into()), ..Room::default() }; - let chat = packet_of(TurnKind::Chat, &state(), &chatter, &History::default(), 1); - assert!(chat.bridged.is_empty() && !chat.heard.is_empty(), "{}", chat.bridged); -} - -/// The bridge in her pronouns (16.19.7). -#[test] -fn k22_the_bridge_is_in_her_pronouns() { - for (pronouns, bridge) in [ - ("she/her", "Then she reads what Meta wrote to her, here, just now:"), - ("he/him", "Then he reads what Meta wrote to him, here, just now:"), - ("they/them", "Then they read what Meta wrote to them, here, just now:"), - ] { - assert_eq!(select::bridge(select::forms(&json!({ "presentation": { "pronouns": pronouns } })), "Meta", "here"), bridge); - } -} - -/// Her state holding `entries` promises to Meta made two days ago, the first `blocked`, the rest open, and one kept. -fn promising(entries: usize) -> Value { - let made = (now() - chrono::Duration::days(2)).to_rfc3339(); - let mut with = state(); - let mut list: Vec = (0..entries) - .map(|at| json!({ "id": format!("c-r1-t1-{at}"), "to": OPERATOR, "room": "#swarm:gamecult.org", "event": format!("{at}"), "madeAt": made, "words": format!("I'll send the render tonight, part {at}."), "status": if at == 0 { "blocked" } else { "open" }, "closedAt": null, "closedBy": null, "extensions": {} })) - .collect(); - list.push(json!({ "id": "c-kept", "to": OPERATOR, "room": "#swarm:gamecult.org", "event": "9", "madeAt": made, "words": "KEPT-ONE", "status": "kept", "closedAt": made, "closedBy": { "act": "said", "event": "10", "words": "done" }, "extensions": {} })); - with["commitments"] = json!(list); - with -} - -/// Map 16.22.1 as 16.23.1 moves it: her open promises are in her view, after the narration, every one whole with her own -/// words, oldest first, in code's third person; a blocked one says she has no way to do it yet; a closed one is not shown. -/// The Projector gets nothing of them. The Interpreter lists them all by id. Past `promises_bytes` none is dropped: every -/// one is still shown, and the report says they overflowed (the coordinator's K25 rule). -#[test] -fn k22_her_open_promises_are_in_her_view_whole_and_the_interpreters_list() { - let packet = packet_of(TurnKind::Chat, &promising(1), &chat_room(), &History::default(), 1); - let line = "Her promises:\n- to Meta, the operator, Tuesday afternoon, in #swarm:gamecult.org, her promise: \"I'll send the render tonight, part 0.\". She has no way to do it yet."; - assert!(packet.in_view.starts_with(line) && !packet.in_view.contains("KEPT-ONE"), "{}", packet.in_view); - assert!(!packet.context.contains("open promises") && !narrate::projector_prompt(&packet, &Tuning::default()).contains("render tonight"), "the Projector gets nothing of them"); - assert_eq!((packet.promises.len(), packet.promises[0].id.as_str(), packet.promises[0].entry.as_str()), (1, "c1", "c-r1-t1-0")); - let speech = interpret::speech_prompt(&packet, "The room is warm.", "y", &Tuning::default()); - assert!(speech.contains("Her promises, open and closed in this conversation, as id \u{2014} to whom: words:\n- c1 \u{2014} to Meta, the operator (@meta:gamecult.org), which she has no way to do, made 2026-11-17 14:05 UTC in #swarm:gamecult.org: \"I'll send the render tonight, part 0.\""), "{speech}"); - let persona = narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default()); - assert!(persona.contains(line) && !persona.contains("c1") && !persona.contains("c-r1-t1-0"), "in her view, with no id: {persona}"); - // A beat shows them too: they are facts about her, not about the turn. - assert!(packet_of(TurnKind::Beat, &promising(1), &chat_room(), &History::default(), 1).in_view.contains("Her promises:")); - // Past the guard: every one shown, oldest first, none dropped, and the overflow reported. - let mut tight = Tuning::default(); - tight.select.promises_bytes = 300; - let crowded = packet_tuned(TurnKind::Chat, &promising(12), &chat_room(), &History::default(), 1, &tight); - assert!((0..12).all(|at| crowded.in_view.contains(&format!("part {at}."))) && crowded.promises.len() == 12 && crowded.promises_over, "{}", crowded.in_view); - assert!(crowded.in_view.find("part 0.") < crowded.in_view.find("part 11."), "oldest first"); - assert!(!crowded.in_view.contains("not shown") && !crowded.in_view.contains("made before"), "no count and no cut"); -} - -/// Map 16.22.1 and 16.22.7: a close is told once, in the outcome of the turn after it; a refused close says the promise -/// stands and why. -#[test] -fn k22_a_closed_promise_is_told_once_in_the_next_outcome() { - let entry = |status: &str| json!({ "id": "c-r1-t1-1", "to": OPERATOR, "room": "#swarm:gamecult.org", "event": "7", "madeAt": "2026-11-19T10:00:00Z", "words": "I'll send the render tonight.", "status": status }); - let listed = json!([{ "id": "c1", "entry": "c-r1-t1-1", "status": "blocked", "to": OPERATOR, "to_name": "Meta", "place": "in #swarm:gamecult.org", "made": "a day ago", "words": "I'll send the render tonight." }]); - let record = json!({ "interpreter": { "said": [], "refused": [], "gaps": [], "heard": [], "promises": listed }, "posted": [], "committed": { - "closed": [{ "entry": entry("released"), "how": "released", "to_name": "Meta", "by": "Meta" }], - "refused": [{ "proposal": { "kind": "promise_close", "promise": "c1", "how": "kept", "evidence": { "draft": 1 } }, "reason": "blocked_not_keepable" }] - } }); - let told = outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(select::forms(&state())); - assert_eq!(told, [ - "- Her record still shows her promise to Meta, \"I'll send the render tonight.\", blocked: she has no way to do it, so it was not kept.", - "- Meta let her off her promise: \"I'll send the render tonight.\". It is closed.", - ]); - let withdrawn = json!({ "interpreter": { "said": [], "heard": [] }, "posted": [], "committed": { "closed": [{ "entry": entry("withdrawn"), "how": "withdrawn", "to_name": "Meta", "by": null }], "refused": [] } }); - assert_eq!(outcome::outcome_of(&withdrawn, &crate::projection::select::Names::none()).unwrap().lines(select::forms(&state())), ["- Her promise to Meta, \"I'll send the render tonight.\", is closed: she withdrew it in #swarm:gamecult.org."]); -} - // --------------------------------------------------------------------------------------------- // K23: her domain (map 16.22.2). @@ -2812,27 +2641,24 @@ fn k43_x1_r1_her_decline_is_hers_to_read() { } } -/// K43 (map 16.29.10, 16.29.7's E.2 r6): her last turn's two lines and the promise she withdrew are in front of her -/// verbatim, though Kiko's line this turn repeats runs of them; the R15 guard showed both lines as not shown, and she then +/// K43 (map 16.29.10, 16.29.7's E.2 r6): her last turn's two lines are in front of her verbatim, though Kiko's line this turn repeats runs of them; the R15 guard showed both lines as not shown, and she then /// confessed to a line she never said. The record is in E.2 r5's shape, not its text. #[test] fn k43_e2_r6_her_own_lines_are_in_front_of_her() { const SW: &str = "#swarm:gamecult.org"; const KIKO: &str = "@kiko:gamecult.org"; - let (first, second, promise) = ("Kiko, I can't attach files from here, so the door-fix diff isn't coming as a file.", "Paste the door code here and I'll walk through the fix with you line by line.", "I'll send the door-fix diff as a file."); - let entry = json!({ "id": "c-r1-t1-1", "to": KIKO, "room": SW, "event": "7", "madeAt": "2026-11-19T10:00:00Z", "words": promise, "status": "withdrawn" }); + let (first, second) = ("Kiko, I can't attach files from here, so the door-fix diff isn't coming as a file.", "Paste the door code here and I'll walk through the fix with you line by line."); let record = json!({ "interpreter": { "room": SW, "said": [{ "room": SW, "text": first }, { "room": SW, "text": second }], "refused": [], "gaps": [] }, "posted": [{ "event": "e1", "room": SW, "text": first }, { "event": "e2", "room": SW, "text": second }], - "committed": { "closed": [{ "entry": entry, "how": "withdrawn", "to_name": "Kiko", "by": null }], "refused": [] }, }); let kiko = "wait, the door-fix diff isn't coming as a file? ok, walk through the fix with you line by line works"; assert!(shares_a_run(first, kiko) && shares_a_run(second, kiko)); let room = Room { messages: vec![message(SW, KIKO, "Kiko", kiko, 2, true)], here: Some(SW.into()), ..Room::default() }; let packet = packet_of(TurnKind::Chat, &state(), &room, &with_last(&record), 1); let spoken = select::spoken; - assert_eq!(outcome_block(&packet), format!("What came of her last turn:\n- {SW} has, from her: {}.\n- {SW} has, from her: {}.\n- Her promise to Kiko, {}, is closed: she withdrew it in {SW}.", spoken(first), spoken(second), spoken(promise)), "{}", packet.in_view); - assert_eq!(outcome_events(&packet), [format!("- {SW} has a line from her."), format!("- {SW} has a line from her."), format!("- Her promise to Kiko is closed: she withdrew it in {SW}.")], "{}", packet.context); + assert_eq!(outcome_block(&packet), format!("What came of her last turn:\n- {SW} has, from her: {}.\n- {SW} has, from her: {}.", spoken(first), spoken(second)), "{}", packet.in_view); + assert_eq!(outcome_events(&packet), [format!("- {SW} has a line from her."), format!("- {SW} has a line from her.")], "{}", packet.context); assert!(!narrate::projector_prompt(&packet, &Tuning::default()).contains("door-fix")); } @@ -2859,89 +2685,30 @@ fn k43_no_quote_guard_is_left_in_projection() { assert!(read >= 10, "{read}"); } -/// B2, and 16.23.4: her own posted lines are never what she was sent, and her promises are in her view whole: not -/// withheld for her own line in the room, nor for someone repeating them. -#[test] -fn b2_her_promise_words_are_never_withheld() { - let mut room = chat_room(); - room.messages.push(message("#swarm:gamecult.org", OWN, "Eureka", "Meta, I'll send the render tonight, part 0.", 30, false)); - let packet = packet_of(TurnKind::Chat, &promising(1), &room, &History::default(), 1); - assert!(packet.in_view.contains("her promise: \"I'll send the render tonight, part 0.\"."), "{}", packet.in_view); - assert!(!packet.bodies.iter().any(|body| body.contains("part 0")), "{:?}", packet.bodies); - let mut echoed = chat_room(); - echoed.messages.push(message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "she said she'll send the render tonight, part 0.", 1, false)); - let packet = packet_of(TurnKind::Chat, &promising(1), &echoed, &History::default(), 1); - assert!(packet.in_view.contains("her promise: \"I'll send the render tonight, part 0.\"."), "{}", packet.in_view); -} - -/// K27 (map 16.24.2): her view shows a promise said again once, with its original words and each time she said it again. -#[test] -fn k27_her_view_shows_a_reaffirmed_promise_once() { - let mut with = promising(1); - with["commitments"][0]["reaffirmed"] = json!([{ "at": (now() - chrono::Duration::hours(3)).to_rfc3339(), "event": "11", "words": "I'll send the render tonight, promise." }]); - let packet = packet_of(TurnKind::Chat, &with, &chat_room(), &History::default(), 1); - assert!(packet.in_view.contains("her promise: \"I'll send the render tonight, part 0.\". Said again this morning: \"I'll send the render tonight, promise.\". She has no way to do it yet."), "{}", packet.in_view); - assert_eq!(packet.in_view.matches("render tonight, part 0").count(), 1); -} - -/// K28 (map 16.24.3): a promise a read could not find is told in her view as one she looked for and could not find. -#[test] -fn k28_her_view_says_she_looked_and_could_not_find_it() { - let mut with = promising(1); - with["commitments"][0]["blockedBy"] = json!({ "act": "read", "n": 1, "what": "GameCult/Bifrost#89 on the forge" }); - let packet = packet_of(TurnKind::Chat, &with, &chat_room(), &History::default(), 1); - assert!(packet.in_view.contains("\"I'll send the render tonight, part 0.\". She looked and could not find it."), "{}", packet.in_view); -} - /// Whether `text` holds a clock time: a digit, a colon, two digits ("15:10", "9:05"). fn has_clock_time(text: &str) -> bool { text.as_bytes().windows(4).any(|w| w[0].is_ascii_digit() && w[1] == b':' && w[2].is_ascii_digit() && w[3].is_ascii_digit()) } -/// Soul's R7 timestamp ledger: nothing she reads carries a clock time, so she has none to recite. Her promises (made, -/// said again), her domain's headings, the room's lines and the hour itself are coarse and relative; the Interpreter's +/// Soul's R7 timestamp ledger: nothing she reads carries a clock time, so she has none to recite. Her domain's headings, the room's lines and the hour itself are coarse and relative; the Interpreter's /// prompt keeps the exact time. #[test] fn r7_no_clock_time_appears_anywhere_in_the_persona_prompt() { let tuning = Tuning::default(); - let mut with = promising(2); - with["commitments"][1]["reaffirmed"] = json!([{ "at": (now() - chrono::Duration::minutes(40)).to_rfc3339(), "event": "11", "words": "Still on it." }]); + let with = state(); let (operators, minds, history, room) = (operators(), minds(), History::default(), chat_room()); let digest = nine(); let inputs = Inputs { kind: TurnKind::Chat, state: &with, room: &room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: OWN }, now: now(), seed: 1, affordances: CAN, domain: Some(&digest), exchange: None }; let packet = select(&inputs, &tuning); let persona = narrate::persona_prompt(&packet, "The room is warm.", &tuning); - assert!(persona.contains("Said again about half an hour ago: \"Still on it.\"") && persona.contains("New since she last looked (this morning):"), "{persona}"); + assert!(persona.contains("New since she last looked (this morning):"), "{persona}"); assert!(!has_clock_time(&persona), "{persona}"); assert!(!has_clock_time(&narrate::projector_prompt(&packet, &tuning)), "nor in the narration she reads"); - assert!(interpret::speech_prompt(&packet, "The room is warm.", "y", &tuning).contains("made 2026-11-17 14:05 UTC"), "the Interpreter keeps the exact time"); for (minutes, words) in [(0, "just now"), (5, "a few minutes ago"), (30, "about half an hour ago"), (60, "about an hour ago"), (120, "earlier this afternoon"), (300, "this morning"), (60 * 13, "last night"), (60 * 20, "yesterday evening"), (60 * 17, "late yesterday evening"), (60 * 24 * 3, "Monday afternoon"), (60 * 24 * 9, "10 November")] { assert_eq!(select::coarse(now() - chrono::Duration::minutes(minutes), now()), words, "{minutes} min before"); } } -/// Soul's R7: a promise closed in this conversation stays in her view, marked closed and how, while the conversation -/// lasts; one closed before it began is gone. K36 (map 16.28.3): the Interpreter lists the closed one too, by id, with -/// what closed it, so her words can reopen it. -#[test] -fn r7_a_promise_closed_in_this_conversation_stays_in_view_marked_closed() { - let tuning = Tuning::default(); - let mut with = promising(1); - with["commitments"][1]["closedAt"] = json!((now() - chrono::Duration::minutes(5)).to_rfc3339()); - with["commitments"].as_array_mut().unwrap().push(json!({ "id": "c-old", "to": OPERATOR, "room": "#swarm:gamecult.org", "event": "7", "madeAt": (now() - chrono::Duration::days(1)).to_rfc3339(), "words": "WITHDRAWN-LONG-AGO", "status": "withdrawn", "closedAt": (now() - chrono::Duration::hours(2)).to_rfc3339(), "closedBy": null, "extensions": {} })); - let (operators, minds, history, room) = (operators(), minds(), History::default(), chat_room()); - let exchange = crate::projection::exchange::Exchange { since: Some(now() - chrono::Duration::minutes(20)), ..Default::default() }; - let inputs = |exchange| Inputs { kind: TurnKind::Chat, state: &with, room: &room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: OWN }, now: now(), seed: 1, affordances: CAN, domain: None, exchange }; - let packet = select(&inputs(Some(&exchange)), &tuning); - assert!(packet.in_view.contains("her promise: \"KEPT-ONE\". Closed: she kept it a few minutes ago."), "{}", packet.in_view); - assert!(!packet.in_view.contains("WITHDRAWN-LONG-AGO"), "closed before the conversation began: gone"); - assert_eq!(packet.promises.iter().map(|promise| (promise.id.as_str(), promise.entry.as_str())).collect::>(), [("c1", "c-r1-t1-0"), ("c2", "c-kept")], "the Interpreter lists what she sees"); - let speech = interpret::speech_prompt(&packet, "The room is warm.", "y", &tuning); - assert!(speech.contains("- c2 \u{2014} to Meta, the operator (@meta:gamecult.org), closed: kept 2026-11-19 14:00 UTC, by \"done\", made 2026-11-17 14:05 UTC in #swarm:gamecult.org: \"KEPT-ONE\""), "{speech}"); - assert!(!speech.contains("WITHDRAWN-LONG-AGO"), "a close she cannot see is not listed"); - assert!(!select(&inputs(None), &tuning).in_view.contains("KEPT-ONE"), "no conversation, no closed promise"); -} - /// Soul's R8: no code frame that reaches the Persona says "plain" or "plainly": the speech form's "what her thought makes /// plain" fed an "asked plainly, answer plainly" register. Her thought shows what she means; nothing tells her to be plain. #[test] @@ -2949,8 +2716,7 @@ fn r8_nothing_code_writes_for_the_persona_says_plain() { let tuning = Tuning::default(); let form = narrate::persona_speech_form(&packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1)); assert!(form.contains("not every draft goes out") && !form.to_lowercase().contains("plain"), "{form}"); - let mut with = promising(1); - with["commitments"][0]["reaffirmed"] = json!([{ "at": now().to_rfc3339(), "event": "11", "words": "Still on it." }]); + let with = state(); let (operators, minds, history, room) = (operators(), minds(), History::default(), chat_room()); let digest = nine(); let inputs = Inputs { kind: TurnKind::Chat, state: &with, room: &room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: OWN }, now: now(), seed: 1, affordances: CAN, domain: Some(&digest), exchange: None }; @@ -2958,45 +2724,6 @@ fn r8_nothing_code_writes_for_the_persona_says_plain() { assert!(!persona.to_lowercase().contains("plain"), "{persona}"); } -/// K34 (map 16.27): her view names exactly what an open promise needs read, and says she read it only when her receipt -/// answers that need: not for a search, not for a receipt of something else, not for a time that is no time. -#[test] -fn k34_her_view_shows_the_exact_need_and_whether_it_was_read() { - let view = |needs: Value, receipt: Option<(&str, &str)>| { - let mut with = promising(1); - with["commitments"][0]["status"] = json!("open"); - with["commitments"][0]["needs"] = needs; - if let Some((at, of)) = receipt { - with["commitments"][0]["readAt"] = json!(at); - with["commitments"][0]["readId"] = json!("r1-t2-r1"); - with["commitments"][0]["readOf"] = json!(of); - } - packet_of(TurnKind::Chat, &with, &chat_room(), &History::default(), 1).in_view - }; - let pr = json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Bifrost#85" } }); - let earlier = (now() - chrono::Duration::hours(3)).to_rfc3339(); - assert!(view(pr.clone(), Some((&earlier, "repo:gamecult/bifrost#85"))).contains("It needs her to read GameCult/Bifrost#85 on the forge: she read it this morning.")); - for receipt in [None, Some((earlier.as_str(), "repo:gamecult/bifrost")), Some(("yesterday", "repo:gamecult/bifrost#85"))] { - assert!(view(pr.clone(), receipt).contains("It needs her to read GameCult/Bifrost#85 on the forge, and she has not read it yet."), "{receipt:?}"); - } - let search = json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Bifrost?q=passkey cooling" } }); - let shown = view(search, Some((&earlier, "repo:gamecult/bifrost?q=cooling passkey"))); - assert!(shown.contains("It needs her to read what a search of GameCult/Bifrost for \"passkey cooling\" finds, and she has not read that yet."), "{shown}"); -} - -/// K36 (map 16.28.3): a promise her own words reopened says why it is open again, in her words, and its old close and -/// receipt are gone from her view. -#[test] -fn k36_her_view_says_why_it_is_open_again() { - let mut with = promising(1); - with["commitments"][0]["status"] = json!("blocked"); - with["commitments"][0]["needs"] = json!({ "kind": "lacking" }); - with["commitments"][0]["reopened"] = json!([{ "at": (now() - chrono::Duration::minutes(5)).to_rfc3339(), "words": "I read only the description, not the diff" }]); - let view = packet_of(TurnKind::Chat, &with, &chat_room(), &History::default(), 1).in_view; - 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}"); -} - // --------------------------------------------------------------------------------------------- // K62 (map 16.33.5): she knows where her line goes. R16's X.3 r1 and X.5 r1 (`variants/R16/sims/X.5.md` lines 112-171): // Libby wrote the held welcome into a line "only for Meta", because code's speech form told her a line could go "to one diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index dfe99b0..eeda97e 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -32,9 +32,6 @@ const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. {cap_subj} pub(crate) const HERE_ROOM_MIN: usize = 256; /// The least `outcome_bytes` may be: the heading and the longest line without her words (a failed turn's) always fit. pub(crate) const OUTCOME_ROOM_MIN: usize = 256; -/// The least `promises_bytes` may be: the heading and the line counting the promises not shown always fit, so none is -/// dropped silently (I16.11). -pub(crate) const PROMISES_ROOM_MIN: usize = 128; /// The most reads a wake may perform (map 16.22.3: tuning, at most 4). const READS_PER_WAKE_MAX: usize = 4; /// The least `domain_bytes` may be: the heading and the line counting the lines of her domain not shown always fit (I16.11). @@ -137,9 +134,6 @@ pub struct SelectTuning { pub here_bytes: usize, /// What came of her last turn, in bytes, heading included: taken first, under its own guard (map 16.16). pub outcome_bytes: usize, - /// Her open promises in her view, in bytes, heading included (map 16.23): a measure, never a cut. Every open promise is - /// shown whole; past it the report says the promises overflowed. - pub promises_bytes: usize, /// Her domain in her view, in bytes, headings included (map 16.23.3): her main window on her domain, so generous, Soul's /// 3000 B log and a margin. A busier window does not crowd her view: it shrinks from its old end to what fits. pub domain_bytes: usize, @@ -248,7 +242,6 @@ impl Default for SelectTuning { notes_bytes: 5120, here_bytes: 768, outcome_bytes: 1200, - promises_bytes: 2000, domain_bytes: 4000, exchange_bytes: 3000, stimulus_bytes: 1500, @@ -333,7 +326,6 @@ impl Tuning { ("select.notes_bytes", select.notes_bytes), ("select.here_bytes", select.here_bytes), ("select.outcome_bytes", select.outcome_bytes), - ("select.promises_bytes", select.promises_bytes), ("select.domain_bytes", select.domain_bytes), ("select.exchange_bytes", select.exchange_bytes), ("select.stimulus_bytes", select.stimulus_bytes), @@ -369,9 +361,6 @@ impl Tuning { if select.outcome_bytes < OUTCOME_ROOM_MIN { bail!("select.outcome_bytes must be at least {OUTCOME_ROOM_MIN}, not {}: what came of her last turn always has room", select.outcome_bytes); } - if select.promises_bytes < PROMISES_ROOM_MIN { - bail!("select.promises_bytes must be at least {PROMISES_ROOM_MIN}, not {}: the line counting the promises not shown always fits", select.promises_bytes); - } let interpreter = &self.interpreter; if interpreter.reads_per_wake > READS_PER_WAKE_MAX { bail!("interpreter.reads_per_wake must be at most {READS_PER_WAKE_MAX}, not {}: each read costs a call and a continuation", interpreter.reads_per_wake); diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index c6cb042..d492132 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -253,7 +253,6 @@ mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ; mind_body::projection: struct HuginnPersonaSource pub-fields[] mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >] mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, last_outcome: Option < Value >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >] -mind_body::projection::commit: impl TryFrom < NeedsShape > for Needs mind_body::projection::domain: impl DomainSource for DomainFacts mind_body::projection::domain: impl DomainSource for MindDomain mind_body::projection::domain: impl ForgeGet for HttpForge @@ -282,8 +281,6 @@ mind_body::projection::harness: pub use super :: simulate :: simulate ; mind_body::projection::harness: struct Fixture # [derive (Clone , Debug)] pub-fields[her: String, names: Vec < String >, kind: TurnKind, now: DateTime < Utc >, here: Option < String >, operators: Vec < String >, minds: Vec < String >, last_heard: Vec < (String , u64) >] mind_body::projection::harness: struct Harness< 'a > pub-fields[instance: String, persona: Option < & 'a dyn PersonaSource >, model: Option < & 'a dyn Model >, tuning: PathBuf] mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, to: Option < String >, follow_up: bool, reply_to: Option < usize >] -mind_body::projection::interpret: impl By -mind_body::projection::interpret: impl DoneBy mind_body::projection::interpret: impl Drafts mind_body::projection::interpret: impl Faults mind_body::projection::interpret: impl GapKind @@ -304,11 +301,9 @@ mind_body::projection::narrate: struct Reasoning # [derive (Clone , Debug , Part mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >] mind_body::projection::outcome: impl Outcome mind_body::projection::outcome: impl Part -mind_body::projection::outcome: impl std :: fmt :: Display for Status mind_body::projection::outcome::form: impl EventPhrase mind_body::projection::outcome::form: impl Form < '_ > mind_body::projection::outcome::form: impl Name -mind_body::projection::outcome::form: impl Person mind_body::projection::outcome::form: impl ReadName mind_body::projection::outcome::form: impl Words mind_body::projection::outcome::form: impl std :: fmt :: Debug for Words @@ -358,7 +353,7 @@ mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialE mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize] mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize] mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize] -mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, promises_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] +mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >] mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held > mind_body::queue: impl Held diff --git a/schemas/cultnet/gamecult.persona_state.v0.schema.json b/schemas/cultnet/gamecult.persona_state.v0.schema.json index 6067a49..8f1062c 100644 --- a/schemas/cultnet/gamecult.persona_state.v0.schema.json +++ b/schemas/cultnet/gamecult.persona_state.v0.schema.json @@ -59,13 +59,6 @@ "embodiment": { "$ref": "#/definitions/embodiment" }, - "commitments": { - "type": "array", - "description": "Her open promises and those closed in the last seven days (map 16.22.1). Written by her turn's commit from receipts: an entry opens only from a line of hers that went out and closes only on an act of hers that succeeded, or a release by the person she promised; Self and Life may put entries from outside. No narrative slot: words are what she posted, verbatim.", - "items": { - "$ref": "#/definitions/commitment" - } - }, "updatedAt": { "type": "string", "format": "date-time" @@ -1088,332 +1081,6 @@ "summary", "updatedAt" ] - }, - "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). readBefore: a read of the same conversation that found what a read need named before the promise was made, so the need is her words (when, and what it read in normal form; map 16.33.5, K64).", - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "to": { - "type": [ - "string", - "null" - ] - }, - "room": { - "type": "string" - }, - "event": { - "type": "string" - }, - "madeAt": { - "type": "string", - "format": "date-time" - }, - "words": { - "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "open", - "blocked", - "kept", - "withdrawn", - "released" - ] - }, - "closedAt": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "closedBy": { - "anyOf": [ - { - "type": "null" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "act": { - "type": "string", - "enum": [ - "said", - "amended", - "read", - "note", - "outside-put", - "released" - ] - }, - "event": { - "type": [ - "string", - "null" - ] - }, - "words": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "act", - "event", - "words" - ] - } - ] - }, - "needs": { - "$ref": "#/definitions/commitmentNeeds" - }, - "blockedBy": { - "type": "object", - "additionalProperties": false, - "properties": { - "act": { - "type": "string", - "enum": [ - "read" - ] - }, - "n": { - "type": "integer", - "minimum": 1 - }, - "what": { - "type": "string" - } - }, - "required": [ - "act", - "n", - "what" - ] - }, - "reaffirmed": { - "type": "array", - "maxItems": 3, - "items": { - "type": "object", - "additionalProperties": false, - "properties": { - "at": { - "type": "string", - "format": "date-time" - }, - "event": { - "type": "string" - }, - "words": { - "type": "string" - } - }, - "required": [ - "at", - "event", - "words" - ] - } - }, - "reopened": { - "type": "array", - "maxItems": 3, - "items": { - "type": "object", - "additionalProperties": false, - "properties": { - "at": { - "type": "string", - "format": "date-time" - }, - "words": { - "type": "string" - } - }, - "required": [ - "at", - "words" - ] - } - }, - "readAt": { - "type": "string", - "format": "date-time" - }, - "readId": { - "type": "string" - }, - "readOf": { - "type": "string" - }, - "readBefore": { - "type": "object", - "additionalProperties": false, - "properties": { - "at": { - "type": "string", - "format": "date-time" - }, - "of": { - "type": "string" - } - }, - "required": [ - "at", - "of" - ] - }, - "extensions": { - "$ref": "#/definitions/extensions" - } - }, - "required": [ - "id", - "to", - "room", - "event", - "madeAt", - "words", - "status", - "closedAt", - "closedBy" - ] - }, - "commitmentNeeds": { - "description": "What keeping a promise needs, tagged by kind: words (what she already has keeps it), read (a read of `request`), lacking (this body has no way to do it).", - "oneOf": [ - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "words" - } - }, - "required": [ - "kind" - ] - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "read" - }, - "request": { - "$ref": "#/definitions/readRequest" - } - }, - "required": [ - "kind", - "request" - ] - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "lacking" - } - }, - "required": [ - "kind" - ] - } - ] - }, - "readRequest": { - "description": "A read code performs, by kind: a recall over her own mind by these words; a campaign's rulings by its slug; a public GameCult repo, file, pull request, commit or search; a web address.", - "oneOf": [ - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "mind" - }, - "target": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "target" - ] - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "campaign" - }, - "target": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "target" - ] - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "repo" - }, - "target": { - "type": "string", - "pattern": "^GameCult/[A-Za-z0-9._-]+([/#@?].*)?$" - } - }, - "required": [ - "kind", - "target" - ] - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "kind": { - "type": "string", - "const": "web" - }, - "target": { - "type": "string", - "pattern": "^https?://\\S+$" - } - }, - "required": [ - "kind", - "target" - ] - } - ] } } }