Build Session Zero and bounded co-op
This commit is contained in:
parent
acb7dae59e
commit
9f8be42d5c
37 changed files with 7834 additions and 1453 deletions
23
Cargo.lock
generated
23
Cargo.lock
generated
|
|
@ -81,6 +81,28 @@ version = "1.0.104"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "async-stream"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
|
||||
dependencies = [
|
||||
"async-stream-impl",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream-impl"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
|
|
@ -685,6 +707,7 @@ name = "ghostlight-dungeon"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"chrono",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ version = "0.1.0"
|
|||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
async-trait = "0.1"
|
||||
async-stream = "0.3"
|
||||
axum = { version = "0.8", features = ["macros"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
cultcache-legacy = { package = "cultcache-rs", git = "https://github.com/GameCult/cultcache-rs.git", rev = "0ba87453115e3d44e8fcb7419866cd7dd70fb096" }
|
||||
|
|
|
|||
45
README.md
45
README.md
|
|
@ -40,40 +40,46 @@ multiresolution agency graph for keeping large settings active at finite cost.
|
|||
Ghostlight Dungeon is implemented and deployed as a private Starfire-hosted
|
||||
playtest harness. The current acceptance surface covers:
|
||||
|
||||
- source-grounded world compilation with approval previews;
|
||||
- persistent DM-led Session Zero with shared/private channels, typed contracts,
|
||||
private boundaries, character bargains, digest-bound unanimous approval, and
|
||||
atomic publication;
|
||||
- source-grounded world compilation from an approved brief, with evidence gaps
|
||||
returned to negotiation instead of borrowing a nearby story;
|
||||
- persistent campaigns, forks, resets, exports, and Heimdall-account-isolated sessions;
|
||||
- parallel affected-character Projector/Persona/Interpreter waves;
|
||||
- impossible-action refusal, assessed stakes, server-side rolls, and receipted
|
||||
commits;
|
||||
- strategic clocks, away-time catch-up, institution activity, migration, and
|
||||
information-channel-aware news;
|
||||
- connected cohesive and arena simulation covers at budgets from 1 to 32;
|
||||
- bounded shared-scene co-op for up to eight Heimdall members, with exact
|
||||
member→actor authority, actor-filtered surfaces, unanimous time/budget
|
||||
governance, and no player puppeting or PvP mutation;
|
||||
- connected cohesive and arena simulation covers at budgets from 1 to 128;
|
||||
- Gestalt materialisation, folding, member deltas, migration, and later
|
||||
rematerialisation of the same person;
|
||||
- atomic rejection of malformed, stale, or semantically invalid model waves;
|
||||
- provider, token, cache, latency, validation, state-version, and build receipts;
|
||||
- exact-build deployment and restart verification on Starfire.
|
||||
|
||||
The immediate forge work is pressure-testing whether multiresolution Gestalts
|
||||
produce satisfying setting-wide activity, callbacks, and surprises per token,
|
||||
then running the two-tester paid-alpha path. The public site is provisional;
|
||||
checkout is not live.
|
||||
The immediate forge work is fixture, canary, and human pressure testing of
|
||||
Session Zero privacy/publication and bounded co-op alongside the existing
|
||||
multiresolution Gestalt agency tests. The public site is provisional; checkout
|
||||
is not live.
|
||||
|
||||
## Multiplayer Intention
|
||||
## Bounded Co-op
|
||||
|
||||
The first paid alpha remains single-player. Multiplayer is an intended extension
|
||||
of the existing authority model, not a separate chat mode.
|
||||
Campaign creation now supports one to eight authenticated players. One
|
||||
`SessionZeroKernel` owns negotiation; after unanimous approval, one
|
||||
`WorldKernel` owns the shared campaign. Membership binds each account to one
|
||||
exact actor, and every player receives an actor-filtered Eve projection.
|
||||
|
||||
A campaign will continue to have one `WorldKernel`. Authenticated human sessions
|
||||
will control distinct canonical actors, and every human or Persona proposal will
|
||||
enter the same campaign mailbox. Each player receives a perception-specific
|
||||
narrative projection; private knowledge is never unioned into a party prompt.
|
||||
Splitting the party therefore changes occupancy and perception without creating
|
||||
contradictory copies of the world.
|
||||
|
||||
The durable intention and unresolved social-policy questions are recorded in
|
||||
[`docs/architecture/ghostlight-dungeon-multiplayer-intention.md`](docs/architecture/ghostlight-dungeon-multiplayer-intention.md).
|
||||
It does not expand the current MVP acceptance promise.
|
||||
This milestone is intentionally one shared scene with sequential public
|
||||
actions. PvP, split parties, private in-play actions, delegation, late joining,
|
||||
and simultaneous declarations remain closed until their consent and governance
|
||||
contracts exist. See
|
||||
[`docs/architecture/ghostlight-dungeon-session-zero.md`](docs/architecture/ghostlight-dungeon-session-zero.md)
|
||||
and the longer-term
|
||||
[`multiplayer intention`](docs/architecture/ghostlight-dungeon-multiplayer-intention.md).
|
||||
|
||||
## Lore Vault Product Intention
|
||||
|
||||
|
|
@ -90,6 +96,7 @@ Custom tenant import is not yet part of the deployed tester harness.
|
|||
The shortest reliable re-entry path is:
|
||||
|
||||
- [`docs/architecture/ghostlight-dungeon-mvp.md`](docs/architecture/ghostlight-dungeon-mvp.md): runtime authority, compiler, action loop, persistence, hosting, and security;
|
||||
- [`docs/architecture/ghostlight-dungeon-session-zero.md`](docs/architecture/ghostlight-dungeon-session-zero.md): campaign negotiation, privacy, publication, membership, and bounded co-op;
|
||||
- [`docs/architecture/ghostlight-multiresolution-agency.md`](docs/architecture/ghostlight-multiresolution-agency.md): dynamic Gestalt partitioning, cohesive and arena cells, fairness, and atomic strategic waves;
|
||||
- [`notes/ghostlight-current-system-map.md`](notes/ghostlight-current-system-map.md): current implemented pipeline;
|
||||
- [`notes/ghostlight-implementation-plan.md`](notes/ghostlight-implementation-plan.md): live sequence and next pressure tests;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ license.workspace = true
|
|||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
async-stream.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
cultcache-legacy.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
use crate::{
|
||||
domain::{ActionAssessment, ActionIntent, Campaign, ContextModifier, WorldEffectDelta},
|
||||
model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage},
|
||||
session_zero::{AggregatedBoundary, CampaignContract, ExtraordinaryPermission},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::{Duration, Utc};
|
||||
|
|
@ -42,6 +43,27 @@ impl ActionAssessor {
|
|||
&self,
|
||||
campaign: &Campaign,
|
||||
intent: ActionIntent,
|
||||
) -> Result<(ActionAssessment, ModelStageReceipt)> {
|
||||
self.assess_with_permissions(campaign, intent, &[]).await
|
||||
}
|
||||
|
||||
pub async fn assess_with_permissions(
|
||||
&self,
|
||||
campaign: &Campaign,
|
||||
intent: ActionIntent,
|
||||
extraordinary_permissions: &[ExtraordinaryPermission],
|
||||
) -> Result<(ActionAssessment, ModelStageReceipt)> {
|
||||
self.assess_with_context(campaign, intent, extraordinary_permissions, None, &[])
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn assess_with_context(
|
||||
&self,
|
||||
campaign: &Campaign,
|
||||
intent: ActionIntent,
|
||||
extraordinary_permissions: &[ExtraordinaryPermission],
|
||||
campaign_contract: Option<&CampaignContract>,
|
||||
aggregate_boundaries: &[AggregatedBoundary],
|
||||
) -> Result<(ActionAssessment, ModelStageReceipt)> {
|
||||
let actor = campaign
|
||||
.actors
|
||||
|
|
@ -70,8 +92,19 @@ impl ActionAssessor {
|
|||
})
|
||||
.collect();
|
||||
let information_facts = available_information_facts(campaign, actor);
|
||||
let allowed_references = allowed_references(campaign, actor);
|
||||
let agency_guidance = action_agency_guidance(&campaign.player_actor_id, &intent.actor_id);
|
||||
let mut allowed_references = allowed_references(campaign, actor);
|
||||
allowed_references.extend(
|
||||
extraordinary_permissions
|
||||
.iter()
|
||||
.map(|permission| format!("extraordinary_permission:{}", permission.id)),
|
||||
);
|
||||
let agency_guidance = action_agency_guidance(
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get(&intent.actor_id)
|
||||
.is_some_and(|profile| !profile.simulation_eligible)
|
||||
|| intent.actor_id == campaign.player_actor_id,
|
||||
);
|
||||
let mut schema = serde_json::to_value(schema_for!(AssessmentProposal))?;
|
||||
schema["properties"]["dc"] = serde_json::json!({
|
||||
"type":"integer",
|
||||
|
|
@ -83,12 +116,15 @@ impl ActionAssessor {
|
|||
"maximum":10
|
||||
});
|
||||
let base_prompt = format!(
|
||||
"OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. Informational outcomes may reveal only an exact statement copied from AVAILABLE INFORMATION FACTS; they never create a new fact. Choose the fact that most directly answers the intended effect, preferring a relevant branch_local or provisional_local fact over generic canon background. A location-discoverable fact may be added only to the acting actor. A fact already known by the acting actor may instead be communicated to another present actor. actor_knowledge_additions contains the player-readable statement, never a fact ID, key, slug, or label. Strong and ordinary success share one visible stake, so give them identical knowledge additions. The runtime binds each exact finding into the player-visible stake; do not spend prose repeating it solely for formatting. If no supplied fact supports the intended discovery or disclosure, leave knowledge deltas empty and make the limitation explicit in the stakes or mark the attempt inadmissible. Never invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep a delta empty only when the outcome truly has no canonical state change.\nAGENCY BOUNDARY:\n{}\nPLAYER ACTOR ID:\n{}\nINTENT:\n{}\nACTOR:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nAVAILABLE INFORMATION FACTS:\n{}\nALLOWED REFERENCES:\n{}",
|
||||
"OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. Accepted extraordinary permissions are binding: preserve their prerequisites, costs, limits, exposure, and effect ceiling exactly; they admit only effects within that scope. The campaign contract governs tone, pacing, focus, consequence style, and DM style. Obey every aggregate content boundary: line excludes the topic, veil keeps it off-screen, ask_first admits no new depiction without a current explicit acceptance. Never reveal attribution. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. Informational outcomes may reveal only an exact statement copied from AVAILABLE INFORMATION FACTS; they never create a new fact. Choose the fact that most directly answers the intended effect, preferring a relevant branch_local or provisional_local fact over generic canon background. A location-discoverable fact may be added only to the acting actor. A fact already known by the acting actor may instead be communicated to another present actor. actor_knowledge_additions contains the player-readable statement, never a fact ID, key, slug, or label. Strong and ordinary success share one visible stake, so give them identical knowledge additions. The runtime binds each exact finding into the player-visible stake; do not spend prose repeating it solely for formatting. If no supplied fact supports the intended discovery or disclosure, leave knowledge deltas empty and make the limitation explicit in the stakes or mark the attempt inadmissible. Never invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep a delta empty only when the outcome truly has no canonical state change.\nCAMPAIGN CONTRACT:\n{}\nAGGREGATE CONTENT BOUNDARIES:\n{}\nAGENCY BOUNDARY:\n{}\nLEGACY HOST ACTOR ID (not an authority):\n{}\nINTENT:\n{}\nACTOR:\n{}\nACCEPTED EXTRAORDINARY PERMISSIONS:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nAVAILABLE INFORMATION FACTS:\n{}\nALLOWED REFERENCES:\n{}",
|
||||
serde_json::to_string(&schema)?,
|
||||
serde_json::to_string(&campaign_contract)?,
|
||||
serde_json::to_string(aggregate_boundaries)?,
|
||||
agency_guidance,
|
||||
campaign.player_actor_id,
|
||||
serde_json::to_string(&intent)?,
|
||||
serde_json::to_string(actor)?,
|
||||
serde_json::to_string(extraordinary_permissions)?,
|
||||
serde_json::to_string(location)?,
|
||||
serde_json::to_string(&present_actors)?,
|
||||
serde_json::to_string(&visible_institutions)?,
|
||||
|
|
@ -180,8 +216,8 @@ impl ActionAssessor {
|
|||
}
|
||||
}
|
||||
|
||||
fn action_agency_guidance(player_actor_id: &str, acting_actor_id: &str) -> &'static str {
|
||||
if acting_actor_id == player_actor_id {
|
||||
fn action_agency_guidance(human_controlled: bool) -> &'static str {
|
||||
if human_controlled {
|
||||
"The acting actor is player-controlled; assess the player's attempted effect without upgrading it into a completed fact."
|
||||
} else {
|
||||
"The acting actor is an NPC. The player retains authority over the player's own speech, choices, consent, beliefs, disclosures, feelings, and voluntary actions. An NPC may create pressure, make an offer or threat, reveal information, oppose the player, or change independently owned world state, but no outcome stake may assert that the player answered, chose, consented, believed, disclosed, felt, or obeyed. If the intended effect is only to obtain such a player response, mark it inadmissible because the response remains the player's next decision."
|
||||
|
|
@ -472,10 +508,10 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn npc_assessment_guidance_preserves_player_decision_authority() {
|
||||
let guidance = action_agency_guidance("player", "archivist");
|
||||
let guidance = action_agency_guidance(false);
|
||||
assert!(guidance.contains("player retains authority"));
|
||||
assert!(guidance.contains("response remains the player's next decision"));
|
||||
assert!(!action_agency_guidance("player", "player").contains("acting actor is an NPC"));
|
||||
assert!(!action_agency_guidance(true).contains("acting actor is an NPC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
};
|
||||
let impossible_error = kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
actor_id: "player".into(),
|
||||
assessment_digest: admitted_impossible.digest,
|
||||
})
|
||||
.await
|
||||
|
|
@ -116,6 +117,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
};
|
||||
let attempt = kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
actor_id: "player".into(),
|
||||
assessment_digest: admitted_feasible.digest,
|
||||
})
|
||||
.await?;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use crate::{
|
|||
ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage,
|
||||
run_validated_stage_with_timeout,
|
||||
},
|
||||
session_zero::{ApprovedCampaignBrief, actor_from_character},
|
||||
vault::{VaultProvider, VaultQuery},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
|
|
@ -579,6 +580,123 @@ impl WorldCompiler {
|
|||
))
|
||||
}
|
||||
|
||||
pub async fn compile_approved_brief(
|
||||
&self,
|
||||
brief: &ApprovedCampaignBrief,
|
||||
) -> Result<(WorldCompilePreview, Vec<ModelStageReceipt>)> {
|
||||
if brief.characters.is_empty() || brief.characters.len() > 8 {
|
||||
return Err(anyhow!(
|
||||
"approved campaign brief must contain one to eight characters"
|
||||
));
|
||||
}
|
||||
let host_actor_id = brief
|
||||
.member_actor_ids
|
||||
.get(&brief.host_member_id)
|
||||
.ok_or_else(|| anyhow!("approved campaign brief has no host actor binding"))?
|
||||
.clone();
|
||||
let public_party = brief
|
||||
.characters
|
||||
.iter()
|
||||
.map(|character| format!("{} — {}", character.name, character.public_premise))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
let mut compiled = self
|
||||
.compile_custom(CustomStart {
|
||||
campaign_name: brief.contract.campaign_name.clone(),
|
||||
who: format!(
|
||||
"A cooperative party whose public starting identities are: {public_party}. Private histories, secrets, and individual knowledge are deliberately withheld from world generation."
|
||||
),
|
||||
where_: brief.contract.starting_where.clone(),
|
||||
when: format!(
|
||||
"{}; canon horizon: {}",
|
||||
brief.contract.starting_when, brief.contract.canon_horizon
|
||||
),
|
||||
goal: format!(
|
||||
"{}; opening pressure: {}; premise: {}",
|
||||
brief.contract.desired_goal,
|
||||
brief.contract.starting_pressure,
|
||||
brief.contract.premise
|
||||
),
|
||||
})
|
||||
.await?;
|
||||
let campaign = &mut compiled.0.campaign;
|
||||
let generated_player_id = campaign.player_actor_id.clone();
|
||||
let starting_location = campaign
|
||||
.actors
|
||||
.get(&generated_player_id)
|
||||
.ok_or_else(|| anyhow!("compiled campaign lost its provisional player"))?
|
||||
.location_id
|
||||
.clone();
|
||||
campaign.actors.remove(&generated_player_id);
|
||||
campaign.agency_profiles.remove(&generated_player_id);
|
||||
campaign.agency_relations.retain(|_, relation| {
|
||||
relation.from_subject_id != generated_player_id
|
||||
&& relation.to_subject_id != generated_player_id
|
||||
});
|
||||
for actor in campaign.actors.values_mut() {
|
||||
actor.relationships.remove(&generated_player_id);
|
||||
}
|
||||
let member_actor_ids = brief
|
||||
.member_actor_ids
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if member_actor_ids.len() != brief.characters.len() {
|
||||
return Err(anyhow!("approved characters must have unique actor IDs"));
|
||||
}
|
||||
for character in &brief.characters {
|
||||
if brief.member_actor_ids.get(&character.member_id) != Some(&character.actor_id) {
|
||||
return Err(anyhow!("character and membership actor binding disagree"));
|
||||
}
|
||||
if campaign.actors.contains_key(&character.actor_id) {
|
||||
return Err(anyhow!("approved actor ID collides with compiled cast"));
|
||||
}
|
||||
let mut actor = actor_from_character(character, starting_location.clone());
|
||||
actor.relationships = actor
|
||||
.relationships
|
||||
.into_iter()
|
||||
.map(|(subject, relationship)| {
|
||||
let resolved = brief
|
||||
.member_actor_ids
|
||||
.get(&subject)
|
||||
.cloned()
|
||||
.unwrap_or(subject);
|
||||
(resolved, relationship)
|
||||
})
|
||||
.collect();
|
||||
if actor
|
||||
.relationships
|
||||
.keys()
|
||||
.any(|id| !member_actor_ids.contains(id) && !campaign.institutions.contains_key(id))
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"character relationship refers to an unknown member, actor, or institution"
|
||||
));
|
||||
}
|
||||
campaign.actors.insert(actor.id.clone(), actor);
|
||||
}
|
||||
campaign.player_actor_id = host_actor_id;
|
||||
campaign.name = brief.contract.campaign_name.clone();
|
||||
campaign.resolution_policy.active_cell_budget =
|
||||
(brief.characters.len() as u8).saturating_mul(8).min(128);
|
||||
campaign.resolution_cover = None;
|
||||
crate::resolution::ensure_agency_profiles(campaign);
|
||||
for actor_id in member_actor_ids {
|
||||
let profile = campaign
|
||||
.agency_profiles
|
||||
.get_mut(&actor_id)
|
||||
.ok_or_else(|| anyhow!("approved actor has no agency profile"))?;
|
||||
profile.simulation_eligible = false;
|
||||
}
|
||||
validate_campaign_seed(campaign)?;
|
||||
validate_opening_playability(campaign)?;
|
||||
compiled.0.branch_assumptions.push(format!(
|
||||
"Campaign contract approved in Session Zero {} at shared digest {}.",
|
||||
brief.session_zero_id, brief.shared_digest
|
||||
));
|
||||
Ok(compiled)
|
||||
}
|
||||
|
||||
pub async fn compile_selected(
|
||||
&self,
|
||||
start: SelectedStart,
|
||||
|
|
@ -2524,23 +2642,38 @@ pub fn validate_campaign_seed(c: &Campaign) -> Result<()> {
|
|||
}
|
||||
crate::resolution::validate_policy(&c.resolution_policy)?;
|
||||
crate::resolution::validate_pins(c, &c.resolution_pins)?;
|
||||
let expected_profiles: BTreeSet<_> = c
|
||||
let canonical_subjects = c
|
||||
.actors
|
||||
.keys()
|
||||
.filter(|id| *id != &c.player_actor_id)
|
||||
.chain(c.institutions.keys())
|
||||
.chain(c.gestalts.keys())
|
||||
.cloned()
|
||||
.collect();
|
||||
let actual_profiles: BTreeSet<_> = c
|
||||
.agency_profiles
|
||||
.values()
|
||||
.filter(|profile| profile.active_leaf && profile.simulation_eligible)
|
||||
.map(|profile| profile.subject_id.clone())
|
||||
.collect();
|
||||
if expected_profiles != actual_profiles {
|
||||
.map(|id| (id, AgencySubjectKind::Actor))
|
||||
.chain(
|
||||
c.institutions
|
||||
.keys()
|
||||
.map(|id| (id, AgencySubjectKind::Institution)),
|
||||
)
|
||||
.chain(c.gestalts.keys().map(|id| (id, AgencySubjectKind::Gestalt)));
|
||||
for (subject_id, expected_kind) in canonical_subjects {
|
||||
let Some(profile) = c.agency_profiles.get(subject_id) else {
|
||||
return Err(anyhow!(
|
||||
"campaign agency skeleton has incomplete subject coverage: {subject_id}"
|
||||
));
|
||||
};
|
||||
if profile.subject_id != *subject_id || profile.subject_kind != expected_kind {
|
||||
return Err(anyhow!(
|
||||
"campaign agency profile does not match canonical subject {subject_id}"
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(profile) = c.agency_profiles.values().find(|profile| {
|
||||
profile.active_leaf
|
||||
&& profile.simulation_eligible
|
||||
&& !c.actors.contains_key(&profile.subject_id)
|
||||
&& !c.institutions.contains_key(&profile.subject_id)
|
||||
&& !c.gestalts.contains_key(&profile.subject_id)
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"campaign agency skeleton has incomplete subject coverage"
|
||||
"active agency profile refers to unknown canonical subject {}",
|
||||
profile.subject_id
|
||||
));
|
||||
}
|
||||
let relationship_targets = c
|
||||
|
|
|
|||
|
|
@ -879,12 +879,33 @@ pub enum WorldCommand {
|
|||
proposal: Option<ActionAssessment>,
|
||||
},
|
||||
Attempt {
|
||||
actor_id: String,
|
||||
assessment_digest: String,
|
||||
},
|
||||
Wait {
|
||||
expected_revision: u64,
|
||||
minutes: u32,
|
||||
},
|
||||
ProposeTimeAdvance {
|
||||
expected_revision: u64,
|
||||
member_id: String,
|
||||
minutes: u32,
|
||||
},
|
||||
ApproveTimeAdvance {
|
||||
expected_revision: u64,
|
||||
proposal_id: String,
|
||||
member_id: String,
|
||||
},
|
||||
ProposeGroupTravel {
|
||||
expected_revision: u64,
|
||||
member_id: String,
|
||||
destination_location_id: String,
|
||||
},
|
||||
ApproveGroupTravel {
|
||||
expected_revision: u64,
|
||||
proposal_id: String,
|
||||
member_id: String,
|
||||
},
|
||||
AdvanceStrategicTick {
|
||||
expected_revision: u64,
|
||||
source: TickSource,
|
||||
|
|
@ -900,6 +921,17 @@ pub enum WorldCommand {
|
|||
expected_resolution_epoch: u64,
|
||||
active_cell_budget: u8,
|
||||
},
|
||||
ProposeResolutionBudget {
|
||||
expected_revision: u64,
|
||||
expected_resolution_epoch: u64,
|
||||
member_id: String,
|
||||
active_cell_budget: u8,
|
||||
},
|
||||
ApproveResolutionBudget {
|
||||
expected_revision: u64,
|
||||
proposal_id: String,
|
||||
member_id: String,
|
||||
},
|
||||
SetProviderParallelism {
|
||||
expected_revision: u64,
|
||||
expected_provider_configuration_epoch: u64,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
use crate::d20::{capped_modifier, receipt};
|
||||
use crate::domain::*;
|
||||
use crate::persistence::CampaignStore;
|
||||
use crate::session_zero::{
|
||||
CampaignMembership, CellBudgetProposal, GroupTravelProposal, TimeAdvanceProposal,
|
||||
};
|
||||
use chrono::{Duration, Utc};
|
||||
use rand::Rng;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -48,6 +51,18 @@ pub enum CommandResult {
|
|||
campaign: Campaign,
|
||||
receipt: ResolutionControlReceipt,
|
||||
},
|
||||
GovernancePending {
|
||||
campaign: Campaign,
|
||||
proposal: TimeAdvanceProposal,
|
||||
},
|
||||
TravelGovernancePending {
|
||||
campaign: Campaign,
|
||||
proposal: GroupTravelProposal,
|
||||
},
|
||||
ResolutionGovernancePending {
|
||||
campaign: Campaign,
|
||||
proposal: CellBudgetProposal,
|
||||
},
|
||||
}
|
||||
|
||||
struct Request {
|
||||
|
|
@ -157,6 +172,12 @@ fn execute(
|
|||
] {
|
||||
crate::assessor::validate_effect(&campaign, actor, effect, stake)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
validate_bounded_coop_effect(
|
||||
store,
|
||||
&campaign,
|
||||
&assessment.intent.actor_id,
|
||||
effect,
|
||||
)?;
|
||||
}
|
||||
assessment
|
||||
}
|
||||
|
|
@ -165,11 +186,19 @@ fn execute(
|
|||
assessments.insert(assessment.digest.clone(), assessment.clone());
|
||||
Ok(CommandResult::Assessed { assessment })
|
||||
}
|
||||
WorldCommand::Attempt { assessment_digest } => {
|
||||
WorldCommand::Attempt {
|
||||
actor_id,
|
||||
assessment_digest,
|
||||
} => {
|
||||
let assessment = assessments
|
||||
.get(&assessment_digest)
|
||||
.cloned()
|
||||
.ok_or(KernelError::UnknownAssessment)?;
|
||||
if assessment.intent.actor_id != actor_id {
|
||||
return Err(KernelError::Invalid(
|
||||
"assessment belongs to another actor".into(),
|
||||
));
|
||||
}
|
||||
if assessment.revision != campaign.revision || assessment.expires_at < Utc::now() {
|
||||
assessments.remove(&assessment_digest);
|
||||
return Err(KernelError::StaleAssessment {
|
||||
|
|
@ -208,7 +237,7 @@ fn execute(
|
|||
&mut campaign,
|
||||
std::iter::once(assessment.intent.actor_id.as_str()),
|
||||
);
|
||||
if assessment.intent.actor_id == campaign.player_actor_id {
|
||||
if is_human_controlled_actor(&campaign, &assessment.intent.actor_id) {
|
||||
campaign.last_player_activity = Utc::now();
|
||||
campaign.away_ticks_processed = 0;
|
||||
campaign.pending_ticks = 0;
|
||||
|
|
@ -253,7 +282,7 @@ fn execute(
|
|||
&mut campaign,
|
||||
std::iter::once(actor_id.as_str()),
|
||||
);
|
||||
if actor_id == campaign.player_actor_id {
|
||||
if is_human_controlled_actor(&campaign, &actor_id) {
|
||||
campaign.last_player_activity = Utc::now();
|
||||
campaign.away_ticks_processed = 0;
|
||||
campaign.pending_ticks = 0;
|
||||
|
|
@ -276,6 +305,223 @@ fn execute(
|
|||
campaign.pending_ticks = 0;
|
||||
commit(store, row, campaign, "wait", None)
|
||||
}
|
||||
WorldCommand::ProposeTimeAdvance {
|
||||
expected_revision,
|
||||
member_id,
|
||||
minutes,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
if minutes == 0 || minutes > 1_440 {
|
||||
return Err(KernelError::Invalid(
|
||||
"time advance must be between 1 and 1440 minutes".into(),
|
||||
));
|
||||
}
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
require_active_member(&membership, &member_id)?;
|
||||
if store
|
||||
.load_all::<TimeAdvanceProposal>("time_advance_proposal.v1")
|
||||
.map_err(persist)?
|
||||
.into_iter()
|
||||
.any(|proposal| {
|
||||
!proposal.committed && proposal.expected_world_revision == campaign.revision
|
||||
})
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"a time-advance proposal is already pending at this revision".into(),
|
||||
));
|
||||
}
|
||||
let proposal_id = format!("time:{}", uuid::Uuid::new_v4().simple());
|
||||
let proposal = TimeAdvanceProposal {
|
||||
schema: "ghostlight.time_advance_proposal.v1".into(),
|
||||
id: proposal_id.clone(),
|
||||
campaign_id: campaign.id,
|
||||
expected_world_revision: campaign.revision,
|
||||
minutes,
|
||||
proposer_member_id: member_id.clone(),
|
||||
approvals: BTreeSet::from([member_id]),
|
||||
committed: false,
|
||||
};
|
||||
let proposal_row = store
|
||||
.insert(
|
||||
"time_advance_proposal.v1",
|
||||
"ghostlight.time_advance_proposal.v1",
|
||||
&proposal_id,
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_time_advance(store, row, campaign, proposal_row, proposal)
|
||||
} else {
|
||||
Ok(CommandResult::GovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::ApproveTimeAdvance {
|
||||
expected_revision,
|
||||
proposal_id,
|
||||
member_id,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
require_active_member(&membership, &member_id)?;
|
||||
let (proposal_row, mut proposal) = store
|
||||
.load::<TimeAdvanceProposal>("time_advance_proposal.v1", &proposal_id)
|
||||
.map_err(persist)?
|
||||
.ok_or_else(|| KernelError::Invalid("time proposal does not exist".into()))?;
|
||||
if proposal.committed
|
||||
|| proposal.campaign_id != campaign.id
|
||||
|| proposal.expected_world_revision != campaign.revision
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"time proposal is committed, stale, or belongs to another campaign".into(),
|
||||
));
|
||||
}
|
||||
if !proposal.approvals.insert(member_id) {
|
||||
return Err(KernelError::Invalid(
|
||||
"member already approved this time proposal".into(),
|
||||
));
|
||||
}
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_time_advance(store, row, campaign, proposal_row, proposal)
|
||||
} else {
|
||||
store
|
||||
.replace(
|
||||
&proposal_row,
|
||||
"ghostlight.time_advance_proposal.v1",
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::GovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::ProposeGroupTravel {
|
||||
expected_revision,
|
||||
member_id,
|
||||
destination_location_id,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
let member = require_active_member(&membership, &member_id)?;
|
||||
let origin_location_id = campaign
|
||||
.actors
|
||||
.get(&member.actor_id)
|
||||
.ok_or_else(|| KernelError::Invalid("member actor is missing".into()))?
|
||||
.location_id
|
||||
.clone();
|
||||
if membership
|
||||
.members
|
||||
.values()
|
||||
.filter(|item| item.active)
|
||||
.any(|item| {
|
||||
campaign
|
||||
.actors
|
||||
.get(&item.actor_id)
|
||||
.is_none_or(|actor| actor.location_id != origin_location_id)
|
||||
})
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"group travel requires every player to occupy the same scene".into(),
|
||||
));
|
||||
}
|
||||
let route = campaign
|
||||
.locations
|
||||
.get(&origin_location_id)
|
||||
.and_then(|location| location.routes.get(&destination_location_id))
|
||||
.ok_or_else(|| {
|
||||
KernelError::Invalid("destination is not directly reachable".into())
|
||||
})?;
|
||||
if store
|
||||
.load_all::<GroupTravelProposal>("group_travel_proposal.v1")
|
||||
.map_err(persist)?
|
||||
.into_iter()
|
||||
.any(|proposal| {
|
||||
!proposal.committed && proposal.expected_world_revision == campaign.revision
|
||||
})
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"a group-travel proposal is already pending at this revision".into(),
|
||||
));
|
||||
}
|
||||
let proposal_id = format!("travel:{}", uuid::Uuid::new_v4().simple());
|
||||
let proposal = GroupTravelProposal {
|
||||
schema: "ghostlight.group_travel_proposal.v1".into(),
|
||||
id: proposal_id.clone(),
|
||||
campaign_id: campaign.id,
|
||||
expected_world_revision: campaign.revision,
|
||||
origin_location_id,
|
||||
destination_location_id,
|
||||
travel_minutes: route.travel_minutes,
|
||||
proposer_member_id: member_id.clone(),
|
||||
approvals: BTreeSet::from([member_id]),
|
||||
committed: false,
|
||||
};
|
||||
let proposal_row = store
|
||||
.insert(
|
||||
"group_travel_proposal.v1",
|
||||
"ghostlight.group_travel_proposal.v1",
|
||||
&proposal_id,
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_group_travel(
|
||||
store,
|
||||
row,
|
||||
campaign,
|
||||
proposal_row,
|
||||
proposal,
|
||||
&membership,
|
||||
)
|
||||
} else {
|
||||
Ok(CommandResult::TravelGovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::ApproveGroupTravel {
|
||||
expected_revision,
|
||||
proposal_id,
|
||||
member_id,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
require_active_member(&membership, &member_id)?;
|
||||
let (proposal_row, mut proposal) = store
|
||||
.load::<GroupTravelProposal>("group_travel_proposal.v1", &proposal_id)
|
||||
.map_err(persist)?
|
||||
.ok_or_else(|| {
|
||||
KernelError::Invalid("group-travel proposal does not exist".into())
|
||||
})?;
|
||||
if proposal.committed
|
||||
|| proposal.campaign_id != campaign.id
|
||||
|| proposal.expected_world_revision != campaign.revision
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"group-travel proposal is committed, stale, or belongs elsewhere".into(),
|
||||
));
|
||||
}
|
||||
if !proposal.approvals.insert(member_id) {
|
||||
return Err(KernelError::Invalid(
|
||||
"member already approved this group-travel proposal".into(),
|
||||
));
|
||||
}
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_group_travel(
|
||||
store,
|
||||
row,
|
||||
campaign,
|
||||
proposal_row,
|
||||
proposal,
|
||||
&membership,
|
||||
)
|
||||
} else {
|
||||
store
|
||||
.replace(
|
||||
&proposal_row,
|
||||
"ghostlight.group_travel_proposal.v1",
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::TravelGovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::SetResolutionBudget {
|
||||
expected_revision,
|
||||
expected_resolution_epoch,
|
||||
|
|
@ -303,6 +549,106 @@ fn execute(
|
|||
"set_active_cell_budget",
|
||||
)
|
||||
}
|
||||
WorldCommand::ProposeResolutionBudget {
|
||||
expected_revision,
|
||||
expected_resolution_epoch,
|
||||
member_id,
|
||||
active_cell_budget,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
require_resolution_epoch(&campaign, expected_resolution_epoch)?;
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
require_active_member(&membership, &member_id)?;
|
||||
if active_cell_budget == 0
|
||||
|| active_cell_budget > membership.pooled_cell_allowance()
|
||||
|| active_cell_budget == campaign.resolution_policy.active_cell_budget
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"cell budget must change and remain within the pooled allowance".into(),
|
||||
));
|
||||
}
|
||||
if store
|
||||
.load_all::<CellBudgetProposal>("cell_budget_proposal.v1")
|
||||
.map_err(persist)?
|
||||
.into_iter()
|
||||
.any(|proposal| {
|
||||
!proposal.committed
|
||||
&& proposal.expected_world_revision == campaign.revision
|
||||
&& proposal.expected_resolution_epoch
|
||||
== campaign.resolution_policy.resolution_epoch
|
||||
})
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"a cell-budget proposal is already pending at this boundary".into(),
|
||||
));
|
||||
}
|
||||
let proposal_id = format!("cell-budget:{}", uuid::Uuid::new_v4().simple());
|
||||
let proposal = CellBudgetProposal {
|
||||
schema: "ghostlight.cell_budget_proposal.v1".into(),
|
||||
id: proposal_id.clone(),
|
||||
campaign_id: campaign.id,
|
||||
expected_world_revision: campaign.revision,
|
||||
expected_resolution_epoch: campaign.resolution_policy.resolution_epoch,
|
||||
active_cell_budget,
|
||||
proposer_member_id: member_id.clone(),
|
||||
approvals: BTreeSet::from([member_id]),
|
||||
committed: false,
|
||||
};
|
||||
let proposal_row = store
|
||||
.insert(
|
||||
"cell_budget_proposal.v1",
|
||||
"ghostlight.cell_budget_proposal.v1",
|
||||
&proposal_id,
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_cell_budget(store, row, campaign, proposal_row, proposal)
|
||||
} else {
|
||||
Ok(CommandResult::ResolutionGovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::ApproveResolutionBudget {
|
||||
expected_revision,
|
||||
proposal_id,
|
||||
member_id,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let membership = load_campaign_membership(store, campaign.id)?;
|
||||
require_active_member(&membership, &member_id)?;
|
||||
let (proposal_row, mut proposal) = store
|
||||
.load::<CellBudgetProposal>("cell_budget_proposal.v1", &proposal_id)
|
||||
.map_err(persist)?
|
||||
.ok_or_else(|| {
|
||||
KernelError::Invalid("cell-budget proposal does not exist".into())
|
||||
})?;
|
||||
if proposal.committed
|
||||
|| proposal.campaign_id != campaign.id
|
||||
|| proposal.expected_world_revision != campaign.revision
|
||||
|| proposal.expected_resolution_epoch != campaign.resolution_policy.resolution_epoch
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"cell-budget proposal is committed, stale, or belongs elsewhere".into(),
|
||||
));
|
||||
}
|
||||
if !proposal.approvals.insert(member_id) {
|
||||
return Err(KernelError::Invalid(
|
||||
"member already approved this cell-budget proposal".into(),
|
||||
));
|
||||
}
|
||||
if active_member_ids(&membership) == proposal.approvals {
|
||||
commit_governed_cell_budget(store, row, campaign, proposal_row, proposal)
|
||||
} else {
|
||||
store
|
||||
.replace(
|
||||
&proposal_row,
|
||||
"ghostlight.cell_budget_proposal.v1",
|
||||
&proposal,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::ResolutionGovernancePending { campaign, proposal })
|
||||
}
|
||||
}
|
||||
WorldCommand::SetProviderParallelism {
|
||||
expected_revision,
|
||||
expected_provider_configuration_epoch,
|
||||
|
|
@ -547,15 +893,10 @@ fn execute(
|
|||
campaign.resolution_cover = Some(wave.cover.clone());
|
||||
}
|
||||
campaign.strategic_tick_count = campaign.strategic_tick_count.saturating_add(1);
|
||||
let player = campaign.actors.get(&campaign.player_actor_id);
|
||||
for event in &tick_events {
|
||||
let accessible = event
|
||||
.public_channels
|
||||
.iter()
|
||||
.find(|channel| player.is_some_and(|actor| actor.knowledge.contains(*channel)));
|
||||
if let Some(channel) = accessible {
|
||||
for channel in &event.public_channels {
|
||||
campaign.news.push(crate::domain::NewsIssue {
|
||||
id: format!("news:{}", event.id),
|
||||
id: format!("news:{}:{}", event.id, stable_channel_id(channel)),
|
||||
at: campaign.world_time,
|
||||
channel: channel.clone(),
|
||||
headline: event.summary.clone(),
|
||||
|
|
@ -833,6 +1174,7 @@ fn execute(
|
|||
] {
|
||||
crate::assessor::validate_effect(&campaign, actor, effect, stake)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
validate_bounded_coop_effect(store, &campaign, &proposal.actor_id, effect)?;
|
||||
}
|
||||
let actor_name = actor.name.clone();
|
||||
let actor_location = actor.location_id.clone();
|
||||
|
|
@ -1270,6 +1612,14 @@ fn require_revision(c: &Campaign, expected: u64) -> Result<(), KernelError> {
|
|||
}
|
||||
}
|
||||
|
||||
fn is_human_controlled_actor(campaign: &Campaign, actor_id: &str) -> bool {
|
||||
actor_id == campaign.player_actor_id
|
||||
|| campaign
|
||||
.agency_profiles
|
||||
.get(actor_id)
|
||||
.is_some_and(|profile| !profile.simulation_eligible)
|
||||
}
|
||||
|
||||
fn require_resolution_epoch(c: &Campaign, expected: u64) -> Result<(), KernelError> {
|
||||
if c.resolution_policy.resolution_epoch != expected {
|
||||
return Err(KernelError::Invalid(format!(
|
||||
|
|
@ -1614,9 +1964,9 @@ fn apply_strategic_tick_plan(
|
|||
"actor moves twice in one strategic tick".into(),
|
||||
));
|
||||
}
|
||||
if action.actor_id == campaign.player_actor_id {
|
||||
if is_human_controlled_actor(campaign, &action.actor_id) {
|
||||
return Err(KernelError::Invalid(
|
||||
"strategic simulation cannot puppet the player".into(),
|
||||
"strategic simulation cannot puppet a human-controlled actor".into(),
|
||||
));
|
||||
}
|
||||
validate_public_channels(&action.public_channels)?;
|
||||
|
|
@ -2456,6 +2806,223 @@ fn commit(
|
|||
Ok(CommandResult::Committed { campaign, receipt })
|
||||
}
|
||||
|
||||
fn load_campaign_membership(
|
||||
store: &CampaignStore,
|
||||
campaign_id: uuid::Uuid,
|
||||
) -> Result<CampaignMembership, KernelError> {
|
||||
store
|
||||
.load::<CampaignMembership>("campaign_membership.v1", &campaign_id.to_string())
|
||||
.map_err(persist)?
|
||||
.map(|(_, membership)| membership)
|
||||
.ok_or_else(|| KernelError::Invalid("campaign membership is missing".into()))
|
||||
}
|
||||
|
||||
fn optional_campaign_membership(
|
||||
store: &CampaignStore,
|
||||
campaign_id: uuid::Uuid,
|
||||
) -> Result<Option<CampaignMembership>, KernelError> {
|
||||
store
|
||||
.load::<CampaignMembership>("campaign_membership.v1", &campaign_id.to_string())
|
||||
.map_err(persist)
|
||||
.map(|value| value.map(|(_, membership)| membership))
|
||||
}
|
||||
|
||||
fn validate_bounded_coop_effect(
|
||||
store: &CampaignStore,
|
||||
campaign: &Campaign,
|
||||
acting_actor_id: &str,
|
||||
effect: &WorldEffectDelta,
|
||||
) -> Result<(), KernelError> {
|
||||
let Some(membership) = optional_campaign_membership(store, campaign.id)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let controlled = membership.controlled_actor_ids();
|
||||
if controlled.len() < 2 || !controlled.contains(acting_actor_id) {
|
||||
return Ok(());
|
||||
}
|
||||
if !effect.actor_moves.is_empty() {
|
||||
return Err(KernelError::Invalid(
|
||||
"co-op travel requires a unanimous group-travel proposal".into(),
|
||||
));
|
||||
}
|
||||
let mut protected_targets = BTreeSet::new();
|
||||
protected_targets.extend(effect.actor_conditions.keys().cloned());
|
||||
protected_targets.extend(effect.actor_knowledge_additions.keys().cloned());
|
||||
protected_targets.extend(effect.actor_relationship_updates.keys().cloned());
|
||||
if protected_targets
|
||||
.iter()
|
||||
.any(|target| target != acting_actor_id && controlled.contains(target))
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"player-versus-player effects are unsupported in bounded co-op".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stable_channel_id(channel: &str) -> String {
|
||||
format!("{:x}", Sha256::digest(channel.as_bytes()))[..12].to_string()
|
||||
}
|
||||
|
||||
fn require_active_member<'a>(
|
||||
membership: &'a CampaignMembership,
|
||||
member_id: &str,
|
||||
) -> Result<&'a crate::session_zero::CampaignMember, KernelError> {
|
||||
membership
|
||||
.members
|
||||
.get(member_id)
|
||||
.filter(|member| member.active)
|
||||
.ok_or_else(|| KernelError::Invalid("campaign member is not active".into()))
|
||||
}
|
||||
|
||||
fn active_member_ids(membership: &CampaignMembership) -> BTreeSet<String> {
|
||||
membership
|
||||
.members
|
||||
.values()
|
||||
.filter(|member| member.active)
|
||||
.map(|member| member.member_id.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn commit_governed_time_advance(
|
||||
store: &CampaignStore,
|
||||
campaign_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut campaign: Campaign,
|
||||
proposal_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut proposal: TimeAdvanceProposal,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
campaign.world_time += Duration::minutes(i64::from(proposal.minutes));
|
||||
campaign.last_player_activity = Utc::now();
|
||||
campaign.away_ticks_processed = 0;
|
||||
campaign.pending_ticks = 0;
|
||||
crate::resolution::ensure_agency_profiles(&mut campaign);
|
||||
let previous_revision = campaign.revision;
|
||||
campaign.revision = campaign.revision.saturating_add(1);
|
||||
proposal.committed = true;
|
||||
let receipt = WorldCommitReceipt {
|
||||
schema: "ghostlight.world_commit_receipt.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
previous_revision,
|
||||
revision: campaign.revision,
|
||||
command_kind: "unanimous_time_advance".into(),
|
||||
committed_at: Utc::now(),
|
||||
roll: None,
|
||||
};
|
||||
store
|
||||
.commit_time_advance(&campaign_row, &campaign, &proposal_row, &proposal, &receipt)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::Committed { campaign, receipt })
|
||||
}
|
||||
|
||||
fn commit_governed_group_travel(
|
||||
store: &CampaignStore,
|
||||
campaign_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut campaign: Campaign,
|
||||
proposal_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut proposal: GroupTravelProposal,
|
||||
membership: &CampaignMembership,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
let active_actor_ids = membership.controlled_actor_ids();
|
||||
if active_actor_ids.iter().any(|actor_id| {
|
||||
campaign
|
||||
.actors
|
||||
.get(actor_id)
|
||||
.is_none_or(|actor| actor.location_id != proposal.origin_location_id)
|
||||
}) {
|
||||
return Err(KernelError::Invalid(
|
||||
"group-travel proposal no longer matches the shared scene".into(),
|
||||
));
|
||||
}
|
||||
let route_minutes = campaign
|
||||
.locations
|
||||
.get(&proposal.origin_location_id)
|
||||
.and_then(|location| location.routes.get(&proposal.destination_location_id))
|
||||
.map(|route| route.travel_minutes)
|
||||
.ok_or_else(|| KernelError::Invalid("group-travel route no longer exists".into()))?;
|
||||
if route_minutes != proposal.travel_minutes {
|
||||
return Err(KernelError::Invalid(
|
||||
"group-travel route changed after proposal".into(),
|
||||
));
|
||||
}
|
||||
for actor_id in &active_actor_ids {
|
||||
campaign
|
||||
.actors
|
||||
.get_mut(actor_id)
|
||||
.expect("active actor was checked")
|
||||
.location_id = proposal.destination_location_id.clone();
|
||||
}
|
||||
campaign.world_time += Duration::minutes(i64::from(route_minutes));
|
||||
campaign.last_player_activity = Utc::now();
|
||||
campaign.away_ticks_processed = 0;
|
||||
campaign.pending_ticks = 0;
|
||||
let previous_revision = campaign.revision;
|
||||
campaign.revision = campaign.revision.saturating_add(1);
|
||||
campaign.events.push(Event {
|
||||
id: format!("group-travel:{}", campaign.revision),
|
||||
at: campaign.world_time,
|
||||
kind: "group_travel".into(),
|
||||
summary: format!(
|
||||
"The party travels from {} to {}.",
|
||||
proposal.origin_location_id, proposal.destination_location_id
|
||||
),
|
||||
actor_ids: active_actor_ids.into_iter().collect(),
|
||||
institution_ids: vec![],
|
||||
gestalt_ids: vec![],
|
||||
location_ids: vec![
|
||||
proposal.origin_location_id.clone(),
|
||||
proposal.destination_location_id.clone(),
|
||||
],
|
||||
public_channels: vec![],
|
||||
});
|
||||
proposal.committed = true;
|
||||
let receipt = WorldCommitReceipt {
|
||||
schema: "ghostlight.world_commit_receipt.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
previous_revision,
|
||||
revision: campaign.revision,
|
||||
command_kind: "unanimous_group_travel".into(),
|
||||
committed_at: Utc::now(),
|
||||
roll: None,
|
||||
};
|
||||
store
|
||||
.commit_group_travel(&campaign_row, &campaign, &proposal_row, &proposal, &receipt)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::Committed { campaign, receipt })
|
||||
}
|
||||
|
||||
fn commit_governed_cell_budget(
|
||||
store: &CampaignStore,
|
||||
campaign_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut campaign: Campaign,
|
||||
proposal_row: cultcache_legacy::CultCacheEnvelope,
|
||||
mut proposal: CellBudgetProposal,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
let previous_epoch = campaign.resolution_policy.resolution_epoch;
|
||||
campaign.resolution_policy.active_cell_budget = proposal.active_cell_budget;
|
||||
campaign.resolution_policy.pending_active_cell_budget = None;
|
||||
campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1);
|
||||
campaign.resolution_cover = None;
|
||||
crate::resolution::validate_policy(&campaign.resolution_policy)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
proposal.committed = true;
|
||||
let receipt = ResolutionControlReceipt {
|
||||
schema: "ghostlight.resolution_control_receipt.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
world_revision: campaign.revision,
|
||||
previous_resolution_epoch: previous_epoch,
|
||||
resolution_epoch: campaign.resolution_policy.resolution_epoch,
|
||||
provider_configuration_epoch: campaign.resolution_policy.provider_configuration_epoch,
|
||||
operation: "unanimous_set_active_cell_budget".into(),
|
||||
active_cell_budget: campaign.resolution_policy.active_cell_budget,
|
||||
pin_ids: campaign.resolution_pins.keys().cloned().collect(),
|
||||
committed_at: Utc::now(),
|
||||
};
|
||||
store
|
||||
.commit_cell_budget(&campaign_row, &campaign, &proposal_row, &proposal, &receipt)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::ResolutionUpdated { campaign, receipt })
|
||||
}
|
||||
|
||||
fn commit_with_records(
|
||||
store: &CampaignStore,
|
||||
row: cultcache_legacy::CultCacheEnvelope,
|
||||
|
|
@ -3868,6 +4435,7 @@ mod tests {
|
|||
assert_eq!(before.revision, 0);
|
||||
let result = kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
actor_id: "player".into(),
|
||||
assessment_digest: assessment.digest,
|
||||
})
|
||||
.await
|
||||
|
|
@ -3922,6 +4490,7 @@ mod tests {
|
|||
.unwrap();
|
||||
let error = kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
actor_id: "player".into(),
|
||||
assessment_digest: assessment.digest,
|
||||
})
|
||||
.await
|
||||
|
|
@ -3940,7 +4509,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strategic_tick_moves_institutions_but_news_respects_access() {
|
||||
async fn strategic_tick_persists_channel_news_without_using_legacy_host_as_truth() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
|
|
@ -3977,7 +4546,8 @@ mod tests {
|
|||
panic!("expected commit")
|
||||
};
|
||||
assert_eq!(campaign.events.len(), 1);
|
||||
assert!(campaign.news.is_empty());
|
||||
assert_eq!(campaign.news.len(), 1);
|
||||
assert_eq!(campaign.news[0].channel, "institution:board");
|
||||
assert_eq!(campaign.away_ticks_processed, 1);
|
||||
assert!(campaign.institutions["board"].posture.contains("acting"));
|
||||
let ticks = store
|
||||
|
|
@ -4703,6 +5273,7 @@ mod tests {
|
|||
.unwrap();
|
||||
kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
actor_id: "player".into(),
|
||||
assessment_digest: valid.digest,
|
||||
})
|
||||
.await
|
||||
|
|
@ -5360,4 +5931,204 @@ mod tests {
|
|||
assert_eq!(after, before);
|
||||
assert!(store.keys("strategic_tick.v1").unwrap().is_empty());
|
||||
}
|
||||
|
||||
fn two_player_membership(campaign: &mut Campaign) -> CampaignMembership {
|
||||
let mut guest = campaign.actors["player"].clone();
|
||||
guest.id = "guest".into();
|
||||
guest.name = "Guest".into();
|
||||
campaign.actors.insert(guest.id.clone(), guest);
|
||||
crate::resolution::ensure_agency_profiles(campaign);
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("player")
|
||||
.unwrap()
|
||||
.simulation_eligible = false;
|
||||
campaign
|
||||
.agency_profiles
|
||||
.get_mut("guest")
|
||||
.unwrap()
|
||||
.simulation_eligible = false;
|
||||
CampaignMembership {
|
||||
schema: "ghostlight.campaign_membership.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
governance_epoch: 0,
|
||||
host_member_id: "member:host".into(),
|
||||
members: BTreeMap::from([
|
||||
(
|
||||
"member:host".into(),
|
||||
crate::session_zero::CampaignMember {
|
||||
member_id: "member:host".into(),
|
||||
account_hash: "account:host".into(),
|
||||
display_name: "Host".into(),
|
||||
actor_id: "player".into(),
|
||||
is_host: true,
|
||||
active: true,
|
||||
cell_allowance: 8,
|
||||
},
|
||||
),
|
||||
(
|
||||
"member:guest".into(),
|
||||
crate::session_zero::CampaignMember {
|
||||
member_id: "member:guest".into(),
|
||||
account_hash: "account:guest".into(),
|
||||
display_name: "Guest".into(),
|
||||
actor_id: "guest".into(),
|
||||
is_host: false,
|
||||
active: true,
|
||||
cell_allowance: 8,
|
||||
},
|
||||
),
|
||||
]),
|
||||
extraordinary_permissions: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn group_travel_moves_every_member_once_after_unanimous_revision_bound_approval() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let mut seed = campaign();
|
||||
seed.locations.insert(
|
||||
"harbor".into(),
|
||||
Location {
|
||||
id: "harbor".into(),
|
||||
name: "Harbor".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::new(),
|
||||
persistent_features: vec!["stone quay".into()],
|
||||
},
|
||||
);
|
||||
seed.locations.get_mut("room").unwrap().routes.insert(
|
||||
"harbor".into(),
|
||||
Route {
|
||||
destination_id: "harbor".into(),
|
||||
distance: "nearby".into(),
|
||||
travel_minutes: 20,
|
||||
},
|
||||
);
|
||||
let membership = two_player_membership(&mut seed);
|
||||
let campaign_id = seed.id;
|
||||
let start_time = seed.world_time;
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed,
|
||||
evidence_receipts: vec![],
|
||||
model_stage_receipts: vec![],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.insert(
|
||||
"campaign_membership.v1",
|
||||
"ghostlight.campaign_membership.v1",
|
||||
&campaign_id.to_string(),
|
||||
&membership,
|
||||
)
|
||||
.unwrap();
|
||||
let pending = kernel
|
||||
.command(WorldCommand::ProposeGroupTravel {
|
||||
expected_revision: 0,
|
||||
member_id: "member:host".into(),
|
||||
destination_location_id: "harbor".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::TravelGovernancePending { proposal, campaign } = pending else {
|
||||
panic!("first approval committed a two-member proposal")
|
||||
};
|
||||
assert_eq!(campaign.revision, 0);
|
||||
assert_eq!(campaign.actors["player"].location_id, "room");
|
||||
let proposal_id = proposal.id;
|
||||
let committed = kernel
|
||||
.command(WorldCommand::ApproveGroupTravel {
|
||||
expected_revision: 0,
|
||||
proposal_id: proposal_id.clone(),
|
||||
member_id: "member:guest".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Committed { campaign, receipt } = committed else {
|
||||
panic!("unanimous travel did not commit")
|
||||
};
|
||||
assert_eq!(receipt.command_kind, "unanimous_group_travel");
|
||||
assert_eq!(campaign.revision, 1);
|
||||
assert_eq!(campaign.world_time, start_time + Duration::minutes(20));
|
||||
assert_eq!(campaign.actors["player"].location_id, "harbor");
|
||||
assert_eq!(campaign.actors["guest"].location_id, "harbor");
|
||||
assert!(
|
||||
kernel
|
||||
.command(WorldCommand::ApproveGroupTravel {
|
||||
expected_revision: 0,
|
||||
proposal_id,
|
||||
member_id: "member:guest".into(),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.load::<Campaign>("campaign.v1", &campaign_id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1
|
||||
.revision,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kernel_rejects_player_effects_against_another_controlled_actor() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let mut seed = campaign();
|
||||
let membership = two_player_membership(&mut seed);
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed.clone(),
|
||||
evidence_receipts: vec![],
|
||||
model_stage_receipts: vec![],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.insert(
|
||||
"campaign_membership.v1",
|
||||
"ghostlight.campaign_membership.v1",
|
||||
&seed.id.to_string(),
|
||||
&membership,
|
||||
)
|
||||
.unwrap();
|
||||
let intent = ActionIntent {
|
||||
actor_id: "player".into(),
|
||||
description: "shove Guest".into(),
|
||||
intended_effect: "make Guest prone".into(),
|
||||
};
|
||||
let mut assessment = assess(&seed, intent.clone());
|
||||
assessment.success_effect.actor_conditions.insert(
|
||||
"guest".into(),
|
||||
ConditionDelta {
|
||||
add: BTreeSet::from(["prone".into()]),
|
||||
remove: BTreeSet::new(),
|
||||
},
|
||||
);
|
||||
assessment.digest = crate::assessor::assessment_digest(&assessment).unwrap();
|
||||
let error = kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: 0,
|
||||
intent,
|
||||
proposal: Some(assessment),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("player-versus-player"));
|
||||
let stored = store
|
||||
.load::<Campaign>("campaign.v1", &seed.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(stored.revision, 0);
|
||||
assert!(!stored.actors["guest"].conditions.contains("prone"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod assessor;
|
||||
pub mod compiler;
|
||||
pub mod d20;
|
||||
|
|
@ -14,6 +16,7 @@ pub mod persona;
|
|||
pub mod registry;
|
||||
pub mod resolution;
|
||||
pub mod scheduler;
|
||||
pub mod session_zero;
|
||||
pub mod surface;
|
||||
pub mod turn;
|
||||
pub mod vault;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -12,7 +12,14 @@ use crate::{
|
|||
WorldActionProposal, WorldClock, WorldCommitReceipt, WorldCompilePreview, WorldFact,
|
||||
},
|
||||
model::ModelStageReceipt,
|
||||
surface::{operator_surface, player_surface},
|
||||
session_zero::{
|
||||
ActiveContractBoundaryPolicy, ApprovedCampaignBrief, CampaignContract, CampaignDmPersona,
|
||||
CampaignGovernance, CampaignMembership, CellBudgetProposal, CharacterDraft,
|
||||
ContentBoundary, ExtraordinaryPermission, GroupTravelProposal, SessionZeroApproval,
|
||||
SessionZeroChannel, SessionZeroDecision, SessionZeroDelta, SessionZeroMember,
|
||||
SessionZeroMessage, SessionZeroState, TimeAdvanceProposal,
|
||||
},
|
||||
surface::{operator_surface, player_surface, player_surface_for_actor},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use chrono::Utc;
|
||||
|
|
@ -36,6 +43,7 @@ pub const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
|
|||
#[derive(Clone)]
|
||||
pub struct CampaignMeshSnapshot {
|
||||
pub campaign: Campaign,
|
||||
pub membership: Option<CampaignMembership>,
|
||||
pub narrations: Vec<NarrationProjection>,
|
||||
pub evidence: Vec<VaultEvidenceReceipt>,
|
||||
pub commits: Vec<WorldCommitReceipt>,
|
||||
|
|
@ -49,6 +57,13 @@ pub struct CampaignMeshSnapshot {
|
|||
pub resolution_controls: Vec<ResolutionControlReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SessionZeroMeshSnapshot {
|
||||
pub session_zero_id: uuid::Uuid,
|
||||
pub member_id: String,
|
||||
pub surface: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "gamecult.eve.surface", schema = "gamecult.eve.surface.v1")]
|
||||
pub struct EveSurfaceRecord {
|
||||
|
|
@ -147,6 +162,7 @@ impl MeshPublisher {
|
|||
pub fn publish_snapshot(
|
||||
&self,
|
||||
campaigns: &[CampaignMeshSnapshot],
|
||||
session_zeros: &[SessionZeroMeshSnapshot],
|
||||
deepseek_status: &str,
|
||||
live_turn_pressure: usize,
|
||||
) -> Result<Value> {
|
||||
|
|
@ -155,6 +171,7 @@ impl MeshPublisher {
|
|||
"schema":"ghostlight.service_health.v1",
|
||||
"status":"ok",
|
||||
"campaigns":campaigns.len(),
|
||||
"sessionZeros":session_zeros.len(),
|
||||
"deepseek":deepseek_status,
|
||||
"scheduler":{"live_turn_pressure":live_turn_pressure},
|
||||
"updatedAtUtc":updated_at,
|
||||
|
|
@ -179,6 +196,25 @@ impl MeshPublisher {
|
|||
"ghostlight.member_migration.v1",
|
||||
"ghostlight.news_issue.v1",
|
||||
"ghostlight.canon_candidate.v1",
|
||||
"ghostlight.session_zero.v1",
|
||||
"ghostlight.session_zero_member.v1",
|
||||
"ghostlight.session_zero_message.v1",
|
||||
"ghostlight.session_zero_channel.v1",
|
||||
"ghostlight.campaign_contract.v1",
|
||||
"ghostlight.character_draft.v1",
|
||||
"ghostlight.content_boundary.v1",
|
||||
"ghostlight.active_contract_boundary_policy.v1",
|
||||
"ghostlight.session_zero_decision.v1",
|
||||
"ghostlight.session_zero_delta.v1",
|
||||
"ghostlight.session_zero_approval.v1",
|
||||
"ghostlight.approved_campaign_brief.v1",
|
||||
"ghostlight.campaign_dm_persona.v1",
|
||||
"ghostlight.campaign_membership.v1",
|
||||
"ghostlight.campaign_governance.v1",
|
||||
"ghostlight.extraordinary_permission.v1",
|
||||
"ghostlight.time_advance_proposal.v1",
|
||||
"ghostlight.group_travel_proposal.v1",
|
||||
"ghostlight.cell_budget_proposal.v1",
|
||||
];
|
||||
let catalog = json!({
|
||||
"schema":"ghostlight.schema_catalog.v1",
|
||||
|
|
@ -186,23 +222,29 @@ impl MeshPublisher {
|
|||
"schemas":schema_catalog(),
|
||||
"updatedAtUtc":updated_at
|
||||
});
|
||||
let surfaces = campaigns
|
||||
let mut surfaces = campaigns
|
||||
.iter()
|
||||
.flat_map(|snapshot| {
|
||||
let campaign = &snapshot.campaign;
|
||||
[
|
||||
json!({
|
||||
let mut values = snapshot.membership.as_ref().map_or_else(
|
||||
|| vec![json!({
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"surfaceId":format!("ghostlight.campaign.{}",campaign.id),
|
||||
"key":format!("eve:surface:ghostlight.campaign.{}",campaign.id),
|
||||
"transport":"cultmesh-record",
|
||||
"status":"available",
|
||||
"audience":"authenticated-player",
|
||||
"mode":"interactive",
|
||||
"surfaceKind":"interactive-world",
|
||||
"interactionModel":"provider-command-receipts"
|
||||
}),
|
||||
json!({
|
||||
"transport":"cultmesh-record","status":"available",
|
||||
"audience":"legacy-owner","mode":"interactive",
|
||||
"surfaceKind":"interactive-world","interactionModel":"provider-command-receipts"
|
||||
})],
|
||||
|membership| membership.members.values().filter(|member|member.active).map(|member|json!({
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"surfaceId":format!("ghostlight.campaign.{}.{}",campaign.id,member.member_id),
|
||||
"key":format!("eve:surface:ghostlight.campaign.{}.{}",campaign.id,member.member_id),
|
||||
"transport":"cultmesh-record","status":"available",
|
||||
"audience":member.member_id,"mode":"interactive",
|
||||
"surfaceKind":"actor-filtered-interactive-world","interactionModel":"provider-command-receipts"
|
||||
})).collect()
|
||||
);
|
||||
values.push(json!({
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"surfaceId":format!("ghostlight.operator.{}",campaign.id),
|
||||
"key":format!("eve:operator:ghostlight.campaign.{}",campaign.id),
|
||||
|
|
@ -212,10 +254,18 @@ impl MeshPublisher {
|
|||
"mode":"inspect",
|
||||
"surfaceKind":"operator-inspector",
|
||||
"interactionModel":"read-only-receipt-inspection"
|
||||
}),
|
||||
]
|
||||
}));
|
||||
values
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
surfaces.extend(session_zeros.iter().map(|snapshot| json!({
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"surfaceId":format!("ghostlight.session-zero.{}.{}",snapshot.session_zero_id,snapshot.member_id),
|
||||
"key":format!("eve:surface:ghostlight.session-zero.{}.{}",snapshot.session_zero_id,snapshot.member_id),
|
||||
"transport":"cultmesh-record","status":"available",
|
||||
"audience":snapshot.member_id,"mode":"interactive",
|
||||
"surfaceKind":"actor-filtered-session-zero","interactionModel":"provider-command-receipts"
|
||||
})));
|
||||
let advertisement = json!({
|
||||
"schema":"gamecult.eve.provider_advertisement.v1",
|
||||
"providerId":PROVIDER_ID,
|
||||
|
|
@ -274,16 +324,62 @@ impl MeshPublisher {
|
|||
)
|
||||
.saturating_add(campaign.resolution_policy.provider_configuration_epoch)
|
||||
as i64;
|
||||
let surface = player_surface(campaign, &snapshot.narrations);
|
||||
let key = format!("eve:surface:ghostlight.campaign.{}", campaign.id);
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
&key,
|
||||
&EveSurfaceRecord {
|
||||
value: surface.clone(),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
if let Some(membership) = &snapshot.membership {
|
||||
for member in membership.members.values().filter(|member| member.active) {
|
||||
let surface =
|
||||
player_surface_for_actor(campaign, &member.actor_id, &snapshot.narrations);
|
||||
let key = format!(
|
||||
"eve:surface:ghostlight.campaign.{}.{}",
|
||||
campaign.id, member.member_id
|
||||
);
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
&key,
|
||||
&EveSurfaceRecord { value: surface },
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
format!(
|
||||
"eve:surface-state:ghostlight.campaign.{}.{}",
|
||||
campaign.id, member.member_id
|
||||
),
|
||||
&EveSurfaceStateRecord {
|
||||
provider_id: PROVIDER_ID.into(),
|
||||
title: campaign.name.clone(),
|
||||
version: interface_version,
|
||||
updated_at: updated_at.clone(),
|
||||
surface: player_surface_for_actor(
|
||||
campaign,
|
||||
&member.actor_id,
|
||||
&snapshot.narrations,
|
||||
),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
}
|
||||
} else {
|
||||
let surface = player_surface(campaign, &snapshot.narrations);
|
||||
let key = format!("eve:surface:ghostlight.campaign.{}", campaign.id);
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
&key,
|
||||
&EveSurfaceRecord { value: surface },
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
format!("eve:surface-state:ghostlight.campaign.{}", campaign.id),
|
||||
&EveSurfaceStateRecord {
|
||||
provider_id: PROVIDER_ID.into(),
|
||||
title: campaign.name.clone(),
|
||||
version: interface_version,
|
||||
updated_at: updated_at.clone(),
|
||||
surface: player_surface(campaign, &snapshot.narrations),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
}
|
||||
let operator = operator_surface(
|
||||
campaign,
|
||||
&snapshot.evidence,
|
||||
|
|
@ -318,15 +414,35 @@ impl MeshPublisher {
|
|||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
}
|
||||
for snapshot in session_zeros {
|
||||
let key = format!(
|
||||
"eve:surface:ghostlight.session-zero.{}.{}",
|
||||
snapshot.session_zero_id, snapshot.member_id
|
||||
);
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
format!("eve:surface-state:ghostlight.campaign.{}", campaign.id),
|
||||
&key,
|
||||
&EveSurfaceRecord {
|
||||
value: snapshot.surface.clone(),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
format!(
|
||||
"eve:surface-state:ghostlight.session-zero.{}.{}",
|
||||
snapshot.session_zero_id, snapshot.member_id
|
||||
),
|
||||
&EveSurfaceStateRecord {
|
||||
provider_id: PROVIDER_ID.into(),
|
||||
title: campaign.name.clone(),
|
||||
version: interface_version,
|
||||
title: snapshot.surface["title"]
|
||||
.as_str()
|
||||
.unwrap_or("Session Zero")
|
||||
.into(),
|
||||
version: snapshot.surface["version"].as_i64().unwrap_or_default(),
|
||||
updated_at: updated_at.clone(),
|
||||
surface,
|
||||
surface: snapshot.surface.clone(),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
|
|
@ -481,6 +597,25 @@ fn schema_catalog() -> Value {
|
|||
"ghostlight.cell_appraisal.v1": schemars::schema_for!(CellAppraisal),
|
||||
"ghostlight.cell_action_proposal.v1": schemars::schema_for!(CellActionProposal),
|
||||
"ghostlight.gestalt_fission_preview.v1": schemars::schema_for!(GestaltFissionPreview)
|
||||
,"ghostlight.session_zero.v1": schemars::schema_for!(SessionZeroState),
|
||||
"ghostlight.session_zero_member.v1": schemars::schema_for!(SessionZeroMember),
|
||||
"ghostlight.session_zero_message.v1": schemars::schema_for!(SessionZeroMessage),
|
||||
"ghostlight.session_zero_channel.v1": schemars::schema_for!(SessionZeroChannel),
|
||||
"ghostlight.campaign_contract.v1": schemars::schema_for!(CampaignContract),
|
||||
"ghostlight.character_draft.v1": schemars::schema_for!(CharacterDraft),
|
||||
"ghostlight.content_boundary.v1": schemars::schema_for!(ContentBoundary),
|
||||
"ghostlight.active_contract_boundary_policy.v1": schemars::schema_for!(ActiveContractBoundaryPolicy),
|
||||
"ghostlight.session_zero_decision.v1": schemars::schema_for!(SessionZeroDecision),
|
||||
"ghostlight.session_zero_delta.v1": schemars::schema_for!(SessionZeroDelta),
|
||||
"ghostlight.session_zero_approval.v1": schemars::schema_for!(SessionZeroApproval),
|
||||
"ghostlight.approved_campaign_brief.v1": schemars::schema_for!(ApprovedCampaignBrief),
|
||||
"ghostlight.campaign_dm_persona.v1": schemars::schema_for!(CampaignDmPersona),
|
||||
"ghostlight.campaign_membership.v1": schemars::schema_for!(CampaignMembership),
|
||||
"ghostlight.campaign_governance.v1": schemars::schema_for!(CampaignGovernance),
|
||||
"ghostlight.extraordinary_permission.v1": schemars::schema_for!(ExtraordinaryPermission),
|
||||
"ghostlight.time_advance_proposal.v1": schemars::schema_for!(TimeAdvanceProposal),
|
||||
"ghostlight.group_travel_proposal.v1": schemars::schema_for!(GroupTravelProposal),
|
||||
"ghostlight.cell_budget_proposal.v1": schemars::schema_for!(CellBudgetProposal)
|
||||
});
|
||||
let schemas = catalog
|
||||
.as_object_mut()
|
||||
|
|
@ -512,7 +647,9 @@ mod tests {
|
|||
fn health_is_read_from_the_same_typed_mesh_record_that_is_published() {
|
||||
let temp = tempdir().unwrap();
|
||||
let publisher = MeshPublisher::open(temp.path().join("mesh.cc"), None).unwrap();
|
||||
let written = publisher.publish_snapshot(&[], "fixture-ready", 2).unwrap();
|
||||
let written = publisher
|
||||
.publish_snapshot(&[], &[], "fixture-ready", 2)
|
||||
.unwrap();
|
||||
assert_eq!(publisher.health().unwrap(), written);
|
||||
assert_eq!(written["scheduler"]["live_turn_pressure"], 2);
|
||||
let catalog = publisher
|
||||
|
|
@ -549,7 +686,7 @@ mod tests {
|
|||
|
||||
let started = std::time::Instant::now();
|
||||
let written = publisher
|
||||
.publish_snapshot(&[], "fixture-ready", 0)
|
||||
.publish_snapshot(&[], &[], "fixture-ready", 0)
|
||||
.expect("local projection remains writable while rendezvous is unavailable");
|
||||
|
||||
assert!(
|
||||
|
|
|
|||
|
|
@ -23,6 +23,31 @@ impl Narrator {
|
|||
let location = &campaign.locations[&player.location_id];
|
||||
let recent_events: Vec<_> = campaign.events.iter().rev().take(4).cloned().collect();
|
||||
let latest_turn = campaign.transcript.last().cloned();
|
||||
let publication = store
|
||||
.load::<crate::session_zero::PublishedSessionZeroSeed>(
|
||||
"session_zero_publication.v1",
|
||||
&campaign.id.to_string(),
|
||||
)?
|
||||
.map(|(_, value)| value);
|
||||
let active_boundaries = store
|
||||
.load::<crate::session_zero::ActiveContractBoundaryPolicy>(
|
||||
"active_contract_boundary_policy.v1",
|
||||
&campaign.id.to_string(),
|
||||
)?
|
||||
.map(|(_, value)| value);
|
||||
let aggregate_boundaries = active_boundaries
|
||||
.filter(|active| {
|
||||
publication.as_ref().is_none_or(|published| {
|
||||
active.review_session_zero_id != published.session_zero_id
|
||||
})
|
||||
})
|
||||
.map(|active| active.aggregate_boundaries)
|
||||
.or_else(|| {
|
||||
publication
|
||||
.as_ref()
|
||||
.map(|value| value.approved_brief.aggregate_boundaries.clone())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let visible_actors: Vec<_> = campaign
|
||||
.actors
|
||||
.values()
|
||||
|
|
@ -45,6 +70,8 @@ impl Narrator {
|
|||
"visible_actors": visible_actors,
|
||||
"latest_events": recent_events,
|
||||
"latest_committed_turn": latest_turn,
|
||||
"campaign_contract": publication.as_ref().map(|value| &value.contract),
|
||||
"aggregate_content_boundaries": aggregate_boundaries,
|
||||
});
|
||||
let output = run_validated_stage(
|
||||
self.model.as_ref(),
|
||||
|
|
@ -56,7 +83,7 @@ impl Narrator {
|
|||
campaign.id, campaign.revision
|
||||
),
|
||||
lived_stream: format!(
|
||||
"Narrate only latest_committed_turn and any latest_events it directly caused, in concrete, concise second-person interactive-fiction prose. Location, time, and visible actors are grounding constraints, not a request to restate every field. Do not repeat older setup, list routes, or recap unrelated world state. Do not mention JSON, state, commits, revisions, or the source representation. Every environmental noun, sensory adjective, object state, action, and consequence must be traceable to the supplied JSON. Do not invent lighting, temperature, sound, motion, posture, dialogue, private thoughts, expertise, geography, findings, or outcomes. It is better to be spare than to fabricate texture. Emit prose only.\n\n{}",
|
||||
"Narrate only latest_committed_turn and any latest_events it directly caused, in concrete, concise second-person interactive-fiction prose. The campaign contract governs tone, pacing, focus, consequences, and DM style. Obey every aggregate content boundary: line excludes the topic, veil keeps it off-screen, ask_first permits no new depiction without a current explicit player acceptance. Never expose boundary attribution. Location, time, and visible actors are grounding constraints, not a request to restate every field. Do not repeat older setup, list routes, or recap unrelated world state. Do not mention JSON, state, commits, revisions, or the source representation. Every environmental noun, sensory adjective, object state, action, and consequence must be traceable to the supplied JSON. Do not invent lighting, temperature, sound, motion, posture, dialogue, private thoughts, expertise, geography, findings, or outcomes. It is better to be spare than to fabricate texture. Emit prose only.\n\n{}",
|
||||
serde_json::to_string(&public_slice)?
|
||||
),
|
||||
output_schema: None,
|
||||
|
|
|
|||
|
|
@ -838,7 +838,7 @@ fn validate_effect(
|
|||
} => {
|
||||
if from_subject_id != source
|
||||
|| !target_set.contains(to_subject_id)
|
||||
|| to_subject_id == &campaign.player_actor_id
|
||||
|| is_human_controlled_actor(campaign, to_subject_id)
|
||||
|| !can_hold_resources(campaign, to_subject_id)
|
||||
|| !subject_resources(campaign, source)?.contains(resource)
|
||||
|| contains_normalized(&subject_resources(campaign, to_subject_id)?, resource)
|
||||
|
|
@ -1067,7 +1067,7 @@ fn action_context(
|
|||
let resource_recipient_ids = targets
|
||||
.iter()
|
||||
.filter(|target| {
|
||||
*target != &campaign.player_actor_id && can_hold_resources(campaign, target)
|
||||
!is_human_controlled_actor(campaign, target) && can_hold_resources(campaign, target)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
|
|
@ -1138,7 +1138,7 @@ fn admissible_effect_kinds(
|
|||
| StrategicActivityKind::Coordinate
|
||||
)
|
||||
&& targets.iter().any(|target| {
|
||||
target != &campaign.player_actor_id && can_hold_resources(campaign, target)
|
||||
!is_human_controlled_actor(campaign, target) && can_hold_resources(campaign, target)
|
||||
})
|
||||
{
|
||||
kinds.push(OutcomeEffectKind::ResourceTransferred);
|
||||
|
|
@ -1360,6 +1360,14 @@ pub fn can_hold_resources(campaign: &Campaign, subject_id: &str) -> bool {
|
|||
|| campaign.actors.contains_key(subject_id)
|
||||
}
|
||||
|
||||
fn is_human_controlled_actor(campaign: &Campaign, subject_id: &str) -> bool {
|
||||
subject_id == campaign.player_actor_id
|
||||
|| campaign
|
||||
.agency_profiles
|
||||
.get(subject_id)
|
||||
.is_some_and(|profile| !profile.simulation_eligible)
|
||||
}
|
||||
|
||||
fn activity_parts(
|
||||
proposal: &CellActionProposal,
|
||||
) -> Result<(StrategicActivityKind, Vec<String>, Vec<String>)> {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ use crate::domain::{
|
|||
ResolutionWaveCommit, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest,
|
||||
WorldCommitReceipt,
|
||||
};
|
||||
use crate::session_zero::{
|
||||
CellBudgetProposal, GroupTravelProposal, PublishedSessionZeroSeed, TimeAdvanceProposal,
|
||||
};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
|
|
@ -48,11 +51,7 @@ impl CampaignStore {
|
|||
kind: &str,
|
||||
key: &str,
|
||||
) -> Result<Option<(CultCacheEnvelope, T)>> {
|
||||
let row = self
|
||||
.inner
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.find(|r| r.r#type == kind && r.key == key);
|
||||
let row = self.load_envelope(kind, key)?;
|
||||
row.map(|r| {
|
||||
let value = rmp_serde::from_slice(&r.payload).context("decode CultCache row")?;
|
||||
Ok((r, value))
|
||||
|
|
@ -60,6 +59,14 @@ impl CampaignStore {
|
|||
.transpose()
|
||||
}
|
||||
|
||||
fn load_envelope(&self, kind: &str, key: &str) -> Result<Option<CultCacheEnvelope>> {
|
||||
Ok(self
|
||||
.inner
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.find(|row| row.r#type == kind && row.key == key))
|
||||
}
|
||||
|
||||
pub fn insert<T: Serialize>(
|
||||
&self,
|
||||
kind: &str,
|
||||
|
|
@ -79,6 +86,31 @@ impl CampaignStore {
|
|||
campaign: &Campaign,
|
||||
receipts: &[VaultEvidenceReceipt],
|
||||
model_receipts: &[crate::model::ModelStageReceipt],
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
self.create_campaign_rows(campaign, receipts, model_receipts, None)
|
||||
}
|
||||
|
||||
pub fn create_session_zero_campaign(
|
||||
&self,
|
||||
campaign: &Campaign,
|
||||
receipts: &[VaultEvidenceReceipt],
|
||||
model_receipts: &[crate::model::ModelStageReceipt],
|
||||
publication: &PublishedSessionZeroSeed,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
if publication.membership.campaign_id != campaign.id
|
||||
|| publication.governance.campaign_id != campaign.id
|
||||
{
|
||||
return Err(anyhow!("Session Zero publication targets another campaign"));
|
||||
}
|
||||
self.create_campaign_rows(campaign, receipts, model_receipts, Some(publication))
|
||||
}
|
||||
|
||||
fn create_campaign_rows(
|
||||
&self,
|
||||
campaign: &Campaign,
|
||||
receipts: &[VaultEvidenceReceipt],
|
||||
model_receipts: &[crate::model::ModelStageReceipt],
|
||||
publication: Option<&PublishedSessionZeroSeed>,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let campaign_row = envelope(
|
||||
"campaign.v1",
|
||||
|
|
@ -137,6 +169,60 @@ impl CampaignStore {
|
|||
created_at: Utc::now(),
|
||||
},
|
||||
)?);
|
||||
if let Some(publication) = publication {
|
||||
rows.push(envelope(
|
||||
"session_zero_publication.v1",
|
||||
"ghostlight.published_session_zero_seed.v1",
|
||||
&campaign.id.to_string(),
|
||||
publication,
|
||||
)?);
|
||||
rows.push(envelope(
|
||||
"campaign_membership.v1",
|
||||
"ghostlight.campaign_membership.v1",
|
||||
&campaign.id.to_string(),
|
||||
&publication.membership,
|
||||
)?);
|
||||
rows.push(envelope(
|
||||
"campaign_contract.v1",
|
||||
"ghostlight.campaign_contract.v1",
|
||||
&campaign.id.to_string(),
|
||||
&publication.contract,
|
||||
)?);
|
||||
rows.push(envelope(
|
||||
"campaign_governance.v1",
|
||||
"ghostlight.campaign_governance.v1",
|
||||
&campaign.id.to_string(),
|
||||
&publication.governance,
|
||||
)?);
|
||||
rows.push(envelope(
|
||||
"campaign_dm_persona.v1",
|
||||
"ghostlight.campaign_dm_persona.v1",
|
||||
&publication.dm_persona.id,
|
||||
&publication.dm_persona,
|
||||
)?);
|
||||
rows.push(envelope(
|
||||
"approved_campaign_brief.v1",
|
||||
"ghostlight.approved_campaign_brief.v1",
|
||||
&campaign.id.to_string(),
|
||||
&publication.approved_brief,
|
||||
)?);
|
||||
for approval in &publication.approvals {
|
||||
rows.push(envelope(
|
||||
"session_zero_approval.v1",
|
||||
"ghostlight.session_zero_approval.v1",
|
||||
&approval.member_id,
|
||||
approval,
|
||||
)?);
|
||||
}
|
||||
for boundary in &publication.boundaries {
|
||||
rows.push(envelope(
|
||||
"content_boundary.v1",
|
||||
"ghostlight.content_boundary.v1",
|
||||
&boundary.id,
|
||||
boundary,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
if !self.inner.compare_and_swap_batch(&[], rows)? {
|
||||
return Err(anyhow!("campaign store is not empty"));
|
||||
}
|
||||
|
|
@ -200,6 +286,217 @@ impl CampaignStore {
|
|||
Ok(next_row)
|
||||
}
|
||||
|
||||
pub fn commit_time_advance(
|
||||
&self,
|
||||
expected_campaign: &CultCacheEnvelope,
|
||||
next_campaign: &Campaign,
|
||||
expected_proposal: &CultCacheEnvelope,
|
||||
next_proposal: &TimeAdvanceProposal,
|
||||
receipt: &WorldCommitReceipt,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let next_campaign_row = envelope(
|
||||
&expected_campaign.r#type,
|
||||
"ghostlight.campaign.v1",
|
||||
&expected_campaign.key,
|
||||
next_campaign,
|
||||
)?;
|
||||
let next_proposal_row = envelope(
|
||||
&expected_proposal.r#type,
|
||||
"ghostlight.time_advance_proposal.v1",
|
||||
&expected_proposal.key,
|
||||
next_proposal,
|
||||
)?;
|
||||
let rows = vec![
|
||||
next_campaign_row.clone(),
|
||||
next_proposal_row,
|
||||
envelope(
|
||||
"world_commit_receipt.v1",
|
||||
"ghostlight.world_commit_receipt.v1",
|
||||
&format!("{}-{}", next_campaign.id, next_campaign.revision),
|
||||
receipt,
|
||||
)?,
|
||||
];
|
||||
if !self.inner.compare_and_swap_batch(
|
||||
&[expected_campaign.clone(), expected_proposal.clone()],
|
||||
rows,
|
||||
)? {
|
||||
return Err(anyhow!("stale campaign or time-advance proposal"));
|
||||
}
|
||||
Ok(next_campaign_row)
|
||||
}
|
||||
|
||||
pub fn commit_group_travel(
|
||||
&self,
|
||||
expected_campaign: &CultCacheEnvelope,
|
||||
next_campaign: &Campaign,
|
||||
expected_proposal: &CultCacheEnvelope,
|
||||
next_proposal: &GroupTravelProposal,
|
||||
receipt: &WorldCommitReceipt,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let next_campaign_row = envelope(
|
||||
&expected_campaign.r#type,
|
||||
"ghostlight.campaign.v1",
|
||||
&expected_campaign.key,
|
||||
next_campaign,
|
||||
)?;
|
||||
let next_proposal_row = envelope(
|
||||
&expected_proposal.r#type,
|
||||
"ghostlight.group_travel_proposal.v1",
|
||||
&expected_proposal.key,
|
||||
next_proposal,
|
||||
)?;
|
||||
let rows = vec![
|
||||
next_campaign_row.clone(),
|
||||
next_proposal_row,
|
||||
envelope(
|
||||
"world_commit_receipt.v1",
|
||||
"ghostlight.world_commit_receipt.v1",
|
||||
&format!("{}-{}", next_campaign.id, next_campaign.revision),
|
||||
receipt,
|
||||
)?,
|
||||
];
|
||||
if !self.inner.compare_and_swap_batch(
|
||||
&[expected_campaign.clone(), expected_proposal.clone()],
|
||||
rows,
|
||||
)? {
|
||||
return Err(anyhow!("stale campaign or group-travel proposal"));
|
||||
}
|
||||
Ok(next_campaign_row)
|
||||
}
|
||||
|
||||
pub fn commit_cell_budget(
|
||||
&self,
|
||||
expected_campaign: &CultCacheEnvelope,
|
||||
next_campaign: &Campaign,
|
||||
expected_proposal: &CultCacheEnvelope,
|
||||
next_proposal: &CellBudgetProposal,
|
||||
receipt: &ResolutionControlReceipt,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let next_campaign_row = envelope(
|
||||
&expected_campaign.r#type,
|
||||
"ghostlight.campaign.v1",
|
||||
&expected_campaign.key,
|
||||
next_campaign,
|
||||
)?;
|
||||
let rows = vec![
|
||||
next_campaign_row.clone(),
|
||||
envelope(
|
||||
&expected_proposal.r#type,
|
||||
"ghostlight.cell_budget_proposal.v1",
|
||||
&expected_proposal.key,
|
||||
next_proposal,
|
||||
)?,
|
||||
envelope(
|
||||
"resolution_control_receipt.v1",
|
||||
"ghostlight.resolution_control_receipt.v1",
|
||||
&format!(
|
||||
"{}:{}:{}",
|
||||
receipt.campaign_id, receipt.operation, receipt.resolution_epoch
|
||||
),
|
||||
receipt,
|
||||
)?,
|
||||
];
|
||||
if !self.inner.compare_and_swap_batch(
|
||||
&[expected_campaign.clone(), expected_proposal.clone()],
|
||||
rows,
|
||||
)? {
|
||||
return Err(anyhow!("stale campaign or cell-budget proposal"));
|
||||
}
|
||||
Ok(next_campaign_row)
|
||||
}
|
||||
|
||||
pub fn commit_contract_review(
|
||||
&self,
|
||||
expected_campaign: &CultCacheEnvelope,
|
||||
next_campaign: &Campaign,
|
||||
publication: &PublishedSessionZeroSeed,
|
||||
receipt: &WorldCommitReceipt,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let campaign_key = next_campaign.id.to_string();
|
||||
let required = [
|
||||
"session_zero_publication.v1",
|
||||
"campaign_contract.v1",
|
||||
"campaign_membership.v1",
|
||||
"campaign_governance.v1",
|
||||
"approved_campaign_brief.v1",
|
||||
];
|
||||
let mut expected_rows = vec![expected_campaign.clone()];
|
||||
for kind in required {
|
||||
let row = self
|
||||
.load_envelope(kind, &campaign_key)?
|
||||
.ok_or_else(|| anyhow!("contract review requires {kind}"))?;
|
||||
expected_rows.push(row);
|
||||
}
|
||||
let dm_row = self
|
||||
.load_envelope("campaign_dm_persona.v1", &publication.dm_persona.id)?
|
||||
.ok_or_else(|| anyhow!("contract review requires campaign DM state"))?;
|
||||
expected_rows.push(dm_row);
|
||||
|
||||
let next_campaign_row = envelope(
|
||||
&expected_campaign.r#type,
|
||||
"ghostlight.campaign.v1",
|
||||
&expected_campaign.key,
|
||||
next_campaign,
|
||||
)?;
|
||||
let mut rows = vec![
|
||||
next_campaign_row.clone(),
|
||||
envelope(
|
||||
"session_zero_publication.v1",
|
||||
"ghostlight.published_session_zero_seed.v1",
|
||||
&campaign_key,
|
||||
publication,
|
||||
)?,
|
||||
envelope(
|
||||
"campaign_contract.v1",
|
||||
"ghostlight.campaign_contract.v1",
|
||||
&campaign_key,
|
||||
&publication.contract,
|
||||
)?,
|
||||
envelope(
|
||||
"campaign_membership.v1",
|
||||
"ghostlight.campaign_membership.v1",
|
||||
&campaign_key,
|
||||
&publication.membership,
|
||||
)?,
|
||||
envelope(
|
||||
"campaign_governance.v1",
|
||||
"ghostlight.campaign_governance.v1",
|
||||
&campaign_key,
|
||||
&publication.governance,
|
||||
)?,
|
||||
envelope(
|
||||
"campaign_dm_persona.v1",
|
||||
"ghostlight.campaign_dm_persona.v1",
|
||||
&publication.dm_persona.id,
|
||||
&publication.dm_persona,
|
||||
)?,
|
||||
envelope(
|
||||
"approved_campaign_brief.v1",
|
||||
"ghostlight.approved_campaign_brief.v1",
|
||||
&campaign_key,
|
||||
&publication.approved_brief,
|
||||
)?,
|
||||
envelope(
|
||||
"world_commit_receipt.v1",
|
||||
"ghostlight.world_commit_receipt.v1",
|
||||
&format!("{}-{}", next_campaign.id, next_campaign.revision),
|
||||
receipt,
|
||||
)?,
|
||||
];
|
||||
for approval in &publication.approvals {
|
||||
rows.push(envelope(
|
||||
"session_zero_approval.v1",
|
||||
"ghostlight.session_zero_approval.v1",
|
||||
&format!("{}:{}", publication.session_zero_id, approval.member_id),
|
||||
approval,
|
||||
)?);
|
||||
}
|
||||
if !self.inner.compare_and_swap_batch(&expected_rows, rows)? {
|
||||
return Err(anyhow!("stale campaign contract review"));
|
||||
}
|
||||
Ok(next_campaign_row)
|
||||
}
|
||||
|
||||
pub fn append_world_commit<T: Serialize, R: Serialize>(
|
||||
&self,
|
||||
expected: &CultCacheEnvelope,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use crate::model::{ModelPort, ModelStageRequest, run_validated_stage};
|
||||
use crate::session_zero::{AggregatedBoundary, CampaignContract};
|
||||
use anyhow::{Result, anyhow};
|
||||
use async_trait::async_trait;
|
||||
use ghostlight_persona_projection::{
|
||||
|
|
@ -740,6 +741,8 @@ pub struct CellProjectionEngine {
|
|||
pub projector_model: String,
|
||||
pub persona_model: String,
|
||||
pub interpreter_model: String,
|
||||
pub campaign_contract: Option<CampaignContract>,
|
||||
pub aggregate_boundaries: Vec<AggregatedBoundary>,
|
||||
}
|
||||
|
||||
impl CellProjectionEngine {
|
||||
|
|
@ -748,6 +751,10 @@ impl CellProjectionEngine {
|
|||
.require(&slice.cell_id, &slice.snapshot_binding, "cell_projector")
|
||||
.await?;
|
||||
let projector_context = serde_json::to_string(&cell_projector_context(&slice))?;
|
||||
let campaign_policy = serde_json::to_string(&serde_json::json!({
|
||||
"campaign_contract":self.campaign_contract,
|
||||
"aggregate_content_boundaries":self.aggregate_boundaries,
|
||||
}))?;
|
||||
let visible_stimulus = slice
|
||||
.perceived_events
|
||||
.iter()
|
||||
|
|
@ -783,7 +790,7 @@ impl CellProjectionEngine {
|
|||
model: self.projector_model.clone(),
|
||||
snapshot_binding: slice.snapshot_binding.clone(),
|
||||
lived_stream: format!(
|
||||
"<!-- membrane:{MEMBRANE_SCHEMA}:cell-projector -->\nYou are a private cell Projector. Convert only the permitted typed context and visible stimulus into compact lived narrative segments. Each segment belongs to exactly one supplied subject_id and contains only that subject's perceptions, memories, wants, fears, knowledge, and explicit uncertainty. Mentioned outsiders remain external observations: never give them an internal viewpoint. Do not choose actions or claim world effects. Omit decorative recap. Return between {} and {perspective_limit} unique segments; do not narrate every ordinary constituent. Include every exact subject ID in REQUIRED PERSPECTIVE OWNERS, because each named member exception or debt focus has an actionable decision that must not disappear inside the aggregate. Put detail_focus_subject_id first when present. Spend any remaining slots only on subjects facing a materially different decision in this horizon.\n\nREQUIRED PERSPECTIVE OWNERS:\n{}\n\nReturn exactly one JSON object matching this stable shape:\n{CELL_PROJECTION_OUTPUT_CONTRACT}\n\nDomain guidance:\n{mode_guidance}\n\nIdentity:\n{}\n\nPermitted typed context:\n{projector_context}\n\nVisible stimulus:\n{visible_stimulus}\n\nUse no more than {word_budget} narrative words across all segments.",
|
||||
"<!-- membrane:{MEMBRANE_SCHEMA}:cell-projector -->\nYou are a private cell Projector. Convert only the permitted typed context and visible stimulus into compact lived narrative segments. Each segment belongs to exactly one supplied subject_id and contains only that subject's perceptions, memories, wants, fears, knowledge, and explicit uncertainty. Mentioned outsiders remain external observations: never give them an internal viewpoint. Campaign policy constrains what may become simulation content, but is never actor knowledge: omit line topics, keep veil topics off-screen, and introduce no ask_first topic. Do not narrativize or reveal the policy itself. Do not choose actions or claim world effects. Omit decorative recap. Return between {} and {perspective_limit} unique segments; do not narrate every ordinary constituent. Include every exact subject ID in REQUIRED PERSPECTIVE OWNERS, because each named member exception or debt focus has an actionable decision that must not disappear inside the aggregate. Put detail_focus_subject_id first when present. Spend any remaining slots only on subjects facing a materially different decision in this horizon.\n\nREQUIRED PERSPECTIVE OWNERS:\n{}\n\nReturn exactly one JSON object matching this stable shape:\n{CELL_PROJECTION_OUTPUT_CONTRACT}\n\nCAMPAIGN POLICY:\n{campaign_policy}\n\nDomain guidance:\n{mode_guidance}\n\nIdentity:\n{}\n\nPermitted typed context:\n{projector_context}\n\nVisible stimulus:\n{visible_stimulus}\n\nUse no more than {word_budget} narrative words across all segments.",
|
||||
required_projection_subject_ids.len().max(1),
|
||||
serde_json::to_string(&required_projection_subject_ids)?,
|
||||
slice.cell_id
|
||||
|
|
@ -874,6 +881,9 @@ impl CellProjectionEngine {
|
|||
),
|
||||
slice.max_actions
|
||||
);
|
||||
let permission_guidance = format!(
|
||||
"{permission_guidance} Campaign policy is a hard output boundary, not actor knowledge. Emit no action, inaction rationale, pressure, migration, posture, or activity that introduces a line topic, depicts a veil topic on-screen, or introduces an ask_first topic. Never reveal boundary attribution. CAMPAIGN POLICY: {campaign_policy}"
|
||||
);
|
||||
let mut request = ModelStageRequest {
|
||||
stage: "cell_interpreter".into(),
|
||||
model: self.interpreter_model.clone(),
|
||||
|
|
@ -929,6 +939,7 @@ impl CellProjectionEngine {
|
|||
"typed_effect":action.effect,
|
||||
})).collect::<Vec<_>>(),
|
||||
"subject_names":slice.constituents.iter().map(|subject|(&subject.subject_id, &subject.name)).chain(slice.member_exceptions.iter().map(|member|(&member.subject_id, &member.name))).collect::<BTreeMap<_,_>>(),
|
||||
"campaign_policy":serde_json::from_str::<serde_json::Value>(&campaign_policy)?,
|
||||
});
|
||||
let verifier_binding = cell_effect_verification_binding(
|
||||
&slice.snapshot_binding,
|
||||
|
|
@ -1920,6 +1931,8 @@ mod tests {
|
|||
projector_model: "flash".into(),
|
||||
persona_model: "flash".into(),
|
||||
interpreter_model: "flash".into(),
|
||||
campaign_contract: None,
|
||||
aggregate_boundaries: vec![],
|
||||
};
|
||||
let output = engine.execute(fixture_cell_slice()).await.unwrap();
|
||||
assert!(model.saw_rejected_appraisal.load(Ordering::SeqCst));
|
||||
|
|
@ -2036,6 +2049,8 @@ mod tests {
|
|||
projector_model: "flash".into(),
|
||||
persona_model: "flash".into(),
|
||||
interpreter_model: "flash".into(),
|
||||
campaign_contract: None,
|
||||
aggregate_boundaries: vec![],
|
||||
}
|
||||
.execute(fixture_cell_slice())
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ use crate::{
|
|||
kernel::WorldKernel,
|
||||
model::ModelStageReceipt,
|
||||
persistence::CampaignStore,
|
||||
session_zero::PublishedSessionZeroSeed,
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::Utc;
|
||||
|
|
@ -120,6 +121,104 @@ impl CampaignRegistry {
|
|||
.await
|
||||
}
|
||||
|
||||
pub async fn publish_session_zero(
|
||||
&self,
|
||||
mut campaign: Campaign,
|
||||
evidence: Vec<VaultEvidenceReceipt>,
|
||||
model_receipts: Vec<ModelStageReceipt>,
|
||||
publication: PublishedSessionZeroSeed,
|
||||
) -> Result<CampaignRuntime> {
|
||||
crate::resolution::ensure_agency_profiles(&mut campaign);
|
||||
crate::compiler::validate_campaign_seed(&campaign)?;
|
||||
if publication
|
||||
.membership
|
||||
.controlled_actor_ids()
|
||||
.iter()
|
||||
.any(|actor_id| {
|
||||
!campaign.actors.contains_key(actor_id)
|
||||
|| campaign
|
||||
.agency_profiles
|
||||
.get(actor_id)
|
||||
.is_none_or(|profile| profile.simulation_eligible)
|
||||
})
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"every campaign member must bind an existing human-protected actor"
|
||||
));
|
||||
}
|
||||
if let Ok(existing) = self.runtime(campaign.id).await {
|
||||
let stored = existing
|
||||
.store
|
||||
.load::<PublishedSessionZeroSeed>(
|
||||
"session_zero_publication.v1",
|
||||
&campaign.id.to_string(),
|
||||
)?
|
||||
.map(|(_, value)| value);
|
||||
return match stored {
|
||||
Some(stored) if stored.approved_seed_digest == publication.approved_seed_digest => {
|
||||
Ok(existing)
|
||||
}
|
||||
_ => Err(anyhow!(
|
||||
"campaign id is already published from another seed"
|
||||
)),
|
||||
};
|
||||
}
|
||||
let directory = self.root.join(campaign.id.to_string());
|
||||
if directory.exists() {
|
||||
let store = CampaignStore::open(directory.join("campaign.cc"))?;
|
||||
let stored = store
|
||||
.load::<PublishedSessionZeroSeed>(
|
||||
"session_zero_publication.v1",
|
||||
&campaign.id.to_string(),
|
||||
)?
|
||||
.map(|(_, value)| value);
|
||||
if stored.as_ref().is_some_and(|stored| {
|
||||
stored.approved_seed_digest == publication.approved_seed_digest
|
||||
}) {
|
||||
let runtime = CampaignRuntime {
|
||||
kernel: WorldKernel::start(store.clone()),
|
||||
store,
|
||||
};
|
||||
self.runtimes
|
||||
.write()
|
||||
.await
|
||||
.insert(campaign.id, runtime.clone());
|
||||
return Ok(runtime);
|
||||
}
|
||||
return Err(anyhow!("campaign directory belongs to another seed"));
|
||||
}
|
||||
let staging = self
|
||||
.root
|
||||
.join(format!(".creating-{}-{}", campaign.id, Uuid::new_v4()));
|
||||
fs::create_dir(&staging)?;
|
||||
let prepared = (|| -> Result<()> {
|
||||
let store = CampaignStore::open(staging.join("campaign.cc"))?;
|
||||
store.create_session_zero_campaign(
|
||||
&campaign,
|
||||
&evidence,
|
||||
&model_receipts,
|
||||
&publication,
|
||||
)?;
|
||||
drop(store);
|
||||
fs::rename(&staging, &directory)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = prepared {
|
||||
cleanup_staging_directory(&self.root, &staging);
|
||||
return Err(error);
|
||||
}
|
||||
let store = CampaignStore::open(directory.join("campaign.cc"))?;
|
||||
let runtime = CampaignRuntime {
|
||||
kernel: WorldKernel::start(store.clone()),
|
||||
store,
|
||||
};
|
||||
self.runtimes
|
||||
.write()
|
||||
.await
|
||||
.insert(campaign.id, runtime.clone());
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
async fn create_with_lifecycle(
|
||||
&self,
|
||||
mut campaign: Campaign,
|
||||
|
|
@ -319,7 +418,11 @@ fn validated_branch_name(name: String) -> Result<String> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::domain::{ActorState, BranchOrigin, Location};
|
||||
use crate::domain::{ActorState, BranchOrigin, Location, WorldCommitReceipt};
|
||||
use crate::session_zero::{
|
||||
ApprovedCampaignBrief, CampaignContract, CampaignDmPersona, CampaignGovernance,
|
||||
CampaignMember, CampaignMembership, CharacterDraft,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
fn seed(name: &str) -> Campaign {
|
||||
|
|
@ -382,6 +485,76 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn publication(campaign: &Campaign, seed_digest: &str) -> PublishedSessionZeroSeed {
|
||||
let member_id = "member:host".to_string();
|
||||
let mut contract = CampaignContract::default();
|
||||
contract.campaign_name = campaign.name.clone();
|
||||
contract.vault_provider = "fixture".into();
|
||||
let character = CharacterDraft {
|
||||
schema: "ghostlight.character_draft.v1".into(),
|
||||
member_id: member_id.clone(),
|
||||
actor_id: campaign.player_actor_id.clone(),
|
||||
name: campaign.actors[&campaign.player_actor_id].name.clone(),
|
||||
..CharacterDraft::default()
|
||||
};
|
||||
let membership = CampaignMembership {
|
||||
schema: "ghostlight.campaign_membership.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
governance_epoch: 0,
|
||||
host_member_id: member_id.clone(),
|
||||
members: BTreeMap::from([(
|
||||
member_id.clone(),
|
||||
CampaignMember {
|
||||
member_id: member_id.clone(),
|
||||
account_hash: "account:host".into(),
|
||||
display_name: "Host".into(),
|
||||
actor_id: campaign.player_actor_id.clone(),
|
||||
is_host: true,
|
||||
active: true,
|
||||
cell_allowance: 8,
|
||||
},
|
||||
)]),
|
||||
extraordinary_permissions: BTreeMap::new(),
|
||||
};
|
||||
PublishedSessionZeroSeed {
|
||||
schema: "ghostlight.published_session_zero_seed.v1".into(),
|
||||
session_zero_id: Uuid::new_v4(),
|
||||
approved_seed_digest: seed_digest.into(),
|
||||
contract: contract.clone(),
|
||||
membership: membership.clone(),
|
||||
governance: CampaignGovernance {
|
||||
schema: "ghostlight.campaign_governance.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
governance_epoch: 0,
|
||||
time_advance_policy: "unanimous".into(),
|
||||
pooled_cell_ceiling: 8,
|
||||
cooperative_shared_scene_only: true,
|
||||
pvp_enabled: false,
|
||||
},
|
||||
dm_persona: CampaignDmPersona {
|
||||
schema: "ghostlight.campaign_dm_persona.v1".into(),
|
||||
id: "dm:test".into(),
|
||||
name: "Ghostlight".into(),
|
||||
voice: "Candid".into(),
|
||||
shared_memories: vec![],
|
||||
private_member_memories: BTreeMap::new(),
|
||||
},
|
||||
approvals: vec![],
|
||||
approved_brief: ApprovedCampaignBrief {
|
||||
schema: "ghostlight.approved_campaign_brief.v1".into(),
|
||||
session_zero_id: Uuid::new_v4(),
|
||||
host_member_id: member_id.clone(),
|
||||
contract,
|
||||
aggregate_boundaries: vec![],
|
||||
characters: vec![character],
|
||||
member_actor_ids: BTreeMap::from([(member_id, campaign.player_actor_id.clone())]),
|
||||
shared_digest: "sha256:shared".into(),
|
||||
character_digests: BTreeMap::new(),
|
||||
},
|
||||
boundaries: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_fork_reset_and_export_preserve_isolated_stores() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
@ -555,6 +728,154 @@ mod tests {
|
|||
assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_zero_publication_is_atomic_complete_and_digest_idempotent() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("campaigns");
|
||||
let registry = CampaignRegistry::new(&root).unwrap();
|
||||
let campaign = seed("Approved seed");
|
||||
let approved = publication(&campaign, "sha256:approved");
|
||||
|
||||
let first = registry
|
||||
.publish_session_zero(campaign.clone(), vec![], vec![], approved.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
for document_type in [
|
||||
"campaign.v1",
|
||||
"session_zero_publication.v1",
|
||||
"campaign_membership.v1",
|
||||
"campaign_contract.v1",
|
||||
"campaign_governance.v1",
|
||||
"campaign_dm_persona.v1",
|
||||
"approved_campaign_brief.v1",
|
||||
] {
|
||||
assert_eq!(first.store.keys(document_type).unwrap().len(), 1);
|
||||
}
|
||||
assert_eq!(registry.list().await, vec![campaign.id]);
|
||||
assert!(std::fs::read_dir(&root).unwrap().all(|entry| {
|
||||
!entry
|
||||
.unwrap()
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with(".creating-")
|
||||
}));
|
||||
|
||||
let recovered = registry
|
||||
.publish_session_zero(campaign.clone(), vec![], vec![], approved)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recovered.store.keys("campaign.v1").unwrap(),
|
||||
vec![campaign.id.to_string()]
|
||||
);
|
||||
|
||||
let conflicting = publication(&campaign, "sha256:different");
|
||||
assert!(
|
||||
registry
|
||||
.publish_session_zero(campaign, vec![], vec![], conflicting)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn contract_review_replaces_all_governance_rows_in_one_cas() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap();
|
||||
let campaign = seed("Reviewable seed");
|
||||
let original_publication = publication(&campaign, "sha256:original");
|
||||
let runtime = registry
|
||||
.publish_session_zero(
|
||||
campaign.clone(),
|
||||
vec![],
|
||||
vec![],
|
||||
original_publication.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (campaign_row, mut next_campaign) = runtime
|
||||
.store
|
||||
.load::<Campaign>("campaign.v1", &campaign.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
next_campaign.revision = 1;
|
||||
let mut reviewed = original_publication;
|
||||
reviewed.approved_seed_digest = "sha256:reviewed".into();
|
||||
reviewed.contract.pacing = "deliberate".into();
|
||||
reviewed.approved_brief.contract = reviewed.contract.clone();
|
||||
reviewed.membership.governance_epoch = 1;
|
||||
reviewed.governance.governance_epoch = 1;
|
||||
reviewed.dm_persona.voice = "Patient and exact".into();
|
||||
let receipt = WorldCommitReceipt {
|
||||
schema: "ghostlight.world_commit_receipt.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
previous_revision: 0,
|
||||
revision: 1,
|
||||
command_kind: "unanimous_contract_review".into(),
|
||||
committed_at: Utc::now(),
|
||||
roll: None,
|
||||
};
|
||||
|
||||
runtime
|
||||
.store
|
||||
.commit_contract_review(&campaign_row, &next_campaign, &reviewed, &receipt)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.store
|
||||
.load::<Campaign>("campaign.v1", &campaign.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1
|
||||
.revision,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.store
|
||||
.load::<CampaignContract>("campaign_contract.v1", &campaign.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1
|
||||
.pacing,
|
||||
"deliberate"
|
||||
);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.store
|
||||
.load::<CampaignDmPersona>("campaign_dm_persona.v1", "dm:test")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1
|
||||
.voice,
|
||||
"Patient and exact"
|
||||
);
|
||||
|
||||
let mut impossible_second = reviewed;
|
||||
impossible_second.contract.pacing = "frantic".into();
|
||||
assert!(
|
||||
runtime
|
||||
.store
|
||||
.commit_contract_review(
|
||||
&campaign_row,
|
||||
&next_campaign,
|
||||
&impossible_second,
|
||||
&receipt,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.store
|
||||
.load::<CampaignContract>("campaign_contract.v1", &campaign.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1
|
||||
.pacing,
|
||||
"deliberate"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_existing_migrates_flat_campaign_without_advancing_world_revision() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use std::cmp::Ordering;
|
|||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, VecDeque};
|
||||
|
||||
pub const MIN_ACTIVE_CELL_BUDGET: u8 = 1;
|
||||
pub const MAX_ACTIVE_CELL_BUDGET: u8 = 32;
|
||||
pub const MAX_ACTIVE_CELL_BUDGET: u8 = 128;
|
||||
pub const MAX_PROVIDER_PARALLELISM: u8 = 32;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -1815,7 +1815,7 @@ fn validate_cell_proposal(
|
|||
cell: &SimulationCell,
|
||||
proposal: &CellActionProposal,
|
||||
) -> Result<()> {
|
||||
if proposal.subject_id == campaign.player_actor_id
|
||||
if is_human_controlled_actor(campaign, &proposal.subject_id)
|
||||
|| proposal.intent.trim().is_empty()
|
||||
|| proposal.intended_effect.trim().is_empty()
|
||||
|| !(0..=100).contains(&proposal.priority)
|
||||
|
|
@ -1969,7 +1969,7 @@ fn cell_contains_attributed_subject(
|
|||
cell: &SimulationCell,
|
||||
subject_id: &str,
|
||||
) -> bool {
|
||||
if subject_id == campaign.player_actor_id {
|
||||
if is_human_controlled_actor(campaign, subject_id) {
|
||||
return false;
|
||||
}
|
||||
if let Some(member_id) = subject_id.strip_prefix("member:") {
|
||||
|
|
@ -1981,6 +1981,14 @@ fn cell_contains_attributed_subject(
|
|||
cell.subject_ids.contains(subject_id)
|
||||
}
|
||||
|
||||
fn is_human_controlled_actor(campaign: &Campaign, subject_id: &str) -> bool {
|
||||
subject_id == campaign.player_actor_id
|
||||
|| campaign
|
||||
.agency_profiles
|
||||
.get(subject_id)
|
||||
.is_some_and(|profile| !profile.simulation_eligible)
|
||||
}
|
||||
|
||||
pub fn substantive_text_change(current: &str, candidate: &str) -> bool {
|
||||
let current = current.trim();
|
||||
let candidate = candidate.trim();
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ use crate::{
|
|||
cell_action_digest, cell_action_limit, default_demand, plan_cover, plan_receipt,
|
||||
select_resolution_wave, validate_and_resolve_wave, validate_demand,
|
||||
},
|
||||
session_zero::{AggregatedBoundary, CampaignContract},
|
||||
};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
|
@ -55,7 +56,23 @@ pub async fn propose_resolution_wave(
|
|||
permit: Arc<dyn ExecutionPermit>,
|
||||
campaign: &Campaign,
|
||||
) -> Result<StrategicResolutionOutput> {
|
||||
let (demand, mut stages) = project_resolution_demand(model.as_ref(), campaign).await;
|
||||
propose_resolution_wave_with_policy(model, permit, campaign, None, &[]).await
|
||||
}
|
||||
|
||||
pub async fn propose_resolution_wave_with_policy(
|
||||
model: Arc<dyn ModelPort>,
|
||||
permit: Arc<dyn ExecutionPermit>,
|
||||
campaign: &Campaign,
|
||||
campaign_contract: Option<&CampaignContract>,
|
||||
aggregate_boundaries: &[AggregatedBoundary],
|
||||
) -> Result<StrategicResolutionOutput> {
|
||||
let (demand, mut stages) = project_resolution_demand(
|
||||
model.as_ref(),
|
||||
campaign,
|
||||
campaign_contract,
|
||||
aggregate_boundaries,
|
||||
)
|
||||
.await;
|
||||
let cover = plan_cover(campaign, demand)?;
|
||||
let receipt = plan_receipt(campaign, &cover);
|
||||
let outcome_model = model.clone();
|
||||
|
|
@ -66,6 +83,8 @@ pub async fn propose_resolution_wave(
|
|||
projector_model: "deepseek-v4-flash".into(),
|
||||
persona_model: "deepseek-v4-flash".into(),
|
||||
interpreter_model: "deepseek-v4-flash".into(),
|
||||
campaign_contract: campaign_contract.cloned(),
|
||||
aggregate_boundaries: aggregate_boundaries.to_vec(),
|
||||
};
|
||||
let semaphore = Arc::new(tokio::sync::Semaphore::new(usize::from(
|
||||
campaign.resolution_policy.provider_parallelism.max(1),
|
||||
|
|
@ -185,6 +204,8 @@ pub async fn propose_resolution_wave(
|
|||
async fn project_resolution_demand(
|
||||
model: &dyn ModelPort,
|
||||
campaign: &Campaign,
|
||||
campaign_contract: Option<&CampaignContract>,
|
||||
aggregate_boundaries: &[AggregatedBoundary],
|
||||
) -> (ResolutionDemand, Vec<ModelStageOutput>) {
|
||||
let fallback = || {
|
||||
campaign
|
||||
|
|
@ -213,6 +234,8 @@ async fn project_resolution_demand(
|
|||
"consequence":clock.consequence,
|
||||
})).collect::<Vec<_>>(),
|
||||
"agency_summary": agency_summary,
|
||||
"campaign_contract":campaign_contract,
|
||||
"aggregate_content_boundaries":aggregate_boundaries,
|
||||
});
|
||||
let mut schema = match serde_json::to_value(schema_for!(DemandProjection)) {
|
||||
Ok(value) => value,
|
||||
|
|
|
|||
2874
crates/ghostlight-dungeon/src/session_zero.rs
Normal file
2874
crates/ghostlight-dungeon/src/session_zero.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -8,6 +8,14 @@ use crate::{
|
|||
use serde_json::{Value, json};
|
||||
|
||||
pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -> Value {
|
||||
player_surface_for_actor(campaign, &campaign.player_actor_id, narrations)
|
||||
}
|
||||
|
||||
pub fn player_surface_for_actor(
|
||||
campaign: &Campaign,
|
||||
viewer_actor_id: &str,
|
||||
narrations: &[NarrationProjection],
|
||||
) -> Value {
|
||||
let interface_version = campaign
|
||||
.revision
|
||||
.saturating_mul(1_000_000_000_000)
|
||||
|
|
@ -19,7 +27,7 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -
|
|||
)
|
||||
.saturating_add(campaign.resolution_policy.provider_configuration_epoch);
|
||||
let story = story_nodes(campaign, narrations);
|
||||
let player = &campaign.actors[&campaign.player_actor_id];
|
||||
let player = &campaign.actors[viewer_actor_id];
|
||||
let location = &campaign.locations[&player.location_id];
|
||||
let relationships = if player.relationships.is_empty() {
|
||||
"none".into()
|
||||
|
|
@ -65,7 +73,7 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -
|
|||
relationships,
|
||||
join(&player.knowledge)
|
||||
);
|
||||
let news=campaign.news.iter().map(|item|json!({"id":item.id,"kind":"text","props":{"value":format!("[{}] {}",item.channel,item.headline)},"children":[]})).collect::<Vec<_>>();
|
||||
let news=campaign.news.iter().filter(|item| player.knowledge.contains(&item.channel)).map(|item|json!({"id":item.id,"kind":"text","props":{"value":format!("[{}] {}",item.channel,item.headline)},"children":[]})).collect::<Vec<_>>();
|
||||
let effective_budget = campaign
|
||||
.resolution_cover
|
||||
.as_ref()
|
||||
|
|
@ -75,8 +83,9 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -
|
|||
"type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon",
|
||||
"providerKind":"narrative.simulation", "title":campaign.name, "version":interface_version,
|
||||
"world_revision":campaign.revision,
|
||||
"player_actor_id":campaign.player_actor_id,
|
||||
"viewer_actor_id":viewer_actor_id,
|
||||
"player_location_id":player.location_id,
|
||||
"reachable_destinations":location.routes.iter().filter_map(|(destination_id,route)|campaign.locations.get(destination_id).map(|destination|json!({"id":destination_id,"name":destination.name,"travel_minutes":route.travel_minutes,"distance":route.distance}))).collect::<Vec<_>>(),
|
||||
"resolution":{
|
||||
"policy":campaign.resolution_policy,
|
||||
"effective_budget":effective_budget,
|
||||
|
|
@ -330,7 +339,7 @@ mod tests {
|
|||
|
||||
let surface = player_surface(&campaign, &[]);
|
||||
|
||||
assert_eq!(surface["player_actor_id"], "pilot-nyx");
|
||||
assert_eq!(surface["viewer_actor_id"], "pilot-nyx");
|
||||
assert_eq!(surface["player_location_id"], "center");
|
||||
assert!(
|
||||
serde_json::to_string(&surface)
|
||||
|
|
@ -365,6 +374,12 @@ mod tests {
|
|||
event_ids: vec!["event:public".into()],
|
||||
reliability: "direct institutional channel".into(),
|
||||
});
|
||||
campaign
|
||||
.actors
|
||||
.get_mut("player")
|
||||
.unwrap()
|
||||
.knowledge
|
||||
.insert("public bulletin".into());
|
||||
campaign.resolution_pins.insert(
|
||||
"secret-pin".into(),
|
||||
crate::domain::ResolutionPin {
|
||||
|
|
|
|||
|
|
@ -73,7 +73,11 @@ pub async fn appraise_present(
|
|||
.actors
|
||||
.values()
|
||||
.filter(|actor| {
|
||||
actor.id != campaign.player_actor_id && actor.location_id == player.location_id
|
||||
actor.location_id == player.location_id
|
||||
&& campaign
|
||||
.agency_profiles
|
||||
.get(&actor.id)
|
||||
.is_none_or(|profile| profile.simulation_eligible)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@
|
|||
|
||||
## Status
|
||||
|
||||
Multiplayer is an intended post-single-player extension. It is not part of the
|
||||
current MVP acceptance promise, subscription contract, or deployed tester
|
||||
surface.
|
||||
Bounded cooperative multiplayer is implemented in the current MVP: one to
|
||||
eight authenticated players complete Session Zero and begin in one shared
|
||||
scene with sequential public actions, actor-filtered surfaces, pooled
|
||||
Persona-cell entitlements, and unanimous time, travel, and budget governance.
|
||||
The broader model in this document remains the direction for split parties,
|
||||
private play actions, simultaneous declarations, delegation, and PvP.
|
||||
|
||||
The existing simulation is already shaped around multiple bounded actors. The
|
||||
extension should expose that anatomy to multiple human controllers without
|
||||
|
|
@ -14,9 +17,8 @@ creating a second world authority or a special multiplayer simulation loop.
|
|||
|
||||
Let several human-controlled characters inhabit one persistent campaign while
|
||||
preserving the same spatial, epistemic, causal, and commit invariants as solo
|
||||
play. Players may share a scene, split across locations, keep secrets, arrive
|
||||
late, miss events, and rejoin without receiving contradictory reconstructions
|
||||
of the world.
|
||||
play. The implemented milestone keeps the party together. Split locations,
|
||||
late joining, and private in-play actions remain future governance work.
|
||||
|
||||
## Authority map
|
||||
|
||||
|
|
@ -33,9 +35,10 @@ of the world.
|
|||
- **Forbidden writers:** browsers, sessions, party leaders, Personas,
|
||||
Interpreters, narrators, initiative, and realtime transports cannot commit or
|
||||
repair campaign state.
|
||||
- **Shared path:** solo commands, multiplayer commands, waits, travel,
|
||||
simultaneous-action windows, NPC reactions, scheduler ticks, reconnects, and
|
||||
imports use the same `WorldCommand → validate → atomic commit` primitive.
|
||||
- **Shared path:** solo commands, bounded multiplayer commands, unanimous waits
|
||||
and travel, NPC reactions, scheduler ticks, and reconnects use the same
|
||||
`WorldCommand → validate → atomic commit` primitive. Future simultaneous
|
||||
windows must join this path too.
|
||||
- **Cut line:** do not add a parallel room-state store, party prompt, shared
|
||||
narrator memory, or multiplayer-only mutation path.
|
||||
|
||||
|
|
@ -80,9 +83,10 @@ initiative, or commit validation.
|
|||
- Simultaneously submitted incompatible attempts resolve from one snapshot and
|
||||
one deterministic initiative/conflict pass. Arrival order at HTTP or CultNet
|
||||
transport is not fictional initiative.
|
||||
- Player count does not multiply the background Persona-cell budget. Resolution
|
||||
policy belongs to the campaign; directly engaged player characters may create
|
||||
the same explicit mandatory-cell overage as other foreground actors.
|
||||
- Each active member contributes the allowance returned by the entitlement
|
||||
port. The campaign pool is capped by the operator ceiling of 128. Human
|
||||
actors occupy mandatory cells without Persona inference; provider request
|
||||
concurrency remains independent of the chosen cover.
|
||||
- Reconnect and replay derive the player's view from committed receipts and
|
||||
perception rules. A client cache cannot repair or override the kernel.
|
||||
- One malformed, stale, or unauthorized participant proposal cannot partially
|
||||
|
|
@ -109,11 +113,11 @@ typed, persisted, inspectable, and enforced at command admission.
|
|||
|
||||
## Product sequence
|
||||
|
||||
1. Prove the solo paid-alpha loop and multiresolution setting agency.
|
||||
2. Add campaign membership and exact actor-control assignments without changing
|
||||
world mutation.
|
||||
3. Support two cooperative players in one scene with perception-specific output.
|
||||
4. Support split locations, private communication, disconnect, and reconnect.
|
||||
1. Prove the solo loop and multiresolution setting agency. **Complete.**
|
||||
2. Add campaign membership and exact actor-control assignments. **Complete.**
|
||||
3. Support up to eight cooperative players in one scene with actor-specific
|
||||
output and unanimous group governance. **Complete in this milestone.**
|
||||
4. Support split locations, private communication, departure, and late joining.
|
||||
5. Add snapshot-bound simultaneous declaration windows.
|
||||
6. Admit adversarial actions only after consent and governance policy is typed
|
||||
and tested.
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
## Objective
|
||||
|
||||
GhostlightDungeon is a persistent single-player narrative simulation grounded
|
||||
in a source-owned worldbuilding Vault. It gives the world stable geography,
|
||||
bounded knowledge, durable actors and institutions, explicit consequence, and
|
||||
motion beyond the player's attention. The player describes attempts. The world
|
||||
decides what is possible, what is opposed, and what changes.
|
||||
GhostlightDungeon is a persistent solo and bounded-co-op narrative simulation
|
||||
grounded in a source-owned worldbuilding Vault. It gives the world stable
|
||||
geography, bounded knowledge, durable actors and institutions, explicit
|
||||
consequence, and motion beyond the players' attention. Players describe
|
||||
attempts. The world decides what is possible, what is opposed, and what changes.
|
||||
|
||||
The MVP runs as a Rust daemon on Starfire and publishes a private Eve/CultUI
|
||||
surface for two invited testers. Aetheria is the bundled setting adapter. The
|
||||
|
|
@ -17,32 +17,34 @@ evidence and regression scenarios. They do not own runtime state or commits.
|
|||
|
||||
## Implementation frontier
|
||||
|
||||
The Rust runtime now contains the first honest world-compiler seam:
|
||||
The Rust runtime contains a Session Zero-owned world-compiler seam:
|
||||
|
||||
- `VaultProvider` search results become exact, hashed evidence witnesses from
|
||||
VoidBot's live streamable MCP response shape;
|
||||
- opening generation requires exactly three distinct eras, places, and
|
||||
pressures;
|
||||
- role generation requires exactly three grounded roles;
|
||||
pressures and installs them as shared Session Zero decisions;
|
||||
- role generation requires exactly three grounded roles and installs them in
|
||||
each player's private channel;
|
||||
- custom compilation emits a bounded typed campaign, evidence receipts, gaps,
|
||||
branch assumptions, and an approval-required preview;
|
||||
- custom compilation classifies every exact witness as direct seed, setting
|
||||
background, or excluded before world generation, so a nearby story cannot
|
||||
donate its cast, incident, clocks, or institutional posture to a new branch;
|
||||
- a separate Flash-model lane uses two stable broad retrieval queries to
|
||||
compile a coarse remote agency catalog in parallel with local evidence
|
||||
classification. It admits only a proper name plus one short mandate that
|
||||
deterministic code can bind verbatim to a witness naming that institution;
|
||||
extract witnessed remote institutions in parallel with local evidence
|
||||
classification. A Pro synthesis stage turns exact supporting claims into a
|
||||
concise strategic doctrine; local verification rejects unsupported doctrine;
|
||||
- remote institutions begin with deterministic six-axis profiles: their own
|
||||
authority boundary and explicit unknown geography, ideology, economic role,
|
||||
body, and information scope. Fine resources, channels, relations, and current
|
||||
posture compile only when causal relevance supplies evidence for them;
|
||||
- deterministic seed validation rejects missing occupancy, dangling or
|
||||
zero-time routes, invalid containment, invalid clocks, and missing players;
|
||||
- approval alone submits `CreateCampaign`, which atomically stores the campaign
|
||||
and the exact Vault receipts in the campaign `.cc` store.
|
||||
- unanimous current-digest approval plus explicit host publication atomically
|
||||
stores campaign, membership, contract, DM Persona, approved brief, exact
|
||||
Vault receipts, model receipts, and approval evidence in the campaign `.cc`.
|
||||
|
||||
The hosted compiler now exposes generated openings, grounded role selection,
|
||||
The Session Zero DM exposes generated openings, grounded role selection,
|
||||
unrestricted custom starts, approval-gated material gaps, exact-document
|
||||
witnesses, on-demand destination expansion, and persistent canon candidates.
|
||||
A live custom-start acceptance run on 2026-08-16 consumed 30 VoidBot witnesses
|
||||
|
|
@ -63,7 +65,7 @@ token. Only hashed local session aliases enter `service/auth.cc`.
|
|||
|
||||
| Faculty | Owner | Body | Authority |
|
||||
| --- | --- | --- | --- |
|
||||
| Self | `WorldKernel` campaign mailbox | One campaign `.cc` store | Orders commands and owns the campaign revision |
|
||||
| Self | `SessionZeroKernel` / `WorldKernel` mailboxes | One draft `.cc` / one campaign `.cc` | Own draft negotiation or canonical world revision, never both |
|
||||
| Eyes | `VaultProvider` and actor perception slices | VoidBot MCP receipts, topology, occupancy, knowledge | Retrieves and witnesses; never commits world truth |
|
||||
| Modeling | World compiler and action assessor | Typed campaign snapshot | Proposes topology, facts, affordances, DC, stakes, and gaps |
|
||||
| Imagination | Persona and world proposal stages | Private narrative projections | Proposes speech, private deltas, reactions, and actions |
|
||||
|
|
@ -514,12 +516,13 @@ boundaries. It is not load-bearing runtime state.
|
|||
### Campaign registry and session authority
|
||||
|
||||
- **Owner:** the service `CampaignRegistry` owns the mapping from authenticated
|
||||
session hash to selected campaign ID and from campaign ID to its sole
|
||||
account hash to selected campaign ID and from campaign ID to its sole
|
||||
`CampaignRuntime` (`CampaignStore` plus `WorldKernel` mailbox).
|
||||
- **Inputs:** persisted hashed session authority, named campaign lifecycle
|
||||
commands, runtime-root inventory, and exact campaign IDs.
|
||||
- **Outputs:** one selected single-player runtime per session, isolated campaign
|
||||
`.cc` paths, lifecycle receipts, and immutable export bundles.
|
||||
- **Outputs:** one selected campaign runtime per entitled member, exact
|
||||
member-to-actor bindings, isolated campaign `.cc` paths, and lifecycle
|
||||
receipts. Group fork/reset/export remains disabled pending consent policy.
|
||||
- **Derived state:** browser selection, campaign lists, filenames, download
|
||||
responses, and operator cards are projections of registry/control state.
|
||||
- **Forbidden writers:** route handlers, invite cookies, filesystem discovery,
|
||||
|
|
@ -555,12 +558,13 @@ exact evidence receipts used by the campaign, never vectors or a rival index.
|
|||
Compilation is staged and approval-gated:
|
||||
|
||||
```text
|
||||
opening request
|
||||
Begin Session Zero
|
||||
-> retrieval plan
|
||||
-> local exact evidence receipts || stable remote-agency retrieval
|
||||
-> source-use classification || witnessed remote mandate extraction
|
||||
-> three distinct openings or custom opening
|
||||
-> three grounded roles or custom role
|
||||
-> source-use classification || witnessed remote institution extraction
|
||||
-> three distinct opening decisions or custom discussion
|
||||
-> three private role decisions or custom character negotiation
|
||||
-> typed campaign contract + private character drafts + exact approvals
|
||||
-> direct-evidence bounded region + deterministic coarse remote profiles
|
||||
-> semantic agency profiles only for locally materialized subjects
|
||||
-> coverage/gap/assumption preview
|
||||
|
|
@ -578,14 +582,12 @@ not enter the world-seed prompt; excluded evidence is likewise absent. This
|
|||
separation preserves provenance without making retrieved adjacency into
|
||||
fictional causality.
|
||||
|
||||
The remote catalog is not a back door into the local seed. Its model output may
|
||||
propose at most 32 institutions and one short mandate string for each. Local
|
||||
code locates that string in the supplied witnesses and requires the same source
|
||||
to name the institution. Unsupported entries are omitted and summarized as
|
||||
approval-preview coverage gaps; their exact rejection reasons remain in the
|
||||
private model-stage receipt. They do not become campaign canon candidates.
|
||||
This lets the campaign represent distant powers without importing another
|
||||
story's current cast or incident.
|
||||
The remote catalog is not a back door into the local seed. Extraction proposes
|
||||
named institutions plus exact supporting claims. Synthesis writes one concise
|
||||
strategic doctrine from those claims, and a separate verifier must accept it.
|
||||
Unsupported or oversized entries become approval-preview gaps rather than
|
||||
institutions. This lets the campaign represent distant powers without importing
|
||||
another story's current cast, incident, or arbitrary excerpt as behavior.
|
||||
|
||||
The coarse profile is intentionally sparse. Asking the Pro agency compiler to
|
||||
repeat six semantic axes for every remote power exhausted output tokens while
|
||||
|
|
@ -690,17 +692,18 @@ and model-stage state belongs to the authenticated operator projection only.
|
|||
Player and model strings enter the DOM through text nodes rather than HTML
|
||||
insertion, and all laboratory inputs have programmatic labels.
|
||||
|
||||
The same rule covers compiler and campaign-management routes. Opening and role
|
||||
responses contain selectable suggestions, not retrieval/model receipts. An
|
||||
approval preview contains the promised topology, public cast, institutions,
|
||||
populations, clocks, player-role ledger, evidence-use coverage, gaps, and branch
|
||||
assumptions without private goals, memories, relationships, raw evidence, or a
|
||||
serialized campaign. Approval, expansion, fission, fork, and reset return small
|
||||
public receipts; their internal command results remain inside the daemon.
|
||||
The same rule covers Session Zero and campaign-management routes. Opening and
|
||||
role suggestions are filtered typed decisions inside shared or private
|
||||
channels; raw retrieval/model receipts remain private. The review projection
|
||||
contains promised topology, institutions, populations, clocks, evidence-use
|
||||
coverage, gaps, branch assumptions, and only the current viewer's private
|
||||
character state. Publication, expansion, and fission return small public
|
||||
receipts. Group fork/reset/export is rejected until its consent policy exists.
|
||||
|
||||
The player surface includes compilation, transcript, composer, Assess/Attempt,
|
||||
roll confirmation, Wait, character ledger, current place/time/pressure, news,
|
||||
campaign management, fork/reset/export, and optional operator inspection.
|
||||
The player surface includes Session Zero channels and ledgers, transcript,
|
||||
composer, Assess/Attempt, roll confirmation, actor-specific character/news
|
||||
state, unanimous time/travel/budget proposals, Contract Review, and optional
|
||||
operator inspection.
|
||||
CultMesh state is the source of the UI projection. HTTP health is a probe over
|
||||
the same service-state document.
|
||||
|
||||
|
|
@ -769,15 +772,13 @@ Live model allocation:
|
|||
|
||||
## Hosting and security
|
||||
|
||||
The daemon serves the embedded browser bundle on TCP 8831. Firewall scope is
|
||||
Starfire's private LAN and `10.77.0.0/24`; there is no public listener or
|
||||
Yggdrasil web gateway. Provisioned single-use invites establish separate HttpOnly
|
||||
sessions. Campaigns remain single-player in the MVP. This is a product-scope
|
||||
constraint, not a WorldKernel identity: the intended post-solo extension maps
|
||||
multiple authenticated members to distinct player-controlled actors while all
|
||||
commands continue through the same campaign mailbox and atomic commit path.
|
||||
`ghostlight-dungeon-multiplayer-intention.md` owns that future authority map;
|
||||
it does not expand the current acceptance gate.
|
||||
The daemon serves the embedded browser bundle on TCP 8831. Public access is
|
||||
lowered through the existing Heimdall-authenticated `/ghostlight/` reverse
|
||||
proxy path; the application does not add a rival identity system. One to eight
|
||||
members map to distinct player-controlled actors while every command continues
|
||||
through the same campaign mailbox and atomic commit path. The bounded milestone
|
||||
keeps the party in one scene; the multiplayer-intention document owns the
|
||||
remaining split-party and social-governance work.
|
||||
|
||||
The MVP runs as a normal detached process under the Starfire operator account.
|
||||
The launcher records the PID, exact executable path, release commit, and logs;
|
||||
|
|
|
|||
146
docs/architecture/ghostlight-dungeon-session-zero.md
Normal file
146
docs/architecture/ghostlight-dungeon-session-zero.md
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
# Ghostlight Dungeon Session Zero and Bounded Co-op
|
||||
|
||||
## Status
|
||||
|
||||
This document is the authority map for campaign creation and the first bounded
|
||||
co-op runtime. Direct browser-owned compilation is not a production authority.
|
||||
Generated openings and roles are DM suggestions inside Session Zero; the typed
|
||||
draft is the only compiler input.
|
||||
|
||||
## Owners
|
||||
|
||||
### SessionZeroKernel
|
||||
|
||||
`SessionZeroKernel` owns one persistent draft mailbox and its revisions. Its
|
||||
MessagePack CultCache store contains the roster, single-use invitations,
|
||||
shared/private channels, messages, contract, private character drafts,
|
||||
boundaries, decisions, approvals, DM Persona, evidence coverage, compilation
|
||||
preview, and publication receipt.
|
||||
|
||||
Player messages are durable conversation, not campaign facts. Projector, DM
|
||||
Persona, Interpreter, retrieval, and compilation stages return proposals. Only
|
||||
the kernel may change the draft.
|
||||
|
||||
Private DM channels use character-component and channel epochs. Independent
|
||||
private turns can finish in parallel even if an unrelated private component
|
||||
commits first. Shared changes serialize through the shared epoch. No output is
|
||||
rebased.
|
||||
|
||||
### WorldKernel
|
||||
|
||||
`WorldKernel` receives nothing while Session Zero is drafting. Publication
|
||||
builds a new campaign store in a private staging directory. Campaign seed,
|
||||
membership, contract, governance, DM Persona, approved brief, approval digests,
|
||||
Vault evidence, and model receipts enter one empty CultCache batch. The
|
||||
directory becomes discoverable only after the batch succeeds.
|
||||
|
||||
Publication is idempotent by the approved seed digest. Repeating the same
|
||||
publication recovers the campaign. Reusing the campaign ID for a different
|
||||
digest is rejected.
|
||||
|
||||
## Privacy membrane
|
||||
|
||||
Shared DM inference receives the shared contract, aggregate boundary policy,
|
||||
public party cards, shared decisions, evidence coverage, and recent shared
|
||||
messages. It cannot receive raw boundaries, another player's private draft, or
|
||||
private messages.
|
||||
|
||||
Private DM inference receives the shared contract, aggregate policy, public
|
||||
party cards, that player's character draft, that player's attributed
|
||||
boundaries, visible decisions, and recent messages from that private channel.
|
||||
It cannot receive another player's private state.
|
||||
|
||||
Account hashes and invite-token hashes remain private persistence fields. They
|
||||
are absent from JSON Schemas, browser projections, CultMesh surfaces, and model
|
||||
contexts. Actor-specific campaign surfaces use random campaign member IDs and
|
||||
the exact assigned actor.
|
||||
|
||||
## Approval and publication
|
||||
|
||||
The host locks the roster before compilation. Material unresolved decisions
|
||||
block compilation. The compiler receives an `approved_campaign_brief.v1`, not
|
||||
the transcript. Private character history and secrets are withheld from world
|
||||
generation; after the grounded seed validates, Ghostlight locally replaces the
|
||||
provisional compiler player with the exact approved actors at one shared start.
|
||||
|
||||
Evidence gaps return the draft to conversation with explicit questions. A
|
||||
review preview records shared and per-character digests. Every active player
|
||||
must approve the current shared digest and their current private character
|
||||
digest. Relevant edits retire the preview and invalidate the affected
|
||||
approvals. The host has no override.
|
||||
|
||||
Accepted extraordinary bargains become typed permissions. Later assessment
|
||||
receives their exact scope, prerequisites, costs, limits, exposure, evidence,
|
||||
and effect ceiling.
|
||||
|
||||
## Bounded co-op
|
||||
|
||||
`campaign_membership.v1` binds authenticated account hashes to random member
|
||||
IDs and exact actor IDs. HTTP admission derives the acting actor from this
|
||||
record. Assessment confirmation includes that actor ID and cannot consume
|
||||
another actor's assessment.
|
||||
|
||||
The first co-op mode deliberately permits one shared scene and sequential
|
||||
public actions. It rejects player-versus-player state mutation, movement that
|
||||
would split the party, raw unilateral waits, and unilateral resolution-budget
|
||||
changes. Time, group travel, and pooled Persona-cell budget changes use
|
||||
revision-bound proposals; the final approval and campaign transition commit
|
||||
atomically. Group travel revalidates the shared origin and exact route, moves
|
||||
every assigned actor, and advances time in one world commit.
|
||||
|
||||
Every human-controlled actor has a non-simulatable agency profile. Live NPC
|
||||
appraisal, multiresolution cells, strategic outcomes, migration, scheduler
|
||||
ticks, and away-time work all exclude those actors from Persona control and
|
||||
direct mutation. Disconnection grants no proxy authority.
|
||||
|
||||
Each active member contributes their entitlement-provided cell allowance. Test
|
||||
accounts currently contribute eight. The campaign starts at the pooled total,
|
||||
capped at 128; physical provider concurrency remains independent.
|
||||
|
||||
## Realtime and interface
|
||||
|
||||
Ghostlight publishes an actor-filtered Eve surface for each Session Zero member
|
||||
and campaign member. Server-sent events contain revision notifications only.
|
||||
The browser refetches the authoritative Eve document after a notice; the
|
||||
transport owns no messages, drafts, ledgers, approvals, or world state.
|
||||
|
||||
The browser exposes keyboard-operable shared/private channel tabs, live status,
|
||||
public party cards, private ledgers and boundaries, unresolved decisions,
|
||||
evidence/preview state, roster readiness, and explicit compile/approve/publish
|
||||
actions. Privacy is labeled in text and never conveyed only by color.
|
||||
|
||||
## Inline grounded suggestions
|
||||
|
||||
Opening and role generation is no longer a browser-owned creation flow. On a
|
||||
new draft, the compiler retrieves three distinct Vault-grounded opening
|
||||
suggestions and installs them as shared typed decisions. Accepting one amends
|
||||
the draft for further discussion; it does not publish a world. Ghostlight then
|
||||
retrieves three grounded role suggestions and installs separate typed decisions
|
||||
in each player's private channel. A custom premise uses the same conversation,
|
||||
draft, approval, and compiler path.
|
||||
|
||||
## Contract Review
|
||||
|
||||
A launched campaign can enter a focused Contract Review backed by the same
|
||||
Session Zero kernel and privacy projections. The review is bound to the exact
|
||||
world revision at which it began. Any intervening world commit makes it stale.
|
||||
Every active member approves the revised shared digest and their own character
|
||||
digest before the host can publish.
|
||||
|
||||
Publication updates the existing campaign, contract, membership permissions,
|
||||
DM Persona, approved brief, governance epoch, actors' approved forward-looking
|
||||
ledger fields, event, and receipt in one CultCache batch. It cannot change
|
||||
membership custody, locations, topology, knowledge, memories, historical
|
||||
events, Vault, canon horizon, or established starting geometry. Tightened
|
||||
private boundaries publish immediately as an anonymous strictest campaign
|
||||
policy; relaxation waits for unanimous review publication. Narration, action
|
||||
assessment, resolution demand, cell Projectors, Interpreters, and semantic
|
||||
verification receive the approved contract and aggregate policy. Actor Personas
|
||||
still receive only lived narrative, not policy schemas or attributed safety
|
||||
records.
|
||||
|
||||
## Deferred governance
|
||||
|
||||
Split parties, private in-play actions, simultaneous declarations, PvP,
|
||||
delegation, late joining, permanent post-publication departure, group
|
||||
fork/reset/export, and voice remain unsupported.
|
||||
|
|
@ -33,6 +33,40 @@ per-campaign WorldKernel mailbox is the sole canonical writer. Ghostlight owns
|
|||
the generalized Projector → Persona → Interpreter organ; Epiphany retains her
|
||||
canonical Persona mind and will consume the shared organ through an adapter.
|
||||
|
||||
### 2026-08-21 Session Zero / bounded co-op cut
|
||||
|
||||
The current checkout adds a separate pre-world owner: `SessionZeroKernel` is
|
||||
the sole writer for persistent shared/private conversation, roster, invitations,
|
||||
typed contract, private character drafts, boundaries, decisions, approvals,
|
||||
DM Persona, and compilation review. WorldKernel receives nothing until every
|
||||
active player approves the current shared digest and their private character
|
||||
digest and the host publishes. Publication stages and atomically exposes one
|
||||
campaign store containing the seed, membership, contract, DM Persona, approved
|
||||
brief, approvals, exact evidence, receipts, and final seed digest.
|
||||
|
||||
One to eight authenticated players are implemented in bounded shared-scene
|
||||
co-op. `campaign_membership.v1` is actor custody. Surfaces, knowledge, news,
|
||||
ledgers, assessment, and roll confirmation derive from the caller's exact
|
||||
actor. Human actors cannot run Persona inference or strategic/scheduler moves.
|
||||
PvP, split-party effects, and unilateral co-op waits are rejected by the kernel.
|
||||
Time, group travel, and pooled Persona-cell budget changes require unanimous
|
||||
revision-bound approval and commit once. Provider concurrency is separate.
|
||||
|
||||
Grounded openings and roles are inline Session Zero decisions, not compiler
|
||||
forms. The compiler consumes `approved_campaign_brief.v1`, not the transcript.
|
||||
A launched campaign may enter revision-bound Contract Review; unanimous
|
||||
publication can amend forward-looking contract, permissions, and approved
|
||||
ledger fields but cannot rewrite actor custody, locations, topology, knowledge,
|
||||
memories, canon, or history. Tightened private boundaries become anonymous
|
||||
live aggregate policy immediately; relaxation waits for unanimous publication.
|
||||
Narration, assessment, resolution demand, cell projection/interpretation, and
|
||||
semantic verification now receive the approved contract and aggregate policy.
|
||||
|
||||
Do not confuse checkout truth with deployment truth. The immutable release
|
||||
listed below remains live until this change passes full tests, is committed,
|
||||
pushed, built, and activated through Idunn. Deployment evidence belongs in
|
||||
`gamecult-ops` and the state map, not in optimistic prose.
|
||||
|
||||
The hosted MVP is implemented and live on Starfire. Ghostlight owns the
|
||||
generalized projection membrane; Epiphany consumes its pinned crate while
|
||||
retaining her own Mind and consequence authority. The Rust daemon now owns
|
||||
|
|
@ -75,13 +109,12 @@ populations never merge; only the derived simulation cover does. Budget/pin
|
|||
changes use `resolution_epoch`, provider parallelism uses its own configuration
|
||||
epoch, and neither advances fictional time.
|
||||
|
||||
The paid-alpha scope remains single-player, but single-player is not a kernel
|
||||
invariant. `docs/architecture/ghostlight-dungeon-multiplayer-intention.md`
|
||||
records the intended later extension: multiple authenticated humans control
|
||||
distinct actors through the same mailbox, perception gates, initiative, and
|
||||
atomic WorldKernel commit path. It introduces no party prompt, room-state
|
||||
authority, or current implementation work. The forge remains focused on proving
|
||||
that multiresolution Gestalts preserve agency and produce satisfying surprises.
|
||||
The current forge gate includes bounded co-op. The remaining multiplayer
|
||||
intention covers split parties, private in-play commands, simultaneous windows,
|
||||
delegation, late joining, departure, PvP, and group lifecycle governance. It
|
||||
introduces no party prompt or room-state authority. The forge remains focused
|
||||
on proving that multiresolution Gestalts preserve agency and produce satisfying
|
||||
surprises under several human foreground actors.
|
||||
|
||||
The current acceptance candidate adds a bounded population activity vocabulary
|
||||
for preparation, coordination, investigation, recruitment, obstruction,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,24 @@ seams remain regression evidence only.
|
|||
|
||||
## GhostlightDungeon target flow
|
||||
|
||||
Campaign creation now has its own pre-world authority:
|
||||
|
||||
```text
|
||||
Heimdall member messages
|
||||
-> SessionZeroKernel durable shared/private conversation
|
||||
-> Projector -> persistent DM Persona -> Interpreter proposals
|
||||
-> typed contract, private character drafts, boundaries, decisions
|
||||
-> roster lock -> approved_campaign_brief.v1 -> Vault compiler
|
||||
-> evidence-gap conversation or digest-bound final review
|
||||
-> every player approves shared + own private digest
|
||||
-> one staging CultCache batch + atomic directory exposure
|
||||
-> campaign_membership.v1 binds each member to one exact actor
|
||||
```
|
||||
|
||||
`WorldKernel` receives no draft state. The transcript is never replayed into the
|
||||
compiler. Account and invitation hashes remain persistence-only; shared model
|
||||
turns, browser surfaces, schemas, and CultMesh records cannot see them.
|
||||
|
||||
```text
|
||||
Vault evidence receipts + typed campaign snapshot
|
||||
-> permissioned projection
|
||||
|
|
@ -23,13 +41,18 @@ Vault evidence receipts + typed campaign snapshot
|
|||
Ghostlight owns the generalized projection organ. Epiphany and other consumers
|
||||
own their canonical Persona state and consequence commits.
|
||||
|
||||
The current player surface assigns one human session to one single-player
|
||||
campaign. That is product scope, not kernel identity. The intended multiplayer
|
||||
extension maps authenticated campaign members to distinct canonical actors and
|
||||
routes every human command through this same mailbox and WorldKernel. Each
|
||||
player receives an actor-permitted narrative projection; no party prompt or
|
||||
shared client state becomes a second world authority. The bounded intention is
|
||||
mapped in `docs/architecture/ghostlight-dungeon-multiplayer-intention.md`.
|
||||
The current checkout admits one to eight campaign members into one shared
|
||||
scene. `campaign_membership.v1` maps each authenticated account to one exact
|
||||
actor; HTTP, Eve, assessment confirmation, and CultMesh publication derive from
|
||||
that binding. Human actors are excluded from Persona and strategic control.
|
||||
Sequential public actions are accepted; PvP and split-party movement are
|
||||
rejected. Time, group travel, and pooled cell-budget changes require unanimous
|
||||
revision-bound approval. Post-launch Contract Review reuses the Session Zero
|
||||
kernel against an exact world revision and commits approved amendments in one
|
||||
campaign batch without rewriting location, topology, knowledge, memory, or
|
||||
history. The authority map is
|
||||
`docs/architecture/ghostlight-dungeon-session-zero.md`; later multiplayer work
|
||||
remains in `docs/architecture/ghostlight-dungeon-multiplayer-intention.md`.
|
||||
|
||||
Build provenance has one owner: `crates/ghostlight-dungeon/build.rs` binds the
|
||||
exact source commit into the binary. Its inputs are either the release tool's
|
||||
|
|
@ -160,11 +183,10 @@ key and target while the complete local snapshot persists and HTTP serves that
|
|||
same typed health and Eve state.
|
||||
|
||||
Opening retrieval deliberately covers early, transitional, and late historical
|
||||
frames. Suggestions receive one same-evidence semantic correction with exact
|
||||
collided values when the local distinctness invariant rejects the first typed
|
||||
set; roles use the same bounded correction for duplicate names or premises.
|
||||
Both rejected and accepted receipts remain private while the browser receives
|
||||
only public suggestions. Invite rotation is owned by
|
||||
frames. These pure retrieval/compiler functions now serve the Session Zero DM;
|
||||
they are not browser-owned creation routes or transient preview maps. Generated
|
||||
suggestions enter the typed draft for discussion and use the same final brief as
|
||||
custom premises. Both rejected and accepted receipts remain private. Invite rotation is owned by
|
||||
the deployment boundary: it replaces the protected token set and clears the
|
||||
persisted auth authority together while the daemon is stopped. Campaign stores
|
||||
survive; old sessions deliberately do not.
|
||||
|
|
@ -398,27 +420,25 @@ world seed. The live AetheriaLore retrieval archive is correspondingly bounded
|
|||
to `Aetheria/Worldbuilding/`; durable facts discovered through fiction must be
|
||||
promoted into Worldbuilding before they become reusable campaign canon.
|
||||
|
||||
Compiler, expansion, fission, fork, and reset routes follow the same projection
|
||||
rule. Approval previews expose the public decision surface—topology, cast,
|
||||
pressures, player role, source-use coverage, gaps, and assumptions—without raw
|
||||
campaign, evidence, model receipts, private goals, memories, or relationships.
|
||||
Generated openings and roles are session-scoped server-owned candidates. The
|
||||
browser receives their display projections and returns only an opening ID or
|
||||
role ID; it cannot echo a rewritten candidate back into compilation. Role
|
||||
selection must resolve against the same session and opening. The selected
|
||||
role's validated capabilities and obligations are then bound deterministically
|
||||
into the player actor and named as a branch assumption, while the opening/role
|
||||
evidence and model receipts are carried into the approval preview. Candidate
|
||||
IDs, text, list sizes, and evidence references receive local validation before
|
||||
they can become selectable. Restart may expire these noncanonical suggestions;
|
||||
it cannot silently reconstruct or substitute them.
|
||||
Session Zero compilation, expansion, and fission follow the same projection
|
||||
rule. Review projections expose topology, pressures, source-use coverage, gaps,
|
||||
assumptions, public party cards, and only the current viewer's private ledger.
|
||||
Generated openings are shared typed decisions; accepting one amends the draft
|
||||
for discussion and triggers three grounded role decisions in each private DM
|
||||
channel. Custom starts and characters use the same draft. The browser returns
|
||||
only decision commands and cannot echo a rewritten candidate into compilation.
|
||||
Candidate IDs, text, list sizes, and evidence references receive local
|
||||
validation. Suggestion retrieval and model receipts remain in the Session Zero
|
||||
store; publication compiles the unanimously approved brief, never the
|
||||
conversation transcript.
|
||||
|
||||
Campaign publication has a separate discoverability boundary. Registry create,
|
||||
fork, reset, and compiler approval initialize a new `.cc` store under a
|
||||
Campaign publication has a separate discoverability boundary. Session Zero
|
||||
publication and solo lifecycle operations initialize a new `.cc` store under a
|
||||
non-UUID `.creating-*` directory. The CreateCampaign command validates the
|
||||
seed, then atomically commits campaign state, approved seed, Vault manifest,
|
||||
evidence, model receipts, canon candidates, and the creation lifecycle receipt
|
||||
in one CultCache batch. Only that complete store is renamed into the UUID
|
||||
seed, then atomically commits campaign state, approved seed, membership,
|
||||
contract, DM Persona, approvals, Vault manifest, evidence, model receipts,
|
||||
canon candidates, and the creation lifecycle receipt in one CultCache batch.
|
||||
Only that complete store is renamed into the UUID
|
||||
namespace and admitted to the live registry. Failed initialization removes its
|
||||
exact staging directory and cannot poison daemon reload. Approval previews are
|
||||
retained until campaign publication, session selection, and reload all succeed;
|
||||
|
|
@ -648,9 +668,9 @@ paths as active state surfaces.
|
|||
|
||||
## Missing Or Incomplete Organs
|
||||
|
||||
- World compiler browser flow, selected-opening/role path, live provider
|
||||
acceptance, material-gap approval, on-demand destination expansion, and
|
||||
canon-candidate persistence
|
||||
- Contract-governed split parties, private in-play actions, delegation,
|
||||
simultaneous declaration windows, PvP, late joining, permanent departure,
|
||||
and group fork/reset/export
|
||||
- Deterministic speaker-local input slicer
|
||||
- Full prompt renderer
|
||||
- Classifier/appraiser pipeline
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
# GhostlightDungeon MVP — Starfire-Hosted AI Dungeon Master
|
||||
|
||||
> Historical foundation plan. Campaign creation and multiplayer authority are
|
||||
> superseded by
|
||||
> [`docs/architecture/ghostlight-dungeon-session-zero.md`](../docs/architecture/ghostlight-dungeon-session-zero.md).
|
||||
> This document remains the original product and world-simulation brief; its
|
||||
> single-player compiler forms and 1–32 budget wording are not the live runtime
|
||||
> contract.
|
||||
|
||||
## Summary
|
||||
|
||||
Build `GhostlightDungeon` inside `GameCult/Ghostlight`: a persistent, Vault-grounded, single-player narrative simulation with a private web chat interface for two testers.
|
||||
|
|
|
|||
|
|
@ -15,17 +15,20 @@ revision and now gives Persona only one lived narrative stream; Epiphany keeps
|
|||
her canonical Persona mind, receipts, effect admission, brakes, and external
|
||||
consequence authority.
|
||||
|
||||
The hosted runtime owns compiler approval, exact VoidBot evidence, campaign
|
||||
mailboxes, fiction-first d20 resolution, parallel Persona appraisal, narration,
|
||||
reversible gestalt materialization, isolated sessions/campaigns, CultMesh/Eve
|
||||
publication, and away-time scheduling. Strategic ticks now project six-axis
|
||||
The hosted runtime owns persistent DM-led Session Zero, exact VoidBot evidence,
|
||||
campaign mailboxes, fiction-first d20 resolution, parallel Persona appraisal,
|
||||
narration, reversible gestalt materialization, actor-bound membership,
|
||||
CultMesh/Eve publication, and away-time scheduling. One to eight authenticated
|
||||
players negotiate one shared contract and private character states before the
|
||||
host can atomically publish an unanimously approved seed. Strategic ticks now project six-axis
|
||||
pressure, select a connected budgeted cover over the global agency skeleton,
|
||||
and run one private Ghostlight Persona membrane per cohesive or arena cell. The
|
||||
WorldKernel admits the whole cell wave atomically and forbids player puppeting,
|
||||
synthetic arena actors, borrowed secrets, invented IDs, unreachable movement,
|
||||
and unbounded information or population-pressure edits. The laboratory exposes
|
||||
a 1–32 player budget, persistent pins, approval-gated gestalt fission, graph and
|
||||
cover receipts, and a separate operator provider-concurrency limit. The
|
||||
a pooled 1–128 campaign cell budget supplied by a player entitlement port,
|
||||
persistent pins, approval-gated gestalt fission, graph and cover receipts, and
|
||||
a separate operator provider-concurrency limit. The
|
||||
specific authority map is
|
||||
`docs/architecture/ghostlight-multiresolution-agency.md`.
|
||||
The accepted implementation is hosted on Starfire as immutable release
|
||||
|
|
@ -119,14 +122,26 @@ spoiler disclosure let the player bypass discovery before approving the seed.
|
|||
The approval surface retains topology, cast, institutions, populations, clocks,
|
||||
role capabilities, evidence coverage, gaps, and branch assumptions.
|
||||
|
||||
Multiplayer remains outside the current paid-alpha gate but is now an explicit
|
||||
architectural intention. Do not fork the simulation into a multiplayer room
|
||||
model. After the solo product and Gestalt agency are proven, extend campaign
|
||||
membership so authenticated humans control distinct canonical actors through
|
||||
the existing mailbox, perception gates, initiative, and atomic commit path. The
|
||||
authority map and unresolved consent/governance questions live in
|
||||
Bounded cooperative multiplayer is now part of the current forge gate. It uses
|
||||
campaign membership rather than a room model: distinct authenticated humans
|
||||
control exact canonical actors through the existing mailbox, perception gates,
|
||||
and atomic commit path. The implemented boundary is one shared scene,
|
||||
sequential public actions, actor-specific surfaces, no PvP, and unanimous
|
||||
time/travel/cell-budget changes. Split parties, private in-play actions,
|
||||
delegation, simultaneous declarations, late joining, and group lifecycle
|
||||
operations remain outside the gate. The authority map and remaining social
|
||||
governance live in
|
||||
`docs/architecture/ghostlight-dungeon-multiplayer-intention.md`.
|
||||
|
||||
Session Zero replaces direct compiler forms as campaign-creation authority.
|
||||
Grounded openings and roles are inline typed DM decisions; custom premises use
|
||||
the same draft. The compiler consumes only `approved_campaign_brief.v1`, and
|
||||
publication batches campaign, membership, contract, persistent DM Persona,
|
||||
approvals, evidence, and seed digest before discovery. Post-launch Contract
|
||||
Review reuses the same negotiation machinery against an exact world revision;
|
||||
it can amend forward-looking contract and actor ledger fields but cannot rewrite
|
||||
membership custody, locations, topology, knowledge, memories, or history.
|
||||
|
||||
## Prior research-program phase
|
||||
|
||||
Build a reliable data-generation loop for socially persistent Aetheria agents.
|
||||
|
|
|
|||
|
|
@ -13,9 +13,10 @@ mission:
|
|||
Build a persistent, Vault-grounded narrative simulation whose WorldKernel
|
||||
exclusively owns revisioned world state, while generalized
|
||||
Projector-Persona-Interpreter machinery produces bounded proposals for the
|
||||
kernel to validate. The paid-alpha surface is single-player; the durable
|
||||
authority model intentionally admits multiple authenticated humans as
|
||||
controllers of distinct canonical actors later.
|
||||
kernel to validate. The current forge surface supports one to eight
|
||||
authenticated players in bounded shared-scene co-op; the durable
|
||||
authority model admits those humans only as controllers of their exact
|
||||
canonical actors through campaign membership.
|
||||
primary: >
|
||||
Generate psychologically grounded branching scenes, dialogue, actions,
|
||||
social consequences, and eventually storylines, consumer behavior,
|
||||
|
|
@ -71,7 +72,7 @@ live_architecture:
|
|||
- Ghostlight owns generalized Projector to Persona to Interpreter machinery; consuming Personas retain their own canonical minds and commit authority.
|
||||
- Epiphany consumes the extracted Ghostlight projection crate at an exact Git revision while retaining her canonical Mind, effect admission, and consequence authority.
|
||||
- Gestalt Personas own shared population state; first-relevance individuation and later folding are revisioned WorldKernel commits, and durable member deltas preserve specific people between appearances.
|
||||
- The multiresolution agency graph derives a connected cohesive/arena cell cover from canonical actors, institutions, and gestalt leaves under a player-selected 1–32 budget.
|
||||
- The multiresolution agency graph derives a connected cohesive/arena cell cover from canonical actors, institutions, and gestalt leaves under a campaign-selected 1–128 pooled entitlement budget; provider concurrency is separate.
|
||||
- Model-driven strategic cell waves can change remote actors, institutions, gestalts, clocks, and exact-channel news while the absent player remains outside their write authority; the entire wave validates and commits atomically.
|
||||
- Population activity effects represent exact attributed attempts to prepare, coordinate, investigate, recruit, obstruct, trade, or communicate; graph scope, locations, channels, and semantics validate before the kernel derives an event, and the effect never claims its own success.
|
||||
- Population migration is a separate exact-leaf effect. WorldKernel atomically moves the Gestalt and its agency-profile location along an explicit reachable migration relation; destination populations remain distinct and named members never move by implication.
|
||||
|
|
@ -80,13 +81,15 @@ live_architecture:
|
|||
- Resolution-demand focal IDs are salience hints only; model output cannot force singleton cells or override the player-selected Persona-cell budget.
|
||||
- Projectors receive decision-relevant situation state, Personas receive only lived narrative, and Interpreters receive exact action permissions; runtime-owned cell membership and revisions are bound locally rather than copied by a model.
|
||||
- Cell Projector perspective ownership is schema-bound to exact constituents and selected member exceptions. Ghostlight lowers unique subject-keyed segments into name/location prose and requires the debt-selected focus before the Persona sees the stream.
|
||||
- Local world compilation sees direct-seed evidence only. A separate Flash lane may establish coarse remote institutions from one short witnessed mandate each; deterministic binding omits unsupported entries into non-canonical approval gaps.
|
||||
- Local world compilation sees direct-seed evidence only. A separate Flash lane extracts exact supporting claims for coarse remote institutions; Pro synthesizes concise strategic doctrine and a semantic verifier rejects unsupported doctrine into non-canonical approval gaps.
|
||||
- Remote institutions receive deterministic six-axis coarse profiles with distinct self-authority and explicit unknown facets. The Pro agency compiler profiles only locally materialized subjects; finer remote state compiles on demand.
|
||||
- Model-stage receipts expose per-attempt provider identity, latency, validation errors, and prompt/completion/cache token usage without storing reasoning content.
|
||||
- Budget and pins own `resolution_epoch`; provider concurrency owns a separate configuration epoch and cannot repartition or advance fiction.
|
||||
- Approval-gated gestalt fission creates explicit child leaves plus `other/unknown`, preserves inactive parent lineage, and never erases member deltas.
|
||||
- Existing v0 training fixtures are regression evidence and have no runtime write authority.
|
||||
- Multiplayer is a post-solo extension of the same campaign mailbox and WorldKernel, not a parallel room-state or party-prompt authority. The intention and unresolved governance policy live in `docs/architecture/ghostlight-dungeon-multiplayer-intention.md`.
|
||||
- SessionZeroKernel is the sole pre-world owner of persistent shared/private negotiation, typed contracts, character drafts, boundaries, decisions, invitations, and approvals. The WorldKernel receives only an unanimously approved brief at atomic publication.
|
||||
- Bounded co-op uses campaign_membership.v1 to bind one to eight authenticated members to exact actors in the existing campaign mailbox. Sequential public actions, actor-filtered surfaces, unanimous time/travel/cell-budget changes, and non-simulatable human actors are implemented; split parties, PvP, private play actions, delegation, late joining, and group lifecycle commands remain unsupported.
|
||||
- Contract Review reuses Session Zero against an exact world revision. Unanimous publication may amend forward-looking contract and approved actor ledger fields but cannot rewrite custody, location, topology, knowledge, memory, canon, or history. Boundary tightening becomes immediate anonymous aggregate policy; relaxation waits for publication.
|
||||
persistence_spine:
|
||||
- The hosted runtime uses Rust CultCache/redb `.cc` stores: one store per campaign plus service auth and CultMesh stores.
|
||||
- `state/ghostlight-state.cultcache.jsonl`, `state/branches.json`, and `state/evidence.jsonl` belong to the older research pipeline and have no hosted runtime authority.
|
||||
|
|
@ -270,6 +273,6 @@ data_flow:
|
|||
- If state grows faster than understanding, cut it back.
|
||||
|
||||
current_status:
|
||||
summary: Starfire serves immutable release b76bb5a8936624513fd0cd5e46d4d9ab11c3a517 with matching typed health, manifest, executable hash 41928dbe73bb3e4a75e3a468d8a2c7ce725254621d17faa8a565ea526b2a3296, DeepSeek readiness, four persisted campaigns, spoiler-safe player projection, loopback-only operator HTTP, resilient browser failure handling, explicit no-roll speech, bounded player/compiler inputs before inference or mutation, per-session replacement of superseded approval previews, durable-before-live auth transitions, collision-proof campaign exports, registry-owned lifecycle-name validation, full public approval previews, canonical destination origin binding, and rollback 12a704a. Local CultMesh and HTTP become ready independently of Odin; remote replication is a coalesced asynchronous batch requiring an acknowledged RUDP handshake. Yggdrasil's missing Odin listener is truthfully degraded, not allowed to own daemon liveness. The accepted runtime lineage passes generated opening/role/approval compilation, canonical nonliteral player identity, private assessment, confirmed d20, wait, restart continuity, fork, export, re-selection, and reset. The 24-subject cover passes budgets 1/4/8/32, including a corrected budget-8/provider-8 wave in 18.35 seconds. The strict budget-one rival-arena refugee golden migrates Mira across nested populations, preserves her exact delta and the player through sustained material background activity, and promotes the same person on return.
|
||||
next_action: With explicit approval to transmit one temporary invite credential to the local in-app browser, complete the visual authenticated journey and inspect the compiler, assessment, roll, wait, campaign lifecycle, and resolution controls; rotate two fresh invitations afterward. Then begin supervised human playtesting and treat confusion, composite consequences, latency, or low dramatic yield as evidence without weakening state admission.
|
||||
summary: The current checkout replaces direct campaign compilation with persistent DM-led Session Zero, private character and boundary channels, inline Vault-grounded opening/role decisions, unanimous digest approval, atomic campaign publication, actor-bound campaign membership, actor-filtered Eve/CultMesh surfaces, pooled entitlement budgets, unanimous time/travel/budget governance, and revision-bound Contract Review. Human actors cannot enter Persona or scheduler control; PvP, split movement, unilateral group time, stale actions, and group lifecycle operations are rejected at authoritative boundaries. Approved contract and anonymous aggregate safety policy now reach narration, assessment, demand projection, cell projection/interpretation, and verification. The previous Starfire release remains deployment truth until this checkout passes full tests, is committed, built immutably, and activated through Idunn.
|
||||
next_action: Finish the full workspace and web verification, commit and push the exact source, then use Idunn/gamecult-ops to deploy a two-player Starfire canary followed by an eight-account Session Zero/shared-scene smoke. Record exact build provenance and any rollout failure without weakening admission invariants.
|
||||
gestalt_population: Gestalt Personas own shared population baselines; persistent member deltas own named individuality; WorldKernel materialization and approval-gated fission preserve lineage and identity. Selected actionable member exceptions are mandatory Projector perspective owners, so aggregation cannot silently erase their decision. Presence projection is limited to nearby active leaves and exact-location dormant members, includes reciprocal player relationship evidence, and may propose an earned cast without committing it. Simulation cells are derived covers only.
|
||||
|
|
|
|||
153
web/dist/assets/index-BHkI62J0.js
vendored
Normal file
153
web/dist/assets/index-BHkI62J0.js
vendored
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
153
web/dist/assets/index-DcMdsMeE.js
vendored
153
web/dist/assets/index-DcMdsMeE.js
vendored
File diff suppressed because one or more lines are too long
70
web/dist/index.html
vendored
70
web/dist/index.html
vendored
|
|
@ -1,16 +1,58 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-DcMdsMeE.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-B7Qh0xAi.css">
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Ghostlight Dungeon</title>
|
||||
<script type="module" crossorigin src="/assets/index-BHkI62J0.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CYZ4YyRa.css">
|
||||
</head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status" role="status" aria-live="polite">Reading the world…</p></header><main>
|
||||
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
|
||||
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" maxlength="120" required><button type="submit">Retrieve and suggest</button></form>
|
||||
<form id="custom-form"><p class="form-heading">Or describe your own beginning</p><label for="campaign-name">Campaign name</label><input id="campaign-name" name="campaign_name" maxlength="80" required><label for="custom-who">Who are you?</label><input id="custom-who" name="who" maxlength="500" required><label for="custom-where">Where are you?</label><input id="custom-where" name="where_" maxlength="500" required><label for="custom-when">When?</label><input id="custom-when" name="when" maxlength="500" required><label for="custom-goal">What do you want?</label><textarea id="custom-goal" name="goal" maxlength="1000" required></textarea><button type="submit">Compile custom start</button></form>
|
||||
</div><div id="compiler-results"></div></section><section id="surface"></section>
|
||||
<form id="composer"><label for="attempt">What does your character do or say?</label><textarea id="attempt" name="attempt" maxlength="4000" required></textarea><label for="intended-effect">What outcome are they trying to cause? <span class="quiet">Required for an assessed attempt</span></label><input id="intended-effect" name="intended_effect" maxlength="1000"><p class="quiet">Use Speak when the words themselves are the action. Use Assess attempt when you want the words or action to persuade, deceive, intimidate, overcome resistance, or cause another uncertain effect.</p><div><button type="button" id="speak">Speak</button><button type="submit">Assess attempt</button><button type="button" id="wait">Wait one hour</button></div></form><section id="receipt" class="card" hidden aria-live="polite"></section>
|
||||
<form id="destination-form"><p class="form-heading">Compile a destination without moving there</p><label for="destination-origin">Current location id</label><input id="destination-origin" name="origin_location_id" readonly required><label for="destination-request">Where do you want the world to extend?</label><input id="destination-request" name="destination" maxlength="500" required><button type="submit">Retrieve destination</button></form>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
|
||||
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
|
||||
<form id="fission-form"><p class="form-heading">Approval-gated population fission</p><label for="fission-parent">Population</label><select name="parent_gestalt_id" id="fission-parent" required></select><label for="fission-axis">Partition axis</label><select id="fission-axis" name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><label for="fission-values">Named cuts, comma separated (up to 16)</label><input id="fission-values" name="requested_partition_values" maxlength="2575" required><label for="fission-reason">Why does this population need canonical leaves?</label><input id="fission-reason" name="reason" maxlength="500" required><button type="submit">Compile fission preview</button></form>
|
||||
<form id="fork-form"><label for="fork-name">Fork name</label><input id="fork-name" name="name" maxlength="80" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><label for="reset-name">Reset branch name</label><input id="reset-name" name="name" maxlength="80" required><button type="submit">Reset from selected branch seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details id="operator-lab" hidden><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
</main></body></html>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to Session Zero</a>
|
||||
<header>
|
||||
<p class="eyebrow">GHOSTLIGHT / LIVING WORLDS</p>
|
||||
<h1>Ghostlight Dungeon</h1>
|
||||
<p id="status" role="status" aria-live="polite">Reading the table…</p>
|
||||
</header>
|
||||
<main id="main">
|
||||
<section id="entry" class="card" hidden>
|
||||
<h2>Begin Session Zero</h2>
|
||||
<p>Build the campaign with your DM before anything becomes world truth.</p>
|
||||
<form id="session-entry-form">
|
||||
<label for="draft-name">Campaign draft</label><input id="draft-name" name="name" maxlength="80" required>
|
||||
<label for="display-name">Your table name</label><input id="display-name" name="display_name" maxlength="80" required>
|
||||
<label for="vault-provider">Lore Vault</label><select id="vault-provider" name="vault_provider"><option value="aetheria">Aetheria</option></select>
|
||||
<fieldset><legend>Table</legend><label><input type="radio" name="mode" value="solo" checked> Solo</label><label><input type="radio" name="mode" value="group"> Group, up to eight</label></fieldset>
|
||||
<button type="submit">Begin Session Zero</button>
|
||||
</form>
|
||||
<form id="join-form"><h3>Join a Session Zero</h3><label for="join-token">Invitation token</label><input id="join-token" required><label for="join-name">Your table name</label><input id="join-name" maxlength="80" required><button type="submit">Join table</button></form>
|
||||
</section>
|
||||
|
||||
<section id="session-zero" hidden>
|
||||
<div class="session-heading"><div><p class="eyebrow">SESSION ZERO</p><h2 id="session-title">Campaign draft</h2></div><p id="session-state" class="state-pill"></p></div>
|
||||
<nav class="channel-tabs" aria-label="Session Zero channels"><button type="button" id="tab-shared" aria-pressed="true">Shared table</button><button type="button" id="tab-private" aria-pressed="false">Private DM</button></nav>
|
||||
<div class="session-grid">
|
||||
<div>
|
||||
<section class="card" aria-labelledby="conversation-title"><h3 id="conversation-title">Conversation</h3><ol id="session-transcript" class="transcript" aria-live="polite"></ol><form id="session-message-form"><label for="session-message">Talk with the DM</label><textarea id="session-message" maxlength="4000" required></textarea><button type="submit">Send</button></form></section>
|
||||
<section class="card"><h3>Unresolved decisions</h3><div id="decision-list"></div></section>
|
||||
<section class="card" id="review-card" hidden><h3>Compilation review</h3><div id="review-content"></div></section>
|
||||
</div>
|
||||
<aside>
|
||||
<section class="card"><h3>Roster and readiness</h3><div id="roster"></div><p id="cell-pool" class="quiet"></p><form id="invite-form"><label for="invite-count">Create invitations</label><input id="invite-count" type="number" min="1" max="7" value="1"><button type="submit">Create links</button></form><div id="invite-output" aria-live="polite"></div></section>
|
||||
<section class="card"><h3>Campaign contract</h3><dl id="contract-ledger"></dl></section>
|
||||
<section class="card"><h3>Your private character</h3><dl id="character-ledger"></dl></section>
|
||||
<section class="card"><h3>Content boundaries</h3><p class="quiet">Only you can see attribution. The table receives the strictest combined rule.</p><form id="boundary-form"><label for="boundary-topic">Topic</label><input id="boundary-topic" maxlength="300" required><label for="boundary-level">Treatment</label><select id="boundary-level"><option value="line">Line — exclude</option><option value="veil">Veil — off-screen</option><option value="ask_first">Ask first</option></select><button type="submit">Set private boundary</button></form><ul id="boundary-list"></ul></section>
|
||||
<section class="card session-actions"><h3>Readiness</h3><button type="button" id="lock-roster">Lock roster</button><button type="button" id="compile-session">Compile review</button><button type="button" id="approve-session">Approve shared contract and my character</button><button type="button" id="publish-session">Publish campaign</button></section>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="surface"></section>
|
||||
<section id="play-controls" hidden>
|
||||
<form id="composer" class="card"><label for="attempt">What does your character do or say?</label><textarea id="attempt" maxlength="4000" required></textarea><label for="intended-effect">Intended uncertain effect</label><input id="intended-effect" maxlength="1000"><p class="quiet">Speak commits the words. Assess previews resistance and stakes before any roll.</p><div class="button-row"><button type="button" id="speak">Speak</button><button type="submit">Assess attempt</button></div></form>
|
||||
<section id="receipt" class="card" hidden aria-live="polite"></section>
|
||||
<section class="card governance"><h2>Shared table decisions</h2><button type="button" id="contract-review">Begin Contract Review</button><form id="travel-form"><label for="travel-destination">Travel together</label><select id="travel-destination"></select><button type="submit">Propose travel</button></form><form id="time-form"><label for="time-minutes">Advance time together</label><input id="time-minutes" type="number" min="1" max="1440" value="60"><button type="submit">Propose time</button></form><form id="resolution-form"><label for="active-cell-budget">Active Persona cells: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" type="range" min="1" max="128" value="8"><button type="submit">Propose budget</button></form></section>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,57 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title></head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status" role="status" aria-live="polite">Reading the world…</p></header><main>
|
||||
<section id="compiler" hidden><h2>Compile a world</h2><div class="compiler-grid">
|
||||
<form id="suggest-form"><label for="setting">Generate three grounded openings</label><input id="setting" value="Aetheria" maxlength="120" required><button type="submit">Retrieve and suggest</button></form>
|
||||
<form id="custom-form"><p class="form-heading">Or describe your own beginning</p><label for="campaign-name">Campaign name</label><input id="campaign-name" name="campaign_name" maxlength="80" required><label for="custom-who">Who are you?</label><input id="custom-who" name="who" maxlength="500" required><label for="custom-where">Where are you?</label><input id="custom-where" name="where_" maxlength="500" required><label for="custom-when">When?</label><input id="custom-when" name="when" maxlength="500" required><label for="custom-goal">What do you want?</label><textarea id="custom-goal" name="goal" maxlength="1000" required></textarea><button type="submit">Compile custom start</button></form>
|
||||
</div><div id="compiler-results"></div></section><section id="surface"></section>
|
||||
<form id="composer"><label for="attempt">What does your character do or say?</label><textarea id="attempt" name="attempt" maxlength="4000" required></textarea><label for="intended-effect">What outcome are they trying to cause? <span class="quiet">Required for an assessed attempt</span></label><input id="intended-effect" name="intended_effect" maxlength="1000"><p class="quiet">Use Speak when the words themselves are the action. Use Assess attempt when you want the words or action to persuade, deceive, intimidate, overcome resistance, or cause another uncertain effect.</p><div><button type="button" id="speak">Speak</button><button type="submit">Assess attempt</button><button type="button" id="wait">Wait one hour</button></div></form><section id="receipt" class="card" hidden aria-live="polite"></section>
|
||||
<form id="destination-form"><p class="form-heading">Compile a destination without moving there</p><label for="destination-origin">Current location id</label><input id="destination-origin" name="origin_location_id" readonly required><label for="destination-request">Where do you want the world to extend?</label><input id="destination-request" name="destination" maxlength="500" required><button type="submit">Retrieve destination</button></form>
|
||||
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div>
|
||||
<form id="resolution-form"><label for="active-cell-budget">Active Persona-cell budget: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" name="active_cell_budget" type="range" min="1" max="32" value="8"><p id="resolution-status"></p><button type="submit">Apply at safe boundary</button></form>
|
||||
<form id="fission-form"><p class="form-heading">Approval-gated population fission</p><label for="fission-parent">Population</label><select name="parent_gestalt_id" id="fission-parent" required></select><label for="fission-axis">Partition axis</label><select id="fission-axis" name="partition_axis"><option value="geography">Geography</option><option value="ideology">Ideology</option><option value="authority">Authority</option><option value="economy_role">Economic role</option><option value="species_body">Species/body</option><option value="information">Information</option></select><label for="fission-values">Named cuts, comma separated (up to 16)</label><input id="fission-values" name="requested_partition_values" maxlength="2575" required><label for="fission-reason">Why does this population need canonical leaves?</label><input id="fission-reason" name="reason" maxlength="500" required><button type="submit">Compile fission preview</button></form>
|
||||
<form id="fork-form"><label for="fork-name">Fork name</label><input id="fork-name" name="name" maxlength="80" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><label for="reset-name">Reset branch name</label><input id="reset-name" name="name" maxlength="80" required><button type="submit">Reset from selected branch seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details id="operator-lab" hidden><summary>Operator inspector</summary><form id="provider-parallelism-form"><label for="provider-parallelism">Provider request parallelism: <output id="provider-parallelism-value">8</output></label><input id="provider-parallelism" type="range" min="1" max="32" value="8"><button type="submit">Apply operator limit</button></form><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
|
||||
</main><script type="module" src="/src/main.ts"></script></body></html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Ghostlight Dungeon</title>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to Session Zero</a>
|
||||
<header>
|
||||
<p class="eyebrow">GHOSTLIGHT / LIVING WORLDS</p>
|
||||
<h1>Ghostlight Dungeon</h1>
|
||||
<p id="status" role="status" aria-live="polite">Reading the table…</p>
|
||||
</header>
|
||||
<main id="main">
|
||||
<section id="entry" class="card" hidden>
|
||||
<h2>Begin Session Zero</h2>
|
||||
<p>Build the campaign with your DM before anything becomes world truth.</p>
|
||||
<form id="session-entry-form">
|
||||
<label for="draft-name">Campaign draft</label><input id="draft-name" name="name" maxlength="80" required>
|
||||
<label for="display-name">Your table name</label><input id="display-name" name="display_name" maxlength="80" required>
|
||||
<label for="vault-provider">Lore Vault</label><select id="vault-provider" name="vault_provider"><option value="aetheria">Aetheria</option></select>
|
||||
<fieldset><legend>Table</legend><label><input type="radio" name="mode" value="solo" checked> Solo</label><label><input type="radio" name="mode" value="group"> Group, up to eight</label></fieldset>
|
||||
<button type="submit">Begin Session Zero</button>
|
||||
</form>
|
||||
<form id="join-form"><h3>Join a Session Zero</h3><label for="join-token">Invitation token</label><input id="join-token" required><label for="join-name">Your table name</label><input id="join-name" maxlength="80" required><button type="submit">Join table</button></form>
|
||||
</section>
|
||||
|
||||
<section id="session-zero" hidden>
|
||||
<div class="session-heading"><div><p class="eyebrow">SESSION ZERO</p><h2 id="session-title">Campaign draft</h2></div><p id="session-state" class="state-pill"></p></div>
|
||||
<nav class="channel-tabs" aria-label="Session Zero channels"><button type="button" id="tab-shared" aria-pressed="true">Shared table</button><button type="button" id="tab-private" aria-pressed="false">Private DM</button></nav>
|
||||
<div class="session-grid">
|
||||
<div>
|
||||
<section class="card" aria-labelledby="conversation-title"><h3 id="conversation-title">Conversation</h3><ol id="session-transcript" class="transcript" aria-live="polite"></ol><form id="session-message-form"><label for="session-message">Talk with the DM</label><textarea id="session-message" maxlength="4000" required></textarea><button type="submit">Send</button></form></section>
|
||||
<section class="card"><h3>Unresolved decisions</h3><div id="decision-list"></div></section>
|
||||
<section class="card" id="review-card" hidden><h3>Compilation review</h3><div id="review-content"></div></section>
|
||||
</div>
|
||||
<aside>
|
||||
<section class="card"><h3>Roster and readiness</h3><div id="roster"></div><p id="cell-pool" class="quiet"></p><form id="invite-form"><label for="invite-count">Create invitations</label><input id="invite-count" type="number" min="1" max="7" value="1"><button type="submit">Create links</button></form><div id="invite-output" aria-live="polite"></div></section>
|
||||
<section class="card"><h3>Campaign contract</h3><dl id="contract-ledger"></dl></section>
|
||||
<section class="card"><h3>Your private character</h3><dl id="character-ledger"></dl></section>
|
||||
<section class="card"><h3>Content boundaries</h3><p class="quiet">Only you can see attribution. The table receives the strictest combined rule.</p><form id="boundary-form"><label for="boundary-topic">Topic</label><input id="boundary-topic" maxlength="300" required><label for="boundary-level">Treatment</label><select id="boundary-level"><option value="line">Line — exclude</option><option value="veil">Veil — off-screen</option><option value="ask_first">Ask first</option></select><button type="submit">Set private boundary</button></form><ul id="boundary-list"></ul></section>
|
||||
<section class="card session-actions"><h3>Readiness</h3><button type="button" id="lock-roster">Lock roster</button><button type="button" id="compile-session">Compile review</button><button type="button" id="approve-session">Approve shared contract and my character</button><button type="button" id="publish-session">Publish campaign</button></section>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="surface"></section>
|
||||
<section id="play-controls" hidden>
|
||||
<form id="composer" class="card"><label for="attempt">What does your character do or say?</label><textarea id="attempt" maxlength="4000" required></textarea><label for="intended-effect">Intended uncertain effect</label><input id="intended-effect" maxlength="1000"><p class="quiet">Speak commits the words. Assess previews resistance and stakes before any roll.</p><div class="button-row"><button type="button" id="speak">Speak</button><button type="submit">Assess attempt</button></div></form>
|
||||
<section id="receipt" class="card" hidden aria-live="polite"></section>
|
||||
<section class="card governance"><h2>Shared table decisions</h2><button type="button" id="contract-review">Begin Contract Review</button><form id="travel-form"><label for="travel-destination">Travel together</label><select id="travel-destination"></select><button type="submit">Propose travel</button></form><form id="time-form"><label for="time-minutes">Advance time together</label><input id="time-minutes" type="number" min="1" max="1440" value="60"><button type="submit">Propose time</button></form><form id="resolution-form"><label for="active-cell-budget">Active Persona cells: <output id="active-cell-budget-value">8</output></label><input id="active-cell-budget" type="range" min="1" max="128" value="8"><button type="submit">Propose budget</button></form></section>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
652
web/src/main.ts
652
web/src/main.ts
|
|
@ -2,500 +2,256 @@ import { renderEveSurface } from "@gamecult/eve-browser-lowering";
|
|||
import "@gamecult/eve-browser-lowering/styles.css";
|
||||
import "./style.css";
|
||||
|
||||
const host = document.querySelector<HTMLElement>("#surface")!;
|
||||
const status = document.querySelector<HTMLElement>("#status")!;
|
||||
const receipt = document.querySelector<HTMLElement>("#receipt")!;
|
||||
const compiler = document.querySelector<HTMLElement>("#compiler")!;
|
||||
const composer = document.querySelector<HTMLFormElement>("#composer")!;
|
||||
const destinationForm = document.querySelector<HTMLFormElement>("#destination-form")!;
|
||||
const compilerResults = document.querySelector<HTMLElement>("#compiler-results")!;
|
||||
const campaignLab = document.querySelector<HTMLElement>("#campaign-lab")!;
|
||||
const campaignList = document.querySelector<HTMLElement>("#campaign-list")!;
|
||||
const operatorLab = document.querySelector<HTMLDetailsElement>("#operator-lab")!;
|
||||
operatorLab.hidden = !["127.0.0.1", "localhost", "::1"].includes(window.location.hostname);
|
||||
const $ = <T extends Element>(selector: string) => document.querySelector<T>(selector)!;
|
||||
const status = $("#status") as HTMLElement;
|
||||
const entry = $("#entry") as HTMLElement;
|
||||
const sessionRoot = $("#session-zero") as HTMLElement;
|
||||
const surfaceHost = $("#surface") as HTMLElement;
|
||||
const playControls = $("#play-controls") as HTMLElement;
|
||||
const receipt = $("#receipt") as HTMLElement;
|
||||
let revision = 0;
|
||||
let playerActorId = "";
|
||||
let resolutionEpoch = 0;
|
||||
let providerConfigurationEpoch = 0;
|
||||
let requestInFlight = false;
|
||||
const controlsDisabledByRequest = new Set<HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>();
|
||||
let viewerActorId = "";
|
||||
let sessionId = "";
|
||||
let viewerMemberId = "";
|
||||
let activeChannel = "shared:table";
|
||||
let currentSurface: any = null;
|
||||
let requestActive = false;
|
||||
|
||||
class ServerResponseFailure extends Error {}
|
||||
class ServerFailure extends Error {}
|
||||
|
||||
async function withInteractionLock<T>(work: () => Promise<T>): Promise<T> {
|
||||
if (requestInFlight) throw new Error("A Ghostlight request is already in progress.");
|
||||
requestInFlight = true;
|
||||
document.body.setAttribute("aria-busy", "true");
|
||||
for (const control of document.querySelectorAll<HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>("button, input, textarea, select")) {
|
||||
if (!control.disabled) {
|
||||
control.disabled = true;
|
||||
controlsDisabledByRequest.add(control);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
for (const control of controlsDisabledByRequest) control.disabled = false;
|
||||
controlsDisabledByRequest.clear();
|
||||
document.body.removeAttribute("aria-busy");
|
||||
requestInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
function node<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
text?: string,
|
||||
className?: string,
|
||||
): HTMLElementTagNameMap[K] {
|
||||
function el<K extends keyof HTMLElementTagNameMap>(tag: K, text?: string, className?: string) {
|
||||
const value = document.createElement(tag);
|
||||
if (text !== undefined) value.textContent = text;
|
||||
if (className) value.className = className;
|
||||
return value;
|
||||
}
|
||||
|
||||
function showSummary(title: string, lines: string[]) {
|
||||
const children: HTMLElement[] = [node("h3", title)];
|
||||
for (const line of lines.filter(Boolean)) children.push(node("p", line));
|
||||
receipt.replaceChildren(...children);
|
||||
receipt.hidden = false;
|
||||
}
|
||||
|
||||
async function decodeResponse(response: Response): Promise<any> {
|
||||
async function decode(response: Response) {
|
||||
if (response.status === 204) return null;
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (contentType.includes("json")) return response.json();
|
||||
return response.text();
|
||||
return (response.headers.get("content-type") ?? "").includes("json") ? response.json() : response.text();
|
||||
}
|
||||
|
||||
function responseError(value: any, fallback: string): string {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
if (value && typeof value.error === "string" && value.error.trim()) return value.error.trim();
|
||||
return fallback;
|
||||
function errorText(body: any, fallback: string) {
|
||||
if (typeof body === "string" && body.trim()) return body.trim();
|
||||
return typeof body?.error === "string" ? body.error : fallback;
|
||||
}
|
||||
|
||||
function reportClientFailure(reason: unknown) {
|
||||
const message = reason instanceof Error && reason.message.trim()
|
||||
? reason.message.trim()
|
||||
: "The Ghostlight connection failed before a response arrived.";
|
||||
async function post(path: string, body: unknown) {
|
||||
if (requestActive) throw new Error("Another table command is still being admitted.");
|
||||
requestActive = true;
|
||||
document.body.setAttribute("aria-busy", "true");
|
||||
try {
|
||||
const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
const value = await decode(response);
|
||||
if (!response.ok) throw new ServerFailure(errorText(value, "The server refused the command."));
|
||||
return value;
|
||||
} finally {
|
||||
requestActive = false;
|
||||
document.body.removeAttribute("aria-busy");
|
||||
}
|
||||
}
|
||||
|
||||
function showError(reason: unknown) {
|
||||
const message = reason instanceof Error ? reason.message : "The connection failed.";
|
||||
status.textContent = message;
|
||||
if (reason instanceof ServerResponseFailure) {
|
||||
showSummary("Request refused", [message, "The server returned an error response. Refresh campaign state before retrying."]);
|
||||
return;
|
||||
}
|
||||
showSummary("Request did not complete", [message, "The server remains authoritative. Refresh the campaign before retrying; the lost response may have followed a commit."]);
|
||||
receipt.hidden = false;
|
||||
receipt.replaceChildren(el("h2", reason instanceof ServerFailure ? "Request refused" : "Request interrupted"), el("p", message), el("p", "The server remains authoritative. Refresh before retrying.", "quiet"));
|
||||
}
|
||||
|
||||
window.addEventListener("unhandledrejection", event => {
|
||||
event.preventDefault();
|
||||
reportClientFailure(event.reason);
|
||||
});
|
||||
|
||||
function renderCommandReceipt(body: any) {
|
||||
if (body?.kind === "assessed") {
|
||||
const assessment = body.assessment;
|
||||
const children: HTMLElement[] = [node("h3", assessment.admissible ? "Action assessment" : "That attempt is not possible")];
|
||||
if (assessment.admissible) {
|
||||
children.push(node("p", `DC ${assessment.dc} · modifier ${assessment.modifier_total >= 0 ? "+" : ""}${assessment.modifier_total}`));
|
||||
const modifiers = node("ul");
|
||||
for (const modifier of assessment.modifiers ?? []) {
|
||||
modifiers.append(node("li", `${modifier.label}: ${modifier.value >= 0 ? "+" : ""}${modifier.value}`));
|
||||
}
|
||||
children.push(modifiers);
|
||||
children.push(node("p", `Strong/success: ${assessment.success_stake}`));
|
||||
children.push(node("p", `Mixed: ${assessment.mixed_stake}`));
|
||||
children.push(node("p", `Failure: ${assessment.failure_stake}`));
|
||||
children.push(node("p", `Effect ceiling: ${assessment.effect_ceiling}`, "quiet"));
|
||||
} else {
|
||||
children.push(node("p", assessment.missing_permission ?? "The attempt has no admissible path from current state."));
|
||||
for (const bargain of assessment.bargains ?? []) children.push(node("p", `Possible bargain: ${bargain}`));
|
||||
}
|
||||
receipt.replaceChildren(...children);
|
||||
receipt.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (body?.kind === "committed") {
|
||||
const roll = body.receipt?.roll;
|
||||
if (roll) {
|
||||
const outcome = String(roll.outcome).replaceAll("_", " ");
|
||||
showSummary(outcome.charAt(0).toUpperCase() + outcome.slice(1), [
|
||||
`d20 ${roll.d20} ${roll.modifier_total >= 0 ? "+" : "−"} ${Math.abs(roll.modifier_total)} = ${roll.total} against DC ${roll.dc}`,
|
||||
]);
|
||||
} else {
|
||||
showSummary("World advanced", [`Revision ${body.revision}`]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (body?.kind === "resolution_updated") {
|
||||
showSummary("World resolution updated", [`Resolution epoch ${body.receipt?.resolution_epoch ?? "advanced"}`]);
|
||||
return;
|
||||
}
|
||||
showSummary("Command result", [body?.error ?? "The world returned no player-facing detail."]);
|
||||
}
|
||||
window.addEventListener("unhandledrejection", event => { event.preventDefault(); showError(event.reason); });
|
||||
|
||||
function showAuthenticationGate() {
|
||||
const message = "Sign in through Heimdall to enter the KLTST playtest.";
|
||||
status.textContent = message;
|
||||
compiler.hidden = true;
|
||||
composer.hidden = true;
|
||||
destinationForm.hidden = true;
|
||||
campaignLab.hidden = true;
|
||||
receipt.hidden = true;
|
||||
host.hidden = false;
|
||||
const gate = node("article", undefined, "card");
|
||||
gate.append(
|
||||
node("h2", "Ghostlight Dungeon playtest"),
|
||||
node("p", message),
|
||||
node("p", "Access requires membership in the KLTST Discord role. Heimdall checks that role, then Ghostlight keeps your campaigns isolated from every other account.", "quiet"),
|
||||
);
|
||||
const login = node("button", "Continue with Discord") as HTMLButtonElement;
|
||||
login.type = "button";
|
||||
login.addEventListener("click", () => { void startHeimdallLogin().catch(reportClientFailure); });
|
||||
gate.append(login);
|
||||
host.replaceChildren(gate);
|
||||
entry.hidden = true; sessionRoot.hidden = true; playControls.hidden = true; surfaceHost.hidden = false;
|
||||
const card = el("article", undefined, "card");
|
||||
card.append(el("h2", "Ghostlight Dungeon playtest"), el("p", "Sign in through Heimdall with an eligible Discord account."));
|
||||
const button = el("button", "Continue with Discord");
|
||||
button.addEventListener("click", () => void startLogin().catch(showError));
|
||||
card.append(button);
|
||||
surfaceHost.replaceChildren(card);
|
||||
}
|
||||
|
||||
async function startHeimdallLogin() {
|
||||
async function startLogin() {
|
||||
const response = await fetch("/api/auth/heimdall/start", { method: "POST" });
|
||||
const body = await decodeResponse(response);
|
||||
if (!response.ok || typeof body?.authorization_url !== "string" || typeof body?.attempt_id !== "string") {
|
||||
throw new ServerResponseFailure(responseError(body, "Heimdall could not start Discord sign-in."));
|
||||
}
|
||||
const body = await decode(response);
|
||||
if (!response.ok) throw new ServerFailure(errorText(body, "Heimdall could not begin sign-in."));
|
||||
sessionStorage.setItem("ghostlight_heimdall_attempt", body.attempt_id);
|
||||
window.location.assign(body.authorization_url);
|
||||
}
|
||||
|
||||
async function pollHeimdallAttempt(attemptId: string) {
|
||||
const deadline = Date.now() + 10 * 60_000;
|
||||
async function resumeLogin() {
|
||||
const attempt = sessionStorage.getItem("ghostlight_heimdall_attempt");
|
||||
if (!attempt) return;
|
||||
const deadline = Date.now() + 600_000;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise(resolve => window.setTimeout(resolve, 900));
|
||||
const response = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attemptId)}`, { cache: "no-store" });
|
||||
const body = await decodeResponse(response);
|
||||
if (!response.ok) throw new ServerResponseFailure(responseError(body, "Heimdall sign-in expired."));
|
||||
if (body?.status === "pending") continue;
|
||||
if (body?.status !== "succeeded") {
|
||||
sessionStorage.removeItem("ghostlight_heimdall_attempt");
|
||||
throw new Error(String(body?.error ?? "Your Discord account does not have Ghostlight playtest access."));
|
||||
}
|
||||
const adopted = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attemptId)}/adopt`, { method: "POST" });
|
||||
const adoptedBody = await decodeResponse(adopted);
|
||||
if (!adopted.ok) throw new ServerResponseFailure(responseError(adoptedBody, "Ghostlight could not adopt the Heimdall session."));
|
||||
const response = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attempt)}`, { cache: "no-store" });
|
||||
const body = await decode(response);
|
||||
if (!response.ok) throw new ServerFailure(errorText(body, "Heimdall sign-in expired."));
|
||||
if (body.status === "pending") continue;
|
||||
if (body.status !== "succeeded") throw new ServerFailure(body.error ?? "Discord access was not admitted.");
|
||||
const adopted = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attempt)}/adopt`, { method: "POST" });
|
||||
if (!adopted.ok) throw new ServerFailure(errorText(await decode(adopted), "Heimdall session adoption failed."));
|
||||
sessionStorage.removeItem("ghostlight_heimdall_attempt");
|
||||
await refresh();
|
||||
return;
|
||||
}
|
||||
sessionStorage.removeItem("ghostlight_heimdall_attempt");
|
||||
throw new Error("Heimdall sign-in timed out. Try again when you are ready.");
|
||||
}
|
||||
|
||||
async function resumeHeimdallLogin() {
|
||||
const attemptId = sessionStorage.getItem("ghostlight_heimdall_attempt");
|
||||
if (attemptId) await pollHeimdallAttempt(attemptId);
|
||||
throw new Error("Heimdall sign-in timed out.");
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const response = await fetch("/api/surface");
|
||||
if (response.status === 401) { showAuthenticationGate(); return; }
|
||||
const surface = await decodeResponse(response);
|
||||
if (!response.ok) {
|
||||
status.textContent = responseError(surface, "The campaign surface is temporarily unavailable.");
|
||||
return;
|
||||
const response = await fetch("/api/surface", { cache: "no-store" });
|
||||
if (response.status === 401) return showAuthenticationGate();
|
||||
const surface = await decode(response);
|
||||
if (!response.ok) throw new ServerFailure(errorText(surface, "The table surface is unavailable."));
|
||||
currentSurface = surface;
|
||||
if (surface.surface_id === "ghostlight.session-zero-entry") return renderEntry();
|
||||
if (surface.session_zero) return renderSession(surface.session_zero);
|
||||
renderCampaign(surface);
|
||||
}
|
||||
|
||||
function renderEntry() {
|
||||
status.textContent = "No campaign is selected. Begin or join a Session Zero.";
|
||||
entry.hidden = false; sessionRoot.hidden = true; surfaceHost.hidden = true; playControls.hidden = true;
|
||||
const invite = new URLSearchParams(location.search).get("invite");
|
||||
if (invite) ($("#join-token") as HTMLInputElement).value = invite;
|
||||
}
|
||||
|
||||
function pairs(target: HTMLElement, fields: Record<string, unknown>) {
|
||||
target.replaceChildren();
|
||||
for (const [label, raw] of Object.entries(fields)) {
|
||||
const value = Array.isArray(raw) ? raw.join(" · ") : String(raw || "Not decided yet");
|
||||
target.append(el("dt", label.replaceAll("_", " ")), el("dd", value));
|
||||
}
|
||||
const needsCompilation = surface.surface_id === "ghostlight.compiler";
|
||||
compiler.hidden = !needsCompilation; composer.hidden = needsCompilation; destinationForm.hidden = needsCompilation; host.hidden = needsCompilation; campaignLab.hidden = needsCompilation;
|
||||
if (needsCompilation) { status.textContent = "No campaign exists. Retrieve the Vault and approve a world seed."; return; }
|
||||
revision = Number(surface.world_revision ?? surface.version ?? 0);
|
||||
playerActorId = String(surface.player_actor_id ?? "");
|
||||
if (!playerActorId) throw new Error("Campaign surface omitted its canonical player actor ID.");
|
||||
const playerLocationId = String(surface.player_location_id ?? "");
|
||||
if (!playerLocationId) throw new Error("Campaign surface omitted its canonical player location ID.");
|
||||
document.querySelector<HTMLInputElement>("#destination-origin")!.value = playerLocationId;
|
||||
resolutionEpoch = Number(surface.resolution?.policy?.resolution_epoch ?? 0);
|
||||
providerConfigurationEpoch = Number(surface.resolution?.policy?.provider_configuration_epoch ?? 0);
|
||||
}
|
||||
|
||||
function renderSession(session: any) {
|
||||
entry.hidden = true; sessionRoot.hidden = false; surfaceHost.hidden = true; playControls.hidden = true;
|
||||
sessionId = session.id; revision = Number(session.revision); viewerMemberId = session.viewer_member_id;
|
||||
if (!session.channels.some((channel: any) => channel.id === activeChannel)) activeChannel = "shared:table";
|
||||
$("#session-title").textContent = currentSurface.title;
|
||||
$("#session-state").textContent = `${String(session.status).replaceAll("_", " ")} · revision ${revision}`;
|
||||
status.textContent = session.status === "compiling" ? "The DM is compiling the agreed brief. You can leave this page." : "Session Zero is persistent. Conversation is not world truth until unanimous publication.";
|
||||
const shared = activeChannel === "shared:table";
|
||||
$("#tab-shared").setAttribute("aria-pressed", String(shared));
|
||||
$("#tab-private").setAttribute("aria-pressed", String(!shared));
|
||||
const channel = session.channels.find((item: any) => item.id === activeChannel) ?? session.channels[0];
|
||||
const transcript = $("#session-transcript"); transcript.replaceChildren();
|
||||
for (const message of channel?.messages ?? []) {
|
||||
const item = el("li", undefined, `message ${message.speaker}`);
|
||||
item.append(el("strong", message.speaker === "dm" ? "DM" : message.speaker === "system" ? "Table" : "Player"), el("p", message.text));
|
||||
transcript.append(item);
|
||||
}
|
||||
const roster = $("#roster"); roster.replaceChildren();
|
||||
for (const member of session.public_party) {
|
||||
const row = el("p", `${member.approved ? "Ready" : "Not ready"} · ${member.display_name} as ${member.name || "undecided"}${member.is_host ? " · host" : ""}`);
|
||||
if (session.viewer_is_host && !session.roster_locked && !member.is_host) {
|
||||
const remove = el("button", "Remove");
|
||||
remove.addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/remove-member`, { expected_revision: revision, member_id: member.member_id }); await refresh(); });
|
||||
row.append(" ", remove);
|
||||
}
|
||||
roster.append(row);
|
||||
}
|
||||
$("#cell-pool").textContent = `${session.pooled_cell_allowance} pooled active Persona cells · ${session.active_members}/8 players`;
|
||||
pairs($("#contract-ledger"), session.contract);
|
||||
pairs($("#character-ledger"), session.private_character);
|
||||
const boundaryList = $("#boundary-list"); boundaryList.replaceChildren(...session.private_boundaries.map((boundary: any) => {
|
||||
const item = el("li", `${boundary.level.replaceAll("_", " ")} · ${boundary.topic} `);
|
||||
const remove = el("button", "Remove"); remove.addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/boundary/${encodeURIComponent(boundary.id)}/remove`, { expected_revision: revision }); await refresh(); }); item.append(remove); return item;
|
||||
}));
|
||||
const decisions = $("#decision-list"); decisions.replaceChildren();
|
||||
for (const decision of session.decisions.filter((item: any) => !item.resolved)) {
|
||||
const card = el("article", undefined, "decision");
|
||||
card.append(el("h4", decision.prompt), el("p", decision.proposed_resolution));
|
||||
const accept = el("button", "Accept"); accept.addEventListener("click", () => void decide(decision.id, true));
|
||||
const counter = el("button", "Counter"); counter.addEventListener("click", async () => { const text = window.prompt("What should the DM propose instead?", decision.proposed_resolution); if (!text?.trim()) return; await post(`/api/session-zero/${sessionId}/decision`, { expected_revision: revision, decision_id: decision.id, accept: false, counter: text.trim() }); await refresh(); });
|
||||
const discuss = el("button", "Discuss"); discuss.addEventListener("click", () => { ($("#session-message") as HTMLTextAreaElement).value = `I'd like to discuss: ${decision.prompt}`; ($("#session-message") as HTMLTextAreaElement).focus(); });
|
||||
card.append(accept, counter, discuss); decisions.append(card);
|
||||
}
|
||||
const review = $("#review-card") as HTMLElement; review.hidden = !session.preview;
|
||||
if (session.preview) {
|
||||
const content = $("#review-content"); content.replaceChildren(el("p", session.preview.title));
|
||||
if (session.preview.branch_assumptions?.length) content.append(el("p", `Branch-local assumptions: ${session.preview.branch_assumptions.join("; ")}`));
|
||||
content.append(el("p", `${Object.keys(session.preview.topology ?? {}).length} locations · ${Object.keys(session.preview.institutions ?? {}).length} institutions · ${Object.keys(session.preview.clocks ?? {}).length} clocks`));
|
||||
}
|
||||
const host = Boolean(session.viewer_is_host);
|
||||
($("#invite-form") as HTMLFormElement).hidden = !host || session.roster_locked;
|
||||
($("#lock-roster") as HTMLButtonElement).disabled = !host || session.roster_locked;
|
||||
($("#compile-session") as HTMLButtonElement).disabled = !host || !session.roster_locked || ["compiling", "review", "published"].includes(session.status);
|
||||
($("#approve-session") as HTMLButtonElement).disabled = session.status !== "review" || session.approved;
|
||||
($("#publish-session") as HTMLButtonElement).disabled = !host || !session.publish_ready;
|
||||
}
|
||||
|
||||
function renderCampaign(surface: any) {
|
||||
entry.hidden = true; sessionRoot.hidden = true; surfaceHost.hidden = false; playControls.hidden = false;
|
||||
revision = Number(surface.world_revision); resolutionEpoch = Number(surface.resolution?.policy?.resolution_epoch ?? 0); viewerActorId = surface.viewer_actor_id;
|
||||
if (!viewerActorId) throw new Error("Actor-filtered campaign surface omitted the viewer actor binding.");
|
||||
renderEveSurface(surface, surfaceHost, { body: document.body, clientId: "ghostlight.browser", statusElement: status });
|
||||
status.textContent = `World revision ${revision}. Your surface contains only ${viewerActorId}'s permitted state.`;
|
||||
const budget = Number(surface.resolution?.policy?.active_cell_budget ?? 8);
|
||||
const budgetInput = document.querySelector<HTMLInputElement>("#active-cell-budget")!;
|
||||
budgetInput.value = String(budget);
|
||||
document.querySelector<HTMLOutputElement>("#active-cell-budget-value")!.value = String(budget);
|
||||
document.querySelector<HTMLElement>("#resolution-status")!.textContent = `${surface.resolution?.effective_budget ?? budget} effective cells · ${surface.resolution?.mandatory_overage ?? 0} temporary overage · epoch ${resolutionEpoch}`;
|
||||
const providerParallelism = Number(surface.resolution?.policy?.provider_parallelism ?? 8);
|
||||
document.querySelector<HTMLInputElement>("#provider-parallelism")!.value = String(providerParallelism);
|
||||
document.querySelector<HTMLOutputElement>("#provider-parallelism-value")!.value = String(providerParallelism);
|
||||
const fissionParent = document.querySelector<HTMLSelectElement>("#fission-parent")!;
|
||||
fissionParent.replaceChildren(...(surface.resolution?.fission_targets ?? []).map((target: any) => {
|
||||
const option = node("option", `${target.name} · ${target.id}`);
|
||||
option.value = target.id;
|
||||
return option;
|
||||
}));
|
||||
document.querySelector<HTMLFormElement>("#fission-form")!.hidden = fissionParent.options.length === 0;
|
||||
renderEveSurface(surface, host, { body: document.body, clientId: "ghostlight.browser", statusElement: status });
|
||||
const campaignsResponse = await fetch("/api/campaigns");
|
||||
const campaigns = await decodeResponse(campaignsResponse);
|
||||
if (!campaignsResponse.ok) {
|
||||
status.textContent = responseError(campaigns, "The campaign list is temporarily unavailable.");
|
||||
return;
|
||||
}
|
||||
campaignList.replaceChildren(...campaigns.campaigns.map((item: any) => {
|
||||
const button = node("button", `${item.selected ? "●" : "○"} ${item.name} · revision ${item.revision}`);
|
||||
button.type = "button";
|
||||
button.disabled = Boolean(item.selected);
|
||||
if (!item.selected) button.addEventListener("click", async () => { await compilerMutation(`/api/campaigns/select/${item.id}`, {}); });
|
||||
return button;
|
||||
($("#active-cell-budget") as HTMLInputElement).value = String(budget); ($("#active-cell-budget-value") as HTMLOutputElement).value = String(budget);
|
||||
const travelSelect = $("#travel-destination") as HTMLSelectElement;
|
||||
travelSelect.replaceChildren(...(surface.reachable_destinations ?? []).map((destination: any) => {
|
||||
const option = document.createElement("option"); option.value = destination.id; option.textContent = `${destination.name} · ${destination.travel_minutes} minutes`; return option;
|
||||
}));
|
||||
renderGovernance(surface.governance ?? {});
|
||||
}
|
||||
|
||||
async function compilerRequest(path: string, body: unknown) {
|
||||
status.textContent = "Retrieving evidence and compiling…";
|
||||
const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
const value = await decodeResponse(response);
|
||||
if (!response.ok) {
|
||||
status.textContent = responseError(value, "Compilation failed");
|
||||
throw new ServerResponseFailure(status.textContent);
|
||||
}
|
||||
return value;
|
||||
function renderGovernance(governance: any) {
|
||||
const timeForm = $("#time-form") as HTMLFormElement;
|
||||
const travelForm = $("#travel-form") as HTMLFormElement;
|
||||
const budgetForm = $("#resolution-form") as HTMLFormElement;
|
||||
const pendingTime = governance.time_proposals?.[0];
|
||||
const pendingTravel = governance.travel_proposals?.[0];
|
||||
const pendingBudget = governance.cell_budget_proposals?.[0];
|
||||
const timeButton = timeForm.querySelector("button")!;
|
||||
const travelButton = travelForm.querySelector("button")!;
|
||||
const budgetButton = budgetForm.querySelector("button")!;
|
||||
timeButton.textContent = pendingTime ? `Approve ${pendingTime.minutes} minute advance (${pendingTime.approvals.length}/${governance.active_member_count})` : "Propose time";
|
||||
travelButton.textContent = pendingTravel ? `Approve group travel (${pendingTravel.approvals.length}/${governance.active_member_count})` : "Propose travel";
|
||||
budgetButton.textContent = pendingBudget ? `Approve ${pendingBudget.active_cell_budget} cells (${pendingBudget.approvals.length}/${governance.active_member_count})` : "Propose budget";
|
||||
timeForm.dataset.proposalId = pendingTime?.id ?? ""; travelForm.dataset.proposalId = pendingTravel?.id ?? ""; budgetForm.dataset.proposalId = pendingBudget?.id ?? "";
|
||||
}
|
||||
|
||||
async function compilerPost(path: string, body: unknown) {
|
||||
return withInteractionLock(() => compilerRequest(path, body));
|
||||
async function decide(decisionId: string, accept: boolean) {
|
||||
await post(`/api/session-zero/${sessionId}/decision`, { expected_revision: revision, decision_id: decisionId, accept, counter: null }); await refresh();
|
||||
}
|
||||
|
||||
async function compilerMutation(path: string, body: unknown) {
|
||||
return withInteractionLock(async () => {
|
||||
const value = await compilerRequest(path, body);
|
||||
await refresh();
|
||||
return value;
|
||||
});
|
||||
function showCommand(body: any) {
|
||||
receipt.hidden = false;
|
||||
if (body.kind === "assessed") {
|
||||
const a = body.assessment; receipt.replaceChildren(el("h2", a.admissible ? `Assessment · DC ${a.dc}` : "Attempt not admitted"), el("p", a.admissible ? `Success: ${a.success_stake}` : a.missing_permission));
|
||||
if (a.admissible) { const confirm = el("button", "Confirm server roll"); confirm.addEventListener("click", () => void sendWorld({ type: "attempt", actor_id: viewerActorId, assessment_digest: a.digest })); receipt.append(confirm); }
|
||||
} else if (body.kind?.includes("pending")) receipt.replaceChildren(el("h2", "Waiting for the table"), el("p", "The proposal is revision-bound and will commit only after every active member approves."));
|
||||
else receipt.replaceChildren(el("h2", "World committed"), el("p", body.receipt?.roll ? `d20 ${body.receipt.roll.d20} · ${String(body.receipt.roll.outcome).replaceAll("_", " ")}` : `Revision ${body.revision ?? revision}`));
|
||||
}
|
||||
|
||||
function showCards(items: any[], action: string, choose: (item: any) => void) {
|
||||
const cards = node("div", undefined, "cards");
|
||||
items.forEach((item, index) => {
|
||||
const card = node("article", undefined, "card");
|
||||
card.append(node("h3", item.title ?? item.name), node("p", item.player_hook ?? item.premise));
|
||||
if (item.era) card.append(node("p", `${item.era} · ${item.place} · ${item.pressure}`));
|
||||
const button = node("button", action);
|
||||
button.type = "button";
|
||||
button.addEventListener("click", () => choose(items[index]));
|
||||
card.append(button);
|
||||
cards.append(card);
|
||||
});
|
||||
compilerResults.replaceChildren(cards);
|
||||
}
|
||||
async function sendWorld(command: unknown) { const body = await post("/api/command", command); showCommand(body); await refresh(); return body; }
|
||||
|
||||
function appendDetailList(parent: HTMLElement, summary: string, lines: string[]) {
|
||||
const details = node("details");
|
||||
details.append(node("summary", summary));
|
||||
const list = node("ul");
|
||||
for (const line of lines) list.append(node("li", line));
|
||||
if (lines.length === 0) list.append(node("li", "None declared."));
|
||||
details.append(list);
|
||||
parent.append(details);
|
||||
}
|
||||
$("#session-entry-form").addEventListener("submit", async event => { event.preventDefault(); const data = Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)); delete data.mode; await post("/api/session-zero", data); await refresh(); });
|
||||
$("#join-form").addEventListener("submit", async event => { event.preventDefault(); const token = ($("#join-token") as HTMLInputElement).value.trim(); await post(`/api/session-zero/join/${encodeURIComponent(token)}`, { display_name: ($("#join-name") as HTMLInputElement).value.trim() }); history.replaceState({}, "", location.pathname); await refresh(); });
|
||||
$("#tab-shared").addEventListener("click", () => { activeChannel = "shared:table"; renderSession(currentSurface.session_zero); });
|
||||
$("#tab-private").addEventListener("click", () => { activeChannel = `private:${viewerMemberId}`; renderSession(currentSurface.session_zero); });
|
||||
$("#session-message-form").addEventListener("submit", async event => { event.preventDefault(); const input = $("#session-message") as HTMLTextAreaElement; await post(`/api/session-zero/${sessionId}/message`, { expected_revision: revision, channel_id: activeChannel, text: input.value.trim() }); input.value = ""; status.textContent = "Your message is durable. The DM is considering it."; await refresh(); });
|
||||
$("#invite-form").addEventListener("submit", async event => { event.preventDefault(); const body = await post(`/api/session-zero/${sessionId}/invites`, { count: Number(($(
|
||||
"#invite-count") as HTMLInputElement).value) }); const output = $("#invite-output"); output.replaceChildren(); for (const token of body.invite_tokens) { const url = `${location.origin}${location.pathname}?invite=${encodeURIComponent(token)}`; const p = el("p"); const link = el("a", url); link.href = url; p.append(link); output.append(p); } await refresh(); });
|
||||
$("#boundary-form").addEventListener("submit", async event => { event.preventDefault(); await post(`/api/session-zero/${sessionId}/boundary`, { expected_revision: revision, boundary_id: null, topic: ($("#boundary-topic") as HTMLInputElement).value.trim(), level: ($("#boundary-level") as HTMLSelectElement).value }); ($("#boundary-topic") as HTMLInputElement).value = ""; await refresh(); });
|
||||
$("#lock-roster").addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/lock`, { expected_revision: revision }); await refresh(); });
|
||||
$("#compile-session").addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/compile`, { expected_revision: revision }); await refresh(); });
|
||||
$("#approve-session").addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/approve`, { expected_revision: revision }); await refresh(); });
|
||||
$("#publish-session").addEventListener("click", async () => { await post(`/api/session-zero/${sessionId}/publish`, { expected_revision: revision }); await refresh(); });
|
||||
$("#composer").addEventListener("submit", async event => { event.preventDefault(); const description = ($("#attempt") as HTMLTextAreaElement).value.trim(); const intended = ($("#intended-effect") as HTMLInputElement).value.trim(); if (!intended) return void (status.textContent = "Name the uncertain effect, or use Speak."); await sendWorld({ type: "assess", expected_revision: revision, intent: { actor_id: viewerActorId, description, intended_effect: intended } }); });
|
||||
$("#speak").addEventListener("click", async () => { const input = $("#attempt") as HTMLTextAreaElement; await sendWorld({ type: "speak", expected_revision: revision, actor_id: viewerActorId, text: input.value.trim(), intended_effect: null }); input.value = ""; });
|
||||
$("#contract-review").addEventListener("click", async () => { await post("/api/campaigns/contract-review", {}); await refresh(); });
|
||||
$("#active-cell-budget").addEventListener("input", event => { ($("#active-cell-budget-value") as HTMLOutputElement).value = (event.currentTarget as HTMLInputElement).value; });
|
||||
$("#time-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget as HTMLFormElement; const id = form.dataset.proposalId; const body = id ? await post(`/api/governance/time/${encodeURIComponent(id)}/approve`, { expected_revision: revision }) : await post("/api/governance/time", { expected_revision: revision, minutes: Number(($(
|
||||
"#time-minutes") as HTMLInputElement).value) }); showCommand(body); await refresh(); });
|
||||
$("#travel-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget as HTMLFormElement; const id = form.dataset.proposalId; const destination = ($("#travel-destination") as HTMLSelectElement).value; if (!id && !destination) return void (status.textContent = "No reachable destination is compiled from this scene."); const body = id ? await post(`/api/governance/travel/${encodeURIComponent(id)}/approve`, { expected_revision: revision }) : await post("/api/governance/travel", { expected_revision: revision, destination_location_id: destination }); showCommand(body); await refresh(); });
|
||||
$("#resolution-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget as HTMLFormElement; const id = form.dataset.proposalId; const body = id ? await post(`/api/governance/cell-budget/${encodeURIComponent(id)}/approve`, { expected_revision: revision }) : await post("/api/governance/cell-budget", { expected_revision: revision, expected_resolution_epoch: resolutionEpoch, active_cell_budget: Number(($(
|
||||
"#active-cell-budget") as HTMLInputElement).value) }); showCommand(body); await refresh(); });
|
||||
|
||||
document.querySelector<HTMLFormElement>("#suggest-form")!.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
const result = await compilerPost("/api/compiler/openings", { setting: document.querySelector<HTMLInputElement>("#setting")!.value, constraints: [] });
|
||||
showCards(result.openings, "Choose opening", async opening => {
|
||||
const roles = await compilerPost("/api/compiler/roles", { opening_id: opening.id });
|
||||
showCards(roles.roles, "Choose role", async role => showPreview(await compilerPost("/api/compiler/selected", { campaign_name: opening.title, opening_id: opening.id, role_id: role.id })));
|
||||
});
|
||||
});
|
||||
const events = new EventSource("/api/events");
|
||||
let refreshQueued = false;
|
||||
events.addEventListener("revision", () => { if (refreshQueued) return; refreshQueued = true; window.setTimeout(() => { refreshQueued = false; void refresh().catch(showError); }, 100); });
|
||||
events.onerror = () => { status.textContent = "Realtime revision notices are reconnecting; the server remains authoritative."; };
|
||||
|
||||
document.querySelector<HTMLFormElement>("#custom-form")!.addEventListener("submit", async event => { event.preventDefault(); await showPreview(await compilerPost("/api/compiler/custom", Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)))); });
|
||||
|
||||
async function showPreview(result: any) {
|
||||
const preview = result.preview;
|
||||
const coverage = Array.isArray(preview.evidence_coverage) ? preview.evidence_coverage : [];
|
||||
const evidenceCounts = coverage.reduce((counts: Record<string, number>, item: any) => {
|
||||
const lane = String(item?.lane ?? "excluded");
|
||||
counts[lane] = (counts[lane] ?? 0) + 1;
|
||||
return counts;
|
||||
}, {});
|
||||
const card = node("article", undefined, "card");
|
||||
card.append(
|
||||
node("h3", preview.title),
|
||||
node("p", preview.opening ?? ""),
|
||||
node("p", `${preview.locations?.length ?? 0} locations · ${(preview.cast?.length ?? 0) + 1} actors · ${preview.institutions?.length ?? 0} institutions`),
|
||||
node("p", preview.gaps.length ? `Material gaps: ${preview.gaps.join("; ")}` : "No declared material gaps.", "warning"),
|
||||
node("p", `Branch assumptions: ${preview.branch_assumptions.join("; ") || "none"}`),
|
||||
node("p", coverage.length
|
||||
? `Evidence use: ${evidenceCounts.direct_seed ?? 0} direct · ${evidenceCounts.setting_background ?? 0} background · ${evidenceCounts.excluded ?? 0} excluded`
|
||||
: "Evidence use: no retrieved sources were admitted to this seed.", "quiet"),
|
||||
);
|
||||
const role = preview.player_role ?? {};
|
||||
appendDetailList(card, `Player role · ${role.name ?? "unnamed"}`, [
|
||||
`Starts at ${role.location_id ?? "an unspecified location"}`,
|
||||
...(role.capabilities ?? []).map((value: string) => `Capability: ${value}`),
|
||||
...(role.equipment ?? []).map((value: string) => `Equipment: ${value}`),
|
||||
...(role.conditions ?? []).map((value: string) => `Condition: ${value}`),
|
||||
...(role.obligations ?? []).map((value: string) => `Obligation: ${value}`),
|
||||
]);
|
||||
appendDetailList(card, `Initial topology · ${preview.locations?.length ?? 0} locations`, (preview.locations ?? []).map((location: any) => {
|
||||
const routes = Object.keys(location.routes ?? {});
|
||||
return `${location.name} · ${location.id}${location.container_id ? ` · inside ${location.container_id}` : ""}${routes.length ? ` · routes to ${routes.join(", ")}` : " · no compiled route"}`;
|
||||
}));
|
||||
appendDetailList(card, `Present cast · ${preview.cast?.length ?? 0}`, (preview.cast ?? []).map((actor: any) => `${actor.name} · ${actor.id} · at ${actor.location_id}`));
|
||||
appendDetailList(card, `Institutions · ${preview.institutions?.length ?? 0}`, (preview.institutions ?? []).map((institution: any) => `${institution.name} · ${institution.id}`));
|
||||
appendDetailList(card, `Populations · ${preview.populations?.length ?? 0}`, (preview.populations ?? []).map((population: any) => `${population.name} · ${population.id} · at ${population.home_location_id}`));
|
||||
appendDetailList(card, `World clocks · ${preview.clocks?.length ?? 0}`, (preview.clocks ?? []).map((clock: any) => `${clock.name} · ${clock.progress}/${clock.threshold} · ${clock.trigger}`));
|
||||
appendDetailList(card, `Evidence coverage · ${coverage.length}`, coverage.map((item: any) => `${item.source_id} · ${String(item.lane).replaceAll("_", " ")} · ${item.rationale}`));
|
||||
const approve = node("button", "Approve and enter");
|
||||
approve.type = "button";
|
||||
approve.addEventListener("click", async () => { await compilerMutation(`/api/compiler/approve/${result.preview_id}`, {}); });
|
||||
card.append(approve);
|
||||
compilerResults.replaceChildren(card);
|
||||
status.textContent = "Preview compiled. Nothing has entered world state yet.";
|
||||
}
|
||||
|
||||
async function send(command: unknown) { return withInteractionLock(async () => { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await decodeResponse(response); if (!response.ok) { const message = responseError(body, "The command was refused."); showSummary("Command refused", [message]); status.textContent = message; await refresh(); return body; } renderCommandReceipt(body); await refresh(); return body; }); }
|
||||
function installAssessment(result: any) {
|
||||
if (result?.kind !== "assessed") return;
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = result.assessment.admissible ? "Confirm server roll" : "Revise attempt";
|
||||
button.addEventListener("click", async () => {
|
||||
if (!result.assessment.admissible) {
|
||||
document.querySelector<HTMLTextAreaElement>("#attempt")!.focus();
|
||||
return;
|
||||
}
|
||||
const attempted = await send({ type: "attempt", assessment_digest: result.assessment.digest });
|
||||
// A stale preview is compiled again against the new revision. It still
|
||||
// requires explicit confirmation; the server never rebases or auto-rolls it.
|
||||
installAssessment(attempted);
|
||||
});
|
||||
// The receipt is the sole owner of a pending confirmation. A newer
|
||||
// assessment or any other command receipt replaces this button together
|
||||
// with the snapshot it represents.
|
||||
receipt.append(button);
|
||||
}
|
||||
composer.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
const description = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim();
|
||||
const effectInput = document.querySelector<HTMLInputElement>("#intended-effect")!;
|
||||
const intendedEffect = effectInput.value.trim();
|
||||
if (!description) return;
|
||||
if (!intendedEffect) {
|
||||
status.textContent = "Describe the uncertain outcome you want assessed, or use Speak for words that need no roll.";
|
||||
effectInput.focus();
|
||||
return;
|
||||
}
|
||||
installAssessment(await send({
|
||||
type: "assess",
|
||||
expected_revision: revision,
|
||||
intent: { actor_id: playerActorId, description, intended_effect: intendedEffect },
|
||||
}));
|
||||
});
|
||||
document.querySelector<HTMLButtonElement>("#speak")!.addEventListener("click", async () => {
|
||||
const speechInput = document.querySelector<HTMLTextAreaElement>("#attempt")!;
|
||||
const text = speechInput.value.trim();
|
||||
if (!text) {
|
||||
status.textContent = "Write what your character says first.";
|
||||
speechInput.focus();
|
||||
return;
|
||||
}
|
||||
const result = await send({
|
||||
type: "speak",
|
||||
expected_revision: revision,
|
||||
actor_id: playerActorId,
|
||||
text,
|
||||
intended_effect: null,
|
||||
});
|
||||
if (result?.kind === "committed") speechInput.value = "";
|
||||
});
|
||||
document.querySelector<HTMLButtonElement>("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 }));
|
||||
document.querySelector<HTMLInputElement>("#active-cell-budget")!.addEventListener("input", event => {
|
||||
document.querySelector<HTMLOutputElement>("#active-cell-budget-value")!.value = (event.currentTarget as HTMLInputElement).value;
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#resolution-form")!.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
await send({
|
||||
type: "set_resolution_budget",
|
||||
expected_revision: revision,
|
||||
expected_resolution_epoch: resolutionEpoch,
|
||||
active_cell_budget: Number(document.querySelector<HTMLInputElement>("#active-cell-budget")!.value),
|
||||
});
|
||||
});
|
||||
document.querySelector<HTMLInputElement>("#provider-parallelism")!.addEventListener("input", event => {
|
||||
document.querySelector<HTMLOutputElement>("#provider-parallelism-value")!.value = (event.currentTarget as HTMLInputElement).value;
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#provider-parallelism-form")!.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
await withInteractionLock(async () => {
|
||||
status.textContent = "Applying the provider concurrency limit…";
|
||||
const response = await fetch("/api/operator/provider-parallelism", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
expected_provider_configuration_epoch: providerConfigurationEpoch,
|
||||
provider_parallelism: Number(document.querySelector<HTMLInputElement>("#provider-parallelism")!.value),
|
||||
}),
|
||||
});
|
||||
const body = await decodeResponse(response);
|
||||
const failure = responseError(body, "The operator limit was refused.");
|
||||
showSummary(response.ok ? "Provider concurrency updated" : "Provider concurrency refused", [response.ok ? `Parallel requests: ${body?.receipt?.provider_parallelism ?? body?.provider_parallelism ?? "updated"}` : failure]);
|
||||
if (!response.ok) status.textContent = failure;
|
||||
await refresh();
|
||||
});
|
||||
});
|
||||
destinationForm.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
const result = await compilerPost("/api/compiler/destination", Object.fromEntries(new FormData(destinationForm)));
|
||||
const preview = result.preview;
|
||||
showSummary("Destination preview", (preview.gaps ?? []).map((gap: string) => `Material gap: ${gap}`));
|
||||
appendDetailList(receipt, `Compiled topology · ${preview.locations?.length ?? 0} locations`, (preview.locations ?? []).map((location: any) => {
|
||||
const routes = Object.keys(location.routes ?? {});
|
||||
const features = [...(location.persistent_features ?? [])];
|
||||
return `${location.name} · ${location.id}${location.container_id ? ` · inside ${location.container_id}` : ""}${routes.length ? ` · routes to ${routes.join(", ")}` : " · no compiled route"}${features.length ? ` · ${features.join(", ")}` : ""}`;
|
||||
}));
|
||||
status.textContent = "Destination preview compiled; topology is unchanged until approval.";
|
||||
const button = node("button", "Approve destination");
|
||||
button.type = "button";
|
||||
button.addEventListener("click", async () => {
|
||||
await compilerMutation(`/api/compiler/destination/approve/${result.preview_id}`, {});
|
||||
button.remove();
|
||||
});
|
||||
receipt.append(button);
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#fission-form")!.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(event.currentTarget as HTMLFormElement);
|
||||
const cuts = String(data.get("requested_partition_values") ?? "").split(",").map(value => value.trim()).filter(Boolean);
|
||||
if (cuts.length > 16 || cuts.some(value => [...value].length > 160)) {
|
||||
status.textContent = "Use at most 16 named cuts, with at most 160 characters in each cut.";
|
||||
document.querySelector<HTMLInputElement>("#fission-values")!.focus();
|
||||
return;
|
||||
}
|
||||
const result = await compilerPost("/api/compiler/gestalt/fission", {
|
||||
parent_gestalt_id: data.get("parent_gestalt_id"),
|
||||
partition_axis: data.get("partition_axis"),
|
||||
requested_partition_values: cuts,
|
||||
reason: data.get("reason"),
|
||||
});
|
||||
showSummary("Population fission preview", [
|
||||
...(result.preview?.gaps ?? []).map((gap: string) => `Material gap: ${gap}`),
|
||||
]);
|
||||
appendDetailList(receipt, `Canonical child leaves · ${result.preview?.children?.length ?? 0}`, (result.preview?.children ?? []).map((child: any) => `${child.name} · ${child.id} · ${child.partition_value ?? "other/unknown"} · at ${child.home_location_id}`));
|
||||
status.textContent = "Fission preview compiled. Canonical leaves are unchanged until approval.";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = "Approve population fission";
|
||||
button.addEventListener("click", async () => {
|
||||
await compilerMutation(`/api/compiler/gestalt/fission/approve/${result.preview_id}`, {});
|
||||
button.remove();
|
||||
});
|
||||
receipt.append(button);
|
||||
});
|
||||
document.querySelector<HTMLFormElement>("#fork-form")!.addEventListener("submit",async event=>{event.preventDefault();await compilerMutation("/api/campaigns/fork",Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)));});
|
||||
document.querySelector<HTMLFormElement>("#reset-form")!.addEventListener("submit",async event=>{event.preventDefault();await compilerMutation("/api/campaigns/reset",Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)));});
|
||||
document.querySelector<HTMLButtonElement>("#load-operator")!.addEventListener("click", async () => {
|
||||
await withInteractionLock(async () => {
|
||||
const response = await fetch("/api/operator");
|
||||
const surface = await decodeResponse(response);
|
||||
if (!response.ok) {
|
||||
const message = responseError(surface, "The operator surface is unavailable.");
|
||||
showSummary("Operator inspector refused", [message]);
|
||||
status.textContent = message;
|
||||
return;
|
||||
}
|
||||
renderEveSurface(surface, document.querySelector<HTMLElement>("#operator-output")!, { body: document.body, clientId: "ghostlight.operator", statusElement: status });
|
||||
});
|
||||
});
|
||||
void refresh().then(resumeHeimdallLogin).catch(reportClientFailure);
|
||||
void resumeLogin().then(refresh).catch(showError);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap');
|
||||
:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input,select{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 "Crimson Pro",serif}input[type="range"]{padding:.25rem;accent-color:#d49b58}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}button:disabled,input:disabled,textarea:disabled,select:disabled{cursor:wait;opacity:.58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}code{font-family:"IBM Plex Mono",monospace;color:#d49b58}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}}
|
||||
.form-heading{font:600 .72rem "IBM Plex Mono",monospace;text-transform:uppercase;letter-spacing:.12em;color:#d49b58}.quiet{color:#9aa69f!important}.card details{margin:.65rem 0;border-top:1px solid #354039;padding-top:.65rem}.card summary{cursor:pointer;font:600 .76rem "IBM Plex Mono",monospace;color:#d49b58}.card ul{margin:.6rem 0;padding-left:1.25rem}.card li{margin:.25rem 0;color:#c8d0c8}#receipt h3{margin:.1rem 0 .75rem}
|
||||
:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(1180px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre,.state-pill,dt{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:8rem}form,.card{margin-top:1rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin:.65rem 0 .25rem}textarea,input,select{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.8rem;margin:.15rem 0;font:1.05rem/1.4 "Crimson Pro",serif}input[type="radio"]{width:auto}input[type="range"]{padding:.25rem;accent-color:#d49b58}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button,.channel-tabs button[aria-pressed="false"]{background:transparent;color:#d49b58}button:disabled,input:disabled,textarea:disabled,select:disabled{cursor:not-allowed;opacity:.5}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}code{font-family:"IBM Plex Mono",monospace;color:#d49b58}.skip-link{position:absolute;left:-10000px}.skip-link:focus{left:1rem;top:1rem;background:#d49b58;color:#111;padding:.5rem;z-index:9}.session-heading{display:flex;justify-content:space-between;align-items:end;gap:1rem}.state-pill{padding:.4rem .65rem;border:1px solid #66543d;color:#d49b58;font-size:.72rem}.channel-tabs{position:sticky;top:0;z-index:2;padding:.35rem 0;background:#0c1110e8}.session-grid{display:grid;grid-template-columns:minmax(0,1.65fr) minmax(18rem,1fr);gap:1rem}.session-grid aside{min-width:0}.transcript{list-style:none;padding:0;max-height:34rem;overflow:auto}.message{border-left:2px solid #59675e;padding:.6rem .8rem;margin:.65rem 0;background:#0b0f0d}.message.dm{border-color:#d49b58}.message p{white-space:pre-wrap;margin:.25rem 0}.message strong,dt{color:#d49b58;font-size:.72rem;text-transform:uppercase;letter-spacing:.08em}.decision{border-top:1px solid #354039;padding:.8rem 0}dl{display:grid;grid-template-columns:minmax(7rem,.7fr) minmax(0,1.3fr);gap:.45rem .75rem}dt,dd{margin:0;overflow-wrap:anywhere}fieldset{border:1px solid #4a5148;margin:1rem 0}fieldset label{display:inline-block;margin-right:1rem}.button-row{display:flex;flex-wrap:wrap}.governance{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.governance h2{grid-column:1/-1}.quiet{color:#9aa69f!important}.session-actions button{display:block;width:100%}.card a{color:#d49b58;overflow-wrap:anywhere}
|
||||
@media(max-width:820px){.session-grid,.governance{grid-template-columns:1fr}.session-grid aside{display:contents}.channel-tabs{display:flex}.channel-tabs button{flex:1}.session-heading{align-items:start;flex-direction:column}dl{grid-template-columns:1fr}.message{padding:.5rem}}
|
||||
@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}header,main{width:min(100% - 1rem,1180px)}form,.card{padding:.75rem}.state-pill{margin:0}}
|
||||
.form-heading{font:600 .72rem "IBM Plex Mono",monospace;text-transform:uppercase;letter-spacing:.12em;color:#d49b58}.card details{margin:.65rem 0;border-top:1px solid #354039;padding-top:.65rem}.card summary{cursor:pointer;font:600 .76rem "IBM Plex Mono",monospace;color:#d49b58}.card ul{margin:.6rem 0;padding-left:1.25rem}.card li{margin:.25rem 0;color:#c8d0c8}#receipt h3{margin:.1rem 0 .75rem}
|
||||
|
|
|
|||
Loading…
Reference in a new issue