diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 78c7978..9c2fbc3 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -255,6 +255,7 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( }; tokio::spawn(maintain_mesh_projection(state.clone())); tokio::spawn(advance_world_clock(state.clone())); + tokio::spawn(elaborate_world(state.clone())); let app = app_router(state.clone(), web_root); tracing::info!(address = %bound_address, "Ghostlight Dungeon world owner serving"); let server = axum::serve( @@ -308,6 +309,8 @@ fn open_controller( .unwrap_or_else(|_| "gpt-5.6-terra".into()), operational_agent: std::env::var("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL") .unwrap_or_else(|_| "gpt-5.6-terra".into()), + elaborator: std::env::var("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL") + .unwrap_or_else(|_| "gpt-5.6-terra".into()), }, ) .map_err(Into::into) @@ -1462,6 +1465,34 @@ where } } +/// How often the authoring lane takes one sweep. Slow, and skipping: a sweep +/// that admits nothing is a fixed point, not a reason to spin against a paid +/// inference endpoint. +const ELABORATION_SWEEP_INTERVAL: Duration = Duration::from_secs(300); + +/// The authoring lane's only driver. It runs when the cognition organ opened at +/// all, which is the config gate the runtime already has: no mode flag joins it. +/// One sequential sweep per wake, because a boundary binds to its own digest and +/// the loops are logically independent without being separate tasks. +async fn elaborate_world(state: AppState) { + let mut interval = tokio::time::interval(ELABORATION_SWEEP_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + interval.tick().await; + loop { + interval.tick().await; + let runner = { + let controllers = state.controllers.lock().await; + controllers.as_ref().map(ControllerRunner::elaborator) + }; + let Some(runner) = runner else { + continue; + }; + if let Err(error) = runner.sweep().await { + tracing::debug!(%error, "elaboration sweep did not complete"); + } + } +} + /// The world clock's only driver. async fn advance_world_clock(state: AppState) { let Some(minutes) = TickMinutes::new(CLOCK_TICK_MINUTES) else { @@ -1936,6 +1967,7 @@ mod tests { persona: "gpt-5.6-sol".into(), interpreter: "gpt-5.6-terra".into(), operational_agent: "gpt-5.6-terra".into(), + elaborator: "gpt-5.6-terra".into(), }, ) .unwrap(); diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 54c3eaf..776906c 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -6,10 +6,14 @@ //! tools never carry caller, controller, world, opportunity, revision, or //! affordance fields. +use super::elaboration::{ + ElaborationCheckpoint, ElaborationRunner, NullEvidenceSource, valid_elaboration_progression, +}; +use super::tool_schema; use crate::world::{ AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, Confidence, ControllerMode, ControllerPort, Cost, DecisionInvocation, DecisionOpportunity, - DependencyTarget, EdgeId, EntityId, EntityKind, FactStandingView, KernelError, + DependencyTarget, EdgeId, ElaborationPort, EntityId, EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, RoleBinding, Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, WorldMailbox, WorldSnapshot, @@ -47,8 +51,8 @@ const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; const REQUEST_EXPIRY: Duration = Duration::from_secs(300); const TOOL_STEP_BUDGET: usize = 4; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v6"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v6"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v7"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v7"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -59,7 +63,7 @@ const INTERPRETER_SPEAK_TOOL: &str = "speak"; /// kernel carries the name and branches on it nowhere; matching on it here is a /// consumer reading data, which is where genre belongs. const SPEAK_KIND: &str = "speak"; -const RECORD_GAP_TOOL: &str = "record_gap"; +const INTERPRETER_RECORD_GAP_TOOL: &str = "record_gap"; const RECORD_NEED_TOOL: &str = "record_need"; const FINISH_INTERPRETATION_TOOL: &str = "finish_interpretation"; const FINISH_WITHOUT_PROPOSAL_TOOL: &str = "finish_without_proposal"; @@ -72,12 +76,13 @@ pub(crate) enum InferencePurpose { Persona, Interpreter, OperationalAgent, + Elaboration, } /// One exact provider request. Keeping the native request visible at this seam /// makes the prose-only Persona boundary structurally inspectable. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct InferenceRequest { +pub(super) struct InferenceRequest { purpose: InferencePurpose, provider: CodexProviderRequest, } @@ -86,13 +91,13 @@ struct InferenceRequest { /// Replaying this value may recover a completed connector response; rebuilding /// it under the same request ID would be a replay conflict. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct PreparedInference { +pub(super) struct PreparedInference { purpose: InferencePurpose, - invocation: CodexTransportInvocation, + pub(super) invocation: CodexTransportInvocation, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -enum InferenceEvent { +pub(super) enum InferenceEvent { Text(String), ToolCall { call_id: String, @@ -102,9 +107,9 @@ enum InferenceEvent { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct InferenceOutput { - events: Vec, - receipt_digest: String, +pub(super) struct InferenceOutput { + pub(super) events: Vec, + pub(super) receipt_digest: String, } impl InferenceOutput { @@ -177,7 +182,7 @@ impl InferenceFault { } #[async_trait] -trait InferencePort: Send + Sync { +pub(super) trait InferencePort: Send + Sync { fn prepare(&self, request: InferenceRequest) -> Result; async fn infer(&self, request: PreparedInference) -> Result; @@ -355,9 +360,22 @@ fn unix_ms() -> Result { /// never separately persisted. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "mode", content = "checkpoint", rename_all = "snake_case")] -enum ControllerWork { +pub(super) enum ControllerWork { Narrative(NarrativeCheckpoint), Operational(OperationalCheckpoint), + /// The authoring lane. One store, one custody probe, one progression check: + /// forking them would buy nothing and split one authority in three. + Elaboration(ElaborationCheckpoint), +} + +/// Which lane a stored checkpoint belongs to. Distinct from `ControllerMode`, +/// which says how a *subject* is controlled: the elaborator is not a subject +/// and has no mode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WorkLane { + Narrative, + Operational, + Elaboration, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -436,17 +454,19 @@ enum OperationalCheckpoint { } impl ControllerWork { - fn command_id(&self) -> CommandId { + pub(super) fn command_id(&self) -> CommandId { match self { Self::Narrative(checkpoint) => checkpoint.command_id(), Self::Operational(checkpoint) => checkpoint.command_id(), + Self::Elaboration(checkpoint) => checkpoint.command_id(), } } - fn mode(&self) -> ControllerMode { + fn lane(&self) -> WorkLane { match self { - Self::Narrative(_) => ControllerMode::NarrativePersona, - Self::Operational(_) => ControllerMode::OperationalAgent, + Self::Narrative(_) => WorkLane::Narrative, + Self::Operational(_) => WorkLane::Operational, + Self::Elaboration(_) => WorkLane::Elaboration, } } @@ -456,6 +476,11 @@ impl ControllerWork { Self::Operational(OperationalCheckpoint::AgentInFlight { completed, .. }) => { completed.is_empty() } + Self::Elaboration(ElaborationCheckpoint::ElaboratorInFlight { + completed, + last_mismatches, + .. + }) => completed.is_empty() && last_mismatches.is_empty(), _ => false, } } @@ -464,6 +489,7 @@ impl ControllerWork { match self { Self::Narrative(checkpoint) => checkpoint.integrity_is_valid(), Self::Operational(checkpoint) => checkpoint.integrity_is_valid(), + Self::Elaboration(checkpoint) => checkpoint.integrity_is_valid(), } } } @@ -805,7 +831,7 @@ fn derive_operational_capture( } } -fn canonical_model(model: &str) -> bool { +pub(super) fn canonical_model(model: &str) -> bool { !model.is_empty() && model.chars().all(|character| !character.is_whitespace()) } @@ -837,7 +863,7 @@ fn exact_request_identity( .is_ok_and(|expected| provider.conversation_id == expected) } -fn prepared_matches_request( +pub(super) fn prepared_matches_request( prepared: &PreparedInference, expected: &InferenceRequest, command_id: CommandId, @@ -868,7 +894,7 @@ fn persona_request_shape_is_valid(request: &PreparedInference) -> bool { } #[derive(Clone, Debug, Error, PartialEq, Eq)] -enum ControllerWorkStoreError { +pub(super) enum ControllerWorkStoreError { #[error("Eve command ID already belongs to the other controller mode")] CommandModeConflict, #[error("{detail}")] @@ -884,13 +910,13 @@ impl ControllerWorkStoreError { } #[async_trait] -trait ControllerWorkStore: Send + Sync { +pub(super) trait ControllerWorkStore: Send + Sync { async fn lookup( &self, command_id: CommandId, ) -> Result; - /// Owns the only legal checkpoint transition for either cognition mode. + /// Owns the only legal checkpoint transition for any lane. async fn persist( &self, work: &ControllerWork, @@ -902,14 +928,14 @@ trait ControllerWorkStore: Send + Sync { } #[derive(Clone, Debug, PartialEq, Eq)] -enum ControllerWorkLookup { +pub(super) enum ControllerWorkLookup { Missing, Confirmed(ControllerWork), CustodyUncertain(ControllerWork), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ControllerWorkWrite { +pub(super) enum ControllerWorkWrite { Applied, AlreadyPresent, CustodyUncertain, @@ -920,12 +946,13 @@ pub(crate) enum ControllerWorkCustody { Owned { narrative_commands: usize, operational_commands: usize, + elaboration_commands: usize, }, /// A compare-and-swap or post-write ownership check did not confirm. The /// process must reopen the journal before doing any other controller work. Uncertain { command_id: CommandId, - mode: ControllerMode, + lane: WorkLane, }, } @@ -1060,7 +1087,7 @@ impl ControllerWorkStore for CultCacheControllerWorkStore { if existing == work { return Ok(ControllerWorkWrite::AlreadyPresent); } - if existing.mode() != work.mode() { + if existing.lane() != work.lane() { return Err(ControllerWorkStoreError::CommandModeConflict); } if !valid_controller_work_progression(existing, work) { @@ -1113,21 +1140,21 @@ impl ControllerWorkStore for CultCacheControllerWorkStore { if let Some(uncertain) = &journal.uncertain { return Ok(ControllerWorkCustody::Uncertain { command_id: uncertain.command_id(), - mode: uncertain.mode(), + lane: uncertain.lane(), }); } verify_journal_custody(&journal)?; + let count = |lane: WorkLane| { + journal + .work + .values() + .filter(|work| work.lane() == lane) + .count() + }; Ok(ControllerWorkCustody::Owned { - narrative_commands: journal - .work - .values() - .filter(|work| work.mode() == ControllerMode::NarrativePersona) - .count(), - operational_commands: journal - .work - .values() - .filter(|work| work.mode() == ControllerMode::OperationalAgent) - .count(), + narrative_commands: count(WorkLane::Narrative), + operational_commands: count(WorkLane::Operational), + elaboration_commands: count(WorkLane::Elaboration), }) } } @@ -1160,6 +1187,9 @@ fn valid_controller_work_progression(existing: &ControllerWork, next: &Controlle (ControllerWork::Operational(existing), ControllerWork::Operational(next)) => { valid_operational_progression(existing, next) } + (ControllerWork::Elaboration(existing), ControllerWork::Elaboration(next)) => { + valid_elaboration_progression(existing, next) + } _ => false, } } @@ -1425,6 +1455,10 @@ pub(crate) struct ControllerModels { pub(crate) persona: String, pub(crate) interpreter: String, pub(crate) operational_agent: String, + /// The authoring lane's model. The existing config shape already gates + /// cognition by model name, so the driver starts on this and no mode flag + /// is added. + pub(crate) elaborator: String, } impl ControllerModels { @@ -1434,6 +1468,7 @@ impl ControllerModels { &self.persona, &self.interpreter, &self.operational_agent, + &self.elaborator, ] .into_iter() .all(|model| canonical_model(model)) @@ -1677,6 +1712,10 @@ enum ControllerWorldSubmission { pub(crate) struct ControllerRunner { mailbox: ControllerPort, + /// The authoring lane's own narrowing of the same mailbox. It is opened + /// here because this constructor is where a whole `WorldMailbox` is + /// narrowed, and nowhere else in the world subtree holds one. + elaboration: ElaborationPort, inference: Arc, work: Arc, models: ControllerModels, @@ -1708,13 +1747,27 @@ impl ControllerRunner { )?; let work = CultCacheControllerWorkStore::open(controller_work_path)?; Ok(Self { - mailbox: ControllerPort::new(mailbox), + mailbox: ControllerPort::new(mailbox.clone()), + elaboration: ElaborationPort::new(mailbox), inference: Arc::new(inference), work: Arc::new(work), models, }) } + /// The authoring lane, built from the same ports the decision lanes use. + /// `NullEvidenceSource` is what production supplies until a retrieval organ + /// lands; the bound that buys is stated where the source is defined. + pub(crate) fn elaborator(&self) -> ElaborationRunner { + ElaborationRunner::new( + self.elaboration.clone(), + Arc::clone(&self.inference), + Arc::new(NullEvidenceSource), + Arc::clone(&self.work), + self.models.elaborator.clone(), + ) + } + #[cfg(test)] fn with_test_ports( mailbox: WorldMailbox, @@ -1723,7 +1776,8 @@ impl ControllerRunner { models: ControllerModels, ) -> Self { Self { - mailbox: ControllerPort::new(mailbox), + mailbox: ControllerPort::new(mailbox.clone()), + elaboration: ElaborationPort::new(mailbox), inference, work, models, @@ -1757,8 +1811,12 @@ impl ControllerRunner { ControllerPendingReason::StoreReopenRequired, )); } - ControllerWorkLookup::Confirmed(ControllerWork::Operational(_)) - | ControllerWorkLookup::CustodyUncertain(ControllerWork::Operational(_)) => { + ControllerWorkLookup::Confirmed( + ControllerWork::Operational(_) | ControllerWork::Elaboration(_), + ) + | ControllerWorkLookup::CustodyUncertain( + ControllerWork::Operational(_) | ControllerWork::Elaboration(_), + ) => { return Err(ControllerError::CommandMismatch); } ControllerWorkLookup::Missing => {} @@ -1832,8 +1890,12 @@ impl ControllerRunner { ControllerPendingReason::StoreReopenRequired, )); } - ControllerWorkLookup::Confirmed(ControllerWork::Narrative(_)) - | ControllerWorkLookup::CustodyUncertain(ControllerWork::Narrative(_)) => { + ControllerWorkLookup::Confirmed( + ControllerWork::Narrative(_) | ControllerWork::Elaboration(_), + ) + | ControllerWorkLookup::CustodyUncertain( + ControllerWork::Narrative(_) | ControllerWork::Elaboration(_), + ) => { return Err(ControllerError::CommandMismatch); } ControllerWorkLookup::Missing => {} @@ -3030,7 +3092,7 @@ fn encoded_id(id: &T) -> Result { .ok_or_else(|| ControllerError::Serialization("opaque ID was not a string".into())) } -fn tool_decode_need(name: &str, arguments: &str, detail: &str) -> ControllerNeed { +pub(super) fn tool_decode_need(name: &str, arguments: &str, detail: &str) -> ControllerNeed { ControllerNeed { detail: format!( "tool `{name}` arguments were not usable ({detail}); raw_argument_digest={}", @@ -3121,7 +3183,7 @@ fn evaluate_interpreter_loop( ), } } - RECORD_GAP_TOOL => { + INTERPRETER_RECORD_GAP_TOOL => { match serde_json::from_str::(arguments) { Ok(call) => format!("{:?}", accumulator.record_gap(call)), Err(error) => format!( @@ -3471,7 +3533,7 @@ fn operational_request( ) } -fn tool_request( +pub(super) fn tool_request( command_id: CommandId, round: usize, purpose: InferencePurpose, @@ -3493,44 +3555,66 @@ fn tool_request( provider.parallel_tool_calls = false; provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(1_200); + // A patch turn emits many tool calls where a decision turn emits one, so + // the budget is per purpose rather than one constant shared by both + // catalogs. + provider.max_output_tokens = Some(match purpose { + InferencePurpose::Elaboration => 4_000, + _ => 1_200, + }); Ok(InferenceRequest { purpose, provider }) } fn interpreter_tools() -> Vec { vec![ - tool( + tool_schema::tool( INTERPRETER_SPEAK_TOOL, "Capture one exact spoken utterance by byte span in the preserved Persona prose; the harness derives the utterance verbatim.", - json!({ - "type":"object", - "additionalProperties":false, - "properties":{ - "source_start_byte":{"type":"integer","minimum":0}, - "source_end_byte":{"type":"integer","minimum":1} - }, - "required":["source_start_byte","source_end_byte"] - }), + tool_schema::object(vec![ + ( + "source_start_byte".into(), + tool_schema::bounded_integer(0, u64::from(u32::MAX)), + ), + ( + "source_end_byte".into(), + tool_schema::bounded_integer(1, u64::from(u32::MAX)), + ), + ]), ), - tool( - RECORD_GAP_TOOL, + tool_schema::tool( + INTERPRETER_RECORD_GAP_TOOL, "Preserve meaningful source prose that has no safe current typed translation.", - json!({ - "type":"object", - "additionalProperties":false, - "properties":{ - "kind":{"type":"string","enum":["ambiguity","missing_reference","missing_affordance","missing_primitive","unresolved"]}, - "source_start_byte":{"type":"integer","minimum":0}, - "source_end_byte":{"type":"integer","minimum":1}, - "detail":{"type":"string"} - }, - "required":["kind","source_start_byte","source_end_byte","detail"] - }), + tool_schema::object(vec![ + ( + "kind".into(), + tool_schema::name_enum(&[ + "ambiguity", + "missing_reference", + "missing_affordance", + "missing_primitive", + "unresolved", + ]), + ), + ( + "source_start_byte".into(), + tool_schema::bounded_integer(0, u64::from(u32::MAX)), + ), + ( + "source_end_byte".into(), + tool_schema::bounded_integer(1, u64::from(u32::MAX)), + ), + ( + "detail".into(), + tool_schema::canonical_string( + "what the prose says that no typed capture can carry", + ), + ), + ]), ), - tool( + tool_schema::tool( FINISH_INTERPRETATION_TOOL, "Finish the total interpretation after all supported captures and gaps are recorded.", - empty_schema(), + tool_schema::empty_schema(), ), ] } @@ -3548,59 +3632,48 @@ fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { let mut tools: Vec = granted .iter() .map(|entry| { - let mut properties = serde_json::Map::new(); - let mut required = Vec::new(); + let mut properties: Vec<(String, Value)> = Vec::new(); for spec in &entry.entry.roles { - properties.insert( + properties.push(( spec.role.0.clone(), - json!({"type": "string", "description": role_description(spec.kind)}), - ); - required.push(Value::String(spec.role.0.clone())); + tool_schema::canonical_string(role_description(spec.kind)), + )); } for (index, slot) in entry.entry.effect_slots.iter().enumerate() { // The ceiling is in the schema, so the model is told the bound // rather than discovering it through a rejection. let (name, ceiling) = match slot.bounds { Bounds::None => continue, - Bounds::Quantity(max) => (slot_property(index, "qty"), u64::from(max.0)), + Bounds::Quantity(max) => (slot_property(index, "qty"), max.0), Bounds::Cost(max) => (slot_property(index, "cost"), u64::from(max.0)), }; - properties.insert( - name.clone(), - json!({"type": "integer", "minimum": 1, "maximum": ceiling}), - ); - required.push(Value::String(name)); + properties.push((name, tool_schema::bounded_integer(1, ceiling))); } if entry.entry.carries_speech { - properties.insert("text".into(), json!({"type": "string"})); - required.push(Value::String("text".into())); + properties.push(( + "text".into(), + tool_schema::canonical_string("the utterance this invocation carries"), + )); } - tool( + tool_schema::tool( &entry.entry.kind.0, &format!("Invoke the {} affordance.", entry.entry.kind.0), - json!({ - "type": "object", - "additionalProperties": false, - "required": required, - "properties": Value::Object(properties), - }), + tool_schema::object(properties), ) }) .collect(); - tools.push(tool( + tools.push(tool_schema::tool( RECORD_NEED_TOOL, "Record information or capability the agent would need but does not currently have.", - json!({ - "type":"object", - "additionalProperties":false, - "properties":{"detail":{"type":"string"}}, - "required":["detail"] - }), + tool_schema::object(vec![( + "detail".into(), + tool_schema::canonical_string("what the agent would need and does not have"), + )]), )); - tools.push(tool( + tools.push(tool_schema::tool( FINISH_WITHOUT_PROPOSAL_TOOL, "Finish this opportunity without proposing an action.", - empty_schema(), + tool_schema::empty_schema(), )); tools } @@ -3748,20 +3821,7 @@ fn decode_catalog_call( }) } -fn empty_schema() -> Value { - json!({"type":"object","additionalProperties":false,"properties":{}}) -} - -fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition { - CodexToolDefinition { - name: name.into(), - description: description.into(), - parameters_json: serde_json::to_string(&schema) - .expect("static controller tool schemas must serialize"), - } -} - -fn provider_request_id( +pub(super) fn provider_request_id( command_id: CommandId, purpose: InferencePurpose, round: usize, @@ -3791,6 +3851,7 @@ fn purpose_name(purpose: InferencePurpose) -> &'static str { InferencePurpose::Persona => "persona", InferencePurpose::Interpreter => "interpreter", InferencePurpose::OperationalAgent => "operational", + InferencePurpose::Elaboration => "elaboration", } } @@ -3925,7 +3986,7 @@ mod tests { let completed_narrative = vec![InferenceOutput { events: vec![InferenceEvent::ToolCall { call_id: "gap".into(), - name: RECORD_GAP_TOOL.into(), + name: INTERPRETER_RECORD_GAP_TOOL.into(), arguments: json!({ "kind":"unresolved", "source_start_byte":0, @@ -4831,7 +4892,7 @@ mod tests { if existing == work { return Ok(ControllerWorkWrite::AlreadyPresent); } - if existing.mode() != work.mode() { + if existing.lane() != work.lane() { return Err(ControllerWorkStoreError::CommandModeConflict); } if !valid_controller_work_progression(existing, work) { @@ -4851,15 +4912,11 @@ mod tests { async fn custody_probe(&self) -> Result { let stored = self.work.lock().unwrap(); + let count = |lane: WorkLane| stored.values().filter(|work| work.lane() == lane).count(); Ok(ControllerWorkCustody::Owned { - narrative_commands: stored - .values() - .filter(|work| work.mode() == ControllerMode::NarrativePersona) - .count(), - operational_commands: stored - .values() - .filter(|work| work.mode() == ControllerMode::OperationalAgent) - .count(), + narrative_commands: count(WorkLane::Narrative), + operational_commands: count(WorkLane::Operational), + elaboration_commands: count(WorkLane::Elaboration), }) } } @@ -4949,6 +5006,7 @@ mod tests { persona: "persona".into(), interpreter: "interpreter".into(), operational_agent: "operator".into(), + elaborator: "elaborator".into(), } } @@ -5135,7 +5193,7 @@ mod tests { vec![ InferenceEvent::ToolCall { call_id: "gap".into(), - name: RECORD_GAP_TOOL.into(), + name: INTERPRETER_RECORD_GAP_TOOL.into(), arguments: json!({ "kind":"unresolved", "source_start_byte":0, @@ -5468,6 +5526,8 @@ mod tests { .expect("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL is required"), operational_agent: std::env::var("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL") .expect("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL is required"), + elaborator: std::env::var("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL") + .expect("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL is required"), }; let persona_log = std::env::var_os("GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG") .expect("GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG is required"); diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs new file mode 100644 index 0000000..0f31203 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -0,0 +1,1208 @@ +//! The world's authoring loop, inside the world. +//! +//! One jurisdiction's elaborator selects a derived answer, retrieves evidence +//! for the referents that answer names, drives a tool conversation over the +//! reducer's own vocabulary, accumulates a draft patch, submits it, and repairs +//! the same draft from the complete mismatch set the kernel returns. +//! +//! It owns no world truth. It holds no authority beyond the capability the +//! mailbox mints for it, it clears no boundary — boundaries are derived, and a +//! commit that makes the predicate stop holding is the only thing that ends one +//! — and it writes nothing but `AdmitPatch`. + +use super::controllers::{ + ControllerError, ControllerNeed, ControllerWork, ControllerWorkLookup, ControllerWorkStore, + ControllerWorkWrite, InferenceEvent, InferenceOutput, InferencePort, InferencePurpose, + InferenceRequest, PreparedInference, canonical_model, prepared_matches_request, + tool_decode_need, tool_request, +}; +#[cfg(test)] +use super::patch::RECORD_GAP_PATCH_TOOL; +use super::patch::{ComponentOp, FactStandingRef}; +use super::patch::{ + PATCH_TOOLS, PatchToolShape, SUBMIT_PATCH_TOOL, patch_tool_signatures, patch_tools, +}; +use super::{ + BoundaryDigest, CausalBoundary, CommandId, Declaration, ElaborationPort, EntityId, EvidenceRef, + JurisdictionKey, KernelError, MailboxError, Mismatch, PatchAnswer, SubjectId, WorldId, + WorldPatch, WorldPhase, WorldSnapshot, +}; +use async_trait::async_trait; +use codex_connector::CodexInputItem; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use thiserror::Error; +use uuid::Uuid; + +/// The elaborator wants many tool calls inside one round and several rounds for +/// repair, where the operational agent wants one terminal choice. +/// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to. +const ELABORATION_ROUND_BUDGET: usize = 6; + +/// The author owns the size of what it authors. The kernel gets no cap: +/// `resolve_patch` is total, and a cap there would be a second authority over +/// what a patch may be. +const MAX_DRAFT_DECLARATIONS: usize = 64; +const MAX_DRAFT_OPERATIONS: usize = 128; + +const ELABORATION_NAMESPACE: &str = "ghostlight.command.elaboration.v1"; + +const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing."; + +/// The answer a session is bound to, plus the ancestry it was built against. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ElaboratorSession { + pub(super) world_id: WorldId, + pub(super) jurisdiction: JurisdictionKey, + pub(super) answer: PatchAnswer, + /// The boundary's own digest, or for a deficit the digest of + /// `(world_id, jurisdiction, "deficit", ancestry)`. + pub(super) answer_digest: BoundaryDigest, + /// The commit digest the draft is built against. + pub(super) ancestry: String, +} + +/// The stages one authoring session moves through. The draft is **not** a +/// field: it is re-derived from `completed` by `evaluate_elaboration_loop`, +/// exactly as an operational capture is, so a resumed session cannot submit a +/// draft the conversation does not produce. `last_mismatches` is stored, +/// because it is the one input that cannot be re-derived from `completed` — it +/// came from the kernel, not the model. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "stage", rename_all = "snake_case")] +pub(super) enum ElaborationCheckpoint { + ElaboratorInFlight { + command_id: CommandId, + session: ElaboratorSession, + agent_prompt: String, + last_mismatches: Vec, + completed: Vec, + invocation: PreparedInference, + }, + ReadyToSubmit { + command_id: CommandId, + session: ElaboratorSession, + agent_prompt: String, + last_mismatches: Vec, + completed: Vec, + }, + /// The round budget ran out, or the model finished without a submit. The + /// boundary stays derived and visible; nothing is repaired by waiting. + NoPatch { + command_id: CommandId, + session: ElaboratorSession, + agent_prompt: String, + completed: Vec, + gaps: Vec, + }, +} + +impl ElaborationCheckpoint { + pub(super) fn command_id(&self) -> CommandId { + match self { + Self::ElaboratorInFlight { command_id, .. } + | Self::ReadyToSubmit { command_id, .. } + | Self::NoPatch { command_id, .. } => *command_id, + } + } + + fn session(&self) -> &ElaboratorSession { + match self { + Self::ElaboratorInFlight { session, .. } + | Self::ReadyToSubmit { session, .. } + | Self::NoPatch { session, .. } => session, + } + } + + pub(super) fn integrity_is_valid(&self) -> bool { + match self { + Self::ElaboratorInFlight { + command_id, + agent_prompt, + last_mismatches, + completed, + invocation, + .. + } => { + !agent_prompt.is_empty() + && canonical_model(&invocation.invocation.request.model) + && match evaluate_elaboration_loop(agent_prompt, last_mismatches, completed) { + Ok(ElaborationLoopEvaluation::Continue { conversation }) => { + elaboration_request( + *command_id, + completed.len(), + &invocation.invocation.request.model, + conversation, + ) + .is_ok_and(|expected| { + prepared_matches_request( + invocation, + &expected, + *command_id, + completed.len(), + ) + }) + } + Ok(ElaborationLoopEvaluation::Complete { .. }) | Err(_) => false, + } + } + Self::ReadyToSubmit { + agent_prompt, + last_mismatches, + completed, + .. + } => derive_elaboration_capture(agent_prompt, last_mismatches, completed) + .is_ok_and(|capture| capture.submitted), + Self::NoPatch { + agent_prompt, + completed, + .. + } => derive_elaboration_capture(agent_prompt, &[], completed) + .is_ok_and(|capture| !capture.submitted), + } + } +} + +/// A session may gather more evidence and may end, but it may never rewrite the +/// answer it bound to. +pub(super) fn valid_elaboration_progression( + existing: &ElaborationCheckpoint, + next: &ElaborationCheckpoint, +) -> bool { + if existing.command_id() != next.command_id() || existing.session() != next.session() { + return false; + } + match (existing, next) { + ( + ElaborationCheckpoint::ElaboratorInFlight { + completed: existing, + .. + }, + ElaborationCheckpoint::ElaboratorInFlight { + completed: next, .. + } + | ElaborationCheckpoint::ReadyToSubmit { + completed: next, .. + } + | ElaborationCheckpoint::NoPatch { + completed: next, .. + }, + ) => next.len() >= existing.len() && next.starts_with(existing), + // A rejection reopens the same command id for repair. A rejected + // command mutates nothing, so the round evidence starts over. + ( + ElaborationCheckpoint::ReadyToSubmit { .. }, + ElaborationCheckpoint::ElaboratorInFlight { + last_mismatches, .. + }, + ) => !last_mismatches.is_empty(), + _ => false, + } +} + +#[derive(Clone, Debug, Error, PartialEq, Eq)] +#[error("{detail}")] +pub(super) struct EvidenceError { + detail: String, +} + +/// The referents the answer names, as world labels. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct EvidenceQuery { + pub(super) referents: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct EvidenceReceipt { + /// The exact reference an admitted patch may carry. + pub(super) reference: EvidenceRef, + /// What the elaborator is allowed to read. Prompt material, never state. + pub(super) excerpt: String, + pub(super) source: String, +} + +/// The Vault seam. Provenance has an owner and it is the runner: a citation +/// outside the round's retrieved set never reaches the kernel. The reducer does +/// not and must not check that a Vault receipt exists; it checks that the +/// string is canonical and that an `Admit`'s reference is listed in the same +/// patch. +#[async_trait] +pub(super) trait EvidenceSource: Send + Sync { + async fn retrieve(&self, query: &EvidenceQuery) -> Result, EvidenceError>; +} + +/// What `runtime.rs` supplies until a retrieval organ lands. The bound is real +/// and stated rather than hidden: with no receipts an elaborator can declare +/// structure and operate on it, but cannot mint quantity, because `admit` +/// requires a listed reference and there are none. Creation of quantity without +/// provenance should be impossible, not merely discouraged. +pub(super) struct NullEvidenceSource; + +#[async_trait] +impl EvidenceSource for NullEvidenceSource { + async fn retrieve( + &self, + _query: &EvidenceQuery, + ) -> Result, EvidenceError> { + Ok(Vec::new()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ElaborationCapture { + pub(super) draft: WorldPatch, + pub(super) gaps: Vec, + pub(super) inference_receipts: Vec, + pub(super) submitted: bool, +} + +pub(super) enum ElaborationLoopEvaluation { + Continue { conversation: Vec }, + Complete { capture: ElaborationCapture }, +} + +/// What one `step` did, for the driver. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ElaborationOutcome { + /// No boundary and no deficit in this jurisdiction: the terminating + /// condition. + Clean, + /// The world is not Active, so there is nothing to elaborate: seed + /// admission is the owner's lane. + Inactive, + Committed, + /// The kernel returned a complete mismatch set; the next round repairs it. + Rejected, + /// The world moved under the session. Re-select; this is not a retry loop. + Superseded, + /// The round budget was spent without a submit. The boundary stays derived. + NoPatch, +} + +/// One jurisdiction's authoring loop. Holds no state between steps; every field +/// is a port or an identity. +pub(crate) struct ElaborationRunner { + mailbox: ElaborationPort, + inference: Arc, + evidence: Arc, + work: Arc, + model: String, +} + +impl ElaborationRunner { + pub(super) fn new( + mailbox: ElaborationPort, + inference: Arc, + evidence: Arc, + work: Arc, + model: String, + ) -> Self { + Self { + mailbox, + inference, + evidence, + work, + model, + } + } + + /// One answer, start to finish. Session identity is derived, so resumption + /// needs no registry: a boundary that survives a repair keeps its digest and + /// therefore its command id, and a boundary whose digest moved is a + /// different answer with a different id. + pub(super) async fn step( + &self, + jurisdiction: JurisdictionKey, + ) -> Result { + let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?; + if snapshot.phase != WorldPhase::Active { + return Ok(ElaborationOutcome::Inactive); + } + let Some(session) = select_answer(&snapshot, jurisdiction)? else { + return Ok(ElaborationOutcome::Clean); + }; + let command_id = session_command_id(&session)?; + + let receipts = self + .evidence + .retrieve(&EvidenceQuery { + referents: answer_referents(&snapshot, &session.answer), + }) + .await + .map_err(|error| ControllerError::WorkPersistence(error.to_string()))?; + let allowed: BTreeSet = receipts + .iter() + .map(|receipt| receipt.reference.clone()) + .collect(); + + let existing = match self.work.lookup(command_id).await? { + ControllerWorkLookup::Missing => None, + ControllerWorkLookup::Confirmed(ControllerWork::Elaboration(checkpoint)) + | ControllerWorkLookup::CustodyUncertain(ControllerWork::Elaboration(checkpoint)) => { + if checkpoint.session() != &session { + return Ok(ElaborationOutcome::Superseded); + } + Some(checkpoint) + } + ControllerWorkLookup::Confirmed(_) | ControllerWorkLookup::CustodyUncertain(_) => { + return Err(ControllerError::CommandMismatch); + } + }; + + let (agent_prompt, mut last_mismatches, mut completed) = match existing { + Some(ElaborationCheckpoint::NoPatch { .. }) => return Ok(ElaborationOutcome::NoPatch), + Some( + ElaborationCheckpoint::ElaboratorInFlight { + agent_prompt, + last_mismatches, + completed, + .. + } + | ElaborationCheckpoint::ReadyToSubmit { + agent_prompt, + last_mismatches, + completed, + .. + }, + ) => (agent_prompt, last_mismatches, completed), + None => ( + build_prompt(&snapshot, &session, &receipts, &[]), + Vec::new(), + Vec::new(), + ), + }; + + loop { + match evaluate_elaboration_loop(&agent_prompt, &last_mismatches, &completed)? { + ElaborationLoopEvaluation::Continue { conversation } => { + let request = elaboration_request( + command_id, + completed.len(), + &self.model, + conversation, + )?; + let invocation = self.inference.prepare(request).map_err(|source| { + ControllerError::Inference { + purpose: InferencePurpose::Elaboration, + source, + } + })?; + self.persist(ElaborationCheckpoint::ElaboratorInFlight { + command_id, + session: session.clone(), + agent_prompt: agent_prompt.clone(), + last_mismatches: last_mismatches.clone(), + completed: completed.clone(), + invocation: invocation.clone(), + }) + .await?; + let output = + self.inference + .infer(invocation.clone()) + .await + .map_err(|source| ControllerError::Inference { + purpose: InferencePurpose::Elaboration, + source, + })?; + completed.push(output); + } + ElaborationLoopEvaluation::Complete { capture } => { + if !capture.submitted { + self.persist(ElaborationCheckpoint::NoPatch { + command_id, + session, + agent_prompt, + completed, + gaps: capture.gaps, + }) + .await?; + return Ok(ElaborationOutcome::NoPatch); + } + self.persist(ElaborationCheckpoint::ReadyToSubmit { + command_id, + session: session.clone(), + agent_prompt: agent_prompt.clone(), + last_mismatches: last_mismatches.clone(), + completed: completed.clone(), + }) + .await?; + let draft = filter_evidence(capture.draft, &allowed); + let submitted = self + .mailbox + .submit_elaboration( + command_id, + session.jurisdiction, + session.answer.clone(), + draft, + ) + .await; + return match submitted { + Ok(_) => Ok(ElaborationOutcome::Committed), + Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => { + // A rejected command mutates nothing, so reusing the + // id is correct and the idempotency probe never sees + // a conflicting commit. + last_mismatches = mismatches; + let repaired = + build_prompt(&snapshot, &session, &receipts, &last_mismatches); + self.persist_repair(command_id, &session, &repaired, &last_mismatches) + .await?; + Ok(ElaborationOutcome::Rejected) + } + Err(MailboxError::Kernel(KernelError::AnswerNotDerived)) => { + Ok(ElaborationOutcome::Superseded) + } + Err(error) => Err(snapshot_error(error)), + }; + } + } + } + } + + async fn persist(&self, checkpoint: ElaborationCheckpoint) -> Result<(), ControllerError> { + match self + .work + .persist(&ControllerWork::Elaboration(checkpoint)) + .await? + { + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => Ok(()), + ControllerWorkWrite::CustodyUncertain => Err(ControllerError::WorkPersistence( + "controller work custody is uncertain".into(), + )), + } + } + + /// The rejection the next round must repair, persisted against the same + /// command id and the same session. + async fn persist_repair( + &self, + command_id: CommandId, + session: &ElaboratorSession, + agent_prompt: &str, + last_mismatches: &[Mismatch], + ) -> Result<(), ControllerError> { + let conversation = match evaluate_elaboration_loop(agent_prompt, last_mismatches, &[])? { + ElaborationLoopEvaluation::Continue { conversation } => conversation, + ElaborationLoopEvaluation::Complete { .. } => { + return Err(ControllerError::Serialization( + "a repair round completed before any evidence".into(), + )); + } + }; + let request = elaboration_request(command_id, 0, &self.model, conversation)?; + let invocation = + self.inference + .prepare(request) + .map_err(|source| ControllerError::Inference { + purpose: InferencePurpose::Elaboration, + source, + })?; + self.persist(ElaborationCheckpoint::ElaboratorInFlight { + command_id, + session: session.clone(), + agent_prompt: agent_prompt.to_owned(), + last_mismatches: last_mismatches.to_vec(), + completed: Vec::new(), + invocation, + }) + .await + } + + /// One sweep over every jurisdiction the world's scale intent names, then + /// the uncovered residual. Sequential: a boundary binds to its own digest, + /// so the loops' logical independence is preserved without eight tasks + /// against one connector and a capacity-32 mailbox. + pub(crate) async fn sweep(&self) -> Result<(), ControllerError> { + let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?; + let mut jurisdictions: Vec = snapshot + .scale_deficit + .iter() + .map(|row| row.jurisdiction) + .collect(); + jurisdictions.dedup(); + if !jurisdictions.contains(&JurisdictionKey::Uncovered) { + jurisdictions.push(JurisdictionKey::Uncovered); + } + for jurisdiction in jurisdictions { + // The stop condition is "no open boundary and no deficit", plus the + // only other fixed point: a pass over this answer that admits + // nothing. Without it a boundary the model cannot answer becomes a + // hot spin against a paid endpoint. + match self.step(jurisdiction).await { + Ok(_) => {} + Err(error) if error.requires_quarantine() => return Err(error), + Err(error) => { + tracing::debug!(%error, "elaboration step did not admit a patch"); + } + } + } + Ok(()) + } +} + +fn snapshot_error(error: MailboxError) -> ControllerError { + ControllerError::Snapshot(error) +} + +/// The oldest derived boundary in this jurisdiction, else its first nonzero +/// deficit row, else nothing. `snapshot.boundaries` is already ordered by the +/// kernel's derivation, so "oldest" is "first in that order". +fn select_answer( + snapshot: &WorldSnapshot, + jurisdiction: JurisdictionKey, +) -> Result, ControllerError> { + let ancestry = snapshot.last_commit_digest.clone().unwrap_or_default(); + if let Some(boundary) = snapshot + .boundaries + .iter() + .find(|boundary| boundary_in(snapshot, jurisdiction, boundary)) + { + return Ok(Some(ElaboratorSession { + world_id: snapshot.world_id, + jurisdiction, + answer: PatchAnswer::Boundary(boundary.clone()), + answer_digest: boundary_digest(boundary), + ancestry, + })); + } + let deficit = snapshot + .scale_deficit + .iter() + .any(|row| row.jurisdiction == jurisdiction && row.deficit > 0); + if !deficit { + return Ok(None); + } + // A deficit mixes the ancestry, so each admitted commit opens a fresh + // session and the loop advances instead of resubmitting one id forever. + let digest = digest_of(&(snapshot.world_id, jurisdiction, "deficit", &ancestry))?; + Ok(Some(ElaboratorSession { + world_id: snapshot.world_id, + jurisdiction, + answer: PatchAnswer::Deficit(jurisdiction), + answer_digest: BoundaryDigest::from_digest(digest), + ancestry, + })) +} + +/// Selection reads the same covering the kernel's authority check does: a +/// boundary in a nested child is inside its parent's jurisdiction. +fn boundary_in( + snapshot: &WorldSnapshot, + jurisdiction: JurisdictionKey, + boundary: &CausalBoundary, +) -> bool { + let subject_place = |subject: SubjectId| { + snapshot + .subjects + .iter() + .find(|row| row.id == subject) + .and_then(|row| row.position) + }; + match jurisdiction { + JurisdictionKey::Uncovered => match boundary { + CausalBoundary::UnelaboratedDestination { .. } => false, + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + } => subject_place(*subject).is_none(), + }, + JurisdictionKey::PlaceSubtree(root) => match boundary { + CausalBoundary::UnelaboratedDestination { place, .. } => { + snapshot_covers_place(snapshot, root, *place) + } + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + } => subject_place(*subject) + .is_some_and(|place| snapshot_covers_place(snapshot, root, place)), + }, + } +} + +fn snapshot_covers_place(snapshot: &WorldSnapshot, root: EntityId, place: EntityId) -> bool { + let containers: BTreeMap> = snapshot + .places + .iter() + .map(|entry| (entry.id, entry.container)) + .collect(); + let mut current = Some(place); + for _ in 0..=containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = containers.get(&node).copied().flatten(), + } + } + false +} + +fn boundary_digest(boundary: &CausalBoundary) -> BoundaryDigest { + match boundary { + CausalBoundary::UnelaboratedDestination { scope, .. } + | CausalBoundary::MissingStructure { scope, .. } + | CausalBoundary::PolityInCausalRange { scope, .. } + | CausalBoundary::IndividuationRequired { scope, .. } => scope.clone(), + } +} + +/// The world labels the answer names, which is what the Vault is asked for. +fn answer_referents(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Vec { + let place_label = |id: EntityId| { + snapshot + .places + .iter() + .find(|entry| entry.id == id) + .map(|entry| entry.label.clone()) + }; + let subject_label = |id: SubjectId| { + snapshot + .subjects + .iter() + .find(|entry| entry.id == id) + .map(|entry| entry.label.clone()) + }; + match answer { + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { route, place, .. }) => { + let mut referents: Vec = place_label(*place).into_iter().collect(); + referents.extend( + snapshot + .routes + .iter() + .find(|entry| entry.id == *route) + .map(|entry| entry.label.clone()), + ); + referents + } + PatchAnswer::Boundary( + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + }, + ) => subject_label(*subject).into_iter().collect(), + PatchAnswer::Deficit(JurisdictionKey::PlaceSubtree(root)) => { + place_label(*root).into_iter().collect() + } + PatchAnswer::Deficit(JurisdictionKey::Uncovered) => Vec::new(), + } +} + +fn build_prompt( + snapshot: &WorldSnapshot, + session: &ElaboratorSession, + receipts: &[EvidenceReceipt], + last_mismatches: &[Mismatch], +) -> String { + let mut prompt = String::new(); + prompt.push_str("You are elaborating one jurisdiction of a world.\n\n"); + prompt.push_str(&format!("World: {}\n", snapshot.title)); + prompt.push_str(&format!( + "Jurisdiction: {}\n", + render_jurisdiction(snapshot, session.jurisdiction) + )); + prompt.push_str(&format!( + "Answer: {}\n\n", + render_answer(snapshot, &session.answer) + )); + if receipts.is_empty() { + prompt.push_str( + "No evidence receipts were retrieved. You may declare structure and operate on it; you cannot admit quantity without a receipt.\n\n", + ); + } else { + prompt.push_str("Evidence you may cite, exactly as written:\n"); + for receipt in receipts { + prompt.push_str(&format!( + "- {} ({}): {}\n", + receipt.reference.text(), + receipt.source, + receipt.excerpt + )); + } + prompt.push('\n'); + } + if !last_mismatches.is_empty() { + prompt.push_str("Your previous patch was refused. Repair every site:\n"); + for mismatch in last_mismatches { + prompt.push_str(&format!("- {}\n", render_mismatch(mismatch))); + } + prompt.push('\n'); + } + prompt.push_str(&format!("Tools: {}\n", patch_tool_signatures())); + prompt +} + +fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: JurisdictionKey) -> String { + match jurisdiction { + JurisdictionKey::PlaceSubtree(root) => snapshot + .places + .iter() + .find(|entry| entry.id == root) + .map_or_else( + || "an unnamed place subtree".to_owned(), + |entry| entry.label.clone(), + ), + JurisdictionKey::Uncovered => "everything no declared root covers".to_owned(), + } +} + +fn render_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String { + let referents = answer_referents(snapshot, answer).join(", "); + match answer { + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { .. }) => { + format!("a route leads to a place with nothing in it: {referents}") + } + PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => format!( + "a promise has a counterparty who can neither command nor litigate it: {referents}" + ), + PatchAnswer::Boundary(CausalBoundary::PolityInCausalRange { .. }) => { + format!("a polity stands in causal range and is not modelled: {referents}") + } + PatchAnswer::Boundary(CausalBoundary::IndividuationRequired { .. }) => { + format!("a population must be individuated: {referents}") + } + PatchAnswer::Deficit(_) => { + "this jurisdiction holds fewer qualified subjects than the world means it to".to_owned() + } + } +} + +fn render_mismatch(mismatch: &Mismatch) -> String { + serde_json::to_string(mismatch) + .unwrap_or_else(|_| "a structural check failed and could not be rendered".to_owned()) +} + +/// The same shape as the operational evaluator with three substitutions and no +/// fourth: a draft accumulates where the utterance did, many non-terminal calls +/// precede one terminal `submit`, and `record_gap` is a free detail string. +/// Serde is the only decoder; a decode failure becomes a gap, never a kernel +/// round trip. +pub(super) fn evaluate_elaboration_loop( + prompt: &str, + last_mismatches: &[Mismatch], + completed: &[InferenceOutput], +) -> Result { + // The repair set is prompt material, folded in by `build_prompt`; it is + // named here so a checkpoint that carries one cannot be re-derived without + // it. + let _ = last_mismatches; + let mut conversation = vec![CodexInputItem::UserText { + text: prompt.to_owned(), + }]; + let mut draft = WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: Vec::new(), + }; + let mut gaps: Vec = Vec::new(); + let mut receipts = Vec::new(); + let mut submitted = false; + + for (round, output) in completed.iter().enumerate() { + if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest + { + return Err(ControllerError::ProviderContract { + purpose: InferencePurpose::Elaboration, + detail: "provider output has no canonical receipt digest".into(), + }); + } + receipts.push(output.receipt_digest.clone()); + let mut called_tool = false; + 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, + } => { + called_tool = true; + conversation.push(CodexInputItem::ToolCall { + call_id: call_id.clone(), + name: name.clone(), + arguments: arguments.clone(), + }); + let result = + apply_tool_call(name, arguments, &mut draft, &mut gaps, &mut submitted); + conversation.push(CodexInputItem::ToolResult { + call_id: call_id.clone(), + output: result, + }); + } + } + } + + let is_complete = submitted || !called_tool || round + 1 == ELABORATION_ROUND_BUDGET; + if is_complete { + if round + 1 != completed.len() { + return Err(ControllerError::Serialization( + "elaboration evidence continued after total finalization".into(), + )); + } + if !submitted && called_tool && round + 1 == ELABORATION_ROUND_BUDGET { + gaps.push(ControllerNeed { + detail: "The elaboration round budget ended before a submit.".into(), + }); + } + draft.evidence.sort(); + draft.evidence.dedup(); + return Ok(ElaborationLoopEvaluation::Complete { + capture: ElaborationCapture { + draft, + gaps, + inference_receipts: receipts, + submitted, + }, + }); + } + } + + if completed.len() >= ELABORATION_ROUND_BUDGET { + return Err(ControllerError::Serialization( + "elaboration evidence exceeded its round budget".into(), + )); + } + Ok(ElaborationLoopEvaluation::Continue { conversation }) +} + +fn apply_tool_call( + name: &str, + arguments: &str, + draft: &mut WorldPatch, + gaps: &mut Vec, + submitted: &mut bool, +) -> String { + let Some(entry) = PATCH_TOOLS.iter().find(|entry| entry.name == name) else { + gaps.push(tool_decode_need( + name, + arguments, + "tool is not in the patch catalog", + )); + return "unavailable tool recorded as a gap".into(); + }; + let Ok(Value::Object(fields)) = serde_json::from_str::(arguments) else { + gaps.push(tool_decode_need( + name, + arguments, + "arguments are not a JSON object", + )); + return "arguments recorded as a gap".into(); + }; + match entry.shape { + PatchToolShape::Session if name == SUBMIT_PATCH_TOOL => { + if *submitted { + gaps.push(ControllerNeed { + detail: "The elaborator submitted twice for one answer.".into(), + }); + return "a submit is already captured".into(); + } + *submitted = true; + "patch submitted".into() + } + PatchToolShape::Session => match fields.get("detail").and_then(Value::as_str) { + Some(detail) => { + gaps.push(ControllerNeed { + detail: detail.to_owned(), + }); + "gap recorded".into() + } + None => { + gaps.push(tool_decode_need(name, arguments, "no detail was given")); + "arguments recorded as a gap".into() + } + }, + PatchToolShape::Declare { variant, fixed } => { + if draft.declarations.len() >= MAX_DRAFT_DECLARATIONS { + gaps.push(tool_decode_need( + name, + arguments, + "the draft is at its declaration cap", + )); + return "the draft is full".into(); + } + let mut value = fields; + value.insert("type".into(), Value::String(variant.into())); + for (key, fixed_value) in fixed { + value.insert((*key).into(), Value::String((*fixed_value).into())); + } + match serde_json::from_value::(Value::Object(value)) { + Ok(declaration) => { + if let Declaration::Fact(fact) = &declaration + && let FactStandingRef::Canonical { evidence } = &fact.standing + { + draft.evidence.push(evidence.clone()); + } + draft.declarations.push(declaration); + "declaration captured".into() + } + Err(error) => { + gaps.push(tool_decode_need(name, arguments, &error.to_string())); + "arguments recorded as a gap".into() + } + } + } + PatchToolShape::Operate { variant } => { + if draft.operations.len() >= MAX_DRAFT_OPERATIONS { + gaps.push(tool_decode_need( + name, + arguments, + "the draft is at its operation cap", + )); + return "the draft is full".into(); + } + let mut value = fields; + value.insert("op".into(), Value::String(variant.into())); + match serde_json::from_value::(Value::Object(value)) { + Ok(operation) => { + if let ComponentOp::Admit { evidence, .. } = &operation { + draft.evidence.push(evidence.clone()); + } + draft.operations.push(operation); + "operation captured".into() + } + Err(error) => { + gaps.push(tool_decode_need(name, arguments, &error.to_string())); + "arguments recorded as a gap".into() + } + } + } + } +} + +/// A citation outside the round's retrieved set never reaches the kernel as +/// provenance: the draft carries no such reference, so an `admit` that cited it +/// is refused on `AdmitWithoutEvidence` rather than minting quantity. +fn filter_evidence(mut draft: WorldPatch, allowed: &BTreeSet) -> WorldPatch { + draft + .evidence + .retain(|reference| allowed.contains(reference)); + draft +} + +pub(super) fn derive_elaboration_capture( + prompt: &str, + last_mismatches: &[Mismatch], + completed: &[InferenceOutput], +) -> Result { + match evaluate_elaboration_loop(prompt, last_mismatches, completed)? { + ElaborationLoopEvaluation::Complete { capture } => Ok(capture), + ElaborationLoopEvaluation::Continue { .. } => Err(ControllerError::Serialization( + "elaboration evidence did not finalize".into(), + )), + } +} + +pub(super) fn elaboration_request( + command_id: CommandId, + round: usize, + model: &str, + input: Vec, +) -> Result { + tool_request( + command_id, + round, + InferencePurpose::Elaboration, + model, + ELABORATION_INSTRUCTIONS, + input, + patch_tools(), + ) +} + +/// A session's identity is derived from the world, the jurisdiction, and the +/// answer's digest, so a crashed loop resumes the same store row and the +/// mailbox's idempotency probe sees the same command. No `uuid/v5`: the digest +/// is sha256 and its first sixteen bytes become the id. +fn session_command_id(session: &ElaboratorSession) -> Result { + let mut hasher = Sha256::new(); + hasher.update(ELABORATION_NAMESPACE.as_bytes()); + hasher.update( + rmp_serde::to_vec_named(&( + session.world_id, + session.jurisdiction, + &session.answer_digest, + )) + .map_err(|error| ControllerError::Serialization(error.to_string()))?, + ); + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + CommandId::parse_uuid(&Uuid::from_bytes(bytes).to_string()) + .map_err(|error| ControllerError::Serialization(error.to_string())) +} + +fn digest_of(value: &T) -> Result { + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| ControllerError::Serialization(error.to_string()))?; + Ok(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn output(calls: Vec<(&str, Value)>) -> InferenceOutput { + InferenceOutput { + events: 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_digest: "sha256:receipt".into(), + } + } + + fn place(handle: &str) -> Value { + serde_json::json!({"handle": handle, "label": "A Shed", "container": null}) + } + + fn capture(completed: &[InferenceOutput]) -> ElaborationCapture { + derive_elaboration_capture("prompt", &[], completed).expect("the loop finalizes") + } + + /// Each declaration tool call appends a `Declaration`; each operation call + /// appends a `ComponentOp`; `submit` is terminal. + #[test] + fn a_draft_accumulates_in_call_order_and_submit_is_terminal() { + let completed = vec![output(vec![ + ("declare_place", place("north")), + ("declare_place", place("south")), + ( + "open_route", + serde_json::json!({"route": {"ref": "draft", "value": "hatch"}}), + ), + (SUBMIT_PATCH_TOOL, serde_json::json!({})), + ])]; + let capture = capture(&completed); + assert!(capture.submitted); + assert_eq!(capture.draft.declarations.len(), 2); + assert_eq!(capture.draft.operations.len(), 1); + assert!(capture.gaps.is_empty()); + // The model's sequencing is the patch's sequencing; nothing reorders. + assert!(matches!( + &capture.draft.declarations[0], + Declaration::Entity(entity) if entity.label == "A Shed" + )); + } + + /// A malformed call, an unknown tool, and a second submit are gaps. None of + /// them reaches the kernel. + #[test] + fn a_malformed_or_duplicate_call_becomes_a_gap() { + let completed = vec![output(vec![ + ("declare_place", serde_json::json!({"handle": 7})), + ("invent_a_god", serde_json::json!({})), + ("declare_place", place("north")), + (SUBMIT_PATCH_TOOL, serde_json::json!({})), + (SUBMIT_PATCH_TOOL, serde_json::json!({})), + ])]; + let capture = capture(&completed); + assert!(capture.submitted); + assert_eq!(capture.draft.declarations.len(), 1); + assert_eq!(capture.gaps.len(), 3); + assert!(capture.gaps[2].detail.contains("submitted twice")); + } + + /// The author owns the size of what it authors. The kernel gets no cap. + #[test] + fn a_draft_past_the_size_cap_becomes_a_gap() { + let mut calls: Vec<(&str, Value)> = (0..=MAX_DRAFT_DECLARATIONS) + .map(|index| { + ( + "declare_place", + serde_json::json!({ + "handle": format!("shed_{index}"), + "label": "A Shed", + "container": null, + }), + ) + }) + .collect(); + calls.push((SUBMIT_PATCH_TOOL, serde_json::json!({}))); + let capture = capture(&vec![output(calls)]); + assert_eq!(capture.draft.declarations.len(), MAX_DRAFT_DECLARATIONS); + assert!( + capture.gaps.iter().any(|gap| gap.detail.contains("cap")), + "the call past the cap was not recorded as a gap" + ); + } + + /// Provenance has an owner and it is the runner: a citation outside the + /// round's retrieved set never reaches the kernel as evidence. + #[test] + fn a_cited_evidence_ref_outside_the_retrieved_set_is_dropped() { + let completed = vec![output(vec![ + ( + "admit", + serde_json::json!({ + "holder": {"ref": "existing", "value": "00000000-0000-0000-0000-000000000001"}, + "resource": {"ref": "existing", "value": "00000000-0000-0000-0000-000000000002"}, + "qty": 3, + "evidence": "vault:forged", + }), + ), + (SUBMIT_PATCH_TOOL, serde_json::json!({})), + ])]; + let capture = capture(&completed); + assert_eq!( + capture.draft.evidence, + vec![EvidenceRef::new("vault:forged")] + ); + let allowed = BTreeSet::from([EvidenceRef::new("vault:harvest")]); + let filtered = filter_evidence(capture.draft, &allowed); + assert!(filtered.evidence.is_empty()); + // The operation survives and is refused by the resolver's own gate. + assert_eq!(filtered.operations.len(), 1); + } + + /// The round budget is a fixed point, not a retry: a model that never + /// submits ends in `NoPatch` with its gaps, and the boundary stays derived. + #[test] + fn a_fruitless_session_ends_without_a_patch() { + let completed: Vec = (0..ELABORATION_ROUND_BUDGET) + .map(|_| { + output(vec![( + RECORD_GAP_PATCH_TOOL, + serde_json::json!({"detail": "no lore"}), + )]) + }) + .collect(); + let capture = capture(&completed); + assert!(!capture.submitted); + assert!(capture.draft.declarations.is_empty()); + assert!(capture.gaps.last().unwrap().detail.contains("round budget")); + } + + /// A boundary that survives a repair keeps its digest and therefore its + /// command id, so a crashed loop resumes the same store row. A different + /// answer is a different id. + #[test] + fn a_session_identity_is_derived_from_its_answer() { + let session = |digest: &str| ElaboratorSession { + world_id: WorldId::nil_for_test(), + jurisdiction: JurisdictionKey::Uncovered, + answer: PatchAnswer::Deficit(JurisdictionKey::Uncovered), + answer_digest: BoundaryDigest::from_digest(digest.to_owned()), + ancestry: "sha256:ancestry".into(), + }; + let first = session_command_id(&session("sha256:one")).unwrap(); + assert_eq!(first, session_command_id(&session("sha256:one")).unwrap()); + assert_ne!(first, session_command_id(&session("sha256:two")).unwrap()); + } +} diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index 25b0eba..715c0a0 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -12,8 +12,8 @@ use std::{ }; use thiserror::Error; -const STATE_ROW: &str = "world_state.commitment.v1"; -const COMMIT_ROW: &str = "world_commit.commitment.v1"; +const STATE_ROW: &str = "world_state.elaboration.v1"; +const COMMIT_ROW: &str = "world_commit.elaboration.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { @@ -412,6 +412,14 @@ fn verify_history( } let previous_now = replay.now; let previous_commitments = replay.commitments.clone(); + // Authority is re-decided here for free: `apply_committed_command` + // re-runs `reduce` against the pre-commit state and requires effect + // equality, then `apply_effect`, and both of those call + // `require_patch_author` and `confine_to_jurisdiction`. A forged row + // claiming an elaborator caller for a patch outside its jurisdiction + // fails replay rather than being admitted by a reducer that trusts the + // recorded caller. A third statement of the same rule here would be a + // third owner of one decision. apply_committed_command(&mut replay, commit)?; // Two chain checks one state cannot make: the clock never runs // backwards, and it advances only on a tick. diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index cf0a6b5..071852f 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -1,10 +1,10 @@ use super::{ AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, - DraftHandle, EntityDeclaration, EntityKind, KernelError, NewController, OperatorEvent, - PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, - SystemCapability, TickMinutes, WorldKernel, WorldPatch, WorldScaleIntentRef, WorldSnapshot, - journal, patch::kernel_speak_grant, prepare_creation, + DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey, KernelError, NewController, + OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, + SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldKernel, WorldPatch, + WorldScaleIntentRef, WorldSnapshot, journal, patch::kernel_speak_grant, prepare_creation, }; use crate::app_session::VerifiedPrincipalEvidence; use std::path::Path; @@ -328,6 +328,33 @@ impl WorldMailbox { .await } + /// The elaborator's only commit port. Stamped, like every digest-binding + /// command: the loop cannot know the live revision either, and an + /// `AdmitPatch` from an elaborator binds by its answer's digest exactly as + /// an `ExerciseDecision` binds by scope digest. `answers` is not an + /// `Option`, so the port cannot express an unanswered elaborator patch and + /// `AnswerRequired` is reachable only through the owner lane and the + /// journal. Visible inside the world subtree, where the elaboration organ + /// lives; unreachable from runtime ingress. + pub(super) async fn submit_elaboration( + &self, + command_id: CommandId, + jurisdiction: JurisdictionKey, + answers: PatchAnswer, + patch: WorldPatch, + ) -> Result { + self.submit_stamped( + command_id, + CallerId::System(SystemCapability::Elaborator { jurisdiction }), + CommandBody::AdmitPatch { + answers: Some(answers), + patch, + }, + AuthenticatedCaller::verified_system(SystemCapability::Elaborator { jurisdiction }), + ) + .await + } + #[cfg(test)] pub(super) async fn create_fixture( &self, @@ -431,6 +458,37 @@ impl WorldMailbox { /// this type has. Adding `.operator_log()` to `controllers.rs` fails to /// compile, because `ControllerPort` never named it; that failure is the /// proof, not a test that runs and passes. +/// The elaboration organ's narrowing of the mailbox: it reads a snapshot and +/// commits one authored patch. Nothing else on `WorldMailbox` is reachable from +/// the authoring lane, and that is a fact about which methods this type has +/// rather than a test that runs and passes. +#[derive(Clone)] +pub(crate) struct ElaborationPort { + mailbox: WorldMailbox, +} + +impl ElaborationPort { + pub(crate) fn new(mailbox: WorldMailbox) -> Self { + Self { mailbox } + } + + pub(super) async fn snapshot(&self) -> Result { + self.mailbox.snapshot().await + } + + pub(super) async fn submit_elaboration( + &self, + command_id: CommandId, + jurisdiction: JurisdictionKey, + answers: PatchAnswer, + patch: WorldPatch, + ) -> Result { + self.mailbox + .submit_elaboration(command_id, jurisdiction, answers, patch) + .await + } +} + #[derive(Clone)] pub(crate) struct ControllerPort { mailbox: WorldMailbox, diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 8b39ceb..2c35c86 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -8,9 +8,11 @@ mod action; mod clock; mod controllers; +mod elaboration; mod journal; mod mailbox; mod patch; +mod tool_schema; pub(crate) use action::ActionMismatch; pub(crate) use clock::{FictionalMinutes, Motion, TickMinutes}; @@ -20,7 +22,7 @@ pub(crate) use controllers::{ NarrativeRun, OperationalCapture, OperationalDecision, OperationalPending, OperationalRun, SourceRange, SubmissionDisposition, TranslationGapSummary, }; -pub(crate) use mailbox::{ControllerPort, MailboxError, WorldMailbox}; +pub(crate) use mailbox::{ControllerPort, ElaborationPort, MailboxError, WorldMailbox}; pub(crate) use patch::{ AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant, AuthorityKindName, AuthorityTarget, BoundPrecondition, Bounds, ChannelRecord, Commitment, @@ -38,7 +40,7 @@ use patch::{ }; #[cfg(test)] pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef}; -use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; +use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch, Site}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; @@ -49,8 +51,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.commitment.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.commitment.v1"; +pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.elaboration.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.elaboration.v1"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `-` pair (e.g. `foundation-v1`). Callers that publish a @@ -103,6 +105,12 @@ impl CommandId { } impl WorldId { + /// A named zero for tests that need a world identity and no world. + #[cfg(test)] + pub(super) fn nil_for_test() -> Self { + Self(Uuid::nil()) + } + fn issue() -> Self { Self(Uuid::new_v4()) } @@ -225,10 +233,18 @@ enum CallerId { System(SystemCapability), } +/// Internally tagged, because a data-carrying variant cannot join a bare-string +/// encoding without silently changing every commit that already carries +/// `Clock`. The tag is part of the commit digest, so the schema bumps with it. #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] +#[serde(tag = "capability", rename_all = "snake_case")] enum SystemCapability { Clock, + /// Authors structure inside one jurisdiction. Never derived from session + /// evidence, never minted by ingress, never held by a subject. + Elaborator { + jurisdiction: JurisdictionKey, + }, } #[derive(Clone, Debug)] @@ -1308,14 +1324,24 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { - require_owner(state, &command.caller)?; + // Answer before authority, because the jurisdiction check reads the + // answer and a missing one must read as `AnswerRequired` rather + // than `Unauthorized`. Resolution before confinement, because + // confinement reads draft-resolved referents and a structurally + // broken patch should return its complete mismatch set rather than + // a jurisdiction complaint about a reference that does not resolve. require_answer( state, answers.as_ref(), !(patch.declarations.is_empty() && patch.evidence.is_empty()), )?; + let confinement = require_patch_author(state, &command.caller, answers.as_ref())?; let resolved = patch::resolve_patch(state, command.id, patch, None) .map_err(KernelError::PatchRejected)?; + if let Some(jurisdiction) = confinement { + confine_to_jurisdiction(state, &resolved, jurisdiction) + .map_err(KernelError::PatchRejected)?; + } Ok(WorldEffect::PatchAdmitted { answers: answers.clone(), resolved, @@ -1327,13 +1353,21 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result Result<(), KernelError> { - match caller { - CallerId::System(SystemCapability::Clock) - if !matches!(body, CommandBody::AdvanceTime { .. }) => - { - Err(KernelError::Unauthorized) - } - _ => Ok(()), + let CallerId::System(capability) = caller else { + return Ok(()); + }; + let admitted = matches!( + (capability, body), + (SystemCapability::Clock, CommandBody::AdvanceTime { .. }) + | ( + SystemCapability::Elaborator { .. }, + CommandBody::AdmitPatch { .. } + ) + ); + if admitted { + Ok(()) + } else { + Err(KernelError::Unauthorized) } } @@ -3137,6 +3171,14 @@ pub(crate) enum CausalBoundary { #[serde(transparent)] pub(crate) struct BoundaryDigest(String); +impl BoundaryDigest { + /// The deficit lane's answer has no preimage of its own: its digest is the + /// session's, produced by the same `sha256:` spelling. + pub(super) fn from_digest(value: String) -> Self { + Self(value) + } +} + #[derive(Serialize)] struct UnelaboratedDestinationPreimage<'a> { world_id: WorldId, @@ -3574,6 +3616,353 @@ fn required_approvers(state: &WorldState) -> BTreeSet { .collect() } +/// Who may admit a patch, and inside what. `None` means unconfined: the owner. +/// Reached from `reduce`'s `AdmitPatch` arm and re-reached from `apply_effect`'s +/// `PatchAdmitted` arm, per the file's idiom that `reduce` decides and +/// `apply_effect` re-decides. +fn require_patch_author( + state: &WorldState, + caller: &CallerId, + answers: Option<&PatchAnswer>, +) -> Result, KernelError> { + match caller { + CallerId::Principal(principal) if principal == &state.owner => Ok(None), + CallerId::System(SystemCapability::Elaborator { jurisdiction }) => { + let answer = answers.ok_or(KernelError::Unauthorized)?; + if !jurisdiction_covers(state, *jurisdiction, answer) { + return Err(KernelError::Unauthorized); + } + Ok(Some(*jurisdiction)) + } + _ => Err(KernelError::Unauthorized), + } +} + +/// Does the caller's jurisdiction cover the thing the answer names? +/// +/// Two coverings, deliberately asymmetric. A boundary is covered +/// **transitively** through `covers_place`, so a parent jurisdiction's +/// elaborator may answer a boundary in a nested child. A deficit is covered by +/// **exact key equality**: a subject under nested roots counts toward both +/// roots' targets, so a parent answering a child's row would reduce two targets +/// with one subject and drain a child's queue while its own row stays red. +/// Boundaries name a thing; deficits name a row. +fn jurisdiction_covers(state: &WorldState, held: JurisdictionKey, answer: &PatchAnswer) -> bool { + match answer { + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => { + place_in(state, held, *place) + } + // The two never-derived variants join this clause only so the match is + // total; `exact_boundary` refuses them before authority is read. + PatchAnswer::Boundary( + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + }, + ) => match state.positions.get(subject) { + Some(position) => place_in(state, held, position.place), + None => held == JurisdictionKey::Uncovered, + }, + PatchAnswer::Deficit(key) => *key == held, + } +} + +fn place_in(state: &WorldState, held: JurisdictionKey, place: EntityId) -> bool { + match held { + JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&state.entities, root, place), + JurisdictionKey::Uncovered => false, + } +} + +/// The ground a patch writes on, as one map over `state ∪ patch`, so a place +/// declared and built on in the same patch confines through the chain it +/// declares. +fn candidate_places( + state: &WorldState, + resolved: &ResolvedPatch, +) -> BTreeMap { + let mut entities = state.entities.clone(); + for declared in &resolved.entities { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.facts { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.channels { + entities.insert(declared.entity_id, declared.entity.clone()); + } + entities +} + +/// Every place-or-subject referent a jurisdictional author writes must sit under +/// its jurisdiction. Returns the complete set, like every other check. +/// +/// Placeless referents — resource kinds, catalog entries, canonical facts — +/// name no ground and are not confined. A place declared with no container is a +/// new jurisdiction root and is the owner's act. There is no relevance test: a +/// patch that satisfies its answer may also declare unrelated structure inside +/// its jurisdiction, because "the minimum the boundary needs" is a semantic +/// verdict the kernel must not hold. +fn confine_to_jurisdiction( + state: &WorldState, + resolved: &ResolvedPatch, + held: JurisdictionKey, +) -> Result<(), Vec> { + let entities = candidate_places(state, resolved); + let inside = |place: EntityId| match held { + JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&entities, root, place), + JurisdictionKey::Uncovered => false, + }; + let mut positions: BTreeMap> = state + .positions + .iter() + .map(|(subject, position)| (*subject, Some(position.place))) + .collect(); + for declared in &resolved.subjects { + positions.insert( + declared.subject_id, + declared.position.map(|position| position.place), + ); + } + let mut edges: BTreeMap = state + .edges + .iter() + .map(|(edge_id, record)| (*edge_id, record.endpoints())) + .collect(); + for declared in &resolved.routes { + edges.insert(declared.edge_id, declared.edge.endpoints()); + } + + let mut mismatches = Vec::new(); + let mut confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec| { + let admitted = match positions.get(&subject).copied().flatten() { + Some(place) => inside(place), + None => held == JurisdictionKey::Uncovered, + }; + if !admitted { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + let mut confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec| { + if !inside(place) { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + + for declared in &resolved.subjects { + let site = Site::Declaration(declared.handle.clone()); + confine_subject(&site, declared.subject_id, &mut mismatches); + } + for declared in &resolved.entities { + if declared.entity.kind != EntityKind::Place { + continue; + } + let site = Site::Declaration(declared.handle.clone()); + match declared.entity.container { + Some(container) => confine_place(&site, container, &mut mismatches), + // A root is the owner's act. An elaborator elaborates inside one. + None => mismatches.push(Mismatch::OutsideJurisdiction { site }), + } + } + for declared in &resolved.routes { + let site = Site::Declaration(declared.handle.clone()); + let (from, to) = declared.edge.endpoints(); + confine_place(&site, from, &mut mismatches); + confine_place(&site, to, &mut mismatches); + } + for declared in &resolved.facts { + if let FactStanding::Claimed { by } = declared.fact.standing { + let site = Site::Declaration(declared.handle.clone()); + confine_subject(&site, by, &mut mismatches); + } + } + for declared in &resolved.channels { + let site = Site::Declaration(declared.handle.clone()); + match &declared.channel.reach { + Reach::Place(place) => confine_place(&site, *place, &mut mismatches), + Reach::Subjects(subjects) => { + for subject in subjects { + confine_subject(&site, *subject, &mut mismatches); + } + } + } + if let Some(controller) = declared.channel.controller { + confine_subject(&site, controller, &mut mismatches); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + let site = Site::Operation(index); + let (subjects, places, routes) = operation_ground(operation, &entities); + for subject in subjects { + confine_subject(&site, subject, &mut mismatches); + } + for place in places { + confine_place(&site, place, &mut mismatches); + } + for route in routes { + match edges.get(&route) { + Some((from, to)) => { + confine_place(&site, *from, &mut mismatches); + confine_place(&site, *to, &mut mismatches); + } + None => mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }), + } + } + } + mismatches.sort(); + mismatches.dedup(); + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +/// The ground one lowered operation touches: the subjects whose position it +/// must sit under, the places it names directly, and the routes whose endpoints +/// it must sit under. Total over `ResolvedOp`, so a new operation cannot ship +/// without saying where it lands. +fn operation_ground( + operation: &ResolvedOp, + entities: &BTreeMap, +) -> (Vec, Vec, Vec) { + // A resource, a fact, and a channel are placeless referents: they name no + // ground, so only a place among the named entities confines. + let places = |candidates: Vec| { + candidates + .into_iter() + .filter(|entity_id| { + entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }) + .collect() + }; + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => (vec![*subject_id], Vec::new(), vec![*edge_id]), + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + (Vec::new(), Vec::new(), vec![*edge_id]) + } + ResolvedOp::AlterCost { edge_id, .. } => (Vec::new(), Vec::new(), vec![*edge_id]), + ResolvedOp::Transfer { + from, to, resource, .. + } => (vec![*from, *to], places(vec![*resource]), Vec::new()), + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + .. + } => ( + vec![*holder], + places(vec![*from_resource, *into_resource]), + Vec::new(), + ), + ResolvedOp::Consume { + holder, resource, .. + } + | ResolvedOp::Admit { + holder, resource, .. + } => (vec![*holder], places(vec![*resource]), Vec::new()), + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + match target { + DependencyTarget::Subject(other) => { + (vec![*subject, *other], Vec::new(), Vec::new()) + } + DependencyTarget::Route(edge_id) => (vec![*subject], Vec::new(), vec![*edge_id]), + DependencyTarget::Resource(resource) => { + (vec![*subject], places(vec![*resource]), Vec::new()) + } + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => match grant.over { + AuthorityTarget::Subject(other) => (vec![*holder, other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*holder], vec![root], Vec::new()), + }, + ResolvedOp::OpenOffice { institution, .. } + | ResolvedOp::CloseOffice { institution, .. } + | ResolvedOp::VacateOffice { institution, .. } => { + (vec![*institution], Vec::new(), Vec::new()) + } + ResolvedOp::InstallIncumbent { + institution, + incumbent, + .. + } => (vec![*institution, *incumbent], Vec::new(), Vec::new()), + ResolvedOp::OpenForum { + forum, standing, .. + } => match standing { + AuthorityTarget::Subject(other) => (vec![*forum, *other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*forum], vec![*root], Vec::new()), + }, + ResolvedOp::CloseForum { .. } => (Vec::new(), Vec::new(), Vec::new()), + ResolvedOp::AcquireKnowledge { subject, .. } | ResolvedOp::Forget { subject, .. } => { + (vec![*subject], Vec::new(), Vec::new()) + } + ResolvedOp::Communicate { speaker, .. } => (vec![*speaker], Vec::new(), Vec::new()), + ResolvedOp::SetReach { channel, reach } => { + let mut subjects = Vec::new(); + let mut named = Vec::new(); + match reach { + Reach::Place(place) => named.push(*place), + Reach::Subjects(members) => subjects.extend(members.iter().copied()), + } + named.push(*channel); + (subjects, places(named), Vec::new()) + } + ResolvedOp::SetController { + channel, + controller, + } => ( + controller.iter().copied().collect(), + places(vec![*channel]), + Vec::new(), + ), + // Kernel-synthesized by `action::exercise` and by nothing a patch may + // carry; it is confined by its speaker all the same. + ResolvedOp::AssertClaim { by, .. } => (vec![*by], Vec::new(), Vec::new()), + ResolvedOp::CreateCommitment { + subject, + commitment, + .. + } => ( + std::iter::once(*subject) + .chain(commitment.counterparty) + .collect(), + Vec::new(), + Vec::new(), + ), + ResolvedOp::DischargeCommitment { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), + ResolvedOp::AdvancePressure { source, target, .. } + | ResolvedOp::ReducePressure { source, target, .. } + | ResolvedOp::ResolvePressure { source, target } => { + let mut subjects = vec![*target]; + let mut named = Vec::new(); + let mut routes = Vec::new(); + match source { + PressureSource::Commitment { subject, .. } | PressureSource::Subject(subject) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Subject(subject)) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + routes.push(*edge_id); + } + PressureSource::Dependency(DependencyTarget::Resource(resource)) => { + named.push(*resource); + } + } + (subjects, places(named), routes) + } + } +} + fn require_owner(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { if caller == &CallerId::Principal(state.owner.clone()) { Ok(()) @@ -3627,10 +4016,18 @@ fn apply_effect( ) -> Result<(), KernelError> { // The capability rule `reduce` decided, re-decided here against the effect // the command produced. - if matches!(caller, CallerId::System(SystemCapability::Clock)) - && !matches!(effect, WorldEffect::TimeAdvanced { .. }) - { - return Err(KernelError::Unauthorized); + if let CallerId::System(capability) = caller { + let admitted = matches!( + (capability, effect), + (SystemCapability::Clock, WorldEffect::TimeAdvanced { .. }) + | ( + SystemCapability::Elaborator { .. }, + WorldEffect::PatchAdmitted { .. } + ) + ); + if !admitted { + return Err(KernelError::Unauthorized); + } } match effect { WorldEffect::WorldCreated { .. } => { @@ -3639,12 +4036,20 @@ fn apply_effect( )); } WorldEffect::PatchAdmitted { answers, resolved } => { - if caller != &CallerId::Principal(state.owner.clone()) { - return Err(KernelError::Invariant( - "admitted patch does not satisfy admission authority".into(), - )); - } require_answer(state, answers.as_ref(), !resolved.declares_nothing())?; + let confinement = + require_patch_author(state, caller, answers.as_ref()).map_err(|_| { + KernelError::Invariant( + "admitted patch does not satisfy admission authority".into(), + ) + })?; + if let Some(jurisdiction) = confinement { + confine_to_jurisdiction(state, resolved, jurisdiction).map_err(|_| { + KernelError::Invariant( + "admitted patch wrote outside its author's jurisdiction".into(), + ) + })?; + } // The deficit before the write, so "strictly decreased" is a // comparison rather than a claim the effect makes. let before = match answers { @@ -11889,4 +12294,543 @@ mod clock_tests { "the digest ignored the route it names" ); } + + // ---- the elaborator capability ------------------------------------- + + fn elaborator(jurisdiction: JurisdictionKey) -> CallerId { + CallerId::System(SystemCapability::Elaborator { jurisdiction }) + } + + fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + body: CommandBody, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command(&snapshot, CommandId::new(), caller.clone(), body), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn dead_end_boundary(kernel: &WorldKernel) -> CausalBoundary { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the fixture derives one dead end") + } + + fn shed_under(container: EntityId, handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(container)), + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + /// Verification 14: the mailbox port cannot express an unanswered + /// elaborator patch, so this is reachable only through the journal lane — + /// and it is refused there. + #[test] + fn elaborator_patch_without_answer_is_answer_required() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unanswered"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Verification 14: a jurisdiction whose every row is zero has nothing to + /// answer, so the answer is not derived. + #[test] + fn patch_answering_a_zero_deficit_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ZeroDeficit"); + let jurisdiction = JurisdictionKey::PlaceSubtree(clockwork.dead_end); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .all(|row| row.deficit == 0) + ); + let error = submit_as( + &mut kernel, + elaborator(jurisdiction), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(jurisdiction)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The one admission rule at the top of `reduce` refuses four bodies before + /// any of them is read, and the clock's capability is refused the fifth. + #[test] + fn a_system_capability_is_admitted_for_exactly_one_body() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Capability"); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let opportunity = opportunity_for(&active, clockwork.reeve); + let answered = dead_end_boundary(&kernel); + let forbidden = [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + CommandBody::AdvanceTime { + minutes: minutes(60), + }, + ]; + for body in forbidden { + let error = submit_as(&mut kernel, held.clone(), body).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + // The mirror: the clock may not author. + let error = submit_as( + &mut kernel, + clock_caller(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, active.revision); + } + + /// Seed admission is the owner's lane: an elaborator in Draft has no + /// derived boundary to answer and nothing to be authorized for. + #[test] + fn elaborator_in_draft_is_unauthorized() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "DraftLane"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel.snapshot().unwrap().places[0].id; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(commons)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(commons, "shed"), + }, + ) + .unwrap_err(); + // Draft answers nothing, so the answer gate passes and authority + // refuses: an elaborator with no answer holds nothing. + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Boundaries are covered transitively, so a parent jurisdiction's + /// elaborator may answer a boundary in a nested child — and a sibling root + /// may not answer it at all. + #[test] + fn boundary_jurisdiction_is_transitive_and_exclusive() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Transitive"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // The hall's elaborator does not cover the unwalked road. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // One unconfined owner patch answers that boundary and opens a second + // one strictly inside the hall, so the two coverings can be told apart + // on one world. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + 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(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered) + ); + + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let nested = dead_end_boundary(&kernel); + assert!(matches!( + nested, + CausalBoundary::UnelaboratedDestination { place, .. } if place == cellar + )); + + // The road's root does not reach into the hall. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // The hall's does, transitively, through the same containment walk the + // civic lane uses. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the parent root covers a nested boundary"); + assert!(!derive_boundaries(&kernel.state).unwrap().contains(&nested)); + } + + /// A deficit is covered by exact key equality. A parent answering a child's + /// row would reduce two targets with one subject, because a subject under + /// nested roots counts toward both. + #[test] + fn parent_jurisdiction_cannot_answer_a_child_deficit_row() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Rows", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = *kernel + .state + .scale_intent + .jurisdictions + .keys() + .next() + .expect("the declared root"); + let active = activate(&mut kernel); + let inner = active.places[0].id; + let row = JurisdictionKey::PlaceSubtree(commons); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .any(|candidate| candidate.jurisdiction == row && candidate.deficit > 0) + ); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::Uncovered), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(row)), + patch: shed_under(inner, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Confinement: a valid answer does not license a write outside the + /// jurisdiction, and a place with no container is a new root, which is the + /// owner's act. + #[test] + fn an_elaborator_cannot_write_outside_its_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Confined"); + let answered = dead_end_boundary(&kernel); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + + let foreign = submit_as( + &mut kernel, + held.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(&foreign, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("yardshed")), + }]), + "{foreign:?}" + ); + + let rootless = submit_as( + &mut kernel, + held, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&rootless, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("newroot")), + }]), + "{rootless:?}" + ); + + // The owner is unconfined, and the identical rootless patch commits — + // once it answers something the kernel derives. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + } + + /// Verification 17: seed admission and boundary elaboration reach one + /// reducer. The same structural defect returns the same complete set on + /// both lanes. + #[test] + fn seed_admission_and_boundary_elaboration_reach_one_reducer() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OneReducer"); + let answered = dead_end_boundary(&kernel); + let dangling = |handle: &str| WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: "The Nowhere Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("nothing"))), + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let snapshot = kernel.snapshot().unwrap(); + let owner_error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let elaborator_error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ) + .unwrap_err(); + let set_of = |error: &KernelError| match error { + KernelError::PatchRejected(set) => set.clone(), + other => panic!("{other:?}"), + }; + assert_eq!(set_of(&owner_error), set_of(&elaborator_error)); + + // And both lanes commit the sound patch through the one writer. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaborated patch commits"); + } + + /// `reduce` decides and `apply_effect` re-decides: a hand-built effect with + /// a jurisdiction that does not cover its answer never applies. + #[test] + fn apply_effect_re_decides_elaborator_authority() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Redecide"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard].container.unwrap(); + let command_id = CommandId::issue(); + let resolved = patch::resolve_patch( + &kernel.state, + command_id, + &shed_under(clockwork.dead_end, "shed"), + None, + ) + .expect("the patch resolves"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(hall)), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + // The honest jurisdiction applies through the same arm. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &effect, + ) + .expect("the covering jurisdiction applies"); + assert_ne!(candidate, kernel.state); + } + + /// Replay re-decides authority for free, because it re-runs `reduce` and + /// `apply_effect` against the pre-commit state. A row whose recorded caller + /// claims a jurisdiction it does not have fails the journal. + #[test] + fn journal_replay_refuses_a_forged_elaborator_row() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); + let world_id = kernel.state.world_id; + let answered = dead_end_boundary(&kernel); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the honest elaboration commits"); + drop(kernel); + let replayed = WorldKernel::open(&path, world_id).expect("the honest history replays"); + assert!( + replayed + .state + .entities + .values() + .any(|entity| entity.label == "The shed") + ); + } + + /// The mismatch vocabulary is kernel-internal plus controller telemetry. It + /// never enters a commit, and `verify_state_shape` never grows a clause for + /// it because no partition holds one. + #[test] + fn mismatch_never_appears_in_a_world_commit() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); + let answered = dead_end_boundary(&kernel); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaboration commits"); + + let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); + let text = String::from_utf8_lossy(&bytes); + for tag in [ + "outside_jurisdiction", + "unresolved_draft", + "no_canonical_change", + "mismatch", + ] { + assert!(!text.contains(tag), "{tag} reached world state"); + } + } } diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 7c3e936..479cd09 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -12,11 +12,14 @@ //! after that set is empty, so a rejected patch never mints an ID. use super::clock::{FictionalMinutes, TickMinutes}; +use super::tool_schema; use super::{ AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, NewController, SubjectId, SubjectKind, SubjectState, WorldId, }; +use codex_connector::CodexToolDefinition; use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; use uuid::Uuid; @@ -233,7 +236,8 @@ pub(crate) enum Ref { } /// A referent in any of the three referent namespaces, or in the catalog. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "ref", rename_all = "snake_case")] pub(crate) enum RefName { Subject(Ref), Entity(Ref), @@ -858,7 +862,8 @@ pub(crate) struct AffordanceDeclaration { /// Where a failed check appeared. One way to say it, for declarations and /// operations alike. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "site", content = "at", rename_all = "snake_case")] pub(crate) enum Site { Declaration(DraftHandle), Operation(usize), @@ -869,10 +874,9 @@ pub(crate) enum Site { pub(crate) struct EvidenceRef(String); impl EvidenceRef { - /// Gated because no `AdmitPatch` ingress exists yet: every caller that - /// builds a patch today is a test. It loses the gate in the same commit as - /// the first production patch author. - #[cfg(test)] + /// The elaborator's evidence receipts are built here, and `Deserialize` + /// already mints one from any string, so this constructor gates nothing. + /// Canonical text is checked by the resolver, in the complete mismatch set. pub(super) fn new(value: impl Into) -> Self { Self(value.into()) } @@ -1139,8 +1143,12 @@ pub(crate) struct WorldPatch { } /// One named structural check that a patch failed. A rejection carries the -/// complete set, never the first failure, and is never persisted. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +/// complete set, never the first failure. It never enters `WorldState`, +/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist +/// for exactly one reader, the elaboration checkpoint, which is +/// controller-owned telemetry under its own row type and its own schema. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "mismatch", rename_all = "snake_case")] pub(crate) enum Mismatch { EmptyHandle { position: usize, @@ -1403,6 +1411,11 @@ pub(crate) enum Mismatch { /// The permille weights sum over 1000: weights distribute the target and /// never raise it. ScaleWeightsExceedWhole, + /// A jurisdictional author wrote outside its jurisdiction. The owner is + /// unconfined and never sees this. + OutsideJurisdiction { + site: Site, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -5133,6 +5146,1381 @@ pub(super) fn containment_terminates( false } +// --------------------------------------------------------------------------- +// The patch tool catalog. +// +// The vocabulary's owner owns its projection. `PATCH_TOOLS` is one entry per +// admissible authoring shape, and the shape rule is stated once: the tool +// surface is the variants a non-genesis patch may carry, with every +// always-refused choice removed rather than exposed. Nothing else in the tree +// emits a model-facing patch schema. +// --------------------------------------------------------------------------- + +/// What a tool call becomes in the draft patch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchToolShape { + /// Emits `Declaration::` with `fixed` merged into the arguments. + Declare { + variant: &'static str, + fixed: &'static [(&'static str, &'static str)], + }, + /// Emits `ComponentOp::`. + Operate { variant: &'static str }, + /// Ends or annotates the session; produces nothing for the patch. + Session, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PatchField { + pub(crate) name: &'static str, + pub(crate) kind: PatchFieldKind, +} + +/// One argument's projection. Bounds live here rather than only in a rejection, +/// so the model is told the bound instead of discovering it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchFieldKind { + Reference(&'static str), + OptionalReference(&'static str), + ReferenceSet(&'static str), + Handle, + Label, + Statement, + Quantity, + Cost, + Magnitude, + Minutes, + OptionalPeriod, + Evidence, + Flag, + Text(&'static str), + Name(&'static str), + NameSet(&'static str), + Choice(&'static [&'static str]), + Composite(CompositeShape), + CompositeList(CompositeShape), +} + +/// A closed payload type the vocabulary already owns. One arm per shape in both +/// the schema emitter and the exemplar builder, so a new shape breaks the build +/// in two places rather than shipping a schema with no decoder. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CompositeShape { + NewController, + AccessKind, + DependencyRef, + AuthorityTargetRef, + AuthorityGrantRef, + ReachRef, + FactStandingRef, + AudienceRef, + AuthoredSource, + PressureSourceRef, + CommitmentKey, + PreconditionRef, + RoleSpec, + Precondition, + EffectSlot, + OutcomeBand, +} + +pub(crate) struct PatchTool { + /// Equal to the variant's serde tag, except for the two `Entity` splits and + /// the two session tools. + pub(crate) name: &'static str, + pub(crate) description: &'static str, + pub(crate) fields: &'static [PatchField], + pub(crate) shape: PatchToolShape, +} + +const fn field(name: &'static str, kind: PatchFieldKind) -> PatchField { + PatchField { name, kind } +} + +const SUBJECT_KINDS: &[&str] = &["person", "institution", "population"]; +const COMMITMENT_KINDS: &[&str] = &["routine", "obligation", "goal"]; +const CONFIDENCES: &[&str] = &["doubted", "believed", "certain"]; + +pub(crate) const RECORD_GAP_PATCH_TOOL: &str = "record_gap"; +pub(crate) const SUBMIT_PATCH_TOOL: &str = "submit"; + +pub(crate) const PATCH_TOOLS: &[PatchTool] = &[ + PatchTool { + name: "declare_subject", + description: "Declare a new subject: a person, an institution, or a population.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + field("kind", PatchFieldKind::Choice(SUBJECT_KINDS)), + field( + "controller", + PatchFieldKind::Composite(CompositeShape::NewController), + ), + field("affordances", PatchFieldKind::ReferenceSet("affordance")), + field("position", PatchFieldKind::OptionalReference("place")), + ], + shape: PatchToolShape::Declare { + variant: "subject", + fixed: &[], + }, + }, + PatchTool { + name: "declare_place", + description: "Declare a place. Its container, when given, must be a place.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + field("container", PatchFieldKind::OptionalReference("place")), + ], + shape: PatchToolShape::Declare { + variant: "entity", + fixed: &[("kind", "place")], + }, + }, + PatchTool { + name: "declare_resource", + description: "Declare a resource kind. Quantity is admitted separately, with evidence.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + ], + shape: PatchToolShape::Declare { + variant: "entity", + fixed: &[("kind", "resource")], + }, + }, + PatchTool { + name: "declare_route", + description: "Declare an open route between two places.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + field("from", PatchFieldKind::Reference("place")), + field("to", PatchFieldKind::Reference("place")), + field( + "access", + PatchFieldKind::Composite(CompositeShape::AccessKind), + ), + field("cost", PatchFieldKind::Cost), + ], + shape: PatchToolShape::Declare { + variant: "route", + fixed: &[], + }, + }, + PatchTool { + name: "declare_affordance", + description: "Declare one catalog entry: what an affordance is, not who may use it.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("kind", PatchFieldKind::Name("the affordance's tool name")), + field( + "roles", + PatchFieldKind::CompositeList(CompositeShape::RoleSpec), + ), + field( + "preconditions", + PatchFieldKind::CompositeList(CompositeShape::Precondition), + ), + field( + "effect_slots", + PatchFieldKind::CompositeList(CompositeShape::EffectSlot), + ), + field( + "outcome_bands", + PatchFieldKind::CompositeList(CompositeShape::OutcomeBand), + ), + field("carries_speech", PatchFieldKind::Flag), + ], + shape: PatchToolShape::Declare { + variant: "affordance", + fixed: &[], + }, + }, + PatchTool { + name: "declare_fact", + description: "Declare a fact: a short authored name and the statement it carries.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + field("statement", PatchFieldKind::Statement), + field( + "standing", + PatchFieldKind::Composite(CompositeShape::FactStandingRef), + ), + ], + shape: PatchToolShape::Declare { + variant: "fact", + fixed: &[], + }, + }, + PatchTool { + name: "declare_channel", + description: "Declare a channel and the reach it carries over.", + fields: &[ + field("handle", PatchFieldKind::Handle), + field("label", PatchFieldKind::Label), + field("reach", PatchFieldKind::Composite(CompositeShape::ReachRef)), + field("controller", PatchFieldKind::OptionalReference("subject")), + ], + shape: PatchToolShape::Declare { + variant: "channel", + fixed: &[], + }, + }, + PatchTool { + name: "relocate", + description: "Move a subject along one open route it may traverse.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field("via", PatchFieldKind::Reference("route")), + ], + shape: PatchToolShape::Operate { + variant: "relocate", + }, + }, + PatchTool { + name: "open_route", + description: "Open a closed route.", + fields: &[field("route", PatchFieldKind::Reference("route"))], + shape: PatchToolShape::Operate { + variant: "open_route", + }, + }, + PatchTool { + name: "close_route", + description: "Close an open route.", + fields: &[field("route", PatchFieldKind::Reference("route"))], + shape: PatchToolShape::Operate { + variant: "close_route", + }, + }, + PatchTool { + name: "alter_cost", + description: "Set a route's traversal cost in minutes.", + fields: &[ + field("route", PatchFieldKind::Reference("route")), + field("cost", PatchFieldKind::Cost), + ], + shape: PatchToolShape::Operate { + variant: "alter_cost", + }, + }, + PatchTool { + name: "transfer", + description: "Move a held quantity of one resource from one subject to another.", + fields: &[ + field("from", PatchFieldKind::Reference("subject")), + field("to", PatchFieldKind::Reference("subject")), + field("resource", PatchFieldKind::Reference("resource")), + field("qty", PatchFieldKind::Quantity), + ], + shape: PatchToolShape::Operate { + variant: "transfer", + }, + }, + PatchTool { + name: "transform", + description: "Relabel a held quantity one for one: the same quantity leaves and arrives.", + fields: &[ + field("holder", PatchFieldKind::Reference("subject")), + field("from_resource", PatchFieldKind::Reference("resource")), + field("into_resource", PatchFieldKind::Reference("resource")), + field("qty", PatchFieldKind::Quantity), + ], + shape: PatchToolShape::Operate { + variant: "transform", + }, + }, + PatchTool { + name: "consume", + description: "Destroy a held quantity.", + fields: &[ + field("holder", PatchFieldKind::Reference("subject")), + field("resource", PatchFieldKind::Reference("resource")), + field("qty", PatchFieldKind::Quantity), + ], + shape: PatchToolShape::Operate { variant: "consume" }, + }, + PatchTool { + name: "admit", + description: "The only creation path for quantity. Its evidence must be cited in this same patch.", + fields: &[ + field("holder", PatchFieldKind::Reference("subject")), + field("resource", PatchFieldKind::Reference("resource")), + field("qty", PatchFieldKind::Quantity), + field("evidence", PatchFieldKind::Evidence), + ], + shape: PatchToolShape::Operate { variant: "admit" }, + }, + PatchTool { + name: "bind", + description: "Record that a subject depends on a resource, a route, or another subject.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field( + "target", + PatchFieldKind::Composite(CompositeShape::DependencyRef), + ), + ], + shape: PatchToolShape::Operate { variant: "bind" }, + }, + PatchTool { + name: "release", + description: "Remove one dependency of a subject.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field( + "target", + PatchFieldKind::Composite(CompositeShape::DependencyRef), + ), + ], + shape: PatchToolShape::Operate { variant: "release" }, + }, + PatchTool { + name: "grant_authority", + description: "Add one jurisdiction to a subject: a kind, and the ground it runs over.", + fields: &[ + field("holder", PatchFieldKind::Reference("subject")), + field( + "grant", + PatchFieldKind::Composite(CompositeShape::AuthorityGrantRef), + ), + ], + shape: PatchToolShape::Operate { + variant: "grant_authority", + }, + }, + PatchTool { + name: "revoke_authority", + description: "Remove one jurisdiction from a subject.", + fields: &[ + field("holder", PatchFieldKind::Reference("subject")), + field( + "grant", + PatchFieldKind::Composite(CompositeShape::AuthorityGrantRef), + ), + ], + shape: PatchToolShape::Operate { + variant: "revoke_authority", + }, + }, + PatchTool { + name: "open_office", + description: "Constitute a seat inside an institution and the authority kinds it lends.", + fields: &[ + field("institution", PatchFieldKind::Reference("subject")), + field("office", PatchFieldKind::Name("the office's name")), + field( + "delegated", + PatchFieldKind::NameSet("an authority kind the office lends"), + ), + ], + shape: PatchToolShape::Operate { + variant: "open_office", + }, + }, + PatchTool { + name: "close_office", + description: "Dissolve a seat inside an institution.", + fields: &[ + field("institution", PatchFieldKind::Reference("subject")), + field("office", PatchFieldKind::Name("the office's name")), + ], + shape: PatchToolShape::Operate { + variant: "close_office", + }, + }, + PatchTool { + name: "install_incumbent", + description: "Seat a person in one of an institution's offices.", + fields: &[ + field("institution", PatchFieldKind::Reference("subject")), + field("office", PatchFieldKind::Name("the office's name")), + field("incumbent", PatchFieldKind::Reference("subject")), + ], + shape: PatchToolShape::Operate { + variant: "install_incumbent", + }, + }, + PatchTool { + name: "vacate_office", + description: "Empty a seat, preserving the office itself.", + fields: &[ + field("institution", PatchFieldKind::Reference("subject")), + field("office", PatchFieldKind::Name("the office's name")), + ], + shape: PatchToolShape::Operate { + variant: "vacate_office", + }, + }, + PatchTool { + name: "open_forum", + description: "Say where one kind of grievance goes, and who may bring it.", + fields: &[ + field("grievance", PatchFieldKind::Name("the grievance kind")), + field("forum", PatchFieldKind::Reference("subject")), + field( + "standing", + PatchFieldKind::Composite(CompositeShape::AuthorityTargetRef), + ), + ], + shape: PatchToolShape::Operate { + variant: "open_forum", + }, + }, + PatchTool { + name: "close_forum", + description: "Remove the forum that takes one kind of grievance.", + fields: &[field( + "grievance", + PatchFieldKind::Name("the grievance kind"), + )], + shape: PatchToolShape::Operate { + variant: "close_forum", + }, + }, + PatchTool { + name: "acquire_knowledge", + description: "Give a subject a fact it witnessed, or that a canonical receipt evidences.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field("fact", PatchFieldKind::Reference("fact")), + field( + "source", + PatchFieldKind::Composite(CompositeShape::AuthoredSource), + ), + field("confidence", PatchFieldKind::Choice(CONFIDENCES)), + ], + shape: PatchToolShape::Operate { + variant: "acquire_knowledge", + }, + }, + PatchTool { + name: "communicate", + description: "One telling. The recipients are re-derived from live positions and channels.", + fields: &[ + field("speaker", PatchFieldKind::Reference("subject")), + field("fact", PatchFieldKind::Reference("fact")), + field("to", PatchFieldKind::Composite(CompositeShape::AudienceRef)), + ], + shape: PatchToolShape::Operate { + variant: "communicate", + }, + }, + PatchTool { + name: "forget", + description: "Remove one fact from one subject's knowledge.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field("fact", PatchFieldKind::Reference("fact")), + ], + shape: PatchToolShape::Operate { variant: "forget" }, + }, + PatchTool { + name: "set_reach", + description: "Set which subjects a channel carries to.", + fields: &[ + field("channel", PatchFieldKind::Reference("channel")), + field("reach", PatchFieldKind::Composite(CompositeShape::ReachRef)), + ], + shape: PatchToolShape::Operate { + variant: "set_reach", + }, + }, + PatchTool { + name: "set_controller", + description: "Set, or clear, the subject that may speak on a channel from outside its reach.", + fields: &[ + field("channel", PatchFieldKind::Reference("channel")), + field("controller", PatchFieldKind::OptionalReference("subject")), + ], + shape: PatchToolShape::Operate { + variant: "set_controller", + }, + }, + PatchTool { + name: "create_commitment", + description: "Author a promise: a routine with a period, an obligation to another, or a personal goal.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field("counterparty", PatchFieldKind::OptionalReference("subject")), + field("kind", PatchFieldKind::Choice(COMMITMENT_KINDS)), + field("due", PatchFieldKind::Minutes), + field("period", PatchFieldKind::OptionalPeriod), + field( + "checks", + PatchFieldKind::CompositeList(CompositeShape::PreconditionRef), + ), + ], + shape: PatchToolShape::Operate { + variant: "create_commitment", + }, + }, + PatchTool { + name: "discharge_commitment", + description: "Remove a commitment and every pressure row it sources.", + fields: &[ + field("subject", PatchFieldKind::Reference("subject")), + field( + "key", + PatchFieldKind::Composite(CompositeShape::CommitmentKey), + ), + ], + shape: PatchToolShape::Operate { + variant: "discharge_commitment", + }, + }, + PatchTool { + name: "advance_pressure", + description: "Add pressure on a subject from one named source.", + fields: &[ + field( + "source", + PatchFieldKind::Composite(CompositeShape::PressureSourceRef), + ), + field("target", PatchFieldKind::Reference("subject")), + field("by", PatchFieldKind::Magnitude), + ], + shape: PatchToolShape::Operate { + variant: "advance_pressure", + }, + }, + PatchTool { + name: "reduce_pressure", + description: "Subtract pressure on a subject from one named source.", + fields: &[ + field( + "source", + PatchFieldKind::Composite(CompositeShape::PressureSourceRef), + ), + field("target", PatchFieldKind::Reference("subject")), + field("by", PatchFieldKind::Magnitude), + ], + shape: PatchToolShape::Operate { + variant: "reduce_pressure", + }, + }, + PatchTool { + name: "resolve_pressure", + description: "Remove one pressure row entirely.", + fields: &[ + field( + "source", + PatchFieldKind::Composite(CompositeShape::PressureSourceRef), + ), + field("target", PatchFieldKind::Reference("subject")), + ], + shape: PatchToolShape::Operate { + variant: "resolve_pressure", + }, + }, + PatchTool { + name: RECORD_GAP_PATCH_TOOL, + description: "Record something the world needs that this vocabulary cannot say. It changes nothing.", + fields: &[field( + "detail", + PatchFieldKind::Text("what the world needs and this vocabulary cannot express"), + )], + shape: PatchToolShape::Session, + }, + PatchTool { + name: SUBMIT_PATCH_TOOL, + description: "Submit the accumulated patch for admission. Terminal.", + fields: &[], + shape: PatchToolShape::Session, + }, +]; + +/// The catalog. Fixed per build: it reads `PATCH_TOOLS` and nothing else — not +/// world state, not a snapshot, not a config. +pub(crate) fn patch_tools() -> Vec { + PATCH_TOOLS + .iter() + .map(|entry| { + tool_schema::tool( + entry.name, + entry.description, + tool_schema::object( + entry + .fields + .iter() + .map(|field| (field.name.to_owned(), field_schema(field.kind))) + .collect(), + ), + ) + }) + .collect() +} + +/// The same iteration rendered as one prose line, so the prompt's tool list and +/// the schemas have one owner and cannot drift. +pub(crate) fn patch_tool_signatures() -> String { + PATCH_TOOLS + .iter() + .map(|entry| { + let parameters: Vec<&str> = entry.fields.iter().map(|field| field.name).collect(); + format!("{}({})", entry.name, parameters.join(", ")) + }) + .collect::>() + .join(", ") +} + +fn field_schema(kind: PatchFieldKind) -> Value { + match kind { + PatchFieldKind::Reference(referent) => tool_schema::reference(referent), + PatchFieldKind::OptionalReference(referent) => { + tool_schema::nullable(tool_schema::reference(referent)) + } + PatchFieldKind::ReferenceSet(referent) => { + tool_schema::list(tool_schema::reference(referent)) + } + PatchFieldKind::Handle => { + tool_schema::canonical_string("a new draft handle, unique within this patch") + } + PatchFieldKind::Label => tool_schema::canonical_string("a display label"), + PatchFieldKind::Statement => { + tool_schema::canonical_string("the committed world text this fact carries") + } + PatchFieldKind::Quantity => tool_schema::bounded_integer(1, u64::MAX), + PatchFieldKind::Cost => tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)), + PatchFieldKind::Magnitude => tool_schema::bounded_integer(1, u64::from(u32::MAX)), + PatchFieldKind::Minutes => tool_schema::bounded_integer(0, u64::MAX), + PatchFieldKind::OptionalPeriod => { + tool_schema::nullable(tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST))) + } + PatchFieldKind::Evidence => { + tool_schema::canonical_string("an exact evidence receipt retrieved for this answer") + } + PatchFieldKind::Flag => json!({"type": "boolean"}), + PatchFieldKind::Text(description) | PatchFieldKind::Name(description) => { + tool_schema::canonical_string(description) + } + PatchFieldKind::NameSet(description) => { + tool_schema::list(tool_schema::canonical_string(description)) + } + PatchFieldKind::Choice(values) => tool_schema::name_enum(values), + PatchFieldKind::Composite(shape) => composite_schema(shape), + PatchFieldKind::CompositeList(shape) => tool_schema::list(composite_schema(shape)), + } +} + +fn subject_ref_schema() -> Value { + tool_schema::reference("subject") +} + +fn composite_schema(shape: CompositeShape) -> Value { + match shape { + // `human` is absent, not present-and-rejected: `UnadmittedController` + // refuses it outside genesis, so exposing it would be a door slammed. + CompositeShape::NewController => tool_schema::variant( + "type", + vec![("narrative_persona", vec![]), ("operational_agent", vec![])], + ), + CompositeShape::AccessKind => tool_schema::variant( + "access", + vec![ + ("public", vec![]), + ( + "restricted", + vec![( + "requires".to_owned(), + tool_schema::canonical_string("the authority kind that opens this route"), + )], + ), + ], + ), + CompositeShape::DependencyRef => tool_schema::variant_content( + "target", + "ref", + vec![ + ("resource", tool_schema::reference("resource")), + ("route", tool_schema::reference("route")), + ("subject", subject_ref_schema()), + ], + ), + CompositeShape::AuthorityTargetRef => tool_schema::variant_content( + "over", + "ref", + vec![ + ("subject", subject_ref_schema()), + ("place_subtree", tool_schema::reference("place")), + ], + ), + CompositeShape::AuthorityGrantRef => tool_schema::object(vec![ + ( + "kind".to_owned(), + tool_schema::canonical_string("the authority kind"), + ), + ( + "over".to_owned(), + composite_schema(CompositeShape::AuthorityTargetRef), + ), + ]), + CompositeShape::ReachRef => tool_schema::variant_content( + "reach", + "of", + vec![ + ("subjects", tool_schema::list(subject_ref_schema())), + ("place", tool_schema::reference("place")), + ], + ), + CompositeShape::FactStandingRef => tool_schema::variant( + "standing", + vec![ + ( + "canonical", + vec![( + "evidence".to_owned(), + tool_schema::canonical_string("an exact evidence receipt"), + )], + ), + ("claimed", vec![("by".to_owned(), subject_ref_schema())]), + ], + ), + CompositeShape::AudienceRef => tool_schema::external_variant(vec![ + ("colocated", None), + ("channel", Some(tool_schema::reference("channel"))), + ]), + CompositeShape::AuthoredSource => { + tool_schema::variant("source", vec![("witnessed", vec![]), ("evidenced", vec![])]) + } + CompositeShape::PressureSourceRef => tool_schema::variant_content( + "from", + "of", + vec![ + ( + "commitment", + tool_schema::object(vec![ + ("subject".to_owned(), subject_ref_schema()), + ( + "key".to_owned(), + composite_schema(CompositeShape::CommitmentKey), + ), + ]), + ), + ( + "dependency", + composite_schema(CompositeShape::DependencyRef), + ), + ("subject", subject_ref_schema()), + ], + ), + CompositeShape::CommitmentKey => tool_schema::object(vec![ + ( + "command".to_owned(), + tool_schema::canonical_string("the command id that created the commitment"), + ), + ( + "index".to_owned(), + tool_schema::bounded_integer(0, u64::from(u32::MAX)), + ), + ]), + CompositeShape::PreconditionRef => precondition_ref_schema(), + CompositeShape::RoleSpec => tool_schema::object(vec![ + ( + "role".to_owned(), + tool_schema::canonical_string("the slot's parameter name"), + ), + ("kind".to_owned(), ref_kind_schema()), + ]), + CompositeShape::Precondition => precondition_schema(), + CompositeShape::EffectSlot => tool_schema::object(vec![ + ("op_kind".to_owned(), component_op_kind_schema()), + ( + "roles".to_owned(), + tool_schema::list(tool_schema::canonical_string("a declared role name")), + ), + ( + "bounds".to_owned(), + tool_schema::variant_content( + "bound", + "max", + vec![ + ("quantity", tool_schema::bounded_integer(1, u64::MAX)), + ( + "cost", + tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)), + ), + ], + ), + ), + ]), + CompositeShape::OutcomeBand => tool_schema::object(vec![ + ( + "weight".to_owned(), + tool_schema::bounded_integer(1, u64::from(u32::MAX)), + ), + ( + "effects".to_owned(), + tool_schema::list(tool_schema::bounded_integer(0, u64::from(u32::MAX))), + ), + ]), + } +} + +fn ref_kind_schema() -> Value { + tool_schema::variant_content( + "namespace", + "kind", + vec![ + ( + "subject", + tool_schema::nullable(tool_schema::name_enum(SUBJECT_KINDS)), + ), + ( + "entity", + tool_schema::name_enum(&["place", "resource", "fact", "channel"]), + ), + ("edge", tool_schema::name_enum(&["route"])), + ], + ) +} + +/// The referent-naming checks a commitment carries. +fn precondition_ref_schema() -> Value { + tool_schema::variant( + "precondition", + vec![ + ( + "present", + vec![("at".to_owned(), tool_schema::reference("place"))], + ), + ( + "reachable", + vec![ + ("to".to_owned(), tool_schema::reference("place")), + ( + "within".to_owned(), + tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)), + ), + ], + ), + ( + "holds", + vec![ + ("resource".to_owned(), tool_schema::reference("resource")), + ( + "at_least".to_owned(), + tool_schema::bounded_integer(1, u64::MAX), + ), + ], + ), + ( + "authorized", + vec![ + ( + "over".to_owned(), + composite_schema(CompositeShape::AuthorityTargetRef), + ), + ( + "kind".to_owned(), + tool_schema::canonical_string("the authority kind"), + ), + ], + ), + ( + "has_standing", + vec![( + "grievance".to_owned(), + tool_schema::canonical_string("the grievance kind"), + )], + ), + ( + "knows", + vec![ + ("fact".to_owned(), tool_schema::reference("fact")), + ("at_least".to_owned(), tool_schema::name_enum(CONFIDENCES)), + ], + ), + ( + "can_broadcast", + vec![( + "via".to_owned(), + composite_schema(CompositeShape::AudienceRef), + )], + ), + ( + "can_reach", + vec![ + ("subject".to_owned(), subject_ref_schema()), + ( + "via".to_owned(), + composite_schema(CompositeShape::AudienceRef), + ), + ], + ), + ( + "committed", + vec![ + ("to".to_owned(), subject_ref_schema()), + ("kind".to_owned(), tool_schema::name_enum(COMMITMENT_KINDS)), + ], + ), + ], + ) +} + +/// The role-naming twin. A catalog entry's checks name roles the entry +/// declares, never referents. +fn precondition_schema() -> Value { + let role = || tool_schema::canonical_string("a declared role name"); + let audience_spec = + || tool_schema::external_variant(vec![("colocated", None), ("channel", Some(role()))]); + tool_schema::variant( + "precondition", + vec![ + ("present", vec![("at".to_owned(), role())]), + ( + "reachable", + vec![ + ("to".to_owned(), role()), + ( + "within".to_owned(), + tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)), + ), + ], + ), + ( + "holds", + vec![ + ("resource".to_owned(), role()), + ( + "at_least".to_owned(), + tool_schema::bounded_integer(1, u64::MAX), + ), + ], + ), + ( + "authorized", + vec![ + ("over".to_owned(), role()), + ( + "kind".to_owned(), + tool_schema::canonical_string("the authority kind"), + ), + ], + ), + ( + "has_standing", + vec![( + "grievance".to_owned(), + tool_schema::canonical_string("the grievance kind"), + )], + ), + ( + "knows", + vec![ + ("fact".to_owned(), role()), + ("at_least".to_owned(), tool_schema::name_enum(CONFIDENCES)), + ], + ), + ("can_broadcast", vec![("via".to_owned(), audience_spec())]), + ( + "can_reach", + vec![ + ("subject".to_owned(), role()), + ("via".to_owned(), audience_spec()), + ], + ), + ( + "committed", + vec![ + ("to".to_owned(), role()), + ("kind".to_owned(), tool_schema::name_enum(COMMITMENT_KINDS)), + ], + ), + ], + ) +} + +/// Exactly the operations an affordance may propose, with the payload the world +/// fixes when it authors the entry. +fn component_op_kind_schema() -> Value { + let authority_kind = || { + vec![( + "kind".to_owned(), + tool_schema::canonical_string("the authority kind"), + )] + }; + let office = || { + vec![( + "office".to_owned(), + tool_schema::canonical_string("the office's name"), + )] + }; + tool_schema::variant( + "op", + vec![ + ("relocate", vec![]), + ("open_route", vec![]), + ("close_route", vec![]), + ("alter_cost", vec![]), + ("transfer", vec![]), + ("transform", vec![]), + ("consume", vec![]), + ("bind", vec![]), + ("release", vec![]), + ("grant_authority", authority_kind()), + ("revoke_authority", authority_kind()), + ("install_incumbent", office()), + ("vacate_office", office()), + ( + "acquire_knowledge", + vec![("confidence".to_owned(), tool_schema::name_enum(CONFIDENCES))], + ), + ("forget", vec![]), + ( + "create_commitment", + vec![ + ("kind".to_owned(), tool_schema::name_enum(COMMITMENT_KINDS)), + ( + "horizon".to_owned(), + tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)), + ), + ( + "period".to_owned(), + tool_schema::nullable(tool_schema::bounded_integer( + 1, + u64::from(MAX_ROUTE_COST), + )), + ), + ], + ), + ( + "advance_pressure", + vec![( + "by".to_owned(), + tool_schema::bounded_integer(1, u64::from(u32::MAX)), + )], + ), + ( + "reduce_pressure", + vec![( + "by".to_owned(), + tool_schema::bounded_integer(1, u64::from(u32::MAX)), + )], + ), + ("resolve_pressure", vec![]), + ], + ) +} + +/// One example value per field kind, used by the round-trip test to prove the +/// const list's field names and shapes against the real structs. It is not a +/// second schema: serde is the only decoder, so a wrong name cannot survive. +#[cfg(test)] +pub(super) fn field_example(kind: PatchFieldKind) -> Value { + let draft = |handle: &str| json!({"ref": "draft", "value": handle}); + match kind { + PatchFieldKind::Reference(referent) => draft(referent), + PatchFieldKind::OptionalReference(_) => Value::Null, + PatchFieldKind::ReferenceSet(referent) => json!([draft(referent)]), + PatchFieldKind::Handle => json!("example_handle"), + PatchFieldKind::Label => json!("Example Label"), + PatchFieldKind::Statement => json!("The lower hinge flooded."), + PatchFieldKind::Quantity | PatchFieldKind::Minutes => json!(7), + PatchFieldKind::Cost | PatchFieldKind::Magnitude => json!(3), + PatchFieldKind::OptionalPeriod => Value::Null, + PatchFieldKind::Evidence => json!("vault:example/1"), + PatchFieldKind::Flag => json!(false), + PatchFieldKind::Text(_) | PatchFieldKind::Name(_) => json!("example_name"), + PatchFieldKind::NameSet(_) => json!(["example_name"]), + PatchFieldKind::Choice(values) => json!(values[0]), + PatchFieldKind::Composite(shape) => composite_example(shape), + PatchFieldKind::CompositeList(shape) => json!([composite_example(shape)]), + } +} + +#[cfg(test)] +fn composite_example(shape: CompositeShape) -> Value { + let subject = json!({"ref": "draft", "value": "subject"}); + match shape { + CompositeShape::NewController => json!({"type": "narrative_persona"}), + CompositeShape::AccessKind => json!({"access": "public"}), + CompositeShape::DependencyRef => { + json!({"target": "subject", "ref": subject}) + } + CompositeShape::AuthorityTargetRef => json!({"over": "subject", "ref": subject}), + CompositeShape::AuthorityGrantRef => { + json!({"kind": "command", "over": {"over": "subject", "ref": subject}}) + } + CompositeShape::ReachRef => json!({"reach": "subjects", "of": [subject]}), + CompositeShape::FactStandingRef => json!({"standing": "claimed", "by": subject}), + CompositeShape::AudienceRef => json!("colocated"), + CompositeShape::Precondition => json!({"precondition": "present", "at": "target"}), + CompositeShape::AuthoredSource => json!({"source": "witnessed"}), + CompositeShape::PressureSourceRef => json!({"from": "subject", "of": subject}), + CompositeShape::CommitmentKey => { + json!({"command": "00000000-0000-0000-0000-000000000000", "index": 0}) + } + CompositeShape::PreconditionRef => { + json!({"precondition": "committed", "to": subject, "kind": "goal"}) + } + CompositeShape::RoleSpec => { + json!({"role": "target", "kind": {"namespace": "subject", "kind": null}}) + } + CompositeShape::EffectSlot => json!({ + "op_kind": {"op": "forget"}, + "roles": ["target", "fact"], + "bounds": {"bound": "none"}, + }), + CompositeShape::OutcomeBand => json!({"weight": 1, "effects": [0]}), + } +} + +/// Verification 16: the model-facing patch catalog is exactly the vocabulary +/// the reducer owns, with every always-refused choice removed rather than +/// exposed. +#[cfg(test)] +mod catalog_tests { + use super::*; + + /// One arguments object per entry, one example value per field, with the + /// entry's serde tag and its fixed pairs injected exactly as the evaluator + /// injects them. + fn arguments_for(entry: &PatchTool) -> Value { + let mut object = serde_json::Map::new(); + for field in entry.fields { + object.insert(field.name.to_owned(), field_example(field.kind)); + } + match entry.shape { + PatchToolShape::Declare { variant, fixed } => { + object.insert("type".into(), Value::String(variant.into())); + for (key, value) in fixed { + object.insert((*key).into(), Value::String((*value).into())); + } + } + PatchToolShape::Operate { variant } => { + object.insert("op".into(), Value::String(variant.into())); + } + PatchToolShape::Session => {} + } + Value::Object(object) + } + + fn tag_of(value: &T, tag: &str) -> String { + serde_json::to_value(value).expect("the vocabulary serializes")[tag] + .as_str() + .expect("an internally tagged variant") + .to_owned() + } + + /// Serde is the only decoder, so a field name the const list gets wrong + /// cannot survive this. It pins the catalog's argument names and shapes to + /// the real struct fields, in both directions. + #[test] + fn patch_tool_arguments_round_trip_into_the_vocabulary() { + for entry in PATCH_TOOLS { + let arguments = arguments_for(entry); + match entry.shape { + PatchToolShape::Declare { variant, fixed } => { + let declaration: Declaration = serde_json::from_value(arguments.clone()) + .unwrap_or_else(|error| { + panic!("{} did not decode: {error} from {arguments}", entry.name) + }); + assert_eq!(tag_of(&declaration, "type"), variant, "{}", entry.name); + let round_tripped = + serde_json::to_value(&declaration).expect("a declaration re-encodes"); + for (key, value) in fixed { + assert_eq!(round_tripped[*key], Value::String((*value).into())); + } + } + PatchToolShape::Operate { variant } => { + let operation: ComponentOp = serde_json::from_value(arguments.clone()) + .unwrap_or_else(|error| { + panic!("{} did not decode: {error} from {arguments}", entry.name) + }); + assert_eq!(tag_of(&operation, "op"), variant, "{}", entry.name); + } + PatchToolShape::Session => { + assert!(matches!(arguments, Value::Object(_))); + } + } + } + } + + /// Enumeration equality. The tool names, the shapes' variant tags expanded + /// by their fixed choices, and the two session tools are one set. + #[test] + fn patch_tool_catalog_equals_the_vocabulary() { + let emitted: BTreeSet = patch_tools() + .into_iter() + .map(|definition| definition.name) + .collect(); + let listed: BTreeSet = PATCH_TOOLS + .iter() + .map(|entry| entry.name.to_owned()) + .collect(); + assert_eq!(emitted, listed, "the generator invented or dropped a tool"); + assert!(listed.contains(RECORD_GAP_PATCH_TOOL)); + assert!(listed.contains(SUBMIT_PATCH_TOOL)); + + // Seven declaration shapes over six `Declaration` variants — `Entity` + // splits by kind, because a `kind` field would be a door slammed for + // half its values — plus twenty-eight operations and two session tools. + // `assert_exhaustive` below breaks the build when a variant is added; + // these counts are where the addition is restated. + let declarations = PATCH_TOOLS + .iter() + .filter(|entry| matches!(entry.shape, PatchToolShape::Declare { .. })) + .count(); + let operations = PATCH_TOOLS + .iter() + .filter(|entry| matches!(entry.shape, PatchToolShape::Operate { .. })) + .count(); + assert_eq!((declarations, operations, PATCH_TOOLS.len()), (7, 28, 37)); + + // Every declaration variant the vocabulary owns is reachable, and the + // two payload-carrying entity kinds are not exposed as an `Entity` + // choice. + let declared: BTreeSet = PATCH_TOOLS + .iter() + .filter_map(|entry| match entry.shape { + PatchToolShape::Declare { variant, .. } => Some(variant.to_owned()), + _ => None, + }) + .collect(); + assert_eq!( + declared, + BTreeSet::from([ + "subject".to_owned(), + "entity".to_owned(), + "route".to_owned(), + "affordance".to_owned(), + "fact".to_owned(), + "channel".to_owned(), + ]) + ); + } + + /// The forcing function. These carry no data and their only job is to break + /// the build when a variant is added, which sends the author to the count + /// assertions above and then to `PATCH_TOOLS`. + #[test] + fn patch_vocabulary_exemplars_are_exhaustive() { + #[expect(dead_code, reason = "the match arms are the assertion")] + fn assert_declarations_exhaustive(declaration: &Declaration) -> &'static str { + match declaration { + Declaration::Subject(_) => "declare_subject", + Declaration::Entity(_) => "declare_place or declare_resource", + Declaration::Route(_) => "declare_route", + Declaration::Affordance(_) => "declare_affordance", + Declaration::Fact(_) => "declare_fact", + Declaration::Channel(_) => "declare_channel", + } + } + + #[expect(dead_code, reason = "the match arms are the assertion")] + fn assert_operations_exhaustive(operation: &ComponentOp) -> &'static str { + match operation { + ComponentOp::Relocate { .. } => "relocate", + ComponentOp::OpenRoute { .. } => "open_route", + ComponentOp::CloseRoute { .. } => "close_route", + ComponentOp::AlterCost { .. } => "alter_cost", + ComponentOp::Transfer { .. } => "transfer", + ComponentOp::Transform { .. } => "transform", + ComponentOp::Consume { .. } => "consume", + ComponentOp::Admit { .. } => "admit", + ComponentOp::Bind { .. } => "bind", + ComponentOp::Release { .. } => "release", + ComponentOp::GrantAuthority { .. } => "grant_authority", + ComponentOp::RevokeAuthority { .. } => "revoke_authority", + ComponentOp::OpenOffice { .. } => "open_office", + ComponentOp::CloseOffice { .. } => "close_office", + ComponentOp::InstallIncumbent { .. } => "install_incumbent", + ComponentOp::VacateOffice { .. } => "vacate_office", + ComponentOp::OpenForum { .. } => "open_forum", + ComponentOp::CloseForum { .. } => "close_forum", + ComponentOp::AcquireKnowledge { .. } => "acquire_knowledge", + ComponentOp::Communicate { .. } => "communicate", + ComponentOp::Forget { .. } => "forget", + ComponentOp::SetReach { .. } => "set_reach", + ComponentOp::SetController { .. } => "set_controller", + ComponentOp::CreateCommitment { .. } => "create_commitment", + ComponentOp::DischargeCommitment { .. } => "discharge_commitment", + ComponentOp::AdvancePressure { .. } => "advance_pressure", + ComponentOp::ReducePressure { .. } => "reduce_pressure", + ComponentOp::ResolvePressure { .. } => "resolve_pressure", + } + } + + // Every entry that names an operation names one this match knows, which + // is the same set the decoder walks. + for entry in PATCH_TOOLS { + if let PatchToolShape::Operate { variant } = entry.shape { + let operation: ComponentOp = + serde_json::from_value(arguments_for(entry)).expect("the entry decodes"); + assert_eq!(assert_operations_exhaustive(&operation), variant); + } + } + } + + /// The sibling of the action catalog's authority test. A generated patch + /// schema names structure and nothing about who is asking. + #[test] + fn patch_tool_schemas_cannot_claim_authority() { + for definition in patch_tools() { + let text = definition.parameters_json.to_lowercase(); + for forbidden in [ + "caller", + "jurisdiction", + "command_id", + "revision", + "digest", + "principal", + "affordance_id", + "opportunity", + "world_id", + ] { + assert!( + !text.contains(forbidden), + "{} exposed {forbidden}", + definition.name + ); + } + // `human` is absent from the controller choice, not + // present-and-rejected. + if definition.name == "declare_subject" { + assert!( + !text.contains("human"), + "the human controller is a door slammed" + ); + } + // The entity split is data, not a model choice: neither entity + // declaration exposes a `kind` at all, so `fact` and `channel` are + // absent rather than present-and-rejected. A role binding may still + // name a fact or a channel, which is a different question. + if matches!( + definition.name.as_str(), + "declare_place" | "declare_resource" + ) { + assert!( + !text.contains("\"kind\""), + "{} exposed an entity kind choice", + definition.name + ); + } + } + } + + /// One name, two schemas is the drift the catalog exists to prevent: the + /// elaborator's gap tool and the interpreter's do not share a constant, and + /// neither schema deserializes the other's arguments. + #[test] + fn elaborator_record_gap_is_not_the_interpreter_record_gap() { + let ours = patch_tools() + .into_iter() + .find(|definition| definition.name == RECORD_GAP_PATCH_TOOL) + .expect("the catalog carries a gap tool"); + assert!(ours.parameters_json.contains("detail")); + assert!( + !ours.parameters_json.contains("source_start_byte"), + "the elaborator has no source prose and no byte span" + ); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ghostlight-dungeon/src/world/tool_schema.rs b/crates/ghostlight-dungeon/src/world/tool_schema.rs new file mode 100644 index 0000000..2b98179 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/tool_schema.rs @@ -0,0 +1,123 @@ +//! The one emitter for every model-facing tool schema in the tree. +//! +//! Two catalogs sit above it and share nothing else: the action catalog +//! (`controllers::catalog_tools`) projects a world-state snapshot filtered by +//! grant, and the patch catalog (`patch::patch_tools`) projects the reducer's +//! own vocabulary. Both spell a property the same way because both spell it +//! here. Nothing in this module reads world state, a snapshot, or a config. + +use codex_connector::CodexToolDefinition; +use serde_json::{Value, json}; + +pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition { + CodexToolDefinition { + name: name.into(), + description: description.into(), + parameters_json: serde_json::to_string(&schema) + .expect("static tool schemas must serialize"), + } +} + +pub(super) fn empty_schema() -> Value { + json!({"type":"object","additionalProperties":false,"properties":{}}) +} + +/// Every generated object is closed and total: `additionalProperties` is false +/// and every property is required. An optional argument is expressed as a +/// nullable property, never as an absent one, so the decoder and the schema +/// agree without a second rule about omission. +pub(super) fn object(properties: Vec<(String, Value)>) -> Value { + let required: Vec = properties + .iter() + .map(|(name, _)| Value::String(name.clone())) + .collect(); + json!({ + "type": "object", + "additionalProperties": false, + "required": required, + "properties": properties.into_iter().collect::>(), + }) +} + +pub(super) fn canonical_string(description: &str) -> Value { + json!({"type": "string", "description": description}) +} + +pub(super) fn bounded_integer(min: u64, max: u64) -> Value { + json!({"type": "integer", "minimum": min, "maximum": max}) +} + +pub(super) fn name_enum(values: &[&str]) -> Value { + json!({"type": "string", "enum": values}) +} + +/// A closed sum spelled as a tagged object. `tag` is the discriminator field +/// name; each variant carries its own closed object of content. +pub(super) fn variant(tag: &str, variants: Vec<(&str, Vec<(String, Value)>)>) -> Value { + let branches: Vec = variants + .into_iter() + .map(|(name, content)| { + let mut properties = vec![(tag.to_owned(), json!({"const": name}))]; + properties.extend(content); + object(properties) + }) + .collect(); + json!({ "oneOf": branches }) +} + +pub(super) fn nullable(inner: Value) -> Value { + json!({ "oneOf": [inner, {"type": "null"}] }) +} + +pub(super) fn list(inner: Value) -> Value { + json!({"type": "array", "items": inner}) +} + +/// `{"ref": "draft"|"existing", "value": }` — +/// Invariant 1 rendered as a schema, and the only reference shape either +/// catalog emits. +pub(super) fn reference(referent: &str) -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["ref", "value"], + "properties": { + "ref": {"type": "string", "enum": ["draft", "existing"]}, + "value": { + "type": "string", + "description": format!( + "a draft handle declared in this same patch, or the canonical id of an existing {referent}" + ), + }, + }, + }) +} + +/// An adjacently tagged sum: `{"": "", "": }`. +/// A variant with no payload omits the content field entirely, which is what +/// serde emits for a unit variant in an adjacently tagged enum. +pub(super) fn variant_content(tag: &str, content: &str, variants: Vec<(&str, Value)>) -> Value { + let branches: Vec = variants + .into_iter() + .map(|(name, payload)| { + object(vec![ + (tag.to_owned(), json!({"const": name})), + (content.to_owned(), payload), + ]) + }) + .collect(); + json!({ "oneOf": branches }) +} + +/// An externally tagged sum: a bare string for a unit variant, or a +/// single-key object for one that carries a payload. +pub(super) fn external_variant(variants: Vec<(&str, Option)>) -> Value { + let branches: Vec = variants + .into_iter() + .map(|(name, payload)| match payload { + None => json!({"const": name}), + Some(inner) => object(vec![(name.to_owned(), inner)]), + }) + .collect(); + json!({ "oneOf": branches }) +}