From 651bfb2d34486dc76e12d713127a214f1930fda8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Sep 2026 23:46:03 +0200 Subject: [PATCH] Delete the unreachable SPEAK_KIND guard; test the driver's Interrupted arm Fork D was dead code: affordance_grants is insert-only and a checkpoint that reached ReadyToSubmit/NoProposal already had speech, so a fresh opportunity on the same scope always carries it too. Delete the guard, the overtaken(Some(..)) call it fed, and note why in `interrupted`. Widen InferencePurpose, PreparedInference::purpose, and InferenceEvent to pub(crate) (plus fixture_inference_events/fixture_recovery_required test seams) so runtime::tests can script an inference port by purpose. Add a driver-level end-to-end test: through run_cover_tick, the world's operational agent speaks once between the narrative cell's Persona turn and its first submit (a re-lowering) and once more between the re-lowered submit and its own commit, spending the one re-lowering the turn is owed. The second change lands on the driver's own Interrupted arm rather than ControllerRunner::run_narrative directly, and the tick commits exactly the operational agent's two acts. WorldMailbox::submit_controller stays pub(super); the test reaches speech through the already pub(crate) ControllerPort wrapper instead. Soul's follow-up on step 10 (the witness pass): add a MidTurnCommit:: Witness cause and a controllers.rs test proving a Witness landing between the actor's bound turn and its submit re-lowers with only the anonymous "what this person knows changed" line and no Overheard block - KnowledgeSource::Witnessed writes no spoken_at, so overheard_since finds nothing. Rebased onto origin/codex/ghostlight-dungeon-mvp (step 10 integrated, 5cd8853) after step 9's own follow-ups landed; no conflicts at this branch's controllers.rs/runtime.rs seams. Co-Authored-By: Claude Fable 5.1 --- crates/ghostlight-dungeon/src/runtime.rs | 188 ++++++++++++- .../src/world/controllers.rs | 254 +++++++++++++++++- crates/ghostlight-dungeon/src/world/mod.rs | 5 +- 3 files changed, 431 insertions(+), 16 deletions(-) diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index adc87b8..44603f8 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -3001,9 +3001,10 @@ mod tests { } use crate::world::{ - ControllerWork, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError, - ControllerWorkWrite, InferenceFault, InferenceOutput, InferencePort, InferenceRequest, - PreparedInference, fixture_inference_output, fixture_prepared_inference, + ControllerPort, ControllerWork, ControllerWorkLookup, ControllerWorkStore, + ControllerWorkStoreError, ControllerWorkWrite, InferenceEvent, InferenceFault, + InferenceOutput, InferencePort, InferencePurpose, InferenceRequest, PreparedInference, + SubjectId, fixture_inference_events, fixture_inference_output, fixture_prepared_inference, }; use std::sync::atomic::AtomicUsize; @@ -3269,6 +3270,187 @@ mod tests { ); } + /// Lands a real commit on the world's operational agent, through its own + /// granted `speak` affordance and `WorldMailbox::submit_controller` — the + /// same production port a controller's own decision uses, not a test-only + /// ingress. Mirrors `world::controllers`'s own `MidTurnCommit::Speech`, + /// but from outside the `world` module, using only what this module's + /// tests already have `pub(crate)` access to. + async fn speak_through(mailbox: &WorldMailbox, speaker: SubjectId, text: &str) { + let port = ControllerPort::new(mailbox.clone()); + let snapshot = port.snapshot().await.unwrap(); + let opportunity = snapshot + .opportunities + .iter() + .find(|entry| entry.scope.subject_id == speaker) + .expect("the speaker has a live opportunity") + .clone(); + let entry = snapshot + .affordances + .iter() + .find(|entry| { + entry.entry.kind.0 == "speak" && opportunity.affordance_ids.contains(&entry.id) + }) + .expect("the speaker was granted speech") + .clone(); + port.submit_controller( + CommandId::new(), + &opportunity, + DecisionInvocation { + affordance: entry.id, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new(text.to_string()).unwrap()), + }, + ) + .await + .expect("the mid-turn speech committed"); + } + + /// Answers a narrative cell's inference by purpose, landing a real + /// commit on the world's operational agent just before each Interpreter + /// round returns. Every other purpose — the operational agent's own + /// cell, spawned into the same tick — declines immediately: its outcome + /// is not this test's subject, and this port scripts one narrative turn + /// only. + struct InterruptingCoverPort { + mailbox: WorldMailbox, + source: String, + speech_start: usize, + speech_end: usize, + speaker: SubjectId, + interpreter_calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl InferencePort for InterruptingCoverPort { + fn prepare(&self, request: InferenceRequest) -> Result { + fixture_prepared_inference(request) + } + + async fn infer( + &self, + request: PreparedInference, + ) -> Result { + match request.purpose { + InferencePurpose::Projector => Ok(fixture_inference_output( + "The room holds its breath.", + "projector", + )), + InferencePurpose::Persona => { + Ok(fixture_inference_output(self.source.clone(), "persona")) + } + InferencePurpose::Interpreter => { + let round = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); + let text = if round == 0 { + "The tollhouse ledger is short." + } else { + "A second bell rings over the yard." + }; + speak_through(&self.mailbox, self.speaker, text).await; + Ok(fixture_inference_events( + vec![ + InferenceEvent::ToolCall { + call_id: format!("call_speak_{round}"), + name: "speak".into(), + arguments: json!({ + "source_start_byte": self.speech_start, + "source_end_byte": self.speech_end, + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: format!("call_finish_{round}"), + name: "finish_interpretation".into(), + arguments: "{}".into(), + }, + ], + &format!("interpreter-{round}"), + )) + } + // The operational agent's own cell shares this tick and this + // port; declining every other purpose keeps this fixture to + // the one narrative turn it scripts. + InferencePurpose::OperationalAgent + | InferencePurpose::GroupedAgent + | InferencePurpose::Elaboration => Err(InferenceFault::fixture_recovery_required( + "fixture agent declines every purpose but the narrative one", + )), + } + } + } + + /// Soul's follow-up: the driver's own `Interrupted` arm + /// (`Ok(CellRun::Narrative(NarrativeRun::Interrupted(..)))` in + /// `run_cover_tick`), exercised through the tick driver rather than + /// `ControllerRunner::run_narrative` directly. The operational agent + /// speaks once between the narrative cell's Persona turn and its first + /// submit — a re-lowering, per `world::controllers`'s own + /// `a_neighbours_speech_between_the_turn_and_submit_is_re_lowered_once` + /// — and once more between the re-lowered submit and its own commit, + /// spending the one re-lowering the turn is owed + /// (`a_second_scope_change_after_the_re_lowering_spends_nothing`'s own + /// shape, reached here through the driver instead of the runner). The + /// gap the pass exists to close: the tick commits exactly the + /// operational agent's two acts and nothing from the overtaken turn. + #[tokio::test] + async fn a_second_mid_turn_change_reaches_the_drivers_interrupted_arm() { + use crate::world::ControllerMode; + + let fixture = fixture().await; + active_two_cell_world(&fixture.state, &fixture.cookie).await; + + let snapshot = fixture.state.world.snapshot().await.unwrap(); + let operational_agent = snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::OperationalAgent)) + .expect("the genesis world grants an operational agent") + .id; + + let source = "I say, \"Hold the line at the gate.\""; + let speech = "Hold the line at the gate."; + let start = source.find(speech).unwrap(); + + let port = Arc::new(InterruptingCoverPort { + mailbox: fixture.state.world.clone(), + source: source.into(), + speech_start: start, + speech_end: start + speech.len(), + speaker: operational_agent, + interpreter_calls: AtomicUsize::new(0), + }); + let mut state = fixture.state.clone(); + state.controllers = Some(Arc::new(ControllerRunner::with_test_ports( + state.world.clone(), + port.clone(), + Arc::new(AlwaysFreshWorkStore), + test_controller_models(), + ))); + // One permit serializes the two cells' full runs (see + // `the_tick_driver_never_exceeds_its_controller_permit_pool`), so the + // operational agent's own turn — which this port declines on its + // first call — can never interleave with the narrative cell's + // Interpreter rounds. + state.controller_permits = Arc::new(Semaphore::new(1)); + + let committed_before = fixture.state.world.operator_log().await.unwrap().len(); + run_cover_tick(&state).await; + let committed_after = fixture.state.world.operator_log().await.unwrap().len(); + + assert_eq!( + port.interpreter_calls.load(Ordering::SeqCst), + 2, + "the turn should spend exactly its one re-lowering, not loop or stop short" + ); + assert_eq!( + committed_after - committed_before, + 2, + "only the operational agent's two mid-turn acts land; the \ + overtaken narrative turn commits nothing" + ); + } + /// `drive_one_tick` never names `run_cover_tick`: `run_cover` is opaque to /// it, so this test substitutes a fake that walks a real `Cover` (three /// singleton cells, from three fabricated opportunities) and records each diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 17ae5d5..4de35f5 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -115,12 +115,12 @@ pub(crate) struct InferenceRequest { /// it under the same request ID would be a replay conflict. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct PreparedInference { - purpose: InferencePurpose, + pub(crate) purpose: InferencePurpose, pub(super) invocation: CodexTransportInvocation, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub(super) enum InferenceEvent { +pub(crate) enum InferenceEvent { Text(String), ToolCall { call_id: String, @@ -211,6 +211,15 @@ impl InferenceFault { pub(crate) fn fixture_integrity_violation(detail: impl Into) -> Self { Self::integrity_violation(detail) } + + /// The non-quarantining counterpart: a test port outside this module that + /// needs one purpose to fail without raising + /// `ControllerError::requires_quarantine` (so a sibling cell in the same + /// tick is unaffected) has no other legal way to build one. + #[cfg(test)] + pub(crate) fn fixture_recovery_required(detail: impl Into) -> Self { + Self::new(detail) + } } #[async_trait] @@ -258,6 +267,20 @@ pub(crate) fn fixture_inference_output(text: impl Into, receipt: &str) - } } +/// The same seam as `fixture_inference_output`, for a test port outside this +/// module that needs to answer with something other than plain prose — an +/// Interpreter's `speak`/`finish_interpretation` tool calls, in particular. +#[cfg(test)] +pub(crate) fn fixture_inference_events( + events: Vec, + receipt: &str, +) -> InferenceOutput { + InferenceOutput { + events, + receipt_digest: format!("sha256:{receipt}"), + } +} + /// Production lowering to CodexConnector. There is deliberately no retry, /// fallback model, output repair, or stage registry here; transport failure is /// returned to the owning controller flow with its pending evidence intact. @@ -3604,15 +3627,12 @@ impl ControllerRunner { actual: fresh.opportunity.scope_digest, })); } - if !fresh - .granted - .iter() - .any(|entry| entry.entry.kind.0 == SPEAK_KIND) - { - // Lowering prose into an invocation the fresh grant set cannot - // express is a round bought to produce `SpeakUnavailable`. - return overtaken(&checkpoint, Some(fresh.opportunity.scope_digest.clone())); - } + // No branch here checks the fresh grant set for `SPEAK_KIND`: grants + // are recorded in an insert-only ledger (`affordance_grants` never + // removes an entry), and this checkpoint could only reach + // `ReadyToSubmit`/`NoProposal` by having speech granted for this + // scope already, so a fresh opportunity on the same scope always + // carries it too. let interruption = Interruption { components: fresh.subject.components.clone(), overheard: fresh.overheard_since(turn.binding().world_revision), @@ -10707,6 +10727,12 @@ mod tests { /// custody, a route closing under the actor's feet, a grant revoked out /// from under it, a commitment that names a counterparty. Ops(Vec), + /// An owner patch witnessing a pre-declared fact over `place`. Unlike a + /// neighbour's speech, this names no speaker and writes no `spoken_at` + /// row: `KnowledgeSource::Witnessed` is not `Told`, so + /// `overheard_since` finds nothing and the section renders only the + /// anonymous `knows` line. + Witness { fact: EntityId, place: EntityId }, } async fn apply_mid_turn(mailbox: &WorldMailbox, commit: &MidTurnCommit) { @@ -10800,6 +10826,35 @@ mod tests { .await .expect("the mid-turn operations committed"); } + MidTurnCommit::Witness { fact, place } => { + let owner = PrincipalId::new("owner"); + let authenticated = + AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner), + body: CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![crate::world::patch::ComponentOp::Witness { + fact: Ref::Existing(*fact), + place: Ref::Existing(*place), + confidence: Confidence::Certain, + }], + evidence: Vec::new(), + }, + }, + }, + &authenticated, + ) + .await + .expect("the mid-turn witness committed"); + } } } @@ -11204,6 +11259,183 @@ mod tests { task.await.unwrap(); } + /// The same genesis as `active_cell_mailbox`, plus one canonical fact + /// declared and evidenced at genesis (so it needs no post-genesis + /// `PatchAnswer`) that nobody yet knows: a live `EntityId` a mid-turn + /// `Witness` can land over the commons without declaring anything itself. + async fn witness_cell_mailbox() -> ( + tempfile::TempDir, + WorldMailbox, + tokio::task::JoinHandle<()>, + EntityId, + EntityId, + ) { + let directory = tempfile::tempdir().unwrap(); + let (mailbox, task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let owner = PrincipalId::new("owner"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let ledger = EvidenceRef::new("the fixture's own witnessed bell"); + let declarations = vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("commons"), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Fact(crate::world::patch::FactDeclaration { + handle: DraftHandle::new("bell"), + label: "A bell rings over the yard".into(), + statement: Statement::new("A bell rings over the yard.").unwrap(), + standing: crate::world::patch::FactStandingRef::Canonical { + evidence: ledger.clone(), + }, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("subject0"), + label: "Subject 0".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new("commons"))), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("subject1"), + label: "Subject 1".into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new("commons"))), + }), + ]; + let creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Witness Fixture".into(), + patch: WorldPatch { + declarations, + // Genesis is Draft phase, exempt from the post-genesis + // `PatchAnswer` a declaring `AdmitPatch` would need, so + // Subject 1 (never the narrative actor) is handed the + // fact here rather than through a second patch — a + // live `EntityId` to read back, not a fact this test's + // actor is meant to already know. + operations: vec![crate::world::patch::ComponentOp::AcquireKnowledge { + subject: Ref::Draft(DraftHandle::new("subject1")), + fact: Ref::Draft(DraftHandle::new("bell")), + source: crate::world::patch::AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }], + evidence: vec![ledger], + }, + scale_intent: WorldScaleIntentRef::default(), + }, + &authenticated, + ) + .await + .unwrap(); + let mut snapshot = mailbox.snapshot().await.unwrap(); + for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] { + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body, + }, + &authenticated, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + } + assert_eq!(snapshot.phase, WorldPhase::Active); + let commons = snapshot.places[0].id; + let bell = snapshot + .subjects + .iter() + .find(|subject| subject.label == "Subject 1") + .and_then(|subject| subject.knowledge.first()) + .map(|entry| entry.fact) + .expect("Subject 1 was handed the bell at genesis"); + (directory, mailbox, task, bell, commons) + } + + /// Soul's follow-up on the witness pass (step 10): a `Witness` landing + /// between the actor's bound narrative turn and its submit re-lowers like + /// every other un-authored cause, over the same anonymous `knows` line as + /// `every_un_authored_cause_is_re_lowered_with_no_actor_and_no_value`'s own + /// `AcquireKnowledge`-shaped causes. Unlike a neighbour's speech, the row a + /// witness writes carries no `spoken_at` (`KnowledgeSource::Witnessed` is + /// not `Told`), so `overheard_since` finds nothing this turn's binding + /// postdates, and the section must carry no `Overheard` block at all — not + /// even an empty one. + #[tokio::test] + async fn a_witness_between_the_turn_and_submit_carries_no_overheard_row() { + let (_directory, mailbox, task, bell, commons) = witness_cell_mailbox().await; + let (_actor, opportunity) = narrative_opportunity(&mailbox).await; + + let source = "I say, \"The western brace is giving way.\""; + let speech = "The western brace is giving way."; + let turn = interrupted_turn( + &mailbox, + source, + speech, + 2, + vec![( + 2, + MidTurnCommit::Witness { + fact: bell, + place: commons, + }, + )], + ); + let run = turn + .runner + .run_narrative(CommandId::new(), &opportunity) + .await + .unwrap(); + assert!( + matches!(run, NarrativeRun::Completed(_)), + "a witness did not re-lower to a commit: {run:?}" + ); + // Exactly one extra Interpreter inference, the one re-lowering owed. + assert_eq!(turn.calls.load(Ordering::SeqCst), 4); + + let seen = turn.seen.lock().unwrap(); + let second_interpreter = seen[3].clone(); + drop(seen); + let section = interruption_section_of(&second_interpreter) + .expect("the re-lowered prompt has no section"); + assert!( + section.contains("- what this person knows changed"), + "the witness cause did not report the anonymous knows line: {section}" + ); + assert!( + !section.contains("What was said to this person since:"), + "a witness produced an overheard block: {section}" + ); + for leaked in [ + "Subject 0", + "Subject 1", + " said:", + "came to know", + "spoken_at", + ] { + assert!( + !section.contains(leaked), + "the witness section leaked `{leaked}`: {section}" + ); + } + + drop(turn.runner); + drop(mailbox); + task.await.unwrap(); + } + /// Test 6. The row a re-lowering persists rebuilds its own request byte for /// byte from `(turn, prompt, completed)` at the derived round and takes no /// snapshot to do it — which is exactly what a resumed runner does with it. diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 26c2d82..dd0ac7a 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -62,8 +62,9 @@ pub(crate) use vault::VaultEvidenceSource; #[cfg(test)] pub(crate) use controllers::{ ControllerWork, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError, - ControllerWorkWrite, InferenceFault, InferenceOutput, InferencePort, InferenceRequest, - PreparedInference, fixture_inference_output, fixture_prepared_inference, + ControllerWorkWrite, InferenceEvent, InferenceFault, InferenceOutput, InferencePort, + InferencePurpose, InferenceRequest, PreparedInference, fixture_inference_events, + fixture_inference_output, fixture_prepared_inference, }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch, Site};