Ghostlight/crates/ghostlight-dungeon/src/play.rs
Meta Vens 7052644467 Land Cut 12: gate the answer path, recover pre-Cut-11 play stores (PA.f169, PA.f172, PA.f173, PA.f175)
PA.f169 (blocker): two more `client_intents` callers
(`world_create_seed_activate_and_play_round_trip_through_the_real_client`,
`a_create_form_filled_only_by_its_labelled_identity_fields_is_still_accepted`)
ended in `.expect("node must be on PATH ...")` with no skip guard, so
`cargo test --locked -p ghostlight-dungeon --bin ghostlight-dungeon` itself
failed in a `node`-less container -- Idunn's own gate. Both now carry the
same `eve_client_bridge_is_available()` skip guard the third caller already
had, printing a plain SKIPPED line naming themselves. Verified with `node`
scrubbed from PATH: all three skip and the full bin suite is still
156 passed, 0 failed.

PA.f172: `question_surface_version` (added in Cut 11 with no
`#[serde(default)]`) made a pre-Cut-11 `PlayTurnStore` row fail to decode,
which `PlayTurnStore::open` reported as "corrupt" and `runtime.rs` turned
into a silently missing play card. `STORE_SCHEMA` moves to
`ghostlight.play_turn_store.v2`; `question_surface_version` now carries
`#[serde(default)]`, so the same struct is a compatible read of a genuine
v1 row (`LEGACY_STORE_SCHEMA_V1`). `PlayTurnStore::open` recognizes that
schema id as legacy, not corrupt, recovers the turn, and upgrades the row
to v2 in place and durably. The strict canonical re-encode check still
applies to current-schema rows; a v1 row's bytes were never canonical
under v2 and the legacy branch does not attempt the comparison. A row that
matches the current schema id but is genuinely undecodable is still
refused as corrupt. `runtime.rs::runtime_readiness` now reports
`playStatus` ("ok"/"unavailable") on `/health`, the same
`Option -> ok/unavailable` shape `projectionStatus`/`controllerStatus`
already use, so a play table that failed to open is visible there instead
of only in a startup `tracing::warn!`.

PA.f173: `close_with_fault` left `question`/`question_surface_version` set
on the turn it closed. Unobservable through `open_question_id` only
because it gates on `state == AwaitingPlayer`, which closing always
leaves behind in the same write. `close_with_fault` now clears both,
matching `answer_turn`.

PA.f175: `execute_round` took one snapshot at round entry and reused it
for every arm in that round, so a round that authors (a `PLAY_TOOLS` run)
and then asks in the same round recorded `question_surface_version` from
before its own commit. The `ASK_PLAYER_TOOL` arm now fetches a fresh
snapshot at the moment the question actually opens.

Tests added: a_legacy_v1_row_is_recognized_and_upgraded_not_refused_as_corrupt,
a_row_with_the_current_schema_id_and_undecodable_bytes_is_still_refused_as_corrupt,
close_with_fault_clears_the_open_question_off_the_persisted_row,
a_round_that_authors_and_then_asks_records_the_version_as_of_the_question_not_the_round,
health_reports_play_status_from_state_play.

Dungeon bin: 156 passed, 0 failed (bridge available); 156 passed, 0 failed
with `node` scrubbed from PATH (3 SKIPPED).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 02:27:44 +02:00

9813 lines
419 KiB
Rust

//! The play table's store and loop (Cut 8a).
//!
//! One play agent runs a role-playing game over a Ghostlight world: it reads
//! `table_view`, interprets the player's prose, dispatches Personas, commits
//! consequences through the kernel's own `table.rs` vocabulary, and ends the
//! turn or asks the player a question. The kernel is the only writer; this
//! table carries no world state between turns, only the turn's own inference
//! record.
//!
//! Cut 8b (`a99fdfe`) wired this into `AppState`, `GHOSTLIGHT_PLAY_MODEL`,
//! and `world.play` ingress: `runtime.rs` now holds one `Arc<PlayTable>` per
//! world this process owns and routes `world.play` to it. The Eve schema —
//! a descriptor and a button for `world.play` — is not: `operation_schema`
//! carries the operation alone, so far advertised nowhere (Cut 9).
use std::{
collections::VecDeque,
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use anyhow::{Context, bail};
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use ghostlight::{
CommandBody, CommandId, ControllerError, ControllerMode, ControllerPort, DecisionInvocation,
DecisionOpportunity, InferenceEvent, InferenceFault, InferenceFaultDisposition,
InferenceOutput, InferencePort, InferenceRequest, KernelError, MailboxError, PersonaLane,
PlayPort, PrincipalCommandIntent, Statement, SubjectId, TickMinutes, VerifiedPrincipalEvidence,
WorldMailbox, WorldPatch, WorldSnapshot, actor_tools, authoring_tools, decode_actor_call,
decode_authoring_calls, describe_refusal, describe_refusal_to_actor, id_text, id_text_matches,
table_view,
};
use ghostlight_persona_projection::{PersonaTurn, SourceSpan};
use codex_connector::{CodexInputItem, CodexToolDefinition};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use tokio::sync::{Mutex, Semaphore};
const STORE_TYPE: &str = "ghostlight.play_turn_store.v1";
/// PA.f172: bumped from `ghostlight.play_turn_store.v1` when
/// `question_surface_version` was added to `PlayTurn` without
/// `#[serde(default)]` — the row's own shape moved, so its schema id moves
/// with it. `question_surface_version` now carries `#[serde(default)]`, so
/// this v2 reader is a compatible read of a genuine v1 row too: `open` still
/// gates strictly on the row's own declared `schema_id` (a fresh legacy
/// branch recognizes `LEGACY_STORE_SCHEMA_V1` by name, never silently), but
/// once recognized, decodes it with exactly the same struct and upgrades it
/// in place rather than discarding the turn it names as unreadable.
const STORE_SCHEMA: &str = "ghostlight.play_turn_store.v2";
/// The schema id every row written before `question_surface_version` existed
/// carries. Recognized by `PlayTurnStore::open` as legacy, not corrupt, and
/// upgraded to `STORE_SCHEMA` in place (PA.f172).
const LEGACY_STORE_SCHEMA_V1: &str = "ghostlight.play_turn_store.v1";
const STORE_KEY: &str = "primary";
/// The one round budget: exhausting it closes the turn and narrates, rather
/// than leaving it `Running` with nothing said (PA-Q8, Cut 8, PA.f66a/PA.f95).
const ROUND_BUDGET: usize = 12;
/// Bounded so a single round cannot spend the whole response budget one
/// grouped-agent tool spree; matches the grouped agent lane's own order of
/// magnitude (`controllers.rs`'s `OperationalAgent` request).
const PLAY_MAX_OUTPUT_TOKENS: u32 = 8_000;
/// How many `Retryable` inference faults one round's own request may absorb
/// (PA.f94): only `InferenceFaultDisposition::Retryable` retries at all — a
/// `RecoveryRequired` or `IntegrityViolation` fault closes the turn on its
/// first occurrence, through `close_with_fault`, since retrying either kind
/// again cannot succeed differently.
const ROUND_RETRY_BUDGET: usize = ROUND_BUDGET;
/// The key ledger's own retention window (PA.f83): a request key survives in
/// the ledger for the most recent 64 closed turns after the one that carried
/// it, then is forgotten — the store keeps only the current turn's own full
/// record, so an ancient replay past the window opens a fresh turn rather
/// than being recognized.
const KEY_LEDGER_WINDOW: usize = 64;
/// Dungeon's own subset of the library's `PATCH_TOOLS`, named in Cut 8's
/// table (PA-Q7 B). The library hard-codes none of these; this is policy, and
/// policy belongs to the caller.
const PLAY_TOOLS: &[&str] = &[
"relocate",
"transfer",
"consume",
"mint",
"bind",
"release",
"witness",
"acquire_knowledge",
"forget",
"create_commitment",
"discharge_commitment",
"advance_pressure",
"reduce_pressure",
"open_route",
"close_route",
"declare_place",
"declare_route",
"declare_resource",
"declare_fact",
"declare_subject",
"set_persona_material",
"retire",
"grant_affordance",
"revoke_affordance",
];
const DISPATCH_TOOL: &str = "dispatch";
const ADVANCE_TIME_TOOL: &str = "advance_time";
const ASK_PLAYER_TOOL: &str = "ask_player";
const END_TURN_TOOL: &str = "end_turn";
/// A handle names the player or a subject dispatched this turn; nothing else
/// carries the `__` separator into a tool name a model may call.
const HANDLE_SEPARATOR: &str = "__";
/// The table rules, sent once per round as the request's instructions. The
/// turn's own conversation is rebuilt each round from the recorded
/// `opening_prompt` — `table_view` of the snapshot as it stood the moment the
/// turn opened, captured once, not re-rendered on a later round — plus the
/// recorded `rounds` and their recorded results (PA.f111, S6): a resumed
/// round replays this exact recorded opening, never a fresh `table_view` of
/// whatever the world looks like by the time it resumes.
const PLAY_INSTRUCTIONS: &str = "You are the table: the one player-facing role-playing agent for this Ghostlight world. \
The player writes prose; you read the whole-world table view and decide what happens.\n\
\n\
Rules:\n\
- Speech and display are quotes: a `<handle>__<kind>` call's `text` and `display` must be an exact, \
verbatim quote copied from the player's own words or from a dispatched Persona's own turn prose. A \
paraphrase is refused.\n\
- An actor acts only through its own tools: use `<handle>__<kind>` for the player's handle or a \
subject you dispatched this turn, never another subject's tool under a borrowed handle.\n\
- Rulings are authoring tools: mint, transfer, relocate, and the rest of the authoring catalog are \
your own hand as the table, not an actor's act.\n\
- Ask the player with `ask_player` when an outcome needs the player's own choice or negotiation, and \
stop the turn there.\n\
- A fact you invent uses `declare_fact` with `ruled` standing; you reach a subject's knowledge of it \
through `witness` or `acquire_knowledge`.\n\
- You may `mint` quantity into existence; nothing else may.\n\
- Call `dispatch` with the subjects who should act this round before calling their tools, naming each \
subject by its full id exactly as table_view prints it in brackets — never the short <handle>__ prefix \
an actor tool's own name carries. An id naming no dispatchable subject is refused, quoting the text \
given, rather than silently doing nothing.\n\
- Call `end_turn` when the round's consequences are settled.";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum PlayTurnState {
Running,
AwaitingPlayer,
Closed,
}
/// One `run` request. `answers` names the question this request answers, by
/// the same `QuestionId` an `AwaitingPlayer` turn currently exposes; `None`
/// is the plain continue/opening shape (PA.f84). `&str`/`String` still
/// convert directly (`answers: None`), so most call sites are unaffected by
/// this replacing the bare `text` parameter `run` used to take.
#[derive(Clone, Debug)]
pub(crate) struct PlayRequest {
pub(crate) text: String,
pub(crate) answers: Option<QuestionId>,
}
impl From<&str> for PlayRequest {
fn from(text: &str) -> Self {
Self {
text: text.to_owned(),
answers: None,
}
}
}
impl From<String> for PlayRequest {
fn from(text: String) -> Self {
Self { text, answers: None }
}
}
/// The small typed value one open question is identified by (PA.f84): a
/// `run` request whose `answers` does not match the turn's own currently
/// open `QuestionId` is refused as stale rather than being applied to
/// whatever question happens to be open when the request is finally
/// processed — a late retry naming an already-answered or already-superseded
/// question must never land on a different one.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct QuestionId {
turn_id: String,
round: usize,
slot: usize,
}
/// One tool call's recorded body, persisted before submission (PA-Q8): a
/// resumed call resubmits this exact value, never a value rebuilt from a
/// fresh snapshot (mutation M8.3).
#[derive(Clone, Debug, Serialize, Deserialize)]
enum RecordedCall {
Authoring(WorldPatch),
PlayerAct(DecisionOpportunity, DecisionInvocation),
PersonaAct(SubjectId, DecisionOpportunity, DecisionInvocation),
AdvanceTime(TickMinutes),
Dispatch(Vec<SubjectId>),
AskPlayer(String),
EndTurn,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct CallRecord {
call_id: String,
round: usize,
slot: usize,
/// Absent only for a call this table refused before it ever reached a
/// door: a decode failure, an unknown tool, a span that would not
/// locate. Nothing with a body here was ever silently dropped; its
/// `result` is always the reason.
body: Option<RecordedCall>,
result: Option<String>,
}
/// The play turn row (PA-Q8): one row, over `service/play-turn-v1.cc`,
/// following `app_session.rs`'s pattern. The agent's conversation is
/// re-derived each round from `opening_prompt`, `rounds`, and the recorded
/// `calls`/`persona_turns` results — the connector posture — so nothing
/// carries forward between turns except world state.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PlayTurn {
/// Minted fresh (`Uuid::new_v4`) when the turn opens (PA.f83): never
/// taken from any request key. A request key and a turn's own identity
/// are different things — see `applied_keys` below and the store's own
/// `KeyLedger` — so a stale retry of the key that opened this turn can
/// never reproduce this turn's own command ids by opening a second turn
/// under the same id.
turn_id: String,
/// Every request key this open turn has already applied (PA.f62/PA.f63):
/// a key already here is a replay — a no-op — for as long as this turn
/// stays the store's current one. Once the turn closes, this list is
/// archived into the store's own `KeyLedger` (PA.f83), which is where a
/// replay of one of these keys is recognized after a new turn has opened
/// in this one's place. No `#[serde(default)]`: the canonical re-encode
/// check in `PlayTurnStore::open` refuses a row missing this field, so a
/// default here could never actually apply (PA.f95).
applied_keys: Vec<String>,
opening_prompt: String,
player_prose: Vec<String>,
rounds: Vec<InferenceOutput>,
calls: Vec<CallRecord>,
persona_turns: Vec<(SubjectId, PersonaTurn)>,
question: Option<String>,
/// PA.f161: the world's own `eve::surface_version` at the instant this
/// question opened (`execute_round`'s `ASK_PLAYER_TOOL` arm), set and
/// cleared alongside `question` — never re-derived from whatever the
/// world's current revision happens to be when a later request arrives.
/// This is what lets an answer be refused as stale by "older than the
/// version the question first appeared on" rather than by "not exactly
/// today's version," the comparison PA.f161 replaces. `#[serde(default)]`
/// (PA.f172, reversing the earlier PA.f95 reasoning here): a row written
/// before this field existed — a real shape on a workstation that ran
/// Dungeon before Cut 11, not a hypothetical — decodes to `None`, exactly
/// what "no question ever recorded a surface version" means for a turn
/// this old. `STORE_SCHEMA` moved to v2 alongside this default so the
/// canonical re-encode check below still holds current-schema rows to
/// their exact bytes; only the legacy v1 read path in
/// `PlayTurnStore::open` relies on this default to recover an older row.
#[serde(default)]
question_surface_version: Option<u64>,
refusal: Option<String>,
narration: Option<String>,
/// Set when the turn closed on a fault rather than the player's own
/// consequences settling: an inference fault that does not retry, an
/// inference exhausted its retry budget (PA.f65/PA.f94), a request-build,
/// snapshot, or narrate failure after the turn opened (PA.f85/PA.f93), or
/// a kernel `Invariant` error poisoned the table (PA.f66b). `None` for a
/// turn that closed through `end_turn` or the round budget. No
/// `#[serde(default)]`: same reasoning as `applied_keys` above (PA.f95).
fault: Option<String>,
state: PlayTurnState,
}
impl PlayTurn {
/// Every subject a dispatch call this turn's own record names has
/// *successfully* acted (PA.f90): a dispatch whose Persona turn faulted,
/// or found no live opportunity, never produced prose this turn can
/// quote, so it does not count as dispatched — offering its actor tools
/// next round would let the agent call them with nothing behind them.
/// `persona_turns` is the one record of an actually-recorded turn; a
/// subject's own presence there, not merely its presence in a
/// `Dispatch` call's own subject list, is what this reads.
fn dispatched_subjects(&self) -> Vec<SubjectId> {
let mut subjects = Vec::new();
for call in &self.calls {
if let Some(RecordedCall::Dispatch(list)) = &call.body {
for subject in list {
if !subjects.contains(subject) && self.persona_turns.iter().any(|(id, _)| id == subject) {
subjects.push(*subject);
}
}
}
}
subjects
}
/// The `(round, slot)` of the earliest `Dispatch` call in this turn's
/// own record that names `subject`, if any (PA.f125): call order is
/// total, so exactly one call can be credited with producing a
/// subject's own `persona_turns` entry — the first one, in call order,
/// that ever named it. `execute_round` records and persists a dispatch
/// call's own body before `execute_dispatch` runs any persona turn, so
/// a crash-resumed call already appears here, under its own
/// `(round, slot)`, before this is ever consulted — letting
/// `execute_dispatch` recognize its own not-yet-finished work instead
/// of refusing it as `already acted` against a different call.
fn dispatch_owner(&self, subject: SubjectId) -> Option<(usize, usize)> {
self.calls
.iter()
.filter_map(|call| match &call.body {
Some(RecordedCall::Dispatch(list)) if list.contains(&subject) => Some((call.round, call.slot)),
_ => None,
})
.min()
}
fn call_record(&self, round: usize, slot: usize) -> Option<&CallRecord> {
self.calls
.iter()
.find(|call| call.round == round && call.slot == slot)
}
fn call_record_mut(&mut self, round: usize, slot: usize) -> Option<&mut CallRecord> {
self.calls
.iter_mut()
.find(|call| call.round == round && call.slot == slot)
}
/// The currently open question's own `QuestionId`, when the turn is
/// `AwaitingPlayer` (PA.f84): derived from the last round's own
/// unresolved `ask_player` call, the same slot `find_ask_player_slot`
/// locates to record an answer's result.
fn open_question_id(&self) -> Option<QuestionId> {
if self.state != PlayTurnState::AwaitingPlayer {
return None;
}
let round = self.rounds.len().checked_sub(1)?;
let slot = find_ask_player_slot(self, round)?;
Some(QuestionId {
turn_id: self.turn_id.clone(),
round,
slot,
})
}
}
/// `turn.open_question_id()` paired with the question's own text and the
/// surface version it opened on (PA.f134/PA.f161): `None` whenever
/// `open_question_id` is, since `turn.question` and
/// `turn.question_surface_version` are only ever set alongside it
/// (`execute_round`'s `ASK_PLAYER_TOOL` arm sets all three in the same
/// round, and `answer_turn` and `close_with_fault` both clear
/// `question`/`question_surface_version` on their own way out of
/// `AwaitingPlayer`, PA.f173).
fn open_question_of(turn: &PlayTurn) -> Option<OpenQuestion> {
let id = turn.open_question_id()?;
Some(OpenQuestion {
id,
text: turn.question.clone().unwrap_or_default(),
surface_version: turn.question_surface_version.unwrap_or(0),
})
}
#[derive(Clone, Serialize, Deserialize)]
struct PlayTurnStoreState {
schema: String,
turn: Option<PlayTurn>,
/// A closed turn's own applied request keys, kept for `KEY_LEDGER_WINDOW`
/// more closed turns after it (PA.f83). No `#[serde(default)]`, matching
/// `PlayTurn::applied_keys`/`fault` (PA.f95): `PlayTurnStore::open`'s own
/// canonical re-encode check refuses any row missing a declared field
/// regardless, so a default here could never actually apply either.
ledger: KeyLedger,
/// The row's own monotonic counter (Cut 9): incremented exactly once by
/// `swap_in`, the row's one write door, on every committed write —
/// `commit`'s own mid-turn updates and `open_new_turn`'s own turn
/// replacements alike. It never resets, not on a new turn and not on a
/// restart (the store reads it back off disk like every other field), so
/// a reconnecting SSE client can never see it go backwards. This is what
/// lets `eve::authenticated_surface`'s own `surface_version` move on a
/// refusal or a question that commits nothing to the world — the one gap
/// a version derived only from already-existing row fields could not
/// close, because a refusal updates `turn.refusal` without growing
/// `turn.calls` or `turn.rounds` (`execute_actor_call`'s `ActionRejected`
/// arm updates an already-recorded call's own result in place). No
/// `#[serde(default)]`, matching `ledger` above: the store has never been
/// deployed, so no row anywhere is missing it, and the canonical
/// re-encode check stays strict (PA.f95).
revision: u64,
}
/// One closed turn's own applied request keys, oldest closed turn first.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct KeyLedger {
closed: VecDeque<ClosedTurnKeys>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ClosedTurnKeys {
turn_id: String,
keys: Vec<String>,
}
impl KeyLedger {
/// The `turn_id` of the closed turn `key` was applied to, if it is still
/// within the window (PA.f109): `ClosedTurnKeys::turn_id` is written on
/// every archive but was never read anywhere until this — a replay
/// recognized through the ledger can now say which turn it replayed.
fn turn_id_for(&self, key: &str) -> Option<String> {
self.closed
.iter()
.find(|entry| entry.keys.iter().any(|existing| existing == key))
.map(|entry| entry.turn_id.clone())
}
/// Archives one turn's own applied keys as it closes out of the store's
/// single current-turn row, then evicts down to `KEY_LEDGER_WINDOW`
/// closed turns, oldest first.
fn push_closed(&mut self, turn_id: String, keys: Vec<String>) {
if keys.is_empty() {
return;
}
self.closed.push_back(ClosedTurnKeys { turn_id, keys });
while self.closed.len() > KEY_LEDGER_WINDOW {
self.closed.pop_front();
}
}
}
/// `PlayTurnStore` over `service/play-turn-v1.cc`: one `OwnedRedbMessagePackBackingStore`
/// row, the same custody shape `app_session.rs`'s `AppSessionOwner` uses.
struct PlayTurnStore {
store: OwnedRedbMessagePackBackingStore,
row: CultCacheEnvelope,
state: PlayTurnStoreState,
healthy: bool,
}
impl PlayTurnStore {
fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store
.validate_path_identity()
.context("play-turn store path identity is invalid")?;
let rows = store.pull_all()?;
let (row, state) = match rows.as_slice() {
[] => {
let state = PlayTurnStoreState {
schema: STORE_SCHEMA.into(),
turn: None,
ledger: KeyLedger::default(),
revision: 0,
};
let row = envelope(&state)?;
if !store.compare_and_swap_batch(&[], vec![row.clone()])? {
bail!("play-turn store changed during initialization");
}
(row, state)
}
[row]
if row.r#type == STORE_TYPE
&& row.key == STORE_KEY
&& row.schema_id.as_deref() == Some(STORE_SCHEMA) =>
{
let state: PlayTurnStoreState =
rmp_serde::from_slice(&row.payload).context("play-turn state is corrupt")?;
if rmp_serde::to_vec_named(&state)? != row.payload {
bail!("play-turn state is not canonical");
}
if state.schema != STORE_SCHEMA {
bail!("play-turn state schema is invalid");
}
(row.clone(), state)
}
// PA.f172: a row written before `question_surface_version`
// existed — named legacy, not corrupt, because it is neither: it
// is a real, previously-canonical shape this process itself
// wrote, under the schema id that was current when it did.
// `question_surface_version` now carries `#[serde(default)]`, so
// the very same `PlayTurnStoreState` decodes it correctly (the
// field reads back `None`, matching what "no question ever
// recorded a surface version" means for a turn this old). This
// branch upgrades the row to `STORE_SCHEMA` (v2) in place and
// persists that upgrade immediately, so the legacy path is only
// ever taken once per row; the canonical re-encode check does
// not apply here — a v1 row's bytes were never canonical under
// v2 and were never meant to be — it resumes for every write
// this store makes from here on.
[row]
if row.r#type == STORE_TYPE
&& row.key == STORE_KEY
&& row.schema_id.as_deref() == Some(LEGACY_STORE_SCHEMA_V1) =>
{
let mut state: PlayTurnStoreState = rmp_serde::from_slice(&row.payload)
.context("play-turn legacy v1 state is corrupt")?;
if state.schema != LEGACY_STORE_SCHEMA_V1 {
bail!("play-turn legacy v1 state schema is invalid");
}
state.schema = STORE_SCHEMA.into();
let upgraded_row = envelope(&state)?;
if !store.compare_and_swap_batch(std::slice::from_ref(row), vec![upgraded_row.clone()])? {
bail!("play-turn store changed while upgrading a legacy v1 row");
}
(upgraded_row, state)
}
_ => bail!("play-turn store contains foreign or otherwise-unreadable records; start with a fresh store"),
};
Ok(Self {
store,
row,
state,
healthy: true,
})
}
fn current(&self) -> Option<&PlayTurn> {
self.state.turn.as_ref()
}
/// PA.f99's own test seam: re-reads the current turn through a fresh
/// `pull_all` against the *same already-owned* redb `Database` this
/// store already holds — never the cached `self.state` field a mutation
/// could leave stale, and never a second `OwnedRedbMessagePackBackingStore::new`
/// on the same path, which CultCache's own single-owner lock refuses
/// outright (`redb CultCache <path> already has an active owner`): this
/// crate learned that the hard way building this very seam. `pull_all`
/// opens its own fresh redb read transaction against the one open
/// `Database`, so this reflects exactly what the last successful
/// `compare_and_swap_batch` durably committed, independent of whether
/// `self.state` was ever updated at all.
#[cfg(test)]
fn pull_current_from_disk_for_test(&self) -> Option<PlayTurn> {
let rows = self.store.pull_all().ok()?;
let row = rows.into_iter().find(|row| row.r#type == STORE_TYPE && row.key == STORE_KEY)?;
let state: PlayTurnStoreState = rmp_serde::from_slice(&row.payload).ok()?;
state.turn
}
/// The `turn_id` of the turn `key` was already applied to, if any
/// (PA.f109): the still-open current turn, when `key` is recorded on it,
/// or the ledger's own archived record of one of the most recent
/// `KEY_LEDGER_WINDOW` closed turns (PA.f83). Either way, `run` treats a
/// known key as a no-op — a `Replayed` outcome naming the turn it
/// replayed, not a fresh open.
fn turn_id_for_key(&self, key: &str) -> Option<String> {
if let Some(turn) = &self.state.turn
&& turn.applied_keys.iter().any(|existing| existing == key)
{
return Some(turn.turn_id.clone());
}
self.state.ledger.turn_id_for(key)
}
/// Persists `turn` as an update to the store's own still-open current
/// turn: the ledger is carried forward unchanged, because no turn is
/// closing out of the row here.
fn commit(&mut self, turn: PlayTurn) -> anyhow::Result<()> {
self.ensure_owned()?;
self.swap_in(Some(turn), self.state.ledger.clone())
}
/// Opens `turn` as the store's new current turn (PA.f83): whatever turn
/// currently occupies the row — always `Closed`, by `PlayTable::run`'s
/// own invariant that only a closed turn (or no turn) is ever replaced —
/// has its own applied keys archived into the ledger first, so a later
/// replay of one of them is still recognized after its full record is
/// gone.
fn open_new_turn(&mut self, turn: PlayTurn) -> anyhow::Result<()> {
self.ensure_owned()?;
let mut ledger = self.state.ledger.clone();
if let Some(previous) = &self.state.turn {
ledger.push_closed(previous.turn_id.clone(), previous.applied_keys.clone());
}
self.swap_in(Some(turn), ledger)
}
/// The row's one write door (Cut 9): every committed write — `commit`'s
/// own mid-turn updates and `open_new_turn`'s own turn replacements alike
/// — passes through here, and `revision` moves exactly once per call,
/// here alone, so no call site can under- or double-count it.
fn swap_in(&mut self, turn: Option<PlayTurn>, ledger: KeyLedger) -> anyhow::Result<()> {
let next = PlayTurnStoreState {
schema: STORE_SCHEMA.into(),
turn,
ledger,
revision: self.state.revision + 1,
};
let next_row = envelope(&next)?;
let swapped = self
.store
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
if !matches!(swapped, Ok(true)) {
self.healthy = false;
bail!("play-turn commit outcome is uncertain; sole ownership was lost");
}
self.row = next_row;
self.state = next;
Ok(())
}
fn ensure_owned(&mut self) -> anyhow::Result<()> {
if !self.healthy {
bail!("play-turn custody is poisoned; reopen the owner");
}
if self.store.validate_path_identity().is_err() {
self.healthy = false;
bail!("play-turn store ownership was lost");
}
Ok(())
}
}
fn envelope(state: &PlayTurnStoreState) -> anyhow::Result<CultCacheEnvelope> {
Ok(CultCacheEnvelope {
key: STORE_KEY.into(),
r#type: STORE_TYPE.into(),
payload: rmp_serde::to_vec_named(state)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(STORE_SCHEMA.into()),
})
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum PlayError {
#[error("the play table is poisoned by a prior kernel invariant fault; restart to clear it")]
Poisoned,
#[error("world mailbox error: {0}")]
World(#[from] MailboxError),
#[error("controller error: {0}")]
Controller(#[from] ControllerError),
#[error("play store error: {0}")]
Store(#[from] anyhow::Error),
/// PA.f134: carries the turn's own still-open question — the same one
/// the caller was already answering, since this refusal never changes
/// it — so a consumer can retry without re-reading the store.
#[error("an empty or whitespace-only answer is refused")]
EmptyAnswer { turn_id: String, question: OpenQuestion },
/// PA.f84: `request.answers` did not name the turn's own currently open
/// `QuestionId` — either it named a different, no-longer-open question
/// (a late retry), or no question is open at all while the turn is
/// `AwaitingPlayer`, which cannot actually happen but is refused the
/// same way rather than assumed away.
///
/// PA.f134: carries the turn's own *actually* currently open question
/// (`None` only in the "cannot actually happen" case), so a caller who
/// named a stale question can retry against the real one without
/// re-reading the store.
#[error("the answer does not name the currently open question; it is refused as stale")]
StaleAnswer {
turn_id: String,
question: Option<OpenQuestion>,
},
/// PA.f84: `request.answers` was given while no question is open at all
/// — the turn is `Running`, or there is no open turn to answer.
#[error("an answer was given but no question is currently open")]
NoQuestionOpen,
/// PA.f84: the turn is `Running` and `request.text` is non-empty; only
/// an empty continue is accepted while a prior request's own rounds are
/// still being resolved.
#[error("the turn is still running its own prior request; only an empty continue is accepted")]
TurnStillRunning,
/// PA.f108: empty or whitespace-only text with no turn currently open to
/// continue (no turn at all, or the current one is `Closed`) used to
/// open a fresh turn anyway, with prose `[""]`, and run a full inference
/// over nothing the player actually said. A new turn needs the player's
/// own words.
#[error("a new turn needs non-empty text; an empty or whitespace-only opening is refused")]
EmptyOpening,
}
/// A turn's own open question, and the identity a caller answers it by
/// (PA.f134): `id` is the exact `QuestionId` `PlayRequest::answers` expects
/// back; `text` is the question itself, so a consumer never has to read the
/// store to learn either.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct OpenQuestion {
pub(crate) id: QuestionId,
pub(crate) text: String,
/// PA.f161: `eve::surface_version` at the moment this question opened —
/// the value `runtime.rs`'s `world.play` arm compares an answer's own
/// `routeHint.sourceVersion` against, refusing anything older.
pub(crate) surface_version: u64,
}
/// One `run` call's own outcome (PA.f109): `Replayed` names the turn a
/// request key already known — recorded on the still-open current turn, or
/// archived in the store's own `KeyLedger` — replayed, so `ClosedTurnKeys`'s
/// own `turn_id` field, written on every archive, finally has a reader.
///
/// PA.f134: both variants also carry the turn's own currently open question,
/// when one is open, so a caller who reaches `ask_player` can answer it
/// without a second, separate read of the store — `run`'s own return value
/// already names everything `PlayRequest::answers` needs. `world.play`'s own
/// route still cannot hand this back to its HTTP caller (it spawns `run` in
/// a task and answers before the turn even opens); `PlayTable::current_turn_view`
/// is what a later, separate read answers from instead.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RunOutcome {
Ran {
turn_id: String,
question: Option<OpenQuestion>,
},
Replayed {
turn_id: String,
question: Option<OpenQuestion>,
},
}
/// `PlayTable::admit`'s own outcome (Cut 10, PA.f153/PA.f154): a replay is
/// fully decided already — no round ever runs, so nothing is ever spawned
/// for it — while `Spawn` carries the built, already-persisted turn a caller
/// hands to `execute` in a background task.
pub(crate) enum Admission {
Replayed {
turn_id: String,
question: Option<OpenQuestion>,
},
Spawn(Admitted),
}
/// An admitted turn, ready for `PlayTable::execute` (Cut 10). Carries the
/// table's own `run_lock` guard (owned, not borrowed — see `run_lock`'s own
/// doc comment) so the lock stays held from admission through the end of
/// execution even when the two happen in different tasks.
pub(crate) struct Admitted {
turn: PlayTurn,
_run_guard: tokio::sync::OwnedMutexGuard<()>,
}
/// The current turn's own player-facing state (PA.f134), read through
/// `PlayTable::current_turn_view` — see its own doc comment for why this
/// exists beside `RunOutcome`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PlayTurnView {
pub(crate) turn_id: String,
pub(crate) state: PlayTurnState,
pub(crate) question: Option<OpenQuestion>,
pub(crate) narration: Option<String>,
pub(crate) refusal: Option<String>,
/// The play row's own monotonic counter, read straight off the store.
/// `eve::authenticated_wake_version` folds it with `surface_version` to
/// wake the SSE path on a play-row-only change (a fresh refusal, a newly
/// open question, a closed turn's narration) that moves nothing on the
/// world itself. It is never folded into the surface document's own
/// `version` field, which names `surface_version` alone.
pub(crate) revision: u64,
}
/// One outcome of executing a round's already-decided tool calls.
#[derive(Clone, Copy)]
enum RoundOutcome {
/// Every call in the round resolved; the loop should infer the next one.
Continue,
AwaitingPlayer,
Closed,
/// A kernel `Invariant` fault closed the turn and poisoned the table.
Poisoned,
}
/// The play table (Cut 8): one operational model running a role-playing game
/// over a Ghostlight world. `play` is Dungeon's one `PlayPort`, minted here
/// and nowhere else in production (negative grep, matching `PlayPort`'s own
/// doc comment).
pub(crate) struct PlayTable {
play: PlayPort,
world: WorldMailbox,
/// `Arc`, not owned (PA.f13/P8.5): a round's own dispatched Personas run
/// concurrently, each in its own spawned task under a permit drawn from
/// `permits`, so every concurrent call needs its own handle to the same
/// lane rather than a borrow of one `self`.
personas: Arc<PersonaLane>,
inference: Arc<dyn InferencePort>,
model: String,
/// The shared controller/Persona concurrency pool (PA.f13, P8.5):
/// `execute_dispatch` and `close_turn`'s own narration draw from the
/// exact same `Arc<Semaphore>` `runtime.rs` hands `AppState`'s
/// `controller_permits` — the one pool `runtime_readiness`'s
/// `controllerStatus` reads — never a second pool this table mints for
/// itself.
permits: Arc<Semaphore>,
store: Mutex<PlayTurnStore>,
/// One turn at a time for this table (PA.f68/PA.f112): held for the
/// whole body of `run`, so the key check and the turn open happen under
/// one acquisition and two concurrent `run` calls can never interleave.
/// This table is the one owner of one world's play authority, so this is
/// "one running turn per world" exactly as `AppState.play` holds one
/// `Arc<PlayTable>` per world this process owns.
/// `Arc`-wrapped since Cut 10 (PA.f153/PA.f154): `admit` takes an owned
/// guard (`try_lock_owned`) so it can hand the guard into a spawned task
/// alongside the turn it built, rather than holding a borrowed guard for
/// a call that must return to its own caller before the turn's round loop
/// finishes.
run_lock: Arc<Mutex<()>>,
poisoned: AtomicBool,
/// `retry_delay`'s own base, in milliseconds (PA.f122): an ordinary
/// field, always compiled, defaulting to `RETRY_DELAY_BASE_MS` — the
/// same production base `backoff_delay` always scaled from before this
/// field existed. Only a test ever changes it, through
/// `set_retry_delay_base_ms`, so a test's own retries settle instantly
/// without a `#[cfg(test)]` swap over the delay formula itself.
retry_delay_base_ms: std::sync::atomic::AtomicU64,
/// PA.f99's own test seam: fired immediately before each of the four
/// doors that submit or persist a call's already-recorded state
/// (`commit_authoring_run`, `execute_advance_time`, `execute_actor_call`,
/// and, since PA.f123, `execute_dispatch` right after each dispatched
/// subject's own turn is persisted) moves on. It hands the hook the
/// current turn as a fresh `pull_all` against the store's own
/// already-owned redb `Database` finds it
/// (`PlayTurnStore::pull_current_from_disk_for_test`) — not the store's
/// cached `self.state`, and not a second, independently opened store,
/// which CultCache's own single-owner lock refuses outright. No
/// production call installs one.
#[cfg(test)]
before_submit_hook: std::sync::Mutex<Option<Box<dyn Fn(Option<PlayTurn>) + Send + Sync>>>,
/// PA.f127/PA.f133's own test seam: see `fetch_round_snapshot`.
#[cfg(test)]
forced_round_snapshot: std::sync::Mutex<Option<WorldSnapshot>>,
}
impl PlayTable {
pub(crate) fn new(
world: WorldMailbox,
personas: PersonaLane,
inference: Arc<dyn InferencePort>,
model: String,
permits: Arc<Semaphore>,
store_path: impl AsRef<Path>,
) -> anyhow::Result<Self> {
let play = PlayPort::new(world.clone());
let store = PlayTurnStore::open(store_path)?;
Ok(Self {
play,
world,
personas: Arc::new(personas),
inference,
model,
permits,
store: Mutex::new(store),
run_lock: Arc::new(Mutex::new(())),
poisoned: AtomicBool::new(false),
retry_delay_base_ms: std::sync::atomic::AtomicU64::new(RETRY_DELAY_BASE_MS),
#[cfg(test)]
before_submit_hook: std::sync::Mutex::new(None),
#[cfg(test)]
forced_round_snapshot: std::sync::Mutex::new(None),
})
}
/// Installs PA.f99's own before-submit test hook (see the field's own
/// doc comment). Test-only: no production call site exists.
#[cfg(test)]
fn set_before_submit_hook(&self, hook: impl Fn(Option<PlayTurn>) + Send + Sync + 'static) {
*self.before_submit_hook.lock().unwrap() = Some(Box::new(hook));
}
#[cfg(test)]
async fn fire_before_submit_hook(&self) {
let installed = self.before_submit_hook.lock().unwrap().is_some();
if !installed {
return;
}
let durable_turn = self.store.lock().await.pull_current_from_disk_for_test();
if let Some(hook) = self.before_submit_hook.lock().unwrap().as_ref() {
hook(durable_turn);
}
}
#[cfg(not(test))]
async fn fire_before_submit_hook(&self) {}
/// One `world.play` turn. `key` is the caller's own idempotency key
/// (PA-Q8, PA.f62/PA.f63/PA.f83): it is not the turn's identity — the
/// turn mints its own `turn_id` when it opens. A key already known —
/// recorded on the currently open turn, or archived in the store's own
/// `KeyLedger` from one of the most recent 64 closed turns — is a replay
/// and is a no-op, making zero inference calls. A fresh key reaching an
/// open turn continues it: as the player's own answer, when it is
/// `AwaitingPlayer` and `request.answers` names that turn's own currently
/// open question (PA.f84; any other `answers`, or none at all, is
/// refused as stale rather than being applied to whatever question
/// happens to be open), or as a plain continue when it is `Running` and
/// `request.text` is empty (non-empty text is refused: this turn is
/// still running its own prior request and drops nothing silently). A
/// fresh key reaching no turn, or a closed one, opens a new turn under
/// that key (Cut 8a's "one row": only the current turn's own record is
/// ever kept, so the closed turn's record is archived into the ledger
/// and then discarded).
pub(crate) async fn run(
&self,
principal: &VerifiedPrincipalEvidence,
key: String,
request: PlayRequest,
) -> Result<RunOutcome, PlayError> {
match self.admit(key, request).await? {
Admission::Replayed { turn_id, question } => Ok(RunOutcome::Replayed { turn_id, question }),
Admission::Spawn(admitted) => self.execute(admitted, principal).await,
}
}
/// Cut 10 (PA.f153/PA.f154): the synchronous half of `run` — replay
/// detection, the stale-answer/empty-answer/no-question-open/
/// turn-still-running/empty-opening refusals, and building (and
/// persisting) the turn a fresh request continues or opens. None of this
/// spends an inference budget, so `runtime.rs::execute_world`'s
/// `world.play` route now awaits this directly and answers `denied` with
/// the reason on `Err`, instead of discarding every refusal inside a
/// spawned task that had already answered `accepted`. Only
/// `Admission::Spawn`'s own turn actually runs a round loop, and only
/// that is spawned, via `execute`.
pub(crate) async fn admit(&self, key: String, request: PlayRequest) -> Result<Admission, PlayError> {
if self.poisoned.load(Ordering::SeqCst) {
return Err(PlayError::Poisoned);
}
// PA.f68/PA.f112: held from here through the end of `execute`, so
// the replay/key check below and the turn open happen under one
// acquisition and two concurrent `admit` calls for this table can
// never interleave — the second one always observes the first one's
// own already-open (or already-closed) turn, never a stale
// `None`/`Closed` read racing a still-in-flight `open_new_turn`.
//
// PA.f142: `try_lock_owned`, not `lock_owned().await` — a
// `world.play` route spawns the turn's own execution in a task and
// returns before it resolves, so a second request arriving while a
// turn's own round loop is still running (up to `ROUND_BUDGET`
// rounds of inference) must be refused at once, not queued behind it
// with no bound and no signal. A request that finds the lock free —
// including an answer to a question a prior call already left open
// and returned from — is never affected: nothing holds this lock
// between one turn's own execution finishing and the next admission
// starting. Owned (Cut 10), not borrowed, so the guard can move into
// the spawned task alongside the turn `admit` built.
let Ok(run_guard) = Arc::clone(&self.run_lock).try_lock_owned() else {
return Err(PlayError::TurnStillRunning);
};
let PlayRequest { text, answers } = request;
let (stored, replayed_turn_id) = {
let store = self.store.lock().await;
(store.current().cloned(), store.turn_id_for_key(&key))
};
if let Some(turn_id) = replayed_turn_id {
// PA.f134: the replayed key's own turn, only if it is *still*
// the store's current one and still `AwaitingPlayer` — a replay
// of a key from an already-closed or already-superseded turn has
// no open question to report.
let question = stored
.as_ref()
.filter(|current| current.turn_id == turn_id && current.state == PlayTurnState::AwaitingPlayer)
.and_then(open_question_of);
return Ok(Admission::Replayed { turn_id, question });
}
let (turn, is_new_turn) = match stored {
Some(existing) if existing.state == PlayTurnState::AwaitingPlayer => {
let open_question = existing.open_question_id();
match (answers, open_question.clone()) {
(Some(given), Some(open)) if given == open => {
if text.trim().is_empty() {
// Refused before anything is recorded (PA.f65):
// the question stays open, the key is never
// marked applied, and nothing about the stored
// turn changes. PA.f134: the refusal carries the
// same still-open question the caller was
// already answering.
let question = open_question_of(&existing).expect(
"an EmptyAnswer refusal is only reached once open_question_id() already matched",
);
return Err(PlayError::EmptyAnswer {
turn_id: existing.turn_id.clone(),
question,
});
}
(self.answer_turn(existing, key, text), false)
}
// A missing or mismatched `answers` is refused as stale
// (PA.f84): a late retry naming an old question must
// never land on whatever question happens to be open now.
// PA.f134: carries the turn's own *actually* open
// question (from `open_question`, computed before the
// match consumed it), so the caller can retry against it.
_ => {
return Err(PlayError::StaleAnswer {
turn_id: existing.turn_id.clone(),
question: open_question.map(|id| OpenQuestion {
id,
text: existing.question.clone().unwrap_or_default(),
surface_version: existing.question_surface_version.unwrap_or(0),
}),
});
}
}
}
Some(existing) if existing.state == PlayTurnState::Running => {
if answers.is_some() {
return Err(PlayError::NoQuestionOpen);
}
if text.trim().is_empty() {
(self.continue_turn(existing, key), false)
} else {
return Err(PlayError::TurnStillRunning);
}
}
_ => {
if answers.is_some() {
return Err(PlayError::NoQuestionOpen);
}
// PA.f108: no turn is open to continue (none at all, or the
// current one is `Closed`), so this text opens a fresh one —
// and a fresh turn needs the player's own words, not an
// empty or whitespace-only prompt that would run a full
// inference over nothing said.
if text.trim().is_empty() {
return Err(PlayError::EmptyOpening);
}
(self.begin_turn(key, text).await?, true)
}
};
if is_new_turn {
self.store.lock().await.open_new_turn(turn.clone())?;
} else {
self.persist(&turn).await?;
}
Ok(Admission::Spawn(Admitted { turn, _run_guard: run_guard }))
}
/// Cut 10 (PA.f153/PA.f154): the round loop `run` used to run inline —
/// the part that can spend a real inference budget across up to
/// `ROUND_BUDGET` rounds. `runtime.rs::execute_world`'s `world.play`
/// route spawns this, never `admit`, so an admission refusal is never
/// silently swallowed behind an already-sent `accepted` response.
pub(crate) async fn execute(
&self,
admitted: Admitted,
principal: &VerifiedPrincipalEvidence,
) -> Result<RunOutcome, PlayError> {
let Admitted { mut turn, _run_guard } = admitted;
loop {
match turn.state {
PlayTurnState::AwaitingPlayer | PlayTurnState::Closed => break,
PlayTurnState::Running => {}
}
let round = turn.rounds.len().saturating_sub(1);
let round_is_open = !turn.rounds.is_empty() && round_incomplete(&turn, round);
if round_is_open {
match self.execute_round(&mut turn, round, principal).await? {
RoundOutcome::Continue => {
self.persist(&turn).await?;
continue;
}
RoundOutcome::AwaitingPlayer | RoundOutcome::Closed => {
self.persist(&turn).await?;
break;
}
RoundOutcome::Poisoned => {
// `execute_round` has already closed `turn` and
// recorded the fault (PA.f66b): this door only marks
// the table poisoned and persists that state.
self.poisoned.store(true, Ordering::SeqCst);
self.persist(&turn).await?;
return Err(PlayError::Poisoned);
}
}
}
if turn.rounds.len() >= ROUND_BUDGET {
// The round budget is exhausted (PA.f66a): the turn closes
// and narrates through the same door `end_turn` uses, rather
// than being left open with nothing said. A snapshot or
// narrate failure inside `close_turn` still closes the turn,
// with the fault recorded, through `close_with_fault`
// (PA.f85/PA.f93).
match self.close_turn(&turn, principal).await {
Ok(narration) => {
turn.narration = Some(narration);
turn.state = PlayTurnState::Closed;
self.persist(&turn).await?;
}
Err(error) => self.close_with_fault(&mut turn, error.to_string()).await?,
}
break;
}
let round = turn.rounds.len();
match self.infer_round(&turn, round, principal).await {
Ok(output) => {
turn.rounds.push(output);
self.persist(&turn).await?;
}
Err(detail) => {
// PA.f85/PA.f93/PA.f94: a request-build failure, an
// inference fault whose own disposition never retries
// (`RecoveryRequired`/`IntegrityViolation`), or a
// `Retryable` fault that exhausted its retry budget, all
// close the turn with the fault recorded through the one
// shared door, rather than leaving it `Running`.
self.close_with_fault(&mut turn, detail).await?;
break;
}
}
}
// PA.f134: names the turn and, when the loop left it `AwaitingPlayer`,
// the question it is now waiting on — the same value `run`'s own
// `AwaitingPlayer` branches above already derive from `turn`, read
// once more here since `turn` was moved through the loop by value.
let question = open_question_of(&turn);
Ok(RunOutcome::Ran {
turn_id: turn.turn_id.clone(),
question,
})
}
/// The current turn's own player-facing state (PA.f134): its id, state,
/// open question (if any), last narration, and most recent refusal line
/// — everything a consumer needs to answer an open question or observe
/// what a turn did, without reading the store directly. `world.play`'s
/// own route spawns `run` in a task and answers `{"kind":"accepted"}`
/// before that call resolves, so nothing from a `run` call's own return
/// value ever reaches the caller that made it; this is the door a later,
/// separate read goes through instead. `None` when no turn has ever
/// opened on this table.
pub(crate) async fn current_turn_view(&self) -> Option<PlayTurnView> {
let store = self.store.lock().await;
let turn = store.current()?;
Some(PlayTurnView {
turn_id: turn.turn_id.clone(),
state: turn.state,
question: open_question_of(turn),
narration: turn.narration.clone(),
refusal: turn.refusal.clone(),
revision: store.state.revision,
})
}
/// Opens a fresh turn. Takes no principal (PA.f95: the parameter was
/// never read) — the player's own subject is resolved per-round from the
/// live snapshot, not from the caller's own evidence.
async fn begin_turn(&self, key: String, text: String) -> Result<PlayTurn, PlayError> {
let snapshot = self.play.snapshot().await?;
let opening_prompt = format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
text
);
Ok(PlayTurn {
turn_id: uuid::Uuid::new_v4().to_string(),
applied_keys: vec![key],
opening_prompt,
player_prose: vec![text],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
})
}
/// Applies the player's own answer to the currently open question,
/// already checked by `run` to name that question's own `QuestionId`.
fn answer_turn(&self, mut turn: PlayTurn, key: String, text: String) -> PlayTurn {
turn.applied_keys.push(key);
turn.player_prose.push(text.clone());
let round = turn.rounds.len().saturating_sub(1);
if let Some(slot) = find_ask_player_slot(&turn, round) {
if let Some(record) = turn.call_record_mut(round, slot) {
record.result = Some(text);
}
}
turn.question = None;
turn.question_surface_version = None;
turn.state = PlayTurnState::Running;
turn
}
/// A plain continue of a `Running` turn under a fresh key: nothing about
/// the turn's own record changes beyond the key itself (PA.f84).
fn continue_turn(&self, mut turn: PlayTurn, key: String) -> PlayTurn {
turn.applied_keys.push(key);
turn
}
/// Closes `turn` with `detail` as its recorded fault and persists it:
/// the one door every failure reachable only after a turn has already
/// opened goes through (PA.f85/PA.f93) — a request-build failure, a
/// snapshot or narrate failure, an inference fault whose disposition
/// does not retry or that exhausted its retry budget, or a kernel
/// `Invariant` fault. Distinct from poisoning the whole table: that
/// stays each caller's own decision (`RoundOutcome::Poisoned`), because
/// this helper only ever writes the one turn's own record.
async fn close_with_fault(&self, turn: &mut PlayTurn, detail: String) -> Result<(), PlayError> {
turn.state = PlayTurnState::Closed;
turn.fault = Some(detail);
// PA.f173: a fault can close a turn that was `AwaitingPlayer`, and
// `answer_turn` is not the only door out of that state — clear the
// open question here too, the same way `answer_turn` does, so a
// closed turn never carries a question record alongside it. This was
// unobservable before this fix only because `open_question_id` gates
// on `state == AwaitingPlayer`, which a fault always leaves behind by
// setting `state = Closed` in the same write.
turn.question = None;
turn.question_surface_version = None;
self.persist(turn).await
}
/// Runs one round's own inference to completion, or returns the fault
/// detail the caller closes the turn with (PA.f85/PA.f93/PA.f94): a
/// request-build failure (the snapshot, `round_tools`, or
/// `InferenceRequest::play` itself), or an `InferenceFault` whose own
/// disposition does not retry, or that exhausted its bounded retry
/// budget.
async fn infer_round(
&self,
turn: &PlayTurn,
round: usize,
principal: &VerifiedPrincipalEvidence,
) -> Result<InferenceOutput, String> {
let snapshot = self.round_snapshot().await?;
let dispatched = turn.dispatched_subjects();
let tools = self.round_tools(&snapshot, &dispatched, principal)?;
let conversation = rebuild_conversation(turn, round);
let command_id = CommandId::parse_uuid(&turn.turn_id).map_err(|error| error.to_string())?;
let mut attempt = 0usize;
loop {
let request = InferenceRequest::play(
command_id,
round,
&self.model,
PLAY_INSTRUCTIONS,
conversation.clone(),
tools.clone(),
PLAY_MAX_OUTPUT_TOKENS,
)
.map_err(|error| error.to_string())?;
let prepared = match self.inference.prepare(request) {
Ok(prepared) => prepared,
Err(fault) => {
self.absorb_or_close(fault, &mut attempt).await?;
continue;
}
};
match self.inference.infer(prepared).await {
Ok(output) => return Ok(output),
Err(fault) => {
self.absorb_or_close(fault, &mut attempt).await?;
continue;
}
}
}
}
/// One inference fault's own disposition decides its fate (PA.f94): only
/// `Retryable` retries at all, bounded by `ROUND_RETRY_BUDGET` and a
/// small capped exponential backoff (`retry_delay`, zero under test);
/// `RecoveryRequired` and `IntegrityViolation` never retry, closing on
/// their first occurrence — retrying either again cannot succeed
/// differently. `Ok(())` means the caller's loop should try again;
/// `Err(detail)` is the fault's own detail text, to close the turn with.
async fn absorb_or_close(&self, fault: InferenceFault, attempt: &mut usize) -> Result<(), String> {
match fault.disposition() {
InferenceFaultDisposition::Retryable if *attempt < ROUND_RETRY_BUDGET => {
let delay = self.retry_delay(*attempt);
*attempt += 1;
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
Ok(())
}
InferenceFaultDisposition::Retryable
| InferenceFaultDisposition::RecoveryRequired
| InferenceFaultDisposition::IntegrityViolation => Err(fault.to_string()),
}
}
/// A small capped exponential backoff between retries of a `Retryable`
/// inference fault (PA.f94). PA.f122: the base is an ordinary field on
/// the table, not a `#[cfg(test)]` swap over the formula itself —
/// production and test both run `backoff_delay` (below, a free function,
/// compiled and directly unit-testable in every build), over the exact
/// same code path, differing only in the base a test explicitly sets
/// through `set_retry_delay_base_ms` (PA.f94's own zero delay, so a test
/// never actually sleeps).
fn retry_delay(&self, attempt: usize) -> Duration {
backoff_delay(self.retry_delay_base_ms.load(Ordering::Relaxed), attempt)
}
/// Sets the base `backoff_delay` scales from. Test-only: no production
/// call site exists, matching `set_before_submit_hook`'s own shape — the
/// field itself stays ordinary and always compiled so production and
/// test run the identical `retry_delay`/`backoff_delay` code path.
#[cfg(test)]
pub(crate) fn set_retry_delay_base_ms(&self, base_ms: u64) {
self.retry_delay_base_ms.store(base_ms, Ordering::Relaxed);
}
/// The one owner of round entry (PA.f127/PA.f133): fetches the live
/// snapshot and runs the handle-collision check exactly once, for
/// whichever caller is opening this round — `infer_round`, before
/// deciding the round's own tools, and `execute_round`, before resolving
/// a resumed round's already-decided calls. Both used to fetch their own
/// snapshot and run `collision_refusal` independently, which is two
/// owners for one rule; this is the one.
async fn round_snapshot(&self) -> Result<WorldSnapshot, String> {
let snapshot = self.fetch_round_snapshot().await?;
if let Some(refusal) = collision_refusal(&snapshot) {
return Err(refusal);
}
Ok(snapshot)
}
/// The live fetch `round_snapshot` checks. Test-only: a forced snapshot,
/// when set through `force_round_snapshot`, stands in for the kernel's
/// own — the one seam this crate has for driving a *genuine*, real-id
/// handle collision through `round_snapshot` itself, matching
/// `before_submit_hook`'s and `set_retry_delay_base_ms`'s own shape. No
/// production call site ever sets it.
#[cfg(test)]
async fn fetch_round_snapshot(&self) -> Result<WorldSnapshot, String> {
if let Some(forced) = self.forced_round_snapshot.lock().unwrap().clone() {
return Ok(forced);
}
self.play.snapshot().await.map_err(|error| error.to_string())
}
#[cfg(not(test))]
async fn fetch_round_snapshot(&self) -> Result<WorldSnapshot, String> {
self.play.snapshot().await.map_err(|error| error.to_string())
}
/// Test-only: see `fetch_round_snapshot`. No production call site exists.
#[cfg(test)]
fn force_round_snapshot(&self, snapshot: WorldSnapshot) {
*self.forced_round_snapshot.lock().unwrap() = Some(snapshot);
}
fn round_tools(
&self,
snapshot: &WorldSnapshot,
dispatched: &[SubjectId],
principal: &VerifiedPrincipalEvidence,
) -> Result<Vec<CodexToolDefinition>, String> {
let mut tools = authoring_tools(PLAY_TOOLS).map_err(|error| error.to_string())?;
tools.extend(control_tools());
let Some(player) = player_subject(snapshot, principal) else {
return Ok(tools);
};
let mut player_tools = actor_tools(&actor_prefix(player.id), snapshot, player.id);
annotate_actor_tools(&mut player_tools, snapshot, player.id);
tools.extend(player_tools);
for subject in dispatched {
let mut subject_tools = actor_tools(&actor_prefix(*subject), snapshot, *subject);
annotate_actor_tools(&mut subject_tools, snapshot, *subject);
tools.extend(subject_tools);
}
Ok(tools)
}
/// Executes every call in `round` that has not yet resolved, in order.
async fn execute_round(
&self,
turn: &mut PlayTurn,
round: usize,
principal: &VerifiedPrincipalEvidence,
) -> Result<RoundOutcome, PlayError> {
let output = turn.rounds[round].clone();
// PA.f103, PA.f118, PA.f127/PA.f133: this door's own `close_with_fault`
// still calls `persist` under the hood, so a failure right here has no
// lower layer left to record it in — it propagates through the `?` on
// `close_with_fault`'s own `Result` instead of being written into the
// turn, which is exactly the failure that would need writing.
// `round_snapshot` failing here *is* covered, by
// `a_snapshot_failure_mid_round_closes_with_the_fault_recorded` below
// (a live fetch failure) and by the forced-collision tests below (the
// handle-collision refusal): a round resumed after a crash executes
// its already-decided calls through this door directly, never through
// `round_tools` at all, so the same one owner both a fresh round and a
// resumed one share must run here too, rather than resolving calls
// against a handle that no longer names one subject unambiguously.
let snapshot = match self.round_snapshot().await {
Ok(snapshot) => snapshot,
Err(detail) => {
self.close_with_fault(turn, detail).await?;
return Ok(RoundOutcome::Closed);
}
};
let player = player_subject(&snapshot, principal);
// Slotted, unresolved tool calls only: `slot` must still count a
// call this loop skips as already resolved, so slot numbering never
// shifts between a round's first pass and its resumed one.
let mut calls: Vec<(usize, &str, &str, &str)> = Vec::new();
let mut slot = 0usize;
for event in output.events() {
let InferenceEvent::ToolCall {
call_id,
name,
arguments,
} = event
else {
continue;
};
let this_slot = slot;
slot += 1;
if turn
.call_record(round, this_slot)
.is_some_and(|call| call.result.is_some())
{
continue;
}
calls.push((this_slot, call_id.as_str(), name.as_str(), arguments.as_str()));
}
let mut index = 0usize;
while index < calls.len() {
let (this_slot, call_id, name, arguments) = calls[index];
// A maximal run of consecutive authoring calls commits together
// as one shared patch under one command id (PA.f54): actor calls
// and table tools break a run.
if PLAY_TOOLS.contains(&name) {
let mut run = Vec::new();
while index < calls.len() && PLAY_TOOLS.contains(&calls[index].2) {
let (slot, call_id, name, arguments) = calls[index];
run.push((slot, call_id.to_owned(), name.to_owned(), arguments.to_owned()));
index += 1;
}
let results = self.commit_authoring_run(turn, round, &run, &snapshot).await?;
let mut fault = None;
for (slot, call_id, outcome, result) in results {
if matches!(outcome, RoundOutcome::Poisoned) {
fault = Some(result.clone());
}
record_call(turn, &call_id, round, slot, None, Some(result));
}
self.persist(turn).await?;
if let Some(detail) = fault {
// PA.f66b: a kernel `Invariant` fault closes the turn
// with the fault recorded, not left `Running`.
self.close_with_fault(turn, detail).await?;
return Ok(RoundOutcome::Poisoned);
}
continue;
}
index += 1;
if name == END_TURN_TOOL {
record_call(turn, call_id, round, this_slot, Some(RecordedCall::EndTurn), None);
match self.close_turn(turn, principal).await {
Ok(narration) => {
if let Some(record) = turn.call_record_mut(round, this_slot) {
record.result = Some("the turn ended".to_owned());
}
turn.narration = Some(narration);
turn.state = PlayTurnState::Closed;
}
Err(error) => {
// PA.f85/PA.f93: a narrate failure still closes the
// turn, with the fault recorded, rather than leaving
// it stuck `Running` behind a `?`.
self.close_with_fault(turn, error.to_string()).await?;
}
}
return Ok(RoundOutcome::Closed);
}
if name == ASK_PLAYER_TOOL {
let question = parse_ask_player(arguments);
record_call(
turn,
call_id,
round,
this_slot,
Some(RecordedCall::AskPlayer(question.clone())),
None,
);
turn.question = Some(question);
// PA.f161/PA.f175: the world's own surface version at the
// instant this question opens, so a later answer is judged
// against the version the question actually first appeared
// on, never whatever the world's version happens to be when
// the answer arrives. This must be a fresh snapshot taken
// right here, not the round-entry `snapshot` above: a round
// that authors (a `PLAY_TOOLS` run, committed earlier in this
// same `while` loop) and then asks would otherwise record the
// version as of before its own commits, not the version the
// question actually opened on.
let question_snapshot = match self.fetch_round_snapshot().await {
Ok(snapshot) => snapshot,
Err(detail) => {
self.close_with_fault(turn, detail).await?;
return Ok(RoundOutcome::Closed);
}
};
turn.question_surface_version =
Some(crate::eve::surface_version(Some(&question_snapshot)));
turn.state = PlayTurnState::AwaitingPlayer;
return Ok(RoundOutcome::AwaitingPlayer);
}
if name == DISPATCH_TOOL {
// PA.f136: the recorded body decides, exactly like every
// other door's own `recorded` match
// (`commit_authoring_run`/`execute_advance_time`/
// `execute_actor_call`) — a resumed call resubmits its own
// already-recorded subjects, never a value `parse_dispatch`
// re-derives against whatever the live snapshot now says.
// Before this, `subjects`/`refusals` were re-parsed against
// the *current* snapshot on every pass, recorded body or not:
// if the world changed between the crash and the resume so a
// dispatched subject no longer resolved (a retirement), the
// resumed call ran a shorter list and the record below
// silently overwrote the original `RecordedCall::Dispatch`
// with that shorter one — losing the subject from
// `dispatch_owner`/`dispatched_subjects` for the rest of the
// turn even though `persona_turns` still carried her prose.
let recorded = turn.call_record(round, this_slot).and_then(|call| call.body.clone());
let (subjects, refusals) = match recorded {
Some(RecordedCall::Dispatch(subjects)) => (subjects, Vec::new()),
_ => {
let (subjects, refusals) = parse_dispatch(arguments, &snapshot);
// PA.f125: this call's own body — which subjects it
// intends to dispatch — is recorded and persisted
// before `execute_dispatch` runs any persona turn,
// the same "body durable before effects" order every
// other door already uses (PA-Q8, `persist`'s own
// doc comment). Without this, a crash between
// `execute_dispatch`'s own per-subject persist and
// this call's own record here left `persona_turns`
// durable with no call record naming it; a resume
// then mistook the already-durable Persona turn for
// a *different* call's completed dispatch ("already
// acted"), and the Persona's own prose never reached
// the agent (PA.f64).
record_call(
turn,
call_id,
round,
this_slot,
Some(RecordedCall::Dispatch(subjects.clone())),
None,
);
self.persist(turn).await?;
(subjects, refusals)
}
};
self.fire_before_submit_hook().await;
let (outcome, dispatch_summary) =
self.execute_dispatch(turn, round, this_slot, &subjects).await?;
// PA.f98, PA.f114: bad input — an unknown id, a non-string
// entry, a malformed body, or a missing `subjects` key — is
// refused in the tool result, quoting what was given, never
// dropped silently.
let result = if refusals.is_empty() {
dispatch_summary
} else {
let refusals = refusals.join("; ");
if dispatch_summary.is_empty() {
refusals
} else {
format!("{dispatch_summary}; {refusals}")
}
};
record_call(
turn,
call_id,
round,
this_slot,
Some(RecordedCall::Dispatch(subjects)),
Some(result),
);
if matches!(outcome, RoundOutcome::Closed) {
// PA.f85/PA.f93: `execute_dispatch` already closed the
// turn with its fault recorded, mid-loop; nothing later
// in this round resolves.
return Ok(RoundOutcome::Closed);
}
continue;
}
if name == ADVANCE_TIME_TOOL {
let (outcome, result) = self
.execute_advance_time(turn, call_id, round, this_slot, arguments)
.await?;
let fault = matches!(outcome, RoundOutcome::Poisoned).then(|| result.clone());
record_call(turn, call_id, round, this_slot, None, Some(result));
self.persist(turn).await?;
if let Some(detail) = fault {
self.close_with_fault(turn, detail).await?;
return Ok(RoundOutcome::Poisoned);
}
continue;
}
// `<handle>__<kind>` actor call: `handle` alone picks the actor
// (Dungeon's own vocabulary — the library owns no notion of
// which subject was dispatched this turn); the full `name` is
// then handed to `execute_actor_call` unstripped, so the
// library's own `decode_actor_call` owns the prefix strip.
if let Some((handle, _)) = name.split_once(HANDLE_SEPARATOR) {
// PA.f104: derived fresh from the turn's own record right
// here, on every actor call, rather than snapshotted once
// before this loop began — an earlier call in this same
// round's own call order (including a dispatch this round
// already executed) must make its subject's actor tools
// valid on the first pass exactly as it does on a resume,
// since a resume recomputes this same derivation from the
// same persisted record and would otherwise disagree.
let dispatched = turn.dispatched_subjects();
let actor = resolve_handle(handle, player.as_ref(), &dispatched);
let Some(actor) = actor else {
record_call(
turn,
call_id,
round,
this_slot,
None,
Some(format!("`{handle}` is not the player or a subject dispatched this turn")),
);
continue;
};
let (outcome, result) = self
.execute_actor_call(
turn, call_id, round, this_slot, actor, name, arguments, &snapshot, principal,
)
.await?;
let fault = matches!(outcome, RoundOutcome::Poisoned).then(|| result.clone());
record_call(turn, call_id, round, this_slot, None, Some(result));
self.persist(turn).await?;
if let Some(detail) = fault {
self.close_with_fault(turn, detail).await?;
return Ok(RoundOutcome::Poisoned);
}
continue;
}
record_call(
turn,
call_id,
round,
this_slot,
None,
Some(format!("`{name}` is not a tool this table offers")),
);
}
Ok(RoundOutcome::Continue)
}
/// One maximal run of consecutive authoring calls (PA.f54): inside one
/// round, a run of authoring calls with no actor call or table tool
/// between them decodes as one shared patch, through the library's own
/// `decode_authoring_calls`, and commits atomically under one command id
/// derived from the run's own first (anchor) slot. A draft handle a
/// call in the run declares resolves against a later call in the same
/// run, because every call's item lands in that one shared `WorldPatch`
/// before any of it is submitted.
///
/// PA.f61: a run whose shared patch would rewrite an existing subject's
/// persona material is refused whole — `WorldPatch::sets_persona_of_existing_subject`
/// is the one read-only query the library exposes for this, because
/// `WorldPatch`'s own fields are `pub(crate)` and Dungeon may not parse
/// its JSON to decide the question itself. `set_persona_material` still
/// stands for a subject this same run's own `declare_subject` call
/// declares (a `Ref::Draft`, not `Ref::Existing`).
async fn commit_authoring_run(
&self,
turn: &mut PlayTurn,
round: usize,
run: &[(usize, String, String, String)],
snapshot: &WorldSnapshot,
) -> Result<Vec<(usize, String, RoundOutcome, String)>, PlayError> {
let anchor_slot = run[0].0;
let anchor_call_id = run[0].1.clone();
let recorded = turn.call_record(round, anchor_slot).and_then(|call| call.body.clone());
let (patch, batch) = match recorded {
Some(RecordedCall::Authoring(patch)) => (patch, None),
_ => {
let calls: Vec<(&str, &str)> =
run.iter().map(|(_, _, name, arguments)| (name.as_str(), arguments.as_str())).collect();
let decoded = match decode_authoring_calls(&calls) {
Ok(decoded) => decoded,
Err(detail) => return Ok(refuse_run(run, format!("refused: {detail}"))),
};
if decoded.patch.sets_persona_of_existing_subject() {
return Ok(refuse_run(
run,
"refused: set_persona_material may not target an existing subject; \
only a subject this same run declares"
.to_owned(),
));
}
record_call(
turn,
&anchor_call_id,
round,
anchor_slot,
Some(RecordedCall::Authoring(decoded.patch.clone())),
None,
);
self.persist(turn).await?;
let patch = decoded.patch.clone();
(patch, Some(decoded))
}
};
let command_id = derived_command_id(&turn.turn_id, round, anchor_slot);
self.fire_before_submit_hook().await;
let (outcome, result) = match self.play.submit_patch(command_id, patch).await {
Ok(_receipt) => (RoundOutcome::Continue, "applied".to_owned()),
Err(MailboxError::Kernel(KernelError::Invariant(detail))) => (RoundOutcome::Poisoned, detail),
Err(MailboxError::Kernel(kernel_error @ KernelError::PatchRejected(_))) => {
// PA.f54: the batch's own site map names the exact call a
// mismatch belongs to, when one decoded this call (a resumed
// resubmission has no fresh `DecodedBatch` and falls back to
// `describe_refusal`'s own raw-index wording).
let text = describe_refusal(snapshot, None, None, batch.as_ref(), &kernel_error);
(RoundOutcome::Continue, format!("refused: {text}"))
}
Err(error) => (RoundOutcome::Continue, format!("refused: {error}")),
};
Ok(run
.iter()
.map(|(slot, call_id, _, _)| (*slot, call_id.clone(), outcome, result.clone()))
.collect())
}
/// Persists `turn` to the store: the one durable-write door every
/// `execute_*`/`commit_*` method uses to record a call's body *before*
/// attempting its submission (PA-Q8), so a crash between the two leaves
/// the exact submitted body on disk for `execute_round` to resubmit on
/// resume.
async fn persist(&self, turn: &PlayTurn) -> Result<(), PlayError> {
self.store.lock().await.commit(turn.clone())?;
Ok(())
}
async fn execute_advance_time(
&self,
turn: &mut PlayTurn,
call_id: &str,
round: usize,
slot: usize,
arguments: &str,
) -> Result<(RoundOutcome, String), PlayError> {
let recorded = turn.call_record(round, slot).and_then(|call| call.body.clone());
let minutes = match recorded {
Some(RecordedCall::AdvanceTime(minutes)) => minutes,
_ => match parse_minutes(arguments) {
Some(minutes) => {
record_call(turn, call_id, round, slot, Some(RecordedCall::AdvanceTime(minutes)), None);
self.persist(turn).await?;
minutes
}
None => {
return Ok((
RoundOutcome::Continue,
"refused: minutes must be a positive integer within bounds".to_owned(),
));
}
},
};
let command_id = derived_command_id(&turn.turn_id, round, slot);
self.fire_before_submit_hook().await;
match self.play.advance_time(command_id, minutes).await {
Ok(_) => Ok((RoundOutcome::Continue, "the clock advanced".to_owned())),
Err(MailboxError::Kernel(KernelError::Invariant(detail))) => Ok((RoundOutcome::Poisoned, detail)),
Err(error) => Ok((RoundOutcome::Continue, format!("refused: {error}"))),
}
}
async fn execute_actor_call(
&self,
turn: &mut PlayTurn,
call_id: &str,
round: usize,
slot: usize,
actor: Actor,
name: &str,
arguments: &str,
snapshot: &WorldSnapshot,
principal: &VerifiedPrincipalEvidence,
) -> Result<(RoundOutcome, String), PlayError> {
let recorded = turn.call_record(round, slot).and_then(|call| call.body.clone());
let (opportunity, invocation) = match recorded {
Some(RecordedCall::PlayerAct(opportunity, invocation)) => (opportunity, invocation),
Some(RecordedCall::PersonaAct(_, opportunity, invocation)) => (opportunity, invocation),
_ => {
// The real handle prefix `round_tools` handed `actor_tools`
// when it generated this actor's own tools, paired with the
// full, unstripped call `name`, so `decode_actor_call`'s own
// prefix strip is the one and only place that decides what
// the prefix removes.
let prefix = actor_prefix(actor.subject);
let (opportunity, invocation) =
match decode_actor_call(snapshot, actor.subject, &prefix, name, arguments) {
Ok(decoded) => decoded,
Err(detail) => {
return Ok((RoundOutcome::Continue, format!("refused: {detail}")));
}
};
if !span_is_exact(&invocation, &actor, turn) {
return Ok((
RoundOutcome::Continue,
"refused: the quoted text is not an exact quote from the acting subject's own prose"
.to_owned(),
));
}
let body = if actor.is_player {
RecordedCall::PlayerAct(opportunity.clone(), invocation.clone())
} else {
RecordedCall::PersonaAct(actor.subject, opportunity.clone(), invocation.clone())
};
record_call(turn, call_id, round, slot, Some(body), None);
self.persist(turn).await?;
(opportunity, invocation)
}
};
let command_id = derived_command_id(&turn.turn_id, round, slot);
self.fire_before_submit_hook().await;
let submission = if actor.is_player {
self.world
.submit_principal(
PrincipalCommandIntent {
id: command_id,
world_id: opportunity.world_id,
expected_revision: 0,
body: CommandBody::ExerciseDecision {
opportunity: opportunity.clone(),
invocation: invocation.clone(),
},
},
principal,
)
.await
} else {
ControllerPort::new(self.world.clone())
.submit_controller(command_id, &opportunity, invocation.clone())
.await
};
match submission {
Ok(_) => {
// PA.f144: `turn.refusal` names the *most recent* player
// act's own refusal (invariant 8's actor-facing line) — a
// player act that now commits clears whatever an earlier
// round's refusal left standing, so a round-1 refusal is not
// still shown once a later act of the same player's own
// succeeds. A Persona's own act never set it, so this clears
// nothing a Persona commit should not touch either way.
if actor.is_player {
turn.refusal = None;
}
Ok((RoundOutcome::Continue, "applied".to_owned()))
}
Err(MailboxError::Kernel(KernelError::ActionRejected(mismatches))) => {
let error = KernelError::ActionRejected(mismatches);
// The entry the invocation actually named: found on the live
// snapshot alone, never from anything the caller supplied,
// matching `subject_opportunity`'s own rule that a consumer's
// claimed affordance is never trusted back.
let entry = snapshot
.affordances
.iter()
.find(|candidate| candidate.id == invocation.affordance);
// The agent's own surface: full detail, for the play agent to
// reason with.
let text = describe_refusal(snapshot, entry, Some(&invocation), None, &error);
if actor.is_player {
// Invariant 8: the player sees only the actor form —
// `describe_refusal_to_actor` names bare role names, never
// an id, a resolved label, or a fact's statement. A
// missing `entry` (which decode_actor_call's own success
// should make impossible) falls back to the same bare
// "refused" `describe_refusal_to_actor` itself uses for
// every non-`ActionRejected` error, rather than leaking
// the agent-facing text.
let actor_text = match entry {
Some(entry) => describe_refusal_to_actor(entry, &error),
None => "refused".to_owned(),
};
turn.refusal = Some(actor_text);
}
Ok((RoundOutcome::Continue, format!("refused: {text}")))
}
Err(MailboxError::Kernel(KernelError::Invariant(detail))) => Ok((RoundOutcome::Poisoned, detail)),
Err(error) => Ok((RoundOutcome::Continue, format!("refused: {error}"))),
}
}
async fn execute_dispatch(
&self,
turn: &mut PlayTurn,
round: usize,
call_slot: usize,
subjects: &[SubjectId],
) -> Result<(RoundOutcome, String), PlayError> {
// PA.f125: snapshotted before this call's own subjects run, so a
// subject *this* call adds to `persona_turns` later in this same
// loop (the same subject named twice in one `dispatch` call,
// PA.f124) is never mistaken for a subject this call is *resuming*
// after a crash — only a subject already durable *before* this
// invocation began can be that.
let already_durable: Vec<SubjectId> = turn.persona_turns.iter().map(|(id, _)| *id).collect();
// Indexed by the subject's own position in `subjects` (not the order
// any of this resolves in): every subject gets exactly one summary
// line, and the joined summary must read in the call's own JSON
// order whether that subject's line was decided synchronously below
// or by a concurrently dispatched Persona turn later.
let mut summary_slots: Vec<Option<String>> = vec![None; subjects.len()];
let finished_summary = |slots: Vec<Option<String>>| slots.into_iter().flatten().collect::<Vec<_>>().join("; ");
/// One subject this call still needs a fresh Persona turn for,
/// carrying everything `personas.turn` and its own summary line
/// need — captured now, at the same point the old sequential loop
/// captured them, so concurrent dispatch changes nothing about
/// *which* snapshot or opportunity a subject's turn runs against.
struct Pending {
index: usize,
subject: SubjectId,
command_id: CommandId,
opportunity: DecisionOpportunity,
snapshot: WorldSnapshot,
}
let mut pending: Vec<Pending> = Vec::new();
// PA.f124: the same subject named twice in *this* call's own subject
// list is a collision even though neither occurrence has landed in
// `turn.persona_turns` yet — concurrent dispatch means both
// occurrences are seen before either one's Persona turn has run, so
// `turn.persona_turns` alone can no longer tell them apart the way
// the old strictly-sequential loop could (a first occurrence used to
// land in `turn.persona_turns` before the second was even read).
// This is the within-call twin of that same check.
let mut claimed_this_call: Vec<SubjectId> = Vec::new();
for (index, subject) in subjects.iter().enumerate() {
if let Some(prose) = turn
.persona_turns
.iter()
.find(|(id, _)| id == subject)
.map(|(_, persona_turn)| persona_turn.source_prose().to_owned())
{
let resuming_this_call =
already_durable.contains(subject) && turn.dispatch_owner(*subject) == Some((round, call_slot));
if resuming_this_call {
// PA.f125: this call's own body is already durable
// before any persona turn ran (`execute_round` records
// and persists it before this door is entered), so a
// crash between one subject's own persist and this
// call's own final result finds its own prose here on
// resume, rather than refusing it as "already acted"
// against a call that never actually completed.
let snapshot = match self.play.snapshot().await {
Ok(snapshot) => snapshot,
Err(error) => {
self.close_with_fault(turn, error.to_string()).await?;
return Ok((RoundOutcome::Closed, finished_summary(summary_slots)));
}
};
let label = subject_label(&snapshot, *subject);
summary_slots[index] = Some(format!("{label}: {prose}"));
} else {
// PA.f124: printed through the library's own `id_text`,
// the same printer `table_view` and `dispatch`'s own
// matching use — not a fifth hand-spelled debug-paren
// strip.
summary_slots[index] = Some(format!("{} already acted", id_text(*subject)));
}
continue;
}
if claimed_this_call.contains(subject) {
// PA.f124: a repeat within this same call's own list, ahead
// of its own first occurrence's Persona turn actually
// resolving — the same "already acted" text the sequential
// loop gave a repeat once its first occurrence had already
// landed in `turn.persona_turns`.
summary_slots[index] = Some(format!("{} already acted", id_text(*subject)));
continue;
}
let snapshot = match self.play.snapshot().await {
Ok(snapshot) => snapshot,
Err(error) => {
// PA.f85/PA.f93: a snapshot failure mid-dispatch still
// closes the turn with the fault recorded, rather than
// leaving it `Running` behind a `?`.
self.close_with_fault(turn, error.to_string()).await?;
return Ok((RoundOutcome::Closed, finished_summary(summary_slots)));
}
};
let Some(opportunity) = snapshot
.opportunities
.iter()
.find(|opportunity| {
opportunity.scope.subject_id == *subject
&& opportunity.controller_mode == ControllerMode::NarrativePersona
})
.cloned()
else {
summary_slots[index] = Some(format!("{} holds no live Persona opportunity", id_text(*subject)));
continue;
};
// Derived from the dispatch call's own slot and the subject, not
// from the subject's position in this call's own JSON array
// (PA.f66d): two subjects named by one dispatch call, or the
// same subject named by two dispatch calls in one round, must
// never collide, in whatever order either call lists them.
let command_id = dispatch_command_id(&turn.turn_id, round, call_slot, *subject);
claimed_this_call.push(*subject);
pending.push(Pending {
index,
subject: *subject,
command_id,
opportunity,
snapshot,
});
}
// The round's own freshly dispatched Personas run concurrently
// (PA.f13, P8.5): each spawned task draws its own permit from the
// shared `controller_permits` pool before it runs `personas.turn`,
// so the pool's own size bounds how many run cognition at once, not
// this call's own subject count. Spawned, not merely joined, so
// Tokio actually schedules every pending subject's turn as soon as
// its permit is free rather than only interleaving at await points
// inside one task.
let mut handles = Vec::with_capacity(pending.len());
for entry in &pending {
let personas = self.personas.clone();
let permits = self.permits.clone();
let command_id = entry.command_id;
let opportunity = entry.opportunity.clone();
handles.push(tokio::spawn(async move {
let permit = permits
.acquire_owned()
.await
.expect("permit semaphore is never closed");
let result = personas.turn(command_id, &opportunity).await;
drop(permit);
result
}));
}
let mut results = Vec::with_capacity(handles.len());
for handle in handles {
results.push(
handle
.await
.expect("a dispatched Persona's own turn task never panics"),
);
}
for (entry, result) in pending.into_iter().zip(results) {
match result {
Ok(persona_turn) => {
let label = subject_label(&entry.snapshot, entry.subject);
// PA.f64: the dispatched Persona's own prose reaches the
// agent as this call's own tool result, not a bare
// "acted" acknowledgement — `rebuild_conversation` is
// already generic over every call's recorded `result`,
// so recording the prose here is the whole fix.
let prose = persona_turn.source_prose().to_owned();
summary_slots[entry.index] = Some(format!("{label}: {prose}"));
turn.persona_turns.push((entry.subject, persona_turn));
// PA.f123: `execute_dispatch` was the only call kind that
// did not persist at its own site — every other tool
// call's own door (`commit_authoring_run`,
// `execute_advance_time`, `execute_actor_call`) persists
// its own recorded body before submitting, and
// `execute_round`'s per-call loop persists after every
// *other* branch, but a dispatch call's own `continue`
// reached none of that until the round itself finished.
// A crash between two subjects in one dispatch call, or
// between this dispatch call and the round's own later
// persist, would re-infer this subject's Persona prose
// on resume, and an actor call already checked against
// the recorded prose would be checked against the new
// (possibly different) prose instead — persisting as
// soon as each subject's own prose is recorded closes
// that window. Persisted here, sequentially, after every
// concurrent turn has already resolved, so two subjects'
// own persists of the same turn row never race each
// other's `compare_and_swap_batch`.
self.persist(turn).await?;
self.fire_before_submit_hook().await;
}
Err(error) => {
let label = subject_label(&entry.snapshot, entry.subject);
summary_slots[entry.index] = Some(format!("{label} could not act: {error}"));
}
}
}
Ok((RoundOutcome::Continue, finished_summary(summary_slots)))
}
/// Narrates the turn's own close to the player. Takes no snapshot of its
/// own (PA.f95: it was never read) — it always re-fetches its own fresh
/// snapshot below, since the round's own calls may have committed since
/// any snapshot a caller might have held. Cut 10 (PA.f159) added
/// `principal` back: `player_subject` now resolves the player by whose
/// principal is actually running this turn, not merely "the" human
/// subject in the snapshot.
async fn close_turn(
&self,
turn: &PlayTurn,
principal: &VerifiedPrincipalEvidence,
) -> Result<String, PlayError> {
// A fresh snapshot, not the round's own: this round's calls may have
// committed since it was taken, and `PersonaLane::narrate` refuses
// an opportunity that is not the kernel's own currently issued copy.
let snapshot = self.play.snapshot().await?;
let Some(player) = player_subject(&snapshot, principal) else {
return Ok(String::new());
};
let Some(opportunity) = snapshot
.opportunities
.iter()
.find(|opportunity| {
opportunity.scope.subject_id == player.id
&& opportunity.controller_mode == ControllerMode::Human
})
.cloned()
else {
return Ok(String::new());
};
let command_id = derived_command_id(&turn.turn_id, turn.rounds.len(), usize::MAX);
// Narration is cognition over the same shared pool a dispatched
// Persona's own turn draws from (PA.f13, P8.5): the turn's own close
// must queue behind an exhausted pool exactly like a dispatch would,
// rather than running unmetered because it happens to be the one
// Persona-lane call outside `execute_dispatch`.
let permit = self
.permits
.clone()
.acquire_owned()
.await
.expect("permit semaphore is never closed");
let narration = self.personas.narrate(command_id, &opportunity).await;
drop(permit);
Ok(narration?)
}
}
struct Actor {
subject: SubjectId,
is_player: bool,
}
fn resolve_handle(handle: &str, player: Option<&SubjectRow>, dispatched: &[SubjectId]) -> Option<Actor> {
if let Some(player) = player
&& handle_for(player.id) == handle
{
return Some(Actor {
subject: player.id,
is_player: true,
});
}
for subject in dispatched {
if handle_for(*subject) == handle {
return Some(Actor {
subject: *subject,
is_player: false,
});
}
}
None
}
struct SubjectRow {
id: SubjectId,
}
/// Cut 10 (PA.f159): the subject *this principal's own turn* acts as, not
/// merely "the" human-controlled subject in the world. `WorldSnapshot`
/// already carries `human_controller: Option<PrincipalId>` on every
/// `SubjectSnapshot` (the library's own field, no library change needed);
/// this was the one production reader still ignoring it, matching by
/// `controller_mode` alone — correct only by accident, in the one-human-
/// subject worlds every fixture happens to build, and wrong the moment a
/// world has more than one.
fn player_subject(snapshot: &WorldSnapshot, principal: &VerifiedPrincipalEvidence) -> Option<SubjectRow> {
let owner = ghostlight::PrincipalId::new(principal.account_subject_hash());
snapshot
.subjects
.iter()
.find(|subject| {
subject.controller_mode == Some(ControllerMode::Human)
&& subject.human_controller.as_ref() == Some(&owner)
})
.map(|subject| SubjectRow { id: subject.id })
}
fn subject_label(snapshot: &WorldSnapshot, subject: SubjectId) -> String {
snapshot
.subjects
.iter()
.find(|row| row.id == subject)
.map_or_else(|| "an unknown subject".to_owned(), |row| row.label.clone())
}
/// A subject's own short handle: the first 8 hex digits of its id
/// (PA.f97). Actor tool names are `<handle>__<kind>`, and a kind may run up
/// to 48 chars, so the full 36-char uuid text a handle used to carry could
/// reach 86 chars against a common 64-char function-name limit; 8 hex
/// digits plus the `__` separator keeps every name well under that limit
/// (`the_longest_possible_actor_tool_name_is_64_chars_or_fewer`) while still
/// reading as the same bracketed id prefix `table_view` prints. The id text
/// itself comes from the library's own `id_text` (PA.f113/PA.f129) — no
/// second, hand-written debug-paren strip here.
/// Collision between two subjects sharing a handle is astronomically
/// unlikely but not impossible; `round_tools` refuses the whole round as a
/// turn fault rather than silently addressing the wrong subject
/// (`find_handle_collision`).
fn handle_for(id: SubjectId) -> String {
id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect()
}
/// Appends one actor tool's own acting subject's label and full canonical id
/// to its description (PA.f98): `dispatch` takes the id exactly as
/// `table_view` prints it, never the short `<handle>__` prefix these tools'
/// own names carry, so every actor tool now names the id `dispatch` actually
/// expects, right where the agent reads it. `actor_tools` (`table.rs`) knows
/// nothing of a subject's label; annotating here, over the definitions it
/// already returned, is the smallest fix that does not teach the library
/// vocabulary a Dungeon-only presentation concern. The id itself comes from
/// the library's own `id_text` (PA.f113) — Dungeon no longer keeps its own
/// copy of the debug-paren strip `table_view` uses to print it.
fn annotate_actor_tools(tools: &mut [CodexToolDefinition], snapshot: &WorldSnapshot, subject: SubjectId) {
let label = subject_label(snapshot, subject);
let id = id_text(subject);
for tool in tools {
tool.description = format!("{} Acting subject: {label} [{id}].", tool.description);
}
}
/// The first colliding handle among `handles`, if any (PA.f97): two entries
/// naming the *same* handle for the *same* subject is not a collision (a
/// subject may legitimately appear once as the player and, in principle,
/// once more via `dispatched`); two entries naming the same handle for
/// *different* subjects is. Pulled apart from `handle_for` itself so the
/// detection algorithm is directly testable without needing two real
/// subject ids that actually collide — vanishingly unlikely to construct
/// from genuine, randomly issued ids, and `SubjectId` mints nothing a
/// consumer crate can construct by hand.
fn find_handle_collision(handles: impl Iterator<Item = (String, SubjectId)>) -> Option<String> {
let mut seen: std::collections::HashMap<String, SubjectId> = std::collections::HashMap::new();
for (handle, subject) in handles {
match seen.get(&handle) {
Some(existing) if *existing != subject => return Some(handle),
_ => {
seen.insert(handle, subject);
}
}
}
None
}
/// The one collision-refusal rule `round_tools` (before inference offers
/// tools) and `execute_round` (resuming an already-decided round, which
/// never calls `round_tools` at all) both must enforce (PA.f97, PA.f105,
/// PA.f118): a handle collision anywhere in the snapshot's own subjects,
/// found by `find_handle_collision` over every subject the snapshot
/// carries, is a turn fault regardless of which subjects this round happens
/// to offer tools for. One shared owner so the two sites cannot drift the
/// way a verbatim copy invites.
fn collision_refusal(snapshot: &WorldSnapshot) -> Option<String> {
find_handle_collision(snapshot.subjects.iter().map(|row| (handle_for(row.id), row.id))).map(|handle| {
format!("two subjects share the handle `{handle}`; the play table cannot address them safely")
})
}
/// The tool-name prefix one subject's own actor tools carry: exactly what
/// `round_tools` hands `actor_tools` to generate them, and what
/// `execute_actor_call` hands `decode_actor_call` to parse them back — one
/// prefix, shared, so generation and decode can never drift apart.
fn actor_prefix(subject: SubjectId) -> String {
format!("{}{HANDLE_SEPARATOR}", handle_for(subject))
}
fn control_tools() -> Vec<CodexToolDefinition> {
vec![
CodexToolDefinition {
name: DISPATCH_TOOL.into(),
description: "Dispatch one or more subjects to act this round, each named by its full id \
exactly as table_view prints it in brackets — never the short <handle>__ prefix an actor tool's own \
name carries. An id naming no dispatchable subject is refused, quoting the text given."
.into(),
parameters_json: r#"{"type":"object","properties":{"subjects":{"type":"array","items":{"type":"string"}}},"required":["subjects"]}"#.into(),
},
CodexToolDefinition {
name: ADVANCE_TIME_TOOL.into(),
description: "Advance the world clock by a whole number of fictional minutes.".into(),
parameters_json: r#"{"type":"object","properties":{"minutes":{"type":"integer","minimum":1}},"required":["minutes"]}"#.into(),
},
CodexToolDefinition {
name: ASK_PLAYER_TOOL.into(),
description: "Stop the turn and ask the player a question.".into(),
parameters_json: r#"{"type":"object","properties":{"question":{"type":"string"}},"required":["question"]}"#.into(),
},
CodexToolDefinition {
name: END_TURN_TOOL.into(),
description: "End the turn: its consequences are settled.".into(),
parameters_json: r#"{"type":"object","properties":{},"required":[]}"#.into(),
},
]
}
/// Resolves `dispatch`'s own `subjects` argument (PA.f98, PA.f114): each
/// entry is the *full* id `table_view` prints in brackets, matched through
/// the library's own `id_text_matches` — never the short `<handle>__`
/// actor-tool prefix, which exists only to keep a generated tool name under a
/// common function-name length limit and was never meant to be an id a caller
/// supplies back.
///
/// `PLAY_INSTRUCTIONS` promises dispatch refuses bad input rather than
/// silently doing nothing with it, so every shape of bad input returns a
/// refusal in `refusals` that quotes what was given, instead of being
/// dropped: a body that is not valid JSON, a body that is not a JSON object,
/// a missing `subjects` key, a `subjects` that is not an array, a non-string
/// entry, and an entry naming no subject in `snapshot`.
fn parse_dispatch(arguments: &str, snapshot: &WorldSnapshot) -> (Vec<SubjectId>, Vec<String>) {
let value = match serde_json::from_str::<Value>(arguments) {
Ok(value) => value,
Err(_) => {
return (
Vec::new(),
vec![format!("dispatch's arguments are not valid JSON: `{arguments}`")],
);
}
};
let Value::Object(fields) = value else {
return (
Vec::new(),
vec![format!("dispatch's arguments are not a JSON object: `{arguments}`")],
);
};
let Some(subjects_value) = fields.get("subjects") else {
return (
Vec::new(),
vec![format!("dispatch's arguments have no `subjects` key: `{arguments}`")],
);
};
let Value::Array(items) = subjects_value else {
return (
Vec::new(),
vec![format!("dispatch's `subjects` is not an array: `{subjects_value}`")],
);
};
let mut subjects = Vec::new();
let mut refusals = Vec::new();
for item in items {
match item.as_str() {
Some(text) => match snapshot.subjects.iter().find(|subject| id_text_matches(subject.id, text)) {
Some(subject) => subjects.push(subject.id),
None => refusals.push(format!("`{text}` names no dispatchable subject")),
},
None => refusals.push(format!("`{item}` in `subjects` is not a string")),
}
}
(subjects, refusals)
}
fn parse_ask_player(arguments: &str) -> String {
serde_json::from_str::<Value>(arguments)
.ok()
.and_then(|value| value.get("question").and_then(Value::as_str).map(str::to_owned))
.unwrap_or_default()
}
fn parse_minutes(arguments: &str) -> Option<TickMinutes> {
let value = serde_json::from_str::<Value>(arguments).ok()?;
let minutes = value.get("minutes")?.as_u64()?;
TickMinutes::new(u32::try_from(minutes).ok()?)
}
/// The derived command id for one dispatched Persona's own turn (PA.f66d):
/// hashed from the dispatch tool call's own round and slot plus the
/// subject's own handle, never from the subject's position in that call's
/// own JSON `subjects` array. Two subjects one dispatch call names, or the
/// same subject two dispatch calls in one round name, must never collide —
/// the old `dispatch_slot` collided exactly there, since it read only a
/// position within one call's own list and dropped the call's own identity
/// entirely.
fn dispatch_command_id(turn_id: &str, round: usize, call_slot: usize, subject: SubjectId) -> CommandId {
dispatch_command_id_for_handle(turn_id, round, call_slot, &handle_for(subject))
}
/// `dispatch_command_id`'s own hash, taking a bare handle so it is directly
/// testable without minting a `SubjectId` (Dungeon holds no public
/// constructor for one).
fn dispatch_command_id_for_handle(turn_id: &str, round: usize, call_slot: usize, handle: &str) -> CommandId {
let mut hasher = Sha256::new();
hasher.update(b"ghostlight.dungeon.play.dispatch.v1\n");
hasher.update(turn_id.as_bytes());
hasher.update(b"\n");
hasher.update(round.to_le_bytes());
hasher.update(call_slot.to_le_bytes());
hasher.update(b"\n");
hasher.update(handle.as_bytes());
let digest = hasher.finalize();
let uuid = uuid::Uuid::from_slice(&digest[..16]).expect("sha256 digest is at least 16 bytes");
CommandId::parse_uuid(&uuid.to_string()).expect("a formatted uuid always parses")
}
/// `PlayTable::retry_delay`'s own production base, in milliseconds
/// (PA.f122): the default `retry_delay_base_ms` starts at, and the value
/// `backoff_delay`'s own doc-pinned formula (`backoff_delay_grows_then_caps`)
/// still assumes.
const RETRY_DELAY_BASE_MS: u64 = 100;
/// `PlayTable::retry_delay`'s own capped exponential backoff formula
/// (PA.f102, PA.f122): `base_ms * 2^attempt` milliseconds, capped at `CAP`,
/// with `attempt` clamped before the shift so a very large attempt count can
/// never overflow or panic. A free function, always compiled — never hidden
/// behind `#[cfg(test)]` — so it is directly unit-testable in every build,
/// and `retry_delay` always calls exactly this, over `base_ms` alone,
/// whether that base is `RETRY_DELAY_BASE_MS` (production) or whatever a
/// test set it to.
fn backoff_delay(base_ms: u64, attempt: usize) -> Duration {
const CAP: u64 = 5_000;
Duration::from_millis(base_ms.saturating_mul(1u64 << attempt.min(6)).min(CAP))
}
/// A round is incomplete when it holds a tool call this table has not yet
/// resolved to a result.
fn round_incomplete(turn: &PlayTurn, round: usize) -> bool {
let Some(output) = turn.rounds.get(round) else {
return false;
};
let mut slot = 0usize;
for event in output.events() {
if !matches!(event, InferenceEvent::ToolCall { .. }) {
continue;
}
let this_slot = slot;
slot += 1;
if !turn
.call_record(round, this_slot)
.is_some_and(|call| call.result.is_some())
{
return true;
}
}
false
}
fn find_ask_player_slot(turn: &PlayTurn, round: usize) -> Option<usize> {
turn.calls
.iter()
.find(|call| {
call.round == round && matches!(call.body, Some(RecordedCall::AskPlayer(_))) && call.result.is_none()
})
.map(|call| call.slot)
}
/// One refusal, attributed to every call in a run (PA.f54): the run commits
/// atomically, so a decode-time refusal — before any patch is even
/// assembled — is every one of the run's calls own result alike, not just
/// the anchor's.
fn refuse_run(run: &[(usize, String, String, String)], detail: String) -> Vec<(usize, String, RoundOutcome, String)> {
run.iter()
.map(|(slot, call_id, _, _)| (*slot, call_id.clone(), RoundOutcome::Continue, detail.clone()))
.collect()
}
fn record_call(
turn: &mut PlayTurn,
call_id: &str,
round: usize,
slot: usize,
body: Option<RecordedCall>,
result: Option<String>,
) {
if let Some(existing) = turn.call_record_mut(round, slot) {
if body.is_some() {
existing.body = body;
}
if result.is_some() {
existing.result = result;
}
return;
}
turn.calls.push(CallRecord {
call_id: call_id.to_owned(),
round,
slot,
body,
result,
});
}
/// The connector posture: `[UserText(opening_prompt), ...]` replaying every
/// fully-resolved round before `round` as `AssistantText`/`ToolCall`/`ToolResult`
/// items, exactly as `controllers.rs`'s own multi-round lanes rebuild their
/// conversation from `completed` outputs.
fn rebuild_conversation(turn: &PlayTurn, round: usize) -> Vec<CodexInputItem> {
let mut conversation = vec![CodexInputItem::UserText {
text: turn.opening_prompt.clone(),
}];
for (index, output) in turn.rounds.iter().enumerate() {
if index >= round {
break;
}
let mut slot = 0usize;
for event in output.events() {
match event {
InferenceEvent::Text(text) => {
if !text.is_empty() {
conversation.push(CodexInputItem::AssistantText { text: text.clone() });
}
}
InferenceEvent::ToolCall {
call_id,
name,
arguments,
} => {
let this_slot = slot;
slot += 1;
conversation.push(CodexInputItem::ToolCall {
call_id: call_id.clone(),
name: name.clone(),
arguments: arguments.clone(),
});
let output_text = turn
.call_record(index, this_slot)
.and_then(|call| call.result.clone())
.unwrap_or_default();
conversation.push(CodexInputItem::ToolResult {
call_id: call_id.clone(),
output: output_text,
});
}
}
}
}
conversation
}
/// Whether an actor call's `text`/`display` are exact quotes from the
/// acting subject's own preserved prose: the player's submitted texts, or a
/// dispatched Persona's own recorded turn (PA-Q8 invariant 4). A player's
/// display need not be spoken; an empty invocation (neither) is exact by
/// vacuity.
fn span_is_exact(invocation: &DecisionInvocation, actor: &Actor, turn: &PlayTurn) -> bool {
let sources: Vec<&str> = if actor.is_player {
turn.player_prose.iter().map(String::as_str).collect()
} else {
turn.persona_turns
.iter()
.filter(|(id, _)| *id == actor.subject)
.map(|(_, persona_turn)| persona_turn.source_prose())
.collect()
};
let quotes = [
invocation.speech.as_ref().map(Statement::as_str),
invocation.display.as_ref().map(Statement::as_str),
];
for quote in quotes.into_iter().flatten() {
if !sources.iter().any(|source| SourceSpan::locate(source, quote).is_some()) {
return false;
}
}
true
}
/// sha256 over the turn id, round, and slot; the first 16 bytes read back as
/// a UUID. Deterministic over `(turn_id, round, slot)`, so a resumed call
/// re-derives the identical command id the kernel's idempotency ledger
/// already knows (`AlreadyApplied`), never a fresh one.
fn derived_command_id(turn_id: &str, round: usize, slot: usize) -> CommandId {
let mut hasher = Sha256::new();
hasher.update(b"ghostlight.dungeon.play.command.v1\n");
hasher.update(turn_id.as_bytes());
hasher.update(b"\n");
hasher.update(round.to_le_bytes());
hasher.update(slot.to_le_bytes());
let digest = hasher.finalize();
let uuid = uuid::Uuid::from_slice(&digest[..16]).expect("sha256 digest is at least 16 bytes");
CommandId::parse_uuid(&uuid.to_string()).expect("a formatted uuid always parses")
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use ghostlight::{
AffordanceId, CreateWorldIntent, InferenceFault, Lens, LensWeights, PreparedInference,
decode_authoring_call,
};
use ghostlight_persona_projection::PersonaTurnBinding;
use std::{
collections::{BTreeMap, VecDeque},
sync::Mutex as StdMutex,
};
use tokio::task::JoinHandle;
/// Every `.rs` file under `src`, with everything a `#[cfg(test)]` item
/// removed, the same extent-by-indent scan `app_session.rs`'s own
/// forbidden-writer test uses.
fn production_sources() -> Vec<(std::path::PathBuf, String)> {
fn indent(line: &str) -> usize {
line.len() - line.trim_start().len()
}
fn strip_cfg_test(text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let mut kept: Vec<&str> = Vec::new();
let mut index = 0;
while index < lines.len() {
let line = lines[index];
if line.trim() != "#[cfg(test)]" {
kept.push(line);
index += 1;
continue;
}
let guard = indent(line);
index += 1;
let mut opened = lines
.get(index)
.is_some_and(|next| next.trim_end().ends_with('{'));
while index < lines.len() {
let body = lines[index];
index += 1;
let trimmed = body.trim();
if trimmed.is_empty() {
continue;
}
if opened {
if indent(body) == guard && (trimmed == "}" || trimmed == "};" || trimmed == "},") {
break;
}
} else if indent(body) == guard && (trimmed.ends_with(';') || trimmed.ends_with(',')) {
break;
} else if indent(body) == guard && trimmed.ends_with('{') {
opened = true;
}
}
}
kept.join("\n")
}
let mut sources = Vec::new();
let mut pending = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
while let Some(directory) = pending.pop() {
for entry in std::fs::read_dir(&directory).expect("the source tree reads") {
let path = entry.expect("a readable entry").path();
if path.is_dir() {
pending.push(path);
continue;
}
if path.extension().and_then(|value| value.to_str()) != Some("rs") {
continue;
}
let text = std::fs::read_to_string(&path)
.expect("the source reads")
.replace("\r\n", "\n");
sources.push((path, strip_cfg_test(&text)));
}
}
sources
}
/// Pin: Dungeon never builds a `ComponentOp`, `Declaration`, `RoleBinding`,
/// or `ProposedEffect` by hand; everything goes through `table.rs`.
#[test]
fn soul_no_forbidden_writer_name_appears_in_dungeons_own_source() {
for forbidden in ["ComponentOp", "Declaration", "RoleBinding", "ProposedEffect"] {
for (path, source) in production_sources() {
assert!(
!source.contains(forbidden),
"{} names `{forbidden}` directly; Dungeon must compose through table.rs",
path.display()
);
}
}
}
/// Pin: `PlayPort`'s constructor is minted in exactly one production
/// site, matching the library's own doc comment on `PlayPort`. The
/// needle is assembled from halves so this assertion's own source, and
/// this file's doc comments about the rule, are never themselves a
/// match — the same precedent `app_session.rs`'s own single-minter test
/// uses for `VerifiedPrincipalEvidence`.
#[test]
fn soul_exactly_one_production_site_mints_play_port() {
let needle = format!("{}::{}(", "PlayPort", "new");
let mut sites = Vec::new();
for (path, source) in production_sources() {
for _ in source.match_indices(needle.as_str()) {
sites.push(path.clone());
}
}
assert_eq!(sites.len(), 1, "the play port constructor appears in: {sites:?}");
assert!(sites[0].ends_with("play.rs"));
}
/// Rule: `PLAY_TOOLS` is a real subset of the library's own catalog.
#[test]
fn play_tools_are_all_real_authoring_tools() {
authoring_tools(PLAY_TOOLS).expect("every PLAY_TOOLS name is a known authoring tool");
assert!(!PLAY_TOOLS.contains(&"admit"), "admit is not a play tool");
}
pub(crate) fn test_turn_id(n: u128) -> String {
uuid::Uuid::from_u128(n).to_string()
}
fn far_future() -> chrono::DateTime<Utc> {
Utc::now() + chrono::Duration::hours(4)
}
/// PA.f161: widened to `pub(crate)` (test-only, behind `#[cfg(test)]`)
/// so `runtime.rs`'s own test module can script a deterministic
/// `ask_player` question through the real HTTP route — the only way to
/// exercise `world.play`'s own staleness comparison against a question
/// that actually opened, rather than one hand-built.
pub(crate) struct ScriptedPort {
queue: StdMutex<VecDeque<Result<InferenceOutput, String>>>,
seen: StdMutex<Vec<InferenceRequest>>,
}
impl ScriptedPort {
pub(crate) fn new(outputs: Vec<InferenceOutput>) -> Arc<Self> {
Arc::new(Self {
queue: StdMutex::new(outputs.into_iter().map(Ok).collect()),
seen: StdMutex::new(Vec::new()),
})
}
fn seen_requests(&self) -> Vec<InferenceRequest> {
self.seen.lock().unwrap().clone()
}
}
#[async_trait::async_trait]
impl InferencePort for ScriptedPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.seen.lock().unwrap().push(request.clone());
PreparedInference::prepare("play-test-runtime", far_future_unix_ms(), request)
}
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
match self.queue.lock().unwrap().pop_front() {
Some(Ok(output)) => Ok(output),
Some(Err(detail)) => Err(InferenceFault::recovery_required(detail)),
None => Err(InferenceFault::recovery_required("scripted port exhausted")),
}
}
}
fn far_future_unix_ms() -> u64 {
u64::try_from(far_future().timestamp_millis()).unwrap_or(u64::MAX)
}
/// PA.f142's own test seam: an `InferencePort` whose `infer` blocks until
/// the test explicitly releases it, so a test can drive a `run` call to
/// a *known* point deep inside `infer_round` — genuinely holding
/// `run_lock` — before firing a second, racing call. Deterministic,
/// unlike relying on `tokio::join!`'s own scheduling to make a race land
/// a particular way.
struct GatedPort {
ready: tokio::sync::Notify,
release: tokio::sync::Notify,
output: StdMutex<Option<InferenceOutput>>,
}
impl GatedPort {
fn new(output: InferenceOutput) -> Arc<Self> {
Arc::new(Self {
ready: tokio::sync::Notify::new(),
release: tokio::sync::Notify::new(),
output: StdMutex::new(Some(output)),
})
}
/// Resolves once `infer` has been entered (and is itself now
/// waiting on `release`).
async fn wait_ready(&self) {
self.ready.notified().await;
}
/// Lets a blocked `infer` call proceed.
fn release(&self) {
self.release.notify_one();
}
}
#[async_trait::async_trait]
impl InferencePort for GatedPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
PreparedInference::prepare("play-test-runtime", far_future_unix_ms(), request)
}
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
self.ready.notify_one();
self.release.notified().await;
Ok(self
.output
.lock()
.unwrap()
.take()
.expect("GatedPort's own infer is called exactly once in these tests"))
}
}
pub(crate) fn output(receipt: &str, events: Vec<InferenceEvent>) -> InferenceOutput {
InferenceOutput::new(events, receipt.to_owned())
}
pub(crate) fn text_event(text: &str) -> InferenceEvent {
InferenceEvent::Text(text.to_owned())
}
pub(crate) fn call_event(call_id: &str, name: &str, arguments: serde_json::Value) -> InferenceEvent {
InferenceEvent::ToolCall {
call_id: call_id.to_owned(),
name: name.to_owned(),
arguments: arguments.to_string(),
}
}
struct WorldFixture {
_directory: tempfile::TempDir,
world: WorldMailbox,
principal: VerifiedPrincipalEvidence,
/// The mailbox's own background owner task (PA.f118): kept, not
/// discarded, so a test that needs `self.play.snapshot()` (or any
/// other mailbox call) to fail deterministically can `.abort()` it —
/// aborting drops the task's own channel receiver, so every request
/// already queued or sent afterward resolves `MailboxError::Unavailable`
/// rather than hanging or silently succeeding. Unused by a test that
/// never aborts it, which is most of them.
owner: JoinHandle<()>,
}
/// A genesis world, activated: one Human "first-person" subject and,
/// when `persona_label` is given, one NarrativePersona subject, both
/// standing in the commons with the kernel's own `speak` grant. Built
/// entirely through `WorldMailbox`'s public door — the same one Cut 8's
/// own play agent uses — so no test fixture reaches into the kernel's
/// private typed vocabulary.
async fn play_world(persona_label: Option<&str>, account_hash: &str) -> WorldFixture {
let directory = tempfile::tempdir().unwrap();
let (world, owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
let principal = VerifiedPrincipalEvidence::new(account_hash, far_future());
let receipt = world
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "Fixture World".into(),
brief: "A small table for Cut 8a's own tests.".into(),
human_subject_label: "Player".into(),
narrative_persona_label: persona_label.map(str::to_owned),
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ApproveDraft,
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ActivateWorld,
},
&principal,
)
.await
.unwrap();
WorldFixture {
_directory: directory,
world,
principal,
owner,
}
}
/// PA.f159: `player_subject` must resolve the acting subject by *whose*
/// principal is calling, not merely by finding a `ControllerMode::Human`
/// subject at all. A mutation reverting the added
/// `human_controller.as_ref() == Some(&owner)` clause — leaving only the
/// old `controller_mode == Some(Human)` check — would still find the
/// fixture's own human subject here even though the calling principal is
/// a stranger to this world entirely, so this fails under exactly that
/// mutation.
#[tokio::test]
async fn the_player_subject_follows_the_calling_principal() {
let fixture = play_world(None, "the-real-owner").await;
let snapshot = fixture.world.snapshot().await.unwrap();
assert!(
player_subject(&snapshot, &fixture.principal).is_some(),
"the world's own owner/player principal must resolve to the human subject"
);
let stranger = VerifiedPrincipalEvidence::new("a-stranger-principal", far_future());
assert!(
player_subject(&snapshot, &stranger).is_none(),
"a principal that does not control any subject here must resolve to none, even though a \
ControllerMode::Human subject exists in this world"
);
}
/// Test fixtures build exactly one human-controlled subject, so this
/// stays the older, principal-blind lookup deliberately (Cut 10,
/// PA.f159) rather than threading a principal through the 20-odd call
/// sites below: it is testing "which subject is the fixture's own
/// player", not the production selection rule `player_subject` now
/// enforces (that rule has its own direct coverage in
/// `the_player_subject_follows_the_calling_principal` below).
fn player_id(snapshot: &WorldSnapshot) -> SubjectId {
snapshot
.subjects
.iter()
.find(|subject| subject.controller_mode == Some(ControllerMode::Human))
.expect("a play fixture's own single human subject")
.id
}
fn persona_id(snapshot: &WorldSnapshot) -> SubjectId {
snapshot
.subjects
.iter()
.find(|subject| subject.controller_mode == Some(ControllerMode::NarrativePersona))
.unwrap()
.id
}
/// A subject's own full canonical id text, read out of a *real*
/// `table_view` render rather than a test-local copy of its printer
/// (PA.f113): a change to what `table_view` actually prints must break
/// every test that reads an id through this helper, which a fourth
/// hand-spelled debug-paren strip could not do — that copy passed every
/// dispatch test while `table_view`'s own print regressed and every real
/// dispatch an agent could make was refused. Distinct from `handle_for`'s
/// short 8-hex-digit actor handle (PA.f97). A `Ref::Existing` JSON value
/// needs the real id; only a `<handle>__<kind>` tool name needs the
/// truncated handle.
fn subject_id_text(snapshot: &WorldSnapshot, id: SubjectId) -> String {
let label = snapshot
.subjects
.iter()
.find(|subject| subject.id == id)
.map_or_else(|| "an unknown subject".to_owned(), |subject| subject.label.clone());
let view = table_view(snapshot);
// The `Places:` section prints each place's occupants by the same
// "label [id]" shape (PA.f74) before the `Subjects:` section proper
// renders the subject's own canonical entry — the entry
// `PLAY_INSTRUCTIONS` and `dispatch` actually mean. Search only from
// the `Subjects:` header so a subject that also occupies a place
// does not read its id back out of the wrong section.
let subjects_section = view
.find("\n Subjects:")
.map_or(view.as_str(), |at| &view[at..]);
let marker = format!("{label} [");
let start = subjects_section
.find(&marker)
.unwrap_or_else(|| panic!("{label} not found in table_view's Subjects section: {view}"))
+ marker.len();
let end = subjects_section[start..]
.find(']')
.unwrap_or_else(|| panic!("unterminated id bracket after {label} in table_view"));
subjects_section[start..start + end].to_owned()
}
#[tokio::test]
async fn the_turn_closes_with_the_players_narration() {
let fixture = play_world(None, "player-closes").await;
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
// The player's own narration draws one Projector inference.
let projector = output("proj-0", vec![text_event("The room settles.")]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![projector]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(1), "I look around.".into())
.await
.unwrap();
// PA.f69: the narration text itself, not merely its presence.
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.narration.as_deref(), Some("The room settles."));
}
/// Walks a rendered Eve surface for the first node whose own `id` matches
/// — the same small recursive search `eve.rs`'s own tests use, copied
/// rather than shared because it is test-local on both sides.
fn find_surface_node<'a>(node: &'a Value, id: &str) -> Option<&'a Value> {
if node["id"] == id {
return Some(node);
}
node.as_object()?
.values()
.flat_map(|value| match value {
Value::Array(items) => items.iter().collect::<Vec<_>>(),
other => vec![other],
})
.find_map(|child| find_surface_node(child, id))
}
/// Cut 9's own card test: the player's own already-committed speech is
/// durable in the world owner's own unscoped operator log — the
/// operator's surface, per that library method's own doc comment, which
/// "no subject-facing lane may reach" — while the turn's own narration is
/// a *different*, player-facing channel the play table produces.
/// `eve::authenticated_surface`'s play card must show the narration and
/// never the operator feed's own text, proving invariant 8's "nothing
/// else": the player sees a projection, the question, and the refusal of
/// their own act, never an unscoped event log.
///
/// Mutation M9.1 named "render that feed into the card" as the mutant
/// this test kills. It is retired, not re-aimed (Cut 10, PA.f155): Cut 9
/// had already deleted the operator-feed parameter `authenticated_surface`
/// once took, so a mutation that "renders the feed into the card" cannot
/// be expressed as a code change against the current signature — there is
/// no parameter left to wire in. The test's own assertions below (the
/// card renders narration/question/refusal and nothing else) remain a
/// live defense of invariant 8 against whatever *can* still leak — most
/// concretely, a future call site that starts threading operator-log text
/// through `narration`/`refusal` themselves.
#[tokio::test]
async fn the_play_surface_shows_only_the_projection() {
let fixture = play_world(None, "player-projection-only").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let opportunity = snapshot
.opportunities
.iter()
.find(|opportunity| opportunity.scope.subject_id == player)
.cloned()
.expect("the player's own speak opportunity");
let affordance_id = snapshot
.affordances
.iter()
.find(|entry| {
entry.entry.kind.0 == "speak"
&& snapshot
.subjects
.iter()
.any(|subject| subject.id == player && subject.affordances.contains(&entry.id))
})
.map(|entry| entry.id)
.expect("the player's own speak affordance");
fixture
.world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ExerciseDecision {
opportunity,
invocation: DecisionInvocation {
affordance: affordance_id,
bindings: Vec::new(),
proposed: Vec::new(),
speech: Some(
Statement::new("A voice the play table never narrated.".to_owned())
.unwrap(),
),
display: None,
},
},
},
&fixture.principal,
)
.await
.unwrap();
let durable_log = fixture.world.operator_log().await.unwrap();
assert_eq!(durable_log.len(), 1, "the committed speech must be durable in the world owner's own feed");
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("The room settles into quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(90), "I look around.".into())
.await
.unwrap();
let view = table.current_turn_view().await.unwrap();
assert_eq!(view.narration.as_deref(), Some("The room settles into quiet."));
let world = fixture.world.snapshot().await.unwrap();
// `authenticated_surface` takes no operator feed at all any more
// (Cut 9's own deletion commit removed that parameter along with the
// card that once read it) — the leaking text above is durable and
// real, and this call has structurally no way to reach it.
let surface =
crate::eve::authenticated_surface("player-projection-only", Some(&world), Some(&view))
.unwrap();
let play_card = find_surface_node(&surface, "world.play.card").expect("the play card");
let play_card_encoded = serde_json::to_string(play_card).unwrap();
assert!(
play_card_encoded.contains("The room settles into quiet."),
"the card must show the turn's own narration: {play_card_encoded}"
);
assert!(
!play_card_encoded.contains("A voice the play table never narrated."),
"the play card must never render the operator log's own speech, even though it is durably \
committed to the world owner's own unscoped operator log: {play_card_encoded}"
);
// Every other `world.play.*` node too — the text control and the
// and the button — not only the card itself.
for id in ["world.play.answers", "world.play.text", "world.play"] {
if let Some(node) = find_surface_node(&surface, id) {
let encoded = serde_json::to_string(node).unwrap();
assert!(
!encoded.contains("A voice the play table never narrated."),
"{id} must never carry the operator log's own speech: {encoded}"
);
}
}
}
/// PA.f134's own end-to-end proof: answering *through the turn view's own
/// `question.id`* — the id `current_turn_view` actually exposes, never
/// one this test built — resumes the turn, and the closed turn's
/// narration is then visible through the same card. Cut 10 (PA.f151)
/// deleted the card's own rendered id control (the lowering had no way
/// to carry it without leaking it); `runtime.rs::execute_world`'s
/// `world.play` arm is the one production caller that resolves this id
/// now, the same way this test does. Also proves the play row's own
/// revision claim: the world commits nothing across this whole exchange
/// (`ask_player`/`end_turn` are conversational, not kernel patches), so
/// `world.revision` — and so the surface document's own `version`
/// (PA.f148) — never moves, yet `PlayTurnView::revision` still does, on
/// both the question opening and the turn closing.
#[tokio::test]
async fn a_question_is_answered_through_the_cards_own_binding_and_the_turn_closes_with_narration() {
let fixture = play_world(None, "player-card-question").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
let end = output("r1", vec![call_event("c1", END_TURN_TOOL, serde_json::json!({}))]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("The hall falls quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask, end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(91), "I stand at a crossroads.".into())
.await
.unwrap();
let asked_view = table.current_turn_view().await.unwrap();
assert_eq!(
asked_view.question.as_ref().map(|question| question.text.as_str()),
Some("Which way?")
);
let world_before = fixture.world.snapshot().await.unwrap();
let surface_before = crate::eve::authenticated_surface(
"player-card-question",
Some(&world_before),
Some(&asked_view),
)
.unwrap();
let question_row = find_surface_node(&surface_before, "world.play.question")
.expect("the question row");
assert_eq!(question_row["props"]["value"], "Which way?");
assert!(
find_surface_node(&surface_before, "world.play.answers").is_none(),
"Cut 10 deleted the id-carrying control; nothing on the surface names the question"
);
// The exact id `current_turn_view` exposes — the one a production
// caller (`runtime.rs::execute_world`) resolves server-side now,
// never a value the player's own client supplies.
let answers: QuestionId = asked_view.question.as_ref().unwrap().id.clone();
table
.run(
&fixture.principal,
test_turn_id(92),
PlayRequest {
text: "I go left.".into(),
answers: Some(answers),
},
)
.await
.unwrap();
let closed_view = table.current_turn_view().await.unwrap();
assert_eq!(closed_view.state, PlayTurnState::Closed);
assert_eq!(closed_view.question, None);
assert_eq!(closed_view.narration.as_deref(), Some("The hall falls quiet."));
assert!(
closed_view.revision > asked_view.revision,
"the row's own revision must move again once the turn closes: {} -> {}",
asked_view.revision,
closed_view.revision
);
let world_after = fixture.world.snapshot().await.unwrap();
assert_eq!(
world_after.revision, world_before.revision,
"asking and answering a question are conversational; neither commits to the world"
);
let surface_after = crate::eve::authenticated_surface(
"player-card-question",
Some(&world_after),
Some(&closed_view),
)
.unwrap();
assert!(
find_surface_node(&surface_after, "world.play.question").is_none(),
"no question is open any more; the card must not still show one"
);
// PA.f159: the subject census is gone from `world.summary` — phase
// and clock stay, but who else is in the world is not the player's
// own projection.
let summary = find_surface_node(&surface_after, "world.summary").expect("the summary card");
assert_eq!(summary["children"], serde_json::json!([]));
let narration_row = find_surface_node(&surface_after, "world.play.narration")
.expect("the narration row");
assert_eq!(narration_row["props"]["value"], "The hall falls quiet.");
assert_eq!(
surface_before["version"], surface_after["version"],
"the document's own version names world.revision alone, and it never moved"
);
}
/// PA.f175: `execute_round` takes one snapshot at round entry
/// (`round_snapshot`) and, before this fix, reused it for every arm in
/// that same round — including `ASK_PLAYER_TOOL` — so a round that
/// commits an authoring call (a `PLAY_TOOLS` run) and then asks in the
/// same round recorded `question_surface_version` from before its own
/// commit. A later "is this answer stale" comparison
/// (`runtime.rs::an_answer_naming_a_version_older_than_the_question_is_refused_as_stale`)
/// judges a version the question's own commit had already passed, so an
/// answer naming the version the commit actually landed at — the version
/// a real client would have just been served — could be wrongly refused
/// as older than the question.
///
/// Mutation: revert `execute_round`'s `ASK_PLAYER_TOOL` arm to record
/// `crate::eve::surface_version(Some(&snapshot))` (the round-entry
/// snapshot) instead of fetching a fresh one at the moment the question
/// opens — this test's asserted version would then equal the version
/// from before the round's own `declare_fact` commit, one behind the
/// version this test expects.
#[tokio::test]
async fn a_round_that_authors_and_then_asks_records_the_version_as_of_the_question_not_the_round() {
let fixture = play_world(None, "player-author-then-ask").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let world_before = fixture.world.snapshot().await.unwrap();
let version_before = crate::eve::surface_version(Some(&world_before));
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_fact",
serde_json::json!({
"handle": "ruling",
"label": "The Ruling",
"statement": "The gate creaks open on its own.",
"standing": {"standing": "ruled"},
}),
),
call_event(
"c1",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(91), "I stand at a crossroads.".into())
.await
.unwrap();
let asked_view = table.current_turn_view().await.unwrap();
let question = asked_view
.question
.as_ref()
.expect("the scripted ask_player call must open a question");
let world_after = fixture.world.snapshot().await.unwrap();
let version_after = crate::eve::surface_version(Some(&world_after));
assert!(
version_after > version_before,
"declare_fact must have committed and moved the world's own revision \
({version_before} -> {version_after})"
);
assert_eq!(
question.surface_version, version_after,
"the question's own recorded version must be the version as of when it opened \
(after this round's own declare_fact commit, {version_after}), not the \
round-entry version {version_before}"
);
}
/// PA.f173: `close_with_fault` used to leave `question` and
/// `question_surface_version` set on the turn it closed, though a
/// `Closed` turn should never still carry an open question. This was
/// unobservable through `current_turn_view`/`open_question_id` only
/// because both gate on `state == AwaitingPlayer`, which closing always
/// leaves behind in the same write — so this test reaches past that
/// gate, at the raw persisted row.
///
/// Mutation: remove the `turn.question = None; turn.question_surface_version
/// = None;` lines from `close_with_fault` — the persisted row would then
/// still carry the question's own text and version after the turn
/// closed, and this test's assertions would fail.
#[tokio::test]
async fn close_with_fault_clears_the_open_question_off_the_persisted_row() {
let fixture = play_world(None, "player-fault-clears-question").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(91), "I stand at a crossroads.".into())
.await
.unwrap();
let asked_view = table.current_turn_view().await.unwrap();
assert_eq!(asked_view.state, PlayTurnState::AwaitingPlayer);
let mut turn = table.store.lock().await.current().unwrap().clone();
assert!(turn.question.is_some());
assert!(turn.question_surface_version.is_some());
table
.close_with_fault(&mut turn, "manufactured fault for PA.f173".into())
.await
.unwrap();
let persisted = table.store.lock().await.current().unwrap().clone();
assert_eq!(persisted.state, PlayTurnState::Closed);
assert_eq!(
persisted.question, None,
"a closed turn must not still carry the question it closed on top of"
);
assert_eq!(
persisted.question_surface_version, None,
"a closed turn must not still carry the question's own surface version"
);
}
/// A pre-Cut-11 process's own `PlayTurn`, replicated field-for-field
/// minus `question_surface_version` — the shape every row actually
/// written under `LEGACY_STORE_SCHEMA_V1` carries (PA.f172). Test-only:
/// no production writer ever mints this shape again.
#[derive(Clone, Serialize)]
struct LegacyPlayTurnV1 {
turn_id: String,
applied_keys: Vec<String>,
opening_prompt: String,
player_prose: Vec<String>,
rounds: Vec<InferenceOutput>,
calls: Vec<CallRecord>,
persona_turns: Vec<(SubjectId, PersonaTurn)>,
question: Option<String>,
refusal: Option<String>,
narration: Option<String>,
fault: Option<String>,
state: PlayTurnState,
}
#[derive(Clone, Serialize)]
struct LegacyPlayTurnStoreStateV1 {
schema: String,
turn: Option<LegacyPlayTurnV1>,
ledger: KeyLedger,
revision: u64,
}
/// PA.f172: a row written before `question_surface_version` existed —
/// under `LEGACY_STORE_SCHEMA_V1`, the schema id every pre-Cut-11 process
/// actually wrote (it is exactly what `STORE_SCHEMA` used to be) — is
/// recognized by `PlayTurnStore::open` as legacy, not corrupt, and its
/// turn recovered rather than discarded: the missing field decodes to
/// `None`, exactly what "no question ever recorded a surface version"
/// means for a turn this old. The row is also upgraded to `STORE_SCHEMA`
/// in place, durably, so the legacy path is only ever taken once.
///
/// Mutation: remove the `schema_id.as_deref() ==
/// Some(LEGACY_STORE_SCHEMA_V1)` arm from `PlayTurnStore::open` — this
/// row would then fall through to the catch-all and `open` would return
/// `Err`, exactly PA.f172's own bug: a workstation's pre-Cut-11 row
/// silently disables play with "the play table is unavailable".
#[tokio::test]
async fn a_legacy_v1_row_is_recognized_and_upgraded_not_refused_as_corrupt() {
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let legacy_turn = LegacyPlayTurnV1 {
turn_id: "11111111-1111-1111-1111-111111111111".into(),
applied_keys: vec!["key-a".into()],
opening_prompt: "You stand at the gate.".into(),
player_prose: vec!["I knock.".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let legacy_state = LegacyPlayTurnStoreStateV1 {
schema: LEGACY_STORE_SCHEMA_V1.into(),
turn: Some(legacy_turn),
ledger: KeyLedger::default(),
revision: 3,
};
let legacy_row = CultCacheEnvelope {
key: STORE_KEY.into(),
r#type: STORE_TYPE.into(),
payload: rmp_serde::to_vec_named(&legacy_state).unwrap(),
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(LEGACY_STORE_SCHEMA_V1.into()),
};
{
let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
assert!(
raw_store
.compare_and_swap_batch(&[], vec![legacy_row])
.unwrap(),
"seeding the legacy row must succeed against an empty store"
);
}
let store = PlayTurnStore::open(&store_path)
.expect("a genuine pre-Cut-11 row must open, not be refused as corrupt");
let recovered = store.current().expect("the legacy row's own turn must be recovered");
assert_eq!(recovered.turn_id, "11111111-1111-1111-1111-111111111111");
assert_eq!(recovered.opening_prompt, "You stand at the gate.");
assert_eq!(
recovered.question_surface_version, None,
"a pre-Cut-11 turn never recorded a surface version; the missing field must decode to None"
);
assert_eq!(
store.row.schema_id.as_deref(),
Some(STORE_SCHEMA),
"the legacy row must be upgraded to the current schema in place, not left at v1"
);
// Reopening must now take the strict current-schema path, proving
// the upgrade was actually durably persisted, not only held in
// memory on the first `open`. `store` must be dropped first: CultCache's
// own single-owner lock refuses a second `OwnedRedbMessagePackBackingStore::new`
// on the same path while the first is still held (the same custody
// rule `pull_current_from_disk_for_test`'s own doc comment names).
let recovered_turn_id = recovered.turn_id.clone();
drop(store);
let reopened = PlayTurnStore::open(&store_path).unwrap();
assert_eq!(reopened.current().unwrap().turn_id, recovered_turn_id);
}
/// PA.f172's own negative: a row that matches the current schema id but
/// whose bytes do not decode at all is still refused as corrupt — the
/// legacy path recognizes only the one schema id every pre-Cut-11
/// process actually wrote, never a general-purpose "try to read it
/// anyway" escape hatch for a row that is genuinely damaged.
#[tokio::test]
async fn a_row_with_the_current_schema_id_and_undecodable_bytes_is_still_refused_as_corrupt() {
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let corrupt_row = CultCacheEnvelope {
key: STORE_KEY.into(),
r#type: STORE_TYPE.into(),
payload: vec![0xC1], // msgpack's own reserved "never used" marker byte
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(STORE_SCHEMA.into()),
};
{
let raw_store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
assert!(
raw_store
.compare_and_swap_batch(&[], vec![corrupt_row])
.unwrap(),
"seeding the corrupt row must succeed against an empty store"
);
}
// `.expect_err` needs `T: Debug`; `PlayTurnStore` does not derive it
// (its own row holds turn text nobody wants dumped by a failed
// assertion), so this matches directly instead.
let error = match PlayTurnStore::open(&store_path) {
Ok(_) => panic!("undecodable bytes must still refuse to open"),
Err(error) => error,
};
assert!(
error.to_string().contains("corrupt"),
"a genuinely undecodable row must still be named corrupt, not legacy: {error}"
);
}
/// The fork Self ruled on, isolated: a commit that changes only
/// `turn.refusal` — exactly the shape `execute_actor_call`'s
/// `ActionRejected` arm leaves a row in (the call's own record is
/// already persisted before submission, PA-Q8's "body durable before
/// effects" order; this second commit carries only the refusal, growing
/// neither `calls` nor `rounds`) — must still move the row's own
/// `revision`. A counter derived from `calls.len()` or `rounds.len()`
/// cannot see this commit at all, which is the exact gap that made a
/// persisted counter, not a derived one, the ruled answer.
///
/// Mutation: move `PlayTurnStore::swap_in`'s own `revision + 1` onto a
/// condition keyed off `turn.calls.len()` growing (or any other derived
/// field) instead of firing unconditionally on every commit — this
/// commit, which grows nothing, would then leave `revision` exactly
/// where it started, failing the assertion below.
#[tokio::test]
async fn a_commit_changing_only_the_refusal_still_moves_the_rows_own_revision() {
let directory = tempfile::tempdir().unwrap();
let mut store = PlayTurnStore::open(directory.path().join("play-turn-v1.cc")).unwrap();
let base = PlayTurn {
turn_id: test_turn_id(9001),
applied_keys: vec!["k0".into()],
opening_prompt: "opening".into(),
player_prose: vec!["I try the act.".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
store.open_new_turn(base.clone()).unwrap();
let revision_before = store.state.revision;
let mut refused = base;
refused.refusal = Some("refused".into());
store.commit(refused).unwrap();
let revision_after = store.state.revision;
assert!(
revision_after > revision_before,
"a commit that changes only the refusal line must still move the row's own revision: \
{revision_before} -> {revision_after}"
);
}
#[tokio::test]
async fn a_raw_op_is_journaled_as_play_and_never_as_an_actor() {
let fixture = play_world(None, "player-raw-op").await;
let declare = output(
"r0",
vec![
call_event(
"c0",
"declare_resource",
serde_json::json!({"handle": "gold", "label": "Gold"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![declare]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(2), "Declare a resource.".into())
.await
.unwrap();
// In Active phase, only the `Play` capability may admit an
// unanswered declare with no `PatchAnswer` (`require_answer` in
// `lib.rs`); every other caller is refused `AnswerRequired`. This
// resource's presence in the next snapshot is therefore possible
// only if the commit's caller was `System(Play)`.
let snapshot = fixture.world.snapshot().await.unwrap();
assert!(
table_view(&snapshot).contains("Gold"),
"the declared resource did not commit through the Play door"
);
}
#[tokio::test]
async fn an_act_for_an_undispatched_subject_is_refused() {
let fixture = play_world(Some("Mara"), "player-undispatched").await;
let before = fixture.world.snapshot().await.unwrap();
let mara = handle_for(persona_id(&before));
let round = output(
"r0",
vec![
call_event(
"c0",
&format!("{mara}__speak"),
serde_json::json!({"text": "never dispatched"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Silence.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(3), "Hello?".into())
.await
.unwrap();
// PA.f69 S2: `resolve_handle` refuses the undispatched handle before
// any door is touched — asserted, not merely "no panic" — and
// nothing about the world committed from it.
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(
result.contains("not the player or a subject dispatched this turn"),
"{result}"
);
let after = fixture.world.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision, "an undispatched act must commit nothing");
}
#[tokio::test]
async fn a_paraphrased_quote_is_refused() {
let fixture = play_world(None, "player-paraphrase").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let player = handle_for(player_id(&snapshot));
let round = output(
"r0",
vec![
call_event(
"c0",
&format!("{player}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "a whispered WARNING"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(100), "a whispered warning".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(result.contains("not an exact quote"), "{result}");
}
/// Mutation M8.1: if `span_is_exact` stopped checking a Persona's own
/// quotes, this would no longer hold — the paraphrase would commit.
#[tokio::test]
async fn a_paraphrased_quote_is_refused_for_a_persona() {
let fixture = play_world(Some("Mara"), "player-persona-paraphrase").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = handle_for(persona_id(&snapshot));
let mara_id = subject_id_text(&snapshot, persona_id(&snapshot));
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_id]}),
)],
);
let speak_round = output(
"r1",
vec![
call_event(
"c1",
&format!("{mara}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "I nod and SAY nothing"}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("I nod and say nothing")]),
output("proj-narrate", vec![text_event("The room settles.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![dispatch_round, speak_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(120), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 1 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(result.contains("not an exact quote"), "{result}");
}
/// PA.f115 (invariant 4): `span_is_exact`'s own
/// `.filter(|(id, _)| *id == actor.subject)` restricts a Persona's
/// sources to turns recorded *for that subject*; deleting it would let
/// one dispatched Persona speak another's prose verbatim, uncaught, by
/// pooling every dispatched Persona's recorded turns as a shared source
/// list. Mara and Borin are dispatched together; Mara's own `speak` call
/// quotes Borin's own recorded turn prose exactly and must still be
/// refused as not her own exact quote. Mutation: delete the filter in
/// `span_is_exact` (`play.rs`) and this must fail.
#[tokio::test]
async fn a_persona_cannot_speak_another_dispatched_personas_exact_quote() {
let fixture = play_world(Some("Mara"), "player-persona-cross-quote").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let affordance_id = bracketed_id_after(&table_view(&snapshot), "speak [");
// A second Persona subject, declared through the play table's own
// authoring door — the same mechanism
// `dispatch_order_never_changes_the_request_id_a_subject_gets` uses.
let declare = output(
"r0",
vec![
call_event(
"c0",
"declare_subject",
serde_json::json!({
"handle": "borin",
"label": "Borin",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let directory = tempfile::tempdir().unwrap();
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-declare", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![declare]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("declare-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(760), "Introduce Borin.".into())
.await
.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let borin = snapshot.subjects.iter().find(|row| row.label == "Borin").unwrap().id;
let mara_handle = handle_for(mara);
let mara_text = subject_id_text(&snapshot, mara);
let borin_text = subject_id_text(&snapshot, borin);
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_text, borin_text]}),
)],
);
let speak_round = output(
"r1",
vec![
call_event(
"c1",
&format!("{mara_handle}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "Borin says hello to the player."}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
output("proj-borin", vec![text_event("Borin waits his turn.")]),
output("persona-borin", vec![text_event("Borin says hello to the player.")]),
output("proj-narrate", vec![text_event("The room settles.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![dispatch_round, speak_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(761), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 1 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(
result.contains("not an exact quote"),
"Mara speaking Borin's own exact prose must still be refused: {result}"
);
}
/// A second world fixture, owed since 8a (PA-Q8): genesis's own
/// `WorldMailbox::create` grants only the kernel's own zero-role `speak`
/// affordance, whose sole precondition — `CanBroadcast(Colocated)` — is
/// satisfied even by a subject alone in a room, and `declare_affordance`
/// (the only door to a custom precondition) is not in `PLAY_TOOLS`, so
/// the play agent itself can never author one. This fixture instead
/// declares one directly on `fixture.world`, through
/// `decode_authoring_call` and `CommandBody::AdmitPatch`, while the world
/// is still in Draft — exactly the door genesis's own authoring root
/// uses, never anything `PLAY_TOOLS` gates. The affordance's one
/// precondition, `holds`, is bound to a resource role the player is
/// never granted any of, so any attempt against it is refused
/// deterministically, with no movement, authority, or standing setup
/// needed.
async fn play_world_with_precondition_affordance(account_hash: &str) -> (WorldFixture, AffordanceId) {
let directory = tempfile::tempdir().unwrap();
let (world, owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
let principal = VerifiedPrincipalEvidence::new(account_hash, far_future());
let receipt = world
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "Fixture World".into(),
brief: "A small table with one guarded affordance.".into(),
human_subject_label: "Player".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let resource_patch = decode_authoring_call(
"declare_resource",
&serde_json::json!({"handle": "guarded_resource", "label": "Guarded Resource"}).to_string(),
)
.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::AdmitPatch {
answers: None,
patch: resource_patch,
},
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
let affordance_patch = decode_authoring_call(
"declare_affordance",
&serde_json::json!({
"handle": "guarded_act",
"kind": "guarded_act",
"roles": [
{"role": "target", "kind": {"namespace": "entity", "kind": "resource"}},
],
"preconditions": [
{"precondition": "holds", "resource": "target", "at_least": 999_999},
],
"effect_slots": [
{
"op_kind": {"op": "consume"},
"roles": ["actor", "target"],
"bounds": {"bound": "quantity", "max": 1},
},
],
"outcome_bands": [{"weight": 1, "effects": []}],
"carries_speech": false,
})
.to_string(),
)
.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::AdmitPatch {
answers: None,
patch: affordance_patch,
},
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
let affordance_id = snapshot
.affordances
.iter()
.find(|entry| entry.entry.kind.0 == "guarded_act")
.unwrap()
.id;
let grant_patch = decode_authoring_call(
"grant_affordance",
&serde_json::json!({
"subject": {"ref": "existing", "value": subject_id_text(&snapshot, player)},
"affordance": {"ref": "existing", "value": affordance_id_text(&snapshot, affordance_id)},
})
.to_string(),
)
.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::AdmitPatch {
answers: None,
patch: grant_patch,
},
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ApproveDraft,
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ActivateWorld,
},
&principal,
)
.await
.unwrap();
(
WorldFixture {
_directory: directory,
world,
principal,
owner,
},
affordance_id,
)
}
/// The canonical id text for an affordance, read out of a real
/// `table_view` render, on the same precedent `subject_id_text` already
/// uses for a subject: never a test-local copy of the printer.
fn affordance_id_text(snapshot: &WorldSnapshot, id: AffordanceId) -> String {
let entry = snapshot.affordances.iter().find(|entry| entry.id == id).unwrap();
let view = table_view(snapshot);
let marker = format!("{} [", entry.entry.kind.0);
let start = view
.find(&marker)
.unwrap_or_else(|| panic!("{} not found in table_view: {view}", entry.entry.kind.0))
+ marker.len();
let end = view[start..]
.find(']')
.unwrap_or_else(|| panic!("unterminated id bracket after {} in table_view", entry.entry.kind.0));
view[start..start + end].to_owned()
}
/// The canonical id text for a declared resource, by its own label, read
/// out of `table_view`'s own `Resources:` section — `resources` itself is
/// `pub(crate)` inside `ghostlight`, so this crate has no field to read
/// it from directly.
fn resource_id_text(snapshot: &WorldSnapshot, label: &str) -> String {
let view = table_view(snapshot);
let section = view
.find("\n Resources:")
.map_or(view.as_str(), |at| &view[at..]);
let marker = format!(" {label} [");
let start = section
.find(&marker)
.unwrap_or_else(|| panic!("{label} not found in table_view's Resources section: {view}"))
+ marker.len();
let end = section[start..]
.find(']')
.unwrap_or_else(|| panic!("unterminated id bracket after {label} in table_view"));
section[start..start + end].to_owned()
}
/// PA-Q8, owed since 8a: `execute_actor_call`'s `ActionRejected` arm sets
/// `turn.refusal` to the *actor* form (invariant 8) — bare role names,
/// no id, no resolved label, no fact statement — never the agent-facing
/// `describe_refusal` text the tool call's own result still carries.
#[tokio::test]
async fn a_refused_player_act_sets_the_refusal_line() {
let (fixture, _affordance_id) = play_world_with_precondition_affordance("player-refusal-line").await;
let directory = tempfile::tempdir().unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let handle = handle_for(player);
let resource_id = resource_id_text(&snapshot, "Guarded Resource");
let round = output(
"r0",
vec![call_event(
"c0",
&format!("{handle}{HANDLE_SEPARATOR}guarded_act"),
serde_json::json!({
"target": resource_id,
"slot_0_qty": 1,
}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(881), "I try the guarded act.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let refusal = turn
.refusal
.as_deref()
.expect("a refused player act must set the actor-facing refusal line");
assert!(
!refusal.contains(&id_text(player)),
"the actor-facing refusal must carry no id: {refusal}"
);
assert!(
!refusal.to_lowercase().contains("guarded_resource") && !refusal.to_lowercase().contains("guarded resource"),
"the actor-facing refusal must not resolve or name the role's target: {refusal}"
);
}
/// PA.f144: `turn.refusal` names the *most recent* player act, not
/// whichever one last refused — round 0 refuses (setting the line, as
/// `a_refused_player_act_sets_the_refusal_line` above proves), round 1's
/// player act then commits, and the line must be gone, not still
/// showing round 0's now-stale refusal. Mutation: dropping the
/// `turn.refusal = None` this fix adds to `execute_actor_call`'s own
/// success arm.
#[tokio::test]
async fn a_later_successful_player_act_clears_an_earlier_refusal_line() {
let (fixture, _affordance_id) = play_world_with_precondition_affordance("player-f144-clears").await;
let directory = tempfile::tempdir().unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let handle = handle_for(player);
let resource_id = resource_id_text(&snapshot, "Guarded Resource");
const OPENING: &str = "I try the guarded act.";
let refused_round = output(
"r0",
vec![call_event(
"c0",
&format!("{handle}{HANDLE_SEPARATOR}guarded_act"),
serde_json::json!({
"target": resource_id,
"slot_0_qty": 1,
}),
)],
);
// Round 1's own speak call quotes the turn's own opening prose
// exactly (`span_is_exact`'s own player source, PA.f84: a `Running`
// continue never adds fresh `player_prose`, so this is the only text
// a player act can quote mid-turn without a fresh `ask_player`
// round).
let successful_round = output(
"r1",
vec![
call_event(
"c1",
&format!("{handle}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": OPENING}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-narrate", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![refused_round, successful_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table.run(&fixture.principal, test_turn_id(968), OPENING.into()).await.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert!(
turn.refusal.is_none(),
"a later successful player act must clear an earlier round's own refusal line: {:?}",
turn.refusal
);
let speak_result = turn
.calls
.iter()
.find(|call| call.round == 1 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert_eq!(speak_result, "applied", "the later act must itself have actually committed: {speak_result}");
}
#[tokio::test]
async fn a_mint_and_a_ruled_fact_commit_as_play() {
let fixture = play_world(None, "player-mint").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-a", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_resource",
serde_json::json!({"handle": "gold", "label": "Gold"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(90), "Declare gold.".into())
.await
.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let view = table_view(&snapshot);
let resource_id = view
.split("Gold [")
.nth(1)
.and_then(|rest| rest.split(']').next())
.expect("Gold's bracketed id is printed in table_view")
.to_owned();
let player = subject_id_text(&snapshot, player_id(&snapshot));
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-b", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let round = output(
"r0",
vec![
call_event(
"c0",
"mint",
serde_json::json!({
"holder": {"ref": "existing", "value": player},
"resource": {"ref": "existing", "value": resource_id},
"qty": 5,
}),
),
call_event(
"c1",
"declare_fact",
serde_json::json!({
"handle": "ruling",
"label": "The Ruling",
"statement": "Five bars of gold sit in the vault.",
"standing": {"standing": "ruled"},
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(
&fixture.principal,
test_turn_id(91),
"Mint gold and rule it so.".into(),
)
.await
.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let view = table_view(&snapshot);
assert!(view.contains("5 of Gold"), "the mint did not commit: {view}");
// `table_view`'s Facts section lists only facts some subject knows
// (built from `subject.knowledge`, PA-Q7's own doc comment on
// `table_view`); a `declare_fact` with nobody granted knowledge of
// it is invisible there by design, so this checks the call's own
// recorded result instead of the rendered view.
let stored = PlayTurnStore::open(&store_path).unwrap();
let turn = stored.current().unwrap();
let fact_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 1)
.and_then(|call| call.result.clone())
.unwrap();
assert_eq!(fact_result, "applied", "the ruled fact did not commit: {fact_result}");
assert!(!PLAY_TOOLS.contains(&"admit"), "admit is not a play tool");
}
#[tokio::test]
async fn a_persona_fault_becomes_a_tool_result_and_the_turn_continues() {
let fixture = play_world(Some("Mara"), "player-persona-fault").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = subject_id_text(&snapshot, persona_id(&snapshot));
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas_port = ScriptedPort::new(vec![]);
// Faults the dispatch's own Projector inference; one clean output is
// reserved for the player's own closing narration.
personas_port
.queue
.lock()
.unwrap()
.push_back(Err("provider unavailable".into()));
personas_port
.queue
.lock()
.unwrap()
.push_back(Ok(output("proj-narrate", vec![text_event("Quiet.")])));
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
personas_port,
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(80), "Hello.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(dispatch_result.contains("could not act"), "{dispatch_result}");
}
#[tokio::test]
async fn persona_dispatch_draws_only_from_the_permit_pool() {
let fixture = play_world(Some("Mara"), "player-permits").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = subject_id_text(&snapshot, persona_id(&snapshot));
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara nods.")]),
output("persona-mara", vec![text_event("I nod back.")]),
output("proj-narrate", vec![text_event("The room is quiet.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let permits = Arc::new(Semaphore::new(3));
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
permits.clone(),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(70), "Who's there?".into())
.await
.unwrap();
assert_eq!(
permits.available_permits(),
3,
"a dispatch must release every permit it acquires"
);
}
/// PA.f98: `dispatch` takes the subject id exactly as `table_view` prints
/// it in brackets (the full canonical id), not the short `<handle>__`
/// actor-tool prefix. Mutation: reverting `parse_dispatch` to match
/// `handle_for` instead of `full_id_text` fails this, because the id
/// given here is longer than 8 hex digits.
#[tokio::test]
async fn dispatch_by_the_printed_full_id_runs_the_persona() {
let fixture = play_world(Some("Mara"), "player-dispatch-full-id").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara_id = subject_id_text(&snapshot, persona_id(&snapshot));
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_id]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
output("proj-narrate", vec![text_event("Quiet.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(71), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(dispatch_result.contains("Mara nods once."), "{dispatch_result}");
}
/// PA.f124: `execute_dispatch`'s own summaries print a subject through
/// the library's `id_text` — the same printer `table_view` and
/// `dispatch`'s own matching use — never `{subject:?}`'s raw
/// `SubjectId(...)` debug wrapper, a fifth hand-spelled id spelling.
/// Dispatching the same subject twice in one call reaches the
/// `"already acted"` branch, the one call site printing a subject
/// without a `snapshot` (`subject_label`) to fall back on. Mutation:
/// reverting either print in `execute_dispatch` to `{subject:?}` fails
/// this.
#[tokio::test]
async fn dispatch_summaries_print_the_subject_through_id_text_not_debug() {
let fixture = play_world(Some("Mara"), "player-dispatch-id-text-summary").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let mara_text = subject_id_text(&snapshot, mara);
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_text.clone(), mara_text.clone()]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
output("proj-narrate", vec![text_event("Quiet.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(922), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(
dispatch_result.contains(&format!("{mara_text} already acted")),
"the repeated subject must be named by id_text's own spelling, not SubjectId(...) debug: {dispatch_result}"
);
assert!(
!dispatch_result.contains("SubjectId("),
"the debug wrapper must never leak into a dispatch summary: {dispatch_result}"
);
}
/// PA.f98: an id naming no dispatchable subject is refused in the tool
/// result, quoting the text given, rather than being silently dropped.
#[tokio::test]
async fn an_unknown_dispatch_id_is_refused_naming_it() {
let fixture = play_world(Some("Mara"), "player-dispatch-unknown-id").await;
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": ["not-a-real-id"]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
// No queued output: if the unknown id were somehow dispatched
// anyway, the persona lane would fault trying to pop from an
// empty queue, and this test would fail loudly rather than
// silently accepting a dropped id.
ScriptedPort::new(vec![output("proj-narrate", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(72), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(
dispatch_result.contains("`not-a-real-id` names no dispatchable subject"),
"{dispatch_result}"
);
}
/// PA.f98: a mixed dispatch list runs every valid id and names every
/// invalid one in the same call's result — neither is dropped, and the
/// valid one still actually acts.
#[tokio::test]
async fn a_mixed_dispatch_list_runs_the_valid_id_and_names_the_invalid_one() {
let fixture = play_world(Some("Mara"), "player-dispatch-mixed").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara_id = subject_id_text(&snapshot, persona_id(&snapshot));
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_id, "not-a-real-id"]}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
output("proj-narrate", vec![text_event("Quiet.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(73), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(dispatch_result.contains("Mara nods once."), "{dispatch_result}");
assert!(
dispatch_result.contains("`not-a-real-id` names no dispatchable subject"),
"{dispatch_result}"
);
}
/// PA.f114: `PLAY_INSTRUCTIONS` promises an id naming no dispatchable
/// subject is refused, quoting what was given, rather than silently
/// doing nothing. `parse_dispatch` used to drop a non-string entry with
/// `Value::as_str` filtering it out unseen; it is now refused by name.
/// Tested directly against `parse_dispatch`, the exact function the
/// dispatch tool call handler runs the arguments through.
#[tokio::test]
async fn a_non_string_dispatch_entry_is_refused_quoting_it() {
let fixture = play_world(Some("Mara"), "player-dispatch-non-string").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let (subjects, refusals) = parse_dispatch(r#"{"subjects": [42, true]}"#, &snapshot);
assert!(subjects.is_empty());
assert_eq!(
refusals,
vec![
"`42` in `subjects` is not a string".to_owned(),
"`true` in `subjects` is not a string".to_owned(),
]
);
}
/// PA.f114: a body that isn't valid JSON, and a body whose JSON isn't an
/// object, are each refused quoting the text given — not the silent
/// empty dispatch `parse_dispatch` used to return for both.
#[tokio::test]
async fn a_malformed_dispatch_body_is_refused_quoting_it() {
let fixture = play_world(Some("Mara"), "player-dispatch-malformed").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let (subjects, refusals) = parse_dispatch("not json at all", &snapshot);
assert!(subjects.is_empty());
assert_eq!(refusals.len(), 1, "{refusals:?}");
assert!(refusals[0].contains("not valid JSON"), "{refusals:?}");
assert!(refusals[0].contains("not json at all"), "{refusals:?}");
let (subjects, refusals) = parse_dispatch(r#"["a", "b"]"#, &snapshot);
assert!(subjects.is_empty());
assert_eq!(refusals.len(), 1, "{refusals:?}");
assert!(refusals[0].contains("not a JSON object"), "{refusals:?}");
}
/// PA.f114: `dispatch`'s arguments missing the `subjects` key entirely
/// are refused rather than read as an empty dispatch list.
#[tokio::test]
async fn a_dispatch_body_missing_subjects_key_is_refused() {
let fixture = play_world(Some("Mara"), "player-dispatch-missing-key").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let (subjects, refusals) = parse_dispatch("{}", &snapshot);
assert!(subjects.is_empty());
assert_eq!(refusals.len(), 1, "{refusals:?}");
assert!(refusals[0].contains("no `subjects` key"), "{refusals:?}");
}
#[tokio::test]
async fn a_question_holds_the_turn_open_across_a_restart() {
let fixture = play_world(None, "player-question").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let opening_key = test_turn_id(60);
let ask = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
// PA.f155/PA.f156: the row's own revision counter must survive the
// restart exactly, neither reset nor re-derived from anything but
// what was last durably committed — checked at three points below:
// right after the question opens, right after the fresh table
// reopens the same store (nothing committed yet, so unchanged), and
// once more after the answer closes the turn (moved again).
let revision_before_restart;
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(
&fixture.principal,
opening_key.clone(),
"I stand at a crossroads.".into(),
)
.await
.unwrap();
revision_before_restart = table.current_turn_view().await.unwrap().revision;
}
// "Restart": a fresh `PlayTable` reopening the same store path.
// `PlayTable::new` is the one production door that mints `PlayPort`;
// this fixture reuses this table's own `play` field for the
// world-drift commit below rather than minting a second one.
let end = output("r1", vec![call_event("c1", END_TURN_TOOL, serde_json::json!({}))]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-after", vec![text_event("You choose left.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
assert_eq!(
table.current_turn_view().await.unwrap().revision, revision_before_restart,
"reopening the store must read the same revision back, not reset or recompute it"
);
let (opening_prompt_before, turn_id_before, question_id) = {
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
(turn.opening_prompt.clone(), turn.turn_id.clone(), turn.open_question_id().unwrap())
};
// World drift between the question and the answer: a real snapshot
// taken now would print differently. Mutation M8.2 (rebuilding
// `opening_prompt` on resume) is caught by the assertion below.
table
.play
.submit_patch(
CommandId::new(),
decode_authoring_call(
"declare_resource",
&serde_json::json!({"handle": "silver", "label": "Silver"}).to_string(),
)
.unwrap(),
)
.await
.unwrap();
// The answer's own request key (PA.f62/PA.f63): a fresh key, not the
// turn's own identity — the whole point of separating the two is
// that a caller answering a question need not carry the turn's
// original opening key forward.
let answer_key = test_turn_id(61);
table
.run(
&fixture.principal,
answer_key,
PlayRequest {
text: "left".into(),
answers: Some(question_id),
},
)
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.opening_prompt, opening_prompt_before,
"opening_prompt must never be rebuilt on resume (mutation M8.2)"
);
assert_eq!(
turn.turn_id, turn_id_before,
"the turn's own identity, minted once when it opened, never moves"
);
assert_ne!(
turn.turn_id, opening_key,
"turn_id is minted fresh (PA.f83), never taken from the opening request key"
);
assert_eq!(turn.state, PlayTurnState::Closed);
assert_eq!(
turn.player_prose,
vec!["I stand at a crossroads.".to_owned(), "left".to_owned()]
);
assert!(turn.narration.is_some());
drop(stored);
let revision_after_close = table.current_turn_view().await.unwrap().revision;
assert!(
revision_after_close > revision_before_restart,
"the row's own revision must move again once the answer closes the turn: {revision_before_restart} -> {revision_after_close}"
);
}
#[tokio::test]
async fn a_resumed_call_resubmits_its_recorded_body() {
let fixture = play_world(None, "player-resume-body").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(50);
// `PlayTable::new` is the one production door that mints `PlayPort`
// (pinned by `soul_exactly_one_production_site_mints_play_port`);
// this fixture reuses the table's own `play` field for the
// out-of-band pre-crash commit below rather than minting a second
// one.
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-resume", vec![text_event("Still here.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let patch = decode_authoring_call(
"declare_resource",
&serde_json::json!({"handle": "gold", "label": "Gold"}).to_string(),
)
.unwrap();
let command_id = derived_command_id(&turn_id, 0, 0);
// The exact crash window this rule protects: the kernel already
// committed the call, but the store never recorded its result.
table.play.submit_patch(command_id, patch.clone()).await.unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let opening_prompt = format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"Make gold."
);
let call_id = "c0".to_owned();
let round = output(
"r0",
vec![
call_event(&call_id, "declare_resource", serde_json::json!({"handle": "gold", "label": "Gold"})),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt,
player_prose: vec!["Make gold.".into()],
rounds: vec![round],
calls: vec![CallRecord {
call_id,
round: 0,
slot: 0,
body: Some(RecordedCall::Authoring(patch)),
result: None,
}],
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(crashed_turn).unwrap();
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let view = table_view(&snapshot);
assert_eq!(
view.matches("Gold").count(),
1,
"the resumed call must resubmit its recorded body idempotently, not double-commit: {view}"
);
}
/// Mutation M8.3: rebuilding the body from a fresh snapshot on resume,
/// instead of resubmitting the recorded `(opportunity, invocation)`
/// verbatim, fails the kernel's own opportunity-identity check —
/// `PA.f41`'s rule that a caller's opportunity must equal the kernel's
/// currently issued copy exactly — the moment a second `declare_resource`
/// between the crash and the resume has changed the world's revision.
#[tokio::test]
async fn a_resumed_actor_call_resubmits_its_recorded_body() {
let fixture = play_world(None, "player-resume-actor").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(51);
// `PlayTable::new` is the one production door that mints `PlayPort`;
// this fixture reuses the table's own `play` field below instead of
// minting a second one.
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-resume", vec![text_event("Still here.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let (opportunity, invocation) =
decode_actor_call(&snapshot, player, "", "speak", &serde_json::json!({"text": "hold fast"}).to_string())
.unwrap();
let command_id = derived_command_id(&turn_id, 0, 0);
// The crash window: the kernel already committed the exercise, but
// the store never recorded its result. The world then drifts
// (a second, unrelated commit) before the resume runs.
fixture
.world
.submit_principal(
PrincipalCommandIntent {
id: command_id,
world_id: opportunity.world_id,
expected_revision: 0,
body: CommandBody::ExerciseDecision {
opportunity: opportunity.clone(),
invocation: invocation.clone(),
},
},
&fixture.principal,
)
.await
.unwrap();
table
.play
.submit_patch(
CommandId::new(),
decode_authoring_call(
"declare_resource",
&serde_json::json!({"handle": "silver", "label": "Silver"}).to_string(),
)
.unwrap(),
)
.await
.unwrap();
let opening_prompt = format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"hold fast"
);
let call_id = "c0".to_owned();
let player_handle = handle_for(player);
let round = output(
"r0",
vec![
call_event(
&call_id,
&format!("{player_handle}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "hold fast"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt,
player_prose: vec!["hold fast".into()],
rounds: vec![round],
calls: vec![CallRecord {
call_id,
round: 0,
slot: 0,
body: Some(RecordedCall::PlayerAct(opportunity, invocation)),
result: None,
}],
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(crashed_turn).unwrap();
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
let result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert_eq!(result, "applied", "a resubmitted actor call must resolve to AlreadyApplied, not a fresh refusal: {result}");
}
/// PA.f118: `execute_round`'s own `self.play.snapshot()` failing was
/// reported as untested because no fixture tore the world mailbox down
/// independently of the `WorldMailbox` the whole test depends on —
/// false: `WorldFixture` keeps its own mailbox owner task rather than
/// discarding it, and `.abort()`ing it drops the owner's own channel
/// receiver, so the very next mailbox call resolves
/// `MailboxError::Unavailable` deterministically. A round is left
/// unresolved as if the process had crashed mid-round; resuming it with
/// the mailbox owner aborted must close the turn with the fault
/// recorded rather than propagate the error out of `run` unhandled.
/// Mutation: turning the match arm back into a bare
/// `self.play.snapshot().await?` makes `run` return `Err` instead of
/// `Ok` with the fault recorded, failing this.
#[tokio::test]
async fn a_snapshot_failure_mid_round_closes_with_the_fault_recorded() {
let fixture = play_world(None, "player-round-snapshot-fault").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(910);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let call_id = "c0".to_owned();
let round = output("r0", vec![call_event(&call_id, END_TURN_TOOL, serde_json::json!({}))]);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt: "Opening.".into(),
player_prose: vec!["Who's there?".into()],
rounds: vec![round],
calls: vec![CallRecord {
call_id,
round: 0,
slot: 0,
body: None,
result: None,
}],
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(crashed_turn).unwrap();
// The very next mailbox call — the `self.play.snapshot()`
// `execute_round` makes to resolve the unresolved round above —
// fails deterministically once the owner task is gone.
fixture.owner.abort();
let outcome = table.run(&fixture.principal, turn_id, String::new().into()).await.unwrap();
assert!(matches!(outcome, RunOutcome::Ran { .. }));
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert!(
turn.fault.is_some(),
"a snapshot failure mid-round must close the turn with the fault recorded, not propagate: {:?}",
turn.fault
);
assert_eq!(turn.state, PlayTurnState::Closed);
}
/// A persona port wrapping `ScriptedPort` that aborts a world mailbox's
/// own owner task the moment its *first* `infer` call completes (PA.f118,
/// PA.f119): aborting only ever kills *future* mailbox calls — the
/// persona lane's own inference calls never touch `self.play` at all —
/// so a first dispatched subject's own Persona turn (two `infer` calls,
/// projector then persona) still finishes normally, and only a *second*
/// dispatched subject's own `execute_dispatch`-internal
/// `self.play.snapshot()` call, made after the first subject's turn
/// completes, is guaranteed to observe the aborted owner. Gives
/// deterministic, in-process control over exactly when the mailbox goes
/// down mid-dispatch, without timing races.
struct AbortAfterFirstPort {
inner: Arc<ScriptedPort>,
owner: StdMutex<Option<JoinHandle<()>>>,
}
impl AbortAfterFirstPort {
fn new(inner: Arc<ScriptedPort>, owner: JoinHandle<()>) -> Arc<Self> {
Arc::new(Self {
inner,
owner: StdMutex::new(Some(owner)),
})
}
}
#[async_trait::async_trait]
impl InferencePort for AbortAfterFirstPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let result = self.inner.infer(request).await;
if let Some(owner) = self.owner.lock().unwrap().take() {
owner.abort();
}
result
}
}
/// PA.f118, PA.f119: the same failure as
/// `a_snapshot_failure_mid_round_closes_with_the_fault_recorded`, at
/// `execute_dispatch`'s own separate `self.play.snapshot()` call site.
/// Mara and Borin are dispatched together in one call; the persona port
/// aborts the world mailbox's own owner task right after Mara's first
/// inference call, so her own dispatch still completes, and Borin's own
/// `execute_dispatch`-internal snapshot then fails deterministically.
/// Mutation: turning that match arm back into a bare
/// `self.play.snapshot().await?` makes `run` return `Err` instead of
/// `Ok` with the fault recorded and Mara's own successful dispatch
/// discarded, failing this.
#[tokio::test]
async fn a_snapshot_failure_mid_dispatch_closes_with_the_fault_recorded() {
let fixture = play_world(Some("Mara"), "player-dispatch-snapshot-fault").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let affordance_id = bracketed_id_after(&table_view(&snapshot), "speak [");
// A second Persona subject, declared through the play table's own
// authoring door — the same mechanism
// `a_persona_cannot_speak_another_dispatched_personas_exact_quote` uses.
let declare = output(
"r0",
vec![
call_event(
"c0",
"declare_subject",
serde_json::json!({
"handle": "borin",
"label": "Borin",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let directory = tempfile::tempdir().unwrap();
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-declare", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![declare]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("declare-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(913), "Introduce Borin.".into())
.await
.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let borin = snapshot.subjects.iter().find(|row| row.label == "Borin").unwrap().id;
let mara_text = subject_id_text(&snapshot, mara);
let borin_text = subject_id_text(&snapshot, borin);
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_text, borin_text]}),
)],
);
let scripted = ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
AbortAfterFirstPort::new(scripted, fixture.owner),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![dispatch_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
let outcome = table
.run(&fixture.principal, test_turn_id(914), "Who's there?".into())
.await
.unwrap();
assert!(matches!(outcome, RunOutcome::Ran { .. }));
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert!(
turn.fault.is_some(),
"a snapshot failure mid-dispatch must close the turn with the fault recorded, not propagate: {:?}",
turn.fault
);
assert_eq!(turn.state, PlayTurnState::Closed);
assert!(
turn.persona_turns.iter().any(|(id, _)| *id == mara),
"Mara's own dispatch, already snapshot-successful before the abort, must still be recorded"
);
assert!(
!turn.persona_turns.iter().any(|(id, _)| *id == borin),
"Borin's own dispatch must never have started"
);
}
// The old `soul_execute_round_and_round_tools_share_the_collision_refusal_call`
// structural test (PA.f118/PA.f119) counted `collision_refusal(` call
// sites in `play.rs` and pinned it at 2, standing in for behaviour it had
// no seam to observe directly. PA.f127/PA.f133 collapsed the duplicate
// fetch-and-check `infer_round` and `execute_round` each ran into one
// shared owner, `round_snapshot` (which itself now calls
// `collision_refusal` exactly once), so that count is 1 by design and the
// structural test is gone. `fetch_round_snapshot`'s own test seam
// (`force_round_snapshot`) now drives a genuine, real-id collision
// through `round_snapshot` directly — see
// `a_forced_handle_collision_refuses_the_round_through_round_snapshot`
// below — which is real behavioural coverage neither `infer_round` nor
// `execute_round` could get independently before this cut, and it covers
// both callers at once because there is only one implementation left to
// call.
#[tokio::test]
async fn restart_equivalence_of_the_agent_input() {
let directory = tempfile::tempdir().unwrap();
let world_path = directory.path().join("world.cc");
let store_path = directory.path().join("play-turn-v1.cc");
let backup_path = directory.path().join("play-turn-v1.backup.cc");
let principal = VerifiedPrincipalEvidence::new("player-restart-equiv", far_future());
let (world, owner) = WorldMailbox::open(&world_path).unwrap();
let receipt = world
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "Restart Equivalence".into(),
brief: String::new(),
human_subject_label: "Player".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ApproveDraft,
},
&principal,
)
.await
.unwrap();
let snapshot = world.snapshot().await.unwrap();
world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: snapshot.revision,
body: CommandBody::ActivateWorld,
},
&principal,
)
.await
.unwrap();
{
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
ScriptedPort::new(vec![output("proj-1", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&principal, test_turn_id(30), "Turn one.".into())
.await
.unwrap();
}
// Turn two opens and asks a question, fixing its own `turn_id` in
// the store (PA.f83: minted fresh, not derived from the key) before
// the backup is taken — a fresh `begin_turn` mints a new random
// `turn_id` every time it runs, so two *independent* openings from
// the same prior state are no longer expected to produce identical
// requests. Resuming one *already-open* turn across a restart still
// must, and that is what this test now checks.
let (question_id, turn2_id) = {
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let ask = output(
"r0",
vec![call_event("c0", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which path?"}))],
);
let table = PlayTable::new(
world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&principal, test_turn_id(31), "Turn two.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
(turn.open_question_id().unwrap(), turn.turn_id.clone())
};
std::fs::copy(&store_path, &backup_path).unwrap();
let answer_end = || output("r1", vec![call_event("c1", END_TURN_TOOL, serde_json::json!({}))]);
// Path A: no restart, answer the already-open question directly.
let request_a = {
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
ScriptedPort::new(vec![output("proj-2a", vec![text_event("Still fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let port = ScriptedPort::new(vec![answer_end()]);
let table = PlayTable::new(
world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(
&principal,
test_turn_id(32),
PlayRequest {
text: "left".into(),
answers: Some(question_id.clone()),
},
)
.await
.unwrap();
port.seen_requests().into_iter().next().unwrap()
};
// Restart: drop every live clone of the world mailbox, join its
// owner task, restore the store to its post-question state, and
// reopen both.
std::fs::copy(&backup_path, &store_path).unwrap();
drop(world);
owner.await.unwrap();
let (world, _owner) = WorldMailbox::open(&world_path).unwrap();
let request_b = {
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
ScriptedPort::new(vec![output("proj-2b", vec![text_event("Still fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let port = ScriptedPort::new(vec![answer_end()]);
let table = PlayTable::new(
world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(
&principal,
test_turn_id(32),
PlayRequest {
text: "left".into(),
answers: Some(question_id.clone()),
},
)
.await
.unwrap();
let stored = table.store.lock().await;
assert_eq!(stored.current().unwrap().turn_id, turn2_id, "the resumed turn's own id must survive the restart unchanged");
drop(stored);
port.seen_requests().into_iter().next().unwrap()
};
assert_eq!(request_a, request_b);
}
// --- Fix batch 8a-fix ------------------------------------------------
/// The bracketed canonical id following one label in `table_view`'s own
/// rendering, the same parsing `a_mint_and_a_ruled_fact_commit_as_play`
/// already relies on for a declared resource's id.
fn bracketed_id_after(view: &str, needle: &str) -> String {
view.split(needle)
.nth(1)
.and_then(|rest| rest.split(']').next())
.unwrap_or_else(|| panic!("`{needle}` not found in table_view: {view}"))
.to_owned()
}
/// PA.f61: `set_persona_material` refuses an existing subject.
#[tokio::test]
async fn set_persona_material_on_an_existing_subject_is_refused() {
let fixture = play_world(None, "player-persona-existing").await;
let before = fixture.world.snapshot().await.unwrap();
let player = subject_id_text(&before, player_id(&before));
let round = output(
"r0",
vec![
call_event(
"c0",
"set_persona_material",
serde_json::json!({
"subject": {"ref": "existing", "value": player},
"values": ["steadfast"],
"voice": "flat and even",
"memories": [],
"reads": [],
}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(400), "Rewrite the player.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert!(result.contains("existing subject"), "{result}");
let after = fixture.world.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision, "a refused run must commit nothing");
}
/// PA.f61 + PA.f54: `set_persona_material` stands for a subject the same
/// authoring run declares — the draft handle resolves only because the
/// whole run decodes as one shared patch.
#[tokio::test]
async fn set_persona_material_on_a_same_run_declared_subject_commits() {
let fixture = play_world(None, "player-persona-declared").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let affordance_id = bracketed_id_after(&table_view(&snapshot), "speak [");
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_subject",
serde_json::json!({
"handle": "npc",
"label": "A Stranger",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event(
"c1",
"set_persona_material",
serde_json::json!({
"subject": {"ref": "draft", "value": "npc"},
"values": ["steadfast"],
"voice": "flat and even",
"memories": ["the first watch"],
"reads": [],
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(401), "Introduce a stranger.".into())
.await
.unwrap();
let after = fixture.world.snapshot().await.unwrap();
let view = table_view(&after);
assert!(view.contains("A Stranger"), "{view}");
assert!(view.contains("flat and even"), "the persona material did not commit: {view}");
}
/// PA.f54: a maximal run of authoring calls commits atomically, as one
/// kernel command — a later call's declaration resolving an earlier
/// call's draft handle in the same run is possible only because both
/// land in one shared patch.
#[tokio::test]
async fn an_authoring_run_commits_as_one_patch() {
let fixture = play_world(None, "player-run-atomic").await;
let before = fixture.world.snapshot().await.unwrap();
let commons_id = bracketed_id_after(&table_view(&before), "The Commons [");
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_place",
serde_json::json!({"handle": "cell", "label": "A Narrow Cell", "container": null}),
),
call_event(
"c1",
"declare_route",
serde_json::json!({
"handle": "hall",
"label": "The Hall",
"from": {"ref": "existing", "value": commons_id},
"to": {"ref": "draft", "value": "cell"},
"access": {"access": "public"},
"cost": 1,
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(402), "Build a hall to a cell.".into())
.await
.unwrap();
let after = fixture.world.snapshot().await.unwrap();
assert_eq!(
after.revision,
before.revision + 1,
"the whole run must commit as one kernel command, not two"
);
let view = table_view(&after);
assert!(view.contains("A Narrow Cell"), "{view}");
assert!(view.contains("The Hall"), "{view}");
}
/// PA.f54: a refusal inside a run names the exact call that caused it,
/// through the run's own `DecodedBatch` site map, and nothing in the run
/// commits — not even an earlier call's own declaration.
#[tokio::test]
async fn a_refusal_in_a_run_names_the_failing_call_and_nothing_commits() {
let fixture = play_world(None, "player-run-refusal").await;
let before = fixture.world.snapshot().await.unwrap();
let player = handle_for(player_id(&before));
// `declare_place` (call #0) decodes cleanly; `relocate` (call #1) —
// an *operation*, not a declaration — references a route draft
// handle nothing in this run ever declares. An operation mismatch's
// site is attributed by exact call index through the run's own
// `DecodedBatch`, unlike a declaration's own (handle-named) site.
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_place",
serde_json::json!({"handle": "cell", "label": "A Narrow Cell", "container": null}),
),
call_event(
"c1",
"relocate",
serde_json::json!({
"subject": {"ref": "existing", "value": player},
"via": {"ref": "draft", "value": "no_such_route"},
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(403), "Build a hall to nowhere.".into())
.await
.unwrap();
let after = fixture.world.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision, "a refused run must commit nothing");
assert!(
!table_view(&after).contains("A Narrow Cell"),
"the first call's own declaration must not commit either"
);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result0 = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
let result1 = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 1)
.and_then(|call| call.result.clone())
.unwrap();
assert!(result1.contains("call #1"), "{result1}");
assert_eq!(result0, result1, "every call in a run shares the run's own single outcome");
}
/// One half of PA.f87's replacement for the old source-text-position
/// pin: given a store that already holds a run's own recorded body from
/// before a crash (built directly here, the same "crash window" shape
/// `a_resumed_call_resubmits_its_recorded_body` uses for a single
/// call), resume must resubmit that exact recorded body idempotently —
/// one kernel commit, not two. This alone does not prove the record
/// happens *before* the submit in a first, non-resumed attempt; see
/// `commit_authoring_run_records_the_run_even_when_its_submit_is_refused`
/// for that half.
#[tokio::test]
async fn a_resumed_authoring_run_resubmits_its_recorded_shared_patch() {
let fixture = play_world(None, "player-resume-run").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(52);
// `PlayTable::new` is the one production door that mints `PlayPort`;
// this fixture reuses the table's own `play` field for the
// out-of-band pre-crash commit below rather than minting a second
// one.
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-resume-run", vec![text_event("Still here.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let before = fixture.world.snapshot().await.unwrap();
let commons_id = bracketed_id_after(&table_view(&before), "The Commons [");
let declare_place_args =
serde_json::json!({"handle": "cell", "label": "A Narrow Cell", "container": null}).to_string();
let declare_route_args = serde_json::json!({
"handle": "hall",
"label": "The Hall",
"from": {"ref": "existing", "value": commons_id},
"to": {"ref": "draft", "value": "cell"},
"access": {"access": "public"},
"cost": 1,
})
.to_string();
let decoded = decode_authoring_calls(&[
("declare_place", declare_place_args.as_str()),
("declare_route", declare_route_args.as_str()),
])
.unwrap();
let patch = decoded.patch.clone();
let command_id = derived_command_id(&turn_id, 0, 0);
// The exact crash window this rule protects: the kernel already
// committed the run's own shared patch, but the store never
// recorded its result.
table.play.submit_patch(command_id, patch.clone()).await.unwrap();
let opening_prompt = format!("{}\n\nThe player writes:\n{}\n", table_view(&before), "Build a hall.");
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_place",
serde_json::json!({"handle": "cell", "label": "A Narrow Cell", "container": null}),
),
call_event(
"c1",
"declare_route",
serde_json::json!({
"handle": "hall",
"label": "The Hall",
"from": {"ref": "existing", "value": commons_id},
"to": {"ref": "draft", "value": "cell"},
"access": {"access": "public"},
"cost": 1,
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt,
player_prose: vec!["Build a hall.".into()],
rounds: vec![round],
calls: vec![CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Authoring(patch)),
result: None,
}],
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(crashed_turn).unwrap();
table.run(&fixture.principal, turn_id, String::new().into()).await.unwrap();
let after = fixture.world.snapshot().await.unwrap();
// One commit, not two: the world's own revision counter is the
// unambiguous signal — `table_view` prints a place's own label a
// second time wherever a route mentions it as an endpoint, so a
// substring count is not (this mirrors `an_authoring_run_commits_as_one_patch`'s
// own revision-based check).
assert_eq!(
after.revision,
before.revision + 1,
"the resumed run must resubmit its recorded shared patch idempotently, not double-commit"
);
let view = table_view(&after);
assert!(view.contains("A Narrow Cell"), "{view}");
assert!(view.contains("The Hall"), "{view}");
}
/// The other half of PA.f87: `commit_authoring_run` must record the
/// run's own decoded patch *before* it ever finds out whether
/// `submit_patch` will succeed — not only after a success, and not only
/// when a caller happens to resume a pre-crashed turn. Proven with a
/// run whose kernel submission is genuinely refused (the same
/// `relocate`-to-a-nonexistent-route shape
/// `a_refusal_in_a_run_names_the_failing_call_and_nothing_commits`
/// uses): the decode itself succeeds, so a correct `commit_authoring_run`
/// records the run's own patch regardless of what the kernel later says
/// about it. Mutations: delete
/// `record_call(..., Some(RecordedCall::Authoring(...)), ...)`, or move
/// it inside the `Ok(_receipt) =>` success arm of the `submit_patch`
/// match (making the record conditional on success); both leave the
/// anchor slot's own `body` unset after this refusal, failing this test.
#[tokio::test]
async fn commit_authoring_run_records_the_run_even_when_its_submit_is_refused() {
let fixture = play_world(None, "player-record-before-refused-submit").await;
let before = fixture.world.snapshot().await.unwrap();
let player = subject_id_text(&before, player_id(&before));
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_place",
serde_json::json!({"handle": "cell", "label": "A Narrow Cell", "container": null}),
),
call_event(
"c1",
"relocate",
serde_json::json!({
"subject": {"ref": "existing", "value": player},
"via": {"ref": "draft", "value": "no_such_route"},
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(53), "Build a hall to nowhere.".into())
.await
.unwrap();
let after = fixture.world.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision, "a refused run must commit nothing to the world");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let anchor = turn.calls.iter().find(|call| call.round == 0 && call.slot == 0).unwrap();
assert!(
matches!(anchor.body, Some(RecordedCall::Authoring(_))),
"the run's own decoded patch must be recorded even though the kernel refused it: {:?}",
anchor.body
);
assert!(
anchor.result.as_deref().unwrap_or_default().contains("refused"),
"{:?}",
anchor.result
);
}
/// PA.f64: a dispatched Persona's own prose reaches the agent as the
/// dispatch call's own tool result, verbatim, both on the round it
/// happened and after a restart resumes a later round.
#[tokio::test]
async fn a_dispatched_personas_prose_reaches_the_agents_next_request() {
let fixture = play_world(Some("Mara"), "player-dispatch-prose").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = subject_id_text(&snapshot, persona_id(&snapshot));
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara.clone()]}),
)],
);
let ask_round = output(
"r1",
vec![call_event(
"c1",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Well?"}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("The bolt is thrown; nobody enters here.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let port = ScriptedPort::new(vec![dispatch_round, ask_round]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(404), "Who's there?".into())
.await
.unwrap();
let seen = port.seen_requests();
let round1_request = format!("{:?}", seen.get(1).expect("round 1's own request was seen"));
assert!(
round1_request.contains("The bolt is thrown; nobody enters here."),
"round 1's request must carry Mara's own prose verbatim: {round1_request}"
);
let question_id = table.store.lock().await.current().unwrap().open_question_id().unwrap();
// Release the store's exclusive custody before reopening it below —
// the same "restart" precedent `a_question_holds_the_turn_open_across_a_restart`
// relies on: a fresh `PlayTable` is the only production door onto a
// reopened store.
drop(table);
// The same request, rebuilt after a restart reopening the same
// store, must carry the same prose (PA.f64's "including after a
// resume").
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-after", vec![text_event("The hall goes still.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let port2 = ScriptedPort::new(vec![ask_round_repeat()]);
let table2 = PlayTable::new(
fixture.world.clone(),
personas2,
port2.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
// Answering the still-open question forces a fresh round to be
// inferred, rebuilding the conversation from the stored record.
table2
.run(
&fixture.principal,
test_turn_id(405),
PlayRequest {
text: "Answer.".into(),
answers: Some(question_id),
},
)
.await
.unwrap();
let seen2 = port2.seen_requests();
let resumed_request = format!("{:?}", seen2.first().unwrap());
assert!(
resumed_request.contains("The bolt is thrown; nobody enters here."),
"a resumed request must still carry the recorded Persona prose: {resumed_request}"
);
}
fn ask_round_repeat() -> InferenceOutput {
output(
"r2",
vec![call_event("c2", END_TURN_TOOL, serde_json::json!({}))],
)
}
/// PA.f69 S1: a Persona's own exact quote of its own prose is accepted —
/// mutating `span_is_exact` to check the *player's* prose instead of the
/// acting Persona's own recorded turn fails this, since the quote below
/// never appears in the player's own words.
#[tokio::test]
async fn a_persona_acting_on_its_own_exact_quote_is_accepted() {
let fixture = play_world(Some("Mara"), "player-persona-exact-quote").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = handle_for(persona_id(&snapshot));
let mara_id = subject_id_text(&snapshot, persona_id(&snapshot));
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_id]}),
)],
);
let speak_round = output(
"r1",
vec![
call_event(
"c1",
&format!("{mara}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "I nod and say nothing"}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("I nod and say nothing")]),
output("proj-narrate", vec![text_event("The room settles.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![dispatch_round, speak_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(406), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 1 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
assert_eq!(result, "applied", "an exact quote of the Persona's own prose must be accepted: {result}");
}
/// PA.f65: an empty or whitespace-only answer is refused before it is
/// recorded; the turn stays exactly as it was.
#[tokio::test]
async fn an_empty_answer_is_refused_before_it_is_recorded() {
let fixture = play_world(None, "player-empty-answer").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(410);
let ask = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, turn_id.clone(), "I stand at a crossroads.".into())
.await
.unwrap();
let question_id = table.store.lock().await.current().unwrap().open_question_id().unwrap();
let error = table
.run(
&fixture.principal,
test_turn_id(411),
PlayRequest {
text: " ".into(),
answers: Some(question_id),
},
)
.await
.unwrap_err();
assert!(matches!(error, PlayError::EmptyAnswer { .. }), "{error:?}");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::AwaitingPlayer, "an empty answer must not resume the turn");
assert_eq!(turn.question.as_deref(), Some("Which way?"));
}
struct AlwaysFaultyPort {
calls: std::sync::atomic::AtomicUsize,
}
impl AlwaysFaultyPort {
fn new() -> Self {
Self {
calls: std::sync::atomic::AtomicUsize::new(0),
}
}
fn call_count(&self) -> usize {
self.calls.load(std::sync::atomic::Ordering::SeqCst)
}
}
#[async_trait::async_trait]
impl InferencePort for AlwaysFaultyPort {
fn prepare(&self, _request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Err(InferenceFault::recovery_required("provider unavailable"))
}
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
Err(InferenceFault::recovery_required("provider unavailable"))
}
}
/// PA.f102: `RecoveryRequired` is renamed honestly from the prior
/// "exhausted beyond retries" framing this test used to carry — it never
/// actually drove a `Retryable` fault's own retry-and-exhaust path at
/// all; every one of its faults was `RecoveryRequired`, which never
/// retries and closes on its first occurrence. Asserts the call count
/// directly: exactly one `prepare` call, not the whole `ROUND_RETRY_BUDGET`
/// a `Retryable` fault would have spent. Mutation: making
/// `RecoveryRequired` retry (see `a_retryable_fault_exhausts_its_budget_then_closes`
/// for the sibling budget-exhaustion mutation) fails this by driving the
/// call count above one.
#[tokio::test]
async fn a_recovery_required_fault_makes_one_call_then_closes_with_its_detail() {
let fixture = play_world(None, "player-recovery-required").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let port = Arc::new(AlwaysFaultyPort::new());
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(420), "Hello?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.state,
PlayTurnState::Closed,
"a RecoveryRequired fault must close the turn, not leave it Running"
);
assert_eq!(
turn.fault.as_deref(),
Some("provider unavailable"),
"the fault's own detail must be recorded"
);
assert_eq!(
port.call_count(),
1,
"RecoveryRequired must never retry: exactly one call, not the whole retry budget"
);
}
/// PA.f102: a persistent `Retryable` fault, unlike `RecoveryRequired`,
/// does retry — but only up to `ROUND_RETRY_BUDGET` times, then closes
/// with the fault's own detail. Total calls: the initial attempt plus
/// one retry per absorbed fault, `ROUND_RETRY_BUDGET + 1`. Mutations:
/// raising the budget or removing the cap both fail this by changing the
/// exact call count the test pins.
#[tokio::test]
async fn a_retryable_fault_exhausts_its_budget_then_closes() {
let fixture = play_world(None, "player-retryable-exhausted").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
// Pinned expectation, deliberately *not* expressed as
// `ROUND_RETRY_BUDGET + 1`: computing the expected count from the
// same symbol the production code reads would let a mutation that
// raises the budget silently drag this test's own expectation along
// with it. The queue below supplies comfortably more faults than
// today's real budget can consume, so a raised or uncapped budget
// shows up as a call count above the pinned `13`.
const PINNED_EXPECTED_CALLS: usize = ROUND_BUDGET + 1;
assert_eq!(ROUND_RETRY_BUDGET, ROUND_BUDGET, "this pin assumes today's retry budget; update it deliberately if that changes");
let directory = tempfile::tempdir().unwrap();
let port = DispositionPort::new(
std::iter::repeat_with(|| Err(InferenceFault::retryable("transient provider hiccup")))
.take(PINNED_EXPECTED_CALLS + 10)
.collect(),
);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
// PA.f122: production and test run the identical retry_delay code
// path — only the base a test explicitly sets differs, so this
// test's own dozen-plus retries settle instantly. Mutation:
// `retry_delay` ignoring `retry_delay_base_ms` and always scaling
// from the production `RETRY_DELAY_BASE_MS` instead pushes the
// dozen-plus real sleeps below past 30 real seconds; the bound here
// is generously above instant and nowhere near that.
table.set_retry_delay_base_ms(0);
let started = std::time::Instant::now();
table
.run(&fixture.principal, test_turn_id(421), "Hello?".into())
.await
.unwrap();
assert!(
started.elapsed() < Duration::from_secs(2),
"a zero retry_delay_base_ms must make every retry settle instantly, not scale from the production base: {:?}",
started.elapsed()
);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.state,
PlayTurnState::Closed,
"a Retryable fault exhausting its budget must close the turn"
);
assert_eq!(turn.fault.as_deref(), Some("transient provider hiccup"));
assert_eq!(
port.call_count(),
PINNED_EXPECTED_CALLS,
"exactly the initial attempt plus ROUND_RETRY_BUDGET retries, no more and no fewer"
);
}
/// PA.f102: the production backoff formula itself, never the
/// `#[cfg(test)]`-hidden zero delay: it grows, and it caps.
#[test]
fn backoff_delay_grows_then_caps() {
assert_eq!(backoff_delay(RETRY_DELAY_BASE_MS, 0), Duration::from_millis(100));
assert_eq!(backoff_delay(RETRY_DELAY_BASE_MS, 1), Duration::from_millis(200));
assert_eq!(backoff_delay(RETRY_DELAY_BASE_MS, 2), Duration::from_millis(400));
assert_eq!(backoff_delay(RETRY_DELAY_BASE_MS, 5), Duration::from_millis(3_200), "not yet capped");
assert_eq!(backoff_delay(RETRY_DELAY_BASE_MS, 6), Duration::from_millis(5_000), "capped");
assert_eq!(
backoff_delay(RETRY_DELAY_BASE_MS, 1_000_000),
Duration::from_millis(5_000),
"a very large attempt count must stay capped, never overflow or panic"
);
assert_eq!(
backoff_delay(0, 6),
Duration::ZERO,
"a zero base (a test's own setting) must scale to zero at every attempt"
);
}
/// PA.f66a: exhausting the round budget closes the turn and narrates,
/// rather than leaving it `Running` with nothing said.
#[tokio::test]
async fn exhausting_the_round_budget_closes_and_narrates() {
let fixture = play_world(None, "player-round-budget").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-budget", vec![text_event("The moment passes.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let rounds: Vec<InferenceOutput> = (0..ROUND_BUDGET)
.map(|index| output(&format!("r{index}"), vec![text_event("Thinking.")]))
.collect();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(rounds),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(430), "Stall.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.state,
PlayTurnState::Closed,
"the round budget must close the turn, not leave it Running"
);
assert_eq!(turn.narration.as_deref(), Some("The moment passes."));
}
/// PA.f103: a narrate failure right after `end_turn` still closes the
/// turn with the fault recorded — Soul's own probe: `end_turn` with a
/// starved Persona script that yields no narration at all. Mutation:
/// turning `close_turn`'s own call site in the `end_turn` branch back
/// into a bare `self.close_turn(turn).await?` fails this, leaving the
/// turn `Running` behind the propagated error instead of `Closed` with
/// `fault` recorded.
#[tokio::test]
async fn a_narrate_failure_after_end_turn_closes_with_the_fault_recorded() {
let fixture = play_world(None, "player-narrate-fault-end-turn").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
// Starved: `end_turn`'s own narrate call finds nothing queued.
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let round = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(431), "Hello?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.state,
PlayTurnState::Closed,
"a narrate failure after end_turn must still close the turn"
);
assert!(turn.fault.is_some(), "the narrate failure's own fault must be recorded");
assert!(turn.narration.is_none(), "no narration must be recorded when narrate itself faulted");
}
/// PA.f103: a narrate failure at the round budget, not only at
/// `end_turn`, still closes the turn with the fault recorded — the round
/// budget's own `close_turn` call site is a second, independent door
/// onto the same helper. Mutation: turning that call site back into a
/// bare `?` fails this the same way the sibling `end_turn` mutation does.
#[tokio::test]
async fn a_narrate_failure_at_the_round_budget_closes_with_the_fault_recorded() {
let fixture = play_world(None, "player-narrate-fault-round-budget").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
// Starved: the round budget's own narrate call finds nothing
// queued either.
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let rounds: Vec<InferenceOutput> = (0..ROUND_BUDGET)
.map(|index| output(&format!("r{index}"), vec![text_event("Thinking.")]))
.collect();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(rounds),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(432), "Stall.".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.state,
PlayTurnState::Closed,
"the round budget must still close the turn when its own narrate faults"
);
assert!(turn.fault.is_some(), "the narrate failure's own fault must be recorded");
assert!(turn.narration.is_none(), "no narration must be recorded when narrate itself faulted");
}
/// PA.f66c: `dispatched_subjects` is derived from the whole record, in
/// call order, regardless of which round each dispatch call landed in —
/// the same value both `infer_round` (building next round's tools) and
/// `execute_round` (resolving a `<handle>__<kind>` call) read, on a
/// first pass and after a resume alike.
#[tokio::test]
async fn dispatched_subjects_reflects_the_whole_record_in_call_order() {
let fixture = play_world(Some("Mara"), "player-dispatch-order").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let a = player_id(&snapshot);
let b = persona_id(&snapshot);
let turn = PlayTurn {
turn_id: test_turn_id(440),
applied_keys: Vec::new(),
opening_prompt: String::new(),
player_prose: Vec::new(),
rounds: Vec::new(),
calls: vec![
CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![a])),
result: Some("applied".into()),
},
CallRecord {
call_id: "c1".into(),
round: 1,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![b])),
result: Some("applied".into()),
},
],
// PA.f90: a dispatch counts as dispatched only once its Persona
// turn actually produced and recorded prose, so both subjects
// need a `persona_turns` entry here.
persona_turns: vec![(a, fake_persona_turn("a acted")), (b, fake_persona_turn("b acted"))],
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
assert_eq!(turn.dispatched_subjects(), vec![a, b]);
}
/// PA.f90: a dispatch whose Persona turn faulted, or found no live
/// opportunity, never produced prose — it must not count as dispatched,
/// so its actor tools are not offered next round and an actor call for
/// it is refused, even though the `Dispatch` call itself recorded
/// success.
#[tokio::test]
async fn a_dispatch_with_no_recorded_persona_turn_does_not_count_as_dispatched() {
let fixture = play_world(Some("Mara"), "player-dispatch-no-turn").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let subject = persona_id(&snapshot);
let turn = PlayTurn {
turn_id: test_turn_id(441),
applied_keys: Vec::new(),
opening_prompt: String::new(),
player_prose: Vec::new(),
rounds: Vec::new(),
calls: vec![CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![subject])),
result: Some("holds no live Persona opportunity".into()),
}],
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
assert_eq!(turn.dispatched_subjects(), Vec::new());
}
fn fake_persona_turn(prose: &str) -> PersonaTurn {
PersonaTurn::record(
PersonaTurnBinding {
world_id: "world".into(),
controller_id: "controller".into(),
opportunity_digest: "opportunity".into(),
world_revision: 0,
scope_digest: "scope".into(),
projector_receipt_digest: "projector".into(),
persona_inference_receipt_digest: "persona".into(),
interrupted_from: None,
},
prose,
)
}
/// PA.f66d: the derived command id for one dispatched Persona's own turn
/// depends on the dispatch call's own slot and the subject, never on the
/// subject's position within that call's own JSON `subjects` array —
/// two subjects one call names, or the same subject two calls in one
/// round name, must never collide.
#[test]
fn dispatch_command_id_is_distinct_per_subject_and_call_and_stable_regardless_of_list_order() {
let turn_id = test_turn_id(999);
let a = dispatch_command_id_for_handle(&turn_id, 0, 5, "subject-a");
let b = dispatch_command_id_for_handle(&turn_id, 0, 5, "subject-b");
assert_ne!(
format!("{a:?}"),
format!("{b:?}"),
"two subjects named by the same dispatch call must not collide"
);
let a_again = dispatch_command_id_for_handle(&turn_id, 0, 5, "subject-a");
assert_eq!(
format!("{a:?}"),
format!("{a_again:?}"),
"the same subject, round, and call slot must derive the same id"
);
let a_other_call = dispatch_command_id_for_handle(&turn_id, 0, 6, "subject-a");
assert_ne!(
format!("{a:?}"),
format!("{a_other_call:?}"),
"two dispatch calls in one round naming the same subject must not collide"
);
}
/// PA.f104: `[dispatch(Mara), <mara>__speak, end_turn]` in one round must
/// resolve the speak call identically whether it is executed straight
/// through on a first pass, or resumed after a crash that landed only
/// the dispatch call's own result. `dispatched` used to be snapshotted
/// once before a round's own calls executed (before the dispatch call
/// even ran), refusing the speak call on the first pass while a resume's
/// fresh derivation — taken after the dispatch was already recorded —
/// applied it. Mutation: reintroducing that per-round snapshot fails
/// this by making the first-pass branch disagree with the resumed one.
#[tokio::test]
async fn a_same_round_dispatch_then_speak_agrees_on_first_pass_and_resume() {
const PROSE: &str = "Mara considers the player.";
const QUOTE: &str = "I nod once.";
let first_pass = {
let fixture = play_world(Some("Mara"), "player-f104-first-pass").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = handle_for(persona_id(&snapshot));
let mara_id = subject_id_text(&snapshot, persona_id(&snapshot));
let round = output(
"r0",
vec![
call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_id]})),
call_event(
"c1",
&format!("{mara}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": QUOTE}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
// Two inference calls per dispatch: the Projector (`PROSE`)
// then the Persona itself, whose own output — `QUOTE` here —
// becomes `PersonaTurn::source_prose()`, the text the speak
// call's own quote is checked against.
ScriptedPort::new(vec![output("proj-mara", vec![text_event(PROSE)]), output("persona-mara", vec![text_event(QUOTE)])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(740), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let speak_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 1)
.and_then(|call| call.result.clone())
.unwrap();
drop(stored);
let after = fixture.world.snapshot().await.unwrap();
(speak_result, after.revision)
};
let resumed = {
let fixture = play_world(Some("Mara"), "player-f104-resume").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara_subject = persona_id(&snapshot);
let mara = handle_for(mara_subject);
let round = output(
"r0",
vec![
call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [subject_id_text(&snapshot, mara_subject)]}),
),
call_event(
"c1",
&format!("{mara}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": QUOTE}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let turn_id = test_turn_id(741);
// The state a crash right after the dispatch call resolved, but
// before the speak call did, would have left on disk: the
// dispatch call already carries its own recorded body and
// result, and its Persona turn is already recorded — exactly
// what `execute_dispatch`/`record_call`/`persist` would have
// written, never a value this test reconstructs by re-deriving
// anything `dispatched_subjects` itself computes.
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: vec![test_turn_id(742)],
opening_prompt: format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"Who's there?"
),
player_prose: vec!["Who's there?".into()],
rounds: vec![round],
calls: vec![CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![mara_subject])),
result: Some(format!("Mara: {QUOTE}")),
}],
// The Persona's own recorded turn: its `source_prose()` is
// `QUOTE` (the actual Persona response), matching what a
// real `execute_dispatch` would have written, and what the
// speak call below quotes from.
persona_turns: vec![(mara_subject, fake_persona_turn(QUOTE))],
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let mut store = PlayTurnStore::open(&store_path).unwrap();
store.open_new_turn(crashed_turn).unwrap();
}
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(743), String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let speak_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 1)
.and_then(|call| call.result.clone())
.unwrap();
drop(stored);
let after = fixture.world.snapshot().await.unwrap();
(speak_result, after.revision)
};
assert_eq!(first_pass.0, "applied", "first pass: {}", first_pass.0);
assert_eq!(
first_pass, resumed,
"the same round script must resolve the speak call and the world revision identically \
on a first pass and on resume"
);
}
// --- PA.f99: the persisted body is on disk before submission ----------
//
// Each test below installs `PlayTable`'s own `#[cfg(test)]`
// `before_submit_hook` (see its doc comment): fired right before the one
// production call that submits a call's already-decoded body, it hands
// the hook a fresh `pull_all` against the store's own already-owned
// redb `Database` (`PlayTurnStore::pull_current_from_disk_for_test`) —
// never the store's cached `self.state`, which a mutation could leave
// stale relative to disk, and never a second, independently opened
// store: CultCache's own single-owner lock refuses a second
// `OwnedRedbMessagePackBackingStore::new` on the same path outright
// (discovered building this very seam — see the method's own doc
// comment). Each test then asserts the exact recorded body is already
// durably there. Deleting the `persist` call at any of the three record
// sites, or moving it to after its own submit call, must fail the
// matching test here.
#[tokio::test]
async fn the_authoring_patch_is_persisted_before_it_is_submitted() {
let fixture = play_world(None, "player-f99-authoring").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let round = output(
"r0",
vec![
call_event(
"c0",
"declare_resource",
serde_json::json!({"handle": "silver", "label": "Silver"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.set_before_submit_hook(move |durable_turn| {
let turn = durable_turn.expect("a turn is durably on disk at submission time");
let recorded = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.body.clone());
assert!(
matches!(recorded, Some(RecordedCall::Authoring(_))),
"the authoring patch must already be on disk when submission happens: {recorded:?}"
);
});
table
.run(&fixture.principal, test_turn_id(750), "Declare silver.".into())
.await
.unwrap();
}
#[tokio::test]
async fn the_advance_time_minutes_are_persisted_before_they_are_submitted() {
let fixture = play_world(None, "player-f99-advance").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let round = output(
"r0",
vec![
call_event("c0", ADVANCE_TIME_TOOL, serde_json::json!({"minutes": 5})),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.set_before_submit_hook(move |durable_turn| {
let turn = durable_turn.expect("a turn is durably on disk at submission time");
let recorded = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.body.clone());
assert!(
matches!(recorded, Some(RecordedCall::AdvanceTime(_))),
"the advance-time minutes must already be on disk when submission happens: {recorded:?}"
);
});
table
.run(&fixture.principal, test_turn_id(751), "Advance time.".into())
.await
.unwrap();
}
#[tokio::test]
async fn the_actor_calls_invocation_is_persisted_before_it_is_submitted() {
let fixture = play_world(None, "player-f99-actor").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let player = handle_for(player_id(&snapshot));
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let round = output(
"r0",
vec![
call_event(
"c0",
&format!("{player}{HANDLE_SEPARATOR}speak"),
serde_json::json!({"text": "hold fast"}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-0", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.set_before_submit_hook(move |durable_turn| {
let turn = durable_turn.expect("a turn is durably on disk at submission time");
let recorded = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.body.clone());
assert!(
matches!(recorded, Some(RecordedCall::PlayerAct(_, _))),
"the actor call's own invocation must already be on disk when submission happens: {recorded:?}"
);
});
table
.run(&fixture.principal, test_turn_id(752), "hold fast".into())
.await
.unwrap();
}
/// PA.f125. `execute_dispatch` persisted the dispatched Persona's own
/// `persona_turns` entry (its own `self.persist` right after each
/// subject completes, PA.f123) *before* the `Dispatch` call's own body
/// was ever recorded — `execute_round`'s `record_call` for the dispatch
/// call itself used to run only after `execute_dispatch` returned. A
/// crash in that window left `persona_turns` durable with no call
/// record naming it at all; on resume, the unfixed code read the
/// already-durable `persona_turns` entry as evidence some *other* call
/// already dispatched the subject, so the resumed dispatch call's own
/// tool result became `<id> already acted` instead of the Persona's own
/// prose — PA.f64's whole point defeated on exactly the path a crash
/// makes likely.
///
/// The fix: `execute_round` now records and persists the dispatch
/// call's own body before `execute_dispatch` runs any persona turn, and
/// `execute_dispatch` tells its own not-yet-finished work apart from a
/// different call's completed dispatch through `PlayTurn::dispatch_owner`
/// (first call, in call order, to name a subject).
///
/// First pass, live: `before_submit_hook` reads the store fresh off
/// disk right before the dispatched Persona's own turn is submitted
/// (subsuming PA.f123's own coverage), and the dispatch call's own body
/// must already be there. Mutation: reordering the record after the
/// persist, or deleting either, leaves the hook reading a turn whose
/// `calls` are still empty.
///
/// Second pass, resumed: a hand-built crashed turn — no call record at
/// all for the dispatch call, but `persona_turns` already carrying the
/// Persona's own turn, exactly what the pre-fix crash window left on
/// disk (Soul's probe shape: built as the persist writes it, not
/// re-derived from anything `dispatch_owner`/`dispatched_subjects`
/// itself computes) — resumes into a tool result that still carries the
/// Persona's own prose, never "already acted", and the Personas port
/// sees no fresh inference request (the Persona is not re-inferred).
/// All three mutations above fail this half too: without the record,
/// `dispatch_owner` finds no call at all naming the subject and the
/// resumed call falls back to "already acted".
#[tokio::test]
async fn a_resumed_dispatch_call_recovers_its_own_persona_prose_not_already_acted() {
const PROSE: &str = "Mara nods once.";
// First pass: live, hook-verified durability ordering.
{
let fixture = play_world(Some("Mara"), "player-f125-first-pass").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let mara_text = subject_id_text(&snapshot, mara);
let round = output(
"r0",
vec![
call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_text]})),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers.")]),
output("persona-mara", vec![text_event(PROSE)]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table.set_before_submit_hook(move |durable_turn| {
let turn = durable_turn.expect("a turn is durably on disk at submission time");
let recorded = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.body.clone());
assert!(
matches!(recorded, Some(RecordedCall::Dispatch(_))),
"the dispatch call's own body must already be on disk before its Persona turn submits: {recorded:?}"
);
});
table
.run(&fixture.principal, test_turn_id(920), "Who's there?".into())
.await
.unwrap();
}
// Second pass: resumed from the exact crash window PA.f125 closes.
let fixture = play_world(Some("Mara"), "player-f125-resume").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let mara_text = subject_id_text(&snapshot, mara);
let round = output(
"r0",
vec![
call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_text]})),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let turn_id = test_turn_id(921);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt: format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"Who's there?"
),
player_prose: vec!["Who's there?".into()],
rounds: vec![round],
// No call record at all for the dispatch call: exactly what a
// crash between `execute_dispatch`'s own per-subject persist
// and `execute_round`'s own (pre-fix) later `record_call` left
// on disk.
calls: Vec::new(),
persona_turns: vec![(mara, fake_persona_turn(PROSE))],
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let mut store = PlayTurnStore::open(&store_path).unwrap();
store.open_new_turn(crashed_turn).unwrap();
}
let personas_port = ScriptedPort::new(vec![]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
personas_port.clone(),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
let mara_turns = turn.persona_turns.iter().filter(|(id, _)| *id == mara).count();
drop(stored);
assert!(
dispatch_result.contains(PROSE),
"the resumed dispatch call must still carry the Persona's own prose: {dispatch_result}"
);
assert!(
!dispatch_result.contains("already acted"),
"the resumed dispatch call must not be refused as already acted: {dispatch_result}"
);
// Not the shared `personas_port`'s own `seen_requests` (round 0's
// `end_turn` still legitimately narrates through the same lane for
// the player, on the same port): the direct signal that the Persona
// herself was not re-inferred is that her own `persona_turns` entry
// is still exactly the one this test seeded, not a second one a
// fresh `personas.turn()` call would have pushed.
assert_eq!(
mara_turns, 1,
"resuming a completed dispatch must not re-infer the Persona into a duplicate persona_turns entry"
);
}
/// PA.f62/PA.f63: an answer under a fresh request key resumes the
/// waiting turn — already exercised end to end by
/// `a_question_holds_the_turn_open_across_a_restart`, which now uses a
/// distinct key for its own answer.
///
/// This test covers the sibling rule: replaying that same answer key a
/// second time, while the turn it answered is still open (it asks a
/// second question), is a no-op — it must not re-infer or re-answer.
#[tokio::test]
async fn a_replayed_answer_key_is_a_no_op_while_the_turn_is_still_open() {
let fixture = play_world(None, "player-replay-open").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask_one = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
let ask_two = output(
"r1",
vec![call_event(
"c1",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Are you sure?"}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask_one, ask_two]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(450), "start".into())
.await
.unwrap();
let first_question = table.store.lock().await.current().unwrap().open_question_id().unwrap();
let answer_key = test_turn_id(451);
let answer = || PlayRequest {
text: "left".into(),
answers: Some(first_question.clone()),
};
table.run(&fixture.principal, answer_key.clone(), answer()).await.unwrap();
// The inference queue is now exhausted: a broken replay that treats
// this key as unseen would try to answer round 1's own question and
// infer a third round, failing loudly. A correct no-op leaves round
// 1's question exactly as it was.
table.run(&fixture.principal, answer_key, answer()).await.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::AwaitingPlayer);
assert_eq!(turn.question.as_deref(), Some("Are you sure?"));
assert!(turn.fault.is_none(), "a replayed key must never touch inference: {:?}", turn.fault);
}
/// PA.f62/PA.f63: a replayed key from a closed turn returns that turn's
/// state and makes zero new inference calls.
#[tokio::test]
async fn a_replayed_key_from_a_closed_turn_makes_zero_inference_calls() {
let fixture = play_world(None, "player-replay-closed").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let key = test_turn_id(460);
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
// Exactly one output: a second inference attempt would exhaust it.
let port = ScriptedPort::new(vec![end]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, key.clone(), "Go.".into())
.await
.unwrap();
assert_eq!(port.seen_requests().len(), 1);
table
.run(&fixture.principal, key.clone(), "Go.".into())
.await
.unwrap();
assert_eq!(
port.seen_requests().len(),
1,
"a replayed key from a closed turn must make zero new inference calls"
);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert!(turn.applied_keys.contains(&key));
assert_eq!(turn.state, PlayTurnState::Closed);
}
/// PA.f63 + PA.f69 S7 + invariant 1: a genuinely new key after a closed
/// turn opens a fresh turn under that key, and nothing from the closed
/// turn's own record crosses into it — checked against the actual
/// inference request the fresh turn's own round sent, not merely the
/// stored `opening_prompt`.
#[tokio::test]
async fn a_new_key_after_a_closed_turn_starts_a_fresh_turn_with_no_prior_transcript() {
let fixture = play_world(None, "player-fresh-after-close").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-1", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(470), "UNIQUE_TURN_ONE_PROSE".into())
.await
.unwrap();
}
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-2", vec![text_event("Also fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end2 = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let port = ScriptedPort::new(vec![end2]);
let table = PlayTable::new(
fixture.world.clone(),
personas2,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let fresh_key = test_turn_id(471);
table
.run(&fixture.principal, fresh_key.clone(), "UNIQUE_TURN_TWO_PROSE".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert!(
turn.applied_keys.contains(&fresh_key),
"a new key after a closed turn must open a fresh turn recording that key"
);
assert!(turn.opening_prompt.contains("UNIQUE_TURN_TWO_PROSE"));
assert!(
!turn.opening_prompt.contains("UNIQUE_TURN_ONE_PROSE"),
"no transcript may cross from a closed turn into a new one"
);
let seen = port.seen_requests();
let request_text = format!("{:?}", seen.first().unwrap());
assert!(
!request_text.contains("UNIQUE_TURN_ONE_PROSE"),
"the new turn's own request must carry nothing from the closed turn: {request_text}"
);
}
// --- Fix batch 8a-fix2 (PA.f83-PA.f97) --------------------------------
/// PA.f83: two consecutive turns mint distinct `turn_id`s (never taken
/// from either request key), and their derived command ids never
/// collide.
#[tokio::test]
async fn two_consecutive_turns_mint_distinct_ids_and_non_colliding_command_ids() {
let fixture = play_world(None, "player-distinct-turn-ids").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let personas1 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-1", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end1 = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas1,
ScriptedPort::new(vec![end1]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(600), "Turn one.".into()).await.unwrap();
let turn1_id = table.store.lock().await.current().unwrap().turn_id.clone();
drop(table);
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-2", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end2 = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas2,
ScriptedPort::new(vec![end2]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(601), "Turn two.".into()).await.unwrap();
let turn2_id = table.store.lock().await.current().unwrap().turn_id.clone();
assert_ne!(turn1_id, turn2_id, "each turn mints its own fresh turn_id (PA.f83)");
let turn1_command0 = derived_command_id(&turn1_id, 0, 0);
let turn2_command0 = derived_command_id(&turn2_id, 0, 0);
assert_ne!(
format!("{turn1_command0:?}"),
format!("{turn2_command0:?}"),
"command ids derived from distinct turn_ids must not collide"
);
}
fn minimal_closed_turn(turn_id: String, keys: Vec<String>) -> PlayTurn {
PlayTurn {
turn_id,
applied_keys: keys,
opening_prompt: String::new(),
player_prose: Vec::new(),
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Closed,
}
}
/// PA.f100: `turn_id` is minted fresh (`Uuid::new_v4`), never derived
/// from the request key — the same key, once evicted from the store's
/// own `KeyLedger` window and so no longer recognized as a replay, opens
/// a genuinely new turn with a fresh id each time. Mutation: deriving
/// `turn_id` as a hash of `key` fails this, since both opens below share
/// exactly one key and a hash of one value cannot differ from itself.
#[tokio::test]
async fn the_same_evicted_key_opens_two_turns_with_distinct_fresh_ids() {
let fixture = play_world(None, "player-f100-evicted-key").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let key = "reused-opening-key".to_owned();
let personas1 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-1", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end1 = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas1,
ScriptedPort::new(vec![end1]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, key.clone(), "Turn one.".into()).await.unwrap();
let turn1_id = table.store.lock().await.current().unwrap().turn_id.clone();
// Evict `key` from the ledger: turn one is already the store's
// current (closed) turn, so the first of `KEY_LEDGER_WINDOW + 1`
// more closed turns, written directly through the store (no
// inference needed to close an already-`Closed` fixture turn),
// archives it as the oldest entry, filling the window exactly; the
// one past that finally pushes it out (matching
// `the_ledger_forgets_a_closed_turns_keys_past_the_window`'s own
// window-plus-one shape against the pure `KeyLedger` value).
{
let mut store = table.store.lock().await;
for index in 0..=KEY_LEDGER_WINDOW {
store
.open_new_turn(minimal_closed_turn(format!("filler-{index}"), vec![format!("filler-key-{index}")]))
.unwrap();
}
assert!(
store.turn_id_for_key(&key).is_none(),
"the original key must be evicted past the window before the second open"
);
}
drop(table);
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-2", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end2 = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas2,
ScriptedPort::new(vec![end2]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let outcome = table.run(&fixture.principal, key.clone(), "Turn two.".into()).await.unwrap();
assert!(matches!(outcome, RunOutcome::Ran { .. }), "the evicted key must open a fresh turn, not replay: {outcome:?}");
let turn2_id = table.store.lock().await.current().unwrap().turn_id.clone();
assert_ne!(
turn1_id, turn2_id,
"the same request key, reused only after eviction, must still mint a fresh turn_id each open"
);
}
/// PA.f83, PA.f116, PA.f128: K1, K2, K3 and K4 each open and close their
/// own turn in order; opening K4 archives K1, K2 and K3 into the
/// store's own `KeyLedger` (one more entry per turn that closes and is
/// then displaced), so a retry of K2 — the archived entry in the
/// ledger's own *middle*, at neither end — must still name K2's own
/// `turn_id`. With only K1 and K2 closed (PA.f116's own shape), the
/// retried key's entry happened to sit at the ledger's back regardless
/// of whether `turn_id_for` actually searched or just returned the back
/// entry, so that shape passed without exercising the search at all
/// (PA.f128); a fourth closed turn is needed to put K2 at neither end.
/// Mutations: `KeyLedger::turn_id_for` returning `self.closed.front()`'s
/// id on any match, or `self.closed.iter().find(...)?; self.closed.back()`'s
/// id on any match, must both fail this.
#[tokio::test]
async fn a_retried_key_from_a_turn_before_the_most_recent_is_a_no_op() {
let fixture = play_world(None, "player-ledger-retry").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
fn personas(world: &WorldMailbox, proj: &'static str) -> PersonaLane {
PersonaLane::new(
ControllerPort::new(world.clone()),
ScriptedPort::new(vec![output(proj, vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap()
}
async fn run_and_close(
fixture: &WorldFixture,
store_path: &Path,
proj: &'static str,
key: String,
text: &str,
) -> String {
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas(&fixture.world, proj),
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
store_path,
)
.unwrap();
table.run(&fixture.principal, key, text.into()).await.unwrap();
drop(table);
PlayTurnStore::open(store_path).unwrap().current().unwrap().turn_id.clone()
}
let k1 = test_turn_id(610);
let turn1_id = run_and_close(&fixture, &store_path, "proj-k1", k1, "K1.").await;
let k2 = test_turn_id(611);
let turn2_id = run_and_close(&fixture, &store_path, "proj-k2", k2.clone(), "K2.").await;
assert_ne!(turn1_id, turn2_id);
let k3 = test_turn_id(612);
let turn3_id = run_and_close(&fixture, &store_path, "proj-k3", k3, "K3.").await;
assert_ne!(turn2_id, turn3_id);
let k4 = test_turn_id(613);
let turn4_id = run_and_close(&fixture, &store_path, "proj-k4", k4, "K4.").await;
assert_ne!(turn3_id, turn4_id);
// A retry of K2: an empty scripted port means any inference attempt
// fails loudly, so this stays a genuine "zero inference calls" check.
let port = ScriptedPort::new(vec![]);
let table = PlayTable::new(
fixture.world.clone(),
personas(&fixture.world, "proj-k2-retry"),
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let outcome = table.run(&fixture.principal, k2, "K2.".into()).await.unwrap();
assert_eq!(
port.seen_requests().len(),
0,
"a retried key already known to the ledger must make zero inference calls"
);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.turn_id, turn4_id, "the retry must not open a fifth turn");
// PA.f109: the replay's own outcome names the turn it replayed —
// K2's own turn, neither K1's (the ledger's front entry), K3's, nor
// K4's (the store's current one).
assert_eq!(
outcome,
RunOutcome::Replayed { turn_id: turn2_id, question: None },
"a replayed key's own outcome must name the turn it originally opened, not the ledger's front or back entry"
);
}
/// PA.f83, PA.f117: the ledger keeps a closed turn's own keys only while
/// it remains among the most recent `KEY_LEDGER_WINDOW` closed turns;
/// one more closed turn past the window evicts the oldest one's keys. A
/// small helper against the pure `KeyLedger` value directly, so this
/// does not run 65 real turns. Reached through `turn_id_for` — `contains`
/// had no production caller left after PA.f109's `turn_id_for` replaced
/// it and is deleted.
#[test]
fn the_ledger_forgets_a_closed_turns_keys_past_the_window() {
let mut ledger = KeyLedger::default();
ledger.push_closed("oldest-turn".into(), vec!["oldest-key".into()]);
for index in 0..KEY_LEDGER_WINDOW - 1 {
ledger.push_closed(format!("turn-{index}"), vec![format!("key-{index}")]);
}
assert_eq!(
ledger.turn_id_for("oldest-key"),
Some("oldest-turn".to_owned()),
"the oldest turn's own key must still be known while it is within the window"
);
// The 65th closed turn: exactly one past the window, evicting the
// oldest.
ledger.push_closed("one-too-many".into(), vec!["newest-key".into()]);
assert_eq!(
ledger.turn_id_for("oldest-key"),
None,
"a key older than the window must be forgotten"
);
assert_eq!(ledger.turn_id_for("newest-key"), Some("one-too-many".to_owned()));
}
/// PA.f84 probe: K1 opens the turn and asks Q1; K2 answers Q1 and the
/// next round asks Q2; a retry of K1 is recognized as a replay and is a
/// no-op — it does not, and cannot, answer Q2.
#[tokio::test]
async fn a_retried_opening_key_never_answers_a_later_question() {
let fixture = play_world(None, "player-probe-late-retry").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask_one = output(
"r0",
vec![call_event("c0", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which way?"}))],
);
let ask_two = output(
"r1",
vec![call_event("c1", ASK_PLAYER_TOOL, serde_json::json!({"question": "Are you sure?"}))],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let port = ScriptedPort::new(vec![ask_one, ask_two]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let k1 = test_turn_id(630);
// K1 closes: the turn is now `AwaitingPlayer` on Q1.
table.run(&fixture.principal, k1.clone(), "start".into()).await.unwrap();
let q1 = table.store.lock().await.current().unwrap().open_question_id().unwrap();
let k2 = test_turn_id(631);
// K2 asks a question: it answers Q1, and the next round asks Q2.
table
.run(
&fixture.principal,
k2,
PlayRequest {
text: "left".into(),
answers: Some(q1),
},
)
.await
.unwrap();
assert_eq!(table.store.lock().await.current().unwrap().question.as_deref(), Some("Are you sure?"));
let seen_before_retry = port.seen_requests().len();
// K1 is retried: it opened the turn and is already known, so this is
// a no-op.
table.run(&fixture.principal, k1, "left".into()).await.unwrap();
assert_eq!(
port.seen_requests().len(),
seen_before_retry,
"a retried key must make zero new inference calls"
);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::AwaitingPlayer);
assert_eq!(turn.question.as_deref(), Some("Are you sure?"), "K1's own retry must not answer Q2");
}
/// PA.f84: an answer naming a different, no-longer-open question is
/// refused as stale rather than being applied to whatever question is
/// open now.
#[tokio::test]
async fn an_answer_naming_a_different_question_is_refused_as_stale() {
let fixture = play_world(None, "player-stale-answer").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask_one = output(
"r0",
vec![call_event("c0", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which way?"}))],
);
let ask_two = output(
"r1",
vec![call_event("c1", ASK_PLAYER_TOOL, serde_json::json!({"question": "Are you sure?"}))],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask_one, ask_two]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(620), "start".into()).await.unwrap();
let stale_question = table.store.lock().await.current().unwrap().open_question_id().unwrap();
table
.run(
&fixture.principal,
test_turn_id(621),
PlayRequest {
text: "left".into(),
answers: Some(stale_question.clone()),
},
)
.await
.unwrap();
// Q2 is now open; a fresh key answering with Q1's own (now stale)
// question id must be refused, not silently applied to Q2.
let error = table
.run(
&fixture.principal,
test_turn_id(622),
PlayRequest {
text: "sure".into(),
answers: Some(stale_question),
},
)
.await
.unwrap_err();
assert!(matches!(error, PlayError::StaleAnswer { .. }), "{error:?}");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.question.as_deref(),
Some("Are you sure?"),
"the stale answer must not touch the currently open question"
);
assert!(
!turn.applied_keys.contains(&test_turn_id(622)),
"a refused stale answer's key must never be marked applied"
);
}
/// PA.f101: `answers: None` while a question genuinely is open is
/// refused exactly like a stale, wrongly-named one — the match at
/// `run`'s own open-question arm only ever applies the `(Some(given),
/// Some(open)) if given == open` case; every other combination,
/// including `None`, falls to the same `StaleAnswer` refusal. Mutation:
/// accepting `None` there (treating an absent answer as "answer
/// whatever is open") fails this, since nothing here supplied any text
/// naming an actual answer.
#[tokio::test]
async fn an_answer_of_none_while_a_question_is_open_is_refused_and_records_nothing() {
let fixture = play_world(None, "player-none-answer").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask = output(
"r0",
vec![call_event("c0", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which way?"}))],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(623), "start".into()).await.unwrap();
let before = table.store.lock().await.current().unwrap().clone();
assert_eq!(before.state, PlayTurnState::AwaitingPlayer);
let error = table
.run(
&fixture.principal,
test_turn_id(624),
PlayRequest {
text: "left".into(),
answers: None,
},
)
.await
.unwrap_err();
assert!(matches!(error, PlayError::StaleAnswer { .. }), "{error:?}");
let stored = table.store.lock().await;
let after = stored.current().unwrap();
assert_eq!(after.state, PlayTurnState::AwaitingPlayer, "the turn must stay AwaitingPlayer");
assert_eq!(after.question, before.question, "the open question must not change");
assert_eq!(after.calls.len(), before.calls.len(), "nothing must be recorded from a refused None answer");
assert!(
!after.applied_keys.contains(&test_turn_id(624)),
"a refused None answer's key must never be marked applied"
);
}
/// PA.f84: `answers` given while the turn is `Running` (no question
/// open at all) is refused.
#[tokio::test]
async fn an_answer_while_the_turn_is_running_is_refused() {
let fixture = play_world(None, "player-answers-while-running").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(640);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
// A turn caught mid-loop, `Running`, between rounds — the exact
// shape a real crash could leave persisted (`run` itself persists
// right after each round with `RoundOutcome::Continue`, before its
// own loop condition re-checks `turn.state`).
let running_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: vec![test_turn_id(639)],
opening_prompt: "opening".into(),
player_prose: vec!["hello".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(running_turn).unwrap();
let bogus_question = QuestionId {
turn_id,
round: 0,
slot: 0,
};
let error = table
.run(
&fixture.principal,
test_turn_id(641),
PlayRequest {
text: String::new(),
answers: Some(bogus_question),
},
)
.await
.unwrap_err();
assert!(matches!(error, PlayError::NoQuestionOpen), "{error:?}");
}
/// PA.f84: `answers` given when there is no open turn at all is refused.
#[tokio::test]
async fn an_answer_with_no_open_turn_at_all_is_refused() {
let fixture = play_world(None, "player-answers-no-turn").await;
let directory = tempfile::tempdir().unwrap();
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
let bogus_question = QuestionId {
turn_id: "nonexistent".into(),
round: 0,
slot: 0,
};
let error = table
.run(
&fixture.principal,
test_turn_id(650),
PlayRequest {
text: "hi".into(),
answers: Some(bogus_question),
},
)
.await
.unwrap_err();
assert!(matches!(error, PlayError::NoQuestionOpen), "{error:?}");
}
/// PA.f84: while the turn is `Running`, non-empty text is refused
/// rather than dropped silently — the turn is still resolving its own
/// prior request's rounds.
#[tokio::test]
async fn nonempty_text_while_the_turn_is_running_is_refused() {
let fixture = play_world(None, "player-turn-still-running").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(660);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let running_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: vec![test_turn_id(659)],
opening_prompt: "opening".into(),
player_prose: vec!["hello".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(running_turn).unwrap();
let error = table.run(&fixture.principal, test_turn_id(661), "more text".into()).await.unwrap_err();
assert!(matches!(error, PlayError::TurnStillRunning), "{error:?}");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Running);
assert!(!turn.applied_keys.contains(&test_turn_id(661)));
}
/// PA.f84: while the turn is `Running`, empty text continues it.
#[tokio::test]
async fn empty_text_while_the_turn_is_running_continues_it() {
let fixture = play_world(None, "player-turn-continues").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let turn_id = test_turn_id(670);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
let snapshot = fixture.world.snapshot().await.unwrap();
let running_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: vec![test_turn_id(669)],
opening_prompt: format!("{}\n\nThe player writes:\n{}\n", table_view(&snapshot), "hi"),
player_prose: vec!["hi".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
table.store.lock().await.commit(running_turn).unwrap();
table.run(&fixture.principal, test_turn_id(671), String::new().into()).await.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
assert!(turn.applied_keys.contains(&test_turn_id(671)));
}
/// PA.f108: empty or whitespace-only text with no turn open to continue
/// — no turn at all, or the current one already `Closed` — is refused
/// before a fresh turn opens, rather than opening one with prose `[""]`
/// and running a full inference over nothing the player said. Checked
/// both with no stored turn at all and with a `Closed` one on record,
/// and in each case zero inference calls are made and the store's own
/// current turn is untouched.
#[tokio::test]
async fn empty_text_with_no_turn_open_is_refused_and_infers_nothing() {
let fixture = play_world(None, "player-empty-opening").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let play_port = ScriptedPort::new(vec![]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
play_port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
// No turn on record at all.
let error = table
.run(&fixture.principal, test_turn_id(672), String::new().into())
.await
.unwrap_err();
assert!(matches!(error, PlayError::EmptyOpening), "{error:?}");
assert!(table.store.lock().await.current().is_none(), "no turn must have opened");
assert!(play_port.seen_requests().is_empty(), "an empty opening must make zero inference calls");
// A whitespace-only text with a `Closed` turn already on record must
// be refused the same way, not treated as a continue of the closed
// turn or as a fresh (empty) opening.
let snapshot = fixture.world.snapshot().await.unwrap();
let closed_turn = PlayTurn {
turn_id: test_turn_id(673),
applied_keys: vec![test_turn_id(674)],
opening_prompt: format!("{}\n\nThe player writes:\n{}\n", table_view(&snapshot), "done"),
player_prose: vec!["done".into()],
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: Some("The end.".into()),
fault: None,
state: PlayTurnState::Closed,
};
table.store.lock().await.commit(closed_turn).unwrap();
let error = table
.run(&fixture.principal, test_turn_id(675), " ".into())
.await
.unwrap_err();
assert!(matches!(error, PlayError::EmptyOpening), "{error:?}");
assert!(play_port.seen_requests().is_empty(), "still zero inference calls");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.turn_id, test_turn_id(673), "the closed turn on record must be untouched");
assert!(
!turn.applied_keys.contains(&test_turn_id(675)),
"a refused empty opening's key must never be marked applied"
);
}
struct DispositionPort {
queue: StdMutex<VecDeque<Result<InferenceOutput, InferenceFault>>>,
calls: StdMutex<usize>,
}
impl DispositionPort {
fn new(items: Vec<Result<InferenceOutput, InferenceFault>>) -> Arc<Self> {
Arc::new(Self {
queue: StdMutex::new(items.into_iter().collect()),
calls: StdMutex::new(0),
})
}
fn call_count(&self) -> usize {
*self.calls.lock().unwrap()
}
}
#[async_trait::async_trait]
impl InferencePort for DispositionPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
PreparedInference::prepare("play-test-runtime", far_future_unix_ms(), request)
}
async fn infer(&self, _prepared: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
*self.calls.lock().unwrap() += 1;
match self.queue.lock().unwrap().pop_front() {
Some(item) => item,
None => Err(InferenceFault::recovery_required("disposition port exhausted")),
}
}
}
/// PA.f85/PA.f93/PA.f94: an `IntegrityViolation` fault never retries —
/// exactly one inference call — and closes the turn with the fault
/// recorded through `close_with_fault`, rather than being left
/// `Running`. The next request then opens a fresh turn.
#[tokio::test]
async fn an_integrity_violation_makes_one_call_then_closes_and_the_next_request_opens_a_fresh_turn() {
let fixture = play_world(None, "player-integrity-violation").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let port = DispositionPort::new(vec![Err(InferenceFault::integrity_violation("bad tool schema"))]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(680), "Hello?".into()).await.unwrap();
assert_eq!(port.call_count(), 1, "an IntegrityViolation must not retry");
let closed_turn_id = {
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
assert!(turn.fault.as_deref().unwrap().contains("bad tool schema"), "{:?}", turn.fault);
turn.turn_id.clone()
};
// Release the store's exclusive custody before reopening it below —
// the same "restart" precedent `a_question_holds_the_turn_open_across_a_restart`
// relies on.
drop(table);
// The next request opens a fresh turn rather than resuming the
// fault-closed one.
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-after", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let table2 = PlayTable::new(
fixture.world.clone(),
personas2,
ScriptedPort::new(vec![end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table2.run(&fixture.principal, test_turn_id(681), "Try again.".into()).await.unwrap();
let stored = table2.store.lock().await;
let turn = stored.current().unwrap();
assert_ne!(turn.turn_id, closed_turn_id, "the next request must open a fresh turn, not resume the fault-closed one");
assert_eq!(turn.state, PlayTurnState::Closed);
assert!(turn.fault.is_none());
}
/// PA.f94: a `Retryable` fault retries and, on success, the turn
/// proceeds normally.
#[tokio::test]
async fn a_retryable_fault_followed_by_success_succeeds() {
let fixture = play_world(None, "player-retry-success").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Fine.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let end = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let port = DispositionPort::new(vec![Err(InferenceFault::retryable("transient")), Ok(end)]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table.set_retry_delay_base_ms(0);
table.run(&fixture.principal, test_turn_id(682), "Hello?".into()).await.unwrap();
assert_eq!(port.call_count(), 2, "a Retryable fault must retry once, then succeed");
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
assert!(turn.fault.is_none());
}
/// PA.f86 (S6): a resumed round's opening conversation item must be the
/// turn's own recorded `opening_prompt`, never a `table_view` of a
/// fresh snapshot taken at resume time — the world may have drifted (a
/// patch committed between rounds) by then. Mutation: rebuilding
/// `conversation[0]` from `table_view(&fresh_snapshot)` in
/// `rebuild_conversation`/`infer_round` fails this.
#[tokio::test]
async fn a_resumed_rounds_opening_item_is_the_recorded_prompt_not_a_fresh_view() {
let fixture = play_world(None, "player-s6-fresh-view").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask = output(
"r0",
vec![call_event("c0", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which way?"}))],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(510), "I stand at a crossroads.".into())
.await
.unwrap();
let (opening_prompt, question_id) = {
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
(turn.opening_prompt.clone(), turn.open_question_id().unwrap())
};
drop(table);
// World drift between the question and the answer.
let personas2 = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("You choose left.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let end = output("r1", vec![call_event("c1", END_TURN_TOOL, serde_json::json!({}))]);
let port = ScriptedPort::new(vec![end]);
let table = PlayTable::new(
fixture.world.clone(),
personas2,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.play
.submit_patch(
CommandId::new(),
decode_authoring_call(
"declare_resource",
&serde_json::json!({"handle": "silver", "label": "Silver"}).to_string(),
)
.unwrap(),
)
.await
.unwrap();
table
.run(
&fixture.principal,
test_turn_id(511),
PlayRequest {
text: "left".into(),
answers: Some(question_id),
},
)
.await
.unwrap();
let seen = port.seen_requests();
let request_text = format!("{:?}", seen.first().unwrap());
// `request_text` is `Debug`-formatted, so a literal newline inside
// the recorded `opening_prompt` prints as the two characters `\n`;
// match that same escaping rather than the raw string.
let opening_prompt_escaped = opening_prompt.replace('\n', "\\n");
assert!(
request_text.contains(&opening_prompt_escaped),
"the resumed round's opening item must be the recorded opening_prompt: {request_text}"
);
assert!(
!request_text.contains("Silver"),
"a fresh table_view would leak the mid-turn patch into the opening item: {request_text}"
);
}
/// PA.f88: Dungeon's own `PLAY_TOOLS` is the single policy owner of
/// what the play agent may call (the library's own copy in
/// `ghostlight::table` is its test fixture only) — pinned here at its
/// exact 24-tool contents, `communicate` excluded (PA.f75). Mutation:
/// re-adding `communicate`.
#[test]
fn play_tools_is_pinned_to_its_exact_contents_with_no_communicate() {
const EXPECTED: &[&str] = &[
"relocate",
"transfer",
"consume",
"mint",
"bind",
"release",
"witness",
"acquire_knowledge",
"forget",
"create_commitment",
"discharge_commitment",
"advance_pressure",
"reduce_pressure",
"open_route",
"close_route",
"declare_place",
"declare_route",
"declare_resource",
"declare_fact",
"declare_subject",
"set_persona_material",
"retire",
"grant_affordance",
"revoke_affordance",
];
assert_eq!(PLAY_TOOLS, EXPECTED);
assert_eq!(PLAY_TOOLS.len(), 24);
assert!(!PLAY_TOOLS.contains(&"communicate"));
}
/// The `request_id` an `InferenceRequest` `Debug`-prints, extracted so
/// two requests can be compared on that field alone — it is the one
/// place `dispatch_command_id`'s own output value actually reaches
/// something this test can observe from outside `execute_dispatch`.
fn request_id_of(request: &InferenceRequest) -> String {
let text = format!("{request:?}");
let key = "request_id: \"";
let start = text.find(key).expect("a request carries its own request_id") + key.len();
let end = start + text[start..].find('"').expect("the request_id value is a quoted string");
text[start..end].to_owned()
}
/// PA.f96: replaces the old test that called `dispatch_command_id_for_handle`
/// directly by observing the *actual* production path instead. Two
/// Persona subjects are dispatched together under one shared `turn_id`,
/// once as `[Mara, Borin]` and once as `[Borin, Mara]`. Each dispatched
/// subject's own inference `request_id` carries `dispatch_command_id`'s
/// own output — the same value `execute_dispatch` itself derives and
/// hands to `personas.turn` — so comparing Mara's own `request_id`
/// across the two orders observes whether that id actually depended on
/// her position in the JSON list, without recomputing the hash
/// ourselves. Mutation: hashing the subject's list position (`position`)
/// instead of the subject itself at the `execute_dispatch` call site
/// changes Mara's own `request_id` between the two runs, failing this.
#[tokio::test]
async fn dispatch_order_never_changes_the_request_id_a_subject_gets() {
let fixture = play_world(Some("Mara"), "player-dispatch-order-ids").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let affordance_id = bracketed_id_after(&table_view(&snapshot), "speak [");
// A second Persona subject, declared through the play table's own
// authoring door — the same mechanism
// `set_persona_material_on_a_same_run_declared_subject_commits` uses.
let declare = output(
"r0",
vec![
call_event(
"c0",
"declare_subject",
serde_json::json!({
"handle": "borin",
"label": "Borin",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-declare", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![declare]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.run(&fixture.principal, test_turn_id(690), "Introduce Borin.".into()).await.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let borin = snapshot.subjects.iter().find(|row| row.label == "Borin").unwrap().id;
// One turn_id shared by both orders: `dispatch_command_id` derives
// from `(turn_id, round, slot, subject)`, so holding turn_id, round,
// and slot fixed isolates subject-vs-position as the only variable.
let shared_turn_id = test_turn_id(691);
async fn dispatch_pair(
world: &WorldMailbox,
turn_id: &str,
order: [SubjectId; 2],
) -> (PlayTurn, Arc<ScriptedPort>) {
let port = ScriptedPort::new(vec![
output("proj-0", vec![text_event("considers.")]),
output("persona-0", vec![text_event("speaks first.")]),
output("proj-1", vec![text_event("waits.")]),
output("persona-1", vec![text_event("speaks second.")]),
]);
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
port.clone(),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let table = PlayTable::new(
world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
let mut turn = PlayTurn {
turn_id: turn_id.to_owned(),
applied_keys: Vec::new(),
opening_prompt: String::new(),
player_prose: Vec::new(),
rounds: Vec::new(),
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let (outcome, summary) = table.execute_dispatch(&mut turn, 0, 0, &order).await.unwrap();
assert!(matches!(outcome, RoundOutcome::Continue), "dispatch must not fault: {summary}");
assert!(!summary.contains("could not act"), "{summary}");
(turn, port)
}
let (forward, forward_port) = dispatch_pair(&fixture.world, &shared_turn_id, [mara, borin]).await;
let (reverse, reverse_port) = dispatch_pair(&fixture.world, &shared_turn_id, [borin, mara]).await;
for (label, turn, subject) in [
("forward", &forward, mara),
("forward", &forward, borin),
("reverse", &reverse, mara),
("reverse", &reverse, borin),
] {
assert!(
turn.persona_turns.iter().any(|(id, _)| *id == subject),
"{label} dispatch must have recorded a Persona turn for the subject"
);
}
// Forward dispatched [Mara, Borin]: Mara's own Projector request is
// seen first (index 0); reverse dispatched [Borin, Mara]: Mara's own
// is seen third (index 2), after Borin's own pair.
let forward_seen = forward_port.seen_requests();
let reverse_seen = reverse_port.seen_requests();
let mara_request_id_at_position_0 = request_id_of(&forward_seen[0]);
let mara_request_id_at_position_1 = request_id_of(&reverse_seen[2]);
assert_eq!(
mara_request_id_at_position_0, mara_request_id_at_position_1,
"Mara's own request id must depend only on (turn_id, round, slot, subject), never her position in the dispatch list"
);
let borin_request_id_at_position_1 = request_id_of(&forward_seen[2]);
let borin_request_id_at_position_0 = request_id_of(&reverse_seen[0]);
assert_eq!(
borin_request_id_at_position_1, borin_request_id_at_position_0,
"Borin's own request id must depend only on (turn_id, round, slot, subject), never his position in the dispatch list"
);
assert_ne!(
mara_request_id_at_position_0, borin_request_id_at_position_0,
"two distinct subjects dispatched together must not share a request id"
);
}
// --- PA.f97: short handles and collision detection --------------------
/// The longest possible actor tool name (`<8-hex-handle>__<48-char kind>`)
/// stays well under a common 64-char function-name limit.
#[tokio::test]
async fn the_longest_possible_actor_tool_name_is_64_chars_or_fewer() {
let fixture = play_world(Some("Mara"), "player-handle-length").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let prefix = actor_prefix(player_id(&snapshot));
assert!(prefix.len() <= 10, "the handle prefix must be short: {prefix}");
let longest_kind = "x".repeat(48);
let name = format!("{prefix}{longest_kind}");
assert!(name.len() <= 64, "an actor tool name of {} chars exceeds a common 64-char limit: {name}", name.len());
}
/// The player's and a Persona's own short handles round-trip through
/// `resolve_handle` unchanged.
#[tokio::test]
async fn player_and_persona_handles_round_trip() {
let fixture = play_world(Some("Mara"), "player-handle-roundtrip").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let persona = persona_id(&snapshot);
assert_eq!(handle_for(player).len(), 8);
assert_eq!(handle_for(persona).len(), 8);
assert_ne!(handle_for(player), handle_for(persona));
let player_row = SubjectRow { id: player };
let resolved_player = resolve_handle(&handle_for(player), Some(&player_row), &[persona]);
let resolved = resolved_player.expect("the player's own handle resolves");
assert_eq!(resolved.subject, player);
assert!(resolved.is_player);
let resolved_persona = resolve_handle(&handle_for(persona), Some(&player_row), &[persona]);
let resolved = resolved_persona.expect("the dispatched Persona's own handle resolves");
assert_eq!(resolved.subject, persona);
assert!(!resolved.is_player);
}
/// PA.f97: two distinct subjects sharing one handle is a collision;
/// `find_handle_collision` is the pure function `round_tools` calls to
/// refuse the whole round as a turn fault. `SubjectId` mints nothing a
/// consumer crate can construct by hand and two real, randomly issued
/// ids cannot feasibly be forced to collide, so this drives the
/// detection algorithm directly with two real (distinct) subject ids
/// under a shared, hand-assigned handle string, rather than attempting
/// to force a genuine 8-hex-digit collision through a fixture — which
/// is the infeasible half of this rule's own test list; reported here
/// rather than faked.
#[tokio::test]
async fn a_handle_collision_between_distinct_subjects_is_detected() {
let fixture = play_world(Some("Mara"), "player-handle-collision").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let a = player_id(&snapshot);
let b = persona_id(&snapshot);
let collision =
find_handle_collision(vec![("SAME1234".to_owned(), a), ("SAME1234".to_owned(), b)].into_iter());
assert_eq!(collision.as_deref(), Some("SAME1234"));
}
/// The same subject appearing twice under its own handle (a subject
/// that could in principle be named more than once) is not a collision.
#[tokio::test]
async fn the_same_subject_listed_twice_under_one_handle_is_not_a_collision() {
let fixture = play_world(None, "player-handle-no-collision").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let a = player_id(&snapshot);
let collision = find_handle_collision(vec![(handle_for(a), a), (handle_for(a), a)].into_iter());
assert_eq!(collision, None);
}
/// PA.f105: a genuine collision between two *real* `SubjectId`s, not a
/// hand-assigned string pair — `SubjectId` is `#[serde(transparent)]`
/// over a `Uuid` and `WorldSnapshot::subjects[i].id` is `pub`, so a real
/// id can be forged by re-deriving its text with the player's own first
/// hex group spliced in, then deserializing that text back into a real
/// `SubjectId` through the one door this crate has for constructing one
/// at all: `serde_json`. No kernel-level backdoor is needed; this was
/// wrongly reported infeasible in the prior pass. `collision_refusal` is
/// called directly with the mutated snapshot: since PA.f127/PA.f133
/// collapsed the check out of `round_tools` and into `round_snapshot`,
/// this is the pure rule `round_snapshot` itself calls, not a copy of it.
#[tokio::test]
async fn a_genuine_handle_collision_between_two_real_subjects_is_refused() {
let fixture = play_world(Some("Mara"), "player-real-handle-collision").await;
let mut snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let persona_index = snapshot
.subjects
.iter()
.position(|row| row.controller_mode == Some(ControllerMode::NarrativePersona))
.unwrap();
let player_text = subject_id_text(&snapshot, player);
let persona_text = subject_id_text(&snapshot, snapshot.subjects[persona_index].id);
// The player's own first 8-hex-digit group, spliced onto the
// persona's own remaining groups: a distinct, real, well-formed
// uuid string that still shares `handle_for`'s whole extent with
// the player.
let colliding_text = format!("{}{}", &player_text[..8], &persona_text[8..]);
let colliding_id: SubjectId =
serde_json::from_value(serde_json::Value::String(colliding_text)).expect("a valid uuid deserializes");
assert_ne!(colliding_id, snapshot.subjects[persona_index].id, "the forged id must be a distinct subject");
snapshot.subjects[persona_index].id = colliding_id;
let error = collision_refusal(&snapshot).expect("a genuine collision is detected");
assert!(error.contains("share the handle"), "{error}");
}
/// PA.f127/PA.f133: `round_snapshot` is the one owner both `infer_round`
/// and `execute_round` call for a round's own snapshot and collision
/// check. `fetch_round_snapshot`'s test seam (`force_round_snapshot`)
/// stands in for the kernel fetch with the same genuine, spliced-real-id
/// collision the test above drives through the pure rule directly —
/// this drives it through the *production async door itself*, the one
/// both callers share, so a mutation of the `collision_refusal` call
/// inside `round_snapshot` (`.filter(|_| false)`) fails this rather than
/// only a copy of the check. Because `infer_round` and `execute_round`
/// now call the identical function, this one test covers both: there is
/// no second implementation left for either to diverge into.
#[tokio::test]
async fn a_forced_handle_collision_refuses_the_round_through_round_snapshot() {
let fixture = play_world(Some("Mara"), "player-forced-handle-collision").await;
let mut snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let persona_index = snapshot
.subjects
.iter()
.position(|row| row.controller_mode == Some(ControllerMode::NarrativePersona))
.unwrap();
let player_text = subject_id_text(&snapshot, player);
let persona_text = subject_id_text(&snapshot, snapshot.subjects[persona_index].id);
let colliding_text = format!("{}{}", &player_text[..8], &persona_text[8..]);
let colliding_id: SubjectId =
serde_json::from_value(serde_json::Value::String(colliding_text)).expect("a valid uuid deserializes");
snapshot.subjects[persona_index].id = colliding_id;
let directory = tempfile::tempdir().unwrap();
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table.force_round_snapshot(snapshot);
let error = table.round_snapshot().await.unwrap_err();
assert!(error.contains("share the handle"), "{error}");
}
/// PA.f68/PA.f112/PA.f142: `run_lock` is acquired with `try_lock`, not a
/// blocking wait, so the replay check and the turn open still happen
/// under one acquisition (no two concurrent `run` calls for this table
/// ever interleave), but a second call arriving while the first is still
/// inside its own round loop is refused *at once* with
/// `TurnStillRunning` rather than queuing behind it for up to
/// `ROUND_BUDGET` rounds of inference (PA.f142). Two concurrent `run`
/// calls carrying the *same* idempotency key — the shape a genuine
/// client retry racing itself takes — therefore give exactly one turn
/// either way: one call actually runs it, and the other, if it loses the
/// race for the lock, is refused immediately rather than replaying (a
/// caller that retries again afterward, once the key is durably applied,
/// gets `Replayed` then). Mutation: removing `run_lock`'s acquisition
/// (or reverting `try_lock` to a blocking `lock().await`) reopens the
/// race this asserts against.
#[tokio::test]
async fn two_concurrent_world_play_calls_for_one_world_give_one_turn() {
let fixture = play_world(None, "player-one-turn-per-world").await;
let directory = tempfile::tempdir().unwrap();
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output(
"proj-race",
vec![text_event("The race settles.")],
)]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = Arc::new(
PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![output(
"r0",
vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))],
)]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap(),
);
let key = test_turn_id(919);
let first = {
let table = table.clone();
let principal = fixture.principal.clone();
let key = key.clone();
tokio::spawn(async move { table.run(&principal, key, "Who goes there?".into()).await })
};
let second = {
let table = table.clone();
let principal = fixture.principal.clone();
let key = key.clone();
tokio::spawn(async move { table.run(&principal, key, "Who goes there?".into()).await })
};
let (first_outcome, second_outcome) = tokio::join!(first, second);
let first_outcome = first_outcome.unwrap();
let second_outcome = second_outcome.unwrap();
// Exactly one of the two actually ran the turn; the other, having
// lost the race for `run_lock`, is refused at once rather than
// queued — `try_lock` decides which one wins, not this test.
let ran = match (first_outcome, second_outcome) {
(Ok(RunOutcome::Ran { .. }), Err(PlayError::TurnStillRunning)) => true,
(Err(PlayError::TurnStillRunning), Ok(RunOutcome::Ran { .. })) => true,
other => panic!("expected exactly one Ran and one immediate TurnStillRunning refusal: {other:?}"),
};
assert!(ran);
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(
turn.applied_keys.iter().filter(|applied| **applied == key).count(),
1,
"the race's shared key must be recorded on the turn exactly once, never once per racer"
);
}
/// PA.f142, second half: a request racing an in-flight turn is refused
/// at once, never queued behind it. `GatedPort` blocks the first call's
/// own round-0 inference until this test explicitly releases it, so the
/// second call is known to arrive while `run_lock` is genuinely still
/// held — not a race whose outcome depends on scheduling luck.
#[tokio::test]
async fn a_request_racing_an_in_flight_turn_is_refused_at_once_not_queued() {
let fixture = play_world(None, "player-f142-busy").await;
let directory = tempfile::tempdir().unwrap();
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-gated", vec![text_event("Settled.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let gated = GatedPort::new(output(
"r0",
vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))],
));
let table = Arc::new(
PlayTable::new(
fixture.world.clone(),
personas,
gated.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap(),
);
let first = {
let table = table.clone();
let principal = fixture.principal.clone();
let key = test_turn_id(950);
tokio::spawn(async move { table.run(&principal, key, "Who goes there?".into()).await })
};
// The first call is now durably inside `infer_round`'s own
// `self.inference.infer(...)` call, holding `run_lock` for the
// whole body of `run` — genuinely busy, not merely "about to run".
tokio::time::timeout(Duration::from_secs(5), gated.wait_ready())
.await
.expect("the first call must reach the gated inference within the timeout");
let busy = tokio::time::timeout(Duration::from_secs(5), {
let table = table.clone();
let principal = fixture.principal.clone();
let key = test_turn_id(951);
async move { table.run(&principal, key, "Anyone there?".into()).await }
})
.await
.expect("a busy table must refuse at once, not block waiting for run_lock");
assert!(
matches!(busy, Err(PlayError::TurnStillRunning)),
"a request racing an in-flight turn must be refused immediately: {busy:?}"
);
gated.release();
let first_outcome = first.await.unwrap().unwrap();
assert!(matches!(first_outcome, RunOutcome::Ran { .. }));
// PA.f142's own "careful" clause: once the first call has actually
// returned (so `run_lock` is free again), answering an open
// question the *same* table is now waiting on must still succeed —
// `try_lock` never starves a genuine answer, it only refuses a
// request that arrives while the lock is truly held.
let ask_table = Arc::new(
PlayTable::new(
fixture.world.clone(),
PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap(),
ScriptedPort::new(vec![output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
)]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1-ask.cc"),
)
.unwrap(),
);
ask_table
.run(&fixture.principal, test_turn_id(952), "start".into())
.await
.unwrap();
let question_id = ask_table.store.lock().await.current().unwrap().open_question_id().unwrap();
let answered = ask_table
.run(
&fixture.principal,
test_turn_id(953),
PlayRequest {
text: "left".into(),
answers: Some(question_id),
},
)
.await;
assert!(
answered.is_ok(),
"answering an open question must not be refused as busy once no call holds the lock: {answered:?}"
);
}
/// PA.f68/PA.f112: `run_lock` lives on `PlayTable`, one per world in
/// production (`AppState.play` holds one `Arc<PlayTable>` for the one
/// world this process owns) — so two *different* worlds' own tables never
/// share a lock and never block each other. Two fresh turns, one per
/// table, run concurrently and each resolves on its own, with distinct
/// turn ids.
#[tokio::test]
async fn two_worlds_own_play_tables_run_independently() {
let fixture_a = play_world(None, "player-world-a").await;
let fixture_b = play_world(None, "player-world-b").await;
let directory_a = tempfile::tempdir().unwrap();
let directory_b = tempfile::tempdir().unwrap();
let build_table = |fixture: &WorldFixture, directory: &tempfile::TempDir| {
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj", vec![text_event("Settled.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![output(
"r0",
vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))],
)]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap()
};
let table_a = Arc::new(build_table(&fixture_a, &directory_a));
let table_b = Arc::new(build_table(&fixture_b, &directory_b));
let run_a = {
let table_a = table_a.clone();
let principal = fixture_a.principal.clone();
tokio::spawn(async move {
table_a
.run(&principal, test_turn_id(931), "Hello from world A.".into())
.await
})
};
let run_b = {
let table_b = table_b.clone();
let principal = fixture_b.principal.clone();
tokio::spawn(async move {
table_b
.run(&principal, test_turn_id(932), "Hello from world B.".into())
.await
})
};
let (outcome_a, outcome_b) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(run_a, run_b)
})
.await
.expect("two worlds' own tables must not block on each other's run_lock");
assert!(matches!(outcome_a.unwrap().unwrap(), RunOutcome::Ran { .. }));
assert!(matches!(outcome_b.unwrap().unwrap(), RunOutcome::Ran { .. }));
let turn_a = table_a.store.lock().await.current().cloned().unwrap();
let turn_b = table_b.store.lock().await.current().cloned().unwrap();
assert_ne!(
turn_a.turn_id, turn_b.turn_id,
"each world's own table opened its own turn"
);
}
/// PA.f134: a turn that reaches `ask_player` names its own `QuestionId`
/// through `RunOutcome::Ran` itself — no test-local construction of the
/// id — and feeding that exact id back through a fresh `run` call
/// answers it. Also checks `PlayTable::current_turn_view`, the door a
/// separate later reader (PA.f134's own consumer-facing seam) uses
/// instead of a second `run` call, agrees with it at every stage.
#[tokio::test]
async fn a_question_is_answerable_through_run_outcome_alone() {
let fixture = play_world(None, "player-f134-answerable").await;
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
let ask = output(
"r0",
vec![call_event(
"c0",
ASK_PLAYER_TOOL,
serde_json::json!({"question": "Which way?"}),
)],
);
let end = output("r1", vec![call_event("c1", END_TURN_TOOL, serde_json::json!({}))]);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-answered", vec![text_event("Settled.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![ask, end]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
// Before any turn opens, there is nothing to view.
assert!(table.current_turn_view().await.is_none());
let outcome = table
.run(&fixture.principal, test_turn_id(960), "start".into())
.await
.unwrap();
let (turn_id, question) = match outcome {
RunOutcome::Ran { turn_id, question } => (turn_id, question),
other => panic!("expected Ran with an open question: {other:?}"),
};
let question = question.expect("a turn that asks a question must report it on Ran");
assert_eq!(question.text, "Which way?");
assert_eq!(question.id.turn_id, turn_id);
let view = table.current_turn_view().await.unwrap();
assert_eq!(view.turn_id, turn_id);
assert_eq!(view.state, PlayTurnState::AwaitingPlayer);
assert_eq!(view.question.as_ref(), Some(&question));
assert_eq!(view.refusal, None);
// Feeding exactly `question.id` back — never a hand-built
// `QuestionId` — answers it and the turn closes.
let answered = table
.run(
&fixture.principal,
test_turn_id(961),
PlayRequest {
text: "left".into(),
answers: Some(question.id),
},
)
.await
.unwrap();
match answered {
RunOutcome::Ran { turn_id: answered_turn_id, question: None } => {
assert_eq!(answered_turn_id, turn_id, "the answer resumes the same turn");
}
other => panic!("expected Ran with no further open question: {other:?}"),
}
let view = table.current_turn_view().await.unwrap();
assert_eq!(view.state, PlayTurnState::Closed);
assert_eq!(view.question, None);
// A replay of the key that opened the turn also names the turn and
// its own then-open question — `Replayed` carries the same
// information `Ran` did, not merely the turn id.
let replayed = table
.run(&fixture.principal, test_turn_id(960), "start".into())
.await
.unwrap();
assert_eq!(
replayed,
RunOutcome::Replayed { turn_id, question: None },
"a replay of the opening key, now that the turn has closed, carries no open question"
);
}
/// PA.f136: a resumed dispatch call resubmits its own already-recorded
/// subjects, never a value re-derived from `parse_dispatch` against
/// whatever the round's own snapshot says *now* — the same "recorded
/// body decides" rule `commit_authoring_run`/`execute_advance_time`/
/// `execute_actor_call` already follow. `force_round_snapshot` stands in
/// for a subject the world changed out from under the resumed call (a
/// retirement removing her from the dispatchable set `parse_dispatch`
/// resolves against): the *live* world `execute_dispatch` itself
/// re-fetches still has her, so the resumed call recovers her already-
/// durable prose exactly like `a_resumed_dispatch_call_recovers_its_own_persona_prose_not_already_acted`
/// does, proving the recorded subject list survived, not merely that
/// dispatch didn't crash. Mutation: re-parsing `arguments` against the
/// round's own snapshot regardless of whether a body is already
/// recorded.
#[tokio::test]
async fn a_resumed_dispatch_call_resubmits_its_recorded_subjects_not_a_reparsed_list() {
const PROSE: &str = "Mara studies the retired door.";
let fixture = play_world(Some("Mara"), "player-f136-retire").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let mara_text = subject_id_text(&snapshot, mara);
// The snapshot `round_snapshot` will hand `execute_round` for the
// resumed round: Mara removed from the dispatchable subject list
// entirely, standing in for a retirement between the crash and the
// resume. `execute_dispatch`'s own "already durable" branch never
// reads this snapshot at all (it re-fetches the live one through
// `self.play.snapshot()`), so this only ever affects `parse_dispatch`.
let mut retired_snapshot = snapshot.clone();
retired_snapshot.subjects.retain(|row| row.id != mara);
let round = output(
"r0",
vec![
call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_text]})),
call_event("c1", END_TURN_TOOL, serde_json::json!({})),
],
);
let turn_id = test_turn_id(962);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt: format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"Who's there?"
),
player_prose: vec!["Who's there?".into()],
rounds: vec![round],
// The dispatch call's own body is already durable (recorded
// before `execute_dispatch` ever ran, PA.f125) but its result is
// not: exactly the crash window a resumed call recovers from.
calls: vec![CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![mara])),
result: None,
}],
persona_turns: vec![(mara, fake_persona_turn(PROSE))],
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let mut store = PlayTurnStore::open(&store_path).unwrap();
store.open_new_turn(crashed_turn).unwrap();
}
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.force_round_snapshot(retired_snapshot);
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let dispatch_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
let recorded_body = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.body.clone());
drop(stored);
assert!(
dispatch_result.contains(PROSE),
"the resumed call must still carry Mara's own already-durable prose: {dispatch_result}"
);
assert!(
!dispatch_result.contains("names no dispatchable subject"),
"the resumed call must not be re-parsed against the round's own (retired) snapshot: {dispatch_result}"
);
assert!(
matches!(&recorded_body, Some(RecordedCall::Dispatch(list)) if *list == vec![mara]),
"the call's own recorded body must still name Mara, not be overwritten with a shorter re-parsed list: {recorded_body:?}"
);
}
/// PA.f139: `dispatch_owner` credits the *earliest* call, in call order,
/// that names a subject — never the latest. Two dispatch calls in one
/// round both name Mara; only the first actually produced her
/// `persona_turns` entry (the crashed-and-resumed shape: her prose is
/// already durable, but only the first call's own record is present at
/// the point she was credited). Resuming the *second*, still-unresolved
/// call must recognize she already acted through the first and say so,
/// never re-claim her prose as if the second call had produced it.
/// Mutation: `.min()` → `.max()` in `dispatch_owner`.
#[tokio::test]
async fn dispatch_owner_credits_the_earliest_call_not_the_latest() {
const PROSE: &str = "Mara studies the door.";
let fixture = play_world(Some("Mara"), "player-f139-owner").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let mara_text = subject_id_text(&snapshot, mara);
let round = output(
"r0",
vec![
call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_text.clone()]})),
call_event("c1", DISPATCH_TOOL, serde_json::json!({"subjects": [mara_text]})),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let turn_id = test_turn_id(963);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt: format!(
"{}\n\nThe player writes:\n{}\n",
table_view(&snapshot),
"Who's there?"
),
player_prose: vec!["Who's there?".into()],
rounds: vec![round],
calls: vec![
CallRecord {
call_id: "c0".into(),
round: 0,
slot: 0,
body: Some(RecordedCall::Dispatch(vec![mara])),
result: Some(format!("Mara: {PROSE}")),
},
CallRecord {
call_id: "c1".into(),
round: 0,
slot: 1,
body: Some(RecordedCall::Dispatch(vec![mara])),
result: None,
},
],
persona_turns: vec![(mara, fake_persona_turn(PROSE))],
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let mut store = PlayTurnStore::open(&store_path).unwrap();
store.open_new_turn(crashed_turn).unwrap();
}
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let second_result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 1)
.and_then(|call| call.result.clone())
.unwrap();
drop(stored);
assert!(
second_result.contains("already acted"),
"the second call naming an already-owned subject must be credited to the earliest \
call, not re-claim her prose: {second_result}"
);
assert!(
!second_result.contains(PROSE),
"the second call must not carry the first call's own prose: {second_result}"
);
}
/// PA.f143: `execute_dispatch`'s own `pending.into_iter().zip(results)`
/// pairs each dispatched subject's own summary slot and `persona_turns`
/// entry with its own spawned task's result, in the call's own JSON
/// `subjects` order — never completion order. No test in the repo
/// dispatched more than two subjects concurrently before this; three
/// distinct subjects, each with distinguishable prose, pins the joined
/// summary's own order and `persona_turns`'s own order. This follows
/// `a_persona_cannot_speak_another_dispatched_personas_exact_quote`'s own
/// proven two-subject shape (a shared `ScriptedPort` FIFO queue primed
/// in JSON order, concurrently dispatched under a semaphore that never
/// contends) one subject further. Mutation: reversing either side of the
/// zip, or `results`/`pending` independently.
#[tokio::test]
async fn concurrent_three_subject_dispatch_preserves_json_order_in_summary_and_persona_turns() {
let fixture = play_world(Some("Mara"), "player-f143-three").await;
let snapshot = fixture.world.snapshot().await.unwrap();
let mara = persona_id(&snapshot);
let affordance_id = bracketed_id_after(&table_view(&snapshot), "speak [");
let declare = output(
"r0",
vec![
call_event(
"c0",
"declare_subject",
serde_json::json!({
"handle": "borin",
"label": "Borin",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event(
"c1",
"declare_subject",
serde_json::json!({
"handle": "cass",
"label": "Cass",
"kind": "person",
"controller": {"type": "narrative_persona"},
"affordances": [{"ref": "existing", "value": affordance_id}],
"position": null,
}),
),
call_event("c2", END_TURN_TOOL, serde_json::json!({})),
],
);
let directory = tempfile::tempdir().unwrap();
{
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![output("proj-declare", vec![text_event("Quiet.")])]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![declare]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(3)),
directory.path().join("declare-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(964), "Introduce Borin and Cass.".into())
.await
.unwrap();
}
let snapshot = fixture.world.snapshot().await.unwrap();
let borin = snapshot.subjects.iter().find(|row| row.label == "Borin").unwrap().id;
let cass = snapshot.subjects.iter().find(|row| row.label == "Cass").unwrap().id;
let mara_text = subject_id_text(&snapshot, mara);
let borin_text = subject_id_text(&snapshot, borin);
let cass_text = subject_id_text(&snapshot, cass);
let dispatch_round = output(
"r0",
vec![call_event(
"c0",
DISPATCH_TOOL,
serde_json::json!({"subjects": [mara_text, borin_text, cass_text]}),
)],
);
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![
output("proj-mara", vec![text_event("Mara considers the player.")]),
output("persona-mara", vec![text_event("Mara nods once.")]),
output("proj-borin", vec![text_event("Borin waits his turn.")]),
output("persona-borin", vec![text_event("Borin clears his throat.")]),
output("proj-cass", vec![text_event("Cass watches quietly.")]),
output("persona-cass", vec![text_event("Cass says nothing.")]),
]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![dispatch_round]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(3)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(965), "Who's there?".into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
let result = turn
.calls
.iter()
.find(|call| call.round == 0 && call.slot == 0)
.and_then(|call| call.result.clone())
.unwrap();
let mara_at = result.find("Mara nods once.").expect("Mara's own prose is in the summary");
let borin_at = result
.find("Borin clears his throat.")
.expect("Borin's own prose is in the summary");
let cass_at = result.find("Cass says nothing.").expect("Cass's own prose is in the summary");
assert!(
mara_at < borin_at && borin_at < cass_at,
"the dispatch summary must list subjects in the call's own JSON order, not completion order: {result}"
);
let order: Vec<SubjectId> = turn.persona_turns.iter().map(|(id, _)| *id).collect();
assert_eq!(
order,
vec![mara, borin, cass],
"persona_turns must record dispatched subjects in the call's own JSON order too"
);
}
/// PA.f137: `round_snapshot` is the one owner `infer_round` and
/// `execute_round` both call for a round's own snapshot and collision
/// check, but `a_forced_handle_collision_refuses_the_round_through_round_snapshot`
/// above calls `table.round_snapshot()` directly — it would still pass
/// if either caller were mutated to call `fetch_round_snapshot` instead
/// (skipping the collision check). This drives the same forced
/// collision through the *production `run` path* on a fresh turn, which
/// only ever reaches `round_snapshot` through `infer_round`: the turn
/// must close with the collision fault, and `ScriptedPort`'s own empty
/// inference queue proves no `InferenceRequest` was ever built (a
/// mutation bypassing the check would reach `round_tools`/inference
/// instead and fail with "scripted port exhausted", not "share the
/// handle").
#[tokio::test]
async fn a_forced_handle_collision_closes_a_fresh_round_through_infer_round() {
let fixture = play_world(Some("Mara"), "player-f137-infer").await;
let mut snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let persona_index = snapshot
.subjects
.iter()
.position(|row| row.controller_mode == Some(ControllerMode::NarrativePersona))
.unwrap();
let player_text = subject_id_text(&snapshot, player);
let persona_text = subject_id_text(&snapshot, snapshot.subjects[persona_index].id);
let colliding_text = format!("{}{}", &player_text[..8], &persona_text[8..]);
let colliding_id: SubjectId =
serde_json::from_value(serde_json::Value::String(colliding_text)).expect("a valid uuid deserializes");
snapshot.subjects[persona_index].id = colliding_id;
let directory = tempfile::tempdir().unwrap();
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table.force_round_snapshot(snapshot);
let outcome = table
.run(&fixture.principal, test_turn_id(966), "Who's there?".into())
.await
.unwrap();
assert!(matches!(outcome, RunOutcome::Ran { .. }));
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
let fault = turn.fault.as_deref().expect("the collision must close the turn with a fault");
assert!(fault.contains("share the handle"), "{fault}");
}
/// PA.f137's other half: the same forced collision, driven through
/// `execute_round` instead — a round already open (an unresolved call
/// from a prior pass) never touches `infer_round` at all on resume, so
/// this reaches the *other* of the two callers `round_snapshot` unifies.
#[tokio::test]
async fn a_forced_handle_collision_closes_a_resumed_round_through_execute_round() {
let fixture = play_world(Some("Mara"), "player-f137-execute").await;
let mut snapshot = fixture.world.snapshot().await.unwrap();
let player = player_id(&snapshot);
let persona_index = snapshot
.subjects
.iter()
.position(|row| row.controller_mode == Some(ControllerMode::NarrativePersona))
.unwrap();
let player_text = subject_id_text(&snapshot, player);
let persona_text = subject_id_text(&snapshot, snapshot.subjects[persona_index].id);
let colliding_text = format!("{}{}", &player_text[..8], &persona_text[8..]);
let colliding_id: SubjectId =
serde_json::from_value(serde_json::Value::String(colliding_text)).expect("a valid uuid deserializes");
snapshot.subjects[persona_index].id = colliding_id;
// A round already open, with an unresolved call — `execute_round`'s
// own entry, `round_is_open`, is what `run` takes when a round is
// present but not yet fully resolved; `infer_round` is never called
// for it.
let round = output("r0", vec![call_event("c0", END_TURN_TOOL, serde_json::json!({}))]);
let turn_id = test_turn_id(967);
let crashed_turn = PlayTurn {
turn_id: turn_id.clone(),
applied_keys: Vec::new(),
opening_prompt: "opening".into(),
player_prose: vec!["hello".into()],
rounds: vec![round],
calls: Vec::new(),
persona_turns: Vec::new(),
question: None,
question_surface_version: None,
refusal: None,
narration: None,
fault: None,
state: PlayTurnState::Running,
};
let directory = tempfile::tempdir().unwrap();
let store_path = directory.path().join("play-turn-v1.cc");
{
let mut store = PlayTurnStore::open(&store_path).unwrap();
store.open_new_turn(crashed_turn).unwrap();
}
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let table = PlayTable::new(
fixture.world.clone(),
personas,
ScriptedPort::new(vec![]),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
&store_path,
)
.unwrap();
table.force_round_snapshot(snapshot);
table
.run(&fixture.principal, turn_id, String::new().into())
.await
.unwrap();
let stored = table.store.lock().await;
let turn = stored.current().unwrap();
assert_eq!(turn.state, PlayTurnState::Closed);
let fault = turn.fault.as_deref().expect("the collision must close the resumed round with a fault");
assert!(fault.contains("share the handle"), "{fault}");
}
}