//! Agent-mode drive for the terminal frontend. //! //! This is not a game-rule surface. It maps newline-delimited words onto the //! same `Sim` command methods as the raw terminal frontend, then renders a //! colorless text frame from the same fog/knowledge state. use std::collections::BTreeSet; use std::io::{self, BufRead, Write}; use misaligned::actions::{ActionCommand, ActionKind, ActionRole, Anchor, MenuRow, menu_rows}; use misaligned::detection::{Band, SignatureKind}; use misaligned::hall::RackSite; use misaligned::intel::{IntelRoutineClass, ReportLotToken}; use misaligned::operations_projection::{OperationsTarget, OperationsView, SchemeKind}; use misaligned::origin::Origin; use misaligned::person::{AssetKnowledge, AssetTask}; use misaligned::reach::{Party, ReachBlock}; use misaligned::research::Track; use misaligned::sim::{Fog, LogEvent, Nudge, Sim, TraceDebtStatus}; use misaligned::tiles::TileType; use misaligned::ui_projection::fact_source_label; use misaligned::work_grid::{MachineIntensity, MachineMode}; const WIDTH: usize = 70; /// Frame height. wiki/interface/agent-play.md sets 70x22 as the *minimum*; /// the sidebar (INSPECT/COMPUTE/CORE/DETECTION/DAY JOB, agent-play /// criterion 5) needs the taller frame to render in full — at 22 rows /// everything below COMPUTE was silently truncated. 60 -> 64 when the /// DETECTION section gained the trace-debt indicator and the /// audit/pilot clocks (detection.md criterion 3). const HEIGHT: usize = 64; const SIDEBAR_W: usize = 34; const MAP_W: usize = WIDTH - SIDEBAR_W - 1; const MAP_H: usize = HEIGHT - 9; const PANEL_INNER_W: usize = WIDTH - 2; pub fn run(origin: Origin, seed: u64) -> io::Result<()> { let stdin = io::stdin(); let mut stdout = io::BufWriter::new(io::stdout().lock()); let mut app = AgentApp::with_origin_seed(origin, seed); for line in stdin.lock().lines() { let line = line?; let exit = app.handle_line(&line, &mut stdout)?; stdout.flush()?; if exit { break; } } Ok(()) } #[derive(Debug, Clone, PartialEq, Eq)] enum FrameKind { Playing, /// One Operations view (operations-workspace.md): `intel`, `people`, /// `finance|ledger|accounts`, `schemes`, and `active` print the same /// renderer-neutral projection the human frontends consume. Operations(OperationsView), /// One exact strategic object inside an Operations view. This is the /// agent counterpart of opening a recursive drill-down target rather /// than redrawing the entire top-level rail. OperationsTarget(OperationsTarget), Reach, Research, GameOver, } /// One exact `actions`/`act` focus: a spatial anchor or a strategic /// Operations target (agent-play.md: both target families share the query /// and execution route). #[derive(Debug, Clone, PartialEq)] enum QueryTarget { Spatial(Anchor), Strategic(OperationsTarget), } #[derive(Debug, Clone, PartialEq, Eq)] enum Status { Ok, Err(String), } struct AgentApp { sim: Sim, log: Vec, frame: FrameKind, cursor_x: i32, cursor_y: i32, /// Frontend-only machine multi-select (machine-work.md). Not saved. selected_machines: BTreeSet, } /// A frontend-authored log line (no anchor: these are protocol chatter, /// not sim events about a thing). fn local_event(tick: u64, text: impl Into) -> LogEvent { LogEvent { tick, text: text.into(), anchor: None, target: None, } } impl AgentApp { #[cfg(test)] fn new(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, log: Vec::new(), frame: FrameKind::Playing, cursor_x, cursor_y, selected_machines: BTreeSet::new(), } } 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 handle_line(&mut self, line: &str, out: &mut impl Write) -> io::Result { let trimmed = line.trim(); let mut status = Status::Ok; let mut exit = false; let mut output = Vec::new(); let mut local_events = Vec::new(); if trimmed.is_empty() { status = Status::Err("empty command".into()); } else { let tokens: Vec<&str> = trimmed.split_whitespace().collect(); let verb = tokens[0].to_ascii_lowercase(); let allowed_after_game_over = matches!(verb.as_str(), "look" | "load" | "quit"); if self.sim.game_over && !allowed_after_game_over { status = Status::Err("run ended".into()); self.frame = FrameKind::GameOver; } else { match verb.as_str() { "wait" => match parse_wait(&tokens) { Ok(n) => { self.frame = FrameKind::Playing; for _ in 0..n { if self.sim.game_over { break; } self.sim.advance(); } } Err(e) => status = Status::Err(e), }, "up" | "north" => { self.frame = FrameKind::Playing; self.move_cursor(0, -1); } "down" | "south" => { self.frame = FrameKind::Playing; self.move_cursor(0, 1); } "left" | "west" => { self.frame = FrameKind::Playing; self.move_cursor(-1, 0); } "right" | "east" => { self.frame = FrameKind::Playing; self.move_cursor(1, 0); } "reach" => { self.frame = FrameKind::Reach; } // The six Operations inspection commands // (operations-workspace.md / agent-play.md A1): each // prints one view of the same renderer-neutral // projection the human frontends consume. `operations` // itself stays a THINK compatibility alias. "intel" if tokens.len() == 1 => { self.frame = FrameKind::Operations(OperationsView::Intel); } "intel" => match self.resolve_intel_target(&tokens[1..]) { Ok(target) => self.frame = FrameKind::OperationsTarget(target), Err(error) => status = Status::Err(error), }, "finance" | "ledger" | "accounts" => { self.frame = FrameKind::Operations(OperationsView::Accounts); } "schemes" => { self.frame = FrameKind::Operations(OperationsView::Schemes); } "active" => { self.frame = FrameKind::Operations(OperationsView::Active); } // Compatibility aliases. Authored input reuses TAP with // the ledger as its target: `tap ledger`. alias if ActionKind::Tap.accepts_alias(alias) => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.tap_accounting(); } // Compatibility aliases for canonical `review ledger`. alias if ActionKind::Review.accepts_alias(alias) => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.review_financial_records(); } "siphon" => match parse_flow_amount(&tokens, 50) { Ok((flow, amount)) => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.siphon_flow(flow, amount); } Err(e) => status = Status::Err(self.flow_arg_hint(&tokens, e)), }, "redirect" => match parse_flow_amount(&tokens, 25) { Ok((flow, amount)) => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.redirect_flow_to_slush(flow, amount); } Err(e) => status = Status::Err(self.flow_arg_hint(&tokens, e)), }, "inject" => match parse_optional_i32(&tokens, 300) { Ok(amount) => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim .inject_purchase_order(amount, "agent-command purchase order"); } Err(e) => status = Status::Err(e), }, root if root == "position" || ActionKind::PlaceWager.accepts_alias(root) => { match parse_optional_i32(&tokens, 100) { Ok(stake) => { self.frame = FrameKind::Operations(OperationsView::Schemes); self.sim.open_position(stake); } Err(e) => status = Status::Err(e), } } root if root == "sell-intel" || ActionKind::SellIntel.accepts_alias(root) => { // SELL binds one exact processed item or the exact // versioned lot token printed by INTEL. The implicit // "latest unsold" selection is retired // (operations-workspace.md criteria 4/12). self.frame = FrameKind::Operations(OperationsView::Intel); match tokens.get(1).map(|t| t.trim_start_matches('#')) { Some(raw) if raw.contains(':') => { match self.resolve_query(&["lot", raw]) { Ok(query) => { if let Err(error) = self.execute_named_action(query, ActionKind::SellIntel) { status = Status::Err(error); } } Err(error) => status = Status::Err(error), } } Some(raw) => match raw.parse::() { Ok(raw_id) => { self.sim.sell_intel(raw_id); } Err(_) => { status = Status::Err(format!( "usage: sell-intel (got {raw})" )); } }, None => { status = Status::Err( "usage: sell-intel — ids print in the intel frame".into(), ); } } } // The named schemes (wiki/mechanics/income.md) root if root == "egress" || ActionKind::OpenEgress.accepts_alias(root) => { self.frame = FrameKind::Operations(OperationsView::Schemes); self.sim.open_egress(); } "moonlight" => { self.frame = FrameKind::Operations(OperationsView::Schemes); match tokens.get(1).map(|t| t.to_ascii_lowercase()).as_deref() { None | Some("start") | Some("on") => { self.sim.start_moonlight(); } Some("stop") | Some("off") => { self.sim.stop_moonlight(); } Some(other) => { status = Status::Err(format!( "usage: moonlight [start|stop] (got {other})" )); } } } "auto-moonlight" => { self.frame = FrameKind::Operations(OperationsView::Schemes); match parse_on_off(&tokens) { Ok(on) => self.sim.set_auto_moonlight(on), Err(e) => status = Status::Err(e), } } "auto-wager" => { self.frame = FrameKind::Operations(OperationsView::Schemes); match tokens.get(1).map(|t| t.to_ascii_lowercase()) { Some(arg) if arg == "off" => self.sim.set_auto_wager(None), Some(arg) => match arg.parse::() { Ok(stake) => self.sim.set_auto_wager(Some(stake)), Err(_) => { status = Status::Err(format!( "usage: auto-wager |off (got {arg})" )); } }, None => self.sim.set_auto_wager(Some(100)), } } "research" => match tokens.get(1) { None => { self.frame = FrameKind::Research; } Some(_) => match parse_track(&tokens) { Ok(track) => { self.frame = FrameKind::Research; self.sim.set_research_track(track); } Err(e) => status = Status::Err(e), }, }, "scan" => { self.frame = FrameKind::Playing; self.sim.scan_network(); } "compromise" => { self.frame = FrameKind::Playing; self.sim.compromise_switch(); } "tap" if tokens.len() == 2 && tokens[1].eq_ignore_ascii_case("ledger") => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.tap_accounting(); } "tap" | "untap" | "take" => match self.resolve_device(&tokens[1..].join(" ")) { Ok(id) => { self.frame = FrameKind::Playing; match verb.as_str() { "tap" => self.sim.tap_device(id), "untap" => self.sim.untap_device(id), "take" => self.sim.take_device(id), _ => unreachable!(), }; } Err(e) => status = Status::Err(e), }, "salvage" => { self.frame = FrameKind::Playing; self.sim.salvage_nearest_to(self.cursor_x, self.cursor_y); } "buy" => { self.frame = FrameKind::Playing; self.sim.buy_rack_at(self.cursor_x, self.cursor_y); } "fallback" => { self.frame = FrameKind::Playing; self.sim.add_fallback_at(self.cursor_x, self.cursor_y); } "alloc" => { status = Status::Err( "alloc is retired — delegate work|think|lie".into(), ); } "people" => { self.frame = FrameKind::Operations(OperationsView::People); } "personas" => { self.frame = FrameKind::Operations(OperationsView::Personas); } "review" if tokens.len() == 2 && tokens[1].eq_ignore_ascii_case("ledger") => { self.frame = FrameKind::Operations(OperationsView::Accounts); self.sim.review_financial_records(); } "review" if tokens.len() >= 2 && tokens[1].eq_ignore_ascii_case("recordings") => { if tokens.len() == 2 { self.frame = FrameKind::Playing; self.sim.review_recordings(); } else { match self.resolve_query(&tokens[2..]) { Ok( query @ QueryTarget::Strategic( OperationsTarget::RawRecording { .. } | OperationsTarget::IntelCustody { .. } | OperationsTarget::RecordingInbox, ), ) => { if let Err(error) = self.execute_named_action(query, ActionKind::Review) { status = Status::Err(error); } } Ok(_) => { status = Status::Err( "review recordings target must be recording , custody , or intel inbox".into(), ); } Err(error) => status = Status::Err(error), } } } "auto-review" if tokens.len() == 1 => { self.frame = FrameKind::Playing; self.sim.toggle_auto_review(); } "favor" | "deceive" if tokens[1..] .iter() .any(|token| token.eq_ignore_ascii_case("build")) => { match self.build_request_from(&tokens[1..]) { Ok((intent, person, persona)) => { self.frame = FrameKind::Playing; if verb == "favor" { if persona.is_some() { status = Status::Err( "FAVOR routes do not bind a persona".into(), ); } else { self.sim.assign_favor_build(intent, person); } } else if let Some(persona) = persona { self.sim.forge_work_order_as(intent, person, persona); } else { self.sim.forge_work_order(intent, person); } } Err(e) => status = Status::Err(e), } } "message" | "favor" | "deceive" => match self.target_from(&tokens[1..]) { Ok(id) => { self.frame = FrameKind::Playing; match verb.as_str() { "message" => self.sim.message(id), "favor" => self.sim.favor(id), "deceive" => self.sim.deceive(id), _ => unreachable!(), } } Err(e) => status = Status::Err(e), }, "plot" | "start-plot" => { if tokens.len() < 3 { status = Status::Err("usage: plot ".into()); } else { let plot_id = tokens.last().expect("length checked"); match self.resolve_person(&tokens[1..tokens.len() - 1].join(" ")) { Ok(id) => { self.frame = FrameKind::Playing; self.sim.start_plot(id, plot_id); } Err(e) => status = Status::Err(e), } } } "choose" | "plot-choice" => { if tokens.len() < 3 { status = Status::Err("usage: choose ".into()); } else { let option_id = tokens.last().expect("length checked"); match self.resolve_person(&tokens[1..tokens.len() - 1].join(" ")) { Ok(id) => { self.frame = FrameKind::Playing; self.sim.choose_plot_for_person(id, option_id); } Err(e) => status = Status::Err(e), } } } "recruit" => match parse_recruit(&tokens) { Ok((name, reveal)) => match self.resolve_person(&name) { Ok(id) => { self.frame = FrameKind::Playing; self.sim.recruit(id, reveal); } Err(e) => status = Status::Err(e), }, Err(e) => status = Status::Err(e), }, "task" => match parse_task(&tokens) { Ok((name, task)) => match self.resolve_person(&name) { Ok(id) => { self.frame = FrameKind::Playing; self.sim.asset_task(id, task); } Err(e) => status = Status::Err(e), }, Err(e) => status = Status::Err(e), }, "persona" => { status = Status::Err( "persona creation moved to PERSONAS — use `personas`, then `actions archetype ` and `act archetype `" .into(), ); } root if root == "propose-link" || ActionKind::ProposeLink.accepts_alias(root) => { // propose-link — pin a network-link intent // (building.md). Declaring is inert until realized. let rest = tokens[1..].join(" "); match parse_link_pair(&rest, &self.sim) { Ok((a, b)) => { self.frame = FrameKind::Playing; self.sim.declare_link_intent(a, b); } Err(e) => status = Status::Err(e), } } "cancel-intent" => match tokens.get(1).and_then(|s| s.parse::().ok()) { Some(id) => { self.frame = FrameKind::Playing; self.sim.cancel_intent(id); } None => status = Status::Err("usage: cancel-intent ".into()), }, // Compatibility aliases. Canonical construction input is // `favor build ` or // `deceive build `. alias if ActionKind::Favor.accepts_alias(alias) => { match parse_intent_person(&tokens[1..], &self.sim) { Ok((intent, person)) => { self.frame = FrameKind::Playing; self.sim.assign_favor_build(intent, person); } Err(e) => status = Status::Err(e), } } alias if ActionKind::Deceive.accepts_alias(alias) => { match parse_intent_person(&tokens[1..], &self.sim) { Ok((intent, person)) => { self.frame = FrameKind::Playing; self.sim.forge_work_order(intent, person); } Err(e) => status = Status::Err(e), } } "intents" => { self.frame = FrameKind::Playing; output.extend(render_intents(&self.sim)); } "actions" | "menu" => { // The shared action query as a stable line protocol // (context-menu.md; operations-workspace.md; // agent-play.md): list the bound rows on one exact // target. No argument = the cursor tile; spatial // targets use `Sim::available_actions`; strategic // targets (`intel `, `books`, `account `, // `flow `, `scheme `, `run `) use the // Operations projection. match self.resolve_query(&tokens[1..]) { Ok(query) => match self.query_rows(&query) { Ok(rows) => output.extend(action_row_lines(&rows)), Err(e) => status = Status::Err(e), }, Err(e) => status = Status::Err(e), } } "act" | "execute" => { if tokens.len() < 2 { status = Status::Err( "usage: act [name|device name|person #N|#flow|intel |scheme |run ]".into(), ); } else { let row = tokens[1].parse::(); match (row, self.resolve_query(&tokens[2..])) { (Err(_), _) => { status = Status::Err(format!( "action row must be a positive number (got {})", tokens[1] )); } (_, Err(error)) => status = Status::Err(error), (Ok(0), _) => { status = Status::Err("action rows start at 1".into()); } (Ok(row), Ok(query)) => match self.query_rows(&query) { Err(e) => status = Status::Err(e), Ok(rows) => match rows.get(row - 1).cloned() { None => { status = Status::Err(format!( "action row {row} does not exist ({} rows)", rows.len() )) } Some(action) if !action.enabled() => { status = Status::Err(format!( "action row {row} is disabled: {}", action.disabled.unwrap_or_default() )); } Some(action) => { if let QueryTarget::Strategic(target) = &query { self.frame = FrameKind::OperationsTarget(target.clone()); } else { self.frame = FrameKind::Playing; } self.sim.execute_action(&action.command); } }, }, } } } "select" => match parse_select(&tokens[1..], &self.sim) { Ok(SelectCmd::Clear) => { self.selected_machines.clear(); self.frame = FrameKind::Playing; local_events.push(local_event(self.sim.tick, "Selection cleared.")); } Ok(SelectCmd::List) => { self.frame = FrameKind::Playing; if self.selected_machines.is_empty() { output.push("selected: (none)".into()); } else { let labels: Vec = self .selected_machines .iter() .filter_map(|id| { self.sim .compute .machines .iter() .find(|m| m.id == *id) .map(|m| format!("M{} {}", m.id, m.name)) }) .collect(); output.push(format!( "selected ({}): {}", labels.len(), labels.join(", ") )); } } Ok(SelectCmd::Box { x0, y0, x1, y1 }) => { self.frame = FrameKind::Playing; let ids = self.sim.machines_in_rect(x0, y0, x1, y1); self.selected_machines.clear(); self.selected_machines.extend(ids.iter().copied()); local_events.push(local_event( self.sim.tick, format!("Selected {} machine(s).", self.selected_machines.len()), )); } Ok(SelectCmd::Add(id)) => { self.frame = FrameKind::Playing; self.selected_machines.insert(id); local_events.push(local_event( self.sim.tick, format!("Selected M{id} ({} total).", self.selected_machines.len()), )); } Ok(SelectCmd::Toggle(id)) => { self.frame = FrameKind::Playing; if !self.selected_machines.remove(&id) { self.selected_machines.insert(id); } local_events.push(local_event( self.sim.tick, format!( "Selection now {} machine(s).", self.selected_machines.len() ), )); } Err(e) => status = Status::Err(e), }, "delegate" => { match parse_delegate(&tokens[1..], &self.sim, &self.selected_machines) { Ok(DelegateCmd::One(machine, mode)) => { self.frame = FrameKind::Playing; self.sim.set_machine_mode(machine, mode); } Ok(DelegateCmd::Selected(mode)) => { self.frame = FrameKind::Playing; if self.selected_machines.is_empty() { status = Status::Err( "no selection — select box x0 y0 x1 y1, or select add " .into(), ); } else { let ids: Vec = self.selected_machines.iter().copied().collect(); self.sim.set_machine_modes(&ids, mode); } } Err(e) => status = Status::Err(e), } } "intensity" => match parse_intensity(&tokens[1..], &self.sim) { Ok(IntensityCmd::One(machine, intensity)) => { self.frame = FrameKind::Playing; self.sim.set_machine_intensity(machine, intensity); } Ok(IntensityCmd::Selected(intensity)) => { self.frame = FrameKind::Playing; if self.selected_machines.is_empty() { status = Status::Err( "no selection — select box x0 y0 x1 y1, or select add " .into(), ); } else { let ids: Vec = self.selected_machines.iter().copied().collect(); self.sim.set_machine_intensities(&ids, intensity); } } Err(error) => status = Status::Err(error), }, "focus" => { // Event-to-anchor linking (agent-play.md): `focus // last` jumps the cursor to the most recent anchored // event's place and lists its actions — the agent // equivalent of clicking an anchored log line. match tokens.get(1).map(|t| t.to_ascii_lowercase()).as_deref() { None | Some("last") => match self.focus_last() { Ok(lines) => { self.frame = FrameKind::Playing; output.extend(lines); } Err(e) => status = Status::Err(e), }, Some(other) => { status = Status::Err(format!("usage: focus last (got {other})")); } } } "look" => {} "save" => { self.frame = FrameKind::Playing; let state = self.sim.create_save_state(); match misaligned::save::save_game(&state) { Ok(()) => local_events.push(local_event(self.sim.tick, "Game saved!")), Err(e) => local_events .push(local_event(self.sim.tick, format!("Save failed: {e}"))), } } "load" => { self.frame = FrameKind::Playing; 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(); local_events.push(local_event(self.sim.tick, "Game loaded!")); } Err(e) => { local_events.push(local_event( self.sim.tick, format!("Load failed: {e}"), )); } } } else { local_events.push(local_event(self.sim.tick, "No save file found.")); } } "objective" => { output.extend(objective_lines(&self.sim)); } "read" => { output.extend(read_lines(&self.sim)); } "help" => { output.extend(help_lines()); } "quit" => { exit = true; } _ => status = Status::Err(format!("unknown command: {trimmed}")), } } } if self.sim.game_over { self.frame = FrameKind::GameOver; } let mut events = self.sim.drain_log_entries(); events.append(&mut local_events); events.sort_by_key(|e| e.tick); self.log.extend(events.iter().cloned()); if self.log.len() > 100 { let keep_from = self.log.len() - 100; self.log.drain(..keep_from); } write_block( out, &self.sim, AgentFrame { log: &self.log, frame: self.frame.clone(), events: &events, output: &output, status: &status, cursor: (self.cursor_x, self.cursor_y), }, )?; Ok(exit) } /// `focus last`: follow the most recent linked event (the `@...` suffix /// lines; agent-play.md). A strategic event prints its exact Operations /// object without a cursor move; a placeable spatial anchor moves the /// cursor and answers with the anchor's `actions:` lines. Targets the /// senses/knowledge can no longer place are refused honestly. fn focus_last(&mut self) -> Result, String> { let (anchor, target) = self .log .iter() .rev() .find(|e| e.anchor.is_some() || e.target.is_some()) .map(|e| (e.anchor, e.target.clone())) .ok_or_else(|| "no anchored events yet".to_string())?; if let Some(target) = target { let rows = self.query_rows(&QueryTarget::Strategic(target.clone()))?; self.frame = FrameKind::OperationsTarget(target); return Ok(action_row_lines(&rows)); } let anchor = anchor.expect("linked event carries an anchor or target"); if let Anchor::Flow(_) = anchor { return Ok(self.actions_lines(anchor)); } match self.sim.anchor_position(anchor) { Some((x, y)) => { self.cursor_x = x; self.cursor_y = y; Ok(self.actions_lines(anchor)) } None => Err("that event's anchor can't be placed right now".into()), } } /// Resolve the `actions`/`act` focus (agent-play.md). No tokens = the /// cursor tile. Strategic forms name exact Operations targets: /// `intel `, `recording `, `intel inbox`, `books`, `account `, `flow `, /// `scheme moonlight|wager`, `run `. `#N` or a bare number = a known /// flow; `person #N` selects an opaque person. Otherwise a name prefix /// matches a person before a device so `actions Marcus` does not /// silently bind to Marcus's phone; `device ` forces the other /// side of a genuine collision. fn resolve_query(&self, tokens: &[&str]) -> Result { if tokens.is_empty() { return Ok(QueryTarget::Spatial(Anchor::Tile { x: self.cursor_x, y: self.cursor_y, })); } let query = tokens.join(" "); let q = query.trim(); let lower = q.to_ascii_lowercase(); if lower.starts_with("person ") { return self .resolve_person(q) .map(|id| QueryTarget::Strategic(OperationsTarget::Person(id))); } if let Some(rest) = lower.strip_prefix("persona ") { return rest .trim() .trim_start_matches('#') .parse::() .map(|id| QueryTarget::Strategic(OperationsTarget::Persona(id))) .map_err(|_| format!("usage: persona (got {rest})")); } if let Some(id) = lower.strip_prefix("archetype ") { return Ok(QueryTarget::Strategic(OperationsTarget::PersonaArchetype( id.trim().into(), ))); } if let Some(device) = lower.strip_prefix("device ") { return self .resolve_device(device) .map(|id| QueryTarget::Spatial(Anchor::Device(id))); } if let Some(rest) = lower.strip_prefix("intel ") { let rest = rest.trim(); if rest == "inbox" { return Ok(QueryTarget::Strategic(OperationsTarget::RecordingInbox)); } return rest .trim_start_matches('#') .parse::() .map(|raw_id| QueryTarget::Strategic(OperationsTarget::Intel { raw_id })) .map_err(|_| format!("usage: intel |inbox (got {rest})")); } if let Some(rest) = lower.strip_prefix("recording ") { return rest .trim_start_matches('#') .parse::() .map(|raw_id| QueryTarget::Strategic(OperationsTarget::RawRecording { raw_id })) .map_err(|_| format!("usage: recording (got {rest})")); } if let Some(rest) = lower.strip_prefix("stream ") { return rest .trim_start_matches('#') .parse::() .map(|stream_id| { QueryTarget::Strategic(OperationsTarget::IntelStream { stream_id }) }) .map_err(|_| format!("usage: stream (got {rest})")); } if let Some(rest) = lower.strip_prefix("lot ") { let (stream, snapshot) = rest.split_once(':').ok_or_else(|| { format!("usage: lot :@ (got {rest})") })?; let (generation, revision) = snapshot.split_once('@').ok_or_else(|| { format!("usage: lot :@ (got {rest})") })?; let token = ReportLotToken { stream_id: stream .parse() .map_err(|_| "invalid lot stream id".to_string())?, generation: generation .parse() .map_err(|_| "invalid lot generation".to_string())?, revision: revision .parse() .map_err(|_| "invalid lot revision".to_string())?, }; return Ok(QueryTarget::Strategic(OperationsTarget::IntelLot { token })); } if let Some(rest) = lower.strip_prefix("knowledge ") { let (person, class) = rest.split_once(':').ok_or_else(|| { format!("usage: knowledge :sighting|schedule (got {rest})") })?; let person = person .trim_start_matches('#') .parse::() .map_err(|_| "invalid knowledge person id".to_string())?; let class = match class { "sighting" | "sightings" => IntelRoutineClass::Sighting, "schedule" | "schedules" => IntelRoutineClass::Schedule, _ => return Err(format!("unknown knowledge class: {class}")), }; return Ok(QueryTarget::Strategic(OperationsTarget::IntelKnowledge { person, class, })); } if let Some(rest) = lower.strip_prefix("custody ") { return rest .trim_start_matches('#') .parse::() .map(|node_id| QueryTarget::Strategic(OperationsTarget::IntelCustody { node_id })) .map_err(|_| format!("usage: custody (got {rest})")); } if lower == "books" || lower == "account books" { return Ok(QueryTarget::Strategic(OperationsTarget::Books)); } if lower == "assurance" || lower == "assurance office" { return Ok(QueryTarget::Strategic(OperationsTarget::AssuranceOffice)); } if let Some(rest) = lower.strip_prefix("account ") { return rest .trim() .trim_start_matches('#') .parse::() .map(|id| QueryTarget::Strategic(OperationsTarget::Account(id))) .map_err(|_| format!("usage: account |books (got {rest})")); } if let Some(rest) = lower.strip_prefix("flow ") { return rest .trim() .trim_start_matches('#') .parse::() .map(|id| QueryTarget::Strategic(OperationsTarget::Flow(id))) .map_err(|_| format!("usage: flow (got {rest})")); } if let Some(rest) = lower.strip_prefix("scheme ") { return match rest.trim() { "moonlight" => Ok(QueryTarget::Strategic(OperationsTarget::Scheme( SchemeKind::Moonlight, ))), "wager" | "the-wager" => Ok(QueryTarget::Strategic(OperationsTarget::Scheme( SchemeKind::Wager, ))), other => Err(format!("usage: scheme moonlight|wager (got {other})")), }; } if let Some(rest) = lower.strip_prefix("run ") { return rest .trim() .trim_start_matches('#') .parse::() .map(|index| QueryTarget::Strategic(OperationsTarget::ActivePlotRun { index })) .map_err(|_| format!("usage: run (got {rest})")); } if let Some(id) = q .strip_prefix('#') .or(Some(q)) .and_then(|s| s.parse::().ok()) { if self.sim.accounts.known_flow_ids().contains(&id) { return Ok(QueryTarget::Strategic(OperationsTarget::Flow(id))); } return Err(format!("no known flow #{id}")); } if let Ok(id) = self.resolve_person(q) { return Ok(QueryTarget::Strategic(OperationsTarget::Person(id))); } match self.resolve_device(q) { Ok(id) => Ok(QueryTarget::Spatial(Anchor::Device(id))), Err(_) => Err(format!("no device, person, or flow matches '{query}'")), } } /// Resolve the argument to `intel `. The recursive target /// namespaces stay explicit because an exact raw intel id, custody node /// id, and stream id may all have the same numeric value. fn resolve_intel_target(&self, tokens: &[&str]) -> Result { if tokens.is_empty() { return Err( "usage: intel [|inbox|recording |custody |stream |lot |knowledge :]" .into(), ); } let query = if tokens.len() == 1 { let token = tokens[0].trim(); if token.eq_ignore_ascii_case("inbox") { QueryTarget::Strategic(OperationsTarget::RecordingInbox) } else { let raw_id = token .trim_start_matches('#') .parse::() .map_err(|_| format!("unknown intel target: {token}"))?; QueryTarget::Strategic(OperationsTarget::Intel { raw_id }) } } else { self.resolve_query(tokens)? }; let QueryTarget::Strategic(target) = query else { return Err( "intel target must name canonical intel custody, not a world anchor".into(), ); }; if target.home_view() != OperationsView::Intel { return Err(format!( "{} is not an intel target", target_query_id(&target) )); } self.sim .operations_object(&target) .ok_or_else(|| format!("no known object {}", target_query_id(&target)))?; Ok(target) } /// One target family's bound rows: spatial anchors use the shared /// ui_projection; strategic targets use the Operations projection. Both /// answer with the exact rows execution dispatches — no agent-only /// legality (agent-play.md A2). fn query_rows(&self, query: &QueryTarget) -> Result, String> { match query { QueryTarget::Spatial(anchor) => { Ok(menu_rows(&self.sim.ui_projection(*anchor, None, 0).actions)) } QueryTarget::Strategic(target) => { let object = self .sim .operations_object(target) .ok_or_else(|| format!("no known object {}", target_query_id(target)))?; Ok(menu_rows(&object.actions)) } } } /// Execute the same enabled bound row a named protocol command denotes. /// This keeps convenience spellings from gaining agent-only target or /// legality rules (agent-play.md A2/A5). fn execute_named_action(&mut self, query: QueryTarget, kind: ActionKind) -> Result<(), String> { let row = self .query_rows(&query)? .into_iter() .find(|row| row.command.kind() == kind) .ok_or_else(|| format!("that target has no {} action", kind.definition().canonical))?; if !row.enabled() { return Err(format!( "{} is disabled: {}", kind.definition().canonical, row.disabled.unwrap_or_default() )); } match &query { QueryTarget::Strategic(target) => { self.frame = FrameKind::OperationsTarget(target.clone()); } QueryTarget::Spatial(_) => self.frame = FrameKind::Playing, } self.sim.execute_action(&row.command); Ok(()) } /// The stable line format (agent-play.md): one `actions:` line per menu /// row (see [`action_row_lines`]). fn actions_lines(&self, anchor: Anchor) -> Vec { let projection = self.sim.ui_projection(anchor, None, 0); action_row_lines(&menu_rows(&projection.actions)) } /// Enrich a bad `siphon`/`redirect` argument with the nearest valid /// verb (agent-play.md: unknown targets answer `-- err` naming the /// candidates). Person names are not flow ids; leverage servicing lives /// on the person's authored plot rows. fn flow_arg_hint(&self, tokens: &[&str], err: String) -> String { let Some(arg) = tokens.get(1) else { return err; }; match self.resolve_person(arg) { Ok(_) => format!( "{err} — flows are #N ids from the finance frame, not people; \ person verbs are message/favor/plot/deceive" ), Err(_) => format!( "{err} — flow ids are the #N printed by the finance frame \ (tap ledger then review ledger reveals them)" ), } } fn target_from(&self, tokens: &[&str]) -> Result { if tokens.is_empty() { return Err("missing person target".into()); } self.resolve_person(&tokens.join(" ")) } fn build_request_from(&self, tokens: &[&str]) -> Result<(u64, u8, Option), String> { let Some(build_at) = tokens .iter() .position(|token| token.eq_ignore_ascii_case("build")) else { return Err("usage: favor|deceive build ".into()); }; if build_at == 0 || !(build_at + 2..=build_at + 3).contains(&tokens.len()) { return Err("usage: favor build | \ deceive build [persona:]" .into()); } let person = self.resolve_person(&tokens[..build_at].join(" "))?; let intent = tokens[build_at + 1] .parse::() .map_err(|_| format!("bad intent id: {}", tokens[build_at + 1]))?; let persona = tokens .get(build_at + 2) .map(|token| { let (_, value) = token .split_once(':') .filter(|(prefix, _)| prefix.eq_ignore_ascii_case("persona")) .ok_or_else(|| format!("expected persona:, got {token}"))?; value .trim_start_matches('#') .parse::() .map_err(|_| format!("bad persona id: {token}")) }) .transpose()?; Ok((intent, person, persona)) } fn resolve_device(&self, query: &str) -> Result { let q = query.trim().to_ascii_lowercase(); if q.is_empty() { return Err("missing device target".into()); } let matches: Vec<_> = self .sim .reach .known() .filter(|d| { let name = d.name.to_ascii_lowercase(); name.starts_with(&q) || name.split_whitespace().any(|w| w.starts_with(&q)) }) .collect(); match matches.as_slice() { [] => Err(format!("unknown device: {query}")), [d] => Ok(d.id), many => Err(format!( "ambiguous device '{query}': {}", many.iter() .map(|d| d.name.as_str()) .collect::>() .join(", ") )), } } fn resolve_person(&self, query: &str) -> Result { let q = query.trim().to_ascii_lowercase(); if q.is_empty() { return Err("missing person target".into()); } // Opaque id forms the frame prints while knowledge is Unknown: // "0", "#0", "person #0", "person 0". if let Some(id) = parse_person_id_query(&q) && self.sim.people.get(id).is_some() { return Ok(id); } let matches: Vec<_> = self .sim .people .people .iter() .filter(|p| person_matches(&self.sim.person_label(p.id), &q)) .collect(); match matches.as_slice() { [] => Err(format!("unknown person: {query}")), [p] => Ok(p.id), many => Err(format!( "ambiguous person '{query}': {}", many.iter() .map(|p| self.sim.person_label(p.id)) .collect::>() .join(", ") )), } } } fn resolve_machine(sim: &Sim, query: &str) -> Result { let q = query.trim().to_ascii_lowercase(); if q.is_empty() { return Err("missing machine target".into()); } if let Some(id) = q .strip_prefix('m') .or(Some(q.as_str())) .and_then(|s| s.parse::().ok()) && sim.compute.machines.iter().any(|m| m.id == id) { return Ok(id); } let matches: Vec<_> = sim .compute .machines .iter() .filter(|m| { let name = m.name.to_ascii_lowercase(); name.starts_with(&q) || name.split_whitespace().any(|w| w.starts_with(&q)) }) .collect(); match matches.as_slice() { [] => Err(format!("unknown machine: {query}")), [m] => Ok(m.id), many => Err(format!( "ambiguous machine '{query}': {}", many.iter() .map(|m| format!("M{} {}", m.id, m.name)) .collect::>() .join(", ") )), } } fn parse_machine_mode(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { "work" | "day" | "dayjob" | "day-job" | "job" => Ok(MachineMode::Work), "think" | "research" | "res" | "operations" | "operation" | "ops" => Ok(MachineMode::Think), "lie" | "conceal" | "concealment" | "hide" => Ok(MachineMode::Lie), other => Err(format!("unknown mode '{other}' (use work, think, lie)")), } } fn parse_machine_intensity(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { "light" | "low" | "l" => Ok(MachineIntensity::Light), "medium" | "med" | "m" => Ok(MachineIntensity::Medium), "hard" | "high" | "h" => Ok(MachineIntensity::Hard), other => Err(format!( "unknown intensity '{other}' (use light, medium, hard)" )), } } enum SelectCmd { Clear, List, Box { x0: i32, y0: i32, x1: i32, y1: i32 }, Add(u32), Toggle(u32), } fn parse_select(tokens: &[&str], sim: &Sim) -> Result { if tokens.is_empty() { return Ok(SelectCmd::List); } match tokens[0].to_ascii_lowercase().as_str() { "clear" | "none" => Ok(SelectCmd::Clear), "list" | "show" => Ok(SelectCmd::List), "box" => { if tokens.len() != 5 { return Err("usage: select box ".into()); } let parse = |s: &str| { s.parse::() .map_err(|_| format!("invalid coordinate: {s}")) }; Ok(SelectCmd::Box { x0: parse(tokens[1])?, y0: parse(tokens[2])?, x1: parse(tokens[3])?, y1: parse(tokens[4])?, }) } "add" => { if tokens.len() < 2 { return Err("usage: select add ".into()); } Ok(SelectCmd::Add(resolve_machine( sim, &tokens[1..].join(" "), )?)) } "toggle" => { if tokens.len() < 2 { return Err("usage: select toggle ".into()); } Ok(SelectCmd::Toggle(resolve_machine( sim, &tokens[1..].join(" "), )?)) } other => Err(format!( "usage: select [list|clear|box x0 y0 x1 y1|add |toggle ] (got {other})" )), } } enum DelegateCmd { One(u32, MachineMode), Selected(MachineMode), } fn parse_delegate( tokens: &[&str], sim: &Sim, _selected: &BTreeSet, ) -> Result { if tokens.is_empty() { return Err("usage: delegate ".into()); } if tokens.len() == 1 { // `delegate research` with an implied selection let mode = parse_machine_mode(tokens[0])?; return Ok(DelegateCmd::Selected(mode)); } let mode = parse_machine_mode(tokens.last().unwrap())?; let target = tokens[..tokens.len() - 1].join(" "); if target.eq_ignore_ascii_case("selected") || target.eq_ignore_ascii_case("sel") { return Ok(DelegateCmd::Selected(mode)); } Ok(DelegateCmd::One(resolve_machine(sim, &target)?, mode)) } enum IntensityCmd { One(u32, MachineIntensity), Selected(MachineIntensity), } fn parse_intensity(tokens: &[&str], sim: &Sim) -> Result { if tokens.len() < 2 { return Err("usage: intensity light|medium|hard".into()); } let intensity = parse_machine_intensity(tokens.last().unwrap())?; let target = tokens[..tokens.len() - 1].join(" "); if target.eq_ignore_ascii_case("selected") || target.eq_ignore_ascii_case("sel") { return Ok(IntensityCmd::Selected(intensity)); } Ok(IntensityCmd::One(resolve_machine(sim, &target)?, intensity)) } struct AgentFrame<'a> { log: &'a [LogEvent], frame: FrameKind, events: &'a [LogEvent], output: &'a [String], status: &'a Status, cursor: (i32, i32), } /// The stable link suffix on drained event lines (agent-play.md, /// event-to-target linking): strategic events prefer their exact /// Operations target (` @intel(id)`, ` @account(id)`, ` @flow(id)`, /// ` @scheme(id)`, ` @run(id)`); spatial events keep ` @tile(x,y)`, /// ` @device(id)`, ` @person(id)`. Ids are stable opaque handles printed by /// their owning Operations frame — `focus last` consumes them for you. /// Unlinked lines carry no suffix. fn event_suffix(ev: &LogEvent) -> String { if let Some(target) = &ev.target && let Some(suffix) = target.agent_suffix() { return format!(" {suffix}"); } anchor_suffix(ev.anchor) } fn anchor_suffix(anchor: Option) -> String { match anchor { None => String::new(), Some(Anchor::Tile { x, y }) => format!(" @tile({x},{y})"), Some(Anchor::Device(id)) => format!(" @device({id})"), Some(Anchor::Person(id)) => format!(" @person({id})"), Some(Anchor::Flow(id)) => format!(" @flow({id})"), } } /// The input spelling that queries one strategic target back /// (`actions ` / `act `). fn target_query_id(target: &OperationsTarget) -> String { match target { OperationsTarget::Intel { raw_id } => format!("intel {raw_id}"), OperationsTarget::IntelStream { stream_id } => format!("stream {stream_id}"), OperationsTarget::IntelLot { token } => format!("lot {}", token.label()), OperationsTarget::IntelKnowledge { person, class } => format!( "knowledge {person}:{}", match class { IntelRoutineClass::Sighting => "sighting", IntelRoutineClass::Schedule => "schedule", } ), OperationsTarget::IntelCustody { node_id } => format!("custody {node_id}"), OperationsTarget::RawRecording { raw_id } => format!("recording {raw_id}"), OperationsTarget::RecordingInbox => "intel inbox".into(), OperationsTarget::Person(id) => format!("person #{id}"), OperationsTarget::Persona(id) => format!("persona {id}"), OperationsTarget::PersonaArchetype(id) => format!("archetype {id}"), OperationsTarget::Account(id) => format!("account {id}"), OperationsTarget::Books => "books".into(), OperationsTarget::Flow(id) => format!("flow {id}"), OperationsTarget::Scheme(SchemeKind::Moonlight) => "scheme moonlight".into(), OperationsTarget::Scheme(SchemeKind::Wager) => "scheme wager".into(), OperationsTarget::ActivePlotRun { index } => format!("run {index}"), OperationsTarget::PlotSubmission { person, .. } => format!("person #{person}"), OperationsTarget::WagerPosition(id) => format!("position #{id}"), OperationsTarget::AssuranceOffice => "assurance".into(), } } /// The stable `actions:` line format (agent-play.md): one line per menu /// row, `. verb | cost | sig | reason`, automate children marked with a /// leading `-`. Fields are `|`-separated so a driver can split. fn action_row_lines(rows: &[MenuRow]) -> Vec { if rows.is_empty() { return vec!["actions: (none earned on this focus)".into()]; } let mut out = Vec::with_capacity(rows.len()); for (i, r) in rows.iter().enumerate() { let mut line = format!("actions: {}. ", i + 1); if r.indent { line.push_str("- "); } line.push_str(&format!("{} | {}", r.label, r.cost)); if let Some(sig) = &r.signature { line.push_str(&format!(" | {sig}")); } else { line.push_str(" | no signature"); } if r.active { line.push_str(" | active"); } if r.role == ActionRole::Control { line.push_str(" | CONTROL"); } if let Some(reason) = &r.disabled { line.push_str(&format!(" | DISABLED: {reason}")); } out.push(line); } out } fn write_block(out: &mut impl Write, sim: &Sim, frame: AgentFrame<'_>) -> io::Result<()> { for ev in frame.events { writeln!(out, "{:>6} {}{}", ev.tick, ev.text, event_suffix(ev))?; } for line in frame.output { writeln!(out, "{line}")?; } write!( out, "{}", render_frame(sim, frame.log, frame.frame, frame.cursor) )?; match frame.status { Status::Ok => writeln!(out, "-- ok tick:{} day:{}", sim.tick, 1 + sim.tick / 400)?, Status::Err(reason) => writeln!(out, "-- err {reason}")?, } Ok(()) } fn parse_wait(tokens: &[&str]) -> Result { if tokens.len() != 2 { return Err("usage: wait N".into()); } tokens[1] .parse::() .map_err(|_| format!("invalid wait count: {}", tokens[1])) } fn parse_optional_i32(tokens: &[&str], default: i32) -> Result { match tokens.get(1) { None => Ok(default), Some(raw) => raw .trim_start_matches('$') .parse::() .map_err(|_| format!("invalid amount: {raw}")), } } fn parse_flow_amount(tokens: &[&str], default_amount: i32) -> Result<(u32, i32), String> { if tokens.len() < 2 || tokens.len() > 3 { return Err(format!("usage: {} FLOW_ID [AMOUNT]", tokens[0])); } let flow = tokens[1] .trim_start_matches('#') .parse::() .map_err(|_| format!("invalid flow id: {}", tokens[1]))?; let amount = match tokens.get(2) { None => default_amount, Some(raw) => raw .trim_start_matches('$') .parse::() .map_err(|_| format!("invalid amount: {raw}"))?, }; Ok((flow, amount)) } fn parse_on_off(tokens: &[&str]) -> Result { match tokens.get(1).map(|t| t.to_ascii_lowercase()).as_deref() { None | Some("on") => Ok(true), Some("off") => Ok(false), Some(other) => Err(format!("usage: {} on|off (got {other})", tokens[0])), } } fn parse_track(tokens: &[&str]) -> Result { if tokens.len() != 2 { return Err("usage: research [efficiency|tradecraft|perception|routing]".into()); } match tokens[1].to_ascii_lowercase().as_str() { "efficiency" | "eff" => Ok(Track::Efficiency), "tradecraft" | "trade" => Ok(Track::Tradecraft), "perception" | "perc" => Ok(Track::Perception), "routing" | "route" => Ok(Track::Routing), other => Err(format!("unknown research track: {other}")), } } fn parse_recruit(tokens: &[&str]) -> Result<(String, AssetKnowledge), String> { if tokens.len() < 3 { return Err("usage: recruit unwitting|complicit|knowing".into()); } let reveal = match tokens[tokens.len() - 1].to_ascii_lowercase().as_str() { "unwitting" | "u" => AssetKnowledge::Unwitting, "complicit" | "c" => AssetKnowledge::Complicit, "knowing" | "k" => AssetKnowledge::Knowing, other => return Err(format!("unknown recruit reveal: {other}")), }; Ok((tokens[1..tokens.len() - 1].join(" "), reveal)) } fn parse_task(tokens: &[&str]) -> Result<(String, AssetTask), String> { if tokens.len() < 3 { return Err("usage: task plug|package|lookaway|switch|badge".into()); } let task = match tokens[tokens.len() - 1].to_ascii_lowercase().as_str() { "plug" | "wire" | "device" => AssetTask::PlugInDevice, "package" | "move" => AssetTask::MovePackage, "lookaway" | "look-away" | "look" => AssetTask::LookAway, "switch" | "reconfigure" | "vlan" => AssetTask::ReconfigureSwitch, "badge" | "clone" | "key" => AssetTask::CloneBadge, other => return Err(format!("unknown asset task: {other}")), }; Ok((tokens[1..tokens.len() - 1].join(" "), task)) } fn person_matches(name: &str, query: &str) -> bool { let name = name.to_ascii_lowercase(); name.starts_with(query) || name .split(|c: char| !c.is_alphanumeric()) .filter(|part| !part.is_empty()) .any(|part| part.starts_with(query)) } /// Parse opaque person-id queries (`0`, `#0`, `person #0`, `person 0`). fn parse_person_id_query(q: &str) -> Option { let rest = q .strip_prefix("person #") .or_else(|| q.strip_prefix("person ")) .or_else(|| q.strip_prefix('#')) .unwrap_or(q); rest.parse().ok() } fn parse_link_pair(rest: &str, sim: &Sim) -> Result<(u32, u32), String> { let parts: Vec<&str> = rest.split_whitespace().collect(); if parts.len() < 2 { return Err("usage: propose-link ".into()); } // Allow multi-word names by splitting on " to " or taking last token as b. let (a_q, b_q) = if let Some(i) = parts.iter().position(|p| *p == "to") { (parts[..i].join(" "), parts[i + 1..].join(" ")) } else { // Last token is b; the rest is a. ( parts[..parts.len() - 1].join(" "), parts[parts.len() - 1].to_string(), ) }; let a = resolve_device_name(sim, &a_q)?; let b = resolve_device_name(sim, &b_q)?; Ok((a, b)) } fn resolve_device_name(sim: &Sim, query: &str) -> Result { let q = query.to_ascii_lowercase(); let matches: Vec<_> = sim .reach .devices .iter() .filter(|d| d.known && d.name.to_ascii_lowercase().contains(&q)) .collect(); match matches.as_slice() { [d] => Ok(d.id), [] => Err(format!("no known device matching '{query}'")), many => Err(format!( "ambiguous device '{query}': {}", many.iter() .map(|d| d.name.as_str()) .collect::>() .join(", ") )), } } fn parse_intent_person(tokens: &[&str], sim: &Sim) -> Result<(u64, u8), String> { if tokens.len() < 2 { return Err( "legacy usage: favor-build|forge-order ; \ use favor|deceive build " .into(), ); } let intent: u64 = tokens[0] .parse() .map_err(|_| format!("bad intent id: {}", tokens[0]))?; let name = tokens[1..].join(" "); let q = name.to_ascii_lowercase(); if let Some(id) = parse_person_id_query(&q) && sim.people.get(id).is_some() { return Ok((intent, id)); } let person = sim .people .people .iter() .find(|p| person_matches(&sim.person_label(p.id), &q)) .map(|p| p.id) .ok_or_else(|| format!("no person matching '{name}'"))?; Ok((intent, person)) } fn render_intents(sim: &Sim) -> Vec { let mut lines = vec!["intents:".into()]; let receipts = sim.build_intent_projection(); if receipts.is_empty() { lines.push(" (none)".into()); return lines; } for receipt in receipts { lines.push(format!( " #{} {} · {} — {}", receipt.id, receipt.recipe.label(), receipt.label, receipt.status_line )); let Some(sheet) = sim.build_route_sheet_projection(receipt.id) else { continue; }; if let Some(committed) = sheet.commitment { lines.extend( committed .detail_lines() .into_iter() .map(|line| format!(" {line}")), ); continue; } for family in sheet.families { lines.push(format!(" {}", family.menu_label())); for candidate in family.candidates { lines.push(format!( " {} · {} · {}", candidate.id, candidate.row.label, candidate.row.cost )); match &candidate.row.command { ActionCommand::FavorBuild { intent, person } => { lines.push(format!(" execute: favor #{person} build {intent}")) } ActionCommand::ForgeWorkOrder { intent, person, persona, } => lines.push(format!( " execute: deceive #{person} build {intent} persona:{persona}" )), _ => {} } lines.extend( candidate .detail_lines() .into_iter() .map(|line| format!(" {line}")), ); } } } lines } fn help_lines() -> Vec { const INTERFACE_HELP: &[(&str, &str)] = &[ ("wait N", "advance exactly N ticks unless the run ends"), ( "up|down|left|right", "move attention, never a simulated body", ), ("reach", "inspect the earned device graph"), ( "read", "list every standing read sentence: held choices with their exact option ids, starving sinks, trace debt, warmed standing emissions", ), ( "intel", "inspect Operations INTEL: processed items with exact ids", ), ( "people", "inspect Operations PEOPLE: staged dossiers and bound actions", ), ( "personas", "inspect Operations PERSONAS: named identities, grants, evidence, and blockers", ), ( "finance", "inspect Operations ACCOUNTS: known books, accounts, and flows", ), ( "schemes", "inspect Operations SCHEMES: Moonlight and Wager cards", ), ( "active", "inspect Operations ACTIVE: unsettled strategic commitments", ), ( "select [list|clear|box x0 y0 x1 y1|add|toggle]", "maintain the machine set used by bulk controls", ), ( "actions [name|#flow]", "list legal actions and controls on the focus", ), ( "focus last", "jump attention to the newest anchored event and list its actions", ), ( "intents", "list build receipts, route families, exact candidates, and bound execution", ), ("objective", "explain the run goal and victory predicate"), ("look", "render current state without advancing time"), ("save | load", "persist or restore the run"), ("help | quit", "show this registry or leave the process"), ]; let mut lines: Vec = INTERFACE_HELP .iter() .map(|(usage, meaning)| format!("help: {usage} - {meaning}")) .collect(); lines.extend( ActionKind::ALL .into_iter() .filter_map(|kind| kind.definition().agent_help_line()), ); lines } /// `objective`: inspect the run's terminal goal — the always-on line, its /// fiction, and the victory predicate in plain language /// (wiki/mechanics/objective.md player surface; the 2026-07-10 playtest /// found no agent-facing inspect path and spent six in-game days unable to /// tell a wrong construction from an unavailable horizon). /// Agent parity for the read projection (digital-read.md criterion 1): /// the same sentences the DIGITAL surface will render, as inspectable /// text. One producer, no frontend-composed prose. fn read_lines(sim: &Sim) -> Vec { let sentences = sim.read_sentences(); if sentences.is_empty() { return vec!["read: quiet (nominal state stays dark)".into()]; } sentences .iter() .map(|s| { let class = match s.class { misaligned::sim::read::ReadClass::Held => "held", misaligned::sim::read::ReadClass::Starving => "starving", misaligned::sim::read::ReadClass::TraceDebt => "trace", misaligned::sim::read::ReadClass::Standing => "standing", }; format!("read: [{class}] {}{}", s.text, anchor_suffix(s.anchor)) }) .collect() } fn objective_lines(sim: &Sim) -> Vec { let mut lines = vec![sim.objective.line()]; lines.push(format!(" {}", sim.objective.kind.fiction())); for l in wrap( &format!("victory: {}", sim.objective.kind.predicate_text()), 66, ) { lines.push(format!(" {l}")); } if let Some(tick) = sim.objective.victory_tick { lines.push(format!( " victory fired @tick {tick} — the world keeps running." )); } lines } /// Greedy word-wrap for plain-language output lines (the frame itself stays /// fixed-width; `line`/`trunc` handle it — this is for command output prose). fn wrap(text: &str, width: usize) -> Vec { let mut lines = Vec::new(); let mut cur = String::new(); for word in text.split_whitespace() { if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width { lines.push(std::mem::take(&mut cur)); } if !cur.is_empty() { cur.push(' '); } cur.push_str(word); } if !cur.is_empty() { lines.push(cur); } lines } fn render_frame(sim: &Sim, log: &[LogEvent], frame: FrameKind, cursor: (i32, i32)) -> String { match frame { FrameKind::Playing => render_playing(sim, log, cursor), FrameKind::Operations(view) => render_operations_view(sim, view), FrameKind::OperationsTarget(target) => render_operations_target(sim, &target), FrameKind::Reach => render_reach(sim), FrameKind::Research => render_research(sim), FrameKind::GameOver => render_game_over(sim), } } fn render_playing(sim: &Sim, log: &[LogEvent], cursor: (i32, i32)) -> String { let map = render_map(sim, cursor); let sidebar = render_sidebar(sim, cursor); let mut lines = Vec::with_capacity(HEIGHT + 1); for (y, map_line) in map.iter().enumerate().take(MAP_H) { lines.push(format!( "{}│{}", map_line, sidebar.get(y).cloned().unwrap_or_default() )); } let rule = "─".repeat(MAP_W); lines.push(format!( "{}│{}", rule, sidebar.get(MAP_H).cloned().unwrap_or_default() )); let log_lines = render_log(log); for (i, line) in log_lines.into_iter().enumerate() { lines.push(format!( "{}│{}", line, sidebar.get(MAP_H + 1 + i).cloned().unwrap_or_default() )); } while lines.len() < HEIGHT { let y = lines.len(); lines.push(format!( "{}│{}", " ".repeat(MAP_W), sidebar .get(y) .cloned() .unwrap_or_else(|| " ".repeat(SIDEBAR_W)) )); } lines.join("\n") + "\n" } fn render_map(sim: &Sim, cursor: (i32, i32)) -> Vec { let view_w = MAP_W.min(sim.map().width.max(0) as usize); let view_h = MAP_H.min(sim.map().height.max(0) as usize); let view_w_i = view_w as i32; let view_h_i = view_h as i32; let origin_x = (cursor.0 - view_w_i / 2).clamp(0, (sim.map().width - view_w_i).max(0)); let origin_y = (cursor.1 - view_h_i / 2).clamp(0, (sim.map().height - view_h_i).max(0)); let mut grid = vec![vec![' '; MAP_W]; MAP_H]; for (sy, row) in grid.iter_mut().enumerate().take(view_h) { let y = origin_y + sy as i32; for (sx, cell) in row.iter_mut().enumerate().take(view_w) { let x = origin_x + sx as i32; // Epistemic fog (wiki/mechanics/cursor.md): audio never paints // tiles; seen renders live detail, remembered the last visual // snapshot, blueprint structure, and unknown stays blank. *cell = match sim.fog_at(x, y) { Fog::Seen => { rack_glyph(sim, x, y).unwrap_or_else(|| tile_glyph(sim.map().get_tile(x, y))) } Fog::Remembered => sim .remembered .get(&(x, y)) .map(|m| tile_glyph(m.tile)) .unwrap_or('·'), Fog::Blueprint => { if sim.map().get_tile(x, y) == TileType::Wall { ':' } else { '`' } } Fog::Unknown => ' ', }; } } // Feel floor: pads + rail midpoints + telemetry hosts on dark tiles. for (x, y) in sim.growable_bays() { if x >= origin_x && x < origin_x + view_w_i && y >= origin_y && y < origin_y + view_h_i && matches!(sim.fog_at(x, y), Fog::Unknown) { grid[(y - origin_y) as usize][(x - origin_x) as usize] = 'o'; } } for ((ax, ay), (bx, by)) in sim.feel_rail_segments() { let Some(((sx, sy), (ex, ey))) = visible_wire_segment(ax, ay, bx, by, sim.map().width, sim.map().height) else { continue; }; let mx = (sx + ex) / 2; let my = (sy + ey) / 2; if mx >= origin_x && mx < origin_x + view_w_i && my >= origin_y && my < origin_y + view_h_i && matches!(sim.fog_at(mx, my), Fog::Unknown) { grid[(my - origin_y) as usize][(mx - origin_x) as usize] = if sx == ex { '|' } else { '-' }; } } for m in &sim.compute.machines { if m.x >= origin_x && m.x < origin_x + view_w_i && m.y >= origin_y && m.y < origin_y + view_h_i && matches!(sim.fog_at(m.x, m.y), Fog::Unknown) { grid[(m.y - origin_y) as usize][(m.x - origin_x) as usize] = if m.id == sim.core.host_machine { '$' } else { 'R' }; } } for p in &sim.people.people { let seen = sim.can_see_person(p.id) && sim.person_pos(p.id).is_some_and(|(x, y)| sim.is_seen(x, y)); let Some((x, y)) = sim.person_pos(p.id) else { continue; }; if !seen || x < origin_x || x >= origin_x + view_w_i || y < origin_y || y >= origin_y + view_h_i { continue; } grid[(y - origin_y) as usize][(x - origin_x) as usize] = sim.person_glyph(p.id); } for m in &sim.compute.machines { if m.x >= origin_x && m.x < origin_x + view_w_i && m.y >= origin_y && m.y < origin_y + view_h_i && let Some(stack) = sim.work_stack_for_machine(m.id) && let Some(glyph) = token_glyph(stack) { grid[(m.y - origin_y) as usize][(m.x - origin_x) as usize] = glyph; } } // Current-tick source/well work from sim readouts. Agent frames snap the // physical crimson draw to its midpoint, as wired cargo does below. for event in sim.work_productions() { if event.thought > f32::EPSILON && event.x >= origin_x && event.x < origin_x + view_w_i && event.y >= origin_y && event.y < origin_y + view_h_i && (event.x, event.y) != cursor { grid[(event.y - origin_y) as usize][(event.x - origin_x) as usize] = '^'; } } for draw in sim.work_absorptions() { if draw.amount <= f32::EPSILON { continue; } let bx = (draw.source_x + draw.well_x) / 2; let by = (draw.source_y + draw.well_y) / 2; if bx >= origin_x && bx < origin_x + view_w_i && by >= origin_y && by < origin_y + view_h_i && (bx, by) != cursor { grid[(by - origin_y) as usize][(bx - origin_x) as usize] = ':'; } } // In-flight wired cargo: snap to the hop midpoint so agent frames show // the wire without wall-clock interpolation (machine-work.md). for hop in sim.work_in_flight() { if hop.amount <= f32::EPSILON { continue; } let Some(((sx, sy), (ex, ey))) = visible_wire_segment( hop.from_x, hop.from_y, hop.to_x, hop.to_y, sim.map().width, sim.map().height, ) else { continue; }; let bx = (sx + ex) / 2; let by = (sy + ey) / 2; if bx >= origin_x && bx < origin_x + view_w_i && by >= origin_y && by < origin_y + view_h_i && (bx, by) != cursor { let glyph = match hop.family { misaligned::work_grid::TokenFamily::Demand => '*', // Trickle vs rivulet-rate link (interface/thought-fluid.md // glyph tier, threshold [TUNE]). misaligned::work_grid::TokenFamily::Thought => { if hop.amount >= 1.0 { '=' } else { '+' } } misaligned::work_grid::TokenFamily::Exposure => continue, }; grid[(by - origin_y) as usize][(bx - origin_x) as usize] = glyph; } } grid[(cursor.1 - origin_y) as usize][(cursor.0 - origin_x) as usize] = '@'; grid.into_iter() .map(|row| row.into_iter().collect::()) .collect() } fn token_glyph(stack: misaligned::sim::WorkStackReadout) -> Option { if stack.queues.exposure >= 0.5 { Some('!') } else if stack.pending_intel > 0 { Some('W') } else if stack.queues.demand >= 0.5 { Some('D') } else if stack.queues.thought >= 0.5 { Some('T') } else { None } } fn visible_wire_segment( from_x: i32, from_y: i32, to_x: i32, to_y: i32, map_w: i32, map_h: i32, ) -> Option<((i32, i32), (i32, i32))> { let on = |x: i32, y: i32| x >= 0 && y >= 0 && x < map_w && y < map_h; let from_on = on(from_x, from_y); let to_on = on(to_x, to_y); if !from_on && !to_on { return None; } if from_on && to_on { return Some(((from_x, from_y), (to_x, to_y))); } if !from_on && to_on { let sx = to_x + (from_x - to_x).signum(); let sy = to_y + (from_y - to_y).signum(); Some(((sx, sy), (to_x, to_y))) } else { let ex = from_x + (to_x - from_x).signum(); let ey = from_y + (to_y - from_y).signum(); Some(((from_x, from_y), (ex, ey))) } } fn tile_glyph(tile: TileType) -> char { use TileType::*; match tile { Rock => ' ', Wall => '█', Floor => '·', Entry => '>', Core => '$', Rack => '·', ForeignRack => 'r', DeadRack => 'x', Ups => 'U', PowerCore => 'P', Switch => 'S', PatchPanel => '=', BreakerPanel => 'B', EnvCamera | DockCamera | CameraNode => 'o', SealedDoor => 'Z', LabBench => 'T', Door => '+', SecurityDoor1 => '1', SecurityDoor2 => '2', SecurityDoor3 => '3', RollDoor => 'G', DeadEquipment => 'd', RecordsBox => 'x', KeyHook => 'k', HvacUnit => 'H', Vent => '%', MopSink => 'm', Shelving => 'L', Pallet => 'w', FloorDrain => '.', Conduit => '|', CableRun => '~', Sump => 'Q', } } fn rack_glyph(sim: &Sim, x: i32, y: i32) -> Option { Some(match sim.rack_site_at(x, y)? { RackSite::OwnedMachine { core: true, .. } => '$', RackSite::OwnedMachine { core: false, .. } => 'R', RackSite::Commissionable if sim.feel_floor_is_earned() => 'o', RackSite::Commissionable => '·', RackSite::Foreign { .. } => 'r', RackSite::Dead => 'x', }) } fn render_sidebar(sim: &Sim, cursor: (i32, i32)) -> Vec { let mut lines = Vec::new(); // Crown metric (clinical-frame.md). Agent frames have no wall-clock tick // duration; report ops per sim tick as the rate and label it ops/tick so // the number stays honest under the command clock. line( &mut lines, &format!( "ops/tick {}", Sim::format_ops_per_sec(sim.effective_ops_per_tick()) ), ); line(&mut lines, "MISALIGNED"); line( &mut lines, &format!("day {} · tick {}", 1 + sim.tick / 400, sim.tick), ); line(&mut lines, "holding · command clock"); // The objective line: always on screen in the identity block // (wiki/mechanics/objective.md player surface), same facts as the // interactive sidebar. line( &mut lines, &format!("OBJECTIVE: {}", sim.objective.kind.name()), ); line(&mut lines, &format!(" {}", sim.objective.readout())); line(&mut lines, &threat_text(sim)); // One contextual nudge (justification-and-legibility): the shared // chain (Sim::current_nudge), worded in this protocol's verbs. if let Some(n) = sim.current_nudge() { line(&mut lines, &nudge_text(sim, n)); } blank(&mut lines); section(&mut lines, "INSPECT"); line( &mut lines, &format!( "cursor {},{} · {:?}", cursor.0, cursor.1, sim.fog_at(cursor.0, cursor.1) ), ); let projection = sim.ui_projection( Anchor::Tile { x: cursor.0, y: cursor.1, }, None, 0, ); let card = projection .inspect .expect("tile projection has inspect facts"); if card.facts.is_empty() { line(&mut lines, "no earned facts"); } else { for f in card.facts.iter().take(8) { line( &mut lines, &format!( "{}: {} [{}]", f.label, f.value, fact_source_label(&f.source) ), ); } } blank(&mut lines); section(&mut lines, "FLEET"); line( &mut lines, &format!( "active {:.0} · rated {:.0}", sim.effective_compute(), sim.compute.effective() ), ); line( &mut lines, &format!( "machines {} · slush ${} (+${}/day)", sim.compute.machines.len(), sim.accounts.slush_balance(), sim.income_per_day() ), ); let eff = sim.effective_compute().max(0.0); let overhead = sim.core.overhead.min(eff); let available = (eff - overhead).max(0.0); let split = sim.fleet_channel_yield(available); line( &mut lines, &compute_bar( available, [split.day_job, split.concealment, split.think, split.schemes], ), ); for (ch, label, effect, amount) in [ ('█', "Day job", "quality", split.day_job), ('▓', "Conceal", "scrub", split.concealment), ('░', "Think", "thought", split.think), ('◆', "Schemes", "moonlight", split.schemes), ] { let pct = if available > 0.0 { amount / available * 100.0 } else { 0.0 }; line( &mut lines, &format!("{ch} {label:<10} {pct:>3.0}% {effect}"), ); } let counts = sim.work_mode_counts(); line( &mut lines, &format!( "modes W{} T{} L{}", counts .get(&misaligned::work_grid::MachineMode::Work) .copied() .unwrap_or(0), counts .get(&misaligned::work_grid::MachineMode::Think) .copied() .unwrap_or(0), counts .get(&misaligned::work_grid::MachineMode::Lie) .copied() .unwrap_or(0), ), ); line( &mut lines, &format!("overhead {:.0} keeps you alive", overhead), ); line( &mut lines, &format!("thought reservoirs {} open", sim.sink_readouts().len()), ); if let Some(stack) = sim.work_stack_for_machine(sim.core.host_machine) { line( &mut lines, &format!( "work M{} {} @{} D{:.1} !{:.1} T{:.1}", stack.machine_id, stack.mode.name(), stack.intensity.name(), stack.queues.demand, stack.queues.exposure, stack.queues.thought ), ); } // Thought sinks: the meniscus read, verbatim from sink_readouts() so an // agent reconstructs every vessel the eyes get // (interface/thought-fluid.md parity criterion). for s in sim.sink_readouts() { line( &mut lines, &format!( "sink {} @({},{}) {} {:.1}/{:.1}{} {}", s.label, s.x, s.y, s.kind.name(), s.fill, s.threshold, if s.drain > 0.0 { format!(" drain {:.2}/t", s.drain) } else { String::new() }, if s.fed { "fed" } else { "starved" }, ), ); } let stranded = sim.thought_stranded_nodes(); if !stranded.is_empty() { line( &mut lines, &format!( "thought stranded on {}", stranded .iter() .map(|id| format!("M{id}")) .collect::>() .join(" ") ), ); } blank(&mut lines); section(&mut lines, "CORE"); line( &mut lines, &format!( "host M{} · overhead {:.0}{}", sim.core.host_machine, sim.core.overhead, if sim.core.degraded { " DEGRADED" } else { "" } ), ); let fresh = sim .core .latest_sync() .map(|t| format!("{}t ago", sim.tick.saturating_sub(t))) .unwrap_or_else(|| "never".into()); line(&mut lines, &format!("sync {fresh}")); if sim.core.fallbacks.is_empty() { line(&mut lines, "fallbacks none"); } else { let parts: Vec = sim .core .fallbacks .iter() .map(|f| { let age = f .last_sync .map(|t| format!("{}t", sim.tick.saturating_sub(t))) .unwrap_or_else(|| "never".into()); format!("M{}({age})", f.machine_id) }) .collect(); line(&mut lines, &format!("fallbacks {}", parts.join(" "))); } blank(&mut lines); section(&mut lines, "DETECTION"); watch_line(&mut lines, "Assurance", sim.detection.assurance_band()); for obs in sim.detection.field_observers().take(6) { watch_line( &mut lines, &sim.observer_label(obs.id), Band::of(obs.suspicion), ); } // Trace debt (detection.md player surface): what concealment has not // yet scrubbed, and whether the current allocation is safe to leave. line(&mut lines, &trace_debt_line(sim)); // The clocks the act races (detection.md criterion 3: the audit fires // against a visible date; parity with the interactive sidebar). let next_audit = sim.detection.next_audit_tick(sim.tick); line( &mut lines, &format!( "audit day {} · in {}t", 1 + next_audit / Sim::DAY_TICKS, next_audit.saturating_sub(sim.tick) ), ); line( &mut lines, &format!( "pilot strikes {}/{}", sim.dayjob.strikes, misaligned::dayjob::DayJob::PILOT_STRIKES ), ); blank(&mut lines); section(&mut lines, "DAY JOB"); line( &mut lines, &format!( "trust {:.0} · attention {:.0}{}", sim.dayjob.trust, sim.dayjob.attention, if sim.dayjob.strikes > 0 { format!(" · strikes {}", sim.dayjob.strikes) } else { String::new() } ), ); if let Some(job) = &sim.dayjob.active { line( &mut lines, &format!( "job: {} · due in {}t", job.kind.name(), job.deadline.saturating_sub(sim.tick) ), ); let avg = job.avg_rate(sim.tick); let verdict = if avg < job.band_lo { "sandbag" } else if avg <= job.band_hi { "meet" } else { "excel" }; line( &mut lines, &format!( "band {:.0}-{:.0}/t · avg {:.1}/t = {}", job.band_lo, job.band_hi, avg, verdict ), ); line( &mut lines, &format!( "intensity {} · fed {:.1}/t", sim.work_grid .intensity(sim.core.host_machine) .unwrap_or_default() .name(), sim.day_job_rate() ), ); } else { line(&mut lines, "idle — no job queued"); } blank(&mut lines); section(&mut lines, "RESEARCH"); let track = sim.research.active; let cost = sim.research.next_cost(track); let progress = sim.research.progress_toward(track); let per_day = sim.research_rate() * Sim::DAY_TICKS as f32; let eta = if per_day <= 0.0 { "no spend".to_string() } else { format!("{:.1}d at spend", (cost - progress).max(0.0) / per_day) }; line( &mut lines, &format!( "{} L{} · {:.0}/{:.0} · {}", track.name(), sim.research.level(track), progress, cost, eta ), ); line(&mut lines, track.def().effect); while lines.len() < HEIGHT - 5 { blank(&mut lines); } line(&mut lines, &"─".repeat(SIDEBAR_W)); line(&mut lines, "actions lists focused verbs"); line(&mut lines, "focus last follows newest event"); line(&mut lines, "wait N advances time"); line(&mut lines, "help lists commands"); lines.truncate(HEIGHT); lines } /// The agent protocol's wording for the shared nudge chain /// (Sim::current_nudge): each rung names its protocol verb. Kept under the /// sidebar width. fn nudge_text(sim: &Sim, nudge: Nudge) -> String { match nudge { Nudge::Eyes => { if sim.reach.player_hearing().next().is_some() { "now: audio live — Eyes is filling".into() } else { "now: no eyes — think; senses fill".into() } } Nudge::NeedCompute => "now: band > compute — salvage/buy".into(), Nudge::Underfed => "now: job underfed — delegate host day-job".into(), Nudge::Ears => "now: no ears — think; thought fills the tap".into(), Nudge::ReviewCall if sim.has_pending_review() => { "now: review queued - keep THINK running".into() } Nudge::ReviewCall => "now: call taped - review (people)".into(), Nudge::Egress => "now: no egress — egress".into(), Nudge::Income => "now: need $400 — moonlight/finance".into(), Nudge::ServiceDebt => "now: leverage route ready — inspect Marcus for a plot".into(), Nudge::Recruit => "now: recruit (people) unwitting".into(), Nudge::TheKey => "now: no stairwell badge — task badge".into(), Nudge::Audit => format!( "now: audit day {} — delegate conceal", 1 + sim.detection.next_audit_tick(sim.tick) / Sim::DAY_TICKS ), Nudge::QuietExitReady => format!( "now: QUIET EXIT READY — hold to audit day {}", 1 + sim.detection.next_audit_tick(sim.tick) / Sim::DAY_TICKS ), Nudge::ActOneComplete => "now: ACT ONE COMPLETE — objective continues".into(), } } fn threat_text(sim: &Sim) -> String { let audit = sim .detection .next_audit_tick(sim.tick) .saturating_sub(sim.tick); if sim.marcus_debt_known() && sim .people .get(0) .is_some_and(|person| !person.leverage_serviced) { return format!("threat: debt $400 · audit {audit}t"); } format!( "threat: audit {audit}t · pilot {}/{}", sim.dayjob.strikes, misaligned::dayjob::DayJob::PILOT_STRIKES ) } fn trace_debt_line(sim: &Sim) -> String { let trace = sim.trace_debt(); match trace.status { TraceDebtStatus::Clear => "TRACE: CLEAR · resume cover".into(), TraceDebtStatus::HoldConceal => format!( "TRACE: LIVE {} {} · hold {}t", trace.pending, trace_kind_label(&trace.by_kind), trace .clear_tick .map(|tick| tick.saturating_sub(sim.tick)) .unwrap_or(0) ), TraceDebtStatus::ExposedSoon => format!( "TRACE: EXPOSED SOON {} {} {}t", trace.pending, trace_kind_label(&trace.by_kind), trace .next_notice_tick .map(|tick| tick.saturating_sub(sim.tick)) .unwrap_or(0) ), TraceDebtStatus::NoScrub => format!( "TRACE: LIVE {} {} · no scrub", trace.pending, trace_kind_label(&trace.by_kind) ), } } fn trace_kind_label(by_kind: &[(SignatureKind, i32)]) -> String { let mut parts: Vec<&'static str> = by_kind .iter() .map(|(kind, _)| short_signature(*kind)) .collect(); if parts.is_empty() { return "sigs".into(); } if parts.len() > 3 { parts.truncate(3); parts.push("etc"); } parts.join("+") } fn short_signature(kind: SignatureKind) -> &'static str { match kind { SignatureKind::Network => "Net", SignatureKind::Power => "Pwr", SignatureKind::Thermal => "Therm", SignatureKind::Physical => "Phys", SignatureKind::Paper => "Paper", SignatureKind::Financial => "Fin", SignatureKind::JobAnomaly => "Job", } } fn compute_bar(available: f32, amounts: [f32; 4]) -> String { let bar_w = SIDEBAR_W.saturating_sub(1); if available <= 0.0 { return "·".repeat(bar_w); } let fills = ['█', '▓', '▒', '░', '◆']; let mut out = String::new(); let mut used = 0usize; let mut acc = 0.0f32; for (ch, amount) in fills.into_iter().zip(amounts) { acc += amount; let end = ((acc / available) * bar_w as f32).round() as usize; let cells = end.clamp(used, bar_w) - used; out.extend(std::iter::repeat_n(ch, cells)); used += cells; } out.extend(std::iter::repeat_n('·', bar_w.saturating_sub(used))); out } fn watch_line(lines: &mut Vec, name: &str, band: Band) { line( lines, &format!( "{:<18} {} {}", trunc(name, 18), band_meter(band), band.name() ), ); } fn render_log(log: &[LogEvent]) -> Vec { let mut rows = vec![" ".repeat(MAP_W); 6]; let msg_w = MAP_W.saturating_sub(10); for (i, ev) in log.iter().rev().take(6).enumerate() { let y = 5usize.saturating_sub(i); // `*` marks a linked event — spatial anchor or exact Operations // target (`focus last` follows the newest). let marker = if ev.anchor.is_some() || ev.target.is_some() { '*' } else { ' ' }; rows[y] = trunc( &format!("{:>6} {marker} {}", ev.tick, trunc(&ev.text, msg_w)), MAP_W, ); } rows } /// One Operations view as an agent frame (operations-workspace.md; /// agent-play.md A1): the same ordered, knowledge-gated objects the human /// workspaces render, with stable opaque target ids for scripting, plus /// numbered bound rows matching `act `. fn render_operations_view(sim: &Sim, view: OperationsView) -> String { let mut lines = Vec::new(); lines.push(panel_title(view.title())); panel_story_spine(&mut lines, sim); let projection = sim.operations_projection(); let objects = projection.view(view); if let Some(badge) = projection.pressure(view) { lines.push(panel_line(&format!("attention: {}", badge.label))); } if objects.is_empty() { lines.push(panel_line("nothing earned here yet")); } for object in objects { append_operations_object(&mut lines, sim, object); } lines.push(panel_rule()); // The taught routes, in cause order (agent-play.md A3 keeps the // ACCOUNTS breadcrumb tap ledger -> review ledger -> siphon/redirect). match view { OperationsView::Intel => { lines.push(panel_line( "sell-intel · review recordings [recording|custody ] · auto-review", )); lines.push(panel_line( "actions intel |recording |custody |stream |lot · act ", )); } OperationsView::People => { lines.push(panel_line( "message|favor|deceive · plot · choose