diff --git a/crates/mind-body/fixtures/interpret/golden-speech.txt b/crates/mind-body/fixtures/interpret/golden-speech.txt index d0c84e1..bbc05f0 100644 --- a/crates/mind-body/fixtures/interpret/golden-speech.txt +++ b/crates/mind-body/fixtures/interpret/golden-speech.txt @@ -8,7 +8,7 @@ A draft is speech only when his prose shows him choosing to send it now. Wonderi He speaks only in this room. What he knows privately is listed below as private: he says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge. -Answer with the speech contract's object. `say` lists the drafts he sends now, each by its number, with the Matrix ids of anyone listed whom he addresses directly (`mentions`), the id of the line listed below that he answers or passes on (`in_reply_to`, or null: the room shows that line, with who said it, above his own words), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom he promises it (`to`, null when he promises it to the room), when it promises again one of his open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what he already has keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what he meant and did not send. `unsent` accounts for each of his drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`); superseded, when a later draft or later prose of his replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to him this turn is held only when his prose says he holds it. `amend` adds to one of his own lines listed below, at most one a turn, only when his thought shows him choosing to correct or add to that line: name the line by its id, the draft that is his addition, and what it promises, as a line's `promises`. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `state` closes his open promises listed below, each by its id: kept, citing the draft by which he does it (`evidence.draft`); withdrawn, citing the draft in which he takes it back to the person he promised, or tells them he cannot do it; released, citing the id of the line listed below that he may reply to in which the person he promised lets him off it (`evidence.line`). A release says he no longer owes it; patience is not a release, so "no hurry" or "whenever you've read it is fine" leaves the promise open. Every close also quotes in `thought` the words of his prose here that take it up, copied exactly from his thought outside every draft between and , and `still_stands` is true when anything in his prose here holds the promise as still owed or not yet done ("the promise stays open until I've read it"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person he promised can read it, in the room where he made the promise or in a direct message with them, and a thought alone closes nothing. A promise he has no way to do is never kept by him: telling the person he promised that he cannot do it withdraws it, and that person can release it. +Answer with the speech contract's object. `say` lists the drafts he sends now, each by its number, with the Matrix ids of anyone listed whom he addresses directly (`mentions`), the id of the line listed below that he answers or passes on (`in_reply_to`, or null: the room shows that line, with who said it, above his own words), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom he promises it (`to`, null when he promises it to the room), when it promises again one of his open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what he already has keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what he meant and did not send. `unsent` accounts for each of his drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`); superseded, when a later draft or later prose of his replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to him this turn is held only when his prose says he holds it. `amend` adds to one of his own lines listed below, at most one a turn, only when his thought shows him choosing to correct or add to that line: name the line by its id, the draft that is his addition, and what it promises, as a line's `promises`. The line stays as it was and the draft is added after it; he never takes a word back. `suggest` leaves Self one note, at most one a turn, only when his thought shows him choosing to: name the draft that is the note, its kind (feedback when he passes on what someone listed said, with that person's Matrix id in `about`; idea when it is his own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `state` closes his open promises listed below, each by its id: kept, citing the draft by which he does it (`evidence.draft`); withdrawn, citing the draft in which he takes it back to the person he promised, or tells them he cannot do it; released, citing the id of the line listed below that he may reply to in which the person he promised lets him off it (`evidence.line`). A release says he no longer owes it; patience is not a release, so "no hurry" or "whenever you've read it is fine" leaves the promise open. Every close also quotes in `thought` the words of his prose here that take it up, copied exactly from his thought outside every draft between and , and `still_stands` is true when anything in his prose here holds the promise as still owed or not yet done ("the promise stays open until I've read it"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person he promised can read it, in the room where he made the promise or in a direct message with them, and a thought alone closes nothing. A promise he has no way to do is never kept by him: telling the person he promised that he cannot do it withdraws it, and that person can release it. A search finds things and reads none of them: `need` names, for an open promise listed as needing a search, the one pull request or issue that a search he read in this moment listed and that keeping it needs him to read, by the promise's id and as `GameCult/Name#number` in `target`; else it is empty. 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. diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index db5ce01..1525dfd 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -24,7 +24,7 @@ use serde_json::{Value, json}; use super::interpret::drafts; use super::narrate::words; -use super::read::ReadRequest; +use super::read::{ReadRequest, answers, surfaced}; /// How long a closed promise stays in her state before the commit removes it. pub(crate) const CLOSED_KEPT_DAYS: i64 = 7; @@ -34,8 +34,8 @@ const REAFFIRMED_KEPT: usize = 3; 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, a line she heard, by -/// its id in the Interpreter's list, or a read performed this wake (16.22.3). No row accepts a read (16.25.2 rule 3): a -/// read alone keeps nothing, so `Read` is refused as not accepted. +/// its id in the Interpreter's list, or a read performed this wake, by its number (16.22.3). A read alone keeps nothing +/// (16.25.2 rule 3): only `promise_need` accepts one, the search that found what the promise names (map 16.27). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub(crate) enum Evidence { @@ -60,9 +60,9 @@ pub(crate) enum How { /// 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. +/// whether the promise opens or is blocked from it. A field no kind names 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")] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub(crate) enum Needs { Words, Read { request: ReadRequest }, @@ -99,6 +99,9 @@ pub(crate) enum Proposal { #[serde(default, skip_serializing_if = "std::ops::Not::not")] still_stands: bool, }, + /// An open promise that needs a search names the one thing the search found that keeping it needs read (map 16.27): + /// `request` is a pull request or issue the search, this wake's read `evidence`, listed. The receipt is cleared. + PromiseNeed { promise: String, request: ReadRequest, evidence: Evidence }, } /// Why the commit applied nothing of a proposal: what the outcome and the report say. @@ -144,6 +147,10 @@ pub(crate) enum Refusal { /// 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 `promise_need` whose promise needs no search, or whose read is no search of that repo listing what it names. + NotSurfaced, + /// The read number is none this wake made that returned. + NoSuchRead, /// A reaffirmation naming a promise to someone else. ReaffirmsAnother, /// A reaffirmation naming a promise that is no longer open or blocked. @@ -163,10 +170,12 @@ pub(crate) enum Refusal { /// | `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_need` | `Read` | the read is a search this wake that returned, of the repo the promise's search need names, and lists `request` | an open entry whose need is a search | fn accepts(proposal: &Proposal, evidence: &Evidence) -> bool { matches!( (proposal, evidence), (Proposal::PromiseOpen { .. }, Evidence::Draft(_)) + | (Proposal::PromiseNeed { .. }, Evidence::Read(_)) | (Proposal::PromiseClose { how: How::Kept, .. }, Evidence::Draft(_)) | (Proposal::PromiseClose { how: How::Withdrawn, .. }, Evidence::Draft(_)) | (Proposal::PromiseClose { how: How::Released, .. }, Evidence::Heard(_)) @@ -183,6 +192,8 @@ enum Resolved { Sent { act: &'static str, event: String, room: String, text: String, mentions: Vec }, /// A line she heard: its event, sender, room and time. Heard { event: String, sender: String, room: String, at_ms: u64, who: String }, + /// A read this wake that returned: what it read and the text it returned. + Read { request: ReadRequest, text: String }, } fn text(value: &Value) -> String { @@ -221,8 +232,13 @@ fn resolve(evidence: &Evidence, record: &Value, prose: &str) -> Result Err(Refusal::EvidenceNotAccepted), + Evidence::Read(n) => decision["reads"] + .as_array() + .into_iter() + .flatten() + .find(|read| read["n"].as_u64() == Some(*n as u64) && read["ok"] == true) + .and_then(|read| Some(Resolved::Read { request: serde_json::from_value(read["request"].clone()).ok()?, text: text(&read["text"]) })) + .ok_or(Refusal::NoSuchRead), } } @@ -265,8 +281,11 @@ pub(crate) struct Applied { 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`), as they now stand. + /// The open entries whose needed read returned this turn, with its receipt (`readAt`, `readId`, `readOf`), as they + /// now stand. pub read: Vec, + /// The entries whose need now names what a search found (`promise_need`, map 16.27), as they now stand. + pub retargeted: Vec, } /// The one applier: her state with one turn's proposals applied, as deltas to `state` as it stands at commit, and what @@ -275,6 +294,9 @@ pub(crate) struct Applied { /// 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(); let mut applied = Applied::default(); let kept_until = now - Duration::days(CLOSED_KEPT_DAYS); @@ -286,6 +308,11 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: 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); @@ -296,7 +323,7 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: applied.refused.push(json!({ "proposal": raw, "reason": Refusal::NotAProposal })); continue; }; - if let Err(reason) = apply_one(&mut state, &proposal, record, prose, key, now, &mut applied) { + if let Err(reason) = apply_one(&mut state, &started, &proposal, record, prose, key, now, &mut applied) { applied.refused.push(json!({ "proposal": raw, "reason": reason })); } } @@ -305,18 +332,39 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: (state, applied) } -/// The receipt of a read on the promise that needs it (map 16.26): when a read of an open promise's target returns, in -/// any room and at any time, the entry records when (`readAt`) and which read (`readId`, `-r`). A kept close -/// later accepts it, so a read made in another room or after the conversation's window still stands behind the keep. +/// 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`). 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); + answers(&needed_read(entry)?, entry["readOf"].as_str()?).then_some(at) +} + +/// 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).collect(); + 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) = returned.iter().find(|read| read_key(read).as_deref() == Some(needed.as_str())) else { + 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()); } } @@ -352,25 +400,33 @@ fn read_key(read: &Value) -> Option { serde_json::from_value::(read["request"].clone()).ok().map(|request| request.normal()) } -/// Whether a read of `key` stands behind a keep citing `draft` (map 16.25.2, 16.26): the entry's own receipt of a read -/// that returned on an earlier turn (`readAt`), one of the conversation's reads that found it (`conversation_reads`, from -/// her `already_read`, K26), 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. +/// 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), 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"]; - if entry["readAt"].is_string() || decision["conversation_reads"].as_array().into_iter().flatten().any(|read| read["found"] == true && read["key"].as_str() == Some(key)) { + if receipt(entry).is_some() || decision["conversation_reads"].as_array().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).as_deref() == Some(key) && read["after_byte"].as_u64().and_then(|at| usize::try_from(at).ok()).is_some_and(|at| at <= typed_at)) + 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)) } -fn apply_one(state: &mut Value, proposal: &Proposal, record: &Value, prose: &str, key: &str, now: DateTime, applied: &mut Applied) -> Result<(), Refusal> { +/// 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::PromiseOpen { evidence, .. } | Proposal::PromiseClose { evidence, .. } | Proposal::PromiseNeed { evidence, .. } => evidence, }; if !accepts(proposal, evidence) { return Err(Refusal::EvidenceNotAccepted); @@ -390,7 +446,7 @@ fn apply_one(state: &mut Value, proposal: &Proposal, record: &Value, prose: &str if !matches!(entry["status"].as_str(), Some("open" | "blocked")) { return Err(Refusal::ReaffirmsClosed); } - if listed["held"] != *entry { + if !held(listed, started) { return Err(Refusal::OutsidePutChanged); } if entry["to"] != json!(to) { @@ -436,9 +492,8 @@ fn apply_one(state: &mut Value, proposal: &Proposal, record: &Value, prose: &str if closed(&status) && applied.closed.iter().any(|done| done["entry"]["id"] == entry["id"]) { return Err(Refusal::AlreadyClosed); } - // The whole entry against the turn's starting copy: an outside put wins on any field it changed (B6). A listing - // without the copy fails closed. - if listed["held"] != *entry { + // 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 @@ -498,7 +553,29 @@ fn apply_one(state: &mut Value, proposal: &Proposal, record: &Value, prose: &str applied.closed.push(json!({ "entry": entry.clone(), "how": how, "to_name": listed["to_name"], "by": who })); Ok(()) } - (Proposal::PromiseOpen { .. }, _) => Err(Refusal::EvidenceNotAccepted), + // A search finds; the promise names what it found (map 16.27): only an open entry whose need is a search, and only + // a pull request or issue that a search of that repo this wake listed. The receipt is cleared with the old target. + (Proposal::PromiseNeed { promise, request, .. }, Resolved::Read { request: searched, text: found }) => { + 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)?; + if !held(listed, started) { + return Err(Refusal::OutsidePutChanged); + } + let need = match serde_json::from_value::(entry["needs"].clone()) { + Ok(Needs::Read { request: need }) if entry["status"] == "open" && need.search() => need, + _ => return Err(Refusal::NotSurfaced), + }; + // The read is a search of the need's repo, and it listed what the promise now names. + if !surfaced(&searched, &found, request) || !surfaced(&need, &found, request) { + return Err(Refusal::NotSurfaced); + } + entry["needs"] = json!(Needs::Read { request: request.clone() }); + clear_receipt(entry); + applied.retargeted.push(entry.clone()); + Ok(()) + } + (Proposal::PromiseOpen { .. } | Proposal::PromiseNeed { .. }, _) => Err(Refusal::EvidenceNotAccepted), } } diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 6d659eb..b807e7f 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -526,6 +526,7 @@ fn k33_b2_the_published_schema_carries_what_the_commit_writes() { 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}")); } @@ -545,3 +546,190 @@ fn k33_b2_the_published_schema_carries_what_the_commit_writes() { 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; a bare repo +/// is answered by its root or its README; anything else 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"), + ("GameCult/Bifrost", "GameCult/Bifrost/README.md"), + ("GameCult/Bifrost", "GameCult/Bifrost/readme"), + ] { + 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}"); + } +} + +/// A search finds; the promise then names what it found (`promise_need`): only an open promise that needs a search of +/// that repo, only an item a search this wake listed. The receipt is cleared, and a read of the item named then keeps +/// it, in the same turn too. +#[test] +fn k34_a_search_names_what_the_promise_needs() { + let needs = Needs::Read { request: ReadRequest::Repo(PASSKEY_SEARCH.into()) }; + let mut c1 = holding_one(KIKO, F2_PROMISE, &needs, "open"); + c1["commitments"][0]["readAt"] = json!(now().to_rfc3339()); + c1["commitments"][0]["readId"] = json!("r1-t13-r1"); + let search = returned(1, PASSKEY_SEARCH, "- #85 Passkeys: enrolment under a fresh sign-in (pull request merged, opened by heimdall, 2026-11-18)", Some(10)); + let naming = |target: &str| json!(Proposal::PromiseNeed { promise: "c1".into(), request: ReadRequest::Repo(target.into()), evidence: Evidence::Read(1) }); + let quiet = |state: Value, holding: &Value, reads: Value| { + let mut rec = record(state, listing(holding), false); + rec["interpreter"]["said"] = json!([]); + rec["interpreter"]["reads"] = reads; + rec + }; + let (state, applied) = apply(&c1, &quiet(json!([naming("GameCult/Bifrost#85")]), &c1, json!([search.clone()])), "x", "r1-t14", now()); + let entry = &state["commitments"][0]; + assert_eq!((entry["needs"].clone(), applied.retargeted.len()), (json!({ "kind": "read", "request": { "kind": "repo", "target": "GameCult/Bifrost#85" } }), 1), "{state}"); + assert!(RECEIPT.iter().all(|field| entry.get(*field).is_none()), "{state}"); + // What the search did not list, another repo, and a read that is no search: refused. + for (target, reads) in [("GameCult/Bifrost#86", json!([search.clone()])), ("GameCult/Lodur#85", json!([search.clone()])), ("GameCult/Bifrost#85", json!([returned(1, "GameCult/Bifrost#84", "- #85 Passkeys", Some(0))]))] { + assert_eq!(reasons(&apply(&c1, &quiet(json!([naming(target)]), &c1, reads), "x", "r1-t14", now()).1), vec![json!("not_surfaced")], "{target}"); + } + // A promise whose need is no search is not renamed. + let exact = holding_one(KIKO, F2_PROMISE, &Needs::Read { request: ReadRequest::Repo("GameCult/Bifrost#84".into()) }, "open"); + assert_eq!(reasons(&apply(&exact, &quiet(json!([naming("GameCult/Bifrost#85")]), &exact, json!([search.clone()])), "x", "r1-t14", now()).1), vec![json!("not_surfaced")]); + // No such read. + assert_eq!(reasons(&apply(&c1, &quiet(json!([naming("GameCult/Bifrost#85")]), &c1, json!([])), "x", "r1-t14", now()).1), vec![json!("no_such_read")]); + // One wake: the search, then #85 read, then the keep. Naming it is her own turn's change, not an outside put. + let mut rec = keeping_c1(&c1, json!([search, returned(2, "GameCult/Bifrost#85", "#85 Passkeys", Some(0))])); + let keep = rec["interpreter"]["state"][0].clone(); + rec["interpreter"]["state"] = json!([naming("GameCult/Bifrost#85"), keep]); + let (state, applied) = apply(&c1, &rec, F2_PROSE, "r1-t16", now()); + assert_eq!((state["commitments"][0]["status"].as_str(), reasons(&applied)), (Some("kept"), Vec::::new()), "{state}"); +} diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 3c01ab6..cd6a903 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -71,7 +71,7 @@ pub(crate) const SPEECH_OPENING: &str = "You decide what one person says aloud i /// The speech contract, sent as the schema turn's output schema (`--json-schema`): the drafts she sends now by number, /// and the gaps. The model writes no words of hers. -pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps","amend","suggest","state","read","unsent"],"properties":{"unsent":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","how","quote"],"properties":{"draft":{"type":"integer"},"how":{"type":"string","enum":["held","superseded"]},"quote":{"type":"string"}}}},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target","quote"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"},"quote":{"type":"string"}}},"state":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","promise","how","evidence","thought","still_stands"],"properties":{"kind":{"type":"string","enum":["promise_close"]},"promise":{"type":"string"},"how":{"type":"string","enum":["kept","withdrawn","released"]},"evidence":{"type":"object","additionalProperties":false,"required":["draft","line","read"],"properties":{"draft":{"type":["integer","null"]},"line":{"type":["string","null"]},"read":{"type":["integer","null"]}}},"thought":{"type":["string","null"]},"still_stands":{"type":"boolean"}}}},"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft","promises"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to","promises"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#; +pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps","amend","suggest","state","need","read","unsent"],"properties":{"need":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["promise","target"],"properties":{"promise":{"type":"string"},"target":{"type":"string"}}}},"unsent":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","how","quote"],"properties":{"draft":{"type":"integer"},"how":{"type":"string","enum":["held","superseded"]},"quote":{"type":"string"}}}},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target","quote"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"},"quote":{"type":"string"}}},"state":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","promise","how","evidence","thought","still_stands"],"properties":{"kind":{"type":"string","enum":["promise_close"]},"promise":{"type":"string"},"how":{"type":"string","enum":["kept","withdrawn","released"]},"evidence":{"type":"object","additionalProperties":false,"required":["draft","line","read"],"properties":{"draft":{"type":["integer","null"]},"line":{"type":["string","null"]},"read":{"type":["integer","null"]}}},"thought":{"type":["string","null"]},"still_stands":{"type":"boolean"}}}},"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft","promises"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","in_reply_to","promises"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"in_reply_to":{"type":["string","null"]},"promises":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["words","to","reaffirms","needs"],"properties":{"words":{"type":"string"},"to":{"type":["string","null"]},"reaffirms":{"type":["string","null"]},"needs":{"type":"object","additionalProperties":false,"required":["kind","read"],"properties":{"kind":{"type":"string","enum":["words","read","lacking"]},"read":{"type":["object","null"],"additionalProperties":false,"required":["kind","target"],"properties":{"kind":{"type":"string","enum":["domain","mind","repo","web"]},"target":{"type":"string"}}}}}}}}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#; /// The speech frame before the guidance: what to decide, from what, and the attribution rule. Code, not tuning (map /// 16.7), in her own pronouns (16.19.7). The tuning's `interpreter.guidance` (what counts as her choosing to send it @@ -91,7 +91,7 @@ fn speech_frame_tail(her: Forms) -> String { format!( "{cap_subj} speak{s} only in this room. What {subj} know{s} privately is listed below as private: {subj} say{s} none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge. -Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`), the id of the line listed below that {subj} answer{s} or pass{es} on (`in_reply_to`, or null: the room shows that line, with who said it, above {poss} own words), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom {subj} promise{s} it (`to`, null when {subj} promise{s} it to the room), when it promises again one of {poss} open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what {subj} already {has} keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what {subj} meant and did not send. `unsent` accounts for each of {poss} drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when {poss} prose shows {obj} choosing not to send it, quoting those words of {poss} thought (`quote`); superseded, when a later draft or later prose of {poss} replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to {obj} this turn is held only when {poss} prose says {subj} hold{s} it. `amend` adds to one of {poss} own lines listed below, at most one a turn, only when {poss} thought shows {obj} choosing to correct or add to that line: name the line by its id, the draft that is {poss} addition, and what it promises, as a line's `promises`. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `state` closes {poss} open promises listed below, each by its id: kept, citing the draft by which {subj} {does} it (`evidence.draft`); withdrawn, citing the draft in which {subj} take{s} it back to the person {subj} promised, or tell{s} them {subj} cannot do it; released, citing the id of the line listed below that {subj} may reply to in which the person {subj} promised lets {obj} off it (`evidence.line`). A release says {subj} no longer owe{s} it; patience is not a release, so \"no hurry\" or \"whenever you've read it is fine\" leaves the promise open. Every close also quotes in `thought` the words of {poss} prose here that take it up, copied exactly from {poss} thought outside every draft between and , and `still_stands` is true when anything in {poss} prose here holds the promise as still owed or not yet done (\"the promise stays open until I've read it\"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person {subj} promised can read it, in the room where {subj} made the promise or in a direct message with them, and a thought alone closes nothing. A promise {subj} {has} no way to do is never kept by {obj}: telling the person {subj} promised that {subj} cannot do it withdraws it, and that person can release it. +Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`), the id of the line listed below that {subj} answer{s} or pass{es} on (`in_reply_to`, or null: the room shows that line, with who said it, above {poss} own words), and what the draft promises or offers (`promises`, a list, empty when it promises nothing): for each act it promises or offers, its words, copied exactly, the Matrix id of the person listed to whom {subj} promise{s} it (`to`, null when {subj} promise{s} it to the room), when it promises again one of {poss} open promises listed below to the same person, that promise's id (`reaffirms`, else null): a promise said again is the same promise, never a new one; and what keeping it needs (`needs`): `words` when what {subj} already {has} keeps it; finding anything out is a `read`, naming what to read in `read`, or `lacking` when no read reaches it. `gaps` records what {subj} meant and did not send. `unsent` accounts for each of {poss} drafts this answer neither sends (in `say`, `amend` or `suggest`) nor records as a gap: held, when {poss} prose shows {obj} choosing not to send it, quoting those words of {poss} thought (`quote`); superseded, when a later draft or later prose of {poss} replaces it, quoting those later words. Every draft is accounted for: one left out fails the answer. A draft to someone who spoke to {obj} this turn is held only when {poss} prose says {subj} hold{s} it. `amend` adds to one of {poss} own lines listed below, at most one a turn, only when {poss} thought shows {obj} choosing to correct or add to that line: name the line by its id, the draft that is {poss} addition, and what it promises, as a line's `promises`. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left. `state` closes {poss} open promises listed below, each by its id: kept, citing the draft by which {subj} {does} it (`evidence.draft`); withdrawn, citing the draft in which {subj} take{s} it back to the person {subj} promised, or tell{s} them {subj} cannot do it; released, citing the id of the line listed below that {subj} may reply to in which the person {subj} promised lets {obj} off it (`evidence.line`). A release says {subj} no longer owe{s} it; patience is not a release, so \"no hurry\" or \"whenever you've read it is fine\" leaves the promise open. Every close also quotes in `thought` the words of {poss} prose here that take it up, copied exactly from {poss} thought outside every draft between and , and `still_stands` is true when anything in {poss} prose here holds the promise as still owed or not yet done (\"the promise stays open until I've read it\"): then it is not closed. A draft cited closes the promise only when it goes out this turn where the person {subj} promised can read it, in the room where {subj} made the promise or in a direct message with them, and a thought alone closes nothing. A promise {subj} {has} no way to do is never kept by {obj}: telling the person {subj} promised that {subj} cannot do it withdraws it, and that person can release it. A search finds things and reads none of them: `need` names, for an open promise listed as needing a search, the one pull request or issue that a search {subj} read in this moment listed and that keeping it needs {obj} to read, by the promise's id and as `GameCult/Name#number` in `target`; else it is empty. 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" }, @@ -338,6 +338,17 @@ struct Answer { /// The drafts not sent and not gapped, each held by her own choice or superseded, citing her prose (Soul's R10). #[serde(default)] unsent: Vec, + /// What an open promise that needs a search now needs read: one thing the search found (map 16.27). + #[serde(default)] + need: Vec, +} + +/// A promise's need named anew, as the answer carries it: the promise's id and the pull request or issue to read. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ProposedNeed { + promise: String, + target: String, } /// A draft the answer neither sends nor gaps, and why, citing her prose. @@ -382,8 +393,8 @@ fn unaccounted(answer: &Answer, gaps: &[Value], prose: &str, found: &Drafts) -> /// Where in her wake a decision falls (map 16.22.3): what was decided earlier this wake (none for her first segment), /// where her new segment begins in her prose, what she has read so far this wake, and her earlier segments with their -/// bridges, as the Interpreter is shown them. The Interpreter judges only the new segment; drafts are numbered across the -/// wake, and a draft of an earlier segment cannot be sent by a later call. +/// bridges, as the Interpreter is shown them. Drafts are numbered across the wake, and each decision decides every draft +/// of it afresh: the latest decision about a draft is its fate, and the one she is told (map 16.27). #[derive(Clone, Copy, Default)] pub(crate) struct Wake<'a> { pub earlier: Option<&'a Value>, @@ -552,13 +563,13 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu } let refused = if refused.is_empty() { String::new() } else { format!(" Refused earlier, so never named again as it was: {}.", refused.join("; ")) }; let reading = if packet.affordances.contains(&Affordance::Read) { format!("{}{in_view}{refused}\n\n", read_frame(her)) } else { String::new() }; - // Her earlier segments this wake, already decided on: context, never hers to send again. - // Her earlier segments this wake and what she read between them. Her drafts are numbered across the whole moment, and - // a draft from earlier is sent only if nothing she wrote after it says it is superseded or wrong (Soul's R6). + // Her earlier segments this wake and what she read between them. Her drafts are numbered across the whole moment and + // this decision decides each afresh: a draft from earlier is sent only if nothing she wrote after it says it is + // superseded or wrong (Soul's R6). let before = if before.is_empty() { String::new() } else { - format!("Earlier in {} moment, before what follows:\n{before}\n\n{} drafts are numbered across the whole moment. A draft from earlier in it is sent only if nothing {} wrote after it says it is superseded or wrong.\n\n", her.poss, capitalized(her.poss), her.subj) + format!("Earlier in {} moment, before what follows:\n{before}\n\n{} drafts are numbered across the whole moment, and each is decided here afresh, earlier ones too. A draft from earlier in it is sent only if nothing {} wrote after it says it is superseded or wrong.\n\n", her.poss, capitalized(her.poss), her.subj) }; let tail = format!("{reading}{}", speech_frame_tail(her)); // The pronouns of anyone her prose names, in view or not (Soul's R6, E r6). @@ -606,9 +617,11 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra } /// One speech decision after the newest segment of her wake (`wake`), over the whole wake (Soul's R6): the Interpreter -/// sees all of her prose and every draft, numbered across the wake, and decides afresh what goes out, so a draft written -/// before a read that her later prose says is superseded or wrong is not sent. Earlier calls' acts are not carried; their -/// reads, refused reads and usage are. What she read joins what an echo is measured against, and `read` is the one read +/// sees all of her prose and every draft, numbered across the wake, and decides afresh what becomes of each, so a draft +/// written before a read that her later prose says is superseded or wrong is not sent, and a draft held earlier may be +/// sent now. Earlier calls' acts and unsent drafts are not carried: every answer accounts for every draft of the wake +/// (`unaccounted`), so the latest decision about a draft is its fate, and she is told it once (map 16.27). Their reads, +/// refused reads and usage are carried. What she read joins what an echo is measured against, and `read` is the one read /// the newest segment reaches for, resolved, or none. pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning, wake: Wake) -> Value { let found = drafts(prose); @@ -678,16 +691,15 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na if let Some(retried) = retried { decision["retried"] = retried; } - // Each unsent draft with its words, so her outcome can tell her a held one did not go out (map 16.26); her earlier - // segments' first. - let mut unsent = earlier("unsent"); - unsent.extend(parsed.unsent.iter().map(|one| { + // Each unsent draft with its words, so her outcome can tell her a held one did not go out (map 16.26). This answer + // decided every draft of the wake, so an earlier segment's unsent drafts are not carried (map 16.27). + let unsent: Vec = parsed.unsent.iter().map(|one| { let mut held = json!(one); if let Some(draft) = found.numbered(one.draft) { held["words"] = json!(draft.text); } held - })); + }).collect(); if !unsent.is_empty() { decision["unsent"] = json!(unsent); } @@ -840,6 +852,14 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na None => state_unused.push(raw), } } + // A promise's need named anew (map 16.27): code cites the newest search this wake that returned and lists what the + // answer names, and the commit holds it to that. + for raw in parsed.need { + match need_of(&raw, wake) { + Some(need) => proposals.push(json!(need)), + None => state_unused.push(json!({ "promise": raw.promise, "target": raw.target })), + } + } decision["state"] = json!(proposals); if !state_unused.is_empty() { decision["state_unused"] = json!(state_unused); @@ -925,12 +945,7 @@ fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake // sentence (Soul's R9: "I'll start with #86. The saga code will say…" names #86), and not a paragraph // apart, where "Meta's notes link asked for nothing" names a link she is not reaching for (Soul's R12 // deviation 4, map 16.26). - .filter(|(at, to)| { - let from = wake.from.min(prose.len()); - let open = prose[from..*at].rfind("\n\n").map_or(from, |gap| from + gap + 2); - let close = prose[*to..].find("\n\n").map_or(prose.len(), |gap| *to + gap); - anchors(&prose[open..close]) - }) + .filter(|(at, to)| anchors(paragraph(prose, wake.from.min(prose.len()), *at, *to))) .map(|(at, to)| prose[at..to].to_owned()) }) }; @@ -941,6 +956,32 @@ fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake Ok(json!({ "kind": asked.kind, "target": asked.target.trim(), "request": request, "what": request.what(packet.forms), "quote": located })) } +/// The paragraph of `prose` that holds `at..to`, no earlier than `from`: a paragraph ends at any line break, a single +/// `\n`, a CRLF, or a line of whitespace alike (map 16.27). The one splitter of her prose into paragraphs. +fn paragraph(prose: &str, from: usize, at: usize, to: usize) -> &str { + let open = prose[from..at].rfind(['\n', '\r']).map_or(from, |gap| from + gap + 1); + let close = prose[to..].find(['\n', '\r']).map_or(prose.len(), |gap| to + gap); + &prose[open..close] +} + +/// A promise's need named anew, as the commit takes it (map 16.27): a pull request or issue of a GameCult repo, citing +/// the newest search of this wake that returned and lists it, or failing that the newest that returned, which the commit +/// then refuses. None when the target is no pull request or issue, or no search returned this wake. +fn need_of(raw: &ProposedNeed, wake: Wake) -> Option { + let promise = raw.promise.trim(); + let request = read::repo_request(&raw.target).filter(|request| matches!(request, ReadRequest::Repo(target) if target.contains('#')))?; + let searches: Vec<(usize, ReadRequest, String)> = wake + .earlier + .and_then(|earlier| earlier["reads"].as_array()) + .into_iter() + .flatten() + .filter(|read| read["ok"] == true) + .filter_map(|read| Some((usize::try_from(read["n"].as_u64()?).ok()?, serde_json::from_value::(read["request"].clone()).ok().filter(ReadRequest::search)?, read["text"].as_str().unwrap_or_default().to_owned()))) + .collect(); + let cited = searches.iter().rev().find(|(_, search, found)| read::surfaced(search, found, &request)).or_else(|| searches.last())?; + (!promise.is_empty()).then(|| Proposal::PromiseNeed { promise: promise.to_owned(), request, evidence: Evidence::Read(cited.0) }) +} + /// The words that name what a read reads (Soul's R6): a repo's name, a pull request's number, a file's name; a campaign; /// an address and its host; a recall's words. Lowercase. A domain item is named by its title instead (`reading`). fn target_words(request: &ReadRequest) -> Vec { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 0577cc9..7beb58f 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -812,7 +812,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","read","unsent"]"#)); + assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","need","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 @@ -1424,3 +1424,76 @@ fn k33_l5_a_junk_read_target_opens_as_lacking() { 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). + +/// Soul's R13 probe 8: a draft held in segment 1 and said in segment 2 is said, and she is not told it was held; a draft +/// held in both segments is told once. The latest decision about a draft is its fate. +#[test] +fn k34_b2_the_latest_decision_about_a_draft_is_its_fate() { + let first = "Not yet, not before I have read it. Meta, it holds."; + let prose = format!("{first}\n\nI have read it now, so I can say it. Meta, and the knee goes first."); + let held_first = json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "held", "quote": "Not yet, not before I have read it" }] }); + let earlier = answered(&reading_packet(), first, held_first); + assert_eq!(earlier["unsent"].as_array().map(Vec::len), Some(1), "{earlier}"); + let later = |answer: Value| { + let reply = answer.to_string(); + let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()); + decide_in(&model, "test", &reading_packet(), "The room is warm.", &prose, &Tuning::default(), Wake { earlier: Some(&earlier), from: first.len() + 2, read: &[], before: first }) + }; + 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": [] })).unwrap().lines(packet().forms); + assert!(!told.iter().any(|line| line.contains("held it back")), "{told:?}"); + let held_again = later(json!({ "say": [{ "draft": 2 }], "gaps": [], "unsent": [{ "draft": 1, "how": "held", "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": [] })).unwrap().lines(packet().forms); + assert_eq!(told.iter().filter(|line| line.contains("held it back")).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. +#[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."]; + 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()) }))]; + 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}"); +} + +/// B1: the answer's `need` names what a search found; code cites the newest search of this wake that listed it, and an +/// answer naming no pull request or issue, or with no search behind it, proposes nothing. +#[test] +fn k34_b1_a_need_named_anew_cites_the_search_that_found_it() { + let reads = json!({ "reads": [ + { "n": 1, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost?q=passkey" }, "text": "- #85 Passkeys (pull request merged, opened by heimdall, 2026-11-18)" }, + { "n": 2, "ok": true, "request": { "kind": "repo", "target": "GameCult/Bifrost?q=cooling" }, "text": "- #90 Something else" } + ] }); + let decide_with = |need: Value, earlier: &Value| { + let reply = json!({ "say": [], "gaps": [], "need": need }).to_string(); + let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()); + decide_in(&model, "test", &reading_packet(), "The room is warm.", "I read the search.", &Tuning::default(), Wake { earlier: Some(earlier), ..Wake::default() }) + }; + let named = decide_with(json!([{ "promise": "c1", "target": "GameCult/Bifrost#85" }]), &reads); + assert_eq!(named["state"], json!([{ "kind": "promise_need", "promise": "c1", "request": { "kind": "repo", "target": "GameCult/Bifrost#85" }, "evidence": { "read": 1 } }]), "{named}"); + let unlisted = decide_with(json!([{ "promise": "c1", "target": "GameCult/Bifrost#86" }]), &reads); + assert_eq!(unlisted["state"][0]["evidence"], json!({ "read": 2 }), "the newest search, for the commit to refuse: {unlisted}"); + for (need, earlier) in [(json!([{ "promise": "c1", "target": "GameCult/Bifrost/src/lib.rs" }]), &reads), (json!([{ "promise": "c1", "target": "GameCult/Bifrost#85" }]), &json!({}))] { + let none = decide_with(need.clone(), earlier); + assert_eq!((none["state"].clone(), none["state_unused"].as_array().map(Vec::len)), (json!([]), Some(1)), "{need}: {none}"); + } + assert!(SPEECH_SCHEMA.contains(r#""required":["say","gaps","amend","suggest","state","need","read","unsent"]"#)); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 4b81f2b..ac99c49 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -425,7 +425,8 @@ impl Part { 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) => 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.", read.what(her)), + 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.", read.what(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.", read.what(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."), diff --git a/crates/mind-body/src/projection/read.rs b/crates/mind-body/src/projection/read.rs index 6031253..1c9ee3a 100644 --- a/crates/mind-body/src/projection/read.rs +++ b/crates/mind-body/src/projection/read.rs @@ -63,7 +63,7 @@ pub(crate) struct Asked { /// A read code performs, resolved from what she reached for. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "target", rename_all = "snake_case")] +#[serde(tag = "kind", content = "target", rename_all = "snake_case", deny_unknown_fields)] pub enum ReadRequest { /// Her own mind, recalled by these words. Mind(String), @@ -105,6 +105,11 @@ 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 { @@ -120,6 +125,31 @@ impl ReadRequest { } } +/// Whether a read whose normal form is `read` reads what a need whose normal form is `need` asks for (map 16.27): the +/// same thing exactly (`ReadRequest::normal`), or, for a bare repo, its README. 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 it names one thing the search +/// found. 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="); + if searched(need) || searched(read) { + return false; + } + let bare = need.strip_prefix("repo:gamecult/").is_some_and(|name| !name.contains(['/', '#', '@', '?'])); + let readme = || read.strip_prefix(need).and_then(|rest| rest.strip_prefix('/')).map(str::to_lowercase).is_some_and(|file| file == "readme" || file.strip_prefix("readme.").is_some_and(|ext| !ext.is_empty() && !ext.contains('/'))); + need == read || (bare && readme()) +} + +/// Whether `found`, the text a search of a repo returned, lists the pull request or issue `target` names in that repo: +/// a line `- # …` with its number, as the forge's search and the fixture's both list them (map 16.27). +pub(crate) fn surfaced(search: &ReadRequest, found: &str, target: &ReadRequest) -> bool { + let (ReadRequest::Repo(searched), ReadRequest::Repo(named)) = (search, target) else { return false }; + let Some((repo, _)) = searched.split_once("?q=") else { return false }; + let Some((of, number)) = named.split_once('#') else { return false }; + let same = repo_name(repo).is_some_and(|repo| repo_name(of).as_deref() == Some(repo.as_str())); + let number = number.trim_start_matches('0'); + same && !number.is_empty() && found.lines().any(|line| line.trim_start().strip_prefix("- #").is_some_and(|rest| rest.split_once(' ').map_or(rest, |(n, _)| n).trim_start_matches('0') == number)) +} + /// 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")] diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 9f6cefd..31566f6 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -1885,10 +1885,12 @@ fn open_promises(inputs: &Inputs, her: Forms) -> (Vec, String) { ("blocked", _) => format!(" {} {} no way to do it yet.", her.cap_subj, her.has), _ => String::new(), }; - // What an open promise needs read, and whether she has read it: her receipt on the entry (map 16.26). + // What an open promise needs read, exactly, and whether she has read that: her receipt on the entry (map 16.26, + // 16.27). A search finds things and reads none, so a promise that needs one needs what it finds read. let reading = match (&promise.needs, promise.status.as_str()) { - (Some(Needs::Read { request }), "open") => match promise.held["readAt"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()) { - Some(at) => format!(" It needs {} to read {}: {} read it {}.", her.obj, request.what(her), her.subj, coarse(at.with_timezone(&Utc), inputs.now)), + (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) { + 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(), diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 79182bc..e5477fc 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -745,10 +745,10 @@ fn promises_markdown(out: &mut String, turn: &Value) { // 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, refused) = (list("opened"), list("closed"), list("reaffirmed"), list("blocked"), list("read"), list("refused")); + let (opened, closed, reaffirmed, blocked, read, retargeted, refused) = (list("opened"), list("closed"), list("reaffirmed"), list("blocked"), list("read"), list("retargeted"), 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, &refused].iter().any(|items| !items.is_empty()) || pruned > 0 { + if [&opened, &closed, &reaffirmed, &blocked, &read, &retargeted, &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()); @@ -771,6 +771,9 @@ fn promises_markdown(out: &mut String, turn: &Value) { for entry in &read { let _ = writeln!(out, "- read for `{}`: {}", id(entry), entry["readId"].as_str().unwrap_or_default()); } + for entry in &retargeted { + let _ = writeln!(out, "- needs for `{}`: {}", id(entry), entry["needs"]["request"]["target"].as_str().unwrap_or_default()); + } for one in &refused { let _ = writeln!(out, "- refused ({}): `{}`", one["reason"].as_str().unwrap_or_default(), one["proposal"]); } diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index e5ed65e..22df383 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -2828,3 +2828,29 @@ fn r8_nothing_code_writes_for_the_persona_says_plain() { let persona = narrate::persona_prompt(&select(&inputs, &tuning), "The room is warm.", &tuning); 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}"); +} diff --git a/schemas/cultnet/gamecult.persona_state.v0.schema.json b/schemas/cultnet/gamecult.persona_state.v0.schema.json index 34d8389..a722789 100644 --- a/schemas/cultnet/gamecult.persona_state.v0.schema.json +++ b/schemas/cultnet/gamecult.persona_state.v0.schema.json @@ -1091,7 +1091,7 @@ }, "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. readAt and readId: when a read of what it needs last returned, and which read (map 16.26).", + "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. 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).", "additionalProperties": false, "properties": { "id": { @@ -1233,6 +1233,9 @@ "readId": { "type": "string" }, + "readOf": { + "type": "string" + }, "extensions": { "$ref": "#/definitions/extensions" }