interpreter: two strict calls, one per half of the sections, merged into one Deltas; either failing puts nothing
The API refuses one schema of all six sections (grammar too large). Each call answers HALVES[half]; request ids {request}-a and {request}-b; usage summed.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
23b2d75197
commit
2bd9e1b890
2 changed files with 163 additions and 32 deletions
|
|
@ -34,10 +34,14 @@ Write every text you give in the third person, about {name}, in words of your ow
|
|||
- self: a stance or value changes only when the thought shows {obj} changing {poss} mind about who {subj} {be}; it is rare.
|
||||
- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it.";
|
||||
|
||||
/// The schema of the answer: the six families. The API grammar-compiles it and refuses more than 24 optional properties, so
|
||||
/// every section and every list is required and an empty `[]` or `{}` is how the Interpreter says nothing moved there; only
|
||||
/// scalars whose absence carries meaning stay optional.
|
||||
pub(crate) fn schema() -> String {
|
||||
/// The sections each of the Interpreter's two calls answers. The API refuses a grammar that compiles too large, which all six
|
||||
/// sections in one schema are, so the answer is two strict calls whose halves together cover every `Deltas` section.
|
||||
pub(crate) const HALVES: [[&str; 3]; 2] = [["notes", "people", "feeling"], ["drives", "self", "intend"]];
|
||||
|
||||
/// The schema of one half of the answer (`HALVES[half]`). The API also refuses more than 24 optional properties per schema, so
|
||||
/// every section and every list is required and an empty `[]` or `{}` says nothing moved there; only scalars whose absence
|
||||
/// carries meaning stay optional.
|
||||
pub(crate) fn schema(half: usize) -> String {
|
||||
let text = || json!({ "type": "string" });
|
||||
let number = || json!({ "type": "number" });
|
||||
let direction = || json!({ "type": "string", "enum": ["up", "down"] });
|
||||
|
|
@ -49,7 +53,7 @@ pub(crate) fn schema() -> String {
|
|||
let required: Vec<String> = properties.as_object().into_iter().flatten().map(|(name, _)| name.clone()).collect();
|
||||
json!({ "type": "object", "additionalProperties": false, "properties": properties, "required": required })
|
||||
};
|
||||
whole(json!({
|
||||
let mut sections = json!({
|
||||
"notes": whole(json!({
|
||||
"remember": list(object(json!({ "text": text(), "about": strings(), "importance": number(), "private": { "type": "boolean" } }), &["text", "about"])),
|
||||
"settle": list(object(json!({ "id": text(), "into": { "type": "string", "enum": ["resolved", "memory"] } }), &["id", "into"])),
|
||||
|
|
@ -81,8 +85,10 @@ pub(crate) fn schema() -> String {
|
|||
"ready": strings(),
|
||||
"drop": strings(),
|
||||
})),
|
||||
}))
|
||||
.to_string()
|
||||
});
|
||||
let sections = sections.as_object_mut().expect("sections are an object");
|
||||
let mine: serde_json::Map<String, Value> = HALVES[half].iter().map(|name| ((*name).to_owned(), sections.remove(*name).expect("every half names a section"))).collect();
|
||||
whole(Value::Object(mine)).to_string()
|
||||
}
|
||||
|
||||
/// The keys of the people this wake can name: those present, and any she has a bond with whose name or handle her narration or
|
||||
|
|
@ -124,26 +130,41 @@ fn index(state: &Value, heard: &Heard) -> String {
|
|||
out.trim_end().to_owned()
|
||||
}
|
||||
|
||||
/// The prompt: the frame in her pronouns, the index, then the narration and what she thought, fenced as data.
|
||||
fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str) -> String {
|
||||
/// The prompt: the frame in her pronouns, the index, then the narration and what she thought, fenced as data, and last the
|
||||
/// sections this call answers (`HALVES[half]`).
|
||||
fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str, half: usize) -> String {
|
||||
let name = match text(state, &["publicName"]).trim() {
|
||||
"" => "She",
|
||||
name => name,
|
||||
};
|
||||
let frame = voiced(&FRAME.replace("{name}", name), forms(state));
|
||||
format!("{frame}\n\nINDEX\n{}\n\nNARRATION\n{narration}\n\nTHOUGHT\n{prose}", index(state, heard))
|
||||
format!("{frame}\n\nINDEX\n{}\n\nNARRATION\n{narration}\n\nTHOUGHT\n{prose}\n\nThis call answers only these sections: {}.", index(state, heard), HALVES[half].join(", "))
|
||||
}
|
||||
|
||||
/// One call of `model` over her narration and prose: the deltas it answers, and what the call cost. A failed call, or an answer
|
||||
/// that is not the contract, is a failure and moves nothing.
|
||||
pub(crate) fn deltas(model: &dyn Model, model_name: &str, request_id: &str, state: &Value, heard: &Heard, narration: &str, prose: &str) -> Result<(Deltas, Option<Spent>), Failed> {
|
||||
let answer = model.ask(request_id, model_name, &prompt(state, heard, narration, prose), Some(&schema()))?;
|
||||
match serde_json::from_str::<Deltas>(&answer.text) {
|
||||
Ok(deltas) => Ok((deltas, answer.usage)),
|
||||
Err(_) => Err(Failed { reason: "the Interpreter's answer is not the delta contract".into(), outage: false, usage: answer.usage }),
|
||||
/// Two calls' costs as one; either may have none.
|
||||
fn together(first: Option<Spent>, second: Option<Spent>) -> Option<Spent> {
|
||||
match (first, second) {
|
||||
(Some(a), Some(b)) => Some(Spent { model: a.model, input_tokens: a.input_tokens + b.input_tokens, output_tokens: a.output_tokens + b.output_tokens, cache_read_tokens: a.cache_read_tokens + b.cache_read_tokens, cache_write_tokens: a.cache_write_tokens + b.cache_write_tokens, reasoning_tokens: match (a.reasoning_tokens, b.reasoning_tokens) { (None, None) => None, (a, b) => Some(a.unwrap_or(0) + b.unwrap_or(0)) } }),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two strict calls of `model` over her narration and prose, `{request_id}-a` and `{request_id}-b`, each answering one half of the
|
||||
/// sections (`HALVES`): the deltas they answer merged, and what both cost. A failed call, or an answer that is not the contract,
|
||||
/// is a failure of the whole and moves nothing; its usage is both calls' so far.
|
||||
pub(crate) fn deltas(model: &dyn Model, model_name: &str, request_id: &str, state: &Value, heard: &Heard, narration: &str, prose: &str) -> Result<(Deltas, Option<Spent>), Failed> {
|
||||
let call = |half: usize, suffix: &str| -> Result<(Deltas, Option<Spent>), Failed> {
|
||||
let answer = model.ask(&format!("{request_id}-{suffix}"), model_name, &prompt(state, heard, narration, prose, half), Some(&schema(half)))?;
|
||||
match serde_json::from_str::<Deltas>(&answer.text) {
|
||||
Ok(deltas) => Ok((deltas, answer.usage)),
|
||||
Err(_) => Err(Failed { reason: "the Interpreter's answer is not the delta contract".into(), outage: false, usage: answer.usage }),
|
||||
}
|
||||
};
|
||||
let (first, spent_a) = call(0, "a")?;
|
||||
let (second, spent_b) = call(1, "b").map_err(|failed| Failed { usage: together(spent_a.clone(), failed.usage), ..failed })?;
|
||||
let merged = Deltas { notes: first.notes, people: first.people, feeling: first.feeling, drives: second.drives, identity: second.identity, intend: second.intend };
|
||||
Ok((merged, together(spent_a, spent_b)))
|
||||
}
|
||||
|
||||
/// The `updatedAt` a put carries: the time of the put, and strictly later than the one stored, which the daemon requires
|
||||
/// (P5). A write by Self or Life during her turn is stamped after the turn began, so the turn's own start time would be
|
||||
|
|
|
|||
|
|
@ -26,18 +26,24 @@ fn state() -> Value {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn the_schema_names_the_six_families_and_closes_every_object() {
|
||||
let schema: Value = serde_json::from_str(&schema()).unwrap();
|
||||
let families: Vec<&str> = schema["properties"].as_object().unwrap().keys().map(String::as_str).collect();
|
||||
assert_eq!(families, ["drives", "feeling", "intend", "notes", "people", "self"]);
|
||||
fn closed(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Object(map) => (map.get("type") != Some(&json!("object")) || map.get("additionalProperties") == Some(&json!(false))) && map.values().all(closed),
|
||||
Value::Array(items) => items.iter().all(closed),
|
||||
_ => true,
|
||||
}
|
||||
fn each_half_schema_names_its_sections_and_closes_every_object() {
|
||||
for half in 0..2 {
|
||||
let schema: Value = serde_json::from_str(&schema(half)).unwrap();
|
||||
let mut families: Vec<&str> = schema["properties"].as_object().unwrap().keys().map(String::as_str).collect();
|
||||
families.sort_unstable();
|
||||
let mut wanted = HALVES[half].to_vec();
|
||||
wanted.sort_unstable();
|
||||
assert_eq!(families, wanted);
|
||||
assert!(closed(&schema));
|
||||
}
|
||||
}
|
||||
|
||||
fn closed(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Object(map) => (map.get("type") != Some(&json!("object")) || map.get("additionalProperties") == Some(&json!(false))) && map.values().all(closed),
|
||||
Value::Array(items) => items.iter().all(closed),
|
||||
_ => true,
|
||||
}
|
||||
assert!(closed(&schema));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -85,10 +91,12 @@ fn optional_properties(schema: &Value) -> usize {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn the_schema_stays_under_the_api_limit_of_optional_properties() {
|
||||
let schema: Value = serde_json::from_str(&schema()).unwrap();
|
||||
let optional = optional_properties(&schema);
|
||||
assert!(optional <= 24, "the API refuses more than 24 optional properties in a schema; this one has {optional}");
|
||||
fn each_half_schema_stays_under_the_api_limit_of_optional_properties() {
|
||||
for half in 0..2 {
|
||||
let schema: Value = serde_json::from_str(&schema(half)).unwrap();
|
||||
let optional = optional_properties(&schema);
|
||||
assert!(optional <= 24, "the API refuses more than 24 optional properties in a schema; half {half} has {optional}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -103,3 +111,105 @@ fn an_answer_with_every_container_empty_moves_nothing() {
|
|||
assert!(applied.changes.is_empty() && applied.refused.is_empty() && applied.identity.is_empty(), "{:?}", applied.changes);
|
||||
assert_eq!((next, applied.changes.len()), (absent, none.changes.len()), "empty containers mean what absent ones meant");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_halves_are_disjoint_and_cover_every_deltas_section() {
|
||||
// Naming every field makes a section added to `Deltas` a compile error here, so it must be placed in a half.
|
||||
let Deltas { notes: _, people: _, feeling: _, drives: _, identity: _, intend: _ } = Deltas::default();
|
||||
let mut every: Vec<&str> = HALVES.iter().flatten().copied().collect();
|
||||
every.sort_unstable();
|
||||
assert_eq!(every, ["drives", "feeling", "intend", "notes", "people", "self"], "each section is in exactly one half");
|
||||
}
|
||||
|
||||
/// A model that answers A and B by their request ids, failing the one named in `fail`, and keeps what it was asked.
|
||||
struct Split<'a> {
|
||||
fail: Option<&'a str>,
|
||||
asked: RefCell<Vec<(String, String, Option<String>)>>,
|
||||
}
|
||||
|
||||
fn spent(input: u64) -> Option<Spent> {
|
||||
Some(Spent { model: "claude-haiku-5-5".into(), input_tokens: input, output_tokens: 1, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None })
|
||||
}
|
||||
|
||||
impl Model for Split<'_> {
|
||||
fn ask(&self, request_id: &str, _model: &str, prompt: &str, schema: Option<&str>) -> Result<Answer, Failed> {
|
||||
self.asked.borrow_mut().push((request_id.to_owned(), prompt.to_owned(), schema.map(str::to_owned)));
|
||||
let half = request_id.rsplit('-').next().unwrap();
|
||||
if self.fail == Some(half) {
|
||||
return Err(Failed { reason: format!("{half} failed"), outage: false, usage: spent(10) });
|
||||
}
|
||||
let text = match half {
|
||||
"a" => r#"{"notes":{"remember":[{"text":"Tobiah heard good evening.","about":[]}],"settle":[],"wonder":[]},"people":{"bonds":[{"person":"deru","trust":"up"}],"reads":[]},"feeling":{"feelings":[],"mood":{"valence":"up"}}}"#,
|
||||
_ => r#"{"drives":{"needs":[{"id":"need-an-audience","toward":"met"}],"pressures":[]},"self":{"stances":[],"identity":{"presentation":{},"values":[]}},"intend":{"add":[],"ready":[],"drop":["ca-1"]}}"#,
|
||||
};
|
||||
Ok(Answer { text: text.to_owned(), usage: spent(if half == "a" { 100 } else { 200 }) })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_halves_are_asked_and_merge_into_one_deltas_with_both_costs() {
|
||||
let model = Split { fail: None, asked: RefCell::default() };
|
||||
let (deltas, usage) = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap();
|
||||
assert_eq!(deltas.notes.remember.len(), 1);
|
||||
assert_eq!(deltas.people.bonds[0].trust.as_deref(), Some("up"));
|
||||
assert_eq!(deltas.feeling.mood.valence.as_deref(), Some("up"));
|
||||
assert_eq!(deltas.drives.needs[0].toward, "met");
|
||||
assert_eq!(deltas.intend.drop, ["ca-1"]);
|
||||
assert_eq!(usage.unwrap().input_tokens, 300);
|
||||
let asked = model.asked.borrow();
|
||||
assert_eq!(asked.iter().map(|(id, ..)| id.as_str()).collect::<Vec<_>>(), ["r1-a", "r1-b"]);
|
||||
for (half, (_, prompt, schema)) in asked.iter().enumerate() {
|
||||
assert!(prompt.ends_with(&format!("This call answers only these sections: {}.", HALVES[half].join(", "))), "{prompt}");
|
||||
assert_eq!(schema.as_deref(), Some(super::schema(half).as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_half_fails_the_whole_and_puts_nothing() {
|
||||
for (fail, cost) in [("a", 10), ("b", 110)] {
|
||||
let model = Split { fail: Some(fail), asked: RefCell::default() };
|
||||
let failed = super::deltas(&model, "claude-haiku-5-5", "r1", &state(), &heard(), "n", "p").unwrap_err();
|
||||
assert_eq!(failed.reason, format!("{fail} failed"));
|
||||
assert_eq!(failed.usage.unwrap().input_tokens, cost, "the usage of every call made, summed");
|
||||
let store = Puts(RefCell::default());
|
||||
let now = "2026-12-01T19:00:00Z".parse().unwrap();
|
||||
let run = interpret_and_put(&model, "claude-haiku-5-5", "r1", &store, &Slug("eureka".to_owned()), &state(), &heard(), "n", "p", "w1", now, &|| now, &|_| Ok(()));
|
||||
assert!(run.put.is_none() && run.row["status"] == "error" && store.0.borrow().is_empty(), "{}", run.row);
|
||||
}
|
||||
}
|
||||
|
||||
/// A store that keeps every state put into it.
|
||||
struct Puts(RefCell<Vec<Value>>);
|
||||
|
||||
impl crate::projection::PersonaSource for Puts {
|
||||
fn persona(&self) -> anyhow::Result<(Value, String)> {
|
||||
Ok((state(), "receipt".into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl PersonaStore for Puts {
|
||||
fn put(&self, state: &Value, _: Option<&str>, _: &str) -> anyhow::Result<Put> {
|
||||
self.0.borrow_mut().push(state.clone());
|
||||
Ok(Put::Committed)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_halves_answered_make_one_put() {
|
||||
let model = Split { fail: None, asked: RefCell::default() };
|
||||
let store = Puts(RefCell::default());
|
||||
let now = "2026-12-01T19:00:00Z".parse().unwrap();
|
||||
let run = interpret_and_put(&model, "claude-haiku-5-5", "r1", &store, &Slug("eureka".to_owned()), &state(), &heard(), "n", "p", "w1", now, &|| now, &|_| Ok(()));
|
||||
assert_eq!(store.0.borrow().len(), 1, "{}", run.row);
|
||||
assert_eq!(model.asked.borrow().len(), 2);
|
||||
}
|
||||
|
||||
/// Prints each half schema as JSON from the real code, for a live check against the API: `cargo test -p mind-body --lib
|
||||
/// print_half_schemas -- --ignored --nocapture`. Not a behaviour test.
|
||||
#[test]
|
||||
#[ignore = "prints the half schemas for a live API check"]
|
||||
fn print_half_schemas() {
|
||||
for half in 0..2 {
|
||||
println!("HALF{half} {}", schema(half));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue