Give the world a tick
Step 6 pass 9: the budgeted connected cover. Every active subject is in the cover every tick; the budget decides at what resolution, never whether. A singleton cell keeps the detail path and its membrane; a grouped cell is one inference over N labeled, never-unioned constituent views, each lowered into an ordinary one-opportunity submission verified by its own opportunity. The kernel never sees a cell. `world/cover.rs` owns the partition and nothing else: pure over (world, now, opportunities, agency graph, budget), disposable, dropped at end of tick. The fairness guarantee is arithmetic over the clock and a total subject order rather than a second persisted memory. Adjacency is a kernel-side projection wider than any subject view, reachable from the tick driver and from no prompt builder. Cut before adding: the runner's exclusive mutex and its three lock sites, `controller_slot.take()` as the quarantine mechanism, `select`'s equation between representation and controller mode, and pass 7's standalone `advance_world_clock` task, which `drive_cover_tick` absorbs so one owner holds the tick's cadence. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
7dbbc81a3b
commit
71d8c536b0
8 changed files with 3208 additions and 188 deletions
|
|
@ -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<CoverPanelTick>,
|
||||
}
|
||||
|
||||
#[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<Value> {
|
||||
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"));
|
||||
|
|
|
|||
|
|
@ -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<Mutex<Option<ControllerRunner>>>,
|
||||
/// 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<Arc<ControllerRunner>>,
|
||||
controller_permits: Arc<Semaphore>,
|
||||
/// 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<AtomicBool>,
|
||||
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<Mutex<Option<CoverSummary>>>,
|
||||
sessions: Arc<Mutex<AppSessionOwner>>,
|
||||
heimdall: Arc<HeimdallClient>,
|
||||
mesh: Option<MeshPublisher>,
|
||||
|
|
@ -63,6 +87,45 @@ struct AppState {
|
|||
fatal: mpsc::UnboundedSender<String>,
|
||||
}
|
||||
|
||||
/// 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<PathBuf>) -> 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<PathBuf>) -> 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<Value> {
|
|||
},
|
||||
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<CoverBudget> {
|
||||
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::<usize>().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::<u64>().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<AppState>) -> 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(
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
921
crates/ghostlight-dungeon/src/world/cover.rs
Normal file
921
crates/ghostlight-dungeon/src/world/cover.rs
Normal file
|
|
@ -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<Constituent>,
|
||||
},
|
||||
}
|
||||
|
||||
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<Cell>,
|
||||
/// 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<Self, CoverBudgetError> {
|
||||
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<SubjectId>,
|
||||
/// 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<SubjectId>) {
|
||||
let members: Vec<SubjectId> = 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<SubjectId> = {
|
||||
let mut ids: Vec<SubjectId> = active
|
||||
.iter()
|
||||
.map(|opportunity| opportunity.scope.subject_id)
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
};
|
||||
let mut chosen: BTreeSet<SubjectId> = 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<Cell> = 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<SubjectId, usize> = 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<SubjectId>> = 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<SubjectId>| {
|
||||
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<SubjectId>> = Vec::new();
|
||||
let mut bucket: Vec<SubjectId> = 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<SubjectId, &DecisionOpportunity> = rest
|
||||
.iter()
|
||||
.map(|opportunity| (opportunity.scope.subject_id, *opportunity))
|
||||
.collect();
|
||||
for members in split {
|
||||
let constituents: Vec<Constituent> = 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::<BTreeSet<_>>()
|
||||
.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<Vec<SubjectId>> {
|
||||
let present: BTreeSet<SubjectId> = rest
|
||||
.iter()
|
||||
.map(|opportunity| opportunity.scope.subject_id)
|
||||
.collect();
|
||||
let mut parent: BTreeMap<SubjectId, SubjectId> =
|
||||
present.iter().map(|subject| (*subject, *subject)).collect();
|
||||
|
||||
fn find(parent: &mut BTreeMap<SubjectId, SubjectId>, 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<SubjectId, Vec<SubjectId>> = 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<DecisionOpportunity> {
|
||||
(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<SubjectId> {
|
||||
let mut subjects: Vec<SubjectId> = 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::<BTreeSet<_>>().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<SubjectId> = opportunities[..36]
|
||||
.iter()
|
||||
.map(|entry| entry.scope.subject_id)
|
||||
.collect();
|
||||
let singletons: BTreeSet<SubjectId> = 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::<BTreeSet<_>>().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<SubjectId> = 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<SubjectId> = 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<SubjectId> = 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<Vec<SubjectId>> = 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<SubjectId> = (10..20).map(subject).collect();
|
||||
let together = cover.cells.iter().any(|cell| {
|
||||
let members: BTreeSet<SubjectId> =
|
||||
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<SubjectId> = (1..=40).map(subject).collect();
|
||||
let mut graph = AgencyGraph::default();
|
||||
graph.relate(&crowd);
|
||||
assert_eq!(graph.edges.len(), 39);
|
||||
|
||||
let small: BTreeSet<SubjectId> = (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());
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<Result<Vec<OperatorEvent>, 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<Result<AgencyGraph, KernelError>>,
|
||||
},
|
||||
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<AgencyGraph, MailboxError> {
|
||||
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<Vec<OperatorEvent>, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
|
|
@ -667,6 +690,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
|
|||
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,
|
||||
|
|
|
|||
|
|
@ -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<AgencyGraph, KernelError> {
|
||||
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<Vec<OperatorEvent>, 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<SubjectId> = 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<EntityId, BTreeSet<SubjectId>> = BTreeMap::new();
|
||||
for (place, record) in &state.entities {
|
||||
if record.kind != EntityKind::Place {
|
||||
continue;
|
||||
}
|
||||
let occupants: BTreeSet<SubjectId> = 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<DependencyTarget, BTreeSet<SubjectId>> = 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<SubjectId> = 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<SubjectId> = 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<WorldSnapshot, KernelError> {
|
||||
// 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.
|
||||
|
|
|
|||
|
|
@ -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::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
format!(
|
||||
"<!-- membrane:{MEMBRANE_SCHEMA}:grouped-agent -->\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!(
|
||||
"<!-- membrane:{MEMBRANE_SCHEMA}:operational-agent -->\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.",
|
||||
|
|
|
|||
Loading…
Reference in a new issue