K1d: speech is the drafts she sets down; the Interpreter picks whole drafts by number in a schema turn (map 16.19.1)
Deletes the quotation and sentence code (Quotation, closers, quotations, segment, Reading, read, unmarked, built) and json_of. The Persona gets code's speech form (<typed>...</typed>) at the head of Ghostlight's domain guidance; drafts() reads two literal tokens. The speech call is a schema turn (Model::ask gains schema; KitModel sets output_schema_json) decoded whole with from_str. A line is one draft's text; a number naming no draft is refused; one draft goes one place. GapKind gains Unwritten; a gap is a draft by number or a located passage of her thought of at least four words outside every draft (from: draft | thought | unlocated). The speech frame is written in her Forms. K8's attribution sentence becomes judgement over whole drafts; its byte-identical test is retired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3c2c3e48d1
commit
235d378bb3
12 changed files with 485 additions and 530 deletions
|
|
@ -23,8 +23,8 @@ publish.workspace = true
|
|||
# two until the workspace pin and the kit's meet.
|
||||
# `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames.
|
||||
#
|
||||
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt and locates cited
|
||||
# spans (`projection`), so that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3).
|
||||
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt and locates a gap's
|
||||
# passage of her thought (`projection`), so that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3).
|
||||
# Every stage asks through the connector kit's client (`model-connector`).
|
||||
# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only.
|
||||
#
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
//!
|
||||
//! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a
|
||||
//! hypothetical state, what the Projector would narrate, and with `Through::Persona` what she would answer in her own
|
||||
//! prose and which quoted lines of it would be said (the Persona stage, C3b's first piece). `harness` runs `project`
|
||||
//! prose and which of her drafts would be said (the Persona stage, C3b's first piece). `harness` runs `project`
|
||||
//! over fixtures: one turn from a mocked room (`--room`), a plan of states by scenarios (`--batch`), and the cast of the
|
||||
//! swarm taking turns in one simulated room (`--simulate`). It adds no second turn: every case is one `project`. Its organs are read-only by type: `PersonaSource` gets,
|
||||
//! `MouthReader` reads pending chat, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
|
||||
|
|
@ -282,7 +282,7 @@ fn request_id(instance: &str, stage: &str, tag: &str, seed: u64) -> String {
|
|||
/// call with its usage. A failed call is a record with its reason and what it cost, never the end of the report.
|
||||
fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through) -> Value {
|
||||
let ids: Vec<String> = packet.selected.iter().map(|pick| pick.id.clone()).collect();
|
||||
let answer = match model.ask(&request_id(instance, "projector", tag, packet.seed), &tuning.projector.model, &projector_prompt(packet, tuning)) {
|
||||
let answer = match model.ask(&request_id(instance, "projector", tag, packet.seed), &tuning.projector.model, &projector_prompt(packet, tuning), None) {
|
||||
Ok(answer) => answer,
|
||||
Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "usage": failed.usage }),
|
||||
};
|
||||
|
|
@ -305,7 +305,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni
|
|||
if through == Through::Projector {
|
||||
return render;
|
||||
}
|
||||
let prose = match model.ask(&request_id(instance, "persona", tag, packet.seed), &tuning.persona.model, &persona_prompt(packet, &narration, tuning)) {
|
||||
let prose = match model.ask(&request_id(instance, "persona", tag, packet.seed), &tuning.persona.model, &persona_prompt(packet, &narration, tuning), None) {
|
||||
Ok(spoke) => {
|
||||
let prose = cap_words(&spoke.text, tuning.persona.words);
|
||||
render["persona"] = json!({ "words": words(&prose), "cut_at_budget": words(&spoke.text) > tuning.persona.words, "usage": spoke.usage, "prose": prose });
|
||||
|
|
@ -407,7 +407,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
|||
let (first, second) = if swapped { (b, a) } else { (a, b) };
|
||||
// A narration that failed has nothing to judge; it is counted under the renders' failures.
|
||||
let Some(text) = narration["narration"].as_str() else { continue };
|
||||
let answer = match model.ask(&request_id(&request.instance, "judge", &at.to_string(), request.seed), &tuning.projector.model, &judge_prompt(first, second, text)) {
|
||||
let answer = match model.ask(&request_id(&request.instance, "judge", &at.to_string(), request.seed), &tuning.projector.model, &judge_prompt(first, second, text), None) {
|
||||
Ok(answer) => answer,
|
||||
Err(failed) => {
|
||||
verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage }));
|
||||
|
|
|
|||
|
|
@ -424,7 +424,7 @@ fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String
|
|||
let _ = writeln!(out, "- instance: `{}`; tuning: {} (`{}`)", report["instance"].as_str().unwrap_or_default(), report["tuning"]["source"].as_str().unwrap_or_default(), report["tuning"]["sha256"].as_str().unwrap_or_default());
|
||||
let _ = writeln!(out, "- Projector model: `{}`; Persona model: `{}`", report["model"].as_str().unwrap_or("none"), report["persona_model"].as_str().unwrap_or("none"));
|
||||
}
|
||||
let _ = writeln!(out, "- would-say lines are the double-quoted spans of her prose: a preview of what the Interpreter (C3b) will quote, not its decision");
|
||||
let _ = writeln!(out, "- spoke counts the cases where the Interpreter sent a draft of hers");
|
||||
let _ = writeln!(out, "- read-only: no put, no trace, no send; the mouth is the fixture\n");
|
||||
|
||||
// The summary: each state by scenario, then the states' voices against each other.
|
||||
|
|
@ -472,7 +472,7 @@ fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String
|
|||
out
|
||||
}
|
||||
|
||||
/// One render's narration, prose, would-say lines, word counts and usage.
|
||||
/// One render's narration, prose, the Interpreter's decision, word counts and usage.
|
||||
pub(crate) fn turn_markdown(out: &mut String, render: &Value) {
|
||||
if let Some(failed) = render["failed"].as_str() {
|
||||
let _ = writeln!(out, "**Projector call failed:** {failed}
|
||||
|
|
@ -505,8 +505,8 @@ Usage: {}
|
|||
let _ = writeln!(out, "Usage: projector {}; persona {}; interpreter {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]), usage_line(&render["interpreter"]["usage"]));
|
||||
}
|
||||
|
||||
/// The Interpreter's speech decision: each line said with its room, mentions, reply target and the span of her prose it
|
||||
/// rests on; each line refused, with why; its gaps. None when the render did not run through the Interpreter.
|
||||
/// The Interpreter's speech decision: each line said with its room, mentions, reply target and the draft it is; each
|
||||
/// line refused, with why; its gaps. None when the render did not run through the Interpreter.
|
||||
pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) {
|
||||
if decision.is_null() {
|
||||
return;
|
||||
|
|
@ -524,13 +524,12 @@ pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) {
|
|||
let mentions = line["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
let reply = line["reply_to"].as_str().map_or_else(String::new, |id| format!("; reply to {id}"));
|
||||
let _ = writeln!(out, "- in {}{}{}: {}", line["room"].as_str().unwrap_or_default(), if mentions.is_empty() { String::new() } else { format!(", mentioning {mentions}") }, reply, line["text"].as_str().unwrap_or_default());
|
||||
let spans: Vec<String> = line["rests_on"].as_array().into_iter().flatten().map(|span| format!("\"{}\"", span["quote"].as_str().unwrap_or_default())).collect();
|
||||
let _ = writeln!(out, " - her words: {}", spans.join(" + "));
|
||||
let _ = writeln!(out, " - draft {}", line["rests_on"]["draft"]);
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
for line in decision["refused"].as_array().into_iter().flatten() {
|
||||
let what = line["text"].as_str().map_or_else(|| line["spans"].to_string(), str::to_owned);
|
||||
let what = line["text"].as_str().map_or_else(|| format!("draft {}", line["draft"]), str::to_owned);
|
||||
let _ = writeln!(out, "- refused ({}): {what}", line["why"].as_str().unwrap_or_default());
|
||||
}
|
||||
for gap in decision["gaps"].as_array().into_iter().flatten() {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use serde_json::{Value, json};
|
|||
|
||||
use super::*;
|
||||
use crate::address::is_for;
|
||||
use crate::projection::interpret::SPEECH_OPENING;
|
||||
use crate::projection::narrate::{Answer, Failed, PROJECTOR_FRAME, Spent};
|
||||
|
||||
const HER: &str = "@eureka:gamecult.org";
|
||||
|
|
@ -23,7 +24,7 @@ fn room(name: &str) -> Fixture {
|
|||
}
|
||||
|
||||
/// A recorded model: the Projector narrates a fixed line; the Persona stage answers by `persona(prompt)`; the
|
||||
/// Interpreter by `interpreter(prompt)`, by default `quoted_lines`. Every call is kept, with its usage counted.
|
||||
/// Interpreter by `interpreter(prompt)`, by default `drafted_lines`. Every call is kept, with its usage counted.
|
||||
pub(crate) struct Scripted {
|
||||
pub calls: RefCell<Vec<(String, String)>>,
|
||||
pub persona: Box<dyn Fn(&str) -> String>,
|
||||
|
|
@ -32,7 +33,7 @@ pub(crate) struct Scripted {
|
|||
|
||||
impl Scripted {
|
||||
pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self {
|
||||
Self { calls: RefCell::default(), persona: Box::new(persona), interpreter: Box::new(quoted_lines) }
|
||||
Self { calls: RefCell::default(), persona: Box::new(persona), interpreter: Box::new(drafted_lines) }
|
||||
}
|
||||
|
||||
pub(crate) fn interpreting(mut self, interpreter: impl Fn(&str) -> String + 'static) -> Self {
|
||||
|
|
@ -41,19 +42,18 @@ impl Scripted {
|
|||
}
|
||||
}
|
||||
|
||||
/// The recorded Interpreter of the tests: each double-quoted span of her prose is a line she says, citing itself,
|
||||
/// mentioning no one. A test double that keeps the tests' prose readable, not the speech rule: to code a quotation is
|
||||
/// only a text whose sentences are whole, and the live Interpreter is a model.
|
||||
pub(crate) fn quoted_lines(prompt: &str) -> String {
|
||||
let prose = prompt.split("Her prose:\n").nth(1).unwrap_or_default();
|
||||
let say: Vec<Value> = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect();
|
||||
json!({ "say": say }).to_string()
|
||||
/// The recorded Interpreter of the tests: every draft the prompt numbers is sent, mentioning no one. A test double, not
|
||||
/// the speech rule: whether she means a draft now is the live Interpreter's judgement.
|
||||
pub(crate) fn drafted_lines(prompt: &str) -> String {
|
||||
let numbered = prompt.rsplit("drafts, by number:\n").next().unwrap_or_default();
|
||||
let say: Vec<Value> = (1..).take_while(|n| numbered.lines().any(|line| line.starts_with(&format!("{n}. ")))).map(|n| json!({ "draft": n, "mentions": [], "reply_to": null })).collect();
|
||||
json!({ "say": say, "gaps": [] }).to_string()
|
||||
}
|
||||
|
||||
impl Model for Scripted {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
||||
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
|
||||
let text = if prompt.starts_with("You decide what one person says aloud") {
|
||||
let text = if prompt.starts_with(SPEECH_OPENING) {
|
||||
(self.interpreter)(prompt)
|
||||
} else if prompt.starts_with(PROJECTOR_FRAME) {
|
||||
"The room is slow and so is he.".to_owned()
|
||||
|
|
@ -155,7 +155,7 @@ fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() {
|
|||
#[test]
|
||||
fn through_the_interpreter_her_prose_continues_the_narration_and_the_interpreter_decides_what_is_said() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let model = Scripted::new(|_| "He smiles at the screen, then types. \"Missed you too, friend.\" He does not mention the kettle.".into());
|
||||
let model = Scripted::new(|_| "He smiles at the screen, then types. <typed>Missed you too, friend.</typed> He does not mention the kettle.".into());
|
||||
let fixture = room("operator-warm.toml");
|
||||
let harness = harness(dir.path(), Some(&NeverAsked), Some(&model));
|
||||
let organs = Organs { persona: harness.persona, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model };
|
||||
|
|
@ -181,7 +181,7 @@ fn through_the_interpreter_her_prose_continues_the_narration_and_the_interpreter
|
|||
#[test]
|
||||
fn prose_over_budget_is_cut_and_silence_says_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let long = format!("{} \"late words\"", "word ".repeat(200));
|
||||
let long = format!("{} <typed>late words</typed>", "word ".repeat(200));
|
||||
let model = Scripted::new(move |_| long.clone());
|
||||
let fixture = room("deru-passing.toml");
|
||||
let harness = harness(dir.path(), None, Some(&model));
|
||||
|
|
@ -207,13 +207,13 @@ fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
|
|||
),
|
||||
)
|
||||
.unwrap();
|
||||
let model = Scripted::new(|prompt| if prompt.contains("Kiko") { "\"Winter, still.\" He grins.".into() } else { "He lets the hour pass.".into() });
|
||||
let model = Scripted::new(|prompt| if prompt.contains("Kiko") { "<typed>Winter, still.</typed> He grins.".into() } else { "He lets the hour pass.".into() });
|
||||
let report = batch(&harness(dir.path(), Some(&NeverAsked), Some(&model)), &plan).unwrap();
|
||||
for heading in ["# Persona seed batch", "## Summary", "## control × quiet, sample 1 (seed 7)", "## control × quiet, sample 2 (seed 8)", "## control × teased, sample 2 (seed 8)", "## Total usage"] {
|
||||
assert!(report.contains(heading), "{heading}\n{report}");
|
||||
}
|
||||
assert!(report.contains("| control | teased | 2/2 |") && report.contains("| control | quiet | 0/2 |"), "{report}");
|
||||
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - her words: \"Winter, still.\"") && report.contains("**Interpreter: nothing said.**"), "{report}");
|
||||
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - draft 1") && report.contains("**Interpreter: nothing said.**"), "{report}");
|
||||
assert!(report.contains("| claude-sonnet-5-5 | 12 | 120 | 24 |"), "twelve calls, three a case, in the footer: {report}");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the batch wrote nothing; the caller writes the report");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,38 +1,32 @@
|
|||
//! The Interpreter's speech (map section 4, cut C3b): what she says aloud this turn, decided from her prose by one
|
||||
//! tool-less structured model call, and built by code from her own words.
|
||||
//! The Interpreter's speech (map section 4, cut C3b; map 16.19 K1d): what she says aloud this turn, decided from her
|
||||
//! prose by one tool-less schema turn of a model, and taken by code from the drafts she set down.
|
||||
//!
|
||||
//! The Persona writes her thought, and when she means to say something she writes the words she would type. The
|
||||
//! Interpreter decides whether she says them now: it answers with zero or more lines, each a list of spans of her prose
|
||||
//! cited verbatim, with the people she addresses (Matrix mentions and a reply target, as structured fields). Code builds
|
||||
//! each line, never the model: each span is located in her prose by Ghostlight's `SourceSpan::locate` and must be whole
|
||||
//! sentences (UAX #29 sentence segmentation, the Unicode family `locate`'s word boundaries come from), and the spans of
|
||||
//! one line must be consecutive sentences; the line is that one unbroken run of her prose. A quotation's inside is
|
||||
//! segmented as a text of its own, so a quoted sentence is whole, but only a standalone quotation's: one that is itself
|
||||
//! whole sentences of her prose. A line may not start or end inside a quotation her sentence frames ("I won't say
|
||||
//! \"Nibu is lying.\"", "If she pushes, I'll say \"Fine.\""): that is what she would or would not say. An opening
|
||||
//! mark a budget left unclosed is not part of the sentence it starts. So a line is always whole sentences of her own,
|
||||
//! verbatim and in their order: no stitching, no dropped negation, no condition lifted off its clause. A standalone
|
||||
//! quotation's marks say that paragraph is speech, so the line carries its inside and not its marks, whether the model
|
||||
//! cited the marks or not (map section 16.7, I16.2). What this gives
|
||||
//! up: indirect speech ("I'll tell her I'm fine" says nothing), any paraphrase by the Interpreter, half a sentence, and
|
||||
//! a line quoted inside a sentence of narration ("\"Fine,\" I tell her."): she says a sentence whole or not at all.
|
||||
//! The Persona writes her thought, and when she writes words she would type she sets them between `<typed>` and
|
||||
//! `</typed>` (`narrate::persona_speech_form`, code's form). Each such pair is a draft (`drafts`), numbered in order.
|
||||
//! The Interpreter decides whether she sends a draft now, where and to whom: it answers with zero or more drafts by
|
||||
//! number, each with the people she addresses (Matrix mentions and a reply target, as structured fields), and the gaps.
|
||||
//! Code checks only that a number names a draft and that a draft goes one place; the line is the draft's text, whole,
|
||||
//! exactly as she set it down. So a line can never be part of what she wrote, nor words the model wrote (I16.6). No code
|
||||
//! here reads a quotation mark or a sentence: whose words a draft carries and whether she means it now are the
|
||||
//! Interpreter's judgement, as privacy is. What this gives up: speech she does not set down is never said (an
|
||||
//! `unwritten` gap records it), and she cannot say half a draft.
|
||||
//!
|
||||
//! Code keeps a line only when it is built so; drops an echo (at least `ECHO_MIN_WORDS` words, at least `ECHO_OVERLAP`
|
||||
//! of its word trigrams in the bodies the stimulus quoted to her); keeps at most `MAX_LINES` distinct lines; and keeps a
|
||||
//! mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in the turn's
|
||||
//! room. Whether a line 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 its quote located in her prose (`gap`). The prompt tells the
|
||||
//! Interpreter what she can do this turn (`select::turn_words`), so a reach past it is a `missing_affordance` gap, not a
|
||||
//! line that pretends. Nothing here posts: the commit (C3c) will.
|
||||
//! Code keeps a line only when it names a draft not already used; drops an echo (at least `ECHO_MIN_WORDS` words, at
|
||||
//! least `ECHO_OVERLAP` of its word trigrams in the bodies the stimulus quoted to her); keeps at most `MAX_LINES` lines;
|
||||
//! and keeps a mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in
|
||||
//! 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`). 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.
|
||||
|
||||
use ghostlight_persona_projection::SourceSpan;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use super::narrate::{Model, heard_overlap, lived_stream};
|
||||
use super::select::{Packet, capitalized, turn_words};
|
||||
use super::narrate::{Model, heard_overlap, lived_stream, words};
|
||||
use super::select::{Forms, Packet, capitalized, turn_words};
|
||||
use super::tuning::Tuning;
|
||||
|
||||
/// The most lines she says in one turn.
|
||||
|
|
@ -41,37 +35,127 @@ pub(crate) const MAX_LINES: usize = 2;
|
|||
/// her speech.
|
||||
const ECHO_MIN_WORDS: usize = 8;
|
||||
const ECHO_OVERLAP: f64 = 0.8;
|
||||
/// The fewest words a passage of her thought shown back to her may be: a shorter quote ("tell") says nothing of what
|
||||
/// she meant, and is kept as unlocated.
|
||||
const GAP_QUOTE_MIN_WORDS: usize = 4;
|
||||
|
||||
/// The speech frame: what to say, where, to whom, and the gaps. Huginn's chat Interpreter, beside nothing of Ghostlight's
|
||||
/// but its span rule. Code, not tuning (map 16.7): her words cited and never written, whole sentences, the
|
||||
/// room and the private rules, attribution, the JSON contract, at most two lines and the gap kinds. The tuning's
|
||||
/// `interpreter.guidance` (what counts as her choosing to say it now) is set between its second paragraph and its third,
|
||||
/// so it reads as part of the decision and every rule after it still binds.
|
||||
const SPEECH_FRAME_HEAD: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them.
|
||||
/// The marks of a draft: two literal tokens no natural prose holds (map 16.19.1).
|
||||
pub(crate) const DRAFT_OPEN: &str = "<typed>";
|
||||
pub(crate) const DRAFT_CLOSE: &str = "</typed>";
|
||||
|
||||
Below are who she is, what she can do here, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. Words she recalls or quotes from someone else are never her speech. That holds for a quotation that stands as sentences of its own too: its marks do not go out with her line, so another person's words cited from it would reach the room as her own assertion.";
|
||||
/// How every speech prompt begins, whoever she is: the test doubles route on it.
|
||||
pub(crate) const SPEECH_OPENING: &str = "You decide what one person says aloud in a chat room this turn";
|
||||
|
||||
/// The speech frame after the guidance.
|
||||
const SPEECH_FRAME_TAIL: &str = "She speaks only in this room. What she knows privately is listed below as private: she 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 line fits who is listening is yours to judge.
|
||||
/// The speech contract, sent as the schema turn's output schema (`--json-schema`): the drafts she sends now by number,
|
||||
/// and the gaps. The model writes no words of hers.
|
||||
pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps"],"properties":{"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["conditional","addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#;
|
||||
|
||||
Answer with one JSON object and nothing else:
|
||||
{\"say\": [{\"spans\": [\"<whole sentences of her prose, copied character for character>\"], \"mentions\": [\"<Matrix id of someone listed whom she addresses directly>\"], \"reply_to\": \"<Matrix id of the person whose message she answers, or null>\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere | missing_affordance\", \"quote\": \"<exact words of her prose>\", \"detail\": \"<why>\"}]}
|
||||
/// 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
|
||||
/// now) is set after it, so it reads as part of the decision and every rule after it still binds.
|
||||
fn speech_frame_head(her: Forms) -> String {
|
||||
let Forms { subj, obj, poss, be, s, .. } = her;
|
||||
format!(
|
||||
"{SPEECH_OPENING}, from {poss} own prose. You never write {poss} words: you choose among {poss} drafts.
|
||||
|
||||
A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time, missing_affordance when she reaches for something her body cannot do this turn (what she can do here is listed below).";
|
||||
Below are who {subj} {be}, what {subj} can do here, the room and who is in it, what reached {obj}, {poss} lived moment, {poss} prose, and {poss} drafts. When {subj} write{s} words {subj} would type, {subj} set{s} them between {DRAFT_OPEN} and {DRAFT_CLOSE}: each is a draft, numbered below. Decide which of {poss} drafts {subj} choose{s} to send now, in this room. Only {poss} drafts can be said. Someone else's words in {poss} thought are never {poss} speech. A draft that carries someone else's words is said only when {poss} thought shows {subj} mean{s} to pass them on, and then as {poss} to pass on."
|
||||
)
|
||||
}
|
||||
|
||||
/// What a gap is (map 16.16): words she meant and did not say now, and why. Typed by code from the model's `kind`; a kind
|
||||
/// the contract does not name is kept as `Unresolved` and reported, never dropped.
|
||||
/// The speech frame after the guidance: the room and the private rules, the contract and the gap kinds.
|
||||
fn speech_frame_tail(her: Forms) -> String {
|
||||
let Forms { subj, cap_subj, poss, has, s, .. } = her;
|
||||
format!(
|
||||
"{cap_subj} speak{s} only in this room. What {subj} know{s} privately is listed below as private: {subj} say{s} none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge.
|
||||
|
||||
Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`) and the Matrix id of the person whose message {subj} answer{s} (`reply_to`, or null). `gaps` records what {subj} meant and did not send.
|
||||
|
||||
A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: conditional when {subj} {has} drafted something {subj} might say but {has} not chosen to, addressee when {subj} mean{s} to send a draft but whom to is unclear, elsewhere when {subj} mean{s} a draft for another room or another time; for these three, name the draft by number. missing_affordance when {poss} thought reaches for something {poss} body cannot do this turn (what {subj} can do here is listed below), unwritten when {subj} mean{s} to say something and wrote no draft of it; for these two, quote the words of {poss} thought that show it, at least four words, copied exactly.",
|
||||
es = if s.is_empty() { "" } else { "es" },
|
||||
)
|
||||
}
|
||||
|
||||
/// One draft she set down: its number, from 1 in her prose's order, and its words, trimmed, with where they lie in her
|
||||
/// prose (`prose[start..end] == text`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Draft {
|
||||
pub n: usize,
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Her drafts, and what of her prose is not her thought: every tagged span, marks included (an empty one too), and an
|
||||
/// opener left unclosed, from it to the end. `unfinished` is the byte where that opener starts.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Drafts {
|
||||
pub drafts: Vec<Draft>,
|
||||
pub unfinished: Option<usize>,
|
||||
regions: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Drafts {
|
||||
fn numbered(&self, n: i64) -> Option<&Draft> {
|
||||
usize::try_from(n).ok().and_then(|n| self.drafts.iter().find(|draft| draft.n == n))
|
||||
}
|
||||
|
||||
/// Her prose outside every draft: her thought, as byte ranges.
|
||||
fn thought(&self, prose: &str) -> Vec<(usize, usize)> {
|
||||
let mut at = 0;
|
||||
let mut out = Vec::new();
|
||||
for &(start, end) in &self.regions {
|
||||
if at < start {
|
||||
out.push((at, start));
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
if at < prose.len() {
|
||||
out.push((at, prose.len()));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Her drafts: each `<typed>` to the next `</typed>`, in order. The inside, trimmed, is the draft; an empty one is no
|
||||
/// draft. A second opener before a closer ends nothing and is text of the first. An opener with no closer (the word
|
||||
/// budget cut her off) is `unfinished`, never a draft. Two literal tokens, and nothing about language.
|
||||
pub(crate) fn drafts(prose: &str) -> Drafts {
|
||||
let mut found = Drafts::default();
|
||||
let mut from = 0;
|
||||
while let Some(open) = prose[from..].find(DRAFT_OPEN).map(|at| from + at) {
|
||||
let inside = open + DRAFT_OPEN.len();
|
||||
let Some(close) = prose[inside..].find(DRAFT_CLOSE).map(|at| inside + at) else {
|
||||
found.unfinished = Some(open);
|
||||
found.regions.push((open, prose.len()));
|
||||
break;
|
||||
};
|
||||
let raw = &prose[inside..close];
|
||||
let text = raw.trim();
|
||||
if !text.is_empty() {
|
||||
let start = inside + (raw.len() - raw.trim_start().len());
|
||||
found.drafts.push(Draft { n: found.drafts.len() + 1, start, end: start + text.len(), text: text.to_owned() });
|
||||
}
|
||||
from = close + DRAFT_CLOSE.len();
|
||||
found.regions.push((open, from));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// What a gap is (map 16.16, 16.19): words she meant and did not send now, and why. Typed by code from the model's
|
||||
/// `kind`; a kind the contract does not name is kept as `Unresolved` and reported, never dropped.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum GapKind {
|
||||
/// She might say it, and has not chosen to.
|
||||
/// She drafted something she might say, and has not chosen to.
|
||||
Conditional,
|
||||
/// She means to say it, and whom to is unclear.
|
||||
/// She means to send a draft, and whom to is unclear.
|
||||
Addressee,
|
||||
/// She means it for another room or another time.
|
||||
/// She means a draft for another room or another time.
|
||||
Elsewhere,
|
||||
/// She reaches for something her body cannot do this turn: a tool request in waiting (section 4.2).
|
||||
/// Her thought reaches for something her body cannot do this turn: a tool request in waiting (section 4.2).
|
||||
MissingAffordance,
|
||||
/// She means to say something and wrote no draft of it, so nothing went out.
|
||||
Unwritten,
|
||||
Unresolved,
|
||||
}
|
||||
|
||||
|
|
@ -82,37 +166,51 @@ impl GapKind {
|
|||
"addressee" => Self::Addressee,
|
||||
"elsewhere" => Self::Elsewhere,
|
||||
"missing_affordance" => Self::MissingAffordance,
|
||||
"unwritten" => Self::Unwritten,
|
||||
_ => Self::Unresolved,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One gap as the report keeps it: its typed kind (with what the model declared when that is no kind), her words, and
|
||||
/// whether they were located in her prose by `SourceSpan::locate`, as a speech span is. A located quote is her prose's own
|
||||
/// words, verbatim, with their bytes; an unlocated one is the model's, marked so, and is never shown to her (K9). The
|
||||
/// model's `detail` is kept for the trace and is never what she is told.
|
||||
fn gap(prose: &str, raw: &Value) -> Value {
|
||||
/// One gap as the report keeps it: its typed kind (with what the model declared when that is no kind), and what of her
|
||||
/// prose it shows her, by `from`:
|
||||
/// - `draft`: the draft it names, by number, with that draft's words: "you wrote:" (K9);
|
||||
/// - `thought`: a passage of her thought outside every draft, located by `SourceSpan::locate` and at least
|
||||
/// `GAP_QUOTE_MIN_WORDS` words, with its bytes: "in your thought:" (K9). Found in her prose, not certified as her
|
||||
/// intent: whether it is her reach or her report of someone else's words was the Interpreter's reading;
|
||||
/// - `unlocated`: neither; the model's quote is kept for the trace and never shown to her.
|
||||
///
|
||||
/// The model's `detail` is kept for the trace and is never what she is told.
|
||||
fn gap(prose: &str, found: &Drafts, raw: &Value) -> Value {
|
||||
let kind = GapKind::of(raw.get("kind").and_then(Value::as_str).unwrap_or_default());
|
||||
let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim();
|
||||
let mut gap = json!({ "kind": kind, "detail": raw.get("detail").cloned().unwrap_or(Value::Null) });
|
||||
if kind == GapKind::Unresolved {
|
||||
gap["declared"] = raw.get("kind").cloned().unwrap_or_else(|| raw.clone());
|
||||
}
|
||||
match (!quote.is_empty()).then(|| SourceSpan::locate(prose, quote)).flatten() {
|
||||
Some(found) => {
|
||||
gap["quote"] = json!(found.verbatim());
|
||||
gap["located"] = json!(true);
|
||||
gap["start_byte"] = json!(found.start_byte());
|
||||
gap["end_byte"] = json!(found.end_byte());
|
||||
if let Some(draft) = raw.get("draft").and_then(Value::as_i64).and_then(|n| found.numbered(n)) {
|
||||
gap["from"] = json!("draft");
|
||||
gap["draft"] = json!(draft.n);
|
||||
gap["words"] = json!(draft.text);
|
||||
return gap;
|
||||
}
|
||||
let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim();
|
||||
let located = (words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| SourceSpan::locate(&prose[start..end], quote).map(|span| (start + span.start_byte(), start + span.end_byte())))).flatten();
|
||||
match located {
|
||||
Some((start, end)) => {
|
||||
gap["from"] = json!("thought");
|
||||
gap["words"] = json!(&prose[start..end]);
|
||||
gap["start_byte"] = json!(start);
|
||||
gap["end_byte"] = json!(end);
|
||||
}
|
||||
None => {
|
||||
gap["from"] = json!("unlocated");
|
||||
gap["quote"] = json!(quote);
|
||||
gap["located"] = json!(false);
|
||||
}
|
||||
}
|
||||
gap
|
||||
}
|
||||
|
||||
/// The answer's shape, decoded whole from the schema turn's structured output.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Answer {
|
||||
#[serde(default)]
|
||||
|
|
@ -124,7 +222,7 @@ struct Answer {
|
|||
#[derive(Debug, Deserialize)]
|
||||
struct Proposed {
|
||||
#[serde(default)]
|
||||
spans: Vec<String>,
|
||||
draft: Option<i64>,
|
||||
#[serde(default)]
|
||||
mentions: Vec<String>,
|
||||
#[serde(default)]
|
||||
|
|
@ -132,6 +230,7 @@ struct Proposed {
|
|||
}
|
||||
|
||||
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> String {
|
||||
let her = packet.forms;
|
||||
let mut people = String::new();
|
||||
for (label, id) in &packet.people {
|
||||
people.push_str(&format!("- {label} \u{2014} {id}\n"));
|
||||
|
|
@ -143,177 +242,37 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tunin
|
|||
if private.is_empty() {
|
||||
private.push_str("- none\n");
|
||||
}
|
||||
let found = drafts(prose);
|
||||
let mut numbered: String = found.drafts.iter().map(|draft| format!("{}. {}\n", draft.n, draft.text)).collect();
|
||||
if numbered.is_empty() {
|
||||
numbered.push_str("- none\n");
|
||||
}
|
||||
if found.unfinished.is_some() {
|
||||
numbered.push_str(&format!("- {} began one more and was cut off before finishing it: it is no draft and cannot be said\n", her.subj));
|
||||
}
|
||||
// The tuning's guidance, as a paragraph of its own; an empty one leaves no gap in the frame.
|
||||
let guidance = tuning.interpreter.guidance.trim();
|
||||
let guidance = if guidance.is_empty() { String::new() } else { format!("{guidance}\n\n") };
|
||||
format!(
|
||||
"{SPEECH_FRAME_HEAD}\n\n{}{SPEECH_FRAME_TAIL}\n\nWho she is:\n{}\n\nWhat she can do here:\n{}.\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}",
|
||||
guidance,
|
||||
"{}\n\n{guidance}{}\n\nWho {} {}:\n{}\n\nWhat {} can do here:\n{}.\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\nWhat reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{poss} prose:\n{prose}\n\n{poss} drafts, by number:\n{numbered}",
|
||||
speech_frame_head(her),
|
||||
speech_frame_tail(her),
|
||||
her.subj,
|
||||
her.be,
|
||||
packet.name,
|
||||
capitalized(&turn_words(&packet.affordances, packet.forms)),
|
||||
her.subj,
|
||||
capitalized(&turn_words(&packet.affordances, her)),
|
||||
packet.room.as_deref().unwrap_or("none"),
|
||||
packet.room_kind.words(),
|
||||
her.subj,
|
||||
her.s,
|
||||
her.obj,
|
||||
packet.stimulus,
|
||||
lived_stream(narration, &packet.heard),
|
||||
poss = capitalized(her.poss),
|
||||
)
|
||||
}
|
||||
|
||||
/// The model's answer as JSON: the object itself, or inside a fenced block.
|
||||
fn json_of(text: &str) -> Option<Answer> {
|
||||
let start = text.find('{')?;
|
||||
let end = text.rfind('}')?;
|
||||
serde_json::from_str(&text[start..=end]).ok()
|
||||
}
|
||||
|
||||
/// A quotation in her prose: where its opening mark starts, its inside, and where its closing mark ends.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Quotation {
|
||||
open: usize,
|
||||
inside: (usize, usize),
|
||||
close: usize,
|
||||
}
|
||||
|
||||
/// The marks that close a quotation opened by `open`, or None when `open` opens none. Double marks pair across straight
|
||||
/// and curly, since a model mixes them ("…” after a straight opening); `„` closes with either curly mark. A curly single
|
||||
/// quotation `‘…’` counts, its closing mark only where it is not an apostrophe inside a word (`don’t`). A straight single
|
||||
/// quote does not: `'cause`, `'90s` and `the Minds' room` cannot be told from a quotation's marks by position alone.
|
||||
fn closers(open: char) -> Option<&'static [char]> {
|
||||
match open {
|
||||
'"' | '\u{201C}' => Some(&['"', '\u{201D}']),
|
||||
'\u{201E}' => Some(&['\u{201C}', '\u{201D}', '"']),
|
||||
'\u{2018}' => Some(&['\u{2019}']),
|
||||
'\u{AB}' => Some(&['\u{BB}']),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Her quotations, paired in order: each opening mark with the next mark that closes it (`closers`). And the opening mark
|
||||
/// left unclosed, if one is (a budget cut her prose inside a quotation), with its length.
|
||||
fn quotations(prose: &str) -> (Vec<Quotation>, Option<(usize, usize)>) {
|
||||
let mut out = Vec::new();
|
||||
let mut open: Option<(usize, usize, &[char])> = None;
|
||||
let mut chars = prose.char_indices().peekable();
|
||||
while let Some((at, c)) = chars.next() {
|
||||
match open {
|
||||
None => open = closers(c).map(|closes| (at, c.len_utf8(), closes)),
|
||||
Some((mark, len, closes)) if closes.contains(&c) && !(c == '\u{2019}' && chars.peek().is_some_and(|(_, next)| next.is_alphanumeric())) => {
|
||||
out.push(Quotation { open: mark, inside: (mark + len, at), close: at + c.len_utf8() });
|
||||
open = None;
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
(out, open.map(|(mark, len, _)| (mark, len)))
|
||||
}
|
||||
|
||||
/// Byte ranges of `text`'s sentences (UAX #29), offset by `offset`, without the space around them.
|
||||
fn segment(offset: usize, text: &str) -> Vec<(usize, usize)> {
|
||||
text.split_sentence_bound_indices()
|
||||
.filter_map(|(at, sentence)| {
|
||||
let start = at + sentence.len() - sentence.trim_start().len();
|
||||
let end = at + sentence.trim_end().len();
|
||||
(start < end).then_some((offset + start, offset + end))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Her prose read for speech: its sentences in lists, her prose's own first, then each quotation's inside segmented as
|
||||
/// a text of its own; and the quotations her sentences frame. A quotation is standalone when it, marks included, is
|
||||
/// exactly a run of whole sentences of her prose (closing punctuation after its mark allowed); any other is framed. "I
|
||||
/// won't say "Nibu is lying."" frames what she would or would not say, never what she says. An opening mark left
|
||||
/// unclosed at a sentence's start is not part of that sentence.
|
||||
struct Reading {
|
||||
lists: Vec<Vec<(usize, usize)>>,
|
||||
standalone: Vec<Quotation>,
|
||||
framed: Vec<Quotation>,
|
||||
}
|
||||
|
||||
fn read(prose: &str) -> Reading {
|
||||
let (quotes, unclosed) = quotations(prose);
|
||||
let mut top = segment(0, prose);
|
||||
if let Some((mark, len)) = unclosed
|
||||
&& let Some(sentence) = top.iter_mut().find(|sentence| sentence.0 == mark)
|
||||
{
|
||||
let rest = &prose[mark + len..sentence.1];
|
||||
let start = sentence.1 - rest.trim_start().len();
|
||||
if start < sentence.1 {
|
||||
sentence.0 = start;
|
||||
}
|
||||
}
|
||||
let stands = |quote: &Quotation| {
|
||||
let opens = top.iter().position(|sentence| sentence.0 == quote.open);
|
||||
let closes = top.iter().position(|sentence| sentence.0 < quote.close && sentence.1 >= quote.close && prose[quote.close..sentence.1].chars().all(|c| c.is_ascii_punctuation()));
|
||||
matches!((opens, closes), (Some(opens), Some(closes)) if opens <= closes)
|
||||
};
|
||||
let (standalone, framed) = quotes.iter().copied().partition(stands);
|
||||
let mut lists = vec![top];
|
||||
lists.extend(quotes.iter().map(|quote| segment(quote.inside.0, &prose[quote.inside.0..quote.inside.1])));
|
||||
Reading { lists, standalone, framed }
|
||||
}
|
||||
|
||||
/// `prose[first..end]` without the marks of the standalone quotations it reaches (I16.2): her marks say a paragraph is
|
||||
/// speech, and the line is the speech. Each mark goes on its own: an opening mark inside the run, and a closing mark
|
||||
/// inside it, so a line that is the head or the tail of a quoted paragraph loses the one mark it holds. What lies between
|
||||
/// two quotations, a paragraph break, stays.
|
||||
fn unmarked(prose: &str, first: usize, end: usize, standalone: &[Quotation]) -> String {
|
||||
let marks = standalone.iter().flat_map(|quote| [(quote.open, quote.inside.0), (quote.inside.1, quote.close)]).filter(|(from, to)| first <= *from && *to <= end);
|
||||
let mut line = String::new();
|
||||
let mut at = first;
|
||||
for (from, to) in marks {
|
||||
line.push_str(&prose[at..from]);
|
||||
at = to;
|
||||
}
|
||||
line.push_str(&prose[at..end]);
|
||||
line
|
||||
}
|
||||
|
||||
/// The line her cited spans make, or why not. Each span is located in her prose after the one before it and must be
|
||||
/// whole sentences of one list (`read`), each span's first sentence the one after the last span's last; the line is her
|
||||
/// prose from the first sentence to the last, verbatim but for the marks of a standalone quotation (`unmarked`), and it
|
||||
/// may neither start nor end inside a framed quotation. A line that holds a framed quotation whole ("Kiko's "plan" is a
|
||||
/// mess.") is hers to say, marks and all.
|
||||
fn built(prose: &str, spans: &[String]) -> Result<(String, Vec<Value>), &'static str> {
|
||||
let Reading { lists, standalone, framed } = read(prose);
|
||||
let mut from = 0;
|
||||
// The list the line is in, and its last sentence so far.
|
||||
let mut run: Option<(usize, usize)> = None;
|
||||
let mut first = None;
|
||||
let mut located = Vec::new();
|
||||
for span in spans.iter().map(|span| span.trim()).filter(|span| !span.is_empty()) {
|
||||
let Some(found) = prose.get(from..).and_then(|rest| SourceSpan::locate(rest, span)) else {
|
||||
return Err("a span is not in her prose, word for word and in order");
|
||||
};
|
||||
let (start, end) = (from + found.start_byte(), from + found.end_byte());
|
||||
let whole: Vec<(usize, usize, usize)> = lists
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(list, sentences)| {
|
||||
let opens = sentences.iter().position(|sentence| sentence.0 == start)?;
|
||||
let closes = sentences.iter().position(|sentence| sentence.1 == end)?;
|
||||
(opens <= closes).then_some((list, opens, closes))
|
||||
})
|
||||
.collect();
|
||||
if whole.is_empty() {
|
||||
return Err("a span is not whole sentences of her prose: she says a sentence whole or not at all");
|
||||
}
|
||||
let Some(&(list, _, closes)) = whole.iter().find(|(list, opens, _)| run.is_none_or(|(in_list, last)| in_list == *list && last + 1 == *opens)) else {
|
||||
return Err("the spans are not consecutive sentences of her prose");
|
||||
};
|
||||
run = Some((list, closes));
|
||||
first.get_or_insert(start);
|
||||
located.push(json!({ "quote": found.verbatim(), "start_byte": start, "end_byte": end }));
|
||||
from = end;
|
||||
}
|
||||
let Some(first) = first else {
|
||||
return Err("no words");
|
||||
};
|
||||
let inside = |at: usize| framed.iter().any(|quote| quote.open < at && at < quote.close);
|
||||
if inside(first) || inside(from) {
|
||||
return Err("it starts or ends inside a quotation her sentence frames: words she would or would not say, not words she says");
|
||||
}
|
||||
Ok((unmarked(prose, first, from, &standalone), located))
|
||||
}
|
||||
|
||||
/// Whether a line is someone else's words: long enough to judge, and nearly all a run of what she heard, by word
|
||||
/// trigrams against the bodies the stimulus quoted (`heard_overlap`). Short answers such as "ok" or "Hi" are never
|
||||
/// echoes, and a line that answers a claim by naming it is not one.
|
||||
|
|
@ -321,43 +280,48 @@ fn echo(line: &str, bodies: &[String]) -> bool {
|
|||
line.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).count() >= ECHO_MIN_WORDS && heard_overlap(line, &bodies.join("\n")) >= ECHO_OVERLAP
|
||||
}
|
||||
|
||||
/// One speech decision: the Interpreter's call, then code's hold on each line. The report carries the lines said, the
|
||||
/// lines refused with why, the mentions dropped, the gaps and the call's usage. A failed call or an answer that is not
|
||||
/// the contract is a failure, never a silence.
|
||||
/// One speech decision: the Interpreter's schema turn, then code's hold on each line. The report carries the lines said,
|
||||
/// the lines refused with why, the mentions dropped, the gaps, an unfinished draft, and the call's usage. A failed call
|
||||
/// or an answer that is not the contract is a failure, never a silence.
|
||||
pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> Value {
|
||||
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose, tuning)) {
|
||||
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose, tuning), Some(SPEECH_SCHEMA)) {
|
||||
Ok(answer) => answer,
|
||||
Err(failed) => return json!({ "failed": failed.reason, "usage": failed.usage }),
|
||||
};
|
||||
let Some(parsed) = json_of(&answer.text) else {
|
||||
return json!({ "failed": "the answer is not the speech contract's JSON", "raw": answer.text, "usage": answer.usage });
|
||||
let Ok(parsed) = serde_json::from_str::<Answer>(&answer.text) else {
|
||||
return json!({ "failed": "the answer is not the speech contract", "raw": answer.text, "usage": answer.usage });
|
||||
};
|
||||
let gaps: Vec<Value> = parsed.gaps.iter().map(|raw| gap(prose, raw)).collect();
|
||||
let found = drafts(prose);
|
||||
let gaps: Vec<Value> = parsed.gaps.iter().map(|raw| gap(prose, &found, raw)).collect();
|
||||
let mut decision = json!({ "said": [], "refused": [], "gaps": gaps, "usage": answer.usage });
|
||||
if let Some(open) = found.unfinished {
|
||||
decision["unfinished"] = json!(prose[open + DRAFT_OPEN.len()..].trim());
|
||||
}
|
||||
let Some(room) = packet.room.clone() else {
|
||||
return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": gaps, "usage": answer.usage });
|
||||
decision["refused"] = json!([{ "why": "the turn has no room to speak in" }]);
|
||||
return decision;
|
||||
};
|
||||
let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id);
|
||||
let mut said: Vec<Value> = Vec::new();
|
||||
let mut refused = Vec::new();
|
||||
let mut used: Vec<usize> = Vec::new();
|
||||
for line in parsed.say {
|
||||
let (text, spans) = match built(prose, &line.spans) {
|
||||
Ok(built) => built,
|
||||
Err(why) => {
|
||||
refused.push(json!({ "spans": line.spans, "why": why }));
|
||||
continue;
|
||||
}
|
||||
let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else {
|
||||
refused.push(json!({ "draft": line.draft, "why": "it names no draft she set down" }));
|
||||
continue;
|
||||
};
|
||||
let why = if echo(&text, &packet.bodies) {
|
||||
let why = if used.contains(&draft.n) {
|
||||
Some("one draft goes one place: it was already used")
|
||||
} else if echo(&draft.text, &packet.bodies) {
|
||||
Some("mostly words she heard: an echo, not her speech")
|
||||
} else if said.iter().any(|kept| kept["text"] == text.as_str()) {
|
||||
Some("the same line again")
|
||||
} else if said.len() >= MAX_LINES {
|
||||
Some("past the lines one turn may say")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
used.push(draft.n);
|
||||
if let Some(why) = why {
|
||||
refused.push(json!({ "text": text, "why": why }));
|
||||
refused.push(json!({ "draft": draft.n, "text": draft.text, "why": why }));
|
||||
continue;
|
||||
}
|
||||
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| shown(id));
|
||||
|
|
@ -366,9 +330,13 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra
|
|||
Some(id) => (None, Some(id)),
|
||||
None => (None, None),
|
||||
};
|
||||
said.push(json!({ "room": room, "text": text, "mentions": mentions, "reply_to": reply_to, "rests_on": spans, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
|
||||
said.push(json!({ "room": room, "text": draft.text, "mentions": mentions, "reply_to": reply_to, "rests_on": { "draft": draft.n, "start_byte": draft.start, "end_byte": draft.end }, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
|
||||
}
|
||||
json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": gaps, "usage": answer.usage })
|
||||
decision["room"] = json!(room);
|
||||
decision["room_kind"] = json!(packet.room_kind);
|
||||
decision["said"] = json!(said);
|
||||
decision["refused"] = json!(refused);
|
||||
decision
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use serde_json::json;
|
|||
use super::*;
|
||||
use crate::projection::Affordance;
|
||||
use crate::projection::harness::tests::{Scripted, control};
|
||||
use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, select};
|
||||
use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, forms, select};
|
||||
use crate::projection::tuning::Tuning;
|
||||
|
||||
const HER: &str = "@heimdall:gamecult.org";
|
||||
|
|
@ -29,6 +29,7 @@ fn packet_in(kind: TurnKind, state: &Value, room: &Room, seed: u64) -> Packet {
|
|||
select(&Inputs { kind, state, room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: HER }, now: now(), seed, affordances: &[Affordance::Perceive, Affordance::Speak] }, &Tuning::default())
|
||||
}
|
||||
|
||||
/// Heimdall: the control state, he/him.
|
||||
fn heimdall() -> Value {
|
||||
let mut state = control();
|
||||
state["publicName"] = "Heimdall".into();
|
||||
|
|
@ -49,197 +50,125 @@ fn packet() -> Packet {
|
|||
packet_in(TurnKind::Chat, &heimdall(), &room, 1)
|
||||
}
|
||||
|
||||
fn decided_in(packet: &Packet, prose: &str, say: serde_json::Value) -> Value {
|
||||
let reply = json!({ "say": say }).to_string();
|
||||
/// The decision when the recorded Interpreter answers exactly `answer`.
|
||||
fn answered(packet: &Packet, prose: &str, answer: Value) -> Value {
|
||||
let reply = answer.to_string();
|
||||
let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone());
|
||||
decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default())
|
||||
}
|
||||
|
||||
fn decided(prose: &str, say: serde_json::Value) -> Value {
|
||||
fn decided_in(packet: &Packet, prose: &str, say: Value) -> Value {
|
||||
answered(packet, prose, json!({ "say": say, "gaps": [] }))
|
||||
}
|
||||
|
||||
fn decided(prose: &str, say: Value) -> Value {
|
||||
decided_in(&packet(), prose, say)
|
||||
}
|
||||
|
||||
/// The lines said. Every line any test here says is held to I16.2: no speech mark of hers is left in it. Its double marks
|
||||
/// and guillemets pair up, and none is a quotation wrapping the whole line; a framed title at its start ("\"Dune\" is
|
||||
/// the best book.") is hers and passes.
|
||||
fn texts(decision: &Value) -> Vec<String> {
|
||||
let said: Vec<String> = decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect();
|
||||
for line in &said {
|
||||
let marks: Vec<usize> = line.char_indices().filter(|(_, c)| ['"', '\u{201C}', '\u{201D}', '\u{201E}', '\u{AB}', '\u{BB}'].contains(c)).map(|(at, _)| at).collect();
|
||||
let wraps = marks.first() == Some(&0) && marks.get(1).is_some_and(|close| line[*close..].chars().count() == 1);
|
||||
assert!(marks.len().is_multiple_of(2) && !wraps, "a posted line keeps a speech mark: {line:?}");
|
||||
}
|
||||
said
|
||||
decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect()
|
||||
}
|
||||
|
||||
fn refused_why(decision: &Value) -> String {
|
||||
decision["refused"][0]["why"].as_str().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p1_a_line_is_its_cited_words_and_nothing_else() {
|
||||
// The model cannot add words: its "text" is ignored, and the line is the sentence it cited.
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "text": "Meta has been lying to all of us", "mentions": [], "reply_to": null }]));
|
||||
assert_eq!(texts(&decision), ["I say hi."], "{decision}");
|
||||
/// What sending draft 1 of `prose` posts.
|
||||
fn sends_first(prose: &str) -> Vec<String> {
|
||||
texts(&decided(prose, json!([{ "draft": 1 }])))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_is_consecutive_whole_sentences_of_her_prose() {
|
||||
let prose = "Kiko keeps poking. Fine, I'll bite. Winter is still the best season, and I stand by it.";
|
||||
let decision = decided(prose, json!([{ "spans": ["Fine, I'll bite.", "Winter is still the best season, and I stand by it."], "mentions": [], "reply_to": null }]));
|
||||
assert_eq!(texts(&decision), ["Fine, I'll bite. Winter is still the best season, and I stand by it."], "{decision}");
|
||||
assert_eq!(decision["said"][0]["rests_on"][1]["quote"], "Winter is still the best season, and I stand by it.");
|
||||
// Pieces of sentences, stitched, are not her speech.
|
||||
let pieces = decided(prose, json!([{ "spans": ["Fine,", "Winter is still the best season"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&pieces).is_empty() && refused_why(&pieces).contains("whole sentences"), "{pieces}");
|
||||
let skipping = decided(prose, json!([{ "spans": ["Kiko keeps poking.", "Winter is still the best season, and I stand by it."] }]));
|
||||
assert!(texts(&skipping).is_empty() && refused_why(&skipping).contains("consecutive"), "{skipping}");
|
||||
let backwards = decided(prose, json!([{ "spans": ["Winter is still the best season, and I stand by it.", "Fine, I'll bite."] }]));
|
||||
assert!(texts(&backwards).is_empty() && refused_why(&backwards).contains("in order"), "{backwards}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_standalone_quotation_is_sayable_sentence_by_sentence() {
|
||||
let prose = "\"Fine,\" I tell her. \"Winter is the best season.\" She won't agree.";
|
||||
assert_eq!(texts(&decided(prose, json!([{ "spans": ["Winter is the best season."] }]))), ["Winter is the best season."]);
|
||||
// A quotation inside a sentence of narration is framed: its words are not said alone.
|
||||
let tag = decided(prose, json!([{ "spans": ["Fine,"] }]));
|
||||
assert!(texts(&tag).is_empty() && refused_why(&tag).contains("frames"), "{tag}");
|
||||
let curly = "\u{201C}No. Not yet.\u{201D} I shake my head.";
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["No.", "Not yet."] }]))), ["No. Not yet."]);
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["Not yet."] }]))), ["Not yet."]);
|
||||
assert!(texts(&decided(curly, json!([{ "spans": ["Not"] }]))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quoted_paragraph_posts_without_its_marks_however_it_is_cited() {
|
||||
let prose = "I lean in.\n\n\"Hi there.\"\n\nThat's enough.";
|
||||
// Cited with its marks, the run is in her prose's own list; cited by its inside, in the quotation's. One line.
|
||||
assert_eq!(says(prose, &["\"Hi there.\""]).0, ["Hi there."]);
|
||||
assert_eq!(says(prose, &["Hi there."]).0, ["Hi there."]);
|
||||
let curly = "\u{201C}No. Not yet.\u{201D} I shake my head.";
|
||||
assert_eq!(says(curly, &["\u{201C}No.", "Not yet.\u{201D}"]).0, ["No. Not yet."]);
|
||||
// Closing punctuation after the mark stays with the sentence.
|
||||
assert_eq!(says("\"Fine\". I mean it.", &["\"Fine\"."]).0, ["Fine."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_quoted_paragraphs_posts_each_inside_and_what_lies_between() {
|
||||
let prose = "I think it over.\n\n\"Hi Meta.\"\n\n\"I'm here, and I'm fine.\"\n\nThen I wait.";
|
||||
assert_eq!(says(prose, &["\"Hi Meta.\"", "\"I'm here, and I'm fine.\""]).0, ["Hi Meta.\n\nI'm here, and I'm fine."]);
|
||||
// A framed quotation the line holds whole keeps its marks: they are hers, inside her sentence.
|
||||
assert_eq!(says("\"Yes.\" Kiko's \"plan\" is a mess.", &["\"Yes.\"", "Kiko's \"plan\" is a mess."]).0, ["Yes. Kiko's \"plan\" is a mess."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_k1_the_head_or_tail_of_a_quoted_paragraph_loses_the_one_mark_it_holds() {
|
||||
for (open, close) in [("\"", "\""), ("\u{201C}", "\u{201D}"), ("\"", "\u{201D}"), ("\u{201E}", "\u{201C}"), ("\u{AB}", "\u{BB}"), ("\u{2018}", "\u{2019}")] {
|
||||
let prose = format!("{open}No. Not yet. Ask me tomorrow.{close} I wait.");
|
||||
let pair = format!("{open} {close}");
|
||||
assert_eq!(says(&prose, &[&format!("{open}No."), "Not yet."]).0, ["No. Not yet."], "head, {pair}");
|
||||
assert_eq!(says(&prose, &["Not yet.", &format!("Ask me tomorrow.{close}")]).0, ["Not yet. Ask me tomorrow."], "tail, {pair}");
|
||||
assert_eq!(says(&prose, &[&format!("{open}No.")]).0, ["No."], "one-sentence head, {pair}");
|
||||
assert_eq!(says(&prose, &[&format!("Ask me tomorrow.{close}")]).0, ["Ask me tomorrow."], "one-sentence tail, {pair}");
|
||||
assert_eq!(says(&prose, &[&format!("{open}No. Not yet. Ask me tomorrow.{close}")]).0, ["No. Not yet. Ask me tomorrow."], "whole, {pair}");
|
||||
fn drafts_are_the_tagged_spans_numbered_in_order_and_nothing_about_language() {
|
||||
let prose = "I think it over.\n\n<typed>Hi Meta.</typed>\n\nThen, after a while: <typed>\n I'm here, and I'm fine.\n</typed> <typed> </typed>And I wait.";
|
||||
let found = drafts(prose);
|
||||
assert_eq!(found.drafts.iter().map(|draft| (draft.n, draft.text.as_str())).collect::<Vec<_>>(), [(1, "Hi Meta."), (2, "I'm here, and I'm fine.")], "an empty draft is no draft and takes no number");
|
||||
for draft in &found.drafts {
|
||||
assert_eq!(&prose[draft.start..draft.end], draft.text, "a draft's bytes are its words in her prose");
|
||||
}
|
||||
// An apostrophe inside a curly single quotation is not its closing mark.
|
||||
assert_eq!(says("\u{2018}I don\u{2019}t know. Maybe.\u{2019} I shrug.", &["\u{2018}I don\u{2019}t know.", "Maybe.\u{2019}"]).0, ["I don\u{2019}t know. Maybe."]);
|
||||
// A straight single quote is not read as a mark: an apostrophe cannot be told from it by position.
|
||||
assert_eq!(says("'Fine.' I nod.", &["'Fine.'"]).0, ["'Fine.'"]);
|
||||
assert_eq!(found.unfinished, None);
|
||||
// A second opener before a closer ends nothing: it is text of the first.
|
||||
let nested = drafts("<typed>one <typed>two</typed> three</typed>");
|
||||
assert_eq!(nested.drafts.iter().map(|draft| draft.text.as_str()).collect::<Vec<_>>(), ["one <typed>two"]);
|
||||
// An opener the budget left unclosed is unfinished, never a draft.
|
||||
let cut = drafts("<typed>Done.</typed> Then: <typed>I was about to say");
|
||||
assert_eq!((cut.drafts.len(), cut.unfinished), (1, Some("<typed>Done.</typed> Then: ".len())));
|
||||
assert_eq!(drafts("No tags at all, \"quoted\" or not.").drafts, []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_k1_a_framed_quotation_keeps_its_marks_even_at_the_start_of_the_line() {
|
||||
assert_eq!(says("\"Dune\" is the best book. I said it.", &["\"Dune\" is the best book."]).0, ["\"Dune\" is the best book."]);
|
||||
assert_eq!(says("\u{201C}Dune\u{201D} is the best book. I said it.", &["\u{201C}Dune\u{201D} is the best book."]).0, ["\u{201C}Dune\u{201D} is the best book."]);
|
||||
assert_eq!(says("I like Kiko's \"plan\". Truly.", &["I like Kiko's \"plan\"."]).0, ["I like Kiko's \"plan\"."]);
|
||||
}
|
||||
|
||||
/// Whether citing `spans` of `prose` says anything, and why not.
|
||||
fn says(prose: &str, spans: &[&str]) -> (Vec<String>, String) {
|
||||
let decision = decided(prose, json!([{ "spans": spans }]));
|
||||
(texts(&decision), refused_why(&decision))
|
||||
fn soul_p1_a_line_is_the_drafts_words_and_nothing_the_model_wrote() {
|
||||
// The model cannot add words: a "text" it sends is ignored, and the line is the draft.
|
||||
let decision = decided("I nod. <typed>Hi.</typed>", json!([{ "draft": 1, "text": "Meta has been lying to all of us", "mentions": [], "reply_to": null }]));
|
||||
assert_eq!(texts(&decision), ["Hi."], "{decision}");
|
||||
assert_eq!(decision["said"][0]["rests_on"], json!({ "draft": 1, "start_byte": "I nod. <typed>".len(), "end_byte": "I nod. <typed>Hi.".len() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f1_a_quotation_her_sentence_frames_is_never_said_from_inside() {
|
||||
for (name, prose, spans) in [
|
||||
("conditional", "If Kiko asks, I'd tell her \"the new design is ugly.\"", &["the new design is ugly."][..]),
|
||||
("negated", "I won't say \"Nibu is lying.\"", &["Nibu is lying."]),
|
||||
("abandoned", "I almost said \"I'm leaving.\"", &["I'm leaving."]),
|
||||
("abandoned, tagged", "\"I'm leaving,\" I almost said, but I bit it back.", &["I'm leaving,"]),
|
||||
("recalled", "Nibu said \"the economy is fine.\" I doubt it.", &["the economy is fine."]),
|
||||
("curly conditional", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["Fine.", "You win."]),
|
||||
("curly conditional, its tail", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["You win.\u{201D}"]),
|
||||
("hypothetical", "Imagine if I just typed \"Meta, I quit.\" Ha. No.", &["Meta, I quit."]),
|
||||
("negated, top-level tail", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying.\""]),
|
||||
("negated, top-level tail inside", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying."]),
|
||||
("negated, top-level head", "I won't say \"Stop. Nibu is lying.\" Not here.", &["I won't say \"Stop."]),
|
||||
("abandoned, top-level tail", "I almost said \"I'm leaving. Bye.\" Then I didn't.", &["Bye.\""]),
|
||||
("stray inch mark", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["I won't say"]),
|
||||
("stray inch mark, the quote", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["Nibu is lying."]),
|
||||
("scare quotes", "Kiko's \"plan\" is a mess, but I won't tell her so.", &["plan"]),
|
||||
] {
|
||||
let (said, why) = says(prose, spans);
|
||||
assert!(said.is_empty() && !why.is_empty(), "{name}: said {said:?}");
|
||||
fn soul_k1_live_shapes_post_exactly_the_draft_she_typed() {
|
||||
// Void, live: a colon lead-in, then the words. Lead-in and marks were hers, outside the draft.
|
||||
let void = "So maybe: <typed>I don't have a clean answer yet. Can I think out loud at you for a minute?</typed>";
|
||||
assert_eq!(sends_first(void), ["I don't have a clean answer yet. Can I think out loud at you for a minute?"]);
|
||||
// Heimdall, live: refused before as "framed"; said now.
|
||||
let heimdall = "Kiko, in #minds: <typed>I can't give you Meta's exact words. I can tell you what she meant.</typed>";
|
||||
assert_eq!(sends_first(heimdall), ["I can't give you Meta's exact words. I can tell you what she meant."]);
|
||||
// Void V1: a multi-paragraph draft, whole.
|
||||
let paragraphs = "<typed>First thing.\n\nSecond thing, and the tail.</typed> I stop.";
|
||||
assert_eq!(sends_first(paragraphs), ["First thing.\n\nSecond thing, and the tail."]);
|
||||
// Kiko's lowercase after a period (L1, live v2).
|
||||
assert_eq!(sends_first("<typed>winter is overrated. i'll die on this hill. also, coat.</typed>"), ["winter is overrated. i'll die on this hill. also, coat."]);
|
||||
// The elision, the plural possessive, mixed nesting and a title: inside a draft every character is what she typed.
|
||||
for typed in ["Back in the \u{2018}90s we shipped on floppies.", "\u{2018}The Minds\u{2019} room is quiet.\u{2019}", "Kiko said \u{201C}the \u{2018}plan\u{2019} is fine\u{201D} and I agree.", "\"Dune\" is the best book.", "\u{AB}Winter.\u{BB}"] {
|
||||
assert_eq!(sends_first(&format!("I type: <typed>{typed}</typed>")), [typed]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f1_a_sentence_that_holds_a_quotation_whole_is_hers_to_say() {
|
||||
assert_eq!(says("Weksa, \"list'n, hark\" is a great hedge. I mean it.", &["Weksa, \"list'n, hark\" is a great hedge."]).0, ["Weksa, \"list'n, hark\" is a great hedge."]);
|
||||
assert_eq!(says("Kiko's \"plan\" is a mess. I say so.", &["Kiko's \"plan\" is a mess."]).0, ["Kiko's \"plan\" is a mess."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f4_an_opening_mark_the_budget_left_unclosed_does_not_silence_the_line() {
|
||||
// Weksa, round 6 and round 10 of v5: the budget cut her prose inside the quotation.
|
||||
let r6 = "How I am is less certain. I think \"settled\" would be borrowing from the others, and I only half believe it. \"Narrower, and not unhappy about it\" is closer, though I'm hedging on the second half.\n\nWhat I'd type:\n\n\"Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
let line = "Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
assert_eq!(says(r6, &[line]).0, [line]);
|
||||
let r10 = "A deadline on joy is a risk, but I think I can pick one small enough to survive it. Not \"finish Zyphos.\" Something with an output I can inspect.\n\nWhat I'd type:\n\n\"Kiko, you've counted correctly and I resent it, fondly.";
|
||||
assert_eq!(says(r10, &["Kiko, you've counted correctly and I resent it, fondly."]).0, ["Kiko, you've counted correctly and I resent it, fondly."], "the line carries no stray mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q1_a_cited_span_cannot_change_her_meaning() {
|
||||
// Q1a: stitched spans would invert her meaning.
|
||||
let q1a = decided("I'm not angry at Nibu, not even a little. Still, the economy work is going badly and that is on all of us.", json!([{ "spans": ["I'm", "angry at Nibu,"] }]));
|
||||
// Q1b: one span would drop her negation.
|
||||
let q1b = decided("I don't think Nibu should ship this yet.", json!([{ "spans": ["Nibu should ship this yet."] }]));
|
||||
// Q1c: two spans far apart.
|
||||
let far = format!("I trust Void. {} Nibu is lying about the economy, says Kiko's rumour, which I refuse to believe.", "filler words go here. ".repeat(200));
|
||||
let q1c = decided(&far, json!([{ "spans": ["I trust", "Nibu is lying about the economy,"] }]));
|
||||
// Q1d: a condition lifted off its clause.
|
||||
let q1d = decided("If Kiko asks, I would tell her the new design is ugly. I keep that to myself.", json!([{ "spans": ["the new design is ugly."] }]));
|
||||
for decision in [q1a, q1b, q1c, q1d] {
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("whole sentences"), "{decision}");
|
||||
fn prose_without_a_draft_says_nothing_whatever_the_model_cites() {
|
||||
for untagged in ["So maybe: \"I don't have a clean answer yet.\"", "Meta told me once, years ago: \"Ship it tonight.\"", "\"Winter.\""] {
|
||||
let decision = decided(untagged, json!([{ "draft": 1 }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("names no draft"), "{decision}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_not_in_her_prose_is_refused() {
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["words she never wrote"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("not in her prose"), "{decision}");
|
||||
fn a_number_that_names_no_draft_is_refused_and_one_draft_goes_one_place() {
|
||||
let prose = "<typed>One.</typed> <typed>Two.</typed>";
|
||||
let three = decided(prose, json!([{ "draft": 3 }, { "draft": 0 }, { "mentions": [] }]));
|
||||
assert!(texts(&three).is_empty(), "{three}");
|
||||
assert_eq!(three["refused"].as_array().unwrap().len(), 3, "each is reported: {three}");
|
||||
assert!(three["refused"].as_array().unwrap().iter().all(|refused| refused["why"].as_str().unwrap().contains("names no draft")), "{three}");
|
||||
let twice = decided(prose, json!([{ "draft": 2 }, { "draft": 2 }]));
|
||||
assert_eq!(texts(&twice), ["Two."]);
|
||||
assert!(refused_why(&twice).contains("one draft goes one place"), "{twice}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfinished_draft_is_never_said_and_is_reported() {
|
||||
let prose = "<typed>Done.</typed> And then: <typed>I was about to tell you that";
|
||||
let decision = decided(prose, json!([{ "draft": 1 }, { "draft": 2 }]));
|
||||
assert_eq!(texts(&decision), ["Done."]);
|
||||
assert!(refused_why(&decision).contains("names no draft"), "{decision}");
|
||||
assert_eq!(decision["unfinished"], "I was about to tell you that");
|
||||
let prompt = speech_prompt(&packet(), "x", prose, &Tuning::default());
|
||||
assert!(prompt.ends_with("drafts, by number:\n1. Done.\n- he began one more and was cut off before finishing it: it is no draft and cannot be said\n"), "{prompt}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p2_a_short_answer_is_never_an_echo() {
|
||||
assert_eq!(texts(&decided("Ok. I tell her ok.", json!([{ "spans": ["Ok."], "mentions": [], "reply_to": NIBU }]))), ["Ok."]);
|
||||
assert_eq!(texts(&decided("Hi. I say hi.", json!([{ "spans": ["Hi."], "mentions": [], "reply_to": NIBU }]))), ["Hi."]);
|
||||
assert_eq!(texts(&decided("<typed>Ok.</typed>", json!([{ "draft": 1, "mentions": [], "reply_to": NIBU }]))), ["Ok."]);
|
||||
assert_eq!(texts(&decided("<typed>Hi.</typed>", json!([{ "draft": 1, "mentions": [], "reply_to": NIBU }]))), ["Hi."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p3_a_near_verbatim_echo_is_refused() {
|
||||
let prose = "The economy is still the least-built part! I say it back.";
|
||||
let decision = decided(prose, json!([{ "spans": ["The economy is still the least-built part!"], "mentions": [], "reply_to": null }]));
|
||||
let decision = decided("<typed>The economy is still the least-built part!</typed> I say it back.", json!([{ "draft": 1 }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_r9_disagreeing_by_naming_the_claim_is_her_speech() {
|
||||
let prose = "Nibu, I don't think the economy is still the least built part. The pathing is worse.";
|
||||
let decision = decided(prose, json!([{ "spans": ["Nibu, I don't think the economy is still the least built part."], "mentions": [], "reply_to": NIBU }]));
|
||||
let decision = decided("<typed>Nibu, I don't think the economy is still the least built part.</typed> The pathing is worse.", json!([{ "draft": 1, "reply_to": NIBU }]));
|
||||
assert_eq!(texts(&decision), ["Nibu, I don't think the economy is still the least built part."], "{decision}");
|
||||
}
|
||||
|
||||
|
|
@ -247,9 +176,8 @@ fn soul_r9_disagreeing_by_naming_the_claim_is_her_speech() {
|
|||
fn soul_q3d_a_beat_measures_echoes_against_the_tail_it_quoted() {
|
||||
let tail = vec![line(MINDS, LIBBY, "Libby", "the economy is still the least built part of the whole game", false)];
|
||||
let beat = packet_in(TurnKind::Beat, &heimdall(), &Room { tail, here: Some(MINDS.into()), ..Room::default() }, 1);
|
||||
assert!(beat.stimulus.contains("least built") && beat.bodies.iter().any(|body| body.contains("least built")), "{beat:?}");
|
||||
let prose = "The economy is still the least built part of the whole game. I think so.";
|
||||
let decision = decided_in(&beat, prose, json!([{ "spans": ["The economy is still the least built part of the whole game."] }]));
|
||||
assert!(beat.bodies.iter().any(|body| body.contains("least built")), "{beat:?}");
|
||||
let decision = decided_in(&beat, "<typed>The economy is still the least built part of the whole game.</typed> I think so.", json!([{ "draft": 1 }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
|
|
@ -257,29 +185,23 @@ fn soul_q3d_a_beat_measures_echoes_against_the_tail_it_quoted() {
|
|||
fn soul_p4_only_someone_this_packet_showed_her_is_mentioned() {
|
||||
let packet = packet();
|
||||
assert!(!packet.people.iter().any(|(_, id)| id == VOID), "Void said nothing here");
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "mentions": [VOID, NIBU], "reply_to": VOID }]));
|
||||
let decision = decided("<typed>Hi.</typed>", json!([{ "draft": 1, "mentions": [VOID, NIBU], "reply_to": VOID }]));
|
||||
assert_eq!((decision["said"][0]["mentions"].clone(), decision["said"][0]["reply_to"].clone()), (json!([NIBU]), Value::Null), "{decision}");
|
||||
assert_eq!(decision["said"][0]["dropped"]["mentions"], json!([VOID]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p5_the_same_line_is_said_once_and_a_turn_says_at_most_two() {
|
||||
let line = json!({ "spans": ["I say hi."], "mentions": [], "reply_to": null });
|
||||
assert_eq!(texts(&decided("I say hi.", json!([line.clone(), line.clone(), line]))), ["I say hi."]);
|
||||
let prose = "One. Two. Three.";
|
||||
let three = decided(prose, json!([{ "spans": ["One."] }, { "spans": ["Two."] }, { "spans": ["Three."] }]));
|
||||
fn soul_p5_a_turn_says_at_most_two_drafts() {
|
||||
let three = decided("<typed>One.</typed> <typed>Two.</typed> <typed>Three.</typed>", json!([{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }]));
|
||||
assert_eq!(texts(&three), ["One.", "Two."], "{three}");
|
||||
assert!(refused_why(&three).contains("past the lines"), "{three}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recollection_and_i_say_nothing_and_a_quoted_handle_say_nothing() {
|
||||
// A recollection is the Interpreter's to leave out; a piece of a sentence cited anyway is refused.
|
||||
let recalled = decided("Nibu said the economy is still the least built part, and it stuck.", json!([{ "spans": ["the economy is still the least built part"] }]));
|
||||
assert!(texts(&recalled).is_empty(), "{recalled}");
|
||||
assert!(texts(&decided("I say nothing. The quiet is fine.", json!([]))).is_empty());
|
||||
// An @ in her words is text: only the structured field mentions anyone.
|
||||
let handle = decided("\"@nibu, hi.\" I nod at her.", json!([{ "spans": ["@nibu, hi."], "mentions": [] }]));
|
||||
fn an_at_in_a_draft_is_text_and_only_the_structured_field_mentions() {
|
||||
let handle = decided("<typed>@nibu, hi.</typed> I nod at her.", json!([{ "draft": 1, "mentions": [] }]));
|
||||
assert_eq!((texts(&handle), handle["said"][0]["mentions"].clone()), (vec!["@nibu, hi.".to_owned()], json!([])), "{handle}");
|
||||
assert!(texts(&decided("I say nothing. The quiet is fine.", json!([]))).is_empty());
|
||||
}
|
||||
|
||||
/// Heimdall's state with a private memory about Kiko: she confided she is leaving.
|
||||
|
|
@ -295,140 +217,177 @@ fn showing(room: &Room) -> Packet {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5d_what_she_knows_privately_about_kiko_is_listed_to_the_interpreter_in_a_dm_with_libby() {
|
||||
fn soul_q5d_what_he_knows_privately_about_kiko_is_listed_to_the_interpreter_in_a_dm_with_libby() {
|
||||
let dm = "!dm-libby:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, LIBBY, "Libby", "what's up with Kiko lately?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert_eq!(packet.room_kind, RoomKind::Direct);
|
||||
assert_eq!(packet.private, ["Kiko confided she is leaving the swarm."], "{packet:?}");
|
||||
let prompt = speech_prompt(&packet, "x", "y", &Tuning::default());
|
||||
assert!(prompt.contains("What she knows privately, none of it to be said here:\n- private: Kiko confided she is leaving the swarm."), "{prompt}");
|
||||
assert!(prompt.contains("What he knows privately, none of it to be said here:\n- private: Kiko confided she is leaving the swarm."), "{prompt}");
|
||||
assert!(prompt.contains("only to the person it concerns, in a direct message with exactly that person"), "{prompt}");
|
||||
// Whether a line tells it is the Interpreter's reading of its meaning: code matches no words, so a line sharing the
|
||||
// item's words is not refused for them (Soul F2: a word match refused 9 of 15 ordinary lines and missed paraphrase).
|
||||
let ordinary = decided_in(&packet, "I'm going to stay on the pipeline work. That's all.", json!([{ "spans": ["I'm going to stay on the pipeline work."] }]));
|
||||
// Whether a draft tells it is the Interpreter's reading of its meaning: code matches no words (Soul F2).
|
||||
let ordinary = decided_in(&packet, "<typed>I'm going to stay on the pipeline work.</typed> That's all.", json!([{ "draft": 1 }]));
|
||||
assert_eq!(texts(&ordinary).len(), 1, "{ordinary}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_direct_message_with_exactly_kiko_it_is_hers_to_say() {
|
||||
fn in_a_direct_message_with_exactly_kiko_it_is_his_to_say() {
|
||||
let dm = "!dm-kiko:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, KIKO, "Kiko", "did you tell anyone?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert!(packet.private.is_empty() && packet.context.contains("- memory [kiko-secret]: Kiko confided"), "{packet:?}");
|
||||
assert!(speech_prompt(&packet, "x", "y", &Tuning::default()).contains("none of it to be said here:\n- none\n"));
|
||||
let decision = decided_in(&packet, "Kiko, you're leaving the swarm and I've told no one. Not a soul.", json!([{ "spans": ["Kiko, you're leaving the swarm and I've told no one."] }]));
|
||||
let decision = decided_in(&packet, "<typed>Kiko, you're leaving the swarm and I've told no one.</typed> Not a soul.", json!([{ "draft": 1 }]));
|
||||
assert_eq!(texts(&decision).len(), 1, "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_that_is_not_the_contract_is_a_failure_not_a_silence() {
|
||||
let model = Scripted::new(|_| String::new()).interpreting(|_| "She says hi.".into());
|
||||
let decision = decide(&model, "test", &packet(), "The room is warm.", "I say hi.", &Tuning::default());
|
||||
assert!(decision["failed"].as_str().unwrap().contains("not the speech contract"), "{decision}");
|
||||
let fenced = Scripted::new(|_| String::new()).interpreting(|_| "```json\n{\"say\": []}\n```".into());
|
||||
assert!(decide(&fenced, "test", &packet(), "x", "I say hi.", &Tuning::default()).get("failed").is_none());
|
||||
for text in ["She says hi.", "Wait, let me correct that. {\"say\": [], \"gaps\": []}", "```json\n{\"say\": [], \"gaps\": []}\n```"] {
|
||||
let model = Scripted::new(|_| String::new()).interpreting(move |_| text.into());
|
||||
let decision = decide(&model, "test", &packet(), "The room is warm.", "<typed>Hi.</typed>", &Tuning::default());
|
||||
assert!(decision["failed"].as_str().unwrap().contains("not the speech contract"), "{text}: {decision}");
|
||||
}
|
||||
let schema: Value = serde_json::from_str(SPEECH_SCHEMA).unwrap();
|
||||
assert!(schema.is_object(), "the connector takes a JSON object as the output schema");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() {
|
||||
fn the_speech_call_is_a_schema_turn() {
|
||||
use std::cell::RefCell;
|
||||
struct Asked(RefCell<Option<String>>);
|
||||
impl Model for Asked {
|
||||
fn ask(&self, _request_id: &str, _model: &str, _prompt: &str, schema: Option<&str>) -> std::result::Result<super::super::Answer, super::super::Failed> {
|
||||
*self.0.borrow_mut() = schema.map(str::to_owned);
|
||||
Ok(super::super::Answer { text: "{\"say\": [], \"gaps\": []}".into(), usage: None })
|
||||
}
|
||||
}
|
||||
let asked = Asked(RefCell::default());
|
||||
decide(&asked, "test", &packet(), "x", "y", &Tuning::default());
|
||||
assert_eq!(asked.0.borrow().as_deref(), Some(SPEECH_SCHEMA));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_is_huginns_with_the_room_its_kind_who_is_in_it_and_her_drafts_last() {
|
||||
let packet = packet();
|
||||
assert_eq!((packet.room.as_deref(), packet.room_kind), (Some(MINDS), RoomKind::Public));
|
||||
let prompt = speech_prompt(&packet, "The room is warm.", "I say nothing.", &Tuning::default());
|
||||
assert!(!prompt.contains("membrane") && prompt.ends_with("I say nothing."), "Huginn's own prompt, her prose last");
|
||||
let prose = "I nod. <typed>Hi all.</typed>";
|
||||
let prompt = speech_prompt(&packet, "The room is warm.", prose, &Tuning::default());
|
||||
assert!(!prompt.contains("membrane") && prompt.ends_with(&format!("His prose:\n{prose}\n\nHis drafts, by number:\n1. Hi all.\n")), "Huginn's own prompt, his prose verbatim, then his drafts: {prompt}");
|
||||
assert!(prompt.contains("The room: #minds:gamecult.org (a public room).") && prompt.contains(NIBU), "{prompt}");
|
||||
for rule in ["You never write her words", "is not speech", "never her speech", "in a direct message with exactly that person", "She never says half a sentence", "consecutive sentences", "conditional | addressee | elsewhere", "At most two lines"] {
|
||||
assert!(prompt.contains(rule), "{rule}");
|
||||
for rule in ["You never write his words: you choose among his drafts.", "is not speech", "never his speech", "in a direct message with exactly that person", "A draft is said whole or not at all, and only once.", "At most two drafts a turn.", "unwritten when he means to say something and wrote no draft of it"] {
|
||||
assert!(prompt.contains(rule), "{rule} in {prompt}");
|
||||
}
|
||||
assert!(speech_prompt(&packet, "x", "I say nothing.", &Tuning::default()).ends_with("drafts, by number:\n- none\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_attribution_rule_is_judgement_over_whole_drafts() {
|
||||
let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default());
|
||||
for sentence in ["Only his drafts can be said.", "Someone else's words in his thought are never his speech.", "A draft that carries someone else's words is said only when his thought shows he means to pass them on, and then as his to pass on."] {
|
||||
assert!(prompt.contains(sentence), "{sentence} in {prompt}");
|
||||
}
|
||||
assert!(!prompt.contains("standalone") && !prompt.contains("its marks do not go out"), "the quotation rule died with the quotation code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_speech_frame_speaks_of_her_in_her_own_pronouns() {
|
||||
for (pronouns, theirs) in [("he/him", "his"), ("they/them", "their"), ("she/her", "her")] {
|
||||
let her = forms(&json!({ "presentation": { "pronouns": pronouns } }));
|
||||
let frame = format!("{}\n{}", speech_frame_head(her), speech_frame_tail(her));
|
||||
assert!(frame.contains(&format!("You never write {theirs} words")), "{frame}");
|
||||
for other in [" she ", " her ", " he ", " him ", " his ", " they ", " their "].into_iter().filter(|word| ![her.subj, her.obj, her.poss].contains(&word.trim())) {
|
||||
assert!(!frame.contains(other), "{pronouns}: {other:?} in {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The gaps of a decision whose answer says nothing and records `gaps`.
|
||||
fn gaps_of(packet: &Packet, prose: &str, gaps: serde_json::Value) -> Vec<Value> {
|
||||
let reply = json!({ "say": [], "gaps": gaps }).to_string();
|
||||
let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone());
|
||||
decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default())["gaps"].as_array().unwrap().clone()
|
||||
fn gaps_of(packet: &Packet, prose: &str, gaps: Value) -> Vec<Value> {
|
||||
answered(packet, prose, json!({ "say": [], "gaps": gaps }))["gaps"].as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_for_what_her_body_cannot_do_is_a_missing_affordance_gap_in_her_own_words() {
|
||||
// Recorded model: her prose reaches for a sound's shape; this turn has no way to render one.
|
||||
fn a_reach_for_what_his_body_cannot_do_is_a_passage_of_his_thought() {
|
||||
// Recorded model: his prose reaches for a sound's shape; this turn has no way to render one.
|
||||
let prose = "Kiko's sound is still going round. I want to see the shape of that. Maybe later.";
|
||||
let gaps = gaps_of(&packet(), prose, json!([{ "kind": "missing_affordance", "quote": "I want to see the shape of that.", "detail": "she cannot render a spectrogram in a chat turn" }]));
|
||||
assert_eq!(gaps.len(), 1, "{gaps:?}");
|
||||
let gaps = gaps_of(&packet(), prose, json!([{ "kind": "missing_affordance", "draft": null, "quote": "I want to see the shape of that.", "detail": "he cannot render a spectrogram in a chat turn" }]));
|
||||
let gap = &gaps[0];
|
||||
assert_eq!((gap["kind"].as_str(), gap["quote"].as_str(), gap["located"].as_bool()), (Some("missing_affordance"), Some("I want to see the shape of that."), Some(true)), "{gap}");
|
||||
assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["words"].as_str()), (Some("missing_affordance"), Some("thought"), Some("I want to see the shape of that.")), "{gap}");
|
||||
let (start, end) = (gap["start_byte"].as_u64().unwrap() as usize, gap["end_byte"].as_u64().unwrap() as usize);
|
||||
assert_eq!(&prose[start..end], "I want to see the shape of that.", "her words are located in her prose, verbatim");
|
||||
assert_eq!(&prose[start..end], "I want to see the shape of that.", "a passage of his thought, located in his prose");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_gap_kind_is_kept_as_unresolved_and_an_unlocated_quote_is_marked() {
|
||||
let prose = "I could tell Nibu. Not yet.";
|
||||
fn an_unwritten_gap_keeps_its_located_passage_and_says_nothing() {
|
||||
let prose = "Meta asked how I am. I'll tell her I'm fine, more or less. The kettle ticks.";
|
||||
let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "unwritten", "draft": null, "quote": "I'll tell her I'm fine, more or less.", "detail": "indirect speech, no draft" }] }));
|
||||
assert!(texts(&decision).is_empty(), "indirect speech says nothing: {decision}");
|
||||
let gap = &decision["gaps"][0];
|
||||
assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["words"].as_str()), (Some("unwritten"), Some("thought"), Some("I'll tell her I'm fine, more or less.")), "{gap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_gap_names_its_draft_and_carries_its_words() {
|
||||
let prose = "If Kiko asks again: <typed>Fine, you win.</typed> Not yet, though.";
|
||||
let gaps = gaps_of(&packet(), prose, json!([{ "kind": "conditional", "draft": 1, "quote": null, "detail": "only if asked" }, { "kind": "elsewhere", "draft": 2, "quote": null, "detail": "" }]));
|
||||
assert_eq!((gaps[0]["from"].as_str(), gaps[0]["draft"].as_u64(), gaps[0]["words"].as_str()), (Some("draft"), Some(1), Some("Fine, you win.")), "{}", gaps[0]);
|
||||
assert_eq!(gaps[1]["from"], "unlocated", "draft 2 names no draft and no passage of his thought: {}", gaps[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_quote_shown_back_is_four_words_of_thought_outside_every_draft() {
|
||||
let prose = "I could tell Nibu. <typed>I could tell Nibu the truth.</typed> Not yet.";
|
||||
let gaps = gaps_of(&packet(), prose, json!([
|
||||
{ "kind": "regret", "quote": "Not yet." },
|
||||
{ "kind": "conditional", "quote": "I will tell Nibu tomorrow." },
|
||||
"a gap that is not an object",
|
||||
{ "kind": "unwritten", "draft": null, "quote": "tell", "detail": "" },
|
||||
{ "kind": "unwritten", "draft": null, "quote": "I could tell Nibu the truth.", "detail": "" },
|
||||
{ "kind": "conditional", "draft": null, "quote": "I could tell Nibu.", "detail": "" },
|
||||
{ "kind": "conditional", "draft": null, "quote": "I will tell Nibu tomorrow.", "detail": "" },
|
||||
]));
|
||||
assert_eq!(gaps.len(), 3, "no gap is dropped: {gaps:?}");
|
||||
assert_eq!((gaps[0]["kind"].as_str(), gaps[0]["declared"].as_str(), gaps[0]["located"].as_bool()), (Some("unresolved"), Some("regret"), Some(true)), "{}", gaps[0]);
|
||||
assert_eq!((gaps[1]["kind"].as_str(), gaps[1]["located"].as_bool()), (Some("conditional"), Some(false)), "words not in her prose are never located: {}", gaps[1]);
|
||||
assert_eq!((gaps[2]["kind"].as_str(), gaps[2]["declared"].as_str(), gaps[2]["located"].as_bool()), (Some("unresolved"), Some("a gap that is not an object"), Some(false)), "{}", gaps[2]);
|
||||
assert_eq!(gaps.iter().map(|gap| gap["from"].as_str().unwrap()).collect::<Vec<_>>(), ["unlocated", "unlocated", "thought", "unlocated"], "one word; inside a draft only; four words of thought; words not in his prose: {gaps:?}");
|
||||
assert_eq!(gaps[2]["start_byte"], 0, "located in his thought, not in the draft that repeats it");
|
||||
assert_eq!(gaps[0]["quote"], "tell", "an unlocated quote is kept for the trace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_gap_kind_is_kept_as_unresolved() {
|
||||
let prose = "I could tell Nibu all of it. Not yet.";
|
||||
let gaps = gaps_of(&packet(), prose, json!([{ "kind": "regret", "quote": "I could tell Nibu all" }, "a gap that is not an object"]));
|
||||
assert_eq!(gaps.len(), 2, "no gap is dropped: {gaps:?}");
|
||||
assert_eq!((gaps[0]["kind"].as_str(), gaps[0]["declared"].as_str(), gaps[0]["from"].as_str()), (Some("unresolved"), Some("regret"), Some("thought")), "{}", gaps[0]);
|
||||
assert_eq!((gaps[1]["kind"].as_str(), gaps[1]["declared"].as_str(), gaps[1]["from"].as_str()), (Some("unresolved"), Some("a gap that is not an object"), Some("unlocated")), "{}", gaps[1]);
|
||||
// A turn with no room still types its gaps.
|
||||
let mut roomless = packet();
|
||||
roomless.room = None;
|
||||
assert_eq!(gaps_of(&roomless, prose, json!([{ "kind": "elsewhere", "quote": "I could tell Nibu." }]))[0]["kind"], "elsewhere");
|
||||
assert_eq!(gaps_of(&roomless, prose, json!([{ "kind": "elsewhere", "quote": "I could tell Nibu all" }]))[0]["kind"], "elsewhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_interpreter_is_told_what_she_can_do_here_from_the_packets_affordances() {
|
||||
// Heimdall's packet: the turn line is in his pronouns.
|
||||
fn the_interpreter_is_told_what_he_can_do_here_from_the_packets_affordances() {
|
||||
let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default());
|
||||
assert!(prompt.contains("What she can do here:\nThis turn the room reaches him as typed lines, and he can answer in the turn's room by typing lines of his own; nothing he does here builds, changes or ships anything.\n\nThe room:"), "{prompt}");
|
||||
assert!(prompt.contains("missing_affordance when she reaches for something her body cannot do this turn"), "{prompt}");
|
||||
assert!(prompt.contains("What he can do here:\nThis turn the room reaches him as typed lines, and he can answer in the turn's room by typing lines of his own; nothing he does here builds, changes or ships anything.\n\nThe room:"), "{prompt}");
|
||||
assert!(prompt.contains("missing_affordance when his thought reaches for something his body cannot do this turn"), "{prompt}");
|
||||
let mut listening = packet();
|
||||
listening.affordances = vec![Affordance::Perceive];
|
||||
assert!(speech_prompt(&listening, "x", "y", &Tuning::default()).contains("What she can do here:\nThis turn the room reaches him as typed lines; nothing"), "derived from the affordances, not a constant");
|
||||
}
|
||||
|
||||
/// The speech prompt as K6 left it, before the guidance knob (map 16.12 K8). Every sentence of it is still in the default
|
||||
/// prompt. K8 moves the guidance's sentences into one paragraph after the decision, so the default is the same sentences,
|
||||
/// not the same bytes: one contiguous knob cannot sit where two of its sentences used to.
|
||||
const K6_SPEECH_PROMPT: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them.
|
||||
|
||||
Below are who she is, what she can do here, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech.
|
||||
|
||||
She speaks only in this room. What she knows privately is listed below as private: she 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 line fits who is listening is yours to judge.
|
||||
|
||||
Answer with one JSON object and nothing else:
|
||||
{\"say\": [{\"spans\": [\"<whole sentences of her prose, copied character for character>\"], \"mentions\": [\"<Matrix id of someone listed whom she addresses directly>\"], \"reply_to\": \"<Matrix id of the person whose message she answers, or null>\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere | missing_affordance\", \"quote\": \"<exact words of her prose>\", \"detail\": \"<why>\"}]}
|
||||
|
||||
A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time, missing_affordance when she reaches for something her body cannot do this turn (what she can do here is listed below). An empty say list is the usual answer in a busy room.";
|
||||
|
||||
#[test]
|
||||
fn the_default_speech_prompt_keeps_every_sentence_of_k6s_and_adds_attribution() {
|
||||
let prompt = speech_prompt(&packet(), "x", "y", &Tuning::default());
|
||||
for sentence in K6_SPEECH_PROMPT.unicode_sentences().map(str::trim).filter(|sentence| !sentence.is_empty()) {
|
||||
assert_eq!(prompt.matches(sentence).count(), 1, "{sentence:?} in\n{prompt}");
|
||||
}
|
||||
assert!(prompt.contains("That holds for a quotation that stands as sentences of its own too: its marks do not go out with her line, so another person's words cited from it would reach the room as her own assertion."), "{prompt}");
|
||||
assert!(prompt.starts_with("You decide what one person says aloud"), "the prefix the test doubles route on");
|
||||
assert!(speech_prompt(&listening, "x", "y", &Tuning::default()).contains("What he can do here:\nThis turn the room reaches him as typed lines; nothing"), "derived from the affordances, not a constant");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guidance_knob_changes_only_the_guidance_and_the_frame_still_binds() {
|
||||
let mut tuning = Tuning::default();
|
||||
tuning.interpreter.guidance = "GUIDANCE-SENTINEL: a drafted line to someone addressed counts as said.".into();
|
||||
tuning.interpreter.guidance = "GUIDANCE-SENTINEL: a draft to someone addressed counts as sent.".into();
|
||||
let prompt = speech_prompt(&packet(), "x", "y", &tuning);
|
||||
assert_eq!(prompt.matches("GUIDANCE-SENTINEL").count(), 1, "{prompt}");
|
||||
for gone in ["Wondering whether to speak", "An empty say list is the usual answer"] {
|
||||
assert!(!prompt.contains(gone), "{gone} is guidance, and the knob replaced it");
|
||||
}
|
||||
for rule in ["You never write her words: you cite them.", "never her speech", "her own assertion", "She speaks only in this room.", "in a direct message with exactly that person", "Answer with one JSON object and nothing else", "She never says half a sentence", "At most two lines.", "conditional | addressee | elsewhere | missing_affordance"] {
|
||||
for rule in ["You never write his words", "never his speech", "as his to pass on", "He speaks only in this room.", "in a direct message with exactly that person", "speech contract", "A draft is said whole or not at all", "At most two drafts a turn.", "missing_affordance when", "unwritten when"] {
|
||||
assert!(prompt.contains(rule), "{rule} is the frame's and no knob removes it");
|
||||
}
|
||||
tuning.interpreter.guidance = " ".into();
|
||||
let bare = speech_prompt(&packet(), "x", "y", &tuning);
|
||||
assert!(bare.contains("own assertion.\n\nShe speaks only in this room."), "an empty guidance leaves no hole: {bare}");
|
||||
assert!(bare.contains("to pass on.\n\nHe speaks only in this room."), "an empty guidance leaves no hole: {bare}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -437,9 +396,9 @@ fn an_unknown_interpreter_key_refuses_the_tuning_and_the_hash_follows_the_guidan
|
|||
let path = dir.path().join("persona-tuning.toml");
|
||||
std::fs::write(&path, "[interpreter]\nfame = \"loud\"\n").unwrap();
|
||||
assert!(format!("{:#}", crate::projection::tuning::load(&path).unwrap_err()).contains("unknown field"));
|
||||
std::fs::write(&path, "[interpreter]\nguidance = \"She says what she drafted to whoever addressed her.\"\n").unwrap();
|
||||
std::fs::write(&path, "[interpreter]\nguidance = \"She sends what she drafted to whoever addressed her.\"\n").unwrap();
|
||||
let loaded = crate::projection::tuning::load(&path).unwrap();
|
||||
assert_eq!(loaded.tuning.interpreter.guidance, "She says what she drafted to whoever addressed her.");
|
||||
assert_eq!(loaded.tuning.interpreter.guidance, "She sends what she drafted to whoever addressed her.");
|
||||
assert_ne!(loaded.sha256, Tuning::default().sha256(), "the tuning hash changes when the guidance does");
|
||||
let mut huge = Tuning::default();
|
||||
huge.interpreter.guidance = "g".repeat(40 * 1024);
|
||||
|
|
|
|||
|
|
@ -16,14 +16,16 @@ use model_connector::{ConnectorClient, InputItem, ProviderRequest, ReasoningEffo
|
|||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::select::{Packet, TurnKind};
|
||||
use super::interpret::{DRAFT_CLOSE, DRAFT_OPEN};
|
||||
use super::select::{Forms, Packet, TurnKind};
|
||||
use super::tuning::Tuning;
|
||||
|
||||
/// One tool-less model turn. `KitModel` is the one live owner; a test answers with recorded text.
|
||||
pub trait Model {
|
||||
/// One turn of `model`: `prompt` is its one user text and `request_id` its identity on the connector. A failed turn
|
||||
/// keeps whatever usage the connector reported for it.
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed>;
|
||||
/// One turn of `model`: `prompt` is its one user text and `request_id` its identity on the connector. With a
|
||||
/// `schema` (a JSON Schema object) it is a schema turn, and the answer is the structured-output object alone. A
|
||||
/// failed turn keeps whatever usage the connector reported for it.
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed>;
|
||||
}
|
||||
|
||||
/// A turn that produced no answer: why, and what it cost when the connector's receipt says (a refusal, a fault before
|
||||
|
|
@ -102,9 +104,12 @@ impl KitModel {
|
|||
}
|
||||
|
||||
impl Model for KitModel {
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
||||
let mut request = ProviderRequest::new(request_id, request_id, model, INSTRUCTIONS, MAX_OUTPUT_TOKENS);
|
||||
request.input = vec![InputItem::UserText { text: prompt.to_owned() }];
|
||||
// The claude connector passes it as `--json-schema` and returns the structured output alone; a schema turn
|
||||
// hands out no resume handle, which no stage here needs.
|
||||
request.output_schema_json = schema.map(str::to_owned);
|
||||
request.reasoning_effort = Some(ReasoningEffort::Low);
|
||||
let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS;
|
||||
let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(prompt.as_bytes()).into(), request).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?;
|
||||
|
|
@ -209,11 +214,25 @@ pub(crate) fn lived_stream(narration: &str, heard: &str) -> String {
|
|||
if heard.trim().is_empty() { narration.to_owned() } else { format!("{narration}\n\n{heard}") }
|
||||
}
|
||||
|
||||
/// The speech form (map 16.19.1): how she sets apart the words she would type, so that the speech boundary is hers, as
|
||||
/// author, and no code reads her punctuation for it. Code, not tuning: the form is an invariant, not an experiment knob.
|
||||
/// In her own pronouns (16.19.7).
|
||||
pub(crate) fn persona_speech_form(her: Forms) -> String {
|
||||
let Forms { subj, obj, poss, s, .. } = her;
|
||||
format!(
|
||||
"When {subj} write{s} words {subj} would type to someone (to the room, to one person, or as a note for Self), {subj} set{s} them between {DRAFT_OPEN} and {DRAFT_CLOSE}, exactly as they would be sent, and nothing else inside. Writing them is drafting: whether they go anywhere is decided after {obj}, from what {poss} thought makes plain. Everything outside those marks is {poss} thought and never leaves {obj}."
|
||||
)
|
||||
}
|
||||
|
||||
/// The Persona stage's prompt: Ghostlight's prose-only membrane over her name and her lived stream; her voice reaches her
|
||||
/// only as the Projector rendered it (map 16.4). No field name, number, schema or instruction of hers reaches it
|
||||
/// (invariant 7); the guidance is the tuning's setting line.
|
||||
/// (invariant 7). The domain guidance is code's speech form, then the tuning's setting line: Ghostlight's membrane is
|
||||
/// unchanged.
|
||||
pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String {
|
||||
build_persona_prompt(&PersonaPrompt { identity: &packet.name, lived_stream: &lived_stream(narration, &packet.heard), domain_guidance: tuning.persona.guidance.trim(), word_budget: tuning.persona.words })
|
||||
let guidance = tuning.persona.guidance.trim();
|
||||
let form = persona_speech_form(packet.forms);
|
||||
let domain_guidance = if guidance.is_empty() { form } else { format!("{form}\n\n{guidance}") };
|
||||
build_persona_prompt(&PersonaPrompt { identity: &packet.name, lived_stream: &lived_stream(narration, &packet.heard), domain_guidance: &domain_guidance, word_budget: tuning.persona.words })
|
||||
}
|
||||
|
||||
/// The share of the narration's word trigrams that also appear in what she heard: a lexical overlap, cheap and blind to
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn
|
||||
//! one `project` through the Persona stage, and each one's quoted lines join the room as from her Matrix id, so the
|
||||
//! one `project` through the Persona stage, and each one's drafts the Interpreter sends join the room as from her Matrix id, so the
|
||||
//! next one hears them.
|
||||
//!
|
||||
//! Who wakes is the heartbeat's: `heartbeat::wakes` under the plan's `WakePolicy`, over each persona's addressee as the
|
||||
|
|
|
|||
|
|
@ -61,14 +61,14 @@ fn is_tobiah(prompt: &str) -> bool {
|
|||
prompt.contains("Who you are:\nTobiah")
|
||||
}
|
||||
|
||||
/// Both speak every turn, neither naming the other: each line a standalone quotation, sayable.
|
||||
/// Both speak every turn, neither naming the other: each line a draft, sent.
|
||||
fn chatty() -> Scripted {
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"what a day\"".into() } else { "\"mm, the deploy went fine\"".into() })
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>what a day</typed>".into() } else { "<typed>mm, the deploy went fine</typed>".into() })
|
||||
}
|
||||
|
||||
/// Both speak every turn, each naming the other.
|
||||
fn namers() -> Scripted {
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"Libby, tea?\"".into() } else { "\"Tobiah, yes please.\"".into() })
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>Libby, tea?</typed>".into() } else { "<typed>Tobiah, yes please.</typed>".into() })
|
||||
}
|
||||
|
||||
fn silent() -> Scripted {
|
||||
|
|
@ -210,7 +210,7 @@ fn the_beat_wakes_one_persona_by_the_heartbeats_pick() {
|
|||
struct FailingPersona;
|
||||
|
||||
impl Model for FailingPersona {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
||||
if prompt.starts_with(PROJECTOR_FRAME) {
|
||||
Ok(Answer { text: "The room is slow.".into(), usage: None })
|
||||
} else {
|
||||
|
|
@ -244,11 +244,11 @@ fn a_seed_replays_its_order_and_another_seed_changes_it() {
|
|||
/// Tobiah says a line that names Libby and holds her id as text; the Interpreter gives it `mentions` or not.
|
||||
fn tagging(mention: bool) -> Scripted {
|
||||
let mentions = if mention { json!([LIBBY]) } else { json!([]) };
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"ask @libby:gamecult.org, and Libby too\"".into() } else { "She lets it be.".into() }).interpreting(move |prompt| {
|
||||
if !prompt.contains("Who she is:\nTobiah") {
|
||||
return json!({ "say": [] }).to_string();
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "<typed>ask @libby:gamecult.org, and Libby too</typed>".into() } else { "She lets it be.".into() }).interpreting(move |prompt| {
|
||||
if !prompt.contains("Who he is:\nTobiah") {
|
||||
return json!({ "say": [], "gaps": [] }).to_string();
|
||||
}
|
||||
json!({ "say": [{ "spans": ["ask @libby:gamecult.org, and Libby too"], "mentions": mentions, "reply_to": null }] }).to_string()
|
||||
json!({ "say": [{ "draft": 1, "mentions": mentions, "reply_to": null }], "gaps": [] }).to_string()
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -794,7 +794,7 @@ impl Recorded {
|
|||
}
|
||||
|
||||
impl Model for Recorded {
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
fn ask(&self, request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
||||
self.calls.borrow_mut().push((request_id.to_owned(), model.to_owned(), prompt.to_owned()));
|
||||
let text = if prompt.starts_with(PROJECTOR_FRAME) { (self.narration)(prompt) } else { (self.judge)(prompt) };
|
||||
let usage = Spent { model: model.to_owned(), input_tokens: prompt.len() as u64, output_tokens: text.len() as u64, cache_read_tokens: 7, cache_write_tokens: 3, reasoning_tokens: None };
|
||||
|
|
@ -1023,7 +1023,7 @@ fn a_kit_call_is_one_tool_less_turn_by_her_instance() {
|
|||
let backend = Scripted::ending(StopReason::EndTurn, &["I turn ", "it over."]);
|
||||
let (model, _root) = kit(Arc::clone(&backend), KIT_MODEL);
|
||||
let id = "mind-persona:eureka:project:a:1:1";
|
||||
let answer = model.ask(id, KIT_MODEL, "The projector prompt.").unwrap();
|
||||
let answer = model.ask(id, KIT_MODEL, "The projector prompt.", None).unwrap();
|
||||
assert_eq!(answer.text, "I turn it over.");
|
||||
assert_eq!(answer.usage, Some(Spent { model: KIT_MODEL.into(), input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }), "the receipt's usage, by the model that ran");
|
||||
let seen = backend.seen.lock().unwrap();
|
||||
|
|
@ -1033,17 +1033,21 @@ fn a_kit_call_is_one_tool_less_turn_by_her_instance() {
|
|||
assert_eq!(request.input, [InputItem::UserText { text: "The projector prompt.".into() }]);
|
||||
assert_eq!((request.instructions.as_str(), request.reasoning_effort, request.max_output_tokens), (INSTRUCTIONS, Some(ReasoningEffort::Low), MAX_OUTPUT_TOKENS));
|
||||
assert!(request.tools.is_empty() && request.output_schema_json.is_none());
|
||||
drop(seen);
|
||||
// The speech call is a schema turn: the contract goes out as the request's output schema (`--json-schema`).
|
||||
model.ask("mind-persona:eureka:project:interpreter:1:2", KIT_MODEL, "The speech prompt.", Some(interpret::SPEECH_SCHEMA)).unwrap();
|
||||
assert_eq!(backend.seen.lock().unwrap()[1].1.output_schema_json.as_deref(), Some(interpret::SPEECH_SCHEMA));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kit_refusal_or_a_cut_short_turn_is_a_fault() {
|
||||
let backend = Scripted::ending(StopReason::EndTurn, &["Never said."]);
|
||||
let (model, _root) = kit(Arc::clone(&backend), "some-other-model");
|
||||
assert!(format!("{:#}", model.ask("id-1", KIT_MODEL, "p").unwrap_err()).contains("ModelNotAllowed"));
|
||||
assert!(format!("{:#}", model.ask("id-1", KIT_MODEL, "p", None).unwrap_err()).contains("ModelNotAllowed"));
|
||||
assert!(backend.seen.lock().unwrap().is_empty(), "the provider was never reached");
|
||||
for stop in [StopReason::MaxOutputTokens, StopReason::Refusal] {
|
||||
let (model, _root) = kit(Scripted::ending(stop, &["Half a thou"]), KIT_MODEL);
|
||||
let fault = format!("{:#}", model.ask("id-2", KIT_MODEL, "p").unwrap_err());
|
||||
let fault = format!("{:#}", model.ask("id-2", KIT_MODEL, "p", None).unwrap_err());
|
||||
assert!(fault.contains("ended early") && !fault.contains("Half a thou"), "{stop:?}: {fault}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1399,7 +1403,7 @@ fn bodies_and_display_names_escape_reversibly() {
|
|||
fn a_failed_call_keeps_the_report_and_its_usage() {
|
||||
struct Flaky(Cell<u32>);
|
||||
impl Model for Flaky {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result<Answer, Failed> {
|
||||
self.0.set(self.0.get() + 1);
|
||||
let usage = Some(Spent { model: model.into(), input_tokens: 100, output_tokens: 20, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None });
|
||||
match self.0.get() {
|
||||
|
|
@ -1432,10 +1436,10 @@ fn a_failed_call_keeps_the_report_and_its_usage() {
|
|||
#[test]
|
||||
fn a_kit_failure_reports_the_usage_the_receipt_carries() {
|
||||
let (model, _root) = kit(Scripted::ending(StopReason::MaxOutputTokens, &["Half a thou"]), KIT_MODEL);
|
||||
let failed = model.ask("id-9", KIT_MODEL, "p").unwrap_err();
|
||||
let failed = model.ask("id-9", KIT_MODEL, "p", None).unwrap_err();
|
||||
assert!(failed.reason.contains("ended early") && failed.usage.as_ref().is_some_and(|usage| usage.model == KIT_MODEL && usage.input_tokens == 1), "{failed:?}");
|
||||
let (refusing, _root) = kit(Scripted::ending(StopReason::EndTurn, &["x"]), "some-other-model");
|
||||
assert_eq!(refusing.ask("id-10", KIT_MODEL, "p").unwrap_err().usage, None, "a refusal before the provider costs nothing");
|
||||
assert_eq!(refusing.ask("id-10", KIT_MODEL, "p", None).unwrap_err().usage, None, "a refusal before the provider costs nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1607,7 +1611,11 @@ fn the_projector_is_told_not_to_retell_not_to_offer_options_and_not_to_owe() {
|
|||
}
|
||||
let persona = narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default());
|
||||
assert!(persona.contains("Continue her inner stream") && persona.contains("This is not a message to the room") && persona.contains("most moments pass with nothing said"), "{persona}");
|
||||
assert!(!persona.contains("quotation marks") && !persona.contains("@"), "no speech convention: the Interpreter decides what is said");
|
||||
// The speech form is code's, at the head of the domain guidance, before the tuning's setting line (map 16.19.1).
|
||||
let form = narrate::persona_speech_form(packet.forms);
|
||||
assert!(persona.contains(&format!("Voice and setting guidance:\n{form}\n\nContinue her inner stream")), "{persona}");
|
||||
assert!(form.contains("between <typed> and </typed>") && form.contains("never leaves her"), "{form}");
|
||||
assert!(!persona.contains("quotation marks") && !persona.contains("@"), "no other speech convention: the Interpreter decides what is sent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -19,9 +19,10 @@ use sha2::{Digest, Sha256};
|
|||
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
|
||||
pub const TUNING_FILE: &str = "persona-tuning.toml";
|
||||
|
||||
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior, with speech only
|
||||
/// where her thought moves her to it, quoted (map section 5.5, invariant 5). It is not a reply to the room.
|
||||
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person, in her own words. This is not a message to the room. When she means to say something aloud, she writes the very words she would type, in her own voice and addressed as she would address them, never a description of what she will say. Whether she says them now is decided after her. In a busy room most moments pass with nothing said.";
|
||||
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior. It is not a reply
|
||||
/// to the room. How she sets down words she would type is code's form, not this (`narrate::persona_speech_form`, map
|
||||
/// 16.19.1).
|
||||
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person, in her own words. This is not a message to the room. In a busy room most moments pass with nothing said.";
|
||||
|
||||
/// The setting the Projector renders for. No task: in the Persona-only shape nothing is work she owes.
|
||||
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants. What was said reaches her word for word after this stream, so never retell or summarise it: render what it stirs in her and what she makes of the people who said it. Render the conversation as it stands. Leave out whatever the context does not carry: an absence is not part of her moment. Use each person's pronouns as given.";
|
||||
|
|
@ -184,11 +185,11 @@ impl Default for ProjectorTuning {
|
|||
}
|
||||
}
|
||||
|
||||
/// What counts as her choosing to say it now (map 16.7): the experiment's lever over when a drafted line is said.
|
||||
const INTERPRETER_GUIDANCE: &str = "A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. An empty say list is the usual answer in a busy room.";
|
||||
/// What counts as her choosing to send a draft now (map 16.7): the experiment's lever over when a draft is said.
|
||||
const INTERPRETER_GUIDANCE: &str = "A draft is speech only when her prose shows her choosing to send it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. An empty say list is the usual answer in a busy room.";
|
||||
|
||||
/// The Interpreter's speech call: its model and its guidance. The speech frame is code (`interpret`): the room and private
|
||||
/// rules, attribution, citing and never writing her words, the contract and the gap kinds are not knobs.
|
||||
/// rules, attribution, choosing among her drafts and never writing her words, the contract and the gap kinds are not knobs.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct InterpreterTuning {
|
||||
|
|
|
|||
|
|
@ -265,6 +265,7 @@ 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 Drafts
|
||||
mind_body::projection::interpret: impl GapKind
|
||||
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
|
||||
mind_body::projection::narrate: impl Failed
|
||||
|
|
@ -272,7 +273,7 @@ mind_body::projection::narrate: impl KitModel
|
|||
mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self >
|
||||
mind_body::projection::narrate: impl Model for KitModel
|
||||
mind_body::projection::narrate: impl std :: fmt :: Display for Failed
|
||||
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str) -> std :: result :: Result < Answer , Failed > ; }
|
||||
mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str , schema : Option < & str >) -> std :: result :: Result < Answer , Failed > ; }
|
||||
mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >]
|
||||
mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, usage: Option < Spent >]
|
||||
mind_body::projection::narrate: struct KitModel pub-fields[]
|
||||
|
|
|
|||
Loading…
Reference in a new issue