From 3ed38689398849b95dce7d8f3b8ee090fb100526 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Sep 2026 01:35:02 +0200 Subject: [PATCH] Falsify pass 8's boundary elaboration lane Soul's tests only. Fifteen checks against the landed shapes: the confinement predicate past its declaration lane, the fifth body the capability rule refuses, disjoint boundaries committing independently with a spent answer refused, an unsatisfied answer through the elaborator lane, canonical provenance surviving the ungating of `EvidenceRef::new`, a forged elaborator commit row re-sealed against its own chain digest so replay's authority half must answer, the emitted tool schema against the decoder branch by branch, the round-trip examples pinned as a second spelling, the unbounded effect slot the catalog cannot express, the elaboration runner's resume-and-repair round trip, a clean jurisdiction spending no inference, `controller_work.v7` refusing `v6`, and the custody discriminator's lane. Co-Authored-By: Claude Opus 5 --- .../src/world/controllers.rs | 388 ++++++++++++++++++ .../src/world/elaboration.rs | 91 ++++ .../ghostlight-dungeon/src/world/journal.rs | 146 +++++++ crates/ghostlight-dungeon/src/world/mod.rs | 344 ++++++++++++++++ crates/ghostlight-dungeon/src/world/patch.rs | 230 +++++++++++ 5 files changed, 1199 insertions(+) diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 776906c..b3469ea 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -5879,4 +5879,392 @@ mod tests { std::io::Write::write_all(&mut persona_file, persona_prose.as_bytes()).unwrap(); persona_file.sync_all().unwrap(); } + + // ---- Soul: the elaboration runner, which nothing drove ------------- + + /// A scripted provider for the authoring lane. It records the exact + /// prepared invocations it was asked to run, so the repaired round's prompt + /// can be read back out of the wire rather than out of the checkpoint. + struct ElaborationScript { + outputs: Mutex>>, + seen: Mutex>, + } + + #[async_trait] + impl InferencePort for ElaborationScript { + fn prepare(&self, request: InferenceRequest) -> Result { + fixture_prepared(request) + } + + async fn infer( + &self, + request: PreparedInference, + ) -> Result { + self.seen.lock().unwrap().push(request); + let mut outputs = self.outputs.lock().unwrap(); + assert!(!outputs.is_empty(), "the script ran out of rounds"); + outputs.remove(0) + } + } + + fn tool_round( + calls: Vec<(&str, Value)>, + receipt: &str, + ) -> Result { + output( + calls + .into_iter() + .enumerate() + .map(|(index, (name, arguments))| InferenceEvent::ToolCall { + call_id: format!("call-{index}"), + name: name.to_owned(), + arguments: arguments.to_string(), + }) + .collect(), + receipt, + ) + } + + /// An Active world with one dead end: a road nothing has grown into, one + /// route away from an inhabited commons. + async fn elaboration_mailbox() -> ( + tempfile::TempDir, + WorldMailbox, + tokio::task::JoinHandle<()>, + crate::world::EntityId, + crate::world::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 creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Elaboration Fixture".into(), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(crate::world::EntityDeclaration { + handle: DraftHandle::new("commons"), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(crate::world::EntityDeclaration { + handle: DraftHandle::new("road"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: Some(crate::world::Ref::Draft(DraftHandle::new( + "commons", + ))), + }), + Declaration::Route(crate::world::RouteDeclaration { + handle: DraftHandle::new("lane"), + label: "The Long Lane".into(), + from: crate::world::Ref::Draft(DraftHandle::new("commons")), + to: crate::world::Ref::Draft(DraftHandle::new("road")), + access: crate::world::AccessKind::Public, + cost: Cost(1), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("subject"), + label: "Subject".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: kernel_speak_grant(), + position: Some(crate::world::Ref::Draft(DraftHandle::new( + "commons", + ))), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + 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 place = |label: &str| { + snapshot + .places + .iter() + .find(|entry| entry.label == label) + .expect("the declared place") + .id + }; + let (commons, road) = (place("The Commons"), place("The Unwalked Road")); + assert_eq!(snapshot.boundaries.len(), 1, "one dead end, and only one"); + (directory, mailbox, task, commons, road) + } + + /// Spec test 20, which the pass wired and did not write. Round one submits a + /// draft the kernel refuses; the complete mismatch set is persisted against + /// the same command id; a **fresh** runner over the same store resumes, + /// renders those mismatches into the round-two prompt, and the repaired + /// draft commits under the same identity. + #[tokio::test] + async fn soul_an_elaboration_session_resumes_and_repairs_from_its_mismatch_set() { + let (_directory, mailbox, task, commons, road) = elaboration_mailbox().await; + let jurisdiction = crate::world::JurisdictionKey::PlaceSubtree(commons); + let road_id = serde_json::to_value(road).unwrap(); + let store = Arc::new(RecordingWorkStore { + persisted: Arc::new(AtomicBool::new(false)), + work: Mutex::new(BTreeMap::new()), + }); + let script = Arc::new(ElaborationScript { + outputs: Mutex::new(vec![ + // Round one: a shed whose container is a handle nothing + // declares, then a submit. + tool_round( + vec![ + ( + "declare_place", + json!({ + "handle": "shed", + "label": "The Roadside Shed", + "container": {"ref": "draft", "value": "nowhere"}, + }), + ), + ("submit", json!({})), + ], + "elaboration-round-zero", + ), + // Round two: the same shed, repaired onto the answered place. + tool_round( + vec![ + ( + "declare_place", + json!({ + "handle": "shed", + "label": "The Roadside Shed", + "container": {"ref": "existing", "value": road_id}, + }), + ), + ("submit", json!({})), + ], + "elaboration-round-one", + ), + ]), + seen: Mutex::new(Vec::new()), + }); + + let first = ElaborationRunner::new( + ElaborationPort::new(mailbox.clone()), + script.clone(), + Arc::new(NullEvidenceSource), + store.clone(), + models().elaborator, + ); + let outcome = first.step(jurisdiction).await.unwrap(); + assert_eq!( + outcome, + crate::world::elaboration::ElaborationOutcome::Rejected + ); + drop(first); + + // The kernel's complete set is what the checkpoint carries, under the + // same command id, and it is not empty. + let (command_id, mismatches, resumed_prompt) = { + let stored = store.work.lock().unwrap(); + assert_eq!(stored.len(), 1, "one session, one row"); + let ControllerWork::Elaboration(ElaborationCheckpoint::ElaboratorInFlight { + command_id, + last_mismatches, + agent_prompt, + completed, + .. + }) = stored.values().next().unwrap().clone() + else { + panic!("the rejection did not reopen the session for repair"); + }; + assert!(!last_mismatches.is_empty(), "the repair set is empty"); + assert!(completed.is_empty(), "a rejected round kept its evidence"); + (command_id, last_mismatches, agent_prompt) + }; + assert!( + resumed_prompt.contains("Your previous patch was refused"), + "{resumed_prompt}" + ); + for mismatch in &mismatches { + let rendered = serde_json::to_string(mismatch).unwrap(); + assert!( + resumed_prompt.contains(&rendered), + "the round-two prompt dropped {rendered}" + ); + } + + // A fresh runner over the same store, holding nothing from the first. + let second = ElaborationRunner::new( + ElaborationPort::new(mailbox.clone()), + script.clone(), + Arc::new(NullEvidenceSource), + store.clone(), + models().elaborator, + ); + let outcome = second.step(jurisdiction).await.unwrap(); + assert_eq!( + outcome, + crate::world::elaboration::ElaborationOutcome::Committed + ); + + // One identity across the whole session, and the answered boundary is + // no longer derived because the commit made the predicate stop holding. + { + let stored = store.work.lock().unwrap(); + assert_eq!(stored.len(), 1); + assert_eq!(stored.values().next().unwrap().command_id(), command_id); + } + let snapshot = mailbox.snapshot().await.unwrap(); + assert!(snapshot.boundaries.is_empty(), "the boundary survived"); + assert!( + snapshot + .places + .iter() + .any(|place| place.label == "The Roadside Shed") + ); + + // The wire agrees with the checkpoint: the second invocation carried + // the repaired prompt. + let seen = script.seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "two rounds, two invocations"); + let second_wire = serde_json::to_string(&seen[1]).unwrap(); + assert!(second_wire.contains("previous patch was refused")); + + drop(second); + drop(mailbox); + task.await.unwrap(); + } + + /// A jurisdiction with no boundary and no deficit is the terminating + /// condition, and it spends no inference. + #[tokio::test] + async fn soul_a_clean_jurisdiction_ends_the_loop_without_an_inference_call() { + let (_directory, mailbox, task, commons, _road) = elaboration_mailbox().await; + let store = Arc::new(RecordingWorkStore { + persisted: Arc::new(AtomicBool::new(false)), + work: Mutex::new(BTreeMap::new()), + }); + let script = Arc::new(ElaborationScript { + outputs: Mutex::new(Vec::new()), + seen: Mutex::new(Vec::new()), + }); + let runner = ElaborationRunner::new( + ElaborationPort::new(mailbox.clone()), + script.clone(), + Arc::new(NullEvidenceSource), + store.clone(), + models().elaborator, + ); + // The road's own subtree holds the road's boundary; a leaf with nothing + // under it and no deficit row is clean. + let outcome = runner + .step(crate::world::JurisdictionKey::Uncovered) + .await + .unwrap(); + assert_eq!( + outcome, + crate::world::elaboration::ElaborationOutcome::Clean + ); + assert!(script.seen.lock().unwrap().is_empty()); + assert!(store.work.lock().unwrap().is_empty()); + let _ = commons; + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The store refuses the version immediately before it, not merely some + /// older one: `v7` is the bump this pass made and `v6` is what a store + /// written before it holds. + #[test] + fn soul_a_controller_work_row_from_v6_is_refused_at_open() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("controller-work.cc"); + let command_id = CommandId::new(); + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let work = operational_in_flight( + command_id, + &opportunity, + "Hold the bridge.", + "operational-model", + vec![], + ); + { + let mut store = OwnedRedbMessagePackBackingStore::new(&path).unwrap(); + store + .push(&CultCacheEnvelope { + key: store_key(command_id).unwrap(), + r#type: "controller_work.v6".into(), + payload: rmp_serde::to_vec_named(&work).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.controller_work.v6".into()), + }) + .unwrap(); + } + let Err(error) = CultCacheControllerWorkStore::open(&path) else { + panic!("a v6 row was accepted by the v7 store"); + }; + assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); + } + + /// The custody discriminator names the lane, and `Uncertain` round-trips + /// through the probe with the authoring lane's own name rather than a + /// subject's control mode. + #[test] + fn soul_controller_work_custody_names_the_authoring_lane() { + let command_id = CommandId::new(); + let uncertain = ControllerWorkCustody::Uncertain { + command_id, + lane: WorkLane::Elaboration, + }; + assert_eq!( + uncertain, + ControllerWorkCustody::Uncertain { + command_id, + lane: WorkLane::Elaboration, + } + ); + assert_ne!( + uncertain, + ControllerWorkCustody::Uncertain { + command_id, + lane: WorkLane::Operational, + } + ); + assert_ne!( + ControllerWorkCustody::Owned { + narrative_commands: 0, + operational_commands: 0, + elaboration_commands: 1, + }, + ControllerWorkCustody::Owned { + narrative_commands: 0, + operational_commands: 1, + elaboration_commands: 0, + } + ); + } } diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs index 0f31203..277f34c 100644 --- a/crates/ghostlight-dungeon/src/world/elaboration.rs +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -1205,4 +1205,95 @@ mod tests { assert_eq!(first, session_command_id(&session("sha256:one")).unwrap()); assert_ne!(first, session_command_id(&session("sha256:two")).unwrap()); } + + // ---- Soul -------------------------------------------------------- + + /// The identity's preimage is (world, jurisdiction, answer digest) and all + /// three separate. The ancestry is deliberately not in it for the boundary + /// lane: a boundary that survives a repair keeps its id, which is what + /// makes the resume idempotent rather than orphaning a store row. + #[test] + fn soul_a_session_identity_separates_world_jurisdiction_and_answer() { + let root = EntityId(Uuid::from_u128(1)); + let sibling = EntityId(Uuid::from_u128(2)); + let session = + |world: WorldId, jurisdiction: JurisdictionKey, digest: &str, ancestry: &str| { + ElaboratorSession { + world_id: world, + jurisdiction, + answer: PatchAnswer::Deficit(jurisdiction), + answer_digest: BoundaryDigest::from_digest(digest.to_owned()), + ancestry: ancestry.to_owned(), + } + }; + let base = session( + WorldId::nil_for_test(), + JurisdictionKey::PlaceSubtree(root), + "sha256:one", + "sha256:ancestry", + ); + let id = |value: &ElaboratorSession| session_command_id(value).unwrap(); + + assert_ne!( + id(&base), + id(&session( + WorldId::nil_for_test(), + JurisdictionKey::PlaceSubtree(sibling), + "sha256:one", + "sha256:ancestry", + )), + "two jurisdictions on one world share an identity" + ); + assert_eq!( + id(&base), + id(&session( + WorldId::nil_for_test(), + JurisdictionKey::PlaceSubtree(root), + "sha256:one", + "sha256:later", + )), + "the boundary lane's identity moved when only the ancestry did" + ); + } + + /// The pass ungates `EvidenceRef::new`, so the question is whether a + /// model-authored patch can now mint a canonical fact on a receipt nobody + /// retrieved. It cannot: the citation is carried into `patch.evidence` by + /// the evaluator and then dropped by `filter_evidence`, and the resolver + /// refuses a canonical fact whose reference the patch does not list. + #[test] + fn soul_a_canonical_fact_cannot_be_minted_on_an_unretrieved_receipt() { + let completed = vec![output(vec![ + ( + "declare_fact", + serde_json::json!({ + "handle": "flood", + "label": "The Flooded Hinge", + "statement": "The lower hinge flooded.", + "standing": {"standing": "canonical", "evidence": "vault:forged"}, + }), + ), + (SUBMIT_PATCH_TOOL, serde_json::json!({})), + ])]; + let capture = capture(&completed); + assert_eq!( + capture.draft.evidence, + vec![EvidenceRef::new("vault:forged")], + "the citation is carried, so the runner is the one that must drop it" + ); + + // Nothing was retrieved this round, which is what `NullEvidenceSource` + // supplies in production today. + let filtered = filter_evidence(capture.draft, &BTreeSet::new()); + assert!(filtered.evidence.is_empty()); + // The declaration survives with its reference intact, which is exactly + // the shape `Mismatch::FactWithoutEvidence` refuses. + assert_eq!(filtered.declarations.len(), 1); + assert!(matches!( + &filtered.declarations[0], + Declaration::Fact(fact) + if matches!(&fact.standing, FactStandingRef::Canonical { evidence } + if evidence == &EvidenceRef::new("vault:forged")) + )); + } } diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index 715c0a0..4accea8 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -2477,4 +2477,150 @@ mod custody_tests { rows.push(envelope(STATE_ROW, STATE_SCHEMA, forged.world_id.key(), &forged).unwrap()); assert!(matches!(recover(rows, None), Err(JournalError::Corrupt(_)))); } + + /// Replay re-decides authority, so a stored row is not believed about who + /// authored it. An honest elaborator commit is rewritten to claim a + /// jurisdiction that does not cover its answer, and the history it belongs + /// to stops recovering. + #[test] + fn soul_a_forged_elaborator_commit_row_fails_replay() { + use crate::world::tests::{activate, submit_owner}; + use crate::world::{ + AuthenticatedCaller, CausalBoundary, Declaration, DraftHandle, EntityDeclaration, + JurisdictionKey, PatchAnswer, RouteDeclaration, SystemCapability, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Forged Authorship"), + &auth_principal(owner()), + ) + .unwrap(); + let seed = kernel.snapshot().unwrap(); + let commons = seed.places[0].id; + submit_owner( + &mut kernel, + &seed, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("road"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(commons)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("lane"), + label: "The Long Lane".into(), + from: Ref::Existing(commons), + to: Ref::Draft(DraftHandle::new("road")), + access: crate::world::AccessKind::Public, + cost: crate::world::Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + activate(&mut kernel); + + let boundary = crate::world::derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the road is a dead end"); + let CausalBoundary::UnelaboratedDestination { place: road, .. } = boundary else { + unreachable!("the boundary was matched above") + }; + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(road), + }); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(boundary)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(road)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the honest elaboration commits"); + + let state_row = || { + envelope( + STATE_ROW, + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap() + }; + let rows_of = |commits: Vec| { + let mut rows: Vec = commits + .iter() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + rows.push(state_row()); + rows + }; + + let honest: Vec = + kernel.journal.commits.values().cloned().collect(); + recover(rows_of(honest.clone()), None).expect("the honest history replays"); + + // Rewrite only the recorded caller, to a jurisdiction that does not + // cover the answer the same row carries. + let mut forged_one = false; + let forged: Vec = honest + .into_iter() + .map(|mut commit| { + if let crate::world::CommittedCommand::WorldCommand(command) = &mut commit.command + && matches!( + command.caller, + CallerId::System(SystemCapability::Elaborator { .. }) + ) + { + command.caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(commons), + }); + // Re-seal the row, so the chain digest cannot answer for + // the authority check. The elaborator commit is the last + // one, so no successor's `previous_commit_digest` moves. + commit.digest = commit_digest(&commit).unwrap(); + forged_one = true; + } + commit + }) + .collect(); + assert!(forged_one, "no elaborator row was found to forge"); + let error = recover(rows_of(forged), None).expect_err("a forged authorship replayed"); + let JournalError::Corrupt(detail) = &error else { + panic!("unexpected refusal: {error:?}"); + }; + assert!( + !detail.contains("commit chain is not contiguous"), + "the chain digest answered for the authority check: {detail}" + ); + } } diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 2c35c86..8666223 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -12833,4 +12833,348 @@ mod clock_tests { assert!(!text.contains(tag), "{tag} reached world state"); } } + + // ---- Soul: the confinement predicate past its declaration lane ------ + + /// Confinement is claimed for every referent a jurisdictional author + /// writes, not only for declarations. An operation naming a route with one + /// endpoint outside the jurisdiction is outside, and the site it reports is + /// the operation's. + #[test] + fn soul_an_operation_naming_a_half_outside_route_is_outside_the_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OperationLane"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + // The Field Gate runs hall -> dead end. The dead end's elaborator holds + // one of its two ends and therefore holds neither. + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { site: Site::Operation(0) }]), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + + // The owner is unconfined and the identical patch commits. + let snapshot = kernel.snapshot().unwrap(); + let mut owner_patch = shed_under(clockwork.dead_end, "shed"); + owner_patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: owner_patch, + }, + ); + } + + /// The fifth body the capability rule refuses. `ExerciseDecision` is the + /// one the existing negative omits, and it is the one a subject's lane uses. + #[test] + fn soul_an_elaborator_cannot_exercise_a_decision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "NoExercise"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, clockwork.reeve), + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + }, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Two boundaries under two disjoint roots, opened by one owner patch. + /// Answering one leaves the other derived with its digest unmoved, so the + /// second elaborator commits afterwards at a later revision. Answering the + /// first a second time is not derived. + #[test] + fn soul_disjoint_boundaries_commit_independently_and_a_spent_answer_is_not_derived() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Disjoint"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One unconfined patch answers the road and opens one dead end under + // each root: a cellar under the yard, an annex off the road. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Road Annex".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("spur"), + label: "The Road Spur".into(), + from: Ref::Existing(clockwork.dead_end), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + + let place_named = |kernel: &WorldKernel, label: &str| { + kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == label) + .map(|(id, _)| *id) + .expect("the declared place") + }; + let cellar = place_named(&kernel, "The Yard Cellar"); + let annex = place_named(&kernel, "The Road Annex"); + let boundary_at = |kernel: &WorldKernel, place: EntityId| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place: at, .. } if *at == place) + }) + .unwrap_or_else(|| panic!("no boundary at {place:?}")) + }; + // Both are derived at the same revision, and both are read before + // either is answered. + let cellar_answer = boundary_at(&kernel, cellar); + let annex_answer = boundary_at(&kernel, annex); + + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the hall's elaborator answers the cellar"); + let after_first = kernel.state.revision; + + // The other root's answer is untouched by that commit: same value, + // same digest, still derived. + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&annex_answer) + ); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(annex_answer)), + patch: shed_under(annex, "barrow"), + }, + ) + .expect("the road's elaborator answers the annex"); + assert!(kernel.state.revision > after_first); + + // The spent answer is a value nothing derives any more. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer)), + patch: shed_under(cellar, "second_crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The third structural bound, reached through the elaborator lane: the + /// answer must be derived, every write must be inside the jurisdiction, and + /// the answer must stop being derived after the write. + #[test] + fn soul_an_elaborator_patch_that_does_not_satisfy_its_answer_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unsatisfied"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One owner patch answers the road and opens a cellar dead end inside + // the hall, so the hall's elaborator has an answer it covers and a + // legal write that does not satisfy it. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let cellar_answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } if *place == cellar) + }) + .expect("the cellar is a dead end"); + let revision = kernel.state.revision; + + // Inside the hall, so confinement passes; nowhere near the cellar, so + // the answered boundary is still derived after the write. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::AnswerNotSatisfied), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer), + "a refused patch left the boundary derived" + ); + + // The same author satisfying the same answer commits. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the satisfying patch commits"); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer) + ); + } + + /// Pass 6's rule survives the ungating of `EvidenceRef::new`: a canonical + /// fact still needs its receipt listed on the patch that declares it, and an + /// elaborator gets the same refusal the owner does. + #[test] + fn soul_an_elaborator_cannot_mint_a_canonical_fact_without_a_listed_receipt() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Provenance"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "The Flooded Hinge".into(), + statement: Statement::new("The lower hinge flooded.").expect("a canonical statement"), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:forged"), + }, + })); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("flood"), + })), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + } } diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 479cd09..27431ea 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -6519,6 +6519,236 @@ mod catalog_tests { "the elaborator has no source prose and no byte span" ); } + + // ---- Soul: the emitter against the decoder ------------------------- + // + // `patch_tool_arguments_round_trip_into_the_vocabulary` proves that a + // hand-written *example* decodes. It never checks that example against the + // *emitted schema*, so `composite_example` is a third spelling of the same + // vocabulary beside `composite_schema` and serde. The tests below close the + // direction that matters for a model: an instance built from the emitted + // schema must decode, for every branch of every sum the schema offers. + + const ANY_STRING: &str = "00000000-0000-0000-0000-000000000000"; + + /// One instance of `schema`, taking `branch` at the top-level `oneOf` and + /// the first alternative everywhere below it. Nothing here reads the const + /// list: the schema is the only input, which is what makes the decode a + /// statement about the schema. + fn instance_of(schema: &Value, branch: usize) -> Value { + if let Some(alternatives) = schema.get("oneOf").and_then(Value::as_array) { + let index = branch.min(alternatives.len().saturating_sub(1)); + return instance_of(&alternatives[index], 0); + } + if let Some(constant) = schema.get("const") { + return constant.clone(); + } + if let Some(values) = schema.get("enum").and_then(Value::as_array) { + return values.first().cloned().unwrap_or(Value::Null); + } + match schema.get("type").and_then(Value::as_str) { + Some("object") => Value::Object( + schema + .get("properties") + .and_then(Value::as_object) + .map(|properties| { + properties + .iter() + .map(|(name, property)| (name.clone(), instance_of(property, 0))) + .collect() + }) + .unwrap_or_default(), + ), + Some("array") => Value::Array(vec![instance_of( + schema.get("items").unwrap_or(&Value::Null), + 0, + )]), + Some("integer") => schema.get("minimum").cloned().unwrap_or_else(|| json!(1)), + Some("boolean") => json!(false), + Some("string") => json!(ANY_STRING), + _ => Value::Null, + } + } + + fn branch_count(schema: &Value) -> usize { + schema + .get("oneOf") + .and_then(Value::as_array) + .map_or(1, Vec::len) + } + + /// A structural reader of exactly the shapes `tool_schema` emits: `oneOf`, + /// `const`, `enum`, closed objects with every property required, arrays, + /// bounded integers, strings, booleans, null. + fn admits(schema: &Value, value: &Value) -> bool { + if let Some(alternatives) = schema.get("oneOf").and_then(Value::as_array) { + return alternatives + .iter() + .any(|alternative| admits(alternative, value)); + } + if let Some(constant) = schema.get("const") { + return constant == value; + } + if let Some(values) = schema.get("enum").and_then(Value::as_array) { + return values.contains(value); + } + match schema.get("type").and_then(Value::as_str) { + Some("object") => { + let Some(fields) = value.as_object() else { + return false; + }; + let empty = serde_json::Map::new(); + let properties = schema + .get("properties") + .and_then(Value::as_object) + .unwrap_or(&empty); + if schema.get("additionalProperties") == Some(&json!(false)) + && fields.keys().any(|name| !properties.contains_key(name)) + { + return false; + } + if let Some(required) = schema.get("required").and_then(Value::as_array) + && required + .iter() + .any(|name| name.as_str().is_none_or(|name| !fields.contains_key(name))) + { + return false; + } + properties.iter().all(|(name, property)| { + fields.get(name).is_none_or(|field| admits(property, field)) + }) + } + Some("array") => value.as_array().is_some_and(|items| { + let inner = schema.get("items").unwrap_or(&Value::Null); + items.iter().all(|item| admits(inner, item)) + }), + Some("integer") => value.as_u64().is_some_and(|number| { + schema + .get("minimum") + .and_then(Value::as_u64) + .is_none_or(|minimum| number >= minimum) + && schema + .get("maximum") + .and_then(Value::as_u64) + .is_none_or(|maximum| number <= maximum) + }), + Some("boolean") => value.is_boolean(), + Some("string") => value.is_string(), + Some("null") => value.is_null(), + _ => true, + } + } + + fn emitted_schema(name: &str) -> Value { + let definition = patch_tools() + .into_iter() + .find(|definition| definition.name == name) + .unwrap_or_else(|| panic!("{name} is not emitted")); + serde_json::from_str(&definition.parameters_json).expect("an emitted schema is JSON") + } + + fn decodes( + entry: &PatchTool, + mut arguments: serde_json::Map, + ) -> Result<(), String> { + match entry.shape { + PatchToolShape::Declare { variant, fixed } => { + arguments.insert("type".into(), Value::String(variant.into())); + for (key, value) in fixed { + arguments.insert((*key).into(), Value::String((*value).into())); + } + serde_json::from_value::(Value::Object(arguments)) + .map(|_| ()) + .map_err(|error| error.to_string()) + } + PatchToolShape::Operate { variant } => { + arguments.insert("op".into(), Value::String(variant.into())); + serde_json::from_value::(Value::Object(arguments)) + .map(|_| ()) + .map_err(|error| error.to_string()) + } + PatchToolShape::Session => Ok(()), + } + } + + /// The direction a model actually travels: it reads the emitted schema and + /// writes an instance of it. Every branch the schema offers, in every + /// argument of every tool, must decode into the vocabulary — otherwise the + /// catalog advertises a shape the reducer cannot read and the model + /// discovers it through a gap. + #[test] + fn soul_every_branch_the_emitted_schema_offers_decodes_into_the_vocabulary() { + for entry in PATCH_TOOLS { + let schema = emitted_schema(entry.name); + let empty = serde_json::Map::new(); + let properties = schema + .get("properties") + .and_then(Value::as_object) + .unwrap_or(&empty) + .clone(); + let widest = properties.values().map(branch_count).max().unwrap_or(1); + for branch in 0..widest { + let arguments: serde_json::Map = properties + .iter() + .map(|(name, property)| (name.clone(), instance_of(property, branch))) + .collect(); + let rendered = Value::Object(arguments.clone()); + assert!( + admits(&schema, &rendered), + "{}: the instance built from its own schema does not satisfy it: {rendered}", + entry.name + ); + if let Err(error) = decodes(entry, arguments) { + panic!( + "{} branch {branch}: the emitted schema offers a shape the decoder refuses ({error}): {rendered}", + entry.name + ); + } + } + } + } + + /// The round-trip test's examples are a third spelling, not a projection of + /// the schema. This pins the exact place where the two disagree today, so a + /// fix removes an entry here and a new drift adds one. + #[test] + fn soul_the_round_trip_examples_are_a_second_spelling_of_the_emitted_schema() { + let mut disagree: Vec<&str> = Vec::new(); + for entry in PATCH_TOOLS { + for field in entry.fields { + if !admits(&field_schema(field.kind), &field_example(field.kind)) { + disagree.push(field.name); + } + } + } + disagree.sort_unstable(); + disagree.dedup(); + assert_eq!( + disagree, + vec!["effect_slots"], + "the example/schema disagreement set moved" + ); + } + + /// `Bounds::None` is a live variant of the vocabulary — an effect slot with + /// no ceiling — and `variant_content` cannot spell a unit variant, so the + /// emitted schema offers only `quantity` and `cost`. A world author using + /// the catalog cannot declare an unbounded effect slot. + #[test] + fn soul_the_catalog_cannot_express_an_unbounded_effect_slot() { + let unbounded = serde_json::to_value(Bounds::None).expect("bounds encode"); + assert_eq!(unbounded, json!({"bound": "none"})); + let slot = field_schema(PatchFieldKind::CompositeList(CompositeShape::EffectSlot)); + let bounds = slot["items"]["properties"]["bounds"].clone(); + assert!( + admits(&bounds, &json!({"bound": "quantity", "max": 1})), + "the bounded spelling is offered" + ); + assert!( + !admits(&bounds, &unbounded), + "the unbounded spelling is now offered; delete this test" + ); + } } #[cfg(test)]