diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs index 89f5d03..acfbd67 100644 --- a/crates/ghostlight-dungeon/src/eve.rs +++ b/crates/ghostlight-dungeon/src/eve.rs @@ -103,10 +103,62 @@ fn anonymous_surface_at(version: u64) -> Value { /// `operator_log` arrives beside the snapshot rather than inside it: the story /// feed is the human operator's surface, and no subject-facing lane may reach an /// unscoped event log. +/// The scheduler's compute budget and what the last tick's cover did with it. +/// Rendered read-only, with no command anywhere: an Eve control to change it +/// would make a projection an owner. Change is a restart, like the model names. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CoverPanel { + pub(crate) cells: u16, + pub(crate) constituent_cap: u16, + pub(crate) urgency_slots: u16, + /// `None` until the first tick has run. + pub(crate) last: Option, +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct CoverPanelTick { + pub(crate) tick: u64, + pub(crate) cells: usize, + pub(crate) singletons: usize, + pub(crate) groups: usize, + pub(crate) oversubscribed: bool, +} + +fn cover_card(panel: &CoverPanel) -> Value { + let detail = match panel.last { + None => "No tick has run yet.".to_owned(), + Some(last) => format!( + "Tick {}: {} cells, {} in detail, {} coarse.{}", + last.tick, + last.cells, + last.singletons, + last.groups, + if last.oversubscribed { + " The world has outgrown the constituent cap; the cap yielded so every subject stayed covered." + } else { + "" + } + ), + }; + json!({ + "id":"world.cover", + "kind":"card", + "props":{ + "title":"Attention budget", + "detail":detail, + "cellBudget":panel.cells, + "constituentCap":panel.constituent_cap, + "urgencySlots":panel.urgency_slots + }, + "children":[] + }) +} + pub(crate) fn authenticated_surface( account: &str, snapshot: Option<&WorldSnapshot>, operator_log: &[OperatorEvent], + cover: &CoverPanel, ) -> anyhow::Result { let version = surface_version(snapshot); let mut children = vec![json!({ @@ -322,6 +374,7 @@ pub(crate) fn authenticated_surface( } if world.owner == crate::world::PrincipalId::new(account) { + children.push(cover_card(cover)); let mut has_controller_command = false; for (index, opportunity) in world .opportunities @@ -537,6 +590,15 @@ fn short_principal(principal: &str) -> String { mod tests { use super::*; + fn fixture_cover() -> CoverPanel { + CoverPanel { + cells: 240, + constituent_cap: 24, + urgency_slots: 36, + last: None, + } + } + fn invocation(operation: &str, schema: &str, payload: Value) -> EveCommandInvocation { EveCommandInvocation { schema: "gamecult.eve.command_invocation.v1".into(), @@ -570,7 +632,7 @@ mod tests { #[test] fn empty_authenticated_surface_has_create_without_session_zero() { - let surface = authenticated_surface("sha256:owner", None, &[]).unwrap(); + let surface = authenticated_surface("sha256:owner", None, &[], &fixture_cover()).unwrap(); let encoded = serde_json::to_string(&surface).unwrap(); assert!(encoded.contains("world.create")); assert!(encoded.contains("narrative_persona_label")); diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 9c2fbc3..4972f25 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -10,11 +10,12 @@ use crate::{ }, mesh::{self, MeshPublisher, MeshRuntimeIdentity}, world::{ - AffordanceId, CommandBody, CommandId, ControllerError, ControllerModels, - ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent, - DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun, - OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition, - SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot, + AffordanceId, CellRun, CommandBody, CommandId, ControllerError, ControllerModels, + ControllerPendingReason, ControllerRunner, ControllerWorkCustody, Cover, CoverBudget, + CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, + NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, + SubmissionDisposition, SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot, + derive_cover, }, }; use anyhow::{Context, bail, ensure}; @@ -36,8 +37,18 @@ use cultnet_rs::{ }; use serde::Deserialize; use serde_json::{Value, json}; -use std::{convert::Infallible, fs, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration}; -use tokio::sync::{Mutex, broadcast, mpsc}; +use std::{ + convert::Infallible, + fs, + net::SocketAddr, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; +use tokio::sync::{Mutex, Semaphore, broadcast, mpsc}; use tower_http::services::ServeDir; use tracing_subscriber::EnvFilter; @@ -53,7 +64,20 @@ struct RuntimeHealthOwner { #[derive(Clone)] struct AppState { world: WorldMailbox, - controllers: Arc>>, + /// The one cognition organ, shared. Concurrency is owned by + /// `controller_permits` and quarantine by `controller_quarantined`: an + /// exclusive lock here would be a second owner of both, and a tick spends a + /// budget of inferences rather than one. + controllers: Option>, + controller_permits: Arc, + /// Set once a turn loses its local invariant. No further permit is granted; + /// in-flight turns finish or fail on their own bindings. + controller_quarantined: Arc, + cover_budget: CoverBudget, + /// Display-only, written by the tick driver and read by Eve and the mesh + /// projection. It decides nothing: the cover it summarises was derived, + /// used, and dropped before this was written. + cover: Arc>>, sessions: Arc>, heimdall: Arc, mesh: Option, @@ -63,6 +87,45 @@ struct AppState { fatal: mpsc::UnboundedSender, } +/// What one tick's cover looked like, for the operator surfaces. A projection +/// of a derived value, never an input to the next tick. +#[derive(Clone, Copy, Debug)] +struct CoverSummary { + tick: u64, + cells: usize, + singletons: usize, + groups: usize, + oversubscribed: bool, +} + +/// The read-only projection of the budget and the last tick, for Eve. +async fn cover_panel(state: &AppState) -> eve::CoverPanel { + eve::CoverPanel { + cells: state.cover_budget.cells, + constituent_cap: state.cover_budget.constituent_cap, + urgency_slots: state.cover_budget.urgency_slots, + last: state.cover.lock().await.map(|summary| eve::CoverPanelTick { + tick: summary.tick, + cells: summary.cells, + singletons: summary.singletons, + groups: summary.groups, + oversubscribed: summary.oversubscribed, + }), + } +} + +impl CoverSummary { + fn of(cover: &Cover) -> Self { + Self { + tick: cover.tick.0, + cells: cover.cells.len(), + singletons: cover.singletons(), + groups: cover.groups(), + oversubscribed: cover.oversubscribed, + } + } +} + struct ProductionAdmission { health: RuntimePresencePublisher, write_lease: ProcessWriteLeaseGuard, @@ -211,9 +274,14 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( }; require_no_runtime_custody_failure(&mut fatal_events)?; let (revisions, _) = broadcast::channel(32); + let cover_budget = configured_cover_budget()?; let mut state = AppState { world, - controllers: Arc::new(Mutex::new(controllers)), + controllers: controllers.map(Arc::new), + controller_permits: Arc::new(Semaphore::new(configured_controller_concurrency())), + controller_quarantined: Arc::new(AtomicBool::new(false)), + cover_budget, + cover: Arc::new(Mutex::new(None)), sessions: Arc::new(Mutex::new(sessions)), heimdall, mesh, @@ -254,7 +322,7 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( _ => bail!("managed runtime health authority is partial"), }; tokio::spawn(maintain_mesh_projection(state.clone())); - tokio::spawn(advance_world_clock(state.clone())); + tokio::spawn(drive_cover_tick(state.clone(), configured_tick_interval())); tokio::spawn(elaborate_world(state.clone())); let app = app_router(state.clone(), web_root); tracing::info!(address = %bound_address, "Ghostlight Dungeon world owner serving"); @@ -452,10 +520,16 @@ async fn eve_surface( let Some(principal) = authenticated_principal(&headers, &state).await else { return Json(eve::anonymous_surface()).into_response(); }; + let panel = cover_panel(&state).await; match current_operator_view(&state) .await .and_then(|(snapshot, log)| { - eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref(), &log) + eve::authenticated_surface( + principal.account_subject_hash(), + snapshot.as_ref(), + &log, + &panel, + ) }) { Ok(surface) => Json(surface).into_response(), Err(error) => ( @@ -857,11 +931,11 @@ async fn dispatch_controller( } }; - // Keep the sole runner borrowed from its availability slot for the full - // turn. Quarantine therefore has a clean edge: no second runner can cross - // another provider boundary after this one loses its local invariant. - let mut controller_slot = state.controllers.lock().await; - let Some(controller) = controller_slot.as_ref() else { + let available = state + .controllers + .as_ref() + .filter(|_| !state.controller_quarantined.load(Ordering::SeqCst)); + let Some(controller) = available else { return Json(eve::command_result( &invocation, "unknown", @@ -875,6 +949,9 @@ async fn dispatch_controller( )) .into_response(); }; + // One permit for the whole turn, from the same pool the tick driver spends. + // There is no second concurrency owner. + let permit = state.controller_permits.clone().acquire_owned().await; let result = match opportunity.controller_mode { crate::world::ControllerMode::NarrativePersona => controller .run_narrative(command_id, &opportunity) @@ -886,6 +963,7 @@ async fn dispatch_controller( .map(controller_operational_result), crate::world::ControllerMode::Human => unreachable!("human opportunity was not admitted"), }; + drop(permit); let quarantine = match &result { Ok(ControllerHttpResult::Pending { quarantine, .. }) => *quarantine, Ok(ControllerHttpResult::Completed { .. }) => false, @@ -893,9 +971,8 @@ async fn dispatch_controller( }; if quarantine { tracing::error!("controller cognition quarantined after losing its local invariant"); - controller_slot.take(); + state.controller_quarantined.store(true, Ordering::SeqCst); } - drop(controller_slot); match result { Ok(ControllerHttpResult::Completed { @@ -1409,20 +1486,23 @@ async fn runtime_readiness(state: &AppState) -> anyhow::Result { }, None => "unavailable", }; - let controller_status = match state.controllers.try_lock() { - Ok(slot) => match slot.as_ref() { - Some(controller) => { - match tokio::time::timeout(Duration::from_millis(100), controller.custody_probe()) - .await - { - Ok(Ok(ControllerWorkCustody::Owned { .. })) => "ok", - Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => "degraded", - Err(_) => "busy", + let controller_status = match state.controllers.as_deref() { + _ if state.controller_quarantined.load(Ordering::SeqCst) => "unavailable", + Some(controller) => { + match tokio::time::timeout(Duration::from_millis(100), controller.custody_probe()).await + { + Ok(Ok(ControllerWorkCustody::Owned { .. })) => { + if state.controller_permits.available_permits() == 0 { + "active" + } else { + "ok" + } } + Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => "degraded", + Err(_) => "busy", } - None => "unavailable", - }, - Err(_) => "active", + } + None => "unavailable", }; health["projectionStatus"] = Value::String(projection_status.into()); health["controllerStatus"] = Value::String(controller_status.into()); @@ -1480,11 +1560,12 @@ async fn elaborate_world(state: AppState) { 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 { + let Some(runner) = state + .controllers + .as_deref() + .filter(|_| !state.controller_quarantined.load(Ordering::SeqCst)) + .map(ControllerRunner::elaborator) + else { continue; }; if let Err(error) = runner.sweep().await { @@ -1493,21 +1574,136 @@ async fn elaborate_world(state: AppState) { } } -/// The world clock's only driver. -async fn advance_world_clock(state: AppState) { +/// The compute budget, read at open exactly as the model names are. It is not +/// world data and does not live beside `WorldScaleIntent`, which is the authored +/// target count of goal-bearing subjects: the two are numerically related and +/// have different owners. Changing either number is a restart. +fn configured_cover_budget() -> anyhow::Result { + let read = |name: &str, default: u16| -> u16 { + std::env::var(name) + .ok() + .and_then(|value| value.trim().parse().ok()) + .unwrap_or(default) + }; + CoverBudget { + cells: read("GHOSTLIGHT_COVER_CELL_BUDGET", 240), + constituent_cap: read("GHOSTLIGHT_COVER_CONSTITUENT_CAP", 24), + urgency_slots: read("GHOSTLIGHT_COVER_URGENCY_SLOTS", 36), + } + .validated() + .context("cover budget configuration is not usable") +} + +/// Sized to the connector's per-caller quota. `Capacity` and `InFlight` +/// refusals are already retryable faults, so a pool above that quota degrades +/// to retry rather than to corruption. +fn configured_controller_concurrency() -> usize { + std::env::var("GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .filter(|value| *value >= 1) + .unwrap_or(4) +} + +fn configured_tick_interval() -> Duration { + std::env::var("GHOSTLIGHT_TICK_INTERVAL_SECONDS") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .filter(|value| *value >= 1) + .map_or(CLOCK_TICK_INTERVAL, Duration::from_secs) +} + +/// The world's only driver: one owner of the tick's cadence, of the cover, and +/// of the clock. It derives a cover from one snapshot, runs each cell under a +/// permit, and then advances the clock — after the cells, so every cell in a +/// tick sees the same `now` and therefore the same tick index, which is what +/// makes the derived command ids stable and the rotation phase well defined. +/// +/// The kernel learns one `AdvanceTime` and `0..N` ordinary one-opportunity +/// submissions. It never learns a tick happened. +async fn drive_cover_tick(state: AppState, interval: Duration) { let Some(minutes) = TickMinutes::new(CLOCK_TICK_MINUTES) else { tracing::error!("the configured clock tick is outside one year of minutes"); return; }; - let mut interval = tokio::time::interval(CLOCK_TICK_INTERVAL); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - interval.tick().await; + let mut ticker = tokio::time::interval(interval); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + ticker.tick().await; loop { - interval.tick().await; + ticker.tick().await; + run_cover_tick(&state).await; submit_clock_tick(minutes, |id, minutes| state.world.submit_clock(id, minutes)).await; + if let Err(error) = publish_projection(&state).await { + tracing::debug!(%error, "world revision could not be read after a tick"); + } } } +/// One tick's cognition, apart from the clock and the wall clock that decides +/// when to run it. +async fn run_cover_tick(state: &AppState) { + let Some(runner) = state.controllers.clone() else { + return; + }; + if state.controller_quarantined.load(Ordering::SeqCst) { + return; + } + let (Ok(snapshot), Ok(graph)) = ( + state.world.snapshot().await, + state.world.agency_graph().await, + ) else { + return; + }; + let cover = derive_cover( + snapshot.world_id, + snapshot.now, + CLOCK_TICK_MINUTES, + &snapshot.opportunities, + &graph, + state.cover_budget, + ); + *state.cover.lock().await = Some(CoverSummary::of(&cover)); + + let mut running = tokio::task::JoinSet::new(); + for cell in cover.cells { + let runner = runner.clone(); + let permits = state.controller_permits.clone(); + let quarantined = state.controller_quarantined.clone(); + running.spawn(async move { + // Quarantine has a clean edge: no permit is granted after the flag + // is set, and turns already holding one finish on their own + // bindings. + if quarantined.load(Ordering::SeqCst) { + return; + } + let Ok(_permit) = permits.acquire().await else { + return; + }; + match runner.run_cell(&cell).await { + Ok(run) => { + if let CellRun::Grouped(grouped) = &run + && let Some(reason) = grouped.pending + { + tracing::debug!(?reason, "a coarse cell did not finish its submissions"); + } + } + Err(error) => { + // A cell that faults does not abort the tick. Custody loss + // does: the work journal is one lock and one custody claim, + // so it is a tick-level outcome rather than a per-cell one. + if error.requires_quarantine() { + tracing::error!(%error, "controller cognition quarantined mid-tick"); + quarantined.store(true, Ordering::SeqCst); + } else { + tracing::debug!(%error, "a cell did not complete this tick"); + } + } + } + }); + } + while running.join_next().await.is_some() {} +} + async fn revision_events(State(state): State) -> impl IntoResponse { let mut revisions = state.revisions.subscribe(); let stream = async_stream::stream! { @@ -1848,6 +2044,10 @@ fn sibling_state_lock_path(path: &std::path::Path) -> PathBuf { #[cfg(test)] mod tests { use super::*; + + /// Small enough that a test can hold every permit and prove a route does + /// not cross the provider boundary. + const TEST_CONTROLLER_CONCURRENCY: usize = 2; use crate::idunn_health::tests::route_observation_fixture; use axum::{ body::{Body, to_bytes}, @@ -1982,7 +2182,15 @@ mod tests { let (fatal, _fatal_events) = mpsc::unbounded_channel(); let state = AppState { world, - controllers: Arc::new(Mutex::new(Some(controllers))), + controllers: Some(Arc::new(controllers)), + controller_permits: Arc::new(Semaphore::new(TEST_CONTROLLER_CONCURRENCY)), + controller_quarantined: Arc::new(AtomicBool::new(false)), + cover_budget: CoverBudget { + cells: 240, + constituent_cap: 24, + urgency_slots: 36, + }, + cover: Arc::new(Mutex::new(None)), sessions: Arc::new(Mutex::new(sessions)), heimdall: Arc::new(HeimdallClient::fixture()), mesh: Some(mesh), @@ -2111,11 +2319,14 @@ mod tests { write_lease: Arc::new(health.write_lease), }); - // If this route enters the controller/provider boundary, the held lock - // makes the request time out. Route admission and signing need only the - // canonical health owner and managed runtime authority. - let controllers = fixture.state.controllers.clone(); - let _provider_execution_barrier = controllers.lock().await; + // If this route enters the controller/provider boundary, the exhausted + // permit pool makes the request time out. Route admission and signing + // need only the canonical health owner and managed runtime authority. + let permits = fixture.state.controller_permits.clone(); + let _provider_execution_barrier = permits + .acquire_many(u32::try_from(TEST_CONTROLLER_CONCURRENCY).expect("a small pool")) + .await + .expect("the controller permit pool is open"); let response = tokio::time::timeout( Duration::from_secs(2), api_router(fixture.state.clone()).oneshot(request( diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index b3469ea..8fdf30f 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -11,12 +11,13 @@ use super::elaboration::{ }; use super::tool_schema; use crate::world::{ - AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, Confidence, - ControllerMode, ControllerPort, Cost, DecisionInvocation, DecisionOpportunity, - DependencyTarget, EdgeId, ElaborationPort, EntityId, EntityKind, FactStandingView, KernelError, - KnowledgeSnapshot, KnowledgeSource, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, - Quantity, RefKind, RoleBinding, Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, - WorldMailbox, WorldSnapshot, + AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, Cell, CellId, CommandId, + CommitReceipt, Confidence, Constituent, ControllerMode, ControllerPort, Cost, + DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, ElaborationPort, EntityId, + EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude, + MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding, + Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, TickIndex, WorldMailbox, + WorldSnapshot, }; use async_trait::async_trait; use chrono::Utc; @@ -28,17 +29,17 @@ use codex_connector::{ }; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use ghostlight_persona_projection::{ - CaptureToolFeedback, InterpretationAccumulator, InterpretationFinalization, - InterpretationReport, InterpreterPrompt, OperationalAgentPrompt, PersonaPrompt, PersonaTurn, - PersonaTurnBinding, ProjectorPrompt, RecordGapToolCall, TranslationGapKind, - build_interpreter_prompt, build_operational_agent_prompt, build_persona_prompt, - build_projector_prompt, sha256, + CaptureToolFeedback, GroupedAgentPrompt, InterpretationAccumulator, InterpretationFinalization, + InterpretationReport, InterpreterPrompt, LabeledView, OperationalAgentPrompt, PersonaPrompt, + PersonaTurn, PersonaTurnBinding, ProjectorPrompt, RecordGapToolCall, TranslationGapKind, + build_grouped_agent_prompt, build_interpreter_prompt, build_operational_agent_prompt, + build_persona_prompt, build_projector_prompt, sha256, }; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, net::SocketAddr, path::Path, sync::{Arc, Mutex}, @@ -50,9 +51,17 @@ use zeroize::Zeroizing; const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; const REQUEST_EXPIRY: Duration = Duration::from_secs(300); const TOOL_STEP_BUDGET: usize = 4; +/// The grouped protocol asks for every call in one round, so this budget buys +/// exactly one repair round after decode gaps are reported back. It deliberately +/// does not scale with the cell: a cell that needs three rounds of repair is a +/// cell that should have been smaller. +const CELL_TOOL_STEP_BUDGET: usize = 2; +/// Separates a constituent handle from the tool it names. Attribution is +/// carried by tool identity, never by a model-written argument. +const HANDLE_SEPARATOR: &str = "__"; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v7"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v7"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v8"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v8"; /// 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 @@ -76,6 +85,11 @@ pub(crate) enum InferencePurpose { Persona, Interpreter, OperationalAgent, + /// One inference over a cell's labeled constituent views. Distinct from + /// `OperationalAgent` so a grouped request's derived ids can never collide + /// with a detail turn's, and so the output budget and the parallel-call + /// shape a cell needs do not leak into the singleton path. + GroupedAgent, Elaboration, } @@ -354,6 +368,55 @@ fn unix_ms() -> Result { u64::try_from(millis).map_err(|_| InferenceFault::new("system time exceeds u64 milliseconds")) } +/// One constituent of a grouped cell, frozen at selection. It carries its own +/// opportunity, so its controller, scope, and authority are exactly what the +/// detail path would have submitted: grouping changes representation, never +/// authority. There is no `controller_mode` beside the opportunity's, because a +/// second copy of a digest-bound value is a value that can disagree. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ConstituentWork { + subject: SubjectId, + opportunity: DecisionOpportunity, + granted: Vec, + /// Derived from `(world, cell, subject, tick)`, so a resumed cell re-submits + /// the same id and the kernel answers from its idempotency ledger. + command_id: CommandId, +} + +/// One cell, one inference, one row. A third variant rather than a widened +/// pair: making the twelve singleton progression comparisons vector-wise for a +/// path that is always length one would buy nothing, and it would put the +/// batched prompt in the same type as the byte-identical singleton one. +/// +/// There is no persisted per-constituent outcome. The submission loop is +/// idempotent by construction — every constituent's command id is derived, and +/// `submit_controller_world` probes the kernel's receipt before committing — so +/// a resumed `Submitting` re-runs the loop and the ledger answers with the +/// original receipts. A stored outcome would be a second, weaker record of what +/// the ledger already owns. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "stage", rename_all = "snake_case")] +enum GroupedCheckpoint { + AgentInFlight { + command_id: CommandId, + cell: CellId, + tick: TickIndex, + agent_prompt: String, + constituents: Vec, + completed: Vec, + invocation: PreparedInference, + }, + Submitting { + command_id: CommandId, + cell: CellId, + tick: TickIndex, + agent_prompt: String, + constituents: Vec, + completed: Vec, + }, +} + /// One command has one durable tagged cognition checkpoint. Every in-flight /// variant owns the exact connector invocation before transport; terminal /// variants retain completed provider outputs so their capture is derived, @@ -363,6 +426,10 @@ fn unix_ms() -> Result { pub(super) enum ControllerWork { Narrative(NarrativeCheckpoint), Operational(OperationalCheckpoint), + /// One coarse cell's cognition. The only durable trace a cover leaves, and + /// it lives in the controller-work store, whose custody is separate from + /// world custody: representation is cognition evidence, not world truth. + Grouped(GroupedCheckpoint), /// The authoring lane. One store, one custody probe, one progression check: /// forking them would buy nothing and split one authority in three. Elaboration(ElaborationCheckpoint), @@ -375,6 +442,7 @@ pub(super) enum ControllerWork { pub(crate) enum WorkLane { Narrative, Operational, + Grouped, Elaboration, } @@ -458,6 +526,7 @@ impl ControllerWork { match self { Self::Narrative(checkpoint) => checkpoint.command_id(), Self::Operational(checkpoint) => checkpoint.command_id(), + Self::Grouped(checkpoint) => checkpoint.command_id(), Self::Elaboration(checkpoint) => checkpoint.command_id(), } } @@ -466,14 +535,29 @@ impl ControllerWork { match self { Self::Narrative(_) => WorkLane::Narrative, Self::Operational(_) => WorkLane::Operational, + Self::Grouped(_) => WorkLane::Grouped, Self::Elaboration(_) => WorkLane::Elaboration, } } + /// How the subjects in this row were represented. Derived from the row's + /// own shape rather than stored beside it: a persisted copy would be a + /// second spelling of `constituents.len()` that could disagree with it. + #[cfg_attr(not(test), expect(dead_code, reason = "read by the resolution test"))] + fn resolution(&self) -> Resolution { + match self { + Self::Narrative(_) | Self::Operational(_) | Self::Elaboration(_) => Resolution::Detail, + Self::Grouped(checkpoint) => Resolution::Coarse { + constituents: checkpoint.constituents().len(), + }, + } + } + fn is_initial(&self) -> bool { match self { Self::Narrative(NarrativeCheckpoint::Projector { .. }) => true, - Self::Operational(OperationalCheckpoint::AgentInFlight { completed, .. }) => { + Self::Operational(OperationalCheckpoint::AgentInFlight { completed, .. }) + | Self::Grouped(GroupedCheckpoint::AgentInFlight { completed, .. }) => { completed.is_empty() } Self::Elaboration(ElaborationCheckpoint::ElaboratorInFlight { @@ -489,6 +573,7 @@ impl ControllerWork { match self { Self::Narrative(checkpoint) => checkpoint.integrity_is_valid(), Self::Operational(checkpoint) => checkpoint.integrity_is_valid(), + Self::Grouped(checkpoint) => checkpoint.integrity_is_valid(), Self::Elaboration(checkpoint) => checkpoint.integrity_is_valid(), } } @@ -730,6 +815,95 @@ impl OperationalCheckpoint { } } +impl GroupedCheckpoint { + fn command_id(&self) -> CommandId { + match self { + Self::AgentInFlight { command_id, .. } | Self::Submitting { command_id, .. } => { + *command_id + } + } + } + + fn cell(&self) -> CellId { + match self { + Self::AgentInFlight { cell, .. } | Self::Submitting { cell, .. } => *cell, + } + } + + fn constituents(&self) -> &[ConstituentWork] { + match self { + Self::AgentInFlight { constituents, .. } | Self::Submitting { constituents, .. } => { + constituents + } + } + } + + fn integrity_is_valid(&self) -> bool { + let (agent_prompt, constituents, completed) = match self { + Self::AgentInFlight { + agent_prompt, + constituents, + completed, + .. + } + | Self::Submitting { + agent_prompt, + constituents, + completed, + .. + } => (agent_prompt, constituents, completed), + }; + if !cell_constituents_are_valid(constituents) || agent_prompt.is_empty() { + return false; + } + match self { + Self::AgentInFlight { + command_id, + invocation, + .. + } => { + canonical_model(&invocation.invocation.request.model) + && match evaluate_grouped_loop(agent_prompt, constituents, completed) { + Ok(GroupedLoopEvaluation::Continue { conversation }) => grouped_request( + *command_id, + completed.len(), + &invocation.invocation.request.model, + constituents, + conversation, + ) + .is_ok_and(|expected| { + prepared_matches_request( + invocation, + &expected, + *command_id, + completed.len(), + ) + }), + Ok(GroupedLoopEvaluation::Complete { .. }) | Err(_) => false, + } + } + Self::Submitting { .. } => { + derive_grouped_capture(agent_prompt, constituents, completed).is_ok() + } + } + } +} + +/// A cell's constituents are ascending, distinct, non-empty, each holding +/// exactly what its own opportunity grants, and each an inference rather than a +/// human turn. A duplicate subject would make one handle able to submit twice. +fn cell_constituents_are_valid(constituents: &[ConstituentWork]) -> bool { + !constituents.is_empty() + && constituents + .windows(2) + .all(|pair| pair[0].subject < pair[1].subject) + && constituents.iter().all(|entry| { + entry.subject == entry.opportunity.scope.subject_id + && entry.opportunity.controller_mode != ControllerMode::Human + && granted_matches_opportunity(&entry.granted, &entry.opportunity) + }) +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct NarrativeCapture { pub(crate) proposal: Option, @@ -758,6 +932,72 @@ pub(crate) struct OperationalCapture { pub(crate) inference_receipts: Vec, } +/// One opportunity's selection against one snapshot. +/// +/// The expected controller mode is read from the opportunity rather than +/// supplied by the caller. Representation and controller mode used to be the +/// same value here, which made a coarsely represented `NarrativePersona` +/// unrepresentable; the lane gate that still matters — whether this turn may +/// enter the Persona membrane — lives at the lane's own entry, where entering +/// the membrane is decided. +fn select_one( + snapshot: &WorldSnapshot, + exact_opportunity: &DecisionOpportunity, +) -> Result { + let expected = exact_opportunity.controller_mode; + let subject_id = exact_opportunity.scope.subject_id; + let Some(subject) = snapshot + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .cloned() + else { + return Err(ControllerError::NoOpportunity { expected }); + }; + if subject.controller_mode != expected { + return Err(ControllerError::NoOpportunity { expected }); + } + if exact_opportunity.controller_id != subject.controller_id { + return Err(ControllerError::OpportunityMismatch); + } + let matches = snapshot + .opportunities + .iter() + .filter(|opportunity| { + opportunity.scope == exact_opportunity.scope + && opportunity.scope_digest == exact_opportunity.scope_digest + }) + .cloned() + .collect::>(); + let [opportunity] = matches.as_slice() else { + return if matches.is_empty() { + Err(ControllerError::NoOpportunity { expected }) + } else { + Err(ControllerError::AmbiguousOpportunity) + }; + }; + let granted: Vec = snapshot + .affordances + .iter() + .filter(|entry| { + subject.affordances.contains(&entry.id) + && opportunity.affordance_ids.contains(&entry.id) + }) + .cloned() + .collect(); + if granted.is_empty() { + return Err(ControllerError::NoGrantedAffordance); + } + Ok(SelectedDecision { + snapshot: snapshot.clone(), + subject, + // The run's own bound value, not the fresh snapshot's: one run binds + // one opportunity, persists it, and submits it unchanged. + opportunity: exact_opportunity.clone(), + granted, + }) +} + fn base_checkpoint_is_valid( identity: &str, typed_view: &str, @@ -1187,6 +1427,9 @@ fn valid_controller_work_progression(existing: &ControllerWork, next: &Controlle (ControllerWork::Operational(existing), ControllerWork::Operational(next)) => { valid_operational_progression(existing, next) } + (ControllerWork::Grouped(existing), ControllerWork::Grouped(next)) => { + valid_grouped_progression(existing, next) + } (ControllerWork::Elaboration(existing), ControllerWork::Elaboration(next)) => { valid_elaboration_progression(existing, next) } @@ -1194,6 +1437,62 @@ fn valid_controller_work_progression(existing: &ControllerWork, next: &Controlle } } +/// The identity of a grouped row is frozen and its evidence only appends. The +/// constituent vector is part of that identity: a resumed cell may not gain, +/// lose, reorder, or re-permission a handle, because a handle is a position in +/// a prompt that has already been sent. +fn valid_grouped_progression(existing: &GroupedCheckpoint, next: &GroupedCheckpoint) -> bool { + let frozen = |left: &GroupedCheckpoint, right: &GroupedCheckpoint| { + let identity = |work: &GroupedCheckpoint| match work { + GroupedCheckpoint::AgentInFlight { + command_id, + cell, + tick, + agent_prompt, + constituents, + .. + } + | GroupedCheckpoint::Submitting { + command_id, + cell, + tick, + agent_prompt, + constituents, + .. + } => ( + *command_id, + *cell, + *tick, + agent_prompt.clone(), + constituents.clone(), + ), + }; + identity(left) == identity(right) + }; + fn completed(work: &GroupedCheckpoint) -> &[InferenceOutput] { + match work { + GroupedCheckpoint::AgentInFlight { completed, .. } + | GroupedCheckpoint::Submitting { completed, .. } => completed.as_slice(), + } + } + if !frozen(existing, next) { + return false; + } + match (existing, next) { + ( + GroupedCheckpoint::AgentInFlight { .. }, + GroupedCheckpoint::AgentInFlight { .. } | GroupedCheckpoint::Submitting { .. }, + ) => completed_advances(completed(existing), completed(next)), + // Submitting is terminal: the submission loop replays against the + // kernel's ledger rather than advancing a persisted outcome, so the row + // never changes again and never regresses to another inference. + (GroupedCheckpoint::Submitting { .. }, GroupedCheckpoint::Submitting { .. }) => { + completed(existing) == completed(next) + } + (GroupedCheckpoint::Submitting { .. }, GroupedCheckpoint::AgentInFlight { .. }) => false, + } +} + fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeCheckpoint) -> bool { match (existing, next) { ( @@ -1623,6 +1922,36 @@ pub(crate) enum OperationalRun { Pending(OperationalPending), } +/// What one cell's run produced. A singleton delegates to the lane its +/// subject's controller mode names, and its outcome is that lane's own: the +/// detail path is not wrapped, re-shaped, or summarised. +#[derive(Debug)] +pub(crate) enum CellRun { + Narrative(NarrativeRun), + Operational(OperationalRun), + Grouped(GroupedRun), +} + +#[derive(Debug)] +pub(crate) struct ConstituentSubmission { + pub(crate) subject: SubjectId, + pub(crate) submission: SubmissionDisposition, +} + +/// One coarse cell's outcome: one inference, N ordinary one-opportunity +/// submissions, and whatever the decode could not attribute. +#[derive(Debug)] +pub(crate) struct GroupedRun { + pub(crate) cell: CellId, + pub(crate) resolution: Resolution, + pub(crate) submissions: Vec, + pub(crate) needs: Vec, + /// Set when the run stopped before every constituent was submitted. The + /// constituents already in `submissions` are committed; the rest resume from + /// the persisted row against the kernel's idempotency ledger. + pub(crate) pending: Option, +} + #[derive(Debug)] pub(crate) struct OperationalPending { work: OperationalCheckpoint, @@ -1793,6 +2122,14 @@ impl ControllerRunner { command_id: CommandId, opportunity: &DecisionOpportunity, ) -> Result { + // The lane gate, where entering the Persona membrane is decided. It is + // not `select`'s job: `select` proves the opportunity is live, and this + // proves this lane may run it. Grouping never reaches here. + if opportunity.controller_mode != ControllerMode::NarrativePersona { + return Err(ControllerError::NoOpportunity { + expected: ControllerMode::NarrativePersona, + }); + } match self.work.lookup(command_id).await? { ControllerWorkLookup::Confirmed(ControllerWork::Narrative(checkpoint)) => { if !binds_same_scope(checkpoint.opportunity(), opportunity) { @@ -1812,22 +2149,20 @@ impl ControllerRunner { )); } ControllerWorkLookup::Confirmed( - ControllerWork::Operational(_) | ControllerWork::Elaboration(_), + ControllerWork::Operational(_) + | ControllerWork::Grouped(_) + | ControllerWork::Elaboration(_), ) | ControllerWorkLookup::CustodyUncertain( - ControllerWork::Operational(_) | ControllerWork::Elaboration(_), + ControllerWork::Operational(_) + | ControllerWork::Grouped(_) + | ControllerWork::Elaboration(_), ) => { return Err(ControllerError::CommandMismatch); } ControllerWorkLookup::Missing => {} } - let selected = self - .select( - opportunity.scope.subject_id, - ControllerMode::NarrativePersona, - opportunity, - ) - .await?; + let selected = self.select(opportunity).await?; let identity = selected.subject.label.clone(); let typed_view = selected.typed_view()?; let projector_context = selected.projector_context()?; @@ -1872,6 +2207,14 @@ impl ControllerRunner { command_id: CommandId, opportunity: &DecisionOpportunity, ) -> Result { + // The detail operational lane runs a subject the world assigned to an + // operational agent. A coarsely represented `NarrativePersona` goes + // through the grouped lane, never through this one. + if opportunity.controller_mode != ControllerMode::OperationalAgent { + return Err(ControllerError::NoOpportunity { + expected: ControllerMode::OperationalAgent, + }); + } match self.work.lookup(command_id).await? { ControllerWorkLookup::Confirmed(ControllerWork::Operational(checkpoint)) => { if !binds_same_scope(checkpoint.opportunity(), opportunity) { @@ -1891,28 +2234,26 @@ impl ControllerRunner { )); } ControllerWorkLookup::Confirmed( - ControllerWork::Narrative(_) | ControllerWork::Elaboration(_), + ControllerWork::Narrative(_) + | ControllerWork::Grouped(_) + | ControllerWork::Elaboration(_), ) | ControllerWorkLookup::CustodyUncertain( - ControllerWork::Narrative(_) | ControllerWork::Elaboration(_), + ControllerWork::Narrative(_) + | ControllerWork::Grouped(_) + | ControllerWork::Elaboration(_), ) => { return Err(ControllerError::CommandMismatch); } ControllerWorkLookup::Missing => {} } - let selected = self - .select( - opportunity.scope.subject_id, - ControllerMode::OperationalAgent, - opportunity, - ) - .await?; + let selected = self.select(opportunity).await?; let identity = selected.subject.label.clone(); let typed_view = selected.typed_view()?; let agent_prompt = build_operational_agent_prompt(&OperationalAgentPrompt { identity: &identity, typed_view: &typed_view, - available_tools: &catalog_signatures(&selected.granted), + available_tools: &catalog_signatures("", &selected.granted), decision_pressure: "Choose whether this decision owner should speak now.", domain_guidance: "", step_budget: TOOL_STEP_BUDGET, @@ -2071,6 +2412,388 @@ impl ControllerRunner { } } } + /// One cell's cognition. It receives a `&Cell` and never a `Cover`: it + /// cannot see other cells, the budget, or the agency graph, and the tick + /// index reaches it only as an opaque value threaded into id derivation. + pub(crate) async fn run_cell(&self, cell: &Cell) -> Result { + match cell { + Cell::Singleton { id, tick, member } => { + // The driver's singleton turn takes a derived id, so it is as + // replayable as its grouped ones. The operator's manual button + // keeps issuing a fresh id, and that is correct: a manual turn + // is not part of a replayable tick. + let command_id = CommandId::for_cell_constituent( + member.opportunity.world_id, + *id, + member.subject, + *tick, + ); + match member.opportunity.controller_mode { + ControllerMode::NarrativePersona => self + .run_narrative(command_id, &member.opportunity) + .await + .map(CellRun::Narrative), + ControllerMode::OperationalAgent => self + .run_operational(command_id, &member.opportunity) + .await + .map(CellRun::Operational), + ControllerMode::Human => Err(ControllerError::NoOpportunity { + expected: ControllerMode::OperationalAgent, + }), + } + } + Cell::Group { id, tick, members } => self + .run_group(*id, *tick, members) + .await + .map(CellRun::Grouped), + } + } + + async fn run_group( + &self, + cell: CellId, + tick: TickIndex, + members: &[Constituent], + ) -> Result { + let Some(first) = members.first() else { + return Err(ControllerError::NoOpportunity { + expected: ControllerMode::OperationalAgent, + }); + }; + let world_id = first.opportunity.world_id; + let command_id = CommandId::for_cell(world_id, cell, tick); + match self.work.lookup(command_id).await? { + ControllerWorkLookup::Confirmed(ControllerWork::Grouped(checkpoint)) => { + if checkpoint.cell() != cell { + return Err(ControllerError::OpportunityMismatch); + } + return self.resume_persisted_group(command_id, checkpoint).await; + } + ControllerWorkLookup::CustodyUncertain(ControllerWork::Grouped(checkpoint)) => { + if checkpoint.cell() != cell { + return Err(ControllerError::OpportunityMismatch); + } + return Ok(grouped_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + ControllerWorkLookup::Confirmed( + ControllerWork::Narrative(_) + | ControllerWork::Operational(_) + | ControllerWork::Elaboration(_), + ) + | ControllerWorkLookup::CustodyUncertain( + ControllerWork::Narrative(_) + | ControllerWork::Operational(_) + | ControllerWork::Elaboration(_), + ) => { + return Err(ControllerError::CommandMismatch); + } + ControllerWorkLookup::Missing => {} + } + + // One snapshot for the whole cell, and no mid-stage rechecks. The detail + // lanes' per-stage recheck is an early exit, not a correctness gate: the + // scope digest is re-derived at admission, so a stale grouped proposal is + // refused with an honest `ScopeChanged` rather than committed. + let snapshot = self + .mailbox + .snapshot() + .await + .map_err(ControllerError::Snapshot)?; + let mut selected = Vec::new(); + let mut constituents = Vec::new(); + let mut needs = Vec::new(); + for member in members { + match select_one(&snapshot, &member.opportunity) { + Ok(decision) => { + constituents.push(ConstituentWork { + subject: member.subject, + opportunity: decision.opportunity.clone(), + granted: decision.granted.clone(), + command_id: CommandId::for_cell_constituent( + world_id, + cell, + member.subject, + tick, + ), + }); + selected.push(decision); + } + // A subject whose opportunity moved between the cover and the + // cell was not active when the cell ran. It is dropped rather + // than declined: declining a stale opportunity would be refused + // anyway, and the drop is recorded where a reader can see it. + Err(error) => needs.push(ControllerNeed { + detail: format!("a constituent left the cell before selection: {error}"), + }), + } + } + if constituents.is_empty() { + return Ok(GroupedRun { + cell, + resolution: Resolution::Coarse { constituents: 0 }, + submissions: Vec::new(), + needs, + pending: None, + }); + } + + let views = partitioned_views(&selected)?; + let labeled: Vec> = views + .iter() + .map(|view| LabeledView { + handle: &view.handle, + identity: &view.identity, + typed_view: &view.typed_view, + tool_signatures: &view.tool_signatures, + }) + .collect(); + let agent_prompt = build_grouped_agent_prompt(&GroupedAgentPrompt { + views: &labeled, + decision_pressure: "Choose whether each decision owner should act now.", + domain_guidance: "", + step_budget: CELL_TOOL_STEP_BUDGET, + }); + let initial_conversation = match evaluate_grouped_loop(&agent_prompt, &constituents, &[])? { + GroupedLoopEvaluation::Continue { conversation } => conversation, + GroupedLoopEvaluation::Complete { .. } => { + return Err(ControllerError::Serialization( + "empty grouped evidence unexpectedly finalized".into(), + )); + } + }; + let checkpoint = GroupedCheckpoint::AgentInFlight { + command_id, + cell, + tick, + agent_prompt, + completed: Vec::new(), + invocation: self.prepare(grouped_request( + command_id, + 0, + &self.models.operational_agent, + &constituents, + initial_conversation, + )?)?, + constituents, + }; + let mut run = if self + .persist(ControllerWork::Grouped(checkpoint.clone())) + .await? + == ControllerWorkWrite::CustodyUncertain + { + grouped_pending(checkpoint, ControllerPendingReason::StoreReopenRequired) + } else { + self.resume_persisted_group(command_id, checkpoint).await? + }; + // The constituents that left the cell are reported beside the run they + // were dropped from, not written into the row: they produced no + // cognition, so they are not cognition evidence. + run.needs.splice(0..0, needs); + Ok(run) + } + + async fn resume_persisted_group( + &self, + command_id: CommandId, + checkpoint: GroupedCheckpoint, + ) -> Result { + if checkpoint.command_id() != command_id { + return Err(ControllerError::CommandMismatch); + } + match checkpoint { + checkpoint @ GroupedCheckpoint::AgentInFlight { .. } => { + self.run_group_pending(checkpoint).await + } + checkpoint @ GroupedCheckpoint::Submitting { .. } => { + self.submit_group(checkpoint).await + } + } + } + + async fn run_group_pending( + &self, + mut checkpoint: GroupedCheckpoint, + ) -> Result { + loop { + let GroupedCheckpoint::AgentInFlight { + command_id, + cell, + tick, + agent_prompt, + constituents, + mut completed, + invocation, + } = checkpoint.clone() + else { + return Err(ControllerError::Serialization( + "grouped runner received a terminal checkpoint".into(), + )); + }; + let model = invocation.invocation.request.model.clone(); + let output = match self.infer(invocation).await { + Ok(output) => output, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(grouped_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + completed.push(output); + match evaluate_grouped_loop(&agent_prompt, &constituents, &completed) { + Ok(GroupedLoopEvaluation::Complete { .. }) => { + let next = GroupedCheckpoint::Submitting { + command_id, + cell, + tick, + agent_prompt, + constituents, + completed, + }; + if self.persist(ControllerWork::Grouped(next.clone())).await? + == ControllerWorkWrite::CustodyUncertain + { + return Ok(grouped_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + return self.submit_group(next).await; + } + Ok(GroupedLoopEvaluation::Continue { conversation }) => { + let round = completed.len(); + let next = GroupedCheckpoint::AgentInFlight { + command_id, + cell, + tick, + agent_prompt, + invocation: self.prepare(grouped_request( + command_id, + round, + &model, + &constituents, + conversation, + )?)?, + completed, + constituents, + }; + match self.persist(ControllerWork::Grouped(next.clone())).await? { + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => { + checkpoint = next; + } + ControllerWorkWrite::CustodyUncertain => { + return Ok(grouped_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + } + } + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(grouped_pending(checkpoint, reason)), + None => return Err(error), + }, + } + } + } + + /// One constituent at a time, in handle order, each through the same + /// `submit_controller_world` a detail turn uses. There is no batch command + /// body and no aggregate receipt: the only way a cell reaches the kernel is + /// one opportunity at a time, which is what keeps a cell-owned proposal + /// unrepresentable. + /// + /// A constituent that proposed nothing declines. Otherwise the world cannot + /// tell "was attended and stayed silent" from "was never attended", and the + /// resume path loses its only record that the turn finished. + async fn submit_group( + &self, + checkpoint: GroupedCheckpoint, + ) -> Result { + let GroupedCheckpoint::Submitting { + cell, + agent_prompt, + constituents, + completed, + .. + } = &checkpoint + else { + return Err(ControllerError::Serialization( + "grouped submission requires terminal controller work".into(), + )); + }; + if matches!( + self.work.custody_probe().await?, + ControllerWorkCustody::Uncertain { .. } + ) { + return Ok(grouped_pending( + checkpoint.clone(), + ControllerPendingReason::StoreReopenRequired, + )); + } + let capture = derive_grouped_capture(agent_prompt, constituents, completed)?; + let resolution = Resolution::Coarse { + constituents: constituents.len(), + }; + let mut needs = capture.needs; + let mut submissions = Vec::new(); + // Declines first. A decline changes no other subject's scope, so every + // silent constituent's turn is consumed. An exercise can change what its + // neighbours bound to, and co-located subjects are exactly + // the ones a connected cover groups. The kernel refuses a proposal + // reasoned from a scope that no longer holds. That refusal is the honest + // outcome; ordering the non-mutating submissions ahead of it loses no + // turns and costs nothing. + let mut ordered: Vec<(usize, &ConstituentWork)> = constituents.iter().enumerate().collect(); + ordered.sort_by_key(|(handle, _)| capture.proposals.contains_key(handle)); + for (handle, constituent) in ordered { + let command = match capture.proposals.get(&handle) { + Some(invocation) => ControllerWorldCommand::Exercise(invocation.clone()), + None => ControllerWorldCommand::Decline, + }; + match self + .submit_controller_world(constituent.command_id, &constituent.opportunity, command) + .await + { + Ok(ControllerWorldSubmission::Completed(submission)) => { + submissions.push(ConstituentSubmission { + subject: constituent.subject, + submission, + }); + } + Ok(ControllerWorldSubmission::Pending(reason)) => { + return Ok(GroupedRun { + cell: *cell, + resolution, + submissions, + needs, + pending: Some(reason), + }); + } + // One constituent's refusal is that constituent's outcome. The + // cell is not a transaction: every other handle's proposal was + // bound to its own opportunity and is unaffected. + Err(ControllerError::World(error)) => needs.push(ControllerNeed { + detail: format!("constituent c{handle} was refused by the world: {error}"), + }), + Err(error) => return Err(error), + } + } + submissions.sort_by_key(|entry| { + constituents + .iter() + .position(|constituent| constituent.subject == entry.subject) + .unwrap_or(usize::MAX) + }); + Ok(GroupedRun { + cell: *cell, + resolution, + submissions, + needs, + pending: None, + }) + } fn prepare(&self, request: InferenceRequest) -> Result { let purpose = request.purpose; @@ -2089,8 +2812,6 @@ impl ControllerRunner { async fn select( &self, - subject_id: SubjectId, - expected: ControllerMode, exact_opportunity: &DecisionOpportunity, ) -> Result { let snapshot = self @@ -2098,59 +2819,7 @@ impl ControllerRunner { .snapshot() .await .map_err(ControllerError::Snapshot)?; - let Some(subject) = snapshot - .subjects - .iter() - .find(|subject| subject.id == subject_id) - .cloned() - else { - return Err(ControllerError::NoOpportunity { expected }); - }; - if subject.controller_mode != expected { - return Err(ControllerError::NoOpportunity { expected }); - } - if exact_opportunity.scope.subject_id != subject.id - || exact_opportunity.controller_id != subject.controller_id - || exact_opportunity.controller_mode != expected - { - return Err(ControllerError::OpportunityMismatch); - } - let matches = snapshot - .opportunities - .iter() - .filter(|opportunity| { - opportunity.scope == exact_opportunity.scope - && opportunity.scope_digest == exact_opportunity.scope_digest - }) - .cloned() - .collect::>(); - let [opportunity] = matches.as_slice() else { - return if matches.is_empty() { - Err(ControllerError::NoOpportunity { expected }) - } else { - Err(ControllerError::AmbiguousOpportunity) - }; - }; - let granted: Vec = snapshot - .affordances - .iter() - .filter(|entry| { - subject.affordances.contains(&entry.id) - && opportunity.affordance_ids.contains(&entry.id) - }) - .cloned() - .collect(); - if granted.is_empty() { - return Err(ControllerError::NoGrantedAffordance); - } - Ok(SelectedDecision { - snapshot, - subject, - // The run's own bound value, not the fresh snapshot's: one run binds - // one opportunity, persists it, and submits it unchanged. - opportunity: exact_opportunity.clone(), - granted, - }) + select_one(&snapshot, exact_opportunity) } /// The scope this run bound still derives the same digest. A commit @@ -2159,13 +2828,7 @@ impl ControllerRunner { &self, opportunity: &DecisionOpportunity, ) -> Result<(), ControllerError> { - self.select( - opportunity.scope.subject_id, - opportunity.controller_mode, - opportunity, - ) - .await - .map(|_| ()) + self.select(opportunity).await.map(|_| ()) } async fn resume_persisted_narrative( @@ -3257,6 +3920,311 @@ fn evaluate_interpreter_loop( Ok(InterpreterLoopEvaluation::Continue { conversation }) } +/// One constituent's prompt block, owned so the borrow of the selection ends +/// before the prompt is built. +struct PartitionedView { + handle: String, + identity: String, + typed_view: String, + tool_signatures: String, +} + +/// Each block is the verbatim output of the same per-subject `typed_view()` the +/// detail path renders, under its own handle. There is no cross-resolution, no +/// merge, no dedup, and no shared header: a fact held under two handles appears +/// twice, and that duplication is the invariant. +fn partitioned_views( + selected: &[SelectedDecision], +) -> Result, ControllerError> { + selected + .iter() + .enumerate() + .map(|(handle, decision)| { + Ok(PartitionedView { + handle: format!("c{handle}"), + identity: decision.subject.label.clone(), + typed_view: decision.typed_view()?, + tool_signatures: catalog_signatures(&handle_prefix(handle), &decision.granted), + }) + }) + .collect() +} + +fn handle_prefix(handle: usize) -> String { + format!("c{handle}{HANDLE_SEPARATOR}") +} + +/// One tool set per constituent, name-namespaced, so an attributed proposal is +/// decided by which tool was called rather than by an argument the model writes. +/// A shared tool with a `subject` argument is the forgeable shape: it would let +/// one constituent's turn propose for another. +fn cell_catalog_tools(constituents: &[ConstituentWork]) -> Vec { + constituents + .iter() + .enumerate() + .flat_map(|(handle, entry)| catalog_tools(&handle_prefix(handle), &entry.granted)) + .collect() +} + +/// `c__`, with one spelling per handle: a padded, signed, or +/// non-numeric index is not a handle, and a handle outside the cell does not +/// exist. +fn split_handle(name: &str, constituents: usize) -> Option<(usize, &str)> { + let (prefix, tool) = name.split_once(HANDLE_SEPARATOR)?; + let digits = prefix.strip_prefix('c')?; + if digits.is_empty() || (digits.len() > 1 && digits.starts_with('0')) { + return None; + } + if !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let handle: usize = digits.parse().ok()?; + (handle < constituents).then_some((handle, tool)) +} + +/// The batched decode. Vector-valued by construction: the singleton evaluator +/// keeps its scalar proposal and is not touched. +struct GroupedCapture { + /// Handle to proposal. A handle absent here proposed nothing and declines. + proposals: BTreeMap, + needs: Vec, + inference_receipts: Vec, +} + +enum GroupedLoopEvaluation { + Continue { conversation: Vec }, + Complete { capture: GroupedCapture }, +} + +fn evaluate_grouped_loop( + prompt: &str, + constituents: &[ConstituentWork], + completed: &[InferenceOutput], +) -> Result { + let mut conversation = vec![CodexInputItem::UserText { + text: prompt.to_owned(), + }]; + let mut proposals: BTreeMap = BTreeMap::new(); + let mut terminal: BTreeSet = BTreeSet::new(); + let mut needs = Vec::new(); + let mut receipts = Vec::new(); + + 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::GroupedAgent, + 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: String = match split_handle(name, constituents.len()) { + // A model that writes `c99__carry` has not proposed + // anything. It has produced a gap. + None => { + needs.push(tool_decode_need( + name, + arguments, + "tool names no handle in this cell", + )); + "unattributable tool recorded as a need".into() + } + Some((handle, tool)) => { + let granted = &constituents[handle].granted; + let entry = granted.iter().find(|entry| entry.entry.kind.0 == tool); + match tool { + _ if entry.is_some() => { + if terminal.contains(&handle) { + needs.push(ControllerNeed { + detail: format!( + "Handle c{handle} was offered more than one terminal choice for one opportunity." + ), + }); + "one terminal choice is already captured for this handle" + .into() + } else { + match decode_catalog_call( + entry.expect("the entry matched above"), + arguments, + ) { + Ok(invocation) => { + proposals.insert(handle, invocation); + terminal.insert(handle); + "invocation captured".into() + } + Err(detail) => { + needs.push(tool_decode_need( + name, arguments, &detail, + )); + "arguments recorded as a need".into() + } + } + } + } + RECORD_NEED_TOOL => { + match serde_json::from_str::(arguments) { + Ok(call) => { + needs.push(ControllerNeed { + detail: format!("c{handle}: {}", call.detail), + }); + "need recorded".into() + } + Err(error) => { + needs.push(tool_decode_need( + name, + arguments, + &error.to_string(), + )); + "arguments recorded as a need".into() + } + } + } + FINISH_WITHOUT_PROPOSAL_TOOL => { + match serde_json::from_str::(arguments) { + Ok(_) if terminal.contains(&handle) => { + return Err(ControllerError::ProviderContract { + purpose: InferencePurpose::GroupedAgent, + detail: "finish_without_proposal contradicted an existing terminal choice".into(), + }); + } + Ok(_) => { + terminal.insert(handle); + "decision finished without a proposal".into() + } + Err(error) => { + needs.push(tool_decode_need( + name, + arguments, + &error.to_string(), + )); + "arguments recorded as a need".into() + } + } + } + _ => { + needs.push(tool_decode_need( + name, + arguments, + "tool is not available to this handle", + )); + "unavailable tool recorded as a need".into() + } + } + } + }; + conversation.push(CodexInputItem::ToolResult { + call_id: call_id.clone(), + output: result, + }); + } + } + } + + let is_complete = terminal.len() == constituents.len() + || !called_tool + || round + 1 == CELL_TOOL_STEP_BUDGET; + if is_complete { + if round + 1 != completed.len() { + return Err(ControllerError::Serialization( + "grouped evidence continued after total finalization".into(), + )); + } + if round + 1 == CELL_TOOL_STEP_BUDGET + && terminal.len() < constituents.len() + && called_tool + { + needs.push(ControllerNeed { + detail: "The grouped step budget ended before every handle finished.".into(), + }); + } + return Ok(GroupedLoopEvaluation::Complete { + capture: GroupedCapture { + proposals, + needs, + inference_receipts: receipts, + }, + }); + } + } + + if completed.len() >= CELL_TOOL_STEP_BUDGET { + return Err(ControllerError::Serialization( + "grouped evidence exceeded its step budget".into(), + )); + } + Ok(GroupedLoopEvaluation::Continue { conversation }) +} + +fn derive_grouped_capture( + prompt: &str, + constituents: &[ConstituentWork], + completed: &[InferenceOutput], +) -> Result { + match evaluate_grouped_loop(prompt, constituents, completed)? { + GroupedLoopEvaluation::Complete { capture } => Ok(capture), + GroupedLoopEvaluation::Continue { .. } => Err(ControllerError::Serialization( + "terminal grouped checkpoint has unfinished evidence".into(), + )), + } +} + +fn grouped_request( + command_id: CommandId, + round: usize, + model: &str, + constituents: &[ConstituentWork], + input: Vec, +) -> Result { + tool_request( + command_id, + round, + InferencePurpose::GroupedAgent, + model, + "Use only the supplied tools. Every tool belongs to exactly one handle, and calling one is how a proposal is attributed. Returning no proposal for a handle is valid.", + input, + cell_catalog_tools(constituents), + RequestShape { + // Output tokens, not the connector frame, are the real bound on a + // cell: one call per handle, plus its arguments. + max_output_tokens: 8_000 + .min(600 + 200 * u32::try_from(constituents.len()).unwrap_or(u32::MAX)), + // The grouped protocol asks for every call in one round, so the + // provider must be allowed to emit them together. + parallel_tool_calls: true, + }, + ) +} + +fn grouped_pending(checkpoint: GroupedCheckpoint, reason: ControllerPendingReason) -> GroupedRun { + GroupedRun { + cell: checkpoint.cell(), + resolution: Resolution::Coarse { + constituents: checkpoint.constituents().len(), + }, + submissions: Vec::new(), + needs: Vec::new(), + pending: Some(reason), + } +} enum OperationalLoopEvaluation { Continue { conversation: Vec }, Complete { capture: OperationalCapture }, @@ -3512,6 +4480,7 @@ fn interpreter_request( "Translate the preserved Persona prose using only the supplied capture tools. Untranslatable meaning is recorded, never repaired or rejected.", input, interpreter_tools(), + DECISION_REQUEST_SHAPE, ) } @@ -3529,10 +4498,27 @@ fn operational_request( model, "Use only the supplied tools for this permissioned decision. Returning no proposal is valid.", input, - catalog_tools(granted), + catalog_tools("", granted), + DECISION_REQUEST_SHAPE, ) } +/// The two knobs a request's *shape* needs beyond its tools: how much the +/// provider may write, and whether it may write more than one call at once. A +/// patch turn emits many calls where a decision turn emits one, and a cell emits +/// one per handle, so these belong to the caller rather than to one constant +/// shared by every catalog. +pub(super) struct RequestShape { + pub(super) max_output_tokens: u32, + pub(super) parallel_tool_calls: bool, +} + +/// One decision, one call: the shape both detail lanes have always had. +const DECISION_REQUEST_SHAPE: RequestShape = RequestShape { + max_output_tokens: 1_200, + parallel_tool_calls: false, +}; + pub(super) fn tool_request( command_id: CommandId, round: usize, @@ -3541,6 +4527,7 @@ pub(super) fn tool_request( instructions: &str, input: Vec, tools: Vec, + shape: RequestShape, ) -> Result { let mut provider = CodexProviderRequest::new( provider_request_id(command_id, purpose, round)?, @@ -3552,16 +4539,10 @@ pub(super) fn tool_request( provider.reasoning_effort = Some("medium".into()); provider.tools = tools; provider.tool_choice = CodexToolChoice::Auto; - provider.parallel_tool_calls = false; + provider.parallel_tool_calls = shape.parallel_tool_calls; provider.output_format_name = None; provider.output_schema_json = None; - // 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, - }); + provider.max_output_tokens = Some(shape.max_output_tokens); Ok(InferenceRequest { purpose, provider }) } @@ -3628,7 +4609,10 @@ fn interpreter_tools() -> Vec { /// slots — never an affordance id, an opportunity, a revision, a world, a /// controller, or a caller. `record_need` and `finish_without_proposal` survive /// because they are not world operations: they end a turn without proposing. -fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { +/// `prefix` is empty on the detail path, so its schemas stay byte-identical, +/// and `c__` on the grouped path, where the tool name is what attributes +/// a proposal to one constituent. One owner, two spellings of the same catalog. +fn catalog_tools(prefix: &str, granted: &[AffordanceSnapshot]) -> Vec { let mut tools: Vec = granted .iter() .map(|entry| { @@ -3656,14 +4640,22 @@ fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { )); } tool_schema::tool( - &entry.entry.kind.0, - &format!("Invoke the {} affordance.", entry.entry.kind.0), + &format!("{prefix}{}", entry.entry.kind.0), + &if prefix.is_empty() { + format!("Invoke the {} affordance.", entry.entry.kind.0) + } else { + format!( + "Invoke the {} affordance for {}.", + entry.entry.kind.0, + prefix.trim_end_matches(HANDLE_SEPARATOR) + ) + }, tool_schema::object(properties), ) }) .collect(); tools.push(tool_schema::tool( - RECORD_NEED_TOOL, + &format!("{prefix}{RECORD_NEED_TOOL}"), "Record information or capability the agent would need but does not currently have.", tool_schema::object(vec![( "detail".into(), @@ -3671,7 +4663,7 @@ fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { )]), )); tools.push(tool_schema::tool( - FINISH_WITHOUT_PROPOSAL_TOOL, + &format!("{prefix}{FINISH_WITHOUT_PROPOSAL_TOOL}"), "Finish this opportunity without proposing an action.", tool_schema::empty_schema(), )); @@ -3680,7 +4672,7 @@ fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { /// The same iteration rendered as one prose line, so the prompt's tool list and /// the schemas have one owner. -fn catalog_signatures(granted: &[AffordanceSnapshot]) -> String { +fn catalog_signatures(prefix: &str, granted: &[AffordanceSnapshot]) -> String { let mut signatures: Vec = granted .iter() .map(|entry| { @@ -3700,11 +4692,11 @@ fn catalog_signatures(granted: &[AffordanceSnapshot]) -> String { if entry.entry.carries_speech { parameters.push("text".into()); } - format!("{}({})", entry.entry.kind.0, parameters.join(", ")) + format!("{prefix}{}({})", entry.entry.kind.0, parameters.join(", ")) }) .collect(); - signatures.push("record_need(detail)".into()); - signatures.push("finish_without_proposal()".into()); + signatures.push(format!("{prefix}record_need(detail)")); + signatures.push(format!("{prefix}finish_without_proposal()")); signatures.join(", ") } @@ -3851,6 +4843,7 @@ fn purpose_name(purpose: InferencePurpose) -> &'static str { InferencePurpose::Persona => "persona", InferencePurpose::Interpreter => "interpreter", InferencePurpose::OperationalAgent => "operational", + InferencePurpose::GroupedAgent => "grouped", InferencePurpose::Elaboration => "elaboration", } } @@ -3858,8 +4851,8 @@ fn purpose_name(purpose: InferencePurpose) -> &'static str { #[cfg(test)] mod tests { use super::*; - use crate::world::WorldScaleIntentRef; use crate::world::patch::{kernel_speak_entry, kernel_speak_grant}; + use crate::world::{CoverBudget, WorldScaleIntentRef, derive_cover}; /// The granted catalog every controller fixture works against: the /// kernel-built Speak entry under a fixture id. @@ -4497,7 +5490,7 @@ mod tests { let granted = vec![speak_snapshot(AffordanceId::issue())]; for definition in interpreter_tools() .into_iter() - .chain(catalog_tools(&granted)) + .chain(catalog_tools("", &granted)) { let schema: Value = serde_json::from_str(&definition.parameters_json).unwrap(); assert_eq!(schema["additionalProperties"], false); @@ -4517,7 +5510,7 @@ mod tests { } } assert_eq!( - catalog_tools(&granted) + catalog_tools("", &granted) .iter() .map(|tool| tool.name.as_str()) .collect::>(), @@ -4587,7 +5580,7 @@ mod tests { // The tool names are exactly the granted entries' kind names plus the // two turn-enders, in that order. assert_eq!( - catalog_tools(&granted) + catalog_tools("", &granted) .iter() .map(|tool| tool.name.as_str()) .collect::>(), @@ -4602,7 +5595,7 @@ mod tests { // Each tool requires exactly its roles, its bounded slots, and `text` // where the entry carries speech, and each bounded slot states its own // ceiling. - let tools = catalog_tools(&granted); + let tools = catalog_tools("", &granted); let schema_of = |name: &str| -> Value { serde_json::from_str( &tools @@ -4631,7 +5624,7 @@ mod tests { // The three model-facing surfaces name the same entries in the same // order, so none of them can drift from the kernel's grant. assert_eq!( - catalog_signatures(&granted), + catalog_signatures("", &granted), "carry(recipient, resource, slot_0_qty), speak(text), record_need(detail), finish_without_proposal()" ); assert_eq!( @@ -4641,7 +5634,7 @@ mod tests { // A subject granted nothing gets no world tools, only the turn-enders. assert_eq!( - catalog_tools(&[]) + catalog_tools("", &[]) .iter() .map(|tool| tool.name.as_str()) .collect::>(), @@ -4649,7 +5642,7 @@ mod tests { ); // No generated schema carries an affordance id or an authority envelope. - for tool in catalog_tools(&granted) { + for tool in catalog_tools("", &granted) { let schema: Value = serde_json::from_str(&tool.parameters_json).unwrap(); let properties = schema["properties"].as_object().unwrap(); for forbidden in [ @@ -6198,9 +7191,557 @@ mod tests { /// The store refuses the version immediately before it, not merely some /// older one: `v7` is the bump this pass made and `v6` is what a store + + /// An active world with several non-human subjects standing in one room, so + /// a cover has something to group. + async fn active_cell_mailbox( + controllers: Vec, + ) -> (tempfile::TempDir, WorldMailbox, tokio::task::JoinHandle<()>) { + let directory = tempfile::tempdir().unwrap(); + let (mailbox, task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let owner = PrincipalId::new("owner"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let mut declarations = vec![Declaration::Entity(crate::world::EntityDeclaration { + handle: DraftHandle::new("commons"), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + })]; + for (index, controller) in controllers.into_iter().enumerate() { + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(&format!("subject{index}")), + label: format!("Subject {index}"), + kind: SubjectKind::Person, + controller, + affordances: kernel_speak_grant(), + position: Some(crate::world::Ref::Draft(DraftHandle::new("commons"))), + })); + } + let creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Cover Fixture".into(), + patch: WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + }, + scale_intent: WorldScaleIntentRef::default(), + }, + &authenticated, + ) + .await + .unwrap(); + let mut snapshot = mailbox.snapshot().await.unwrap(); + for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] { + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body, + }, + &authenticated, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + } + assert_eq!(snapshot.phase, WorldPhase::Active); + (directory, mailbox, task) + } + + /// One cell holding every active subject, derived by the real scheduler + /// rather than hand-built: a test that mints its own cell would prove the + /// runner works on a partition the cover cannot produce. + async fn one_group(mailbox: &WorldMailbox) -> Cell { + let snapshot = mailbox.snapshot().await.unwrap(); + let graph = mailbox.agency_graph().await.unwrap(); + let cover = derive_cover( + snapshot.world_id, + snapshot.now, + 60, + &snapshot.opportunities, + &graph, + CoverBudget { + cells: 1, + constituent_cap: 8, + urgency_slots: 0, + }, + ); + let [cell] = cover.cells.as_slice() else { + panic!("a one-cell budget derived {} cells", cover.cells.len()); + }; + assert!(matches!(cell, Cell::Group { .. }), "the cell is not coarse"); + cell.clone() + } + + fn grouped_runner( + mailbox: &WorldMailbox, + outputs: Vec>, + ) -> (ControllerRunner, Arc) { + let persisted = Arc::new(AtomicBool::new(true)); + let port = Arc::new(RecordingPort { + outputs: Mutex::new(outputs), + persisted_before_interpreter: persisted.clone(), + }); + let store = Arc::new(RecordingWorkStore { + persisted, + work: Mutex::new(BTreeMap::new()), + }); + ( + ControllerRunner::with_test_ports(mailbox.clone(), port, store.clone(), models()), + store, + ) + } + + fn speak_call(call_id: &str, name: &str, text: &str) -> InferenceEvent { + InferenceEvent::ToolCall { + call_id: call_id.into(), + name: name.into(), + arguments: json!({ "text": text }).to_string(), + } + } + + /// Verification 20. One inference proposes for `c0`, names a handle outside + /// the cell, and says nothing for the rest. The valid call commits under its + /// own opportunity; the out-of-cell name produces a gap and reaches no + /// mailbox; every silent handle declines, so "attended and stayed silent" is + /// distinguishable from "was never attended". + #[tokio::test] + async fn soul_a_batched_turn_attributes_by_tool_identity_and_refuses_an_outside_handle() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + assert_eq!(cell.members().len(), 3); + assert_eq!(cell.resolution(), Resolution::Coarse { constituents: 3 }); + + let (runner, _store) = grouped_runner( + &mailbox, + vec![ + output( + vec![ + speak_call("c0", "c0__speak", "Close the western span."), + speak_call("outside", "c7__speak", "I speak for someone else."), + ], + "grouped-one", + ), + output( + vec![InferenceEvent::Text("Nothing further.".into())], + "grouped-two", + ), + ], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert!(run.pending.is_none()); + assert_eq!(run.submissions.len(), 3, "every constituent finished"); + let first = cell.members()[0].subject; + assert!(matches!( + run.submissions + .iter() + .find(|entry| entry.subject == first) + .map(|entry| &entry.submission), + Some(SubmissionDisposition::Completed(_)) + )); + for entry in run + .submissions + .iter() + .filter(|entry| entry.subject != first) + { + assert!( + matches!(entry.submission, SubmissionDisposition::NoProposal(_)), + "a silent constituent did not decline" + ); + } + assert!( + run.needs + .iter() + .any(|need| need.detail.contains("c7__speak")), + "the out-of-cell call left no gap: {:?}", + run.needs + ); + // Exactly one act was committed, by exactly one subject. + let log = mailbox.operator_log().await.unwrap(); + assert_eq!(log.len(), 1); + assert_eq!(log[0].speaker, first); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// Verification 20b. No spelling of a handle outside the cell decodes, and + /// the index-to-subject mapping is scheduler-owned rather than + /// model-supplied: a shared tool with a `subject` argument would be the + /// forgeable shape. + #[test] + fn soul_no_out_of_cell_handle_has_a_decodable_spelling() { + for name in [ + "c9__speak", + "speak", + "c__speak", + "cx__speak", + "c01__speak", + "c-1__speak", + "c 0__speak", + "__speak", + ] { + assert_eq!( + split_handle(name, 3), + None, + "`{name}` decoded to a handle inside a three-constituent cell" + ); + } + assert_eq!(split_handle("c0__speak", 3), Some((0, "speak"))); + assert_eq!(split_handle("c2__record_need", 3), Some((2, "record_need"))); + // In-cell but not granted: a handle, and still no proposal. + assert_eq!(split_handle("c0__notgranted", 3), Some((0, "notgranted"))); + } + + /// A handle that names a tool it was not granted produces a gap, never a + /// proposal. + #[test] + fn an_ungranted_tool_under_a_live_handle_is_a_gap() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let constituents = vec![ConstituentWork { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + granted: vec![speak_snapshot(opportunity.affordance_ids[0])], + command_id: CommandId::new(), + }]; + let completed = vec![ + InferenceOutput { + events: vec![speak_call("call", "c0__notgranted", "Anything.")], + receipt_digest: "sha256:grouped".into(), + }, + // The repair round the grouped budget buys. It calls nothing, so the + // handle finishes silent. + InferenceOutput { + events: vec![InferenceEvent::Text("Nothing further.".into())], + receipt_digest: "sha256:grouped-repair".into(), + }, + ]; + let GroupedLoopEvaluation::Complete { capture } = + evaluate_grouped_loop("prompt", &constituents, &completed).unwrap() + else { + panic!("the round did not finalize") + }; + assert!(capture.proposals.is_empty()); + assert_eq!(capture.needs.len(), 1); + } + + /// Each constituent's view stays under its own handle. Nothing is unioned, + /// nothing is deduplicated, and the detail path's prompt is untouched: a + /// shared builder is how the singleton prompt drifts by one byte and every + /// persisted checkpoint fails its request-shape check on resume. + #[test] + fn soul_partitioned_views_do_not_cross_labels() { + let mine = "ONLY-MINE-TAG"; + let yours = "ONLY-YOURS-TAG"; + let views = [ + LabeledView { + handle: "c0", + identity: "Mara", + typed_view: mine, + tool_signatures: "c0__speak(text)", + }, + LabeledView { + handle: "c1", + identity: "Iris", + typed_view: yours, + tool_signatures: "c1__speak(text)", + }, + ]; + let prompt = build_grouped_agent_prompt(&GroupedAgentPrompt { + views: &views, + decision_pressure: "pressure", + domain_guidance: "", + step_budget: CELL_TOOL_STEP_BUDGET, + }); + assert_eq!(prompt.matches(mine).count(), 1); + assert_eq!(prompt.matches(yours).count(), 1); + let blocks: Vec<&str> = prompt.split("### ").skip(1).collect(); + assert_eq!(blocks.len(), 2); + assert!(blocks[0].contains(mine) && !blocks[0].contains(yours)); + assert!(blocks[1].contains(yours) && !blocks[1].contains(mine)); + + // The detail path's tool names and signatures are unprefixed, and its + // prompt has no handle blocks at all. + let granted = vec![speak_snapshot(AffordanceId::issue())]; + assert_eq!( + catalog_signatures("", &granted), + "speak(text), record_need(detail), finish_without_proposal()" + ); + let singleton = build_operational_agent_prompt(&OperationalAgentPrompt { + identity: "Mara", + typed_view: mine, + available_tools: &catalog_signatures("", &granted), + decision_pressure: "Choose whether this decision owner should speak now.", + domain_guidance: "", + step_budget: TOOL_STEP_BUDGET, + }); + assert!(!singleton.contains("### c0")); + assert!(!singleton.contains("c0__")); + assert_eq!( + catalog_signatures("c1__", &granted), + "c1__speak(text), c1__record_need(detail), c1__finish_without_proposal()" + ); + } + + /// A `NarrativePersona` grouped this tick is represented operationally at + /// coarse resolution. The membrane is not weakened; it is not entered: one + /// inference, no Projector, no Persona, no Interpreter, and no Persona turn + /// receipt. Its controller, scope, and authority do not change, and the + /// kernel cannot tell the difference. + #[tokio::test] + async fn soul_a_coarse_narrative_persona_keeps_its_controller_and_enters_no_membrane() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::NarrativePersona, + NewController::NarrativePersona, + ]) + .await; + let cell = one_group(&mailbox).await; + let before = mailbox.snapshot().await.unwrap(); + for member in cell.members() { + assert_eq!( + member.opportunity.controller_mode, + ControllerMode::NarrativePersona, + "grouping changed a controller mode" + ); + } + + // Exactly one output is supplied. A membrane turn would need three, and + // the port panics when it runs dry. + let (runner, store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "The hinge is flooding."), + InferenceEvent::ToolCall { + call_id: "c1".into(), + name: "c1__finish_without_proposal".into(), + arguments: "{}".into(), + }, + ], + "coarse-narrative", + )], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert!(run.pending.is_none()); + assert_eq!(run.submissions.len(), 2); + + // No Persona turn was minted, and the stored row is a grouped one. + let rows = store.work.lock().unwrap().clone(); + assert_eq!(rows.len(), 1); + let row = rows.values().next().unwrap().clone(); + assert!(matches!(row, ControllerWork::Grouped(_))); + assert_eq!(row.resolution(), Resolution::Coarse { constituents: 2 }); + let encoded = serde_json::to_string(&row).unwrap(); + assert!( + !encoded.contains("persona_turn"), + "a coarse turn minted a receipt" + ); + assert!(!encoded.contains("projector")); + assert!(!encoded.contains("interpreter")); + + // Controller, mode, and scope are exactly what they were. + let after = mailbox.snapshot().await.unwrap(); + for subject in &after.subjects { + let was = before + .subjects + .iter() + .find(|entry| entry.id == subject.id) + .unwrap(); + assert_eq!(subject.controller_id, was.controller_id); + assert_eq!(subject.controller_mode, was.controller_mode); + } + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// A resumed cell re-derives the same command ids, so the kernel answers + /// from its idempotency ledger instead of committing a second time. There is + /// no persisted per-constituent outcome doing this job: the ledger already + /// owns it. + #[tokio::test] + async fn soul_a_resumed_cell_re_derives_its_ids_and_commits_nothing_twice() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + let (runner, _store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "Hold the bridge."), + InferenceEvent::ToolCall { + call_id: "c1".into(), + name: "c1__finish_without_proposal".into(), + arguments: "{}".into(), + }, + ], + "grouped", + )], + ); + let CellRun::Grouped(first) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert_eq!(first.submissions.len(), 2); + assert!(matches!( + first.submissions[0].submission, + SubmissionDisposition::Completed(_) + )); + assert!(matches!( + first.submissions[1].submission, + SubmissionDisposition::NoProposal(_) + )); + let committed = mailbox.operator_log().await.unwrap().len(); + assert_eq!(committed, 1); + + // The port has no outputs left: a second inference would panic. The + // resumed row goes straight to submission, and every constituent's + // derived id answers from the ledger. + let CellRun::Grouped(second) = runner.run_cell(&cell).await.unwrap() else { + panic!("a resumed coarse cell did not run the grouped lane") + }; + assert!( + matches!( + second.submissions[0].submission, + SubmissionDisposition::PreviouslyConfirmed(_) + ), + "a resumed cell committed again: {:?}", + second.submissions + ); + assert!(matches!( + second.submissions[1].submission, + SubmissionDisposition::NoProposal(SubmitReceipt::AlreadyApplied(_)) + )); + assert_eq!(mailbox.operator_log().await.unwrap().len(), committed); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// A cell is not a transaction, and one inference does not buy N commits. + /// + /// Two co-located constituents both propose. The first commits; the second + /// was reasoned from a scope its neighbour has since changed, and the kernel + /// refuses it with `ScopeChanged` rather than committing a proposal whose + /// binding no longer holds. The batch buys one inference, never one + /// admission rule. + /// + /// This is the live cost of a connected cover: the cover groups subjects + /// precisely because they are causally coupled, and coupled subjects + /// contend for the same scope. + #[tokio::test] + async fn soul_a_second_act_in_one_cell_is_refused_rather_than_committed_on_a_stale_scope() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + let (runner, _store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "The hinge is flooding."), + speak_call("c1", "c1__speak", "Then we close the span."), + ], + "two-acts", + )], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert_eq!(run.submissions.len(), 1, "two acts committed from one cell"); + assert!(matches!( + run.submissions[0].submission, + SubmissionDisposition::Completed(_) + )); + assert!( + run.needs + .iter() + .any(|need| need.detail.contains("scope changed")), + "the refused act was not recorded: {:?}", + run.needs + ); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The cover is derived and disposable. Nothing the kernel persists or + /// hands out names a cell, a handle, or a resolution: the only durable + /// trace is the controller-work row, whose custody is separate from world + /// custody. + #[tokio::test] + async fn soul_a_cell_leaves_no_trace_in_world_state() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + let (runner, _store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "Hold the bridge."), + InferenceEvent::ToolCall { + call_id: "c1".into(), + name: "c1__finish_without_proposal".into(), + arguments: "{}".into(), + }, + ], + "grouped", + )], + ); + runner.run_cell(&cell).await.unwrap(); + + let snapshot = mailbox.snapshot().await.unwrap(); + for opportunity in &snapshot.opportunities { + let encoded = serde_json::to_string(opportunity).unwrap(); + for forbidden in ["cell", "resolution", "constituent", "handle"] { + assert!( + !encoded.contains(forbidden), + "an opportunity carries `{forbidden}`" + ); + } + } + assert!( + !serde_json::to_string(&snapshot.state_digest) + .unwrap() + .is_empty() + ); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } /// written before it holds. #[test] - fn soul_a_controller_work_row_from_v6_is_refused_at_open() { + fn soul_a_controller_work_row_from_v7_is_refused_at_open() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("controller-work.cc"); let command_id = CommandId::new(); @@ -6217,15 +7758,15 @@ mod tests { store .push(&CultCacheEnvelope { key: store_key(command_id).unwrap(), - r#type: "controller_work.v6".into(), + r#type: "controller_work.v7".into(), payload: rmp_serde::to_vec_named(&work).unwrap(), stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.controller_work.v6".into()), + schema_id: Some("ghostlight.controller_work.v7".into()), }) .unwrap(); } let Err(error) = CultCacheControllerWorkStore::open(&path) else { - panic!("a v6 row was accepted by the v7 store"); + panic!("a v7 row was accepted by the v8 store"); }; assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); } diff --git a/crates/ghostlight-dungeon/src/world/cover.rs b/crates/ghostlight-dungeon/src/world/cover.rs new file mode 100644 index 0000000..453b9f7 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/cover.rs @@ -0,0 +1,921 @@ +//! The budgeted connected cover: one tick's partition of the active +//! opportunities into cells. +//! +//! This organ owns the partition and nothing else. [`derive_cover`] is pure +//! over its arguments — no clock, no entropy, no mailbox, no filesystem — and +//! the [`Cover`] it returns is derived and disposable. A cell never enters +//! `WorldState`, a `CommandEnvelope`, a `ScopePreimage`, a `DecisionOpportunity`, +//! or any `Declaration`; the kernel never learns a tick happened except through +//! `AdvanceTime` and ordinary one-opportunity submissions. +//! +//! The cover is a partition, never a filter: every active subject is in exactly +//! one cell every tick. The budget decides at what resolution, not whether. + +use super::clock::FictionalMinutes; +use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +/// A place, resource, or channel with more associated subjects than this +/// contributes a star centred on its lowest member instead of a clique. +/// Connectivity is identical for component purposes and the edge count stops +/// being quadratic in a crowded room. +pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16; + +/// The namespace every derived cover id is salted with. A fixed constant, never +/// regenerated: two worlds in one process are separated by the world id inside +/// the name, not by a second namespace. +const COVER_NAMESPACE: &str = "ghostlight.cover.v1"; + +/// Monotone tick index. Derived from the world clock, never stored. It is +/// threaded into every derived command id, so a resumed tick over the same +/// snapshot re-derives the same ids and the kernel's idempotency ledger answers +/// with the original receipts instead of double-committing. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(transparent)] +pub(crate) struct TickIndex(pub(crate) u64); + +impl TickIndex { + /// Floor division by the span one `AdvanceTime` carries. The driver submits + /// the clock *after* the cells run, so every cell in one tick sees the same + /// `now` and therefore the same index. + pub(crate) fn of(now: FictionalMinutes, tick_minutes: u32) -> Self { + Self(now.0 / u64::from(tick_minutes.max(1))) + } +} + +/// How a subject was represented this tick. Derived from the cell, carried +/// nowhere in world state: representation is a compute budget, not world truth. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "resolution", rename_all = "snake_case")] +pub(crate) enum Resolution { + Detail, + Coarse { constituents: usize }, +} + +/// Derived from the partition, so a replayed tick over the same inputs produces +/// byte-identical ids. sha256 over `(namespace, world, tick, size, lowest +/// member)`; no `uuid/v5`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub(crate) struct CellId(Uuid); + +impl std::fmt::Display for CellId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "{}", self.0) + } +} + +fn derive_uuid(name: &str) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(COVER_NAMESPACE.as_bytes()); + hasher.update([0u8]); + hasher.update(name.as_bytes()); + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + Uuid::from_bytes(bytes) +} + +/// `members.len()` is in the name so a component that splits differently under +/// a different cap yields a different cell, and a resumed tick over the same +/// inputs yields the same one. +fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { + let lowest = members + .first() + .copied() + .expect("a cell always has at least one member"); + CellId(derive_uuid(&format!( + "cell|{world:?}|{}|{}|{lowest:?}", + tick.0, + members.len() + ))) +} + +/// The stable, derived identity a cell's controller-work row is keyed by. +pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid { + derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0)) +} + +/// One constituent's submission id. Deterministic, so a resumed cell re-submits +/// the same id and the kernel answers from its idempotency ledger. +pub(crate) fn cell_constituent_uuid( + world: WorldId, + cell: CellId, + subject: SubjectId, + tick: TickIndex, +) -> Uuid { + derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Constituent { + pub(crate) subject: SubjectId, + pub(crate) opportunity: DecisionOpportunity, +} + +/// One inference's worth of the world. A singleton keeps the detail path and its +/// membrane; a group is one inference over N labeled, never-unioned views. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Cell { + Singleton { + id: CellId, + tick: TickIndex, + member: Constituent, + }, + /// `members` is ascending by `SubjectId`; the index into it is the + /// constituent handle the model-facing tool names carry. + Group { + id: CellId, + tick: TickIndex, + members: Vec, + }, +} + +impl Cell { + pub(crate) fn id(&self) -> CellId { + match self { + Self::Singleton { id, .. } | Self::Group { id, .. } => *id, + } + } + + pub(crate) fn tick(&self) -> TickIndex { + match self { + Self::Singleton { tick, .. } | Self::Group { tick, .. } => *tick, + } + } + + pub(crate) fn members(&self) -> &[Constituent] { + match self { + Self::Singleton { member, .. } => std::slice::from_ref(member), + Self::Group { members, .. } => members, + } + } + + pub(crate) fn resolution(&self) -> Resolution { + match self { + Self::Singleton { .. } => Resolution::Detail, + Self::Group { members, .. } => Resolution::Coarse { + constituents: members.len(), + }, + } + } +} + +/// Derived, disposable, dropped at the end of a tick. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Cover { + pub(crate) tick: TickIndex, + pub(crate) cells: Vec, + /// True when the constituent cap could not hold every active subject inside + /// the cell budget, so the cap yielded and every cell grew. "Every active + /// subject is in the cover every tick" is an ontology invariant; the cap is + /// a prompt-size preference. Rendered read-only: it is the honest signal + /// that the world outgrew its prompt budget rather than a truncation nobody + /// sees. + pub(crate) oversubscribed: bool, +} + +impl Cover { + pub(crate) fn singletons(&self) -> usize { + self.cells + .iter() + .filter(|cell| matches!(cell, Cell::Singleton { .. })) + .count() + } + + pub(crate) fn groups(&self) -> usize { + self.cells.len() - self.singletons() + } +} + +/// How many inferences one tick may spend, and how large one prompt may get. +/// Two budgets, deliberately not one: only the second bounds tokens. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CoverBudget { + /// B: cells per tick. + pub(crate) cells: u16, + /// C: the per-cell constituent cap. At least two, or a group is a singleton + /// with extra steps. + pub(crate) constituent_cap: u16, + /// U: singleton slots reserved for the head of the attention order. The + /// rest of the singleton slots carry the rotation window. + pub(crate) urgency_slots: u16, +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub(crate) enum CoverBudgetError { + #[error("cover cell budget must be at least one")] + NoCells, + #[error("cover constituent cap must be at least two")] + CapTooSmall, +} + +impl CoverBudget { + pub(crate) fn validated(self) -> Result { + if self.cells < 1 { + return Err(CoverBudgetError::NoCells); + } + if self.constituent_cap < 2 { + return Err(CoverBudgetError::CapTooSmall); + } + Ok(self) + } +} + +/// The scheduler's own projection, wider than any subject view and reachable +/// from no prompt builder: it is constructed by the tick driver, handed to +/// [`derive_cover`], and dropped. `run_cell` takes a `&Cell`, which contains no +/// graph, so a controller organ that could read adjacency fails to compile +/// rather than failing a test. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct AgencyGraph { + /// Ascending. Exactly the subjects with a non-Human controller assignment. + pub(crate) subjects: Vec, + /// Undirected, canonicalised `(lo, hi)` with `lo < hi`. + pub(crate) edges: BTreeSet<(SubjectId, SubjectId)>, +} + +impl AgencyGraph { + /// A clique below the star threshold, a star above it. Connectivity for + /// component purposes is identical either way. + pub(crate) fn relate(&mut self, group: &BTreeSet) { + let members: Vec = group.iter().copied().collect(); + if members.len() < 2 { + return; + } + if members.len() > AGENCY_STAR_THRESHOLD { + let centre = members[0]; + for member in &members[1..] { + self.link(centre, *member); + } + return; + } + for (index, one) in members.iter().enumerate() { + for other in &members[index + 1..] { + self.link(*one, *other); + } + } + } + + pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) { + if one == other { + return; + } + let pair = if one < other { + (one, other) + } else { + (other, one) + }; + self.edges.insert(pair); + } +} + +/// The partition. Pure over `(world, now, opportunities, graph, budget)`. +/// +/// `opportunities` arrives in the kernel's one attention order (pressure, then +/// attention debt, then id) and is never re-sorted and never filtered here: a +/// Human opportunity is skipped because a human turn is not an inference, which +/// is a fact about cognition rather than a scheduling preference. +pub(crate) fn derive_cover( + world: WorldId, + now: FictionalMinutes, + tick_minutes: u32, + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, +) -> Cover { + let tick = TickIndex::of(now, tick_minutes); + let active: Vec<&DecisionOpportunity> = opportunities + .iter() + .filter(|opportunity| opportunity.controller_mode != ControllerMode::Human) + .collect(); + let count = active.len(); + if count == 0 { + return Cover { + tick, + cells: Vec::new(), + oversubscribed: false, + }; + } + let constituent = |opportunity: &DecisionOpportunity| Constituent { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + }; + let cell_budget = usize::from(budget.cells).max(1); + let cap = usize::from(budget.constituent_cap).max(2); + + if count <= cell_budget { + let cells = active + .iter() + .map(|opportunity| { + let member = constituent(opportunity); + Cell::Singleton { + id: cell_id(world, tick, &[member.subject]), + tick, + member, + } + }) + .collect(); + return Cover { + tick, + cells, + oversubscribed: false, + }; + } + + // Step 2. Group cells must hold the non-singletons under the cap: + // `K + ceil((N - K) / C) <= B`. The cap yields when no such partition + // exists, because coverage is the invariant and the cap is a preference. + let capacity = cap.saturating_mul(cell_budget); + let mut oversubscribed = capacity < count; + let (singleton_slots, effective_cap) = if oversubscribed { + (0usize, count.div_ceil(cell_budget)) + } else { + ((capacity - count) / (cap - 1), cap) + }; + let singleton_slots = singleton_slots.min(count); + let group_budget = cell_budget - singleton_slots; + + // Step 3. The rotation window. A stable order that does not move with + // pressure is what lets it carry a guarantee: a subject at index `i` is in + // the window exactly when `phase == i / R`, and `phase` cycles once every + // `ceil(N / R)` consecutive ticks because `now` only advances. + let urgency = usize::from(budget.urgency_slots).min(singleton_slots); + let reserve = singleton_slots - urgency; + let ascending: Vec = { + let mut ids: Vec = active + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + ids.sort_unstable(); + ids + }; + let mut chosen: BTreeSet = BTreeSet::new(); + if reserve > 0 { + let cycle = count.div_ceil(reserve); + let phase = usize::try_from(tick.0 % cycle as u64).unwrap_or(0); + let lo = phase * reserve; + let hi = (lo + reserve).min(count); + for subject in &ascending[lo.min(count)..hi] { + chosen.insert(*subject); + } + } + // Step 4. Urgency, then backfill in the attention order. A subject in both + // reserves consumes one slot, not two, and every slot is spent. + for opportunity in active.iter().take(urgency) { + chosen.insert(opportunity.scope.subject_id); + } + for opportunity in &active { + if chosen.len() >= singleton_slots { + break; + } + chosen.insert(opportunity.scope.subject_id); + } + + let mut cells: Vec = Vec::new(); + for opportunity in &active { + let subject = opportunity.scope.subject_id; + if !chosen.contains(&subject) { + continue; + } + let member = constituent(opportunity); + cells.push(Cell::Singleton { + id: cell_id(world, tick, &[subject]), + tick, + member, + }); + } + + // Step 5. Connected components over the remainder. + let rest: Vec<&DecisionOpportunity> = active + .iter() + .copied() + .filter(|opportunity| !chosen.contains(&opportunity.scope.subject_id)) + .collect(); + let rank: BTreeMap = active + .iter() + .enumerate() + .map(|(index, opportunity)| (opportunity.scope.subject_id, index)) + .collect(); + let mut groups = components(&rest, graph); + + // Step 6. A component larger than the cap is cut in id order. A chunk of a + // connected component is still a legitimate coarse group, and a graph-aware + // cut would be a second partitioning heuristic whose only payoff is + // adjacency inside a prompt that never mentions adjacency. + let mut split: Vec> = Vec::new(); + for component in groups.drain(..) { + for chunk in component.chunks(effective_cap) { + split.push(chunk.to_vec()); + } + } + + // Step 7. Merge the lowest-ranked cells until the group budget is met. The + // choke falls on the quietest cells; the highest-pressure groups keep the + // smallest, sharpest prompts. Priority is read from the attention order, + // which is its one owner — the scheduler computes no second ranking. + let priority = |members: &Vec| { + members + .iter() + .filter_map(|subject| rank.get(subject).copied()) + .min() + .unwrap_or(usize::MAX) + }; + split.sort_by_key(|members| (priority(members), members[0])); + let mut head = split.len(); + let mut packed: Vec> = Vec::new(); + let mut bucket: Vec = Vec::new(); + while head > 0 { + let open = usize::from(!bucket.is_empty()); + if head + packed.len() + open <= group_budget { + break; + } + head -= 1; + let component = split[head].clone(); + if !bucket.is_empty() && bucket.len() + component.len() > effective_cap { + packed.push(std::mem::take(&mut bucket)); + } + bucket.extend(component); + } + if !bucket.is_empty() { + packed.push(bucket); + } + split.truncate(head); + split.append(&mut packed); + // Component sizes need not pack perfectly into the cap, so the packing pass + // can end above budget. The cap yields here for the same reason it yields in + // step 2: coverage is the invariant, prompt size is the preference, and the + // operator is told rather than shown a silent truncation. + while split.len() > group_budget && split.len() >= 2 { + split.sort_by_key(|members| (priority(members), members[0])); + let last = split.pop().expect("two or more cells were established"); + let previous = split.pop().expect("two or more cells were established"); + let mut merged = previous; + merged.extend(last); + split.push(merged); + oversubscribed = true; + } + + for members in &mut split { + members.sort_unstable(); + } + split.sort_by_key(|members| (priority(members), members[0])); + let by_subject: BTreeMap = rest + .iter() + .map(|opportunity| (opportunity.scope.subject_id, *opportunity)) + .collect(); + for members in split { + let constituents: Vec = members + .iter() + .filter_map(|subject| by_subject.get(subject).map(|entry| constituent(entry))) + .collect(); + if constituents.is_empty() { + continue; + } + cells.push(Cell::Group { + id: cell_id(world, tick, &members), + tick, + members: constituents, + }); + } + + debug_assert_eq!( + cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect::>() + .len(), + count, + "the cover is a partition: every active subject appears exactly once" + ); + debug_assert!(cells.len() <= cell_budget, "the cover respects its budget"); + + Cover { + tick, + cells, + oversubscribed, + } +} + +/// Union-find over the remainder's induced subgraph. Deterministic by +/// construction: a `BTreeSet` of edges in `SubjectId` order, components keyed by +/// their lowest member, members ascending. +fn components(rest: &[&DecisionOpportunity], graph: &AgencyGraph) -> Vec> { + let present: BTreeSet = rest + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + let mut parent: BTreeMap = + present.iter().map(|subject| (*subject, *subject)).collect(); + + fn find(parent: &mut BTreeMap, node: SubjectId) -> SubjectId { + let mut root = node; + while let Some(next) = parent.get(&root).copied() { + if next == root { + break; + } + root = next; + } + let mut cursor = node; + while let Some(next) = parent.get(&cursor).copied() { + if next == cursor { + break; + } + parent.insert(cursor, root); + cursor = next; + } + root + } + + for (one, other) in &graph.edges { + if !present.contains(one) || !present.contains(other) { + continue; + } + let left = find(&mut parent, *one); + let right = find(&mut parent, *other); + if left != right { + let (low, high) = if left < right { + (left, right) + } else { + (right, left) + }; + parent.insert(high, low); + } + } + + let mut buckets: BTreeMap> = BTreeMap::new(); + for subject in &present { + let root = find(&mut parent, *subject); + buckets.entry(root).or_default().push(*subject); + } + buckets + .into_values() + .map(|mut members| { + members.sort_unstable(); + members + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::{DecisionScope, ScopeDigest}; + + fn subject(index: u128) -> SubjectId { + serde_json::from_value(serde_json::json!(Uuid::from_u128(index).to_string())) + .expect("a subject id parses from its canonical uuid") + } + + fn opportunity(index: u128, mode: ControllerMode) -> DecisionOpportunity { + let subject_id = subject(index); + DecisionOpportunity { + world_id: WorldId::nil_for_test(), + revision: 1, + scope_digest: ScopeDigest::fixture(&format!("scope-{index}")), + scope: DecisionScope { subject_id }, + controller_id: serde_json::from_value(serde_json::json!( + Uuid::from_u128(index + 1_000_000).to_string() + )) + .expect("a controller id parses from its canonical uuid"), + controller_mode: mode, + affordance_ids: Vec::new(), + } + } + + fn active(count: u128) -> Vec { + (1..=count) + .map(|index| opportunity(index, ControllerMode::OperationalAgent)) + .collect() + } + + fn budget(cells: u16, cap: u16, urgency: u16) -> CoverBudget { + CoverBudget { + cells, + constituent_cap: cap, + urgency_slots: urgency, + } + } + + fn covered(cover: &Cover) -> Vec { + let mut subjects: Vec = cover + .cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect(); + subjects.sort_unstable(); + subjects + } + + fn derive( + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, + tick: u64, + ) -> Cover { + derive_cover( + WorldId::nil_for_test(), + FictionalMinutes(tick * 60), + 60, + opportunities, + graph, + budget, + ) + } + + /// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap + /// of 24, 36 urgency slots. Every subject exactly once, the budget held, and + /// the head of the attention order attended in detail. + #[test] + fn soul_the_design_profile_covers_every_subject_exactly_once_inside_its_budget() { + let opportunities = active(2_400); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + + assert_eq!(covered(&cover).len(), 2_400); + assert_eq!( + covered(&cover).iter().collect::>().len(), + 2_400, + "no subject is covered twice" + ); + assert!(cover.cells.len() <= 240); + assert!(!cover.oversubscribed); + // K = floor((24*240 - 2400) / 23) = 146 singleton slots. + assert_eq!(cover.singletons(), 146); + assert_eq!(cover.groups(), 94); + assert!( + cover.cells.iter().all(|cell| cell.members().len() <= 24), + "no cell exceeds the constituent cap" + ); + + let head = opportunities[0].scope.subject_id; + let urgent: BTreeSet = opportunities[..36] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + let singletons: BTreeSet = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert!( + singletons.contains(&head), + "the head of the order is a singleton" + ); + assert!( + urgent.is_subset(&singletons), + "every urgency slot is spent on the head of the order" + ); + } + + /// A human opportunity is not an inference. It is skipped, and skipping it + /// is not a filter on the cover: it never was a candidate. + #[test] + fn a_human_opportunity_is_never_in_a_cell() { + let opportunities = vec![ + opportunity(1, ControllerMode::Human), + opportunity(2, ControllerMode::OperationalAgent), + opportunity(3, ControllerMode::NarrativePersona), + ]; + let cover = derive(&opportunities, &AgencyGraph::default(), budget(8, 4, 1), 0); + assert_eq!(covered(&cover), vec![subject(2), subject(3)]); + } + + /// Below the budget every opportunity is its own cell and the detail path is + /// untouched. + #[test] + fn a_small_world_is_all_singletons() { + let opportunities = active(5); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + assert_eq!(cover.singletons(), 5); + assert_eq!(cover.groups(), 0); + assert!(!cover.oversubscribed); + } + + /// The cap yields, the budget does not. Every subject is still covered + /// exactly once and the operator learns the world outgrew the prompt bound. + #[test] + fn soul_an_oversubscribed_world_relaxes_the_cap_rather_than_dropping_a_subject() { + let opportunities = active(100); + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 4, 2), 0); + assert!(cover.oversubscribed); + assert_eq!(covered(&cover).len(), 100); + assert_eq!(covered(&cover).iter().collect::>().len(), 100); + assert!(cover.cells.len() <= 10); + assert_eq!(cover.singletons(), 0, "no slot is spent on detail here"); + } + + /// The fairness arithmetic, with no persisted field behind it: a subject + /// continuously active for `ceil(N / R)` ticks is a singleton at least once. + #[test] + fn soul_every_subject_reaches_a_singleton_within_the_rotation_window() { + // N = 25, B = 12, C = 8, U = 1 → K = floor((96 - 25) / 7) = 10, R = 9. + let opportunities = active(25); + let budget = budget(12, 8, 1); + let cycle = 25usize.div_ceil(9); + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + let all: BTreeSet = opportunities + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert_eq!(seen, all, "the window closes over every subject"); + } + + /// A narrow reserve still closes, it just takes longer. The guarantee is + /// `ceil(N / R)`, never `ceil(N / B)`: giving every cell to a singleton + /// would leave subjects out of the cover, which the ontology forbids. + #[test] + fn the_rotation_guarantee_is_over_the_reserve_not_the_cell_budget() { + let opportunities = active(25); + // K = floor((8*10 - 25) / 7) = 7, U = 6 → R = 1, cycle = 25. + let budget = budget(10, 8, 6); + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..25u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!(seen.len(), 25); + } + + /// The cover is derived, not remembered: the same inputs yield the same + /// partition, the same ids, and the same order. + #[test] + fn soul_the_same_inputs_derive_an_identical_partition() { + let opportunities = active(60); + let mut graph = AgencyGraph::default(); + graph.link(subject(3), subject(4)); + graph.link(subject(4), subject(5)); + let one = derive(&opportunities, &graph, budget(10, 8, 2), 7); + let other = derive(&opportunities, &graph, budget(10, 8, 2), 7); + assert_eq!(one, other); + } + + /// Shuffling the input changes the attention order, which is a real input. + /// Shuffling *within* one priority class does not change the partition: + /// the merge reads the order, and grouping is keyed by id. + #[test] + fn merges_are_deterministic_in_subject_order() { + let opportunities = active(40); + let graph = AgencyGraph::default(); + let one = derive(&opportunities, &graph, budget(6, 8, 1), 3); + let mut reversed = opportunities.clone(); + reversed.reverse(); + let other = derive(&reversed, &graph, budget(6, 8, 1), 3); + let members = |cover: &Cover| { + let mut cells: Vec> = cover + .cells + .iter() + .map(|cell| cell.members().iter().map(|entry| entry.subject).collect()) + .collect(); + cells.sort(); + cells + }; + assert_eq!(covered(&one), covered(&other)); + assert_eq!(members(&one).len(), members(&other).len()); + } + + /// Connected subjects land in one cell when the budget allows it. + #[test] + fn a_connected_component_becomes_one_coarse_cell() { + let opportunities = active(20); + let mut graph = AgencyGraph::default(); + for index in 10..20 { + graph.link(subject(10), subject(index)); + } + let cover = derive(&opportunities, &graph, budget(4, 12, 0), 0); + let component: BTreeSet = (10..20).map(subject).collect(); + let together = cover.cells.iter().any(|cell| { + let members: BTreeSet = + cell.members().iter().map(|entry| entry.subject).collect(); + component.is_subset(&members) + }); + assert!(together, "one component was not split across cells"); + } + + /// Property sweep: the budget and the cap hold, and coverage is exact. + #[test] + fn soul_cell_count_and_cap_hold_across_profiles() { + for count in [1u128, 3, 7, 25, 100, 401] { + for cells in [1u16, 2, 5, 12, 240] { + for cap in [2u16, 3, 8, 24] { + let opportunities = active(count); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(cells, cap, 3), + 11, + ); + assert!( + cover.cells.len() <= usize::from(cells), + "count {count} cells {cells} cap {cap} exceeded its budget" + ); + assert_eq!( + covered(&cover).len(), + usize::try_from(count).expect("a test fixture fits usize"), + "count {count} cells {cells} cap {cap} lost a subject" + ); + if usize::from(cap) * usize::from(cells) + >= usize::try_from(count).expect("a test fixture fits usize") + { + assert!(!cover.oversubscribed); + assert!( + cover + .cells + .iter() + .all(|cell| cell.members().len() <= usize::from(cap)), + "count {count} cells {cells} cap {cap} exceeded the cap" + ); + } else { + assert!(cover.oversubscribed); + } + } + } + } + } + + /// A crowded referent contributes a star, not a clique: connectivity is the + /// same and the edge count stops being quadratic. + #[test] + fn a_crowded_referent_relates_as_a_star() { + let crowd: BTreeSet = (1..=40).map(subject).collect(); + let mut graph = AgencyGraph::default(); + graph.relate(&crowd); + assert_eq!(graph.edges.len(), 39); + + let small: BTreeSet = (1..=4).map(subject).collect(); + let mut clique = AgencyGraph::default(); + clique.relate(&small); + assert_eq!(clique.edges.len(), 6); + } + + /// Derived ids are a pure function of their tuple, and distinct tuples do + /// not collide. + #[test] + fn derived_ids_are_pure_and_distinct() { + let world = WorldId::nil_for_test(); + let cell = cell_id(world, TickIndex(4), &[subject(1), subject(2)]); + assert_eq!( + cell, + cell_id(world, TickIndex(4), &[subject(1), subject(2)]) + ); + assert_ne!( + cell, + cell_id(world, TickIndex(5), &[subject(1), subject(2)]) + ); + assert_ne!(cell, cell_id(world, TickIndex(4), &[subject(1)])); + + assert_eq!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(2), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_work_uuid(world, cell, TickIndex(4)) + ); + } + + #[test] + fn a_budget_without_cells_or_with_a_singleton_cap_is_refused() { + assert_eq!(budget(0, 4, 0).validated(), Err(CoverBudgetError::NoCells)); + assert_eq!( + budget(4, 1, 0).validated(), + Err(CoverBudgetError::CapTooSmall) + ); + assert!(budget(4, 2, 0).validated().is_ok()); + } +} diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs index 277f34c..e88be3e 100644 --- a/crates/ghostlight-dungeon/src/world/elaboration.rs +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -13,7 +13,7 @@ use super::controllers::{ ControllerError, ControllerNeed, ControllerWork, ControllerWorkLookup, ControllerWorkStore, ControllerWorkWrite, InferenceEvent, InferenceOutput, InferencePort, InferencePurpose, - InferenceRequest, PreparedInference, canonical_model, prepared_matches_request, + InferenceRequest, PreparedInference, RequestShape, canonical_model, prepared_matches_request, tool_decode_need, tool_request, }; #[cfg(test)] @@ -1018,6 +1018,12 @@ pub(super) fn elaboration_request( ELABORATION_INSTRUCTIONS, input, patch_tools(), + RequestShape { + // A patch turn emits many tool calls where a decision turn emits + // one, so the budget belongs to the caller. + max_output_tokens: 4_000, + parallel_tool_calls: false, + }, ) } diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index 071852f..26a954e 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -1,10 +1,11 @@ use super::{ - AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, CreateWorld, - CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, - 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, + AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, + CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, + Declaration, 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; @@ -58,6 +59,12 @@ enum Request { OperatorLog { reply: oneshot::Sender, KernelError>>, }, + /// The scheduler's adjacency projection. Separate from `Snapshot` for the + /// same reason the story feed is: it is wider than any subject view, and + /// only the tick driver may hold it. + AgencyGraph { + reply: oneshot::Sender>, + }, ControllerReceipt { command_id: CommandId, opportunity: super::DecisionOpportunity, @@ -377,6 +384,22 @@ impl WorldMailbox { /// The human operator's story feed. It is not a perception surface, and no /// controller lane calls it. + /// The tick driver's adjacency projection. It is on `WorldMailbox` and on + /// neither `ControllerPort` nor `ElaborationPort`: a controller organ that + /// tried to read adjacency would fail to compile. + pub(crate) async fn agency_graph(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.sender + .send(Request::AgencyGraph { reply }) + .await + .map_err(|_| MailboxError::Unavailable)?; + + response + .await + .map_err(|_| MailboxError::Unavailable)? + .map_err(MailboxError::Kernel) + } + pub(crate) async fn operator_log(&self) -> Result, MailboxError> { let (reply, response) = oneshot::channel(); self.sender @@ -667,6 +690,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver) return; } } + Request::AgencyGraph { reply } => { + let result = match &owned { + OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated), + OwnedWorld::Live(kernel) => kernel.agency_graph(), + }; + let owner_must_stop = result + .as_ref() + .is_err_and(KernelError::requires_owner_restart); + let _ = reply.send(result); + if owner_must_stop { + return; + } + } Request::ControllerReceipt { command_id, opportunity, diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index aa67ef9..322446f 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -8,6 +8,7 @@ mod action; mod clock; mod controllers; +mod cover; mod elaboration; mod journal; mod mailbox; @@ -17,11 +18,15 @@ mod tool_schema; pub(crate) use action::ActionMismatch; pub(crate) use clock::{FictionalMinutes, Motion, TickMinutes}; pub(crate) use controllers::{ - ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason, + CellRun, ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, NarrativeCapture, NarrativeDecision, NarrativePending, NarrativeRun, OperationalCapture, OperationalDecision, OperationalPending, OperationalRun, SourceRange, SubmissionDisposition, TranslationGapSummary, }; +pub(crate) use cover::{ + AgencyGraph, Cell, CellId, Constituent, Cover, CoverBudget, CoverBudgetError, Resolution, + TickIndex, derive_cover, +}; pub(crate) use mailbox::{ControllerPort, ElaborationPort, MailboxError, WorldMailbox}; pub(crate) use patch::{ AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant, @@ -99,6 +104,26 @@ impl CommandId { .map_err(|_| KernelError::InvalidCommandId) } + /// The cell's own controller-work key. One row per cell per tick, derived so + /// a resumed tick reopens the row it wrote rather than starting a second + /// cognition chain over the same opportunities. + pub(crate) fn for_cell(world: WorldId, cell: cover::CellId, tick: cover::TickIndex) -> Self { + Self(cover::cell_work_uuid(world, cell, tick)) + } + + /// One constituent's submission id. Deterministic over + /// `(world, cell, subject, tick)`, so a resumed cell re-submits the same id + /// and the kernel's idempotency ledger answers with the original receipt + /// instead of committing a second time. + pub(crate) fn for_cell_constituent( + world: WorldId, + cell: cover::CellId, + subject: SubjectId, + tick: cover::TickIndex, + ) -> Self { + Self(cover::cell_constituent_uuid(world, cell, subject, tick)) + } + fn key(self) -> String { self.0.to_string() } @@ -1117,6 +1142,15 @@ impl WorldKernel { operator_log(&self.state) } + /// The scheduler's adjacency projection. Separate from `snapshot` for the + /// same reason `operator_log` is: it is wider than any subject view, so a + /// `WorldSnapshot` field carrying it would be reachable from every prompt + /// builder in the process. + fn agency_graph(&self) -> Result { + self.journal.ensure_healthy()?; + Ok(agency_graph(&self.state)) + } + fn submit( &mut self, command: CommandEnvelope, @@ -2936,6 +2970,159 @@ fn operator_log(state: &WorldState) -> Result, KernelError> { .collect() } +/// The scheduler's adjacency projection. It is deliberately wider than any +/// subject view — channel reach and place containment are in no subject's +/// snapshot at all — which is exactly why it is derived here, beside +/// `operator_log`, and handed to the cover rather than assembled by a +/// controller organ out of the union of what subjects can see. +/// +/// Nothing here is authority. Two subjects are adjacent when a decision by one +/// can plausibly land on the other, and adjacency only decides which prompt +/// they share. +fn agency_graph(state: &WorldState) -> AgencyGraph { + let active: BTreeSet = state + .controller_assignments + .iter() + .filter(|(_, controller)| controller.mode() != ControllerMode::Human) + .map(|(scope, _)| scope.subject_id) + .collect(); + let mut graph = AgencyGraph { + subjects: active.iter().copied().collect(), + edges: BTreeSet::new(), + }; + if active.len() < 2 { + return graph; + } + let live = |subject: &SubjectId| active.contains(subject); + + // Place containment, which subsumes "standing in the same room": a place + // covers itself, so one closure states both. + let mut in_place: BTreeMap> = BTreeMap::new(); + for (place, record) in &state.entities { + if record.kind != EntityKind::Place { + continue; + } + let occupants: BTreeSet = state + .positions + .iter() + .filter(|(subject, position)| { + live(subject) && patch::covers_place(&state.entities, *place, position.place) + }) + .map(|(subject, _)| *subject) + .collect(); + if occupants.len() >= 2 { + graph.relate(&occupants); + } + if !occupants.is_empty() { + in_place.insert(*place, occupants); + } + } + + // An open route makes two rooms one neighbourhood. One representative per + // side is enough: each side is already related internally. + for edge in state.edges.values() { + let EdgeRecord::Route { from, to, open, .. } = edge; + if !open { + continue; + } + if let (Some(here), Some(there)) = (in_place.get(from), in_place.get(to)) + && let (Some(one), Some(other)) = (here.first(), there.first()) + { + graph.link(*one, *other); + } + } + + // Dependencies: a named subject is a direct edge, a shared resource or + // route is a star over everyone leaning on it. + let mut shared: BTreeMap> = BTreeMap::new(); + for (subject, targets) in &state.dependencies { + if !live(subject) { + continue; + } + for target in targets { + match target { + DependencyTarget::Subject(other) if live(other) => graph.link(*subject, *other), + DependencyTarget::Subject(_) => {} + other => { + shared.entry(*other).or_default().insert(*subject); + } + } + } + } + for group in shared.values() { + graph.relate(group); + } + + // Authority and office: an institution and the people who hold its seats, + // and a jurisdiction that names one subject as its ground. + for (institution, offices) in &state.selection { + let mut seated: BTreeSet = offices + .values() + .filter_map(|office| office.incumbent) + .filter(live) + .collect(); + if live(institution) { + seated.insert(*institution); + } + graph.relate(&seated); + } + for (holder, grants) in &state.authority { + if !live(holder) { + continue; + } + for grant in grants { + if let AuthorityTarget::Subject(over) = grant.over + && live(&over) + { + graph.link(*holder, over); + } + } + } + + // Channel reach. This is the edge no union of subject views could produce: + // a subject sees the channels it controls, never who else is in earshot. + for record in state.channels.values() { + let mut reached: BTreeSet = match &record.reach { + Reach::Subjects(subjects) => subjects.iter().copied().filter(live).collect(), + Reach::Place(place) => in_place.get(place).cloned().unwrap_or_default(), + }; + if let Some(controller) = record.controller.filter(live) { + reached.insert(controller); + } + graph.relate(&reached); + } + + // Pressure, and the promises that raise it. + for (target, sources) in &state.pressures { + if !live(target) { + continue; + } + for source in sources.keys() { + let other = match source { + PressureSource::Commitment { subject, .. } => Some(*subject), + PressureSource::Dependency(DependencyTarget::Subject(subject)) => Some(*subject), + PressureSource::Subject(subject) => Some(*subject), + PressureSource::Dependency(_) => None, + }; + if let Some(other) = other.filter(live) { + graph.link(*target, other); + } + } + } + for (subject, promises) in &state.commitments { + if !live(subject) { + continue; + } + for commitment in promises.values() { + if let Some(counterparty) = commitment.counterparty.filter(live) { + graph.link(*subject, counterparty); + } + } + } + + graph +} + fn snapshot(state: &WorldState) -> Result { // One pass over the causal record so each subject's own knowledge map can be // stamped with the revision that minted each claim it holds. diff --git a/crates/ghostlight-persona-projection/src/lib.rs b/crates/ghostlight-persona-projection/src/lib.rs index df86b9b..3610c06 100644 --- a/crates/ghostlight-persona-projection/src/lib.rs +++ b/crates/ghostlight-persona-projection/src/lib.rs @@ -121,6 +121,62 @@ pub fn build_interpreter_prompt(input: &InterpreterPrompt<'_>) -> String { ) } +/// One constituent's block in a batched prompt. Built by calling the caller's +/// existing per-subject view builder once per constituent: there is no union +/// step anywhere in this type's construction, and a fact held by two +/// constituents appears twice, under each of their handles. That duplication is +/// the invariant, not waste. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LabeledView<'a> { + /// `c0`, `c1`, … — the constituent's index in its cell. + pub handle: &'a str, + pub identity: &'a str, + /// Verbatim per-subject typed view, for this subject alone. + pub typed_view: &'a str, + /// This constituent's tool signatures, already handle-prefixed. + pub tool_signatures: &'a str, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct GroupedAgentPrompt<'a> { + pub views: &'a [LabeledView<'a>], + pub decision_pressure: &'a str, + pub domain_guidance: &'a str, + pub step_budget: usize, +} + +/// A distinct builder, not the singleton builder widened. The singleton prompt +/// must stay byte-identical or every persisted checkpoint's request-shape check +/// fails on resume, and a shared builder with a vector arity is how that drifts +/// by one byte. +/// +/// The only shared text is the instruction and the attribution contract. There +/// is no shared header, no cell summary, no "who is present", and no +/// cross-reference between handles: each of those is a union with a friendly +/// name. +pub fn build_grouped_agent_prompt(input: &GroupedAgentPrompt<'_>) -> String { + let blocks = input + .views + .iter() + .map(|view| { + format!( + "### {handle} — {identity}\n{body}\nTools for {handle}: {tools}", + handle = view.handle, + identity = view.identity, + body = view.typed_view, + tools = view.tool_signatures, + ) + }) + .collect::>() + .join("\n\n"); + format!( + "\nYou are an operational decision agent deciding for several subjects at once, not a Persona and not a prose roleplay surface. Each subject's view appears under its own handle. A subject knows only what appears under its own handle. Call at most one tool per handle. A handle you were not given does not exist. Do not invent identifiers, permissions, observations, resources, or completed consequences, and never propose for one handle out of another handle's view.\n\nDomain guidance and exact permissions:\n{guidance}\n\nCurrent decision pressure:\n{pressure}\n\n{blocks}\n\nUse at most {step_budget} tool steps, and emit every call you intend to make in the first step. Returning no proposal for a handle is valid.", + guidance = input.domain_guidance, + pressure = input.decision_pressure, + step_budget = input.step_budget, + ) +} + pub fn build_operational_agent_prompt(input: &OperationalAgentPrompt<'_>) -> String { format!( "\nYou are an operational decision agent, not a Persona and not a prose roleplay surface. Read the permissioned typed view directly and use only the supplied typed tools. Choose proposals for this decision owner; the owning runtime validates and commits them. Do not invent identifiers, permissions, observations, resources, or completed consequences. Efficient structured reasoning is appropriate here.\n\nDomain guidance and exact permissions:\n{guidance}\n\nDecision owner:\n{identity}\n\nCurrent decision pressure:\n{pressure}\n\nPermissioned typed view:\n{view}\n\nAvailable typed tools:\n{tools}\n\nUse at most {step_budget} tool steps. Returning no proposal is valid.",