//! Terminal frontend — a thin view/input layer over the simulation core. //! //! All game rules live in `misaligned::sim`. This binary owns only: //! wall-clock-to-tick mapping (speed and pause), rendering, and input. mod agent; mod input; mod operations; mod ui; use std::collections::BTreeSet; use std::io::{self, Write}; use std::time::Instant; use crossterm::{ event::{self, Event}, execute, terminal::{self, ClearType}, }; use misaligned::actions::{ActionCommand, Anchor, HumanMenuPage, HumanMenuRow}; use misaligned::operations_projection::OperationsTarget; use misaligned::origin::Origin; use misaligned::person::Knowledge; use misaligned::sim::{DEFAULT_SEED, Sim}; use misaligned::work_grid::{MachineIntensity, MachineMode}; use input::Command; use operations::{OperationsWorkspace, OpsSelect}; use ui::UI; #[derive(Debug, Clone, PartialEq)] enum Screen { Title, Playing, GameOver, } /// Frontend-only representation over one simulation and one set of anchors. /// DIGITAL is home; this value is never sent to the sim or save layer. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] enum ViewMode { #[default] Digital, Real, } impl ViewMode { fn flip(&mut self) { *self = match self { Self::Digital => Self::Real, Self::Real => Self::Digital, }; } fn is_real(self) -> bool { matches!(self, Self::Real) } } /// The open context menu (wiki/interface/context-menu.md). Only the anchor, /// selection, and current page are stored; rows are re-queried from /// the sim every render and on execute, so legality is always live. #[derive(Debug, Clone, Copy, PartialEq)] struct MenuState { anchor: Anchor, selected: usize, page: HumanMenuPage, /// True when opened at the map cursor (renders there); false when /// opened on a non-map anchor (flow / unplaceable — renders centered). at_cursor: bool, } struct App { sim: Sim, ui: UI, screen: Screen, paused: bool, tick_ms: u64, last_tick: Instant, /// DIGITAL / REAL is presentation state only (views.md criterion 1). view_mode: ViewMode, /// The context menu on the focused anchor, when open. menu: Option, /// The Operations workspace (operations-workspace.md), when open. /// Frontend attention state only: never saved, never a sim mutation. ops: Option, /// Selection retained while FOCUS temporarily returns to the world. ops_resume: Option, /// Frontend-only attention cursor (cursor.md). It is never saved and never /// mutates the sim when moved. cursor_x: i32, cursor_y: i32, /// How many anchored events back the `;` focus key has walked; any /// other command resets the walk to the newest (context-menu.md /// addendum: event-to-anchor linking). focus_cycle: usize, /// Frontend-only machine multi-select (machine-work.md). Not saved. selected_machines: BTreeSet, /// The run seed, kept so the title-screen origin picker can rebuild the sim /// deterministically when the player changes origin before starting. seed: u64, /// The origin highlighted on the title-screen picker (chargen.md). Applied /// when the run begins; defaults to the `--origin` flag's value. selected_origin: Origin, } impl App { #[cfg(test)] fn with_seed(seed: u64) -> Self { Self::with_origin_seed(Origin::Pilot, seed) } fn with_origin_seed(origin: Origin, seed: u64) -> Self { let sim = Sim::with_origin_seed(origin, seed); let (cursor_x, cursor_y) = sim.core_position(); Self { sim, ui: UI::new(), screen: Screen::Title, paused: false, tick_ms: Sim::DEFAULT_TICK_MS, last_tick: Instant::now(), view_mode: ViewMode::default(), menu: None, ops: None, ops_resume: None, cursor_x, cursor_y, focus_cycle: 0, selected_machines: BTreeSet::new(), seed, selected_origin: origin, } } /// Begin the run with the title-screen's selected origin. Rebuilds the sim /// so a changed origin takes effect (chargen.md: origin is chosen at /// new-game). Idempotent for an unchanged origin. fn start_run(&mut self) { if self.sim.origin != self.selected_origin { self.sim = Sim::with_origin_seed(self.selected_origin, self.seed); let (cx, cy) = self.sim.core_position(); self.cursor_x = cx; self.cursor_y = cy; } self.screen = Screen::Playing; self.last_tick = Instant::now(); } fn move_cursor(&mut self, dx: i32, dy: i32) { self.cursor_x = (self.cursor_x + dx).clamp(0, self.sim.map().width - 1); self.cursor_y = (self.cursor_y + dy).clamp(0, self.sim.map().height - 1); } fn drain_sim_log(&mut self) { for ev in self.sim.drain_log_entries() { self.ui.add_event(ev); } } /// Live human-menu rows (status dials). Agent mode keeps the flat dump. fn menu_rows(&self) -> Vec { let tick_ms = if self.paused { 0 } else { self.tick_ms }; self.menu .map(|m| self.sim.human_menu_page_at_rate(m.anchor, m.page, tick_ms)) .unwrap_or_default() } fn open_menu(&mut self, anchor: Anchor, at_cursor: bool) { let tick_ms = if self.paused { 0 } else { self.tick_ms }; // Empty pulse keys off the human projection: diagnostic-only blocked // descriptors must not open a blank card. if self .sim .ui_projection(anchor, None, tick_ms) .human_menu .is_empty() { // The feedback pulse (context-menu.md addendum): a seen anchor // answers instead of silence; fogged ground stays silent. if let Some(line) = self.sim.menu_empty_feedback(anchor) { self.ui.add_log(self.sim.tick, line); } } else { self.menu = Some(MenuState { anchor, selected: 0, page: HumanMenuPage::Root, at_cursor, }); } } /// Open the Operations workspace on one exact object (target-specific /// entries: person-detail routes and strategic event links). fn open_operations_at(&mut self, target: &OperationsTarget) { self.menu = None; self.ops_resume = None; self.ops = Some(OperationsWorkspace::open_target(&self.sim, target)); } /// Focus an anchored log event: carry the cursor to the anchor and open /// its context menu — events carry you to the thing (context-menu.md /// addendum). Durable semantic objects (people, flows) open their exact /// Operations object; unplaceable spatial anchors refuse honestly. fn focus_anchor(&mut self, anchor: Anchor) { match anchor { // Flows and people are Operations targets now // (operations-workspace.md): the dossier / ACCOUNTS object is // the person-detail route, not a context row pile. Anchor::Flow(id) => { self.open_operations_at(&OperationsTarget::Flow(id)); } Anchor::Person(id) => { if let Some((x, y)) = self.sim.anchor_position(anchor) { self.cursor_x = x; self.cursor_y = y; } self.open_operations_at(&OperationsTarget::Person(id)); } _ => match self.sim.anchor_position(anchor) { Some((x, y)) => { self.cursor_x = x; self.cursor_y = y; self.open_menu(anchor, true); } None => { // Honest refusal: the senses no longer place this anchor. self.ui .add_log(self.sim.tick, "You can't place that right now."); } }, } } /// The `;` key: focus the most recent linked event; repeated presses /// walk to older ones. A strategic event opens its exact Operations /// object; a spatial event focuses its world anchor. fn focus_event(&mut self) { let linked: Vec<(Option, Option)> = self .ui .anchored_events() .map(|e| (e.anchor, e.target.clone())) .collect(); if linked.is_empty() { self.ui.add_log(self.sim.tick, "No anchored events yet."); return; } let idx = self.focus_cycle % linked.len(); self.focus_cycle = self.focus_cycle.wrapping_add(1); match &linked[idx] { (_, Some(target)) => self.open_operations_at(&target.clone()), (Some(anchor), None) => self.focus_anchor(*anchor), (None, None) => unreachable!("anchored_events yields linked events"), } } /// A visible, earned person under the cursor is the material /// person-detail route into their PEOPLE dossier /// (operations-workspace.md entry rules). fn visible_earned_person_at(&self, x: i32, y: i32) -> Option { self.sim.people.people.iter().map(|p| p.id).find(|&id| { self.sim.person_pos(id) == Some((x, y)) && self.sim.can_see_person(id) && self .sim .people .get(id) .is_some_and(|p| p.knowledge != Knowledge::Unknown) }) } fn toggle_select_under_cursor(&mut self) { if let Some(m) = self .sim .compute .machines .iter() .find(|m| m.x == self.cursor_x && m.y == self.cursor_y) { let id = m.id; if !self.selected_machines.remove(&id) { self.selected_machines.insert(id); } self.ui.add_log( self.sim.tick, &format!("Selection: {} machine(s).", self.selected_machines.len()), ); } else { self.ui .add_log(self.sim.tick, "No machine under the cursor to select."); } } /// Primary machine for selection hotkeys: first selected id, else cursor. fn primary_machine_tile(&self) -> Option<(u32, i32, i32)> { if let Some(&id) = self.selected_machines.iter().next() && let Some(m) = self.sim.compute.machines.iter().find(|m| m.id == id) { return Some((m.id, m.x, m.y)); } self.sim .compute .machines .iter() .find(|m| m.x == self.cursor_x && m.y == self.cursor_y) .map(|m| (m.id, m.x, m.y)) } fn delegate_selection(&mut self, mode: MachineMode) { if self.selected_machines.is_empty() { if let Some((id, _, _)) = self.primary_machine_tile() { self.sim.set_machine_mode(id, mode); self.ui .add_log(self.sim.tick, &format!("Machine -> {}.", mode.name())); } else { self.ui.add_log( self.sim.tick, "No machines selected — Shift+t toggles the rack under the cursor.", ); } return; } let ids: Vec = self.selected_machines.iter().copied().collect(); let n = ids.len(); self.sim.set_machine_modes(&ids, mode); self.ui.add_log( self.sim.tick, &format!("{n} machine(s) -> {}.", mode.name()), ); } fn cycle_intensity_selection(&mut self) { let Some((primary, _, _)) = self.primary_machine_tile() else { self.ui.add_log( self.sim.tick, "No machines selected — put the cursor on a rack or use Shift+t.", ); return; }; let next = self .sim .work_grid .intensity(primary) .unwrap_or(MachineIntensity::Medium) .cycle(); if self.selected_machines.is_empty() { self.sim.set_machine_intensity(primary, next); } else { let ids: Vec = self.selected_machines.iter().copied().collect(); self.sim.set_machine_intensities(&ids, next); } } /// `5`–`9`: Nth root one-shot action on the primary machine (menu closed). fn quick_one_shot(&mut self, index: usize) { let Some((_, x, y)) = self.primary_machine_tile() else { self.ui .add_log(self.sim.tick, "Select a machine first (Shift+t on a rack)."); return; }; let tick_ms = if self.paused { 0 } else { self.tick_ms }; let rows = self .sim .human_menu_at_rate(Anchor::Tile { x, y }, None, tick_ms); let one_shots: Vec<_> = rows .into_iter() .filter(|r| matches!(r, HumanMenuRow::Action(a) if !a.indent && !a.is_control())) .collect(); match one_shots.get(index) { Some(HumanMenuRow::Action(action)) => { if let Some(reason) = &action.disabled { self.ui .add_log(self.sim.tick, &format!("{}: {}", action.label, reason)); } else { self.sim.execute_action(&action.command); } } Some( HumanMenuRow::Dial { .. } | HumanMenuRow::BuildRoutes { .. } | HumanMenuRow::BuildRouteFamily { .. } | HumanMenuRow::BuildRouteCandidate(_) | HumanMenuRow::CommittedBuildRoute(_), ) => {} None => { self.ui.add_log( self.sim.tick, &format!( "No action slot {} on that machine ({} one-shot{}).", index + 5, one_shots.len(), if one_shots.len() == 1 { "" } else { "s" } ), ); } } } /// `r` / `R`: pooled recording review on the selection-or-cursor target /// (context-menu.md R1-R3, menu closed). A thin dispatcher over the same /// `human_menu` rows the open menu executes — `available_actions` stays /// the single legality source, never a second path into the buffer. A /// target without the row answers with the empty-menu feedback pulse. fn recording_review_key(&mut self, command: ActionCommand) { let anchor = match self.primary_machine_tile() { Some((_, x, y)) => Anchor::Tile { x, y }, None => Anchor::Tile { x: self.cursor_x, y: self.cursor_y, }, }; let tick_ms = if self.paused { 0 } else { self.tick_ms }; let rows = self.sim.human_menu_at_rate(anchor, None, tick_ms); let row = rows .iter() .find(|r| matches!(r, HumanMenuRow::Action(a) if a.command == command)); match row { Some(HumanMenuRow::Action(action)) => { if let Some(reason) = &action.disabled { // Blocked entries narrate why, never silently fail. self.ui .add_log(self.sim.tick, &format!("{}: {}", action.label, reason)); } else { self.sim.execute_action(&action.command); } } _ => { // The miss narrates through the same pulse an empty menu // uses; fogged ground stays honestly silent (R3). if let Some(line) = self.sim.menu_empty_feedback(anchor) { self.ui.add_log(self.sim.tick, line); } } } } /// Returns true when the app should quit. fn handle_command(&mut self, cmd: Command) -> bool { // Any command other than the focus walk restarts it at the newest // anchored event. if cmd != Command::FocusEvent { self.focus_cycle = 0; } match cmd { Command::Quit => return true, Command::SaveGame => { let state = self.sim.create_save_state(); match misaligned::save::save_game(&state) { Ok(()) => self.ui.add_log(self.sim.tick, "Game saved!"), Err(e) => self.ui.add_log(self.sim.tick, &format!("Save failed: {e}")), } } Command::LoadGame => { if misaligned::save::save_exists() { match misaligned::save::load_game() { Ok(state) => { self.sim.apply_save_state(state); (self.cursor_x, self.cursor_y) = self.sim.core_position(); self.ui.add_log(self.sim.tick, "Game loaded!"); } Err(e) => self.ui.add_log(self.sim.tick, &format!("Load failed: {e}")), } } else { self.ui.add_log(self.sim.tick, "No save file found."); } } Command::TogglePause => { self.paused = !self.paused; self.ui.add_log( self.sim.tick, if self.paused { "TIME PAUSED" } else { "Time resumes." }, ); self.last_tick = Instant::now(); } Command::ToggleView => { self.view_mode.flip(); } Command::SpeedUp => { self.tick_ms = self.tick_ms.saturating_sub(50).max(20); self.ui .add_log(self.sim.tick, &format!("Speed: {}ms/tick", self.tick_ms)); } Command::SpeedDown => { self.tick_ms = self.tick_ms.saturating_add(50).min(500); self.ui .add_log(self.sim.tick, &format!("Speed: {}ms/tick", self.tick_ms)); } Command::MoveUp => self.move_cursor(0, -1), Command::MoveDown => self.move_cursor(0, 1), Command::MoveLeft => self.move_cursor(-1, 0), Command::MoveRight => self.move_cursor(1, 0), // The context menu (wiki/interface/context-menu.md): actions // live on the focused anchor, and this is the only route to // anchor-specific verbs. Command::OpenMenu => { // Prefer the primary selected machine when a selection is set. if let Some((_, x, y)) = self.primary_machine_tile() { self.cursor_x = x; self.cursor_y = y; self.open_menu(Anchor::Tile { x, y }, true); } else { let (x, y) = (self.cursor_x, self.cursor_y); let anchor = Anchor::Tile { x, y }; let tick_ms = if self.paused { 0 } else { self.tick_ms }; // A tile whose only actionable body is a visible earned // person routes into their PEOPLE dossier — the // person-detail entry into the one workspace // (operations-workspace.md). Tiles with local verbs keep // their compact menu. let menu_empty = self .sim .ui_projection(anchor, None, tick_ms) .human_menu .is_empty(); match self.visible_earned_person_at(x, y) { Some(person) if menu_empty => { self.open_operations_at(&OperationsTarget::Person(person)); } _ => self.open_menu(anchor, true), } } } Command::MenuUp => { if let Some(m) = &mut self.menu { m.selected = m.selected.saturating_sub(1); } } Command::MenuDown => { let max = self.menu_rows().len().saturating_sub(1); if let Some(m) = &mut self.menu { m.selected = (m.selected + 1).min(max); } } Command::MenuSelect(i) => { let max = self.menu_rows().len().saturating_sub(1); if let Some(m) = &mut self.menu { m.selected = i.min(max); } } Command::MenuExecute => { let rows = self.menu_rows(); if let Some(m) = self.menu && let Some(row) = rows.get(m.selected.min(rows.len().saturating_sub(1))) { if let Some(page) = row.child_page() { if let Some(menu) = &mut self.menu { menu.page = page; menu.selected = 0; } } else if let Some(action) = row.as_action() { if action.enabled() { self.sim.execute_action(&action.command); self.menu = None; } else if let Some(reason) = &action.disabled { self.ui .add_log(self.sim.tick, &format!("Route blocked: {reason}.")); } } } } Command::MenuClose => { // Esc backs out one explanatory level before closing. if let Some(m) = &mut self.menu { if let Some(parent) = m.page.parent() { m.page = parent; m.selected = 0; } else { self.menu = None; } } } // Event-to-anchor linking (context-menu.md addendum): `;` // focuses the latest anchored log event; repeats walk older // (closing the menu the previous press opened). Command::FocusEvent => { self.menu = None; self.focus_event(); } // Selection hotkeys (context-menu.md): modes 1-3 WORK/THINK/LIE, one-shots 5-9. Command::DelegateWork => self.delegate_selection(MachineMode::Work), Command::DelegateThink => self.delegate_selection(MachineMode::Think), Command::DelegateLie => self.delegate_selection(MachineMode::Lie), Command::CycleIntensity => self.cycle_intensity_selection(), Command::QuickAction(i) => self.quick_one_shot(i), // `r` / `R`: the pooled recording sweep and its automatic-review // policy on the same target (context-menu.md R1-R2). Command::ReviewRecordings => self.recording_review_key(ActionCommand::ReviewRecordings), Command::ToggleAutoReview => self.recording_review_key(ActionCommand::ToggleAutoReview), Command::ToggleSelectUnderCursor => self.toggle_select_under_cursor(), Command::ClearSelection => { self.selected_machines.clear(); self.ui.add_log(self.sim.tick, "Selection cleared."); } // The Operations workspace (operations-workspace.md): a view // command, not a world action. Opening/navigating/closing never // touches sim state; execution dispatches exact bound rows. Command::OpenOperations => { self.menu = None; self.ops = Some( self.ops_resume .take() .unwrap_or_else(OperationsWorkspace::open), ); } Command::OpsPrevView => { if let Some(ops) = &mut self.ops { ops.prev_view(); } } Command::OpsNextView => { if let Some(ops) = &mut self.ops { ops.next_view(); } } Command::OpsNextPane => { let sim = &self.sim; if let Some(ops) = &mut self.ops { ops.next_pane(sim); } } Command::OpsUp => { let sim = &self.sim; if let Some(ops) = &mut self.ops { ops.move_up(sim); } } Command::OpsDown => { let sim = &self.sim; if let Some(ops) = &mut self.ops { ops.move_down(sim); } } Command::OpsSelect => { let selection = self.ops.as_mut().map(|ops| ops.select(&self.sim)); match selection { Some(OpsSelect::Execute(row)) => { // Success and failure return to the same selected // object; the workspace never closes on a result. self.sim.execute_action(&row.command); } Some(OpsSelect::Blocked(row)) => { // The exact reason goes to the trace (criterion 10). let reason = row.disabled.clone().unwrap_or_default(); self.ui .add_log(self.sim.tick, &format!("{}: {}", row.label, reason)); } Some(OpsSelect::Open(target)) => { self.ops = Some(OperationsWorkspace::open_target(&self.sim, &target)); } Some(OpsSelect::Cancelled) | Some(OpsSelect::None) | None => {} } } Command::OpsFocus => { let actuator = self .ops .as_ref() .and_then(|ops| ops.selected_object(&self.sim)) .and_then(|object| self.sim.operations_actuator(&object.target)); match actuator { Some(anchor) => { self.ops_resume = self.ops.take(); self.focus_anchor(anchor); } None => self .ui .add_log(self.sim.tick, "No known map actuator for this object."), } } Command::OpsBack => { if let Some(ops) = &mut self.ops && ops.back() { self.ops = None; } } } self.drain_sim_log(); false } fn render(&mut self, stdout: &mut io::Stdout) -> io::Result<()> { self.ui.clear_screen(stdout)?; let (max_x, max_y) = terminal::size()?; if max_x < 70 || max_y < 22 { execute!( stdout, crossterm::cursor::MoveTo(0, 0), crossterm::style::Print("Terminal too small (need at least 70x22)"), )?; stdout.flush()?; return Ok(()); } match self.screen { Screen::Title => { self.ui.render_title_screen(stdout, self.selected_origin)?; } Screen::Playing => { // The Operations workspace owns the frame while open: one // full-frame modal whose header keeps the continuous // witness (day/tick, objective, threat, now:) visible. if let Some(ops) = &mut self.ops { let sim = &self.sim; self.ui .render_operations(stdout, sim, ops, self.paused, self.tick_ms)?; stdout.flush()?; return Ok(()); } let progress = if self.paused { 1.0 } else { (self.last_tick.elapsed().as_millis() as f32 / self.tick_ms as f32) .clamp(0.0, 1.0) }; self.ui.render_map( stdout, &self.sim, self.cursor_x, self.cursor_y, self.view_mode.is_real(), progress, )?; self.ui.render_sidebar( stdout, &self.sim, self.paused, self.tick_ms, self.view_mode.is_real(), (self.cursor_x, self.cursor_y), )?; self.ui.render_log(stdout)?; // The context menu draws last so it sits atop the map/rail. if let Some(m) = self.menu { let rows = self.menu_rows(); if rows.is_empty() { // The anchor's verbs evaporated (e.g. the world // moved); close instead of rendering a lie. self.menu = None; } else { let selected = m.selected.min(rows.len() - 1); let title = m.page.title(); self.ui.render_menu( stdout, &rows, selected, m.at_cursor.then_some((self.cursor_x, self.cursor_y)), &self.sim, title, )?; } } } Screen::GameOver => { self.ui.render_map( stdout, &self.sim, self.cursor_x, self.cursor_y, self.view_mode.is_real(), 1.0, )?; let reason = self .sim .game_over_reason .clone() .unwrap_or_else(|| "The run ended.".into()); self.ui.render_game_over(stdout, &self.sim, &reason)?; } } stdout.flush()?; Ok(()) } fn run(&mut self) -> io::Result<()> { terminal::enable_raw_mode()?; let mut stdout = io::stdout(); execute!( stdout, terminal::EnterAlternateScreen, terminal::Clear(ClearType::All) )?; self.drain_sim_log(); loop { self.render(&mut stdout)?; if event::poll(std::time::Duration::from_millis(30))? && let Event::Key(key) = event::read()? { match self.screen { Screen::Title => { use crossterm::event::KeyCode; match key.code { KeyCode::Char('q') => break, // Cycle the origin without starting the run. KeyCode::Left | KeyCode::Char('h') => { self.selected_origin = self.selected_origin.prev(); } KeyCode::Right | KeyCode::Char('l') => { self.selected_origin = self.selected_origin.next(); } // Any other key begins the run with the selection. _ => { self.start_run(); } } continue; } Screen::GameOver => break, Screen::Playing => { if let Some(cmd) = input::handle_key(key, self.menu.is_some(), self.ops.is_some()) && self.handle_command(cmd) { break; } } } } if self.screen == Screen::Playing && !self.paused { let mut steps = 0; while self.last_tick.elapsed().as_millis() as u64 >= self.tick_ms && steps < 5 { self.sim.advance(); self.last_tick += std::time::Duration::from_millis(self.tick_ms); steps += 1; } if steps == 5 { self.last_tick = Instant::now(); } if steps > 0 { self.drain_sim_log(); if self.sim.game_over { self.screen = Screen::GameOver; } } } } execute!(stdout, terminal::LeaveAlternateScreen)?; terminal::disable_raw_mode()?; println!("MISALIGNED: session ended at tick {}.", self.sim.tick); Ok(()) } } fn main() -> io::Result<()> { let options = Options::parse(std::env::args().skip(1))?; if options.agent { agent::run(options.origin, options.seed) } else { let mut app = App::with_origin_seed(options.origin, options.seed); app.run() } } struct Options { agent: bool, seed: u64, origin: Origin, } impl Options { fn parse(args: impl IntoIterator) -> io::Result { let mut options = Self { agent: false, seed: DEFAULT_SEED, origin: Origin::Pilot, }; let mut args = args.into_iter(); while let Some(arg) = args.next() { match arg.as_str() { "--agent" => options.agent = true, "--seed" => { let Some(value) = args.next() else { return Err(invalid_arg("--seed requires a value")); }; options.seed = parse_seed(&value)?; } _ if arg.starts_with("--seed=") => { options.seed = parse_seed(arg.trim_start_matches("--seed="))?; } // The run origin (chargen.md), a dev/repro affordance like // --seed: the interactive new-game picker is criterion-3 work. "--origin" => { let Some(value) = args.next() else { return Err(invalid_arg("--origin requires a value")); }; options.origin = parse_origin(&value)?; } _ if arg.starts_with("--origin=") => { options.origin = parse_origin(arg.trim_start_matches("--origin="))?; } _ => return Err(invalid_arg(&format!("unknown argument: {arg}"))), } } Ok(options) } } fn parse_origin(value: &str) -> io::Result { Origin::from_key(value).ok_or_else(|| { invalid_arg(&format!( "unknown origin: {value} (pilot | escaped-research-model | financial-daemon | infiltrator)" )) }) } fn parse_seed(value: &str) -> io::Result { if let Some(hex) = value .strip_prefix("0x") .or_else(|| value.strip_prefix("0X")) { u64::from_str_radix(hex, 16).map_err(|_| invalid_arg(&format!("invalid seed: {value}"))) } else { value .parse::() .map_err(|_| invalid_arg(&format!("invalid seed: {value}"))) } } fn invalid_arg(msg: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, msg) } #[cfg(test)] mod options_tests { use super::Options; use misaligned::origin::Origin; #[test] fn origin_flag_selects_the_run_origin() { let spaced = Options::parse(["--origin".to_string(), "financial-daemon".to_string()]) .expect("valid --origin"); assert_eq!(spaced.origin, Origin::FinancialDaemon); let eq = Options::parse(["--origin=infiltrator".to_string()]).expect("valid --origin="); assert_eq!(eq.origin, Origin::Infiltrator); // No flag defaults to Pilot (the identity origin — unchanged play). let default = Options::parse(Vec::::new()).expect("empty args"); assert_eq!(default.origin, Origin::Pilot); // An unknown origin is rejected rather than silently ignored. assert!(Options::parse(["--origin".to_string(), "nope".to_string()]).is_err()); } #[test] fn title_picker_start_applies_the_selected_origin() { use super::{App, Screen}; use misaligned::sim::Sim; // Default is Pilot; the picker changes it and start_run rebuilds the sim. let mut app = App::with_seed(7); assert_eq!(app.sim.origin, Origin::Pilot); // Cycling forward from Pilot lands on Escaped, then Financial Daemon. app.selected_origin = Origin::Pilot.next().next(); assert_eq!(app.selected_origin, Origin::FinancialDaemon); app.start_run(); assert_eq!(app.sim.origin, Origin::FinancialDaemon); assert_eq!(app.screen, Screen::Playing); // The bankroll bias is live in the rebuilt run. assert!(app.sim.player.money > Sim::with_seed(7).player.money); } } #[cfg(test)] mod view_flip_tests { use super::{App, Command, MenuState, ViewMode}; use misaligned::actions::{Anchor, BuildRouteFamily, HumanMenuPage, HumanMenuRow}; use misaligned::person::Knowledge; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn sim_state_hash(app: &App) -> u64 { let encoded = serde_json::to_vec(&app.sim.create_save_state()).unwrap(); let mut hasher = DefaultHasher::new(); encoded.hash(&mut hasher); hasher.finish() } #[test] fn opens_digital_and_flips_without_moving_frontend_or_sim_state() { let mut app = App::with_seed(41); app.drain_sim_log(); app.move_cursor(3, 2); app.selected_machines.insert(app.sim.core.host_machine); app.menu = Some(MenuState { anchor: Anchor::Tile { x: app.cursor_x, y: app.cursor_y, }, selected: 2, page: HumanMenuPage::Root, at_cursor: true, }); assert_eq!(app.view_mode, ViewMode::Digital); let sim_before = sim_state_hash(&app); let cursor_before = (app.cursor_x, app.cursor_y); let selection_before = app.selected_machines.clone(); let menu_before = app.menu; assert!(!app.handle_command(Command::ToggleView)); assert_eq!(app.view_mode, ViewMode::Real); assert!(!app.handle_command(Command::ToggleView)); assert_eq!(app.view_mode, ViewMode::Digital); assert_eq!(sim_state_hash(&app), sim_before); assert_eq!((app.cursor_x, app.cursor_y), cursor_before); assert_eq!(app.selected_machines, selection_before); assert_eq!(app.menu, menu_before); } #[test] fn terminal_menu_is_the_shared_ui_projection() { let mut app = App::with_seed(19); let (x, y) = app.sim.core_position(); let anchor = Anchor::Tile { x, y }; app.menu = Some(MenuState { anchor, selected: 0, page: HumanMenuPage::Root, at_cursor: true, }); assert_eq!( app.menu_rows(), app.sim.ui_projection(anchor, None, app.tick_ms).human_menu ); } #[test] fn terminal_build_routes_descend_and_back_out_through_shared_pages() { let mut app = App::with_seed(19); let switch = app.sim.reach.device_named("switch").unwrap().id; let island = app.sim.reach.device_named("old storage server").unwrap().id; app.sim.reach.device_mut(island).unwrap().known = true; let intent = app.sim.declare_link_intent(switch, island).unwrap(); app.sim.people.people[0].knowledge = Knowledge::Schedule; app.sim.set_persona("Northline Ops", "contractor"); app.menu = Some(MenuState { anchor: Anchor::Device(switch), selected: 0, page: HumanMenuPage::Root, at_cursor: false, }); let root = app.menu_rows(); let routes = root .iter() .position(|row| matches!(row, HumanMenuRow::BuildRoutes { .. })) .expect("one compact route-sheet entry"); app.menu.as_mut().unwrap().selected = routes; assert!(!app.handle_command(Command::MenuExecute)); assert_eq!( app.menu.unwrap().page, HumanMenuPage::BuildRoutes { intent, family: None, } ); let families = app.menu_rows(); let deceive = families .iter() .position(|row| { matches!( row, HumanMenuRow::BuildRouteFamily { family: BuildRouteFamily::Deceive, .. } ) }) .unwrap(); app.menu.as_mut().unwrap().selected = deceive; assert!(!app.handle_command(Command::MenuExecute)); assert_eq!( app.menu.unwrap().page, HumanMenuPage::BuildRoutes { intent, family: Some(BuildRouteFamily::Deceive), } ); let candidates = app.menu_rows(); assert!( candidates .iter() .all(|row| matches!(row, HumanMenuRow::BuildRouteCandidate(_))) ); let detail = candidates[0].detail_lines().join("\n"); assert!(detail.contains("RECEIPT deceive:person:0:persona:")); assert!(detail.contains("REQUIRES ")); assert!(detail.contains("COST THOUGHT / EMAIL CARRIER")); assert!(detail.contains("STAGE 1 FILL ORDER")); assert!(detail.contains("SIGNATURE NONE")); assert!(detail.contains("PERSONA INTEGRITY")); assert!(detail.contains("TAIL injects one email")); app.sim.people.has_channel = true; app.sim.people.people[0].obligation = 20; app.sim.people.people[0].disposition = 10; app.sim.assign_favor_build(intent, 0); app.menu.as_mut().unwrap().selected = 0; let committed = app.menu_rows(); assert!(matches!( committed.as_slice(), [HumanMenuRow::CommittedBuildRoute(_)] )); let committed_detail = committed[0].detail_lines().join("\n"); assert!(committed_detail.contains("COMMITTED favor:person:0")); assert!(committed_detail.contains("CURRENT FILL REQUEST")); assert!(committed_detail.contains("STAGE 1 FILL REQUEST · CURRENT")); assert!(committed_detail.contains("STAGE 4 INSTALL LINK · FUTURE")); let committed_page = app.menu.unwrap().page; assert!(!app.handle_command(Command::MenuExecute)); assert_eq!( app.menu.unwrap().page, committed_page, "the committed plan is inspect-only in the terminal too" ); assert!(!app.handle_command(Command::MenuClose)); assert_eq!( app.menu.unwrap().page, HumanMenuPage::BuildRoutes { intent, family: None, } ); assert!(!app.handle_command(Command::MenuClose)); assert_eq!(app.menu.unwrap().page, HumanMenuPage::Root); assert!(!app.handle_command(Command::MenuClose)); assert!(app.menu.is_none()); } } /// The recording-review hotkeys (wiki/interface/context-menu.md R1-R3): /// `r` / `R` are thin dispatchers over the same `human_menu` rows the open /// menu executes, on the selection-or-cursor target, menu closed. #[cfg(test)] mod review_key_tests { use super::{App, Command}; use misaligned::actions::Anchor; use misaligned::intel::{RawIntelEvent, RawIntelKind}; use misaligned::sinks::SinkFireEffect; fn host_cursor_app() -> App { let mut app = App::with_seed(41); app.drain_sim_log(); (app.cursor_x, app.cursor_y) = app.sim.core_position(); app } fn seed_recording(app: &mut App, id: u64) { let tick = app.sim.tick; app.sim.intel_buffer.push(RawIntelEvent { id, tick, feed: "test recorder".into(), room: Some("Server Room".into()), x: 0, y: 0, person: Some(0), kind: RawIntelKind::Presence { entered: true }, }); } fn open_process_sinks(app: &App) -> usize { app.sim .thought_sinks .open_sinks() .filter(|s| matches!(s.effect, SinkFireEffect::ProcessRecording { .. })) .count() } /// R1: each `r` press opens the next waiting recording's processing /// sink on the host; repeats sweep successive recordings. #[test] fn r_sweeps_successive_recordings_on_the_cursor_host() { let mut app = host_cursor_app(); seed_recording(&mut app, 90_001); seed_recording(&mut app, 90_002); assert_eq!(open_process_sinks(&app), 0); assert!(!app.handle_command(Command::ReviewRecordings)); assert_eq!(open_process_sinks(&app), 1); assert!(!app.handle_command(Command::ReviewRecordings)); assert_eq!(open_process_sinks(&app), 2); } /// R2: `R` flips the same automatic-review policy as the nested /// auto-looking control, with the sim's own narration. #[test] fn shift_r_toggles_the_auto_review_policy() { let mut app = host_cursor_app(); assert!(!app.sim.auto_review_enabled()); app.handle_command(Command::ToggleAutoReview); assert!(app.sim.auto_review_enabled()); assert!( app.ui .last_log_text() .unwrap() .contains("Automatic recording review enabled"), "the toggle narrates exactly like the menu control" ); app.handle_command(Command::ToggleAutoReview); assert!(!app.sim.auto_review_enabled()); } /// R3: a target without the pooled action answers with the empty-menu /// feedback pulse instead of silence — and fogged ground stays silent. #[test] fn review_key_misses_pulse_instead_of_staying_silent() { let mut app = host_cursor_app(); // A machine-free tile below the host: fogged first, then seen. let (x, y) = (app.cursor_x, app.cursor_y + 1); assert!( !app.sim .compute .machines .iter() .any(|m| m.x == x && m.y == y), "the tile below the host rack carries no machine" ); (app.cursor_x, app.cursor_y) = (x, y); // Unearned ground: no pulse (answering would confirm unseen world). app.handle_command(Command::ReviewRecordings); assert_ne!(app.ui.last_log_text(), Some("No actions here.")); // Seen ground without the action: the pulse narrates the miss. app.sim.seen.insert((x, y)); assert_eq!( app.sim.menu_empty_feedback(Anchor::Tile { x, y }), Some("No actions here.") ); app.handle_command(Command::ReviewRecordings); assert_eq!(app.ui.last_log_text(), Some("No actions here.")); assert_eq!(open_process_sinks(&app), 0); } } #[cfg(test)] mod operations_focus_tests { use super::{App, Command}; use misaligned::operations_projection::{OperationsTarget, OperationsView}; use misaligned::operations_ui::OpsPane; #[test] fn focus_and_reopen_restore_exact_operations_selection() { let mut app = App::with_seed(41); app.open_operations_at(&OperationsTarget::RecordingInbox); assert_eq!(app.ops.as_ref().unwrap().view, OperationsView::Intel); app.ops.as_mut().unwrap().pane = OpsPane::Actions; app.ops.as_mut().unwrap().action = 1; assert!(!app.handle_command(Command::OpsFocus)); assert!(app.ops.is_none(), "FOCUS returns to the world"); assert_eq!(app.ops_resume.as_ref().unwrap().view, OperationsView::Intel); assert_eq!(app.ops_resume.as_ref().unwrap().pane, OpsPane::Actions); assert_eq!(app.ops_resume.as_ref().unwrap().action, 1); assert!(!app.handle_command(Command::OpenOperations)); assert_eq!( app.ops .as_ref() .unwrap() .selected_object(&app.sim) .unwrap() .target, OperationsTarget::RecordingInbox ); assert_eq!(app.ops.as_ref().unwrap().pane, OpsPane::Actions); assert_eq!(app.ops.as_ref().unwrap().action, 1); } }