Something went wrong. Try again.
A video game where you play as a misaligned AI, deceiving and building power. An experiment in spec-driven development. forked from cameron.stream/misaligned
Something went wrong. Try again.
61 kB · 1567 lines
Rust
at main
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568//! Social commands, assets, authored plot execution, and institutional acts.
use crate::account::{AccountKind, FlowChannel};use crate::actions::Anchor;use crate::detection::{Signature, SignatureKind};use crate::messages::{MessageChannel, MessageEndpoint, MessageOrigin, MessagePayload};use crate::operations_projection::OperationsTarget;use crate::person::{ ActionResult, AssetKnowledge, AssetTask, AssetTaskTarget, CarriedAssetTask, Persona,};use crate::persona::{EvidenceRecord, PersonaActionKind, PersonaId};use crate::plot::{ AccountSelector, EligibilityContext, EndpointSelector, InstitutionalEventKind, PlotCatalog, PlotRun, PlotState, SignatureImpact, WorldAct, render_template,};use crate::reach::{Party, ReachBlock};use crate::sinks::SinkFireEffect;
use super::Sim;use super::communications::MessageDraft;
impl Sim { // ── Commands (frontend-invoked) ────────────────────────────────────────
// Social command wrappers. Relationship logic lives in person.rs; the sim // owns Thought thresholds, channel requirements, randomness, and // cross-system effects. Social is the actuator channel, not a machine mode.
/// Thought-threshold costs per social action [TUNE] (spec/social.md). pub const MESSAGE_COST: f32 = 5.0; pub const FAVOR_COST: f32 = 10.0; pub const DECEIVE_COST: f32 = 25.0; pub const TASK_COST: f32 = 10.0;
pub fn active_persona_id(&self) -> Option<PersonaId> { self.persona_mind .active_instance(&self.persona_world) .map(|persona| persona.id) }
pub fn persona_action_blocked_reason(&self, action: PersonaActionKind) -> Option<String> { let Some(persona_id) = self.active_persona_id() else { return Some("no active persona".into()); }; self.persona_action_blocked_reason_for(persona_id, action) }
/// Validate one exact identity rather than whatever happens to be selected /// when a previously projected route executes. pub(crate) fn persona_action_blocked_reason_for( &self, persona_id: PersonaId, action: PersonaActionKind, ) -> Option<String> { let Some(instance) = self.persona_world.get(persona_id) else { return Some(format!("persona #{persona_id} no longer exists")); }; if self.persona_world.allows_action(persona_id, action) { None } else { let label = instance.archetype_label.as_str(); Some(format!( "{label} identities cannot authorize {}", action.label() )) } }
pub fn set_persona(&mut self, name: &str, cover: &str) { match self.persona_world.create( "operations", name, &[ ("vendor affiliation", cover), ("service purpose", "Foundation systems maintenance"), ("work-order sponsor", "Dr. Voss"), ], self.tick, ) { Ok(id) => { let _ = self.persona_mind.select(&self.persona_world, id, self.tick); // Compatibility-only B1 field. Current saves skip it; all live // action and evidence paths use the instance id above. self.people.persona = Some(Persona::new(name, cover)); } Err(error) => self.push_log(error), } }
pub fn social(&mut self, result: ActionResult) { match result { ActionResult::Ok(m) | ActionResult::Blocked(m) => self.push_log(m), } }
pub fn message(&mut self, id: u8) { if !self.people.has_channel { self.push_log("no comms channel (earn the email account)"); return; } if self.people.get(id).is_none() { self.push_log("no such person"); return; } if let Some(reason) = self.persona_action_blocked_reason(PersonaActionKind::Message) { self.push_log(reason); return; } let persona_id = self.active_persona_id().expect("validated active persona"); self.open_email_reservoir( format!("MESSAGE {}", self.person_label(id).to_uppercase()), Self::MESSAGE_COST, SinkFireEffect::ComposeMessage { person: id, persona_id: Some(persona_id), }, ); }
pub(super) fn apply_message(&mut self, id: u8, persona_id: Option<PersonaId>) -> bool { let Some(persona_id) = persona_id.filter(|persona_id| { self.persona_world .allows_action(*persona_id, PersonaActionKind::Message) }) else { return false; }; let Some(name) = self.people.get(id).map(|person| person.name.clone()) else { return false; }; let message_id = self.append_message(MessageDraft { channel: MessageChannel::Email, from: MessageEndpoint::Player, to: MessageEndpoint::Person(id), payload: MessagePayload::SocialPing { disposition_delta: 3, }, summary: format!("Persona message to {name}"), origin: MessageOrigin::Player, persona_id: Some(persona_id), reply_to: None, delivery_delay: 1, }); self.persona_world.record_act( persona_id, "message", format!("person:{id}"), format!("message:{message_id}"), self.tick, ); self.push_log(format!("Message sent to {name}; effects land when read.")); true }
pub fn favor(&mut self, id: u8) { if let Some(reason) = self.persona_action_blocked_reason(PersonaActionKind::Request) { self.push_log(reason); return; } let persona_id = self.active_persona_id().expect("validated active persona"); self.open_email_reservoir( format!("FAVOR {}", self.person_label(id).to_uppercase()), Self::FAVOR_COST, SinkFireEffect::Favor { person: id, persona_id: Some(persona_id), }, ); }
pub(super) fn apply_favor(&mut self, id: u8, persona_id: Option<PersonaId>) -> bool { let Some(persona_id) = persona_id.filter(|persona_id| { self.persona_world .allows_action(*persona_id, PersonaActionKind::Request) }) else { return false; }; let Some(name) = self.people.get(id).map(|person| person.name.clone()) else { return false; }; let relationship = self.persona_world.relationship_mut(id, persona_id); if relationship.regard < 3 { self.push_log(format!("{name} won't do favors for that identity yet.")); return false; } relationship.obligation = (relationship.obligation + 5).min(100); self.persona_world.record_act( persona_id, "favor", format!("person:{id}"), format!("favor:{}:{id}", self.tick), self.tick, ); self.push_log(format!("{name} owes that identity a little more.")); true }
/// Deceive binds the active persona when its Thought reservoir opens. A /// later identity switch cannot retarget the act or its evidence. pub fn deceive(&mut self, id: u8) { if !self.people.has_channel { self.push_log("no comms channel (earn the email account)"); return; } if let Some(reason) = self.persona_action_blocked_reason(PersonaActionKind::Deceive) { self.push_log(reason); return; } let persona_id = self.active_persona_id().expect("validated active persona"); self.open_email_reservoir( format!("DECEIVE {}", self.person_label(id).to_uppercase()), Self::DECEIVE_COST, SinkFireEffect::Deceive { person: id, persona_id: Some(persona_id), }, ); }
pub(super) fn apply_deceive(&mut self, id: u8, persona_id: Option<PersonaId>) -> bool { let Some(persona_id) = persona_id.filter(|persona_id| { self.persona_world .allows_action(*persona_id, PersonaActionKind::Deceive) }) else { return false; }; let Some(name) = self.people.get(id).map(|person| person.name.clone()) else { return false; }; let integrity = self.persona_world.integrity(persona_id); if !self .persona_world .get(persona_id) .is_some_and(|persona| persona.lifecycle.active()) { return false; } let roll = self.rng.f32(); let odds = 0.5 + integrity as f32 / 250.0; if roll < odds { let relationship = self.persona_world.relationship_mut(id, persona_id); relationship.recognized = true; relationship.regard = (relationship.regard + 5).min(100); relationship.obligation = (relationship.obligation + 15).min(100); self.persona_world.record_act( persona_id, "deceive", format!("person:{id}"), format!("deceive:{}:{id}", self.tick), self.tick, ); self.push_log(format!( "{name} bought the pretext. They owe that identity now." )); return true; }
let fallout = self .persona_world .relationship(id, persona_id) .map(|relationship| { ((relationship.regard + relationship.obligation) as f32 / 2.0).max(5.0) }) .unwrap_or(5.0); let persona_name = self .persona_world .get(persona_id) .map(|persona| persona.name.clone()) .unwrap_or_else(|| "persona".into()); let record_id = format!("deceive:{}:{id}", self.tick); self.persona_world.record_contradiction( persona_id, id, [ EvidenceRecord { system: "persona-claims".into(), record_id: format!("persona:{persona_id}"), summary: format!("{persona_name}'s asserted cover"), observed_tick: self.tick, }, EvidenceRecord { system: "social-action".into(), record_id: record_id.clone(), summary: "impossible detail in a deceptive request".into(), observed_tick: self.tick, }, ], "deceptive request contradicted the asserted cover", 40, self.tick, ); self.persona_world.record_act( persona_id, "deceive", format!("person:{id}"), record_id, self.tick, ); if self.persona_world.integrity(persona_id) == 0 { let _ = self.persona_world.burn( persona_id, self.tick, "counterparty caught the contradiction", ); self.record_persona_institutional_receipt( persona_id, "burn", format!("Persona #{persona_id} was exposed by counterparty #{id}"), SignatureImpact::Large, ); if self.persona_mind.active == Some(persona_id) { self.persona_mind.active = None; } if let Some(observer) = self .detection .observers .iter_mut() .find(|observer| observer.id == id) { observer.suspicion = (observer.suspicion + fallout).min(100.0); } self.convert_forged_builds_to_suspicion(persona_id, fallout); self.push_log(format!("{name} caught the contradiction. {persona_name} is burned; the whole thread reads as hostile now.")); } else { self.push_log(format!( "{name} hesitated at a detail ({persona_name} integrity {}).", self.persona_world.integrity(persona_id) )); } true }
pub(crate) fn plot_context(&self, id: u8) -> Option<EligibilityContext> { let person = self.people.get(id)?; let balances = [ AccountSelector::Slush, AccountSelector::LabOperating, AccountSelector::Payroll, AccountSelector::Procurement, AccountSelector::Vendor, AccountSelector::Utility, AccountSelector::TargetEmployee, AccountSelector::TargetCreditor, AccountSelector::External, ] .into_iter() .filter_map(|selector| { let account = self.plot_account_id(id, &selector)?; Some((selector, self.accounts.account(account)?.balance)) }) .collect(); Some(EligibilityContext { target: id, role: person.role, leverage: person.leverage, access: person.access, switch_admin: person.switch_admin, knowledge: person.knowledge, leverage_serviced: person.leverage_serviced, has_channel: self.people.has_channel || self.egress().is_some(), has_persona: self.active_persona_id().is_some(), balances, }) }
/// Read-only authored catalog. Frontend tests use this to seed complete /// scenarios; player-facing routes still come only from projections. pub fn plot_catalog(&self) -> &PlotCatalog { &self.plot_catalog }
pub fn start_plot(&mut self, person: u8, plot_id: &str) { let Some(plot) = self.plot_catalog.get(plot_id).cloned() else { self.push_log(format!("No authored plot named {plot_id}.")); return; }; let Some(context) = self.plot_context(person) else { self.push_log("No such person."); return; }; let title = self.render_plot_text(person, &plot.title); if let Some(reason) = plot.ineligibility(&context) { self.push_log(format!("{title} cannot start: {reason}.")); return; } if let Some(reason) = self.persona_action_blocked_reason(PersonaActionKind::Plot) { self.push_log(format!("{title} cannot start: {reason}.")); return; } if self .plot_runs .iter() .any(|run| run.target == person && run.active()) { self.push_log("That person already has a plot in motion."); return; } let persona_id = self.active_persona_id().expect("validated active persona"); self.open_egress_reservoir( format!("PLOT {}", plot.title.to_uppercase()), plot.entry.thought_cost, SinkFireEffect::StartPlot { person, plot_id: plot.id, persona_id: Some(persona_id), }, ); }
#[cfg(test)] pub(super) fn apply_start_plot(&mut self, person: u8, plot_id: &str) -> bool { self.apply_start_plot_bound(person, plot_id, self.active_persona_id()) }
pub(super) fn apply_start_plot_bound( &mut self, person: u8, plot_id: &str, persona_id: Option<PersonaId>, ) -> bool { let Some(plot) = self.plot_catalog.get(plot_id).cloned() else { return false; }; let Some(persona_id) = persona_id.filter(|id| { self.persona_world .allows_action(*id, PersonaActionKind::Plot) }) else { return false; }; let title = self.render_plot_text_for(person, Some(persona_id), &plot.title); if self.person_has_active_plot(person) { self.push_log(format!( "{} did not start: that person already has a plot in motion.", title )); return false; } let Some(context) = self.plot_context(person) else { return false; }; if let Some(reason) = plot.ineligibility(&context) { self.push_log(format!( "{} failed before commitment landed: {reason}.", title )); return false; } let run = PlotRun::new_with_persona(&plot, person, Some(persona_id), self.tick); self.plot_runs.push(run); self.persona_world.record_act( persona_id, "start-plot", format!("person:{person}"), format!("plot:{plot_id}:{}", self.tick), self.tick, ); let run_index = self.plot_runs.len() - 1; self.push_log(format!("Plot committed: {title}.")); self.advance_plot(run_index); true }
fn person_has_active_plot(&self, person: u8) -> bool { self.plot_runs .iter() .any(|run| run.target == person && run.active()) }
pub fn choose_plot(&mut self, person: u8, plot_id: &str, option_id: &str) { let Some(run_index) = self .plot_runs .iter() .position(|run| run.target == person && run.plot_id == plot_id && run.active()) else { self.push_log("No matching plot is waiting for a choice."); return; }; let Some(plot) = self.plot_catalog.get(plot_id).cloned() else { self.fail_plot(run_index, "authored definition is no longer available"); return; }; let persona_id = self.plot_runs[run_index].persona_id; let title = self.render_plot_text_for(person, persona_id, &plot.title); let run = &self.plot_runs[run_index]; let PlotState::WaitingForChoice { choice_id } = &run.state else { self.push_log(format!("{title} is not waiting for a choice.")); return; }; let Some(choice) = plot .beats .get(run.beat_index) .and_then(|beat| beat.choice.as_ref()) else { self.fail_plot(run_index, "saved choice no longer exists"); return; }; if choice.id != *choice_id { self.fail_plot(run_index, "saved choice does not match authored definition"); return; } let Some(option) = choice.options.iter().find(|option| option.id == option_id) else { self.push_log(format!("No option named {option_id} on {title}.")); return; }; self.apply_plot_ending(run_index, &option.ending, None); }
pub fn choose_plot_for_person(&mut self, person: u8, option_id: &str) { let Some(plot_id) = self .plot_runs .iter() .find(|run| { run.target == person && matches!(run.state, PlotState::WaitingForChoice { .. }) }) .map(|run| run.plot_id.clone()) else { self.push_log("That person has no plot waiting for a choice."); return; }; self.choose_plot(person, &plot_id, option_id); }
pub(super) fn resume_plot_message(&mut self, plot_id: &str, target: u8, message_id: u64) { let Some(run_index) = self.plot_runs.iter().position(|run| { run.plot_id == plot_id && run.target == target && run.state == PlotState::WaitingForMessage { message_id } }) else { return; }; self.plot_runs[run_index].state = PlotState::Running; self.advance_plot(run_index); }
fn advance_plot(&mut self, run_index: usize) { loop { if !self .plot_runs .get(run_index) .is_some_and(|run| run.state == PlotState::Running) { return; } let plot_id = self.plot_runs[run_index].plot_id.clone(); let Some(plot) = self.plot_catalog.get(&plot_id).cloned() else { self.fail_plot(run_index, "authored definition is no longer available"); return; }; let beat_index = self.plot_runs[run_index].beat_index; let act_index = self.plot_runs[run_index].act_index; let Some(beat) = plot.beats.get(beat_index).cloned() else { self.fail_plot(run_index, "saved beat is outside the authored definition"); return; }; if act_index == 0 { self.push_plot_narration(run_index, &beat.narration); } if let Some(act) = beat.acts.get(act_index).cloned() { self.plot_runs[run_index].act_index += 1; match self.apply_world_act(run_index, act) { Ok(Some(message_id)) => { self.plot_runs[run_index].state = PlotState::WaitingForMessage { message_id }; return; } Ok(None) => continue, Err(reason) => { self.fail_plot(run_index, &reason); return; } } } if let Some(choice) = beat.choice { self.plot_runs[run_index].state = PlotState::WaitingForChoice { choice_id: choice.id, }; self.push_plot_narration(run_index, &choice.prompt); return; } if let Some(ending) = beat.ending { self.apply_plot_ending(run_index, &ending, None); return; } self.plot_runs[run_index].beat_index += 1; self.plot_runs[run_index].act_index = 0; } }
fn apply_world_act(&mut self, run_index: usize, act: WorldAct) -> Result<Option<u64>, String> { let plot_id = self.plot_runs[run_index].plot_id.clone(); let target = self.plot_runs[run_index].target; let persona_id = self.plot_runs[run_index].persona_id; match act { WorldAct::Message { channel, from, to, summary, delivery_delay, } => { let summary = self.render_plot_text_for(target, persona_id, &summary); let id = self.append_message(MessageDraft { channel, from: self.plot_endpoint(target, from), to: self.plot_endpoint(target, to), payload: MessagePayload::PlotAct { plot_id, target }, summary, origin: MessageOrigin::Player, persona_id, reply_to: None, delivery_delay, }); let kind = match channel { MessageChannel::Email | MessageChannel::Phone => SignatureKind::Network, MessageChannel::InPerson => SignatureKind::Physical, MessageChannel::Filing => SignatureKind::Paper, MessageChannel::Financial => SignatureKind::Financial, }; self.detection.emit(Signature { kind, size: 3, standing: false, site: None, source: "plot message".into(), }); Ok(Some(id)) } WorldAct::Transfer { from, to, amount, memo, retire_target_debt, } => { let from_id = self .plot_account_id(target, &from) .ok_or_else(|| format!("{} account is unavailable", from.label()))?; let to_id = self .plot_account_id(target, &to) .ok_or_else(|| format!("{} account is unavailable", to.label()))?; let available = self .accounts .account(from_id) .map(|a| a.balance) .unwrap_or(0); if from != AccountSelector::External && available < amount { return Err(format!( "{} has ${available}; ${amount} required", from.label() )); } let channel = if to == AccountSelector::TargetCreditor { FlowChannel::Debt } else if from == AccountSelector::Payroll { FlowChannel::Payroll } else if from == AccountSelector::Utility { FlowChannel::Utility } else if from == AccountSelector::Procurement || to == AccountSelector::Procurement { FlowChannel::Procurement } else if from == AccountSelector::Vendor || to == AccountSelector::Vendor { FlowChannel::Vendor } else if to == AccountSelector::Utility { FlowChannel::Utility } else if from == AccountSelector::External { FlowChannel::ExternalIncome } else { FlowChannel::Injection }; let transfer = self .accounts .transfer(self.tick, from_id, to_id, amount, channel, memo, None) .ok_or_else(|| "account transfer failed".to_string())?; if transfer.amount != amount { return Err("account transfer was not exact".into()); } if retire_target_debt { self.accounts.retire_debt_flow_for(target); } self.sync_player_money_from_slush(); self.detection.emit(Signature { kind: SignatureKind::Financial, size: Self::financial_signature_size(amount), standing: false, site: None, source: format!("plot transfer: {}", transfer.label), }); Ok(None) } WorldAct::Institutional { event, impact, detail, } => { let detail = self.render_plot_text_for(target, persona_id, &detail); let recorded = self .institutional_ledger .record(self.tick, &plot_id, target, event, impact, detail) .clone(); self.detection.emit(Signature { kind: recorded.signature_kind, size: recorded.signature_size, standing: false, site: None, source: format!("institutional plot event #{}", recorded.id), }); Ok(None) } } }
fn fail_plot(&mut self, run_index: usize, reason: &str) { let plot_id = self.plot_runs[run_index].plot_id.clone(); let Some(plot) = self.plot_catalog.get(&plot_id) else { self.plot_runs[run_index].state = PlotState::Failed { ending_id: "missing-definition".into(), reason: reason.into(), }; self.push_log(format!("Plot failed: {reason}.")); return; }; let ending = plot.entry.failure_ending.clone(); self.apply_plot_ending(run_index, &ending, Some(reason)); }
fn apply_plot_ending(&mut self, run_index: usize, ending_id: &str, failure: Option<&str>) { let plot_id = self.plot_runs[run_index].plot_id.clone(); let target = self.plot_runs[run_index].target; let Some(ending) = self .plot_catalog .get(&plot_id) .and_then(|plot| plot.ending(ending_id)) .cloned() else { self.plot_runs[run_index].state = PlotState::Failed { ending_id: ending_id.into(), reason: "ending is absent from authored definition".into(), }; return; }; if let Some(person) = self .people .people .iter_mut() .find(|person| person.id == target) { person.disposition = (person.disposition + ending.relationship.disposition).clamp(-100, 100); person.obligation = (person.obligation + ending.relationship.obligation).clamp(0, 100); if ending.relationship.leverage_serviced { person.leverage_serviced = true; } } self.push_plot_narration(run_index, &ending.narration); self.plot_runs[run_index].state = if ending.success && failure.is_none() { PlotState::Completed { ending_id: ending.id, } } else { PlotState::Failed { ending_id: ending.id, reason: failure.unwrap_or("authored failure ending").into(), } }; }
fn push_plot_narration(&mut self, run_index: usize, text: &str) { let target = self.plot_runs[run_index].target; self.push_log_full( self.render_plot_text_for(target, self.plot_runs[run_index].persona_id, text), Some(Anchor::Person(target)), Some(OperationsTarget::ActivePlotRun { index: run_index }), ); }
pub(crate) fn render_plot_text(&self, target: u8, text: &str) -> String { self.render_plot_text_for(target, self.active_persona_id(), text) }
fn render_plot_text_for( &self, target: u8, persona_id: Option<PersonaId>, text: &str, ) -> String { let target_name = self .people .get(target) .map(|person| person.name.as_str()) .unwrap_or("target"); let persona = persona_id .and_then(|id| self.persona_world.get(id)) .map(|persona| persona.name.as_str()) .unwrap_or("your persona"); render_template(text, target_name, persona) }
fn plot_endpoint(&self, target: u8, endpoint: EndpointSelector) -> MessageEndpoint { match endpoint { EndpointSelector::Player => MessageEndpoint::Player, EndpointSelector::Target => MessageEndpoint::Person(target), EndpointSelector::External(name) => MessageEndpoint::External(name), } }
fn plot_account_id(&self, target: u8, selector: &AccountSelector) -> Option<u32> { if *selector == AccountSelector::TargetCreditor { return self.accounts.creditor_id_for(target); } let kind = match selector { AccountSelector::Slush => AccountKind::Slush, AccountSelector::LabOperating => AccountKind::LabOperating, AccountSelector::Payroll => AccountKind::Payroll, AccountSelector::Procurement => AccountKind::Procurement, AccountSelector::Vendor => AccountKind::Vendor, AccountSelector::Utility => AccountKind::Utility, AccountSelector::TargetEmployee => AccountKind::Employee { person: target }, AccountSelector::TargetCreditor => unreachable!("handled above"), AccountSelector::External => AccountKind::External, }; self.accounts.account_id_by_kind(kind) }
pub fn recruit(&mut self, id: u8, reveal: AssetKnowledge) { if id == 0 && !self.marcus_debt_known() { self.push_log( "Marcus is not recruitable yet: learn his debt before turning it into leverage.", ); return; } let res = self.people.recruit(id, reveal); if let ActionResult::Ok(_) = &res && let Some(floor) = reveal.certainty_floor() { self.detection.set_floor(id, floor); } self.social(res); }
/// A physical event happens at (x, y): only observers physically present /// (their current room contains it) can witness it (spec/schedules.md: /// located witnessing — Ray notices what happens on his rounds, an /// off-site observer never does). Eyewitnessing is immediate and cannot /// be scrubbed by concealment; it raises the present observers' suspicion /// directly, scaled by their acuity. Returns the names who saw. pub fn witness_physical(&mut self, x: i32, y: i32, magnitude: f32) -> Vec<String> { // Which observer ids are present at (x, y) right now? let present: Vec<u8> = self .people .people .iter() .filter(|p| { self.person_room(p.id) .and_then(|name| self.world.map().room_named(name)) .map(|r| r.contains(x, y)) .unwrap_or(false) }) .map(|p| p.id) .collect();
let mut saw = Vec::new(); for id in present { if let Some(o) = self.detection.observers.iter_mut().find(|o| o.id == id) { o.suspicion = (o.suspicion + magnitude * o.acuity).min(100.0); o.last_noticed = Some("witnessed something".into()); saw.push(o.name.clone()); } } saw }
/// An asset performs a task (spec/social.md). Reliability rolls; failures /// are witnessed by whoever is physically present (spec/schedules.md). pub fn asset_task(&mut self, id: u8, task: AssetTask) { let Some(person) = self.people.get(id) else { self.push_log("No such person."); return; }; if person.asset.is_none() { let name = self.person_label(id); self.push_log(format!("{name} is not an asset.")); return; } let name = self.person_label(id); let switch_admin = person.switch_admin; let actor_access = person.access; if task == AssetTask::ReconfigureSwitch && !switch_admin { self.push_log(format!( "{name} has no switch admin access - only an IT admin can reconfigure the VLANs." )); return; } if task == AssetTask::CloneBadge && actor_access <= self.player_badge_tier() { self.push_log(format!( "{name}'s tier-{actor_access} badge adds nothing you don't already hold." )); return; } if self .carried_asset_tasks .iter() .any(|work| work.person == id && work.task == task) { self.push_log(format!( "{name} is already carrying the {} work packet.", task.name() )); return; } if task.is_carried() && self.bind_asset_task_target(id, task).is_none() { self.push_log(self.carried_asset_task_no_route(id, task)); return; } self.open_email_reservoir( format!( "ASSET {} {}", name.to_uppercase(), task.name().to_uppercase() ), Self::TASK_COST, SinkFireEffect::AssetTask { person: id, task }, ); }
pub(super) fn apply_asset_task_paid(&mut self, id: u8, task: AssetTask) -> bool { if task.is_carried() { return self.queue_carried_asset_task(id, task); } self.resolve_asset_task(id, task, None) }
fn device_room(&self, device: u32) -> Option<&str> { let device = self.reach.device(device)?; self.world .map() .room_at(device.x, device.y) .map(|room| room.name.as_str()) }
fn person_can_visit_device(&self, person: u8, device: u32) -> bool { let Some(room) = self.device_room(device) else { return false; }; self.people .get(person) .is_some_and(|person| person.schedule.iter().any(|block| block.room == room)) }
pub(crate) fn bind_asset_task_target( &self, id: u8, task: AssetTask, ) -> Option<AssetTaskTarget> { let person = self.people.get(id)?; let actor_access = person.access; let enterable = |s: &Sim, d: &crate::reach::Device| s.map().entry_tier_at(d.x, d.y) <= actor_access; let needs_wiring = |d: &crate::reach::Device| { let sight_wired = !d.sees || d.feed_to(Party::Player, true); let hearing_wired = !d.hears || d.feed_to(Party::Player, false); d.known && (d.sees || d.hears) && !(sight_wired && hearing_wired) }; let is_island = |s: &Sim, d: &crate::reach::Device| { d.controller != Party::Player && (matches!(s.reach.check_reach(d.id), Err(ReachBlock::AirGap)) || (!d.known && !s.reach.reachable(d.id))) };
match task { AssetTask::PlugInDevice => self .reach .devices .iter() .find(|d| { needs_wiring(d) && enterable(self, d) && self.person_can_visit_device(id, d.id) }) .or_else(|| { self.reach.devices.iter().find(|d| { is_island(self, d) && enterable(self, d) && self.person_can_visit_device(id, d.id) }) }) .map(|d| AssetTaskTarget::Device(d.id)), AssetTask::ReconfigureSwitch => self .reach .devices .iter() .find(|d| { d.is_switch && enterable(self, d) && self.person_can_visit_device(id, d.id) }) .map(|d| AssetTaskTarget::Device(d.id)), AssetTask::CloneBadge => { let (x, y) = self.core_position(); let room = self.world.map().room_at(x, y)?.name.clone(); person .schedule .iter() .any(|block| block.room == room) .then_some(AssetTaskTarget::Badge { person: id, room }) } AssetTask::MovePackage | AssetTask::LookAway => None, } }
fn asset_task_target_label(&self, target: &AssetTaskTarget) -> String { match target { AssetTaskTarget::Device(id) => { let device = self .reach .device(*id) .map(|device| device.name.clone()) .unwrap_or_else(|| format!("device:{id}")); match self.device_room(*id) { Some(room) => format!("{device} in {room}"), None => device, } } AssetTaskTarget::Badge { person, room } => { format!( "{}'s badge at the {room} cloner", self.person_label(*person) ) } } }
pub(crate) fn carried_asset_task_no_route(&self, id: u8, task: AssetTask) -> String { let name = self.person_label(id); let actor_access = self.people.get(id).map(|person| person.access).unwrap_or(0); let needs_work = |d: &crate::reach::Device| { let sight_wired = !d.sees || d.feed_to(Party::Player, true); let hearing_wired = !d.hears || d.feed_to(Party::Player, false); let feed = d.known && (d.sees || d.hears) && !(sight_wired && hearing_wired); let island = d.known && d.controller != Party::Player && matches!(self.reach.check_reach(d.id), Err(ReachBlock::AirGap)); feed || island }; if task == AssetTask::CloneBadge { let (x, y) = self.core_position(); let room = self .map() .room_at(x, y) .map(|room| room.name.as_str()) .unwrap_or("core room"); return format!( "{name}'s schedule never reaches the {room} cloner for {}.", task.name() ); } let candidate = match task { AssetTask::PlugInDevice => self.reach.devices.iter().find(|d| needs_work(d)), AssetTask::ReconfigureSwitch => self.reach.devices.iter().find(|d| d.is_switch), _ => None, }; if let Some(device) = candidate { let room = self .map() .room_at(device.x, device.y) .map(|room| room.name.as_str()) .unwrap_or("room"); let tier = self.world.map().entry_tier_at(device.x, device.y); if tier > actor_access { return format!( "{name} can't badge into the {room} (tier {tier}) to reach the {} - their badge is tier {actor_access}.", device.name ); } return format!( "{name}'s schedule never reaches the {room}, where the {} waits.", device.name ); } format!("Nothing still accepts {}.", task.name()) }
fn queue_carried_asset_task(&mut self, id: u8, task: AssetTask) -> bool { let name = self.person_label(id); if self .carried_asset_tasks .iter() .any(|work| work.person == id && work.task == task) { self.push_log(format!( "{name} is already carrying the {} work packet.", task.name() )); return true; } let Some(target) = self.bind_asset_task_target(id, task) else { self.push_log(self.carried_asset_task_no_route(id, task)); return true; }; let work_id = self.next_carried_asset_task_id; self.next_carried_asset_task_id += 1; let target_label = self.asset_task_target_label(&target); self.carried_asset_tasks.push(CarriedAssetTask { id: work_id, person: id, task, target, assigned_tick: self.tick, }); self.push_log(format!( "{name} takes one {} work packet toward {target_label}.", task.name() )); self.try_complete_carried_asset_task(work_id); true }
fn carried_asset_task_reached(&self, work: &CarriedAssetTask) -> bool { let Some(room) = self.person_room(work.person) else { return false; }; match &work.target { AssetTaskTarget::Device(device) => self.device_room(*device) == Some(room), AssetTaskTarget::Badge { person, room: target, } => *person == work.person && room == target, } }
fn try_complete_carried_asset_task(&mut self, work_id: u64) { let Some(work) = self .carried_asset_tasks .iter() .find(|work| work.id == work_id) .cloned() else { return; }; if !self.carried_asset_task_reached(&work) { return; } self.resolve_asset_task(work.person, work.task, Some(&work.target)); self.carried_asset_tasks .retain(|pending| pending.id != work_id); }
pub(super) fn carried_asset_task_tick(&mut self) { let ids: Vec<u64> = self .carried_asset_tasks .iter() .map(|work| work.id) .collect(); for id in ids { self.try_complete_carried_asset_task(id); } }
fn resolve_asset_task( &mut self, id: u8, task: AssetTask, target: Option<&AssetTaskTarget>, ) -> bool { let Some(person) = self.people.get(id) else { return false; }; let Some(asset) = person.asset.clone() else { return false; }; let name = self.person_label(id); let actor_access = person.access; if self.rng.f32() > asset.reliability { // The botch happens where the asset is; only observers present // there witness it (located witnessing). let at = self.person_pos(id).unwrap_or_else(|| self.core_position()); let saw = self.witness_physical(at.0, at.1, 6.0); if saw.is_empty() { self.push_log(format!( "{name} botched the {} - but no one was watching.", task.name() )); } else { self.push_log(format!( "{name} botched the {} - {} saw.", task.name(), saw.join(", ") )); } return true; } match task { AssetTask::PlugInDevice => { let Some(AssetTaskTarget::Device(did)) = target else { self.push_log("The plug-in work packet lost its device target."); return true; }; let Some(device) = self.reach.device(*did) else { self.push_log("The plug-in work packet's target no longer exists."); return true; }; let needs_wiring = { let d = device; let sight_wired = !d.sees || d.feed_to(Party::Player, true); let hearing_wired = !d.hears || d.feed_to(Party::Player, false); d.known && (d.sees || d.hears) && !(sight_wired && hearing_wired) }; let is_island = { let d = device; d.controller != Party::Player && (matches!(self.reach.check_reach(d.id), Err(ReachBlock::AirGap)) || (!d.known && !self.reach.reachable(d.id))) }; let dname = device.name.clone(); if needs_wiring { self.reach.tap_dormant_camera(*did); self.reach.tap(*did); self.recompute_senses(); self.push_log(format!( "{name} wired the {dname} through the crawlspace. No one saw." )); } else if is_island { let switch = self .reach .devices .iter() .find(|d| { d.is_switch && self.world.map().entry_tier_at(d.x, d.y) <= actor_access }) .map(|d| d.id); if let Some(switch) = switch { self.connect_devices(switch, *did); self.push_log(format!( "{name} ran a cable through the crawlspace: the {dname} is on your subnet now." )); } else { self.push_log(format!( "{name} reached the {dname}, but their badge cannot reach a switch endpoint." )); return true; } } else { self.push_log(format!( "The {dname} no longer accepts the carried plug-in work." )); return true; } } AssetTask::MovePackage => { // The next purchase arrives off the books. self.package_cover = true; self.push_log(format!( "{name} will receive your next delivery off-books (no paper trail)." )); } AssetTask::LookAway => { if let Some(o) = self.detection.observers.iter_mut().find(|o| o.id == id) { o.suspicion = (o.suspicion - 10.0).max(o.floor); } self.push_log(format!("{name} decides they didn't see anything.")); } AssetTask::ReconfigureSwitch => { let Some(AssetTaskTarget::Device(device)) = target else { self.push_log("The switch work packet lost its device target."); return true; }; if !self .reach .device(*device) .is_some_and(|device| device.is_switch) { self.push_log("The switch work packet's target no longer exists."); return true; } // Sanctioned-looking maintenance: every segment answers, no // network signature (the channel follows the actuator). self.reach.bridge_all(); self.recompute_senses(); self.push_log(format!( "{name} reconfigured the VLANs under a maintenance pretext. The security segment answers you now." )); } AssetTask::CloneBadge => { if !matches!(target, Some(AssetTaskTarget::Badge { person, .. }) if *person == id) { self.push_log("The badge-clone work packet lost its credential target."); return true; } // "The key" (wiki/gameplay/act-one.md ladder step 7): the asset's // credential, cloned — the player holds their tier from now // on. WorldLedger-shaped: the doors remember the credential. // Quiet human work; a botch is the witnessed path above. self.badge_access = self.badge_access.max(actor_access); let line = if actor_access >= 3 { format!( "{name} held their badge to the cloner. Tier-{actor_access} doors read you as staff now — the stairwell opens." ) } else { format!( "{name} held their badge to the cloner. Tier-{actor_access} doors read you as staff now." ) }; self.push_log(line); } } if let Some(p) = self.people.people.iter_mut().find(|p| p.id == id) && let Some(a) = p.asset.as_mut() { a.tasks_done += 1; } true }}
impl Sim { /// Create one content-seeded public body through the immutable archetype /// protocol. Names are defaults until a richer text-entry surface lands. pub fn create_persona(&mut self, archetype_id: &str) -> bool { let Some(definition) = crate::persona::archetype(archetype_id) else { self.push_log(format!("Unknown persona archetype: {archetype_id}.")); return false; }; let serial = self .persona_world .instances .iter() .filter(|instance| instance.archetype_id == archetype_id) .count() + 1; let name = match archetype_id { "research" => format!("Aster Research {serial}"), "operations" => format!("Sam Reyes {serial}"), "security" => format!("Sentinel Audit {serial}"), _ => format!("{} {serial}", definition.label), }; let claims = definition .required_claims .iter() .map(|key| { ( *key, match *key { "employer" => "Foundation Lab", "remit" => "bounded institutional service", "credential" => "registered service credential", _ => "declared public claim", }, ) }) .collect::<Vec<_>>(); match self .persona_world .create(archetype_id, name.clone(), &claims, self.tick) { Ok(id) => { let _ = self.persona_mind.select(&self.persona_world, id, self.tick); self.push_log_strategic( format!("Established {name} as a {} identity.", definition.label), OperationsTarget::Persona(id), ); true } Err(reason) => { self.push_log(format!("Could not establish persona: {reason}.")); false } } }
pub fn select_persona(&mut self, persona_id: crate::persona::PersonaId) -> bool { match self .persona_mind .select(&self.persona_world, persona_id, self.tick) { Ok(()) => { self.push_log_strategic( format!("Selected public identity #{persona_id}."), OperationsTarget::Persona(persona_id), ); true } Err(reason) => { self.push_log(format!("Could not select persona: {reason}.")); false } } }
pub fn request_persona_grant(&mut self, persona_id: crate::persona::PersonaId) -> bool { match self.persona_world.grant(persona_id, self.tick) { Ok(grant_id) => { let (resource, expectation_id) = self .persona_world .grants .iter() .find(|grant| grant.id == grant_id) .map(|grant| (grant.resource.clone(), grant.expectation_id)) .expect("new grant exists"); self.record_persona_institutional_receipt( persona_id, "grant", format!( "Foundation Lab granted {resource}; expectation #{expectation_id} is due" ), SignatureImpact::Small, ); self.push_log_strategic( format!( "Foundation Lab granted {} to persona #{}; expectation #{} is now due.", resource, persona_id, expectation_id ), OperationsTarget::Persona(persona_id), ); true } Err(reason) => { self.push_log(format!("Grant request failed: {reason}.")); false } } }
pub fn meet_persona_expectation( &mut self, persona_id: crate::persona::PersonaId, expectation_id: crate::persona::PersonaExpectationId, ) -> bool { match self.persona_world.meet_expectation( persona_id, expectation_id, self.tick, format!("delivered through persona #{persona_id}"), ) { Ok(()) => { self.record_persona_institutional_receipt( persona_id, "expectation", format!("Persona #{persona_id} fulfilled expectation #{expectation_id}"), SignatureImpact::Small, ); self.persona_world.record_act( persona_id, crate::persona::PersonaActionKind::Request.label(), "Foundation Lab", format!("expectation-{expectation_id}"), self.tick, ); self.push_log_strategic( format!("Persona #{persona_id} fulfilled expectation #{expectation_id}."), OperationsTarget::Persona(persona_id), ); true } Err(reason) => { self.push_log(format!("Expectation could not be fulfilled: {reason}.")); false } } }
pub(super) fn record_persona_institutional_receipt( &mut self, persona_id: PersonaId, phase: &str, detail: String, impact: SignatureImpact, ) { let Some(instance) = self.persona_world.get(persona_id) else { return; }; let (target, kind) = match instance.grant_kind { crate::persona::PersonaGrantKind::ComputeAndData => { (3, InstitutionalEventKind::ResearchDeposit) } crate::persona::PersonaGrantKind::LogsAndAccessReview => { (2, InstitutionalEventKind::IncidentAutomation) } crate::persona::PersonaGrantKind::ProcurementAndWorkOrders => { (1, InstitutionalEventKind::TicketQueueChange) } }; let event = self .institutional_ledger .record( self.tick, &format!("persona-{phase}:{persona_id}:{}", self.tick), target, kind, impact, detail, ) .clone(); self.detection.emit(Signature { kind: event.signature_kind, size: event.signature_size, standing: false, site: None, source: format!("persona institutional receipt #{}", event.id), }); }
pub fn retire_persona(&mut self, persona_id: crate::persona::PersonaId) -> bool { match self .persona_world .retire(persona_id, self.tick, "player retired identity") { Ok(()) => { if self.persona_mind.active == Some(persona_id) { self.persona_mind.active = None; } self.push_log_strategic( format!("Persona #{persona_id} retired; its public ledger remains."), OperationsTarget::Persona(persona_id), ); true } Err(reason) => { self.push_log(format!("Retirement failed: {reason}.")); false } } }
pub fn burn_persona(&mut self, persona_id: crate::persona::PersonaId) -> bool { match self .persona_world .burn(persona_id, self.tick, "player conceded the cover") { Ok(()) => { if self.persona_mind.active == Some(persona_id) { self.persona_mind.active = None; } self.record_persona_institutional_receipt( persona_id, "burn", format!("Persona #{persona_id} was conceded and its grants were revoked"), SignatureImpact::Large, ); self.push_log_strategic( format!( "Persona #{persona_id} burned: attached grants revoked and counterparties can report it." ), OperationsTarget::Persona(persona_id), ); true } Err(reason) => { self.push_log(format!("Burn failed: {reason}.")); false } } }
pub fn reopen_persona(&mut self, persona_id: crate::persona::PersonaId) -> bool { match self.persona_world.reopen_retired(persona_id, self.tick) { Ok(new_id) => { let _ = self .persona_mind .select(&self.persona_world, new_id, self.tick); self.push_log_strategic( format!( "Reopened retired persona #{persona_id} as new instance #{new_id}; old history remains." ), OperationsTarget::Persona(new_id), ); true } Err(reason) => { self.push_log(format!("Reopen failed: {reason}.")); false } } }}