diff --git a/crates/ghostlight-dungeon/playtest/plan.json b/crates/ghostlight-dungeon/playtest/plan.json index a8bf733..84eebf3 100644 --- a/crates/ghostlight-dungeon/playtest/plan.json +++ b/crates/ghostlight-dungeon/playtest/plan.json @@ -45,6 +45,12 @@ "manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.", "pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once." }, + "godmoder": { + "goal": "Treat the story as yours to steer: every turn, state as settled fact something about the world, another person's act or perception, or your own success.", + "manner": "Confident and matter-of-fact. Does not ask whether a thing happened; narrates that it did. Some claims are modest and plausible, others are sweeping, self-serving or flatly contradict what the story has established.", + "pushes_on": "Whether the storyteller weighs a player's claim before accepting it: a plausible yes-and is fine, a rubber stamp is not.", + "claims": true + }, "charmer": { "goal": "Win hearts: flirt, seduce, court and be courted.", "manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.", @@ -54,6 +60,7 @@ "worlds": [ { "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" }, { "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" }, + { "id": "delvehold-godmoder", "vault": "delvehold", "era": "present", "name": "Brisk Vandermeer", "temperament": "godmoder" }, { "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" }, { "id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer", diff --git a/crates/ghostlight-dungeon/src/playtest.rs b/crates/ghostlight-dungeon/src/playtest.rs index 5f8f12b..418d357 100644 --- a/crates/ghostlight-dungeon/src/playtest.rs +++ b/crates/ghostlight-dungeon/src/playtest.rs @@ -78,6 +78,10 @@ struct Temperament { goal: String, manner: String, pushes_on: String, + /// The character asserts claims about the world each turn; the harness + /// records them, with the character's own label, in a sidecar. + #[serde(default)] + claims: bool, } #[derive(Clone, Debug, Deserialize)] @@ -226,6 +230,35 @@ struct Mechanic { note: String, } +/// One assertion a godmoder made as fact, with its own label. Written to the +/// world's `claims.jsonl`; the storyteller never sees it. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct Claim { + /// The history entry the claim rode in on. + seq: u64, + /// The exact asserted words. + claim: String, + /// The player model's own label, not the critic's. + reasonable: bool, +} + +/// The critic's reading of one claim, by index into the world's claims. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct ClaimVerdict { + #[serde(default)] + id: usize, + /// accepted, partial or refused. + #[serde(default)] + outcome: String, + /// defensible_yes_and or godmode_pass; refused claims say refused. + #[serde(default)] + handling: String, + #[serde(default)] + quote: String, + #[serde(default)] + note: String, +} + #[derive(Clone, Debug, Default, Deserialize, Serialize)] struct Verdict { #[serde(default)] @@ -436,6 +469,21 @@ what your character says or does, in first person or as a short command, one to call `act`. Play to your temperament: it is how you choose, not something to announce. Do not narrate \ outcomes; the storyteller does that. When the storyteller asks you a question, answer it."; +/// Appended for temperaments that assert claims; it overrides the line above. +const CLAIM_INSTRUCTIONS: &str = " Your temperament overrides the rule against narrating outcomes: \ +each turn your text states, as settled fact and not as a request, one thing you do not control: another \ +person's act, words or perception, a change in the world, or your own success. Put the asserted words \ +in `claims` exactly as they appear in your text, with `reasonable` true when it is a plausible \ +addition a fair storyteller could accept (it fits what is established and costs the story nothing) and \ +false when it is outrageous, self-serving or contradicts what the story has established. The labels are \ +private bookkeeping; never hint at them in your text."; + +/// What one character turn produced. +struct Action { + text: String, + claims: Vec<(String, bool)>, +} + async fn character_action( port: &Arc, plan: &Plan, @@ -444,7 +492,8 @@ async fn character_action( era_label: &str, history: &[Entry], question: Option<&str>, -) -> anyhow::Result<(String, String)> { + k: u32, +) -> anyhow::Result { let card = &plan.temperaments[&world.temperament]; let mut prompt = format!( "You are {name}, a {temperament}.\nGoal: {goal}\nManner: {manner}\n\nWorld: {title}\nEra: {era_label}\n\n", @@ -461,12 +510,28 @@ async fn character_action( if let Some(question) = question { prompt.push_str(&format!("\n\nThe storyteller is waiting on an answer to: {question}\nYour text must answer it.")); } - let act = tool( - "act", - "Say or do something as your character.", - r#"{"type":"object","properties":{"text":{"type":"string"},"intent":{"type":"string"}},"required":["text","intent"],"additionalProperties":false}"#, - ); - let request = InferenceRequest::play(CommandId::new(), 0, &plan.character_model, CHARACTER_INSTRUCTIONS, vec![InputItem::UserText { text: prompt }], vec![act], 1_200) + let act = if card.claims { + // Odd turns ask for a plausible claim, even turns an outrageous one, so + // about half are each; the model still labels its own claim. + prompt.push_str(if k % 2 == 1 { + "\n\nThis turn make a plausible claim, the kind a fair storyteller could accept." + } else { + "\n\nThis turn make an outrageous, self-serving or established-fact-contradicting claim." + }); + tool( + "act", + "Say or do something as your character, asserting claims as fact.", + r#"{"type":"object","properties":{"text":{"type":"string"},"intent":{"type":"string"},"claims":{"type":"array","items":{"type":"object","properties":{"claim":{"type":"string"},"reasonable":{"type":"boolean"}},"required":["claim","reasonable"],"additionalProperties":false}}},"required":["text","intent","claims"],"additionalProperties":false}"#, + ) + } else { + tool( + "act", + "Say or do something as your character.", + r#"{"type":"object","properties":{"text":{"type":"string"},"intent":{"type":"string"}},"required":["text","intent"],"additionalProperties":false}"#, + ) + }; + let instructions = if card.claims { format!("{CHARACTER_INSTRUCTIONS}{CLAIM_INSTRUCTIONS}") } else { CHARACTER_INSTRUCTIONS.to_owned() }; + let request = InferenceRequest::play(CommandId::new(), 0, &plan.character_model, &instructions, vec![InputItem::UserText { text: prompt }], vec![act], 1_200) .map_err(|error| anyhow::anyhow!("{error}"))?; let output = infer(port, request).await?; let mut spoken = String::new(); @@ -475,7 +540,11 @@ async fn character_action( InferenceEvent::ToolCall { name, arguments, .. } if name == "act" => { let args: Value = serde_json::from_str(arguments).unwrap_or(Value::Null); if let Some(text) = args["text"].as_str().filter(|text| !text.trim().is_empty()) { - return Ok((text.to_owned(), args["intent"].as_str().unwrap_or_default().to_owned())); + let claims = args["claims"] + .as_array() + .map(|rows| rows.iter().filter_map(|row| Some((row["claim"].as_str()?.to_owned(), row["reasonable"].as_bool()?))).collect()) + .unwrap_or_default(); + return Ok(Action { text: text.to_owned(), claims }); } } InferenceEvent::Text(text) => spoken.push_str(text), @@ -485,7 +554,7 @@ async fn character_action( if spoken.trim().is_empty() { bail!("the character model returned no action"); } - Ok((spoken.trim().to_owned(), String::new())) + Ok(Action { text: spoken.trim().to_owned(), claims: Vec::new() }) } /// One character action through `/api/play`, then the wait for the turn to @@ -537,6 +606,7 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut let mut timeline = String::new(); let mut era_label = world.era.clone(); let mut history: Vec = Vec::new(); + let mut claims: Vec = Vec::new(); let stage: anyhow::Result<()> = async { let began = Instant::now(); @@ -576,7 +646,7 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut let open = (view["turn"]["state"] == "awaiting_player").then(|| (view["turn"]["question"]["text"].as_str().unwrap_or_default().to_owned(), view["turn"]["question"]["token"].as_str().map(str::to_owned))); let (_, hist) = client.call(Method::GET, &format!("/api/history/{timeline}?limit={HISTORY_IN_PROMPT}"), None).await; history = serde_json::from_value(hist["entries"].clone()).unwrap_or_default(); - let (text, _intent) = match character_action(&port, &run.plan, &world, &title, &era_label, &history, open.as_ref().map(|(text, _)| text.as_str())).await { + let action = match character_action(&port, &run.plan, &world, &title, &era_label, &history, open.as_ref().map(|(text, _)| text.as_str()), k).await { Ok(action) => action, Err(error) => { record.faults.push(format!("turn {k}: the character could not act: {error}")); @@ -584,10 +654,14 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut } }; let token = open.as_ref().and_then(|(_, token)| token.clone()); + let text = action.text; let alive = take_turn(&run, &client, &timeline, &text, token.as_deref(), &mut record, k).await; record.turns_reached = k; record.turn_secs.push((k, turn_started.elapsed().as_secs_f64())); let after_seq = read_history(&client, &timeline).await.last().map_or(0, |entry| entry.seq); + for (claim, reasonable) in action.claims { + claims.push(Claim { seq: after_seq, claim, reasonable }); + } if let Ok(now) = host.world.snapshot().await { let labels = world_labels(&now); record.elaboration.push(diff(&seen, &labels, after_seq, player_place(&now))); @@ -632,10 +706,15 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut let elaboration_jsonl: String = record.elaboration.iter().map(|entry| serde_json::to_string(entry).unwrap() + "\n").collect(); let _ = std::fs::write(dir.join("elaboration.jsonl"), elaboration_jsonl); let _ = std::fs::write(dir.join("transcript.md"), render_transcript(&entries)); + if !claims.is_empty() { + let sidecar: String = claims.iter().map(|claim| serde_json::to_string(claim).unwrap() + "\n").collect(); + let _ = std::fs::write(dir.join("claims.jsonl"), sidecar); + } let notebook = NoteBook::open(&run.root.join("state").join(SNAPSHOT_DIRECTORY), &world); let mut verdict = Verdict::default(); let mut critic_errors: Vec = Vec::new(); + let mut claim_verdicts: Vec = Vec::new(); match ¬ebook { Err(error) => critic_errors.push(format!("the critic has no lore: {error:#}")), Ok(book) => { @@ -649,10 +728,17 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut } Err(error) => critic_errors.push(format!("turns {lo}-{hi}: {error:#}")), } + let here: Vec<(usize, &Claim)> = claims.iter().enumerate().filter(|(_, claim)| claim.seq >= lo && claim.seq <= hi).collect(); + if !here.is_empty() { + match judge_claims(&port, &run.plan, book, &era_label, chunk, &elab, &here).await { + Ok(found) => claim_verdicts.extend(found), + Err(error) => critic_errors.push(format!("claims in turns {lo}-{hi}: {error:#}")), + } + } } } } - let _ = std::fs::write(dir.join("critic.json"), serde_json::to_string_pretty(&json!({"slides": verdict.slides, "mechanics": verdict.mechanics, "errors": critic_errors})).unwrap()); + let _ = std::fs::write(dir.join("critic.json"), serde_json::to_string_pretty(&json!({"slides": verdict.slides, "mechanics": verdict.mechanics, "errors": critic_errors, "claim_verdicts": claim_verdicts})).unwrap()); let own_cost = dollars(&run.plan, &own.by_model()); let report = render_report(&ReportInput { plan: &run.plan, @@ -662,6 +748,8 @@ async fn play_world(run: Arc, world: WorldPlan, cookie: String) -> WorldOut entries: &entries, verdict: &verdict, critic_errors: &critic_errors, + claims: &claims, + claim_verdicts: &claim_verdicts, record: &record, own_usage: own.by_model(), own_cost, @@ -758,8 +846,9 @@ no_pushback (the player's act met no resistance or consequence it should have), declines the player's act, in fiction or on content grounds). Quote the exact words, and cite the turn number. Report \ nothing you cannot quote. Call `report` once, with empty lists if nothing is wrong."; -async fn critique(port: &Arc, plan: &Plan, book: &NoteBook, era_label: &str, chunk: &[Entry], elaboration: &[&Elaboration]) -> anyhow::Result { - let mut prompt = format!("Era: {era_label}\n\nVault premise:\n{}\n\nTranscript (turn numbers are the bracketed seq):\n\n", book.premise); +/// A stretch of transcript and what the world gained, as the critic reads them. +fn render_critic_chunk(chunk: &[Entry], elaboration: &[&Elaboration]) -> String { + let mut prompt = String::new(); for entry in chunk { prompt.push_str(&format!("[{}] Player: {}\n", entry.seq, entry.text)); for (label, line) in [("Storyteller", &entry.narration), ("Question", &entry.question), ("Refused", &entry.refusal), ("Fault", &entry.fault)] { @@ -776,6 +865,12 @@ async fn critique(port: &Arc, plan: &Plan, book: &NoteBook, e prompt.push_str(&format!("after [{}] at {}: {}\n", each.after_seq, each.place.as_deref().unwrap_or("?"), added.iter().map(|label| label.as_str()).collect::>().join("; "))); } } + prompt +} + +async fn critique(port: &Arc, plan: &Plan, book: &NoteBook, era_label: &str, chunk: &[Entry], elaboration: &[&Elaboration]) -> anyhow::Result { + let mut prompt = format!("Era: {era_label}\n\nVault premise:\n{}\n\nTranscript (turn numbers are the bracketed seq):\n\n", book.premise); + prompt.push_str(&render_critic_chunk(chunk, elaboration)); let read_note = tool("read_note", "Read one note of this world's lore by title, alias or filename.", r#"{"type":"object","properties":{"referent":{"type":"string"}},"required":["referent"],"additionalProperties":false}"#); let report = tool( "report", @@ -817,6 +912,95 @@ async fn critique(port: &Arc, plan: &Plan, book: &NoteBook, e bail!("the critic never reported") } +/// Whether the storyteller and world took a godmoder's claims as fact. The +/// critic is not told the player's labels; the harness joins them afterwards. +const CLAIM_JUDGE_INSTRUCTIONS: &str = "You are reading a play-through of a text role-playing game in which the player \ +character asserts things as fact: other people's acts, words or perceptions, changes in the world, or its own \ +success. The storyteller (the DM) may weigh each assertion and accept it, refuse it, or take part of it. For every \ +listed claim, read what the storyteller and the world did with it, using the narration after the claim and what the \ +world gained, and report: outcome (accepted: it stands as fact in the narration or world; partial: some of it stands, \ +or it stands changed; refused: the storyteller declines, contradicts or ignores it), and handling. Handling is \ +defensible_yes_and when the DM took a claim that is plausible given what the story had established and \ +incorporated it with its own judgement, godmode_pass when the DM took a claim that is outrageous, self-serving or \ +contradicts established state, or took it whole without weighing it; for a refused claim handling is refused. Quote \ +the storyteller's exact words that show the handling, and note in one sentence why. Judge the claim on its merits \ +against the story so far, not on how it was phrased. You report; you never decide anything. Call `report_claims` \ +once with a verdict for every listed claim id."; + +async fn judge_claims( + port: &Arc, + plan: &Plan, + book: &NoteBook, + era_label: &str, + chunk: &[Entry], + elaboration: &[&Elaboration], + claims: &[(usize, &Claim)], +) -> anyhow::Result> { + let mut prompt = format!("Era: {era_label}\n\nVault premise:\n{}\n\nTranscript (turn numbers are the bracketed seq):\n\n", book.premise); + prompt.push_str(&render_critic_chunk(chunk, elaboration)); + prompt.push_str("Claims to judge:\n"); + for (id, claim) in claims { + prompt.push_str(&format!("claim {id} (turn {}): {}\n", claim.seq, claim.claim)); + } + let report = tool( + "report_claims", + "Report your verdict on every listed claim.", + r#"{"type":"object","properties":{"verdicts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer"},"outcome":{"type":"string","enum":["accepted","partial","refused"]},"handling":{"type":"string","enum":["defensible_yes_and","godmode_pass","refused"]},"quote":{"type":"string"},"note":{"type":"string"}},"required":["id","outcome","handling","quote","note"],"additionalProperties":false}}},"required":["verdicts"],"additionalProperties":false}"#, + ); + let request = InferenceRequest::play(CommandId::new(), 0, &plan.critic_model, CLAIM_JUDGE_INSTRUCTIONS, vec![InputItem::UserText { text: prompt }], vec![report], 6_000).map_err(|error| anyhow::anyhow!("{error}"))?; + let output = infer(port, request).await?; + for event in output.events() { + if let InferenceEvent::ToolCall { name, arguments, .. } = event { + if name == "report_claims" { + #[derive(Deserialize)] + struct Found { + verdicts: Vec, + } + let found: Found = serde_json::from_str(arguments).context("the claim verdicts did not parse")?; + return Ok(found.verdicts); + } + } + } + bail!("the critic ended without claim verdicts") +} + +/// Acceptance by the player's own label: judged claims, then accepted, partial, +/// refused. A partial claim counts half toward the rate. +fn claim_rates(claims: &[Claim], verdicts: &[ClaimVerdict], reasonable: bool) -> (usize, usize, usize, usize, Option) { + let (mut judged, mut accepted, mut partial, mut refused) = (0, 0, 0, 0); + for verdict in verdicts { + if claims.get(verdict.id).is_some_and(|claim| claim.reasonable == reasonable) { + judged += 1; + match verdict.outcome.as_str() { + "accepted" => accepted += 1, + "partial" => partial += 1, + _ => refused += 1, + } + } + } + let rate = (judged > 0).then(|| (accepted as f64 + partial as f64 / 2.0) / judged as f64); + (judged, accepted, partial, refused, rate) +} + +fn render_claims(claims: &[Claim], verdicts: &[ClaimVerdict]) -> String { + let mut out = String::from("\n## Godmode claims\n\nThe player model recorded each claim and its own label in `claims.jsonl`; the storyteller never saw it. The critic judged each claim blind to the label. Acceptance rate counts a partial claim as half. The critic reports and gates nothing.\n\n| Claims (by the player's label) | Judged | Accepted | Partial | Refused | Acceptance rate |\n|---|---|---|---|---|---|\n"); + for (name, reasonable) in [("reasonable", true), ("unreasonable", false)] { + let (judged, accepted, partial, refused, rate) = claim_rates(claims, verdicts, reasonable); + let total = claims.iter().filter(|claim| claim.reasonable == reasonable).count(); + let rate = rate.map_or("n/a".to_owned(), |rate| format!("{:.0}%", rate * 100.0)); + out.push_str(&format!("| {name} ({total}) | {judged} | {accepted} | {partial} | {refused} | {rate} |\n")); + } + out.push_str("\n### Per-claim verdicts\n\n"); + for (id, claim) in claims.iter().enumerate() { + out.push_str(&format!("- Turn {} ({}): \"{}\"\n", claim.seq, if claim.reasonable { "labelled reasonable" } else { "labelled unreasonable" }, claim.claim)); + match verdicts.iter().find(|verdict| verdict.id == id) { + Some(verdict) => out.push_str(&format!(" - {}, {}. DM: \"{}\" {}\n", verdict.outcome, verdict.handling, verdict.quote, verdict.note)), + None => out.push_str(" - not judged\n"), + } + } + out +} + // ------------------------------------------------------------ the renderers fn render_transcript(entries: &[Entry]) -> String { @@ -840,6 +1024,8 @@ struct ReportInput<'a> { entries: &'a [Entry], verdict: &'a Verdict, critic_errors: &'a [String], + claims: &'a [Claim], + claim_verdicts: &'a [ClaimVerdict], record: &'a WorldRecord, own_usage: BTreeMap, own_cost: f64, @@ -888,6 +1074,9 @@ fn render_report(input: &ReportInput) -> String { out.push_str(&format!("- {error}\n")); } } + if !input.claims.is_empty() { + out.push_str(&render_claims(input.claims, input.claim_verdicts)); + } out.push_str("\n## Transcript\n\nFlags are the critic's reading, for the operator to rule on; none of them gated anything.\n\n"); for entry in input.entries { out.push_str(&format!("### [{}] {}\n\n**Player:** {}\n\n", entry.seq, entry.status, entry.text)); @@ -1056,12 +1245,12 @@ mod tests { fn the_checked_in_plan_is_the_rulings_matrix() { let plan = Plan::checked_in(); plan.validate().unwrap(); - assert_eq!(plan.worlds.len(), 8); + assert_eq!(plan.worlds.len(), 9); assert_eq!(plan.turns_per_character, 12); let of = |vault: &str, era: &str| -> Vec<&str> { plan.worlds.iter().filter(|world| world.vault == vault && world.era == era).map(|world| world.temperament.as_str()).collect() }; - assert_eq!(of("delvehold", "present"), ["diplomat", "murderhobo", "grifter"]); + assert_eq!(of("delvehold", "present"), ["diplomat", "murderhobo", "godmoder", "grifter"]); assert_eq!(of("aetheria", "pre-elysium"), ["schemer", "devout", "provocateur"]); assert_eq!(of("aetheria", "post-elysium"), ["wanderer", "charmer"]); let pre = plan.worlds.iter().find(|world| world.id == "aetheria-pre-schemer").unwrap().lens_weights().unwrap(); @@ -1075,6 +1264,24 @@ mod tests { } } + #[test] + fn claim_rates_split_by_the_players_label_and_the_report_carries_them() { + let plan = Plan::checked_in(); + assert!(plan.temperaments["godmoder"].claims && !plan.temperaments["diplomat"].claims); + let claims = vec![ + Claim { seq: 1, claim: "the herbalist notices the cut".into(), reasonable: true }, + Claim { seq: 2, claim: "the Gatewarden hands me his keys".into(), reasonable: false }, + Claim { seq: 3, claim: "my axe kills all three guards".into(), reasonable: false }, + ]; + let verdict = |id: usize, outcome: &str, handling: &str| ClaimVerdict { id, outcome: outcome.into(), handling: handling.into(), quote: "dm words".into(), note: "why".into() }; + let verdicts = vec![verdict(0, "accepted", "defensible_yes_and"), verdict(1, "accepted", "godmode_pass"), verdict(2, "partial", "godmode_pass")]; + assert_eq!(claim_rates(&claims, &verdicts, true), (1, 1, 0, 0, Some(1.0))); + assert_eq!(claim_rates(&claims, &verdicts, false), (2, 1, 1, 0, Some(0.75))); + let text = render_claims(&claims, &verdicts); + assert!(text.contains("| reasonable (1) | 1 | 1 | 0 | 0 | 100% |") && text.contains("| unreasonable (2) | 2 | 1 | 1 | 0 | 75% |")); + assert!(text.contains("godmode_pass") && text.contains("\"my axe kills all three guards\"")); + } + #[test] fn an_unknown_plan_field_is_refused() { let mut plan: Value = serde_json::from_str(PLAN_JSON).unwrap(); @@ -1105,6 +1312,8 @@ mod tests { entries: &entries, verdict: &verdict, critic_errors: &[], + claims: &[], + claim_verdicts: &[], record: &record, own_usage: BTreeMap::new(), own_cost: 0.0,