Skip to main content

self_hosted_node/engine_backend/
java_backend.rs

1#![allow(dead_code)]
2
3#[cfg(forge_backend)]
4use std::collections::HashMap;
5use std::env;
6#[cfg(feature = "java-forge")]
7use std::io::{BufRead, BufReader, BufWriter, Write};
8use std::path::{Path, PathBuf};
9#[cfg(feature = "java-forge")]
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::atomic::AtomicBool;
12use std::sync::mpsc as std_mpsc;
13#[cfg(feature = "java-forge")]
14use std::sync::mpsc::RecvTimeoutError;
15#[cfg(forge_backend)]
16use std::sync::mpsc::TryRecvError;
17use std::sync::Arc;
18#[cfg(feature = "java-forge")]
19use std::sync::Mutex;
20#[cfg(forge_backend)]
21use std::time::Duration;
22#[cfg(forge_backend)]
23use std::time::Instant;
24
25use manabrew_protocol::deck_dto::{Deck, DeckCardIdentity};
26
27use crate::config::DeckSelection;
28#[cfg(feature = "java-forge")]
29use manabot::{BotAgent, SimpleAi};
30#[cfg(forge_backend)]
31use manabrew_agent_interface::game_view_dto::GameViewDto;
32use manabrew_agent_interface::prompt::{AgentMessage, ClientToServerMessage};
33#[cfg(forge_backend)]
34use manabrew_agent_interface::prompt::{
35    AgentPrompt, ChooseActionOutput, DiceRolledOutput, DirectiveInput, GameOverInput, PromptInput,
36    PromptOutput, ProtocolError, ProtocolErrorCode, ResponseViolation, StateUpdate,
37};
38#[cfg(feature = "java-forge")]
39use manabrew_agent_interface::prompt::{MulliganOutput, MulliganPutBackOutput};
40use serde::Serialize;
41#[cfg(feature = "java-forge")]
42use serde_json::json;
43#[cfg(feature = "java-forge")]
44use serde_json::Value;
45#[cfg(forge_backend)]
46use tracing::warn;
47#[cfg(forge_backend)]
48use tracing::{debug, info};
49
50use super::HostedGameOver;
51use crate::config::workspace_root;
52
53pub fn unsupported_message() -> &'static str {
54    "hosted java-forge backend is unavailable; rebuild self-hosted-node with --features java-forge"
55}
56
57#[cfg(feature = "java-forge")]
58pub fn run_smoke_game(max_prompts: usize) -> Result<(), String> {
59    let config = JavaRuntimeConfig::from_env();
60    let assets_dir = config.assets_dir.to_string_lossy().to_string();
61    let bridge = SubprocessBridge::spawn(&config)?;
62    let mut session = JavaForgeSession::new(bridge);
63    session.initialize(&assets_dir)?;
64
65    let deck_a = smoke_deck("Mountain", "Lightning Bolt");
66    let deck_b = smoke_deck("Forest", "Grizzly Bears");
67    let request = StartGameRequest::new(
68        "self-hosted-java-smoke".to_string(),
69        String::new(),
70        20,
71        42,
72        vec![
73            PlayerConfig::new("Smoke A".to_string(), &deck_a, Vec::new()),
74            PlayerConfig::new("Smoke B".to_string(), &deck_b, Vec::new()),
75        ],
76    );
77    let session_id = session.start_game(&request)?;
78    info!(session_id, "java-forge smoke session started");
79
80    let mut prompts_seen = 0usize;
81    while prompts_seen < max_prompts {
82        let Some(prompt_json) = wait_for_prompt(&mut session, 600)? else {
83            session.end_game()?;
84            return Err("timed out waiting for java-forge smoke prompt".to_string());
85        };
86        let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
87            .map_err(|err| format!("failed to parse java-forge smoke prompt: {err}"))?;
88        let player = player_index(&prompt.deciding_player_id);
89        info!(prompts_seen, player, "java-forge smoke prompt");
90        let pass = PromptOutput::ChooseAction(ChooseActionOutput::Pass {
91            until: None,
92            exhaust_stack: false,
93        });
94        session.submit_action(&serde_json::to_string(&pass).map_err(|err| err.to_string())?)?;
95        prompts_seen += 1;
96    }
97
98    let snapshot_json = session.get_snapshot(Some(0))?;
99    let snapshot: Value = serde_json::from_str(&snapshot_json)
100        .map_err(|err| format!("failed to parse java-forge smoke snapshot: {err}"))?;
101    info!(
102        turn = snapshot
103            .get("turn")
104            .and_then(|value| value.as_i64())
105            .unwrap_or_default(),
106        phase = snapshot
107            .get("phase")
108            .and_then(|value| value.as_str())
109            .unwrap_or("<missing>"),
110        "java-forge smoke snapshot"
111    );
112    session.end_game()?;
113    Ok(())
114}
115
116#[cfg(not(feature = "java-forge"))]
117pub fn run_smoke_game(_max_prompts: usize) -> Result<(), String> {
118    Err(
119        "java-forge smoke requires building self-hosted-node with --features java-forge"
120            .to_string(),
121    )
122}
123
124// Unlike run_smoke_game, which spawns the JAR in a subprocess, this drives the
125// GraalVM native library in-process: isolate creation, forge_initialize (which
126// loads the card database) and a real game start. CI runs it after restoring
127// forge-harness/native/build from cache, where nothing else would notice a
128// stale or broken libforgeharness.
129#[cfg(feature = "graal-forge")]
130pub fn run_graal_smoke() -> Result<(), String> {
131    let config = JavaRuntimeConfig::from_env();
132    let engine = GraalEngineHandle::create(&config.assets_dir)?;
133
134    let deck_a = smoke_deck("Mountain", "Lightning Bolt");
135    let deck_b = smoke_deck("Forest", "Grizzly Bears");
136    let request = StartGameRequest::new(
137        "self-hosted-graal-smoke".to_string(),
138        String::new(),
139        20,
140        42,
141        vec![
142            PlayerConfig::new("Smoke A".to_string(), &deck_a, Vec::new()),
143            PlayerConfig::new("Smoke B".to_string(), &deck_b, Vec::new()),
144        ],
145    );
146
147    let session_id = engine.start_game(&request.to_json().map_err(|err| err.to_string())?)?;
148    info!(session_id, "graal-forge smoke session started");
149    engine.end_game(&session_id)?;
150    Ok(())
151}
152
153#[cfg(not(feature = "graal-forge"))]
154pub fn run_graal_smoke() -> Result<(), String> {
155    Err(
156        "graal-forge smoke requires building self-hosted-node with --features graal-forge"
157            .to_string(),
158    )
159}
160
161#[cfg(feature = "java-forge")]
162pub fn run_scenario(name: &str, max_prompts: usize) -> Result<(), String> {
163    let scenario = JavaScenario::from_name(name)?;
164    let config = JavaRuntimeConfig::from_env();
165    let assets_dir = config.assets_dir.to_string_lossy().to_string();
166    let bridge = SubprocessBridge::spawn(&config)?;
167    let mut session = JavaForgeSession::new(bridge);
168    session.initialize(&assets_dir)?;
169
170    let request = StartGameRequest::new(
171        format!("self-hosted-java-scenario-{}", scenario.name()),
172        String::new(),
173        20,
174        42,
175        vec![
176            PlayerConfig::new(
177                "Scenario A".to_string(),
178                &scenario_deck("Swamp"),
179                Vec::new(),
180            ),
181            PlayerConfig::new(
182                "Scenario B".to_string(),
183                &scenario_deck("Forest"),
184                Vec::new(),
185            ),
186        ],
187    );
188    let session_id = session.start_game(&request)?;
189    info!(
190        session_id,
191        scenario = scenario.name(),
192        "java-forge scenario started"
193    );
194
195    let result = run_scenario_loop(&mut session, scenario, max_prompts);
196    let end_result = session.end_game();
197    result.and(end_result)
198}
199
200#[cfg(not(feature = "java-forge"))]
201pub fn run_scenario(_name: &str, _max_prompts: usize) -> Result<(), String> {
202    Err(
203        "java-forge scenarios require building self-hosted-node with --features java-forge"
204            .to_string(),
205    )
206}
207
208#[cfg(feature = "java-forge")]
209pub fn run_self_play(
210    seats: &[DeckSelection],
211    starting_life: i32,
212    seed: u64,
213    max_prompts: usize,
214    games: usize,
215) -> Result<(), String> {
216    let config = JavaRuntimeConfig::from_env();
217    let assets_dir = config.assets_dir.to_string_lossy().to_string();
218    let bridge = SubprocessBridge::spawn(&config)?;
219    let mut session = JavaForgeSession::new(bridge);
220    session.initialize(&assets_dir)?;
221
222    let mut players = Vec::with_capacity(seats.len());
223    for (i, seat) in seats.iter().enumerate() {
224        let identities = deck_card_identities(&seat.deck);
225        players.push(PlayerConfig::new(
226            format!("Self-Play {}", i + 1),
227            &identities,
228            commander_names_for_java(&seat.deck, seat.commander_name.as_deref()),
229        ));
230    }
231
232    for game_index in 0..games.max(1) {
233        let request = StartGameRequest::new(
234            format!("self-hosted-java-self-play-{game_index}"),
235            String::new(),
236            starting_life,
237            seed.wrapping_add(game_index as u64),
238            players.clone(),
239        );
240        let session_id = session.start_game(&request)?;
241        info!(
242            session_id,
243            game_index,
244            games,
245            players = seats.len(),
246            starting_life,
247            max_prompts,
248            "java-forge self-play game started"
249        );
250        let result = run_self_play_loop(&mut session, max_prompts);
251        let end_result = session.end_game();
252        result.and(end_result)?;
253    }
254    Ok(())
255}
256
257#[cfg(not(feature = "java-forge"))]
258pub fn run_self_play(
259    _seats: &[DeckSelection],
260    _starting_life: i32,
261    _seed: u64,
262    _max_prompts: usize,
263    _games: usize,
264) -> Result<(), String> {
265    Err(
266        "java-forge self-play requires building self-hosted-node with --features java-forge"
267            .to_string(),
268    )
269}
270
271#[cfg(feature = "java-forge")]
272type SharedBridge = Arc<Mutex<SubprocessBridge>>;
273
274#[cfg(feature = "java-forge")]
275struct PoolSlot {
276    bridge: SharedBridge,
277    active: usize,
278}
279
280#[cfg(feature = "java-forge")]
281pub struct JavaEnginePool {
282    config: JavaRuntimeConfig,
283    max_sessions: usize,
284    sessions_per_process: usize,
285    slots: Mutex<Vec<PoolSlot>>,
286    in_use: Mutex<HashMap<String, SharedBridge>>,
287}
288
289#[cfg(feature = "java-forge")]
290#[derive(Clone)]
291pub struct JavaEngineHandle {
292    pool: Arc<JavaEnginePool>,
293}
294
295#[cfg(feature = "java-forge")]
296impl JavaEnginePool {
297    pub fn start(
298        config: &JavaRuntimeConfig,
299        max_sessions: usize,
300        sessions_per_process: usize,
301    ) -> Result<Arc<Self>, String> {
302        let max_sessions = max_sessions.max(1);
303        let sessions_per_process = sessions_per_process.max(1);
304        let processes = max_sessions.div_ceil(sessions_per_process);
305        let mut slots = Vec::with_capacity(processes);
306        for slot in 0..processes {
307            info!(
308                slot,
309                processes, sessions_per_process, "pre-warming java subprocess"
310            );
311            let bridge = SubprocessBridge::spawn(config)?;
312            slots.push(PoolSlot {
313                bridge: Arc::new(Mutex::new(bridge)),
314                active: 0,
315            });
316        }
317        Ok(Arc::new(Self {
318            config: config.clone(),
319            max_sessions,
320            sessions_per_process,
321            slots: Mutex::new(slots),
322            in_use: Mutex::new(HashMap::new()),
323        }))
324    }
325
326    pub fn handle(self: &Arc<Self>) -> JavaEngineHandle {
327        JavaEngineHandle {
328            pool: Arc::clone(self),
329        }
330    }
331}
332
333#[cfg(feature = "java-forge")]
334impl Drop for JavaEnginePool {
335    fn drop(&mut self) {
336        let slots = self.slots.get_mut().map(std::mem::take).unwrap_or_default();
337        for slot in slots {
338            if let Ok(mutex) = Arc::try_unwrap(slot.bridge) {
339                if let Ok(inner) = mutex.into_inner() {
340                    inner.shutdown();
341                }
342            }
343        }
344    }
345}
346
347#[cfg(feature = "java-forge")]
348impl JavaEnginePool {
349    fn acquire(&self) -> Result<SharedBridge, String> {
350        let deadline = Instant::now() + Duration::from_secs(60);
351        loop {
352            let claimed = {
353                let mut slots = self
354                    .slots
355                    .lock()
356                    .map_err(|_| "java engine slots poisoned".to_string())?;
357                let mut claimed = None;
358                for slot in slots.iter_mut() {
359                    if slot.active < self.sessions_per_process {
360                        slot.active += 1;
361                        claimed = Some(Arc::clone(&slot.bridge));
362                        break;
363                    }
364                }
365                claimed
366            };
367            if let Some(bridge) = claimed {
368                let alive = bridge
369                    .lock()
370                    .ok()
371                    .map(|mut guard| guard.is_alive())
372                    .unwrap_or(false);
373                if alive {
374                    return Ok(bridge);
375                }
376                warn!("discarding dead java subprocess from pool");
377                self.replace_slot(&bridge);
378                continue;
379            }
380            if Instant::now() >= deadline {
381                return Err(format!(
382                    "java engine pool exhausted (max_sessions={}); no free session slot after 60s",
383                    self.max_sessions
384                ));
385            }
386            std::thread::sleep(Duration::from_millis(50));
387        }
388    }
389
390    fn release(&self, bridge: SharedBridge) {
391        let now_idle = {
392            let mut slots = match self.slots.lock() {
393                Ok(slots) => slots,
394                Err(_) => return,
395            };
396            match slots.iter_mut().find(|s| Arc::ptr_eq(&s.bridge, &bridge)) {
397                Some(slot) => {
398                    slot.active = slot.active.saturating_sub(1);
399                    slot.active == 0
400                }
401                None => return,
402            }
403        };
404        if !now_idle {
405            return;
406        }
407        let healthy = {
408            let mut guard = match bridge.lock() {
409                Ok(guard) => guard,
410                Err(_) => return,
411            };
412            guard.is_alive() && guard.reset().is_ok()
413        };
414        if !healthy {
415            warn!("java subprocess unhealthy at idle; respawning");
416            self.replace_slot(&bridge);
417        }
418    }
419
420    fn replace_slot(&self, dead: &SharedBridge) {
421        let Ok(mut slots) = self.slots.lock() else {
422            return;
423        };
424        let Some(index) = slots.iter().position(|s| Arc::ptr_eq(&s.bridge, dead)) else {
425            return;
426        };
427        match SubprocessBridge::spawn(&self.config) {
428            Ok(replacement) => {
429                slots[index] = PoolSlot {
430                    bridge: Arc::new(Mutex::new(replacement)),
431                    active: 0,
432                };
433            }
434            Err(error) => {
435                warn!(%error, "failed to respawn java subprocess; retiring pool slot");
436                slots.remove(index);
437            }
438        }
439    }
440}
441
442#[cfg(feature = "java-forge")]
443impl JavaEngineHandle {
444    fn bridge_for(&self, session_id: &str) -> Result<SharedBridge, String> {
445        let in_use = self
446            .pool
447            .in_use
448            .lock()
449            .map_err(|_| "java engine in_use map poisoned".to_string())?;
450        in_use
451            .get(session_id)
452            .cloned()
453            .ok_or_else(|| format!("unknown java session: {session_id}"))
454    }
455
456    pub fn start_game(&self, request_json: &str) -> Result<String, String> {
457        let bridge = self.pool.acquire()?;
458        let response = {
459            let mut guard = bridge
460                .lock()
461                .map_err(|_| "java subprocess mutex poisoned".to_string())?;
462            guard.start_game_json(request_json)
463        };
464        let response = match response {
465            Ok(response) => response,
466            Err(error) => {
467                self.pool.release(bridge);
468                return Err(error);
469            }
470        };
471        let parsed: StartGameResponse = match serde_json::from_str(&response) {
472            Ok(parsed) => parsed,
473            Err(error) => {
474                self.pool.release(bridge);
475                return Err(format!("malformed startGame response: {error}"));
476            }
477        };
478        let session_id = parsed.session_id.clone();
479        let displaced = {
480            let mut in_use = self
481                .pool
482                .in_use
483                .lock()
484                .map_err(|_| "java engine in_use map poisoned".to_string())?;
485            in_use.insert(session_id.clone(), bridge)
486        };
487        if let Some(displaced) = displaced {
488            warn!(
489                session_id,
490                "session_id collision; releasing displaced java subprocess"
491            );
492            self.pool.release(displaced);
493        }
494        Ok(session_id)
495    }
496
497    pub fn submit_action(&self, session_id: &str, action_json: &str) -> Result<String, String> {
498        let bridge = self.bridge_for(session_id)?;
499        let mutex_started = Instant::now();
500        let mut guard = bridge
501            .lock()
502            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
503        crate::metrics::record_forge_decision_stage("bridge_mutex", mutex_started.elapsed());
504        let call_started = Instant::now();
505        let result = guard.submit_action(session_id, action_json);
506        crate::metrics::record_forge_decision_stage("submit_action", call_started.elapsed());
507        result
508    }
509
510    pub fn get_prompt(
511        &self,
512        session_id: &str,
513        player_index: usize,
514    ) -> Result<Option<String>, String> {
515        let bridge = self.bridge_for(session_id)?;
516        let mut guard = bridge
517            .lock()
518            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
519        guard.get_prompt(session_id, player_index)
520    }
521
522    pub fn is_game_over(&self, session_id: &str) -> Result<bool, String> {
523        let bridge = self.bridge_for(session_id)?;
524        let mut guard = bridge
525            .lock()
526            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
527        guard.is_game_over(session_id)
528    }
529
530    pub fn drain_checkpoint_metrics(&self, session_id: &str) -> Result<String, String> {
531        let bridge = self.bridge_for(session_id)?;
532        let mut guard = bridge
533            .lock()
534            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
535        guard.drain_checkpoint_metrics(session_id)
536    }
537
538    pub fn state_revision(&self, session_id: &str) -> Result<u64, String> {
539        let bridge = self.bridge_for(session_id)?;
540        let mut guard = bridge
541            .lock()
542            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
543        guard.state_revision(session_id)
544    }
545
546    pub fn get_snapshot(&self, session_id: &str, viewer: Option<usize>) -> Result<String, String> {
547        let bridge = self.bridge_for(session_id)?;
548        let mut guard = bridge
549            .lock()
550            .map_err(|_| "java subprocess mutex poisoned".to_string())?;
551        guard.get_snapshot(session_id, viewer)
552    }
553
554    pub fn end_game(&self, session_id: &str) -> Result<(), String> {
555        let bridge = {
556            let mut in_use = self
557                .pool
558                .in_use
559                .lock()
560                .map_err(|_| "java engine in_use map poisoned".to_string())?;
561            in_use.remove(session_id)
562        };
563        let Some(bridge) = bridge else {
564            return Ok(());
565        };
566        let result = {
567            let mut guard = bridge
568                .lock()
569                .map_err(|_| "java subprocess mutex poisoned".to_string())?;
570            guard.end_game(session_id)
571        };
572        self.pool.release(bridge);
573        result
574    }
575
576    pub fn abort_game(&self, session_id: &str) -> Result<(), String> {
577        let bridge = {
578            let mut in_use = self
579                .pool
580                .in_use
581                .lock()
582                .map_err(|_| "java engine in_use map poisoned".to_string())?;
583            in_use.remove(session_id)
584        };
585        let Some(bridge) = bridge else {
586            return Ok(());
587        };
588        let result = {
589            let mut guard = bridge
590                .lock()
591                .map_err(|_| "java subprocess mutex poisoned".to_string())?;
592            guard.abort_game(session_id)
593        };
594        self.pool.release(bridge);
595        result
596    }
597}
598
599#[cfg(feature = "java-forge")]
600static JAVA_ENGINE: std::sync::OnceLock<Arc<JavaEnginePool>> = std::sync::OnceLock::new();
601
602#[cfg(feature = "java-forge")]
603pub fn init_engine() -> Result<(), String> {
604    if JAVA_ENGINE.get().is_some() {
605        return Ok(());
606    }
607    let config = JavaRuntimeConfig::from_env();
608    // SELF_HOSTED_NODE_MAX_GAMES is the concurrent-session ceiling for this node.
609    // SELF_HOSTED_NODE_GAMES_PER_JVM multiplexes that many sessions into each
610    // subprocess (the engine is concurrency-safe since the endstep patches), so
611    // the pool spawns ceil(max_games / games_per_jvm) processes. Default 1 keeps
612    // the historical one-subprocess-per-game shape.
613    let max_sessions = env::var("SELF_HOSTED_NODE_MAX_GAMES")
614        .ok()
615        .and_then(|value| value.parse::<usize>().ok())
616        .filter(|n| *n >= 1)
617        .unwrap_or(1);
618    let sessions_per_process = env::var("SELF_HOSTED_NODE_GAMES_PER_JVM")
619        .ok()
620        .and_then(|value| value.parse::<usize>().ok())
621        .filter(|n| *n >= 1)
622        .unwrap_or(1);
623    let pool = JavaEnginePool::start(&config, max_sessions, sessions_per_process)?;
624    JAVA_ENGINE
625        .set(pool)
626        .map_err(|_| "java engine already initialized".to_string())
627}
628
629#[cfg(all(feature = "graal-forge", not(feature = "java-forge")))]
630pub fn init_engine() -> Result<(), String> {
631    // Loading the card database into the isolate takes tens of seconds on a
632    // small box. Pay it here, before any room is advertised, rather than
633    // leaving it for whoever starts the first game.
634    if shared_isolate_enabled() {
635        drop(GraalEngineHandle::create(
636            &JavaRuntimeConfig::from_env().assets_dir,
637        )?);
638    }
639    Ok(())
640}
641
642#[cfg(not(forge_backend))]
643pub fn init_engine() -> Result<(), String> {
644    Err(
645        "forge engine requires building self-hosted-node with --features java-forge or graal-forge"
646            .to_string(),
647    )
648}
649
650#[cfg(feature = "java-forge")]
651fn engine_handle() -> Result<JavaEngineHandle, String> {
652    JAVA_ENGINE
653        .get()
654        .map(JavaEnginePool::handle)
655        .ok_or_else(|| "java engine is not initialized".to_string())
656}
657
658#[cfg(feature = "java-forge")]
659type ForgeEngine = JavaEngineHandle;
660
661#[cfg(feature = "java-forge")]
662fn obtain_engine() -> Result<ForgeEngine, String> {
663    engine_handle()
664}
665
666#[cfg(all(feature = "graal-forge", not(feature = "java-forge")))]
667type ForgeEngine = GraalEngineHandle;
668
669#[cfg(all(feature = "graal-forge", not(feature = "java-forge")))]
670fn obtain_engine() -> Result<ForgeEngine, String> {
671    GraalEngineHandle::create(&JavaRuntimeConfig::from_env().assets_dir)
672}
673
674#[cfg(feature = "graal-forge")]
675mod graal_ffi {
676    use std::os::raw::{c_char, c_int};
677
678    #[allow(non_camel_case_types)]
679    pub type graal_isolate_t = std::ffi::c_void;
680    #[allow(non_camel_case_types)]
681    pub type graal_isolatethread_t = std::ffi::c_void;
682
683    extern "C" {
684        pub fn graal_create_isolate(
685            params: *mut std::ffi::c_void,
686            isolate: *mut *mut graal_isolate_t,
687            thread: *mut *mut graal_isolatethread_t,
688        ) -> c_int;
689        pub fn graal_tear_down_isolate(thread: *mut graal_isolatethread_t) -> c_int;
690        pub fn graal_attach_thread(
691            isolate: *mut graal_isolate_t,
692            thread: *mut *mut graal_isolatethread_t,
693        ) -> c_int;
694        pub fn graal_detach_thread(thread: *mut graal_isolatethread_t) -> c_int;
695        pub fn forge_initialize(
696            thread: *mut graal_isolatethread_t,
697            assets_dir: *const c_char,
698        ) -> *mut c_char;
699        pub fn forge_start_game(
700            thread: *mut graal_isolatethread_t,
701            request_json: *const c_char,
702        ) -> *mut c_char;
703        pub fn forge_submit_action(
704            thread: *mut graal_isolatethread_t,
705            session_id: *const c_char,
706            action_json: *const c_char,
707        ) -> *mut c_char;
708        pub fn forge_get_prompt(
709            thread: *mut graal_isolatethread_t,
710            session_id: *const c_char,
711            player_index: c_int,
712        ) -> *mut c_char;
713        pub fn forge_get_snapshot(
714            thread: *mut graal_isolatethread_t,
715            session_id: *const c_char,
716            viewer: c_int,
717        ) -> *mut c_char;
718        pub fn forge_get_game_over(
719            thread: *mut graal_isolatethread_t,
720            session_id: *const c_char,
721        ) -> *mut c_char;
722        pub fn forge_drain_checkpoint_metrics(
723            thread: *mut graal_isolatethread_t,
724            session_id: *const c_char,
725        ) -> *mut c_char;
726        pub fn forge_get_state_revision(
727            thread: *mut graal_isolatethread_t,
728            session_id: *const c_char,
729        ) -> *mut c_char;
730        pub fn forge_end_game(
731            thread: *mut graal_isolatethread_t,
732            session_id: *const c_char,
733        ) -> *mut c_char;
734        pub fn forge_abort_game(
735            thread: *mut graal_isolatethread_t,
736            session_id: *const c_char,
737        ) -> *mut c_char;
738        pub fn forge_free_string(thread: *mut graal_isolatethread_t, ptr: *mut c_char);
739        pub fn forge_dump_heap(
740            thread: *mut graal_isolatethread_t,
741            path: *const c_char,
742            live_objects_only: c_int,
743        ) -> *mut c_char;
744        pub fn forge_gc_stats(thread: *mut graal_isolatethread_t) -> *mut c_char;
745    }
746}
747
748/// Isolate-wide GC and heap counters, as reported by the engine itself.
749/// `collections` and `pause_millis` are -1 when the native image exposes no
750/// collector beans; the heap figures are always present.
751#[cfg(feature = "graal-forge")]
752#[derive(serde::Deserialize)]
753#[serde(rename_all = "camelCase")]
754pub struct GcStats {
755    pub heap_used_bytes: u64,
756    pub heap_total_bytes: u64,
757    pub heap_max_bytes: u64,
758    pub collections: i64,
759    pub pause_millis: i64,
760    /// Keyed by collector name. An incremental collection is a few milliseconds;
761    /// a complete one traces the whole live set, which here is a permanently
762    /// reachable card database, so it costs the same whether it reclaims
763    /// anything or not. The totals above hide that difference.
764    #[serde(default)]
765    pub by_collector: std::collections::HashMap<String, GcCollector>,
766    /// Wall clock the engine was stopped, measured inside the isolate by sleep
767    /// overshoot rather than by the collector, because a G1 image registers no
768    /// collector beans and leaves every field above at zero. Counts scheduler
769    /// preemption as well as collection pauses.
770    #[serde(default)]
771    pub stalled_millis: u64,
772    #[serde(default)]
773    pub max_stall_millis: u64,
774    #[serde(default)]
775    pub long_stalls: u64,
776}
777
778#[cfg(feature = "graal-forge")]
779#[derive(serde::Deserialize)]
780#[serde(rename_all = "camelCase")]
781pub struct GcCollector {
782    pub collections: u64,
783    pub pause_millis: u64,
784}
785
786#[cfg(feature = "graal-forge")]
787#[derive(serde::Deserialize)]
788struct ForgeReply {
789    ok: bool,
790    #[serde(default)]
791    result: String,
792    #[serde(default)]
793    error: Option<String>,
794}
795
796// A GraalVM isolate hosts the in-process Forge engine. The `thread` handle is
797// bound to the hosted-engine thread that created or attached it (isolate
798// threads are not portable), so the handle is Rc/!Send by design. In shared
799// mode one isolate serves all rooms: the first creator initializes Forge, later
800// rooms attach their own thread to it and sessions coexist in the adapter.
801#[cfg(feature = "graal-forge")]
802struct GraalBridge {
803    thread: *mut graal_ffi::graal_isolatethread_t,
804    attached: bool,
805}
806
807#[cfg(feature = "graal-forge")]
808struct SharedIsolate(*mut graal_ffi::graal_isolate_t);
809#[cfg(feature = "graal-forge")]
810unsafe impl Send for SharedIsolate {}
811
812#[cfg(feature = "graal-forge")]
813static SHARED_GRAAL_ISOLATE: std::sync::Mutex<Option<SharedIsolate>> = std::sync::Mutex::new(None);
814
815// One isolate hosts every room's game (safe since the endstep concurrency
816// patches), so the card database loads once per node. Off keeps the historical
817// isolate-per-game shape.
818#[cfg(feature = "graal-forge")]
819fn shared_isolate_enabled() -> bool {
820    let asked = env::var("SELF_HOSTED_NODE_SHARED_ISOLATE")
821        .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
822        .unwrap_or(false);
823    // G1 permits one isolate per process and aborts the process on the second:
824    //   guarantee(SVMIsolateData::_heap_base == nullptr) failed:
825    //   G1 doesn't support multiple isolates at the moment.
826    // The published image is built with G1, and the collector is fixed at build
827    // time and not visible from here, so isolate-per-game cannot be honoured
828    // without risking that abort on the second room. One isolate is correct for
829    // a Serial build too — it is what production has run since the card
830    // database became shared — so this is forced rather than merely defaulted.
831    if !asked {
832        warn!(
833            "isolate-per-game is not available: the engine image is built with G1, \
834             which aborts on a second isolate. Hosting every room in one isolate."
835        );
836    }
837    true
838}
839
840#[cfg(feature = "graal-forge")]
841impl GraalBridge {
842    fn create() -> Result<Self, String> {
843        let mut isolate: *mut graal_ffi::graal_isolate_t = std::ptr::null_mut();
844        let mut thread: *mut graal_ffi::graal_isolatethread_t = std::ptr::null_mut();
845        let rc = unsafe {
846            graal_ffi::graal_create_isolate(std::ptr::null_mut(), &mut isolate, &mut thread)
847        };
848        if rc != 0 {
849            return Err(format!("graal_create_isolate failed with code {rc}"));
850        }
851        Ok(Self {
852            thread,
853            attached: false,
854        })
855    }
856
857    fn create_in_shared_isolate(assets_dir: &Path) -> Result<Self, String> {
858        let mut guard = SHARED_GRAAL_ISOLATE
859            .lock()
860            .map_err(|_| "shared graal isolate poisoned".to_string())?;
861        if let Some(shared) = guard.as_ref() {
862            let mut thread: *mut graal_ffi::graal_isolatethread_t = std::ptr::null_mut();
863            let rc = unsafe { graal_ffi::graal_attach_thread(shared.0, &mut thread) };
864            if rc != 0 {
865                return Err(format!("graal_attach_thread failed with code {rc}"));
866            }
867            return Ok(Self {
868                thread,
869                attached: true,
870            });
871        }
872        let mut isolate: *mut graal_ffi::graal_isolate_t = std::ptr::null_mut();
873        let mut thread: *mut graal_ffi::graal_isolatethread_t = std::ptr::null_mut();
874        let rc = unsafe {
875            graal_ffi::graal_create_isolate(std::ptr::null_mut(), &mut isolate, &mut thread)
876        };
877        if rc != 0 {
878            return Err(format!("graal_create_isolate failed with code {rc}"));
879        }
880        let mut bridge = Self {
881            thread,
882            attached: false,
883        };
884        let assets = cstring(&assets_dir.to_string_lossy())?;
885        bridge.decode(unsafe { graal_ffi::forge_initialize(bridge.thread, assets.as_ptr()) })?;
886        bridge.attached = true;
887        *guard = Some(SharedIsolate(isolate));
888        info!("shared graal isolate initialized");
889        Ok(bridge)
890    }
891
892    fn decode(&self, raw: *mut std::os::raw::c_char) -> Result<String, String> {
893        if raw.is_null() {
894            return Err("forge native lib returned null".to_string());
895        }
896        let envelope = unsafe { std::ffi::CStr::from_ptr(raw) }
897            .to_string_lossy()
898            .into_owned();
899        unsafe { graal_ffi::forge_free_string(self.thread, raw) };
900        let reply: ForgeReply = serde_json::from_str(&envelope)
901            .map_err(|err| format!("malformed forge envelope: {err}"))?;
902        if reply.ok {
903            Ok(reply.result)
904        } else {
905            Err(reply
906                .error
907                .unwrap_or_else(|| "unknown forge error".to_string()))
908        }
909    }
910}
911
912#[cfg(feature = "graal-forge")]
913impl Drop for GraalBridge {
914    fn drop(&mut self) {
915        if self.attached {
916            unsafe { graal_ffi::graal_detach_thread(self.thread) };
917        } else {
918            // Reachable only from the isolate-per-game path, which
919            // `shared_isolate_enabled` forces off. Teardown refuses while any
920            // thread is still attached, and the engine now keeps a permanent
921            // stall-probe thread inside the isolate, so restoring that path
922            // means giving the probe a way to be stopped first.
923            unsafe { graal_ffi::graal_tear_down_isolate(self.thread) };
924        }
925    }
926}
927
928#[cfg(feature = "graal-forge")]
929#[derive(Clone)]
930struct GraalEngineHandle {
931    bridge: std::rc::Rc<GraalBridge>,
932}
933
934#[cfg(feature = "graal-forge")]
935impl GraalEngineHandle {
936    fn create(assets_dir: &Path) -> Result<Self, String> {
937        let shared = shared_isolate_enabled();
938        let bridge = if shared {
939            GraalBridge::create_in_shared_isolate(assets_dir)?
940        } else {
941            let bridge = GraalBridge::create()?;
942            let assets = cstring(&assets_dir.to_string_lossy())?;
943            bridge
944                .decode(unsafe { graal_ffi::forge_initialize(bridge.thread, assets.as_ptr()) })?;
945            bridge
946        };
947        if shared {
948            start_engine_gc_sampler();
949        }
950        Ok(Self {
951            bridge: std::rc::Rc::new(bridge),
952        })
953    }
954
955    fn start_game(&self, request_json: &str) -> Result<String, String> {
956        let request = cstring(request_json)?;
957        let response = self
958            .bridge
959            .decode(unsafe { graal_ffi::forge_start_game(self.bridge.thread, request.as_ptr()) })?;
960        let parsed: StartGameResponse = serde_json::from_str(&response)
961            .map_err(|err| format!("malformed startGame response: {err}"))?;
962        Ok(parsed.session_id)
963    }
964
965    fn submit_action(&self, session_id: &str, action_json: &str) -> Result<String, String> {
966        let session = cstring(session_id)?;
967        let action = cstring(action_json)?;
968        let started = Instant::now();
969        let result = self.bridge.decode(unsafe {
970            graal_ffi::forge_submit_action(self.bridge.thread, session.as_ptr(), action.as_ptr())
971        });
972        crate::metrics::record_forge_decision_stage("submit_action", started.elapsed());
973        result
974    }
975
976    /// Cumulative collections, pause time and heap for the whole isolate. Every
977    /// room on this node shares it, so a collection here stops all of them.
978    fn gc_stats(&self) -> Result<GcStats, String> {
979        gc_stats_via(&self.bridge)
980    }
981
982    fn get_prompt(&self, session_id: &str, player_index: usize) -> Result<Option<String>, String> {
983        let session = cstring(session_id)?;
984        let prompt = self.bridge.decode(unsafe {
985            graal_ffi::forge_get_prompt(
986                self.bridge.thread,
987                session.as_ptr(),
988                player_index as std::os::raw::c_int,
989            )
990        })?;
991        Ok((!prompt.is_empty()).then_some(prompt))
992    }
993
994    fn is_game_over(&self, session_id: &str) -> Result<bool, String> {
995        let session = cstring(session_id)?;
996        let value = self.bridge.decode(unsafe {
997            graal_ffi::forge_get_game_over(self.bridge.thread, session.as_ptr())
998        })?;
999        Ok(value.trim() == "true")
1000    }
1001
1002    fn drain_checkpoint_metrics(&self, session_id: &str) -> Result<String, String> {
1003        let session = cstring(session_id)?;
1004        self.bridge.decode(unsafe {
1005            graal_ffi::forge_drain_checkpoint_metrics(self.bridge.thread, session.as_ptr())
1006        })
1007    }
1008
1009    fn state_revision(&self, session_id: &str) -> Result<u64, String> {
1010        let session = cstring(session_id)?;
1011        let value = self.bridge.decode(unsafe {
1012            graal_ffi::forge_get_state_revision(self.bridge.thread, session.as_ptr())
1013        })?;
1014        parse_state_revision(&value)
1015    }
1016
1017    fn get_snapshot(&self, session_id: &str, viewer: Option<usize>) -> Result<String, String> {
1018        let session = cstring(session_id)?;
1019        let viewer = viewer.map_or(-1, |v| v as std::os::raw::c_int);
1020        self.bridge.decode(unsafe {
1021            graal_ffi::forge_get_snapshot(self.bridge.thread, session.as_ptr(), viewer)
1022        })
1023    }
1024
1025    fn end_game(&self, session_id: &str) -> Result<(), String> {
1026        let session = cstring(session_id)?;
1027        self.bridge
1028            .decode(unsafe { graal_ffi::forge_end_game(self.bridge.thread, session.as_ptr()) })
1029            .map(|_| ())
1030    }
1031
1032    fn abort_game(&self, session_id: &str) -> Result<(), String> {
1033        let session = cstring(session_id)?;
1034        self.bridge
1035            .decode(unsafe { graal_ffi::forge_abort_game(self.bridge.thread, session.as_ptr()) })
1036            .map(|_| ())
1037    }
1038}
1039
1040/// Write an hprof dump of the shared isolate's heap. Attaches its own isolate
1041/// thread, so it is callable from a signal handler task rather than the engine
1042/// thread that owns the room's bridge.
1043#[cfg(feature = "graal-forge")]
1044pub fn dump_shared_heap(path: &str) -> Result<(), String> {
1045    let isolate = SHARED_GRAAL_ISOLATE
1046        .lock()
1047        .map_err(|_| "shared graal isolate poisoned".to_string())?
1048        .as_ref()
1049        .map(|shared| shared.0)
1050        .ok_or_else(|| "no shared isolate to dump".to_string())?;
1051    let mut thread: *mut graal_ffi::graal_isolatethread_t = std::ptr::null_mut();
1052    let rc = unsafe { graal_ffi::graal_attach_thread(isolate, &mut thread) };
1053    if rc != 0 {
1054        return Err(format!("graal_attach_thread failed with code {rc}"));
1055    }
1056    let bridge = GraalBridge {
1057        thread,
1058        attached: true,
1059    };
1060    let target = cstring(path)?;
1061    bridge
1062        .decode(unsafe { graal_ffi::forge_dump_heap(bridge.thread, target.as_ptr(), 1) })
1063        .map(|_| ())
1064}
1065
1066#[cfg(feature = "graal-forge")]
1067fn cstring(value: &str) -> Result<std::ffi::CString, String> {
1068    std::ffi::CString::new(value).map_err(|_| "string contained interior NUL".to_string())
1069}
1070
1071#[cfg(feature = "java-forge")]
1072pub fn run_concurrent_self_play(
1073    seats: &[DeckSelection],
1074    starting_life: i32,
1075    seed: u64,
1076    max_prompts: usize,
1077    concurrency: usize,
1078) -> Result<(), String> {
1079    let config = JavaRuntimeConfig::from_env();
1080    let games_per_process = env::var("SELF_HOSTED_NODE_GAMES_PER_JVM")
1081        .ok()
1082        .and_then(|value| value.parse::<usize>().ok())
1083        .filter(|n| *n >= 1)
1084        .unwrap_or(1);
1085    let pool = JavaEnginePool::start(&config, concurrency.max(1), games_per_process)?;
1086    info!(
1087        concurrency,
1088        "java-engine started; launching concurrent games"
1089    );
1090
1091    let mut players = Vec::with_capacity(seats.len());
1092    for (i, seat) in seats.iter().enumerate() {
1093        let identities = deck_card_identities(&seat.deck);
1094        players.push(PlayerConfig::new(
1095            format!("Self-Play {}", i + 1),
1096            &identities,
1097            commander_names_for_java(&seat.deck, seat.commander_name.as_deref()),
1098        ));
1099    }
1100
1101    let mut joins = Vec::with_capacity(concurrency.max(1));
1102    for game_index in 0..concurrency.max(1) {
1103        let handle = pool.handle();
1104        let request = StartGameRequest::new(
1105            format!("self-hosted-java-concurrent-{game_index}"),
1106            String::new(),
1107            starting_life,
1108            seed.wrapping_add(game_index as u64),
1109            players.clone(),
1110        );
1111        joins.push(std::thread::spawn(move || -> Result<(), String> {
1112            let request_json = request.to_json().map_err(|error| error.to_string())?;
1113            let session_id = handle.start_game(&request_json)?;
1114            info!(session_id, game_index, "concurrent java game started");
1115            let result = drive_game_via_handle(&handle, &session_id, max_prompts);
1116            let _ = handle.end_game(&session_id);
1117            result
1118        }));
1119    }
1120
1121    let mut outcome = Ok(());
1122    for join in joins {
1123        match join.join() {
1124            Ok(Ok(())) => {}
1125            Ok(Err(error)) => outcome = Err(error),
1126            Err(_) => outcome = Err("concurrent game thread panicked".to_string()),
1127        }
1128    }
1129    outcome
1130}
1131
1132#[cfg(not(feature = "java-forge"))]
1133pub fn run_concurrent_self_play(
1134    _seats: &[DeckSelection],
1135    _starting_life: i32,
1136    _seed: u64,
1137    _max_prompts: usize,
1138    _concurrency: usize,
1139) -> Result<(), String> {
1140    Err(
1141        "java-forge concurrent self-play requires building self-hosted-node with --features java-forge"
1142            .to_string(),
1143    )
1144}
1145
1146#[cfg(all(feature = "graal-forge", not(feature = "java-forge")))]
1147fn report_engine_gc(engine: &ForgeEngine) {
1148    match engine.gc_stats() {
1149        Ok(stats) => publish_engine_gc(&stats),
1150        Err(err) => debug!(%err, "engine gc stats unavailable"),
1151    }
1152}
1153
1154#[cfg(feature = "graal-forge")]
1155fn publish_engine_gc(stats: &GcStats) {
1156    crate::metrics::record_engine_gc(
1157        stats.collections,
1158        stats.pause_millis,
1159        stats.heap_used_bytes,
1160        stats.heap_max_bytes,
1161    );
1162    crate::metrics::record_engine_stall(
1163        stats.stalled_millis,
1164        stats.max_stall_millis,
1165        stats.long_stalls,
1166    );
1167    for (name, per) in &stats.by_collector {
1168        crate::metrics::record_engine_gc_collector(name, per.collections, per.pause_millis);
1169    }
1170}
1171
1172#[cfg(feature = "graal-forge")]
1173fn gc_stats_via(bridge: &GraalBridge) -> Result<GcStats, String> {
1174    let raw = bridge.decode(unsafe { graal_ffi::forge_gc_stats(bridge.thread) })?;
1175    serde_json::from_str(&raw).map_err(|err| format!("malformed gcStats response: {err}"))
1176}
1177
1178#[cfg(feature = "graal-forge")]
1179const ENGINE_GC_SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
1180
1181/// Sampling on the decision path made an idle node and a wedged node look the
1182/// same: both stop reporting. A node that is stalling is exactly the node that
1183/// stops completing decisions, so the sample has to come from a thread that is
1184/// not on that path. It attaches its own isolate thread because the handles the
1185/// rooms hold are bound to their creating thread.
1186#[cfg(feature = "graal-forge")]
1187fn start_engine_gc_sampler() {
1188    static STARTED: std::sync::Once = std::sync::Once::new();
1189    STARTED.call_once(|| {
1190        let spawned = std::thread::Builder::new()
1191            .name("engine-gc-sampler".to_string())
1192            .spawn(|| {
1193                let isolate = match SHARED_GRAAL_ISOLATE.lock() {
1194                    Ok(guard) => guard.as_ref().map(|shared| shared.0),
1195                    Err(_) => None,
1196                };
1197                let Some(isolate) = isolate else {
1198                    return;
1199                };
1200                let mut thread: *mut graal_ffi::graal_isolatethread_t = std::ptr::null_mut();
1201                let rc = unsafe { graal_ffi::graal_attach_thread(isolate, &mut thread) };
1202                if rc != 0 {
1203                    warn!(rc, "gc sampler could not attach to the engine isolate");
1204                    return;
1205                }
1206                let bridge = GraalBridge {
1207                    thread,
1208                    attached: true,
1209                };
1210                loop {
1211                    std::thread::sleep(ENGINE_GC_SAMPLE_INTERVAL);
1212                    match gc_stats_via(&bridge) {
1213                        Ok(stats) => publish_engine_gc(&stats),
1214                        Err(err) => debug!(%err, "engine gc stats unavailable"),
1215                    }
1216                }
1217            });
1218        if let Err(err) = spawned {
1219            warn!(%err, "could not start the engine gc sampler");
1220        }
1221    });
1222}
1223
1224/// The subprocess backend already reports this by parsing its own GC log.
1225#[cfg(feature = "java-forge")]
1226fn report_engine_gc(_engine: &ForgeEngine) {}
1227
1228#[cfg(feature = "java-forge")]
1229fn drive_game_via_handle(
1230    handle: &JavaEngineHandle,
1231    session_id: &str,
1232    max_prompts: usize,
1233) -> Result<(), String> {
1234    let mut bots: HashMap<usize, SimpleAi> = HashMap::new();
1235    let mut last_prompt: Option<String> = None;
1236    let mut acted = 0usize;
1237    let mut seen_prompt = false;
1238    let max_iterations = max_prompts.saturating_mul(200).max(2_000);
1239
1240    for _ in 0..max_iterations {
1241        if let Some(prompt_json) = handle.get_prompt(session_id, 0)? {
1242            seen_prompt = true;
1243            if last_prompt.as_deref() == Some(prompt_json.as_str()) {
1244                if handle.is_game_over(session_id)? {
1245                    return Ok(());
1246                }
1247                std::thread::sleep(Duration::from_millis(20));
1248                continue;
1249            }
1250            let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
1251                .map_err(|error| format!("failed to parse concurrent prompt: {error}"))?;
1252            let player = player_index(&prompt.deciding_player_id);
1253            if let Some(action) = bots.entry(player).or_default().decide(prompt) {
1254                let action_json = serde_json::to_string(&action).map_err(|err| err.to_string())?;
1255                handle.submit_action(session_id, &action_json)?;
1256                acted += 1;
1257                if acted >= max_prompts {
1258                    return Err(format!(
1259                        "concurrent game {session_id} did not finish within {max_prompts} decisions"
1260                    ));
1261                }
1262            }
1263            last_prompt = Some(prompt_json);
1264            continue;
1265        }
1266        if seen_prompt && handle.is_game_over(session_id)? {
1267            return Ok(());
1268        }
1269        std::thread::sleep(Duration::from_millis(20));
1270    }
1271    Err(format!(
1272        "concurrent game {session_id} exceeded its iteration cap"
1273    ))
1274}
1275
1276/// G1 keeps pauses roughly bounded as the live set grows; Serial does not.
1277const DEFAULT_JAVA_COLLECTOR: &str = "G1";
1278const DEFAULT_JAVA_GC_LOG: &str = "stderr";
1279const DEFAULT_JAVA_HEAP_MB: u64 = 1024;
1280const DEFAULT_JAVA_ACTIVE_PROCESSORS: u64 = 2;
1281
1282#[derive(Debug, Clone)]
1283pub struct JavaRuntimeConfig {
1284    pub assets_dir: PathBuf,
1285    pub harness_jar: PathBuf,
1286    pub java_home: Option<PathBuf>,
1287    pub extra_classpath: Vec<PathBuf>,
1288    pub heap_mb: Option<u64>,
1289    pub active_processor_count: Option<u64>,
1290    pub gc_log: Option<String>,
1291    pub collector: Option<String>,
1292    pub extra_jvm_args: Vec<String>,
1293}
1294
1295impl JavaRuntimeConfig {
1296    pub fn from_env() -> Self {
1297        let root = workspace_root();
1298        Self {
1299            assets_dir: env_path("SELF_HOSTED_NODE_FORGE_ASSETS_DIR")
1300                .or_else(|| env_path("MANA_BREW_FORGE_ASSETS_DIR"))
1301                .unwrap_or_else(|| root.join("forge/forge-gui")),
1302            harness_jar: env_path("SELF_HOSTED_NODE_FORGE_HARNESS_JAR")
1303                .or_else(|| env_path("MANA_BREW_FORGE_HARNESS_JAR"))
1304                .unwrap_or_else(|| {
1305                    root.join("forge-harness/target/forge-harness-jar-with-dependencies.jar")
1306                }),
1307            java_home: env_path("SELF_HOSTED_NODE_JAVA_HOME")
1308                .or_else(|| env_path("MANA_BREW_JAVA_HOME"))
1309                .or_else(|| env_path("JAVA_HOME")),
1310            extra_classpath: env_classpath("SELF_HOSTED_NODE_FORGE_EXTRA_CLASSPATH")
1311                .into_iter()
1312                .chain(env_classpath("MANA_BREW_FORGE_EXTRA_CLASSPATH"))
1313                .collect(),
1314            heap_mb: env_sizing("SELF_HOSTED_NODE_JAVA_HEAP_MB", DEFAULT_JAVA_HEAP_MB),
1315            active_processor_count: env_sizing(
1316                "SELF_HOSTED_NODE_JAVA_ACTIVE_PROCESSORS",
1317                DEFAULT_JAVA_ACTIVE_PROCESSORS,
1318            ),
1319            collector: env::var("SELF_HOSTED_NODE_JAVA_COLLECTOR")
1320                .ok()
1321                .map(|value| value.trim().to_string())
1322                .filter(|value| !value.is_empty())
1323                .or_else(|| Some(DEFAULT_JAVA_COLLECTOR.to_string())),
1324            // Defaults on: the fleet ships no logs, so this log exists to be
1325            // turned into metrics by the stderr pump (see metrics.rs).
1326            gc_log: env::var("SELF_HOSTED_NODE_JAVA_GC_LOG")
1327                .ok()
1328                .map(|value| value.trim().to_string())
1329                .filter(|value| !value.is_empty())
1330                .or_else(|| Some(DEFAULT_JAVA_GC_LOG.to_string())),
1331            extra_jvm_args: env::var("SELF_HOSTED_NODE_JAVA_OPTS")
1332                .unwrap_or_default()
1333                .split_whitespace()
1334                .map(str::to_string)
1335                .collect(),
1336        }
1337    }
1338
1339    #[cfg(feature = "java-forge")]
1340    fn jvm_args(&self) -> Vec<String> {
1341        let mut args = vec![
1342            "-Dfile.encoding=UTF-8".to_string(),
1343            "-Dsun.stdout.encoding=UTF-8".to_string(),
1344            "-Dsun.stderr.encoding=UTF-8".to_string(),
1345            "-Djava.awt.headless=true".to_string(),
1346            // Forge's endstep concurrency patches assume a heap exhaustion kills the process
1347            // instead of thrashing; a supervised node is restarted, a thrashing one is not.
1348            "-XX:+ExitOnOutOfMemoryError".to_string(),
1349            // Forge calls System.gc() on match boundaries (Match.java,
1350            // HostedMatch.java) and so does the harness. Each one is a full
1351            // collection, and a full collection costs about 1.3ms per MB of
1352            // live set, so on a large board they are seconds of stop-the-world
1353            // for no benefit the collector would not have reached anyway.
1354            "-XX:+DisableExplicitGC".to_string(),
1355        ];
1356        // Pause time is linear in the live set and Serial collects on one
1357        // thread, so a bigger heap under Serial means longer freezes, not
1358        // shorter ones. Name the collector rather than inheriting whatever the
1359        // host's environment happens to set.
1360        if let Some(collector) = &self.collector {
1361            args.push(format!("-XX:+Use{collector}GC"));
1362        }
1363        // A fleet runs many of these side by side, and every JVM sizes its heap and its GC
1364        // thread count from the whole machine unless told otherwise.
1365        if let Some(heap_mb) = self.heap_mb {
1366            args.push(format!("-Xmx{heap_mb}m"));
1367        }
1368        if let Some(processors) = self.active_processor_count {
1369            args.push(format!("-XX:ActiveProcessorCount={processors}"));
1370        }
1371        // In a container the only log that reaches Loki is the node's own, and the
1372        // subprocess owns stdout for the protocol, so "stderr" routes GC through the
1373        // stderr pump instead of a file nothing ships.
1374        match self.gc_log.as_deref() {
1375            None => {}
1376            Some("stderr") => args.push("-Xlog:gc*:stderr:time,uptime,level,tags".to_string()),
1377            Some(dir) => args.push(format!(
1378                "-Xlog:gc*:file={}:time,uptime,level,tags:filecount=5,filesize=20M",
1379                Path::new(dir).join("engine-gc-%p.log").display()
1380            )),
1381        }
1382        args.extend(self.extra_jvm_args.iter().cloned());
1383        args
1384    }
1385
1386    pub fn validate(&self) -> Result<(), String> {
1387        require_dir(&self.assets_dir, "Forge assets directory")?;
1388        require_file(&self.harness_jar, "Forge harness jar")?;
1389        if let Some(java_home) = &self.java_home {
1390            require_dir(java_home, "Java home")?;
1391        }
1392        for entry in &self.extra_classpath {
1393            if !entry.exists() {
1394                return Err(format!(
1395                    "Classpath entry does not exist: {}",
1396                    entry.display()
1397                ));
1398            }
1399        }
1400        Ok(())
1401    }
1402
1403    pub fn classpath_entries(&self) -> Vec<PathBuf> {
1404        let mut entries = Vec::with_capacity(1 + self.extra_classpath.len());
1405        entries.push(self.harness_jar.clone());
1406        entries.extend(self.extra_classpath.iter().cloned());
1407        entries
1408    }
1409}
1410
1411#[cfg(forge_backend)]
1412#[allow(clippy::too_many_arguments)]
1413pub fn run_hosted_engine_game(
1414    game_id: String,
1415    player_names: Vec<String>,
1416    decks: Vec<Deck>,
1417    commander_names: Vec<Option<String>>,
1418    commander_variant: bool,
1419    game_variant: String,
1420    local_player_index: Option<usize>,
1421    ai_player_indices: Vec<usize>,
1422    bot_player_indices: Vec<usize>,
1423    starting_life: i32,
1424    remote_prompt_tx: std_mpsc::Sender<(usize, AgentMessage)>,
1425    remote_response_rxs: Vec<(usize, std_mpsc::Receiver<ClientToServerMessage>)>,
1426    game_over_tx: std_mpsc::Sender<HostedGameOver>,
1427    cancel: Arc<AtomicBool>,
1428) -> Result<(), String> {
1429    run_hosted_engine_game_inner(
1430        game_id,
1431        player_names,
1432        decks,
1433        commander_names,
1434        commander_variant,
1435        game_variant,
1436        local_player_index,
1437        ai_player_indices,
1438        bot_player_indices,
1439        starting_life,
1440        remote_prompt_tx,
1441        remote_response_rxs,
1442        game_over_tx,
1443        cancel,
1444    )
1445}
1446
1447#[cfg(not(forge_backend))]
1448#[allow(clippy::too_many_arguments)]
1449pub fn run_hosted_engine_game(
1450    _game_id: String,
1451    _player_names: Vec<String>,
1452    _decks: Vec<Deck>,
1453    _commander_names: Vec<Option<String>>,
1454    _commander_variant: bool,
1455    _game_variant: String,
1456    _local_player_index: Option<usize>,
1457    _ai_player_indices: Vec<usize>,
1458    _bot_player_indices: Vec<usize>,
1459    _starting_life: i32,
1460    _remote_prompt_tx: std_mpsc::Sender<(usize, AgentMessage)>,
1461    _remote_response_rxs: Vec<(usize, std_mpsc::Receiver<ClientToServerMessage>)>,
1462    _game_over_tx: std_mpsc::Sender<HostedGameOver>,
1463    _cancel: Arc<AtomicBool>,
1464) -> Result<(), String> {
1465    Err(unsupported_message().to_string())
1466}
1467
1468// 10s missed the ones that actually happen. A real game on 2026-08-25 ran 4094
1469// decisions with a median of 96ms and put 96 of them over a second and 12 over
1470// two, and none of it logged. The expensive ones are `chooseAction` on a large
1471// board: ~125 legal actions across 140 permanents cost 2.8s.
1472#[cfg(forge_backend)]
1473const SLOW_DECISION: Duration = Duration::from_millis(1500);
1474
1475/// How often the host loop looks for a player's answer and for the engine's
1476/// next prompt.
1477///
1478/// It polled every 50ms flat, and that was the floor under every decision:
1479/// over seven days of production the node-side histogram had no decision
1480/// under 50ms and 92% of them between 50 and 100ms, one poll cycle, with the
1481/// answer itself waiting up to a further 50ms in the channel before the loop
1482/// saw it. Now the loop runs hot for a moment after anything happens, which
1483/// is when the engine's reply is due, and idles at a fifth of the old
1484/// interval the rest of the time. A poll is a channel check per seat and one
1485/// call across the bridge, cheap enough at either rate.
1486#[cfg(forge_backend)]
1487const POLL_HOT: Duration = Duration::from_millis(2);
1488#[cfg(forge_backend)]
1489const POLL_IDLE: Duration = Duration::from_millis(10);
1490#[cfg(forge_backend)]
1491const POLL_HOT_FOR: Duration = Duration::from_millis(500);
1492
1493/// Serde tag of the prompt variant, for the slow-decision log. `PromptInput` is
1494/// internally tagged, so this is the same string the captures carry. Only called
1495/// on the rare slow path, so the trip through a `Value` is not worth avoiding.
1496#[cfg(forge_backend)]
1497fn prompt_input_name(input: &PromptInput) -> String {
1498    serde_json::to_value(input)
1499        .ok()
1500        .and_then(|value| {
1501            value
1502                .get("type")
1503                .and_then(serde_json::Value::as_str)
1504                .map(str::to_owned)
1505        })
1506        .unwrap_or_else(|| "unknown".to_string())
1507}
1508
1509#[cfg(forge_backend)]
1510fn report_checkpoint_metrics(
1511    engine: &ForgeEngine,
1512    session_id: &str,
1513    seats: usize,
1514) -> Option<Duration> {
1515    let samples = engine
1516        .drain_checkpoint_metrics(session_id)
1517        .and_then(|json| {
1518            serde_json::from_str::<Vec<[u64; 2]>>(&json).map_err(|error| error.to_string())
1519        });
1520    match samples {
1521        Ok(samples) => {
1522            let mut total = Duration::ZERO;
1523            for [copy, bookkeeping] in samples {
1524                let copy = Duration::from_nanos(copy);
1525                let bookkeeping = Duration::from_nanos(bookkeeping);
1526                crate::metrics::record_forge_checkpoint(seats, copy, bookkeeping);
1527                total += copy + bookkeeping;
1528            }
1529            Some(total)
1530        }
1531        Err(error) => {
1532            warn!(%error, "checkpoint metrics unavailable");
1533            None
1534        }
1535    }
1536}
1537
1538#[cfg(forge_backend)]
1539#[allow(clippy::too_many_arguments)]
1540fn run_hosted_engine_game_inner(
1541    game_id: String,
1542    player_names: Vec<String>,
1543    decks: Vec<Deck>,
1544    commander_names: Vec<Option<String>>,
1545    commander_variant: bool,
1546    game_variant: String,
1547    local_player_index: Option<usize>,
1548    ai_player_indices: Vec<usize>,
1549    bot_player_indices: Vec<usize>,
1550    starting_life: i32,
1551    remote_prompt_tx: std_mpsc::Sender<(usize, AgentMessage)>,
1552    remote_response_rxs: Vec<(usize, std_mpsc::Receiver<ClientToServerMessage>)>,
1553    game_over_tx: std_mpsc::Sender<HostedGameOver>,
1554    cancel: Arc<AtomicBool>,
1555) -> Result<(), String> {
1556    let engine = obtain_engine()?;
1557
1558    let mut players = Vec::with_capacity(player_names.len());
1559    for (index, name) in player_names.iter().enumerate() {
1560        let identities = deck_card_identities(&decks[index]);
1561        let seat_commander_names = if commander_variant {
1562            commander_names_for_java(&decks[index], commander_names[index].as_deref())
1563        } else {
1564            Vec::new()
1565        };
1566        players.push(PlayerConfig::new(
1567            name.clone(),
1568            &identities,
1569            seat_commander_names,
1570        ));
1571    }
1572    for &idx in &ai_player_indices {
1573        if let Some(player) = players.get_mut(idx) {
1574            player.ai = true;
1575        }
1576    }
1577    for &idx in &bot_player_indices {
1578        if let Some(player) = players.get_mut(idx) {
1579            player.bot = true;
1580        }
1581    }
1582    let mut request = StartGameRequest::new(
1583        game_id.clone(),
1584        game_variant,
1585        starting_life,
1586        rand::random(),
1587        players,
1588    );
1589    request.checkpoint_metrics = true;
1590    let session_id = engine.start_game(&request.to_json().map_err(|err| err.to_string())?)?;
1591    info!(game_id, session_id, "hosted java-forge session started");
1592
1593    struct SessionGuard {
1594        engine: ForgeEngine,
1595        session_id: String,
1596        armed: std::cell::Cell<bool>,
1597    }
1598    impl Drop for SessionGuard {
1599        fn drop(&mut self) {
1600            if self.armed.get() {
1601                if let Err(error) = self.engine.abort_game(&self.session_id) {
1602                    warn!(session_id = %self.session_id, %error, "failed to abort java session; context may leak");
1603                }
1604            }
1605        }
1606    }
1607    let guard = SessionGuard {
1608        engine: engine.clone(),
1609        session_id: session_id.clone(),
1610        armed: std::cell::Cell::new(true),
1611    };
1612
1613    let mut remote_response_rxs: HashMap<usize, std_mpsc::Receiver<ClientToServerMessage>> =
1614        remote_response_rxs.into_iter().collect();
1615    let mut last_prompt: Option<AgentPrompt> = None;
1616    let mut pending_roll_acks: usize = 0;
1617    let mut decision_received: Option<Instant> = None;
1618    let mut decision_submitted: Option<Instant> = None;
1619    // The last time an answer went in or a prompt came out. The loop polls
1620    // hot for a moment after either, which is when the next is due.
1621    let mut last_activity = Instant::now();
1622    let mut state_revision = 0;
1623
1624    loop {
1625        if cancel.load(std::sync::atomic::Ordering::Relaxed) {
1626            info!(
1627                session_id,
1628                "hosted java-forge session cancelled; player left the game"
1629            );
1630            return Ok(());
1631        }
1632        for (player_index, rx) in &mut remote_response_rxs {
1633            loop {
1634                match rx.try_recv() {
1635                    Ok(ClientToServerMessage::Response {
1636                        action: PromptOutput::DiceRolled(DiceRolledOutput::DiceRolledAcknowledged),
1637                        ..
1638                    }) => {
1639                        if pending_roll_acks > 0 {
1640                            pending_roll_acks -= 1;
1641                            if pending_roll_acks == 0 {
1642                                let ack = serde_json::to_string(&PromptOutput::DiceRolled(
1643                                    DiceRolledOutput::DiceRolledAcknowledged,
1644                                ))
1645                                .map_err(|err| format!("failed to serialize roll ack: {err}"))?;
1646                                engine.submit_action(&session_id, &ack)?;
1647                            }
1648                        }
1649                    }
1650                    Ok(ClientToServerMessage::Response { prompt_id, action }) => {
1651                        // prompt_id 0 is transport-synthesized: the
1652                        // absent-player default, exempt from validation.
1653                        if prompt_id != 0 {
1654                            let Some(prompt) =
1655                                last_prompt.as_ref().filter(|p| p.prompt_id == prompt_id)
1656                            else {
1657                                reject_response(
1658                                    &remote_prompt_tx,
1659                                    *player_index,
1660                                    last_prompt.as_ref().filter(|p| {
1661                                        self::player_index(&p.deciding_player_id) == *player_index
1662                                    }),
1663                                    ProtocolErrorCode::StalePrompt,
1664                                    format!("response for prompt {prompt_id} is not open"),
1665                                );
1666                                continue;
1667                            };
1668                            if self::player_index(&prompt.deciding_player_id) != *player_index {
1669                                reject_response(
1670                                    &remote_prompt_tx,
1671                                    *player_index,
1672                                    None,
1673                                    ProtocolErrorCode::WrongPlayer,
1674                                    format!(
1675                                        "prompt {prompt_id} is for {}",
1676                                        prompt.deciding_player_id
1677                                    ),
1678                                );
1679                                continue;
1680                            }
1681                            match prompt.input.validate_response(&action) {
1682                                Ok(()) => {}
1683                                Err(ResponseViolation::WrongPromptType) => {
1684                                    reject_response(
1685                                        &remote_prompt_tx,
1686                                        *player_index,
1687                                        Some(prompt),
1688                                        ProtocolErrorCode::WrongPromptType,
1689                                        "response output does not match the prompt type"
1690                                            .to_string(),
1691                                    );
1692                                    continue;
1693                                }
1694                                Err(ResponseViolation::UnknownActionId(id)) => {
1695                                    reject_response(
1696                                        &remote_prompt_tx,
1697                                        *player_index,
1698                                        Some(prompt),
1699                                        ProtocolErrorCode::UnknownActionId,
1700                                        format!(
1701                                            "action id {id:?} was not advertised by the prompt"
1702                                        ),
1703                                    );
1704                                    continue;
1705                                }
1706                                Err(ResponseViolation::CancelNotAllowed) => {
1707                                    reject_response(
1708                                        &remote_prompt_tx,
1709                                        *player_index,
1710                                        Some(prompt),
1711                                        ProtocolErrorCode::CancelNotAllowed,
1712                                        "this prompt is not cancellable".to_string(),
1713                                    );
1714                                    continue;
1715                                }
1716                            }
1717                        }
1718                        decision_received = Some(Instant::now());
1719                        let action_json = serde_json::to_string(&action).map_err(|err| {
1720                            format!(
1721                                "failed to serialize prompt output for player {player_index}: {err}"
1722                            )
1723                        })?;
1724                        debug!(player_index, %action_json, "submitting remote response to java");
1725                        engine.submit_action(&session_id, &action_json)?;
1726                        decision_submitted = Some(Instant::now());
1727                        last_activity = Instant::now();
1728                    }
1729                    Ok(ClientToServerMessage::Directive { directive }) => {
1730                        // A directive can arrive while another player's prompt
1731                        // is open (this loop drains every seat), so it names
1732                        // its seat.
1733                        let directive_json = directive_json(*player_index, directive);
1734                        debug!(player_index, %directive_json, "submitting directive to java");
1735                        engine.submit_action(&session_id, &directive_json)?;
1736                        last_activity = Instant::now();
1737                    }
1738                    Err(TryRecvError::Empty) => break,
1739                    Err(TryRecvError::Disconnected) => {
1740                        debug!(player_index, "java-forge response channel disconnected");
1741                        break;
1742                    }
1743                }
1744            }
1745        }
1746
1747        let revision = engine.state_revision(&session_id)?;
1748        if revision != state_revision {
1749            state_revision = revision;
1750            for &agent_index in remote_response_rxs.keys() {
1751                let state =
1752                    AgentMessage::State(state_via_handle(&engine, &session_id, Some(agent_index))?);
1753                if remote_prompt_tx.send((agent_index, state)).is_err() {
1754                    return Ok(());
1755                }
1756            }
1757            send_observer_state(&engine, &session_id, &remote_prompt_tx);
1758        }
1759
1760        if let Some(prompt_json) = engine.get_prompt(&session_id, 0)? {
1761            let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
1762                .map_err(|err| format!("failed to parse java prompt: {err}"))?;
1763            if last_prompt.as_ref().map(|p| p.prompt_id) != Some(prompt.prompt_id) {
1764                last_activity = Instant::now();
1765                let decision_elapsed = decision_received.take().map(|started| started.elapsed());
1766                let submitted_elapsed = decision_submitted.take().map(|started| started.elapsed());
1767                let checkpoint_time =
1768                    report_checkpoint_metrics(&engine, &session_id, player_names.len());
1769                if let Some(elapsed) = submitted_elapsed {
1770                    crate::metrics::record_forge_decision_stage("next_prompt", elapsed);
1771                }
1772                if let Some(elapsed) = decision_elapsed {
1773                    if let Some(checkpoint_time) = checkpoint_time {
1774                        crate::metrics::record_forge_checkpoint_decision(
1775                            player_names.len(),
1776                            checkpoint_time,
1777                        );
1778                    }
1779                    crate::metrics::record_forge_decision_stage("decision_total", elapsed);
1780                    crate::metrics::record_forge_decision(player_names.len(), elapsed);
1781                    // The metric alone cannot say which game was slow, and these
1782                    // are rare enough that finding one afterwards meant replaying
1783                    // captures by hand. Named so a log query can list them.
1784                    if elapsed >= SLOW_DECISION {
1785                        warn!(
1786                            game_id,
1787                            session_id,
1788                            seats = player_names.len(),
1789                            bots = ai_player_indices.len(),
1790                            elapsed_ms = elapsed.as_millis() as u64,
1791                            prompt = prompt_input_name(&prompt.input),
1792                            "slow engine decision"
1793                        );
1794                    }
1795                    report_engine_gc(&engine);
1796                }
1797                last_prompt = Some(prompt.clone());
1798                let player = player_index(&prompt.deciding_player_id);
1799                debug!(player, "forwarding java prompt to remote");
1800                if matches!(prompt.input, PromptInput::DiceRolled(_)) {
1801                    let snapshots_started = Instant::now();
1802                    let prompt_msg = AgentMessage::Prompt(prompt);
1803                    for &agent_index in remote_response_rxs.keys() {
1804                        let state = AgentMessage::State(state_via_handle(
1805                            &engine,
1806                            &session_id,
1807                            Some(agent_index),
1808                        )?);
1809                        let _ = remote_prompt_tx.send((agent_index, state));
1810                        let _ = remote_prompt_tx.send((agent_index, prompt_msg.clone()));
1811                    }
1812                    send_observer_state(&engine, &session_id, &remote_prompt_tx);
1813                    pending_roll_acks = remote_response_rxs.len();
1814                    if pending_roll_acks == 0 {
1815                        let ack = serde_json::to_string(&PromptOutput::DiceRolled(
1816                            DiceRolledOutput::DiceRolledAcknowledged,
1817                        ))
1818                        .map_err(|err| format!("failed to serialize roll ack: {err}"))?;
1819                        engine.submit_action(&session_id, &ack)?;
1820                    }
1821                    crate::metrics::record_forge_decision_stage(
1822                        "snapshots",
1823                        snapshots_started.elapsed(),
1824                    );
1825                } else if Some(player) == local_player_index {
1826                    if let Some(output) = auto_action(&prompt) {
1827                        let action_json = serde_json::to_string(&output)
1828                            .map_err(|err| format!("failed to serialize auto action: {err}"))?;
1829                        engine.submit_action(&session_id, &action_json)?;
1830                    }
1831                } else {
1832                    let snapshots_started = Instant::now();
1833                    for &agent_index in remote_response_rxs.keys() {
1834                        let state = AgentMessage::State(state_via_handle(
1835                            &engine,
1836                            &session_id,
1837                            Some(agent_index),
1838                        )?);
1839                        if remote_prompt_tx.send((agent_index, state)).is_err() {
1840                            return Ok(());
1841                        }
1842                    }
1843                    send_observer_state(&engine, &session_id, &remote_prompt_tx);
1844                    let prompt_msg = AgentMessage::Prompt(prompt);
1845                    if remote_prompt_tx.send((player, prompt_msg)).is_err() {
1846                        return Ok(());
1847                    }
1848                    crate::metrics::record_forge_decision_stage(
1849                        "snapshots",
1850                        snapshots_started.elapsed(),
1851                    );
1852                }
1853            }
1854        }
1855
1856        if engine.is_game_over(&session_id)? {
1857            report_checkpoint_metrics(&engine, &session_id, player_names.len());
1858            info!("hosted java-forge session reached game over");
1859            let mut final_messages = Vec::new();
1860            for &agent_index in remote_response_rxs.keys() {
1861                match state_via_handle(&engine, &session_id, Some(agent_index)) {
1862                    Ok(state_update) => {
1863                        final_messages.push((agent_index, AgentMessage::State(state_update)));
1864                    }
1865                    Err(error) => {
1866                        warn!(%error, agent_index, "game over: final snapshot unavailable; sending game-over prompt only");
1867                    }
1868                }
1869            }
1870            if let Ok(state_update) = state_via_handle(&engine, &session_id, None) {
1871                final_messages.push((
1872                    crate::host::OBSERVER_SEAT,
1873                    AgentMessage::State(state_update),
1874                ));
1875            }
1876            let game_over = AgentMessage::Prompt(game_over_prompt());
1877            for &agent_index in remote_response_rxs.keys() {
1878                final_messages.push((agent_index, game_over.clone()));
1879            }
1880            let _ = game_over_tx.send(HostedGameOver {
1881                game_id: game_id.clone(),
1882                messages: final_messages,
1883            });
1884            engine.end_game(&session_id)?;
1885            guard.armed.set(false);
1886            return Ok(());
1887        }
1888
1889        std::thread::sleep(if last_activity.elapsed() < POLL_HOT_FOR {
1890            POLL_HOT
1891        } else {
1892            POLL_IDLE
1893        });
1894    }
1895}
1896
1897#[cfg(feature = "java-forge")]
1898fn wait_for_prompt<B: JavaBridge>(
1899    session: &mut JavaForgeSession<B>,
1900    max_polls: usize,
1901) -> Result<Option<String>, String> {
1902    for _ in 0..max_polls {
1903        if let Some(prompt) = session.get_prompt(0)? {
1904            return Ok(Some(prompt));
1905        }
1906        std::thread::sleep(Duration::from_millis(50));
1907    }
1908    Ok(None)
1909}
1910
1911#[cfg(forge_backend)]
1912fn send_observer_state(
1913    engine: &ForgeEngine,
1914    session_id: &str,
1915    remote_prompt_tx: &std_mpsc::Sender<(usize, AgentMessage)>,
1916) {
1917    match state_via_handle(engine, session_id, None) {
1918        Ok(state_update) => {
1919            let _ = remote_prompt_tx.send((
1920                crate::host::OBSERVER_SEAT,
1921                AgentMessage::State(state_update),
1922            ));
1923        }
1924        Err(error) => warn!(%error, "observer snapshot unavailable"),
1925    }
1926}
1927
1928#[cfg(forge_backend)]
1929fn player_index(deciding_player_id: &str) -> usize {
1930    deciding_player_id
1931        .strip_prefix("player-")
1932        .and_then(|n| n.parse().ok())
1933        .unwrap_or(0)
1934}
1935
1936#[cfg(forge_backend)]
1937fn reject_response(
1938    remote_prompt_tx: &std_mpsc::Sender<(usize, AgentMessage)>,
1939    seat: usize,
1940    reopen_prompt: Option<&AgentPrompt>,
1941    code: ProtocolErrorCode,
1942    message: String,
1943) {
1944    let _ = remote_prompt_tx.send((
1945        seat,
1946        AgentMessage::Error(ProtocolError {
1947            code,
1948            message,
1949            prompt_id: reopen_prompt.map(|p| p.prompt_id),
1950        }),
1951    ));
1952    if let Some(prompt) = reopen_prompt {
1953        let _ = remote_prompt_tx.send((seat, AgentMessage::Prompt(prompt.clone())));
1954    }
1955}
1956
1957#[cfg(forge_backend)]
1958fn auto_action(prompt: &AgentPrompt) -> Option<PromptOutput> {
1959    match prompt.input {
1960        PromptInput::ChooseAction(_) => {
1961            Some(PromptOutput::ChooseAction(ChooseActionOutput::Pass {
1962                until: None,
1963                exhaust_stack: false,
1964            }))
1965        }
1966        _ => None,
1967    }
1968}
1969
1970#[cfg(forge_backend)]
1971fn game_over_prompt() -> AgentPrompt {
1972    AgentPrompt {
1973        prompt_id: u32::MAX,
1974        deciding_player_id: "player-0".to_string(),
1975        source_card: None,
1976        source_ability_text: None,
1977        input: PromptInput::GameOver(GameOverInput {}),
1978    }
1979}
1980
1981#[cfg(forge_backend)]
1982fn state_via_handle(
1983    engine: &ForgeEngine,
1984    session_id: &str,
1985    viewer: Option<usize>,
1986) -> Result<StateUpdate, String> {
1987    let game_view: GameViewDto = serde_json::from_str(&engine.get_snapshot(session_id, viewer)?)
1988        .map_err(|err| format!("failed to parse java snapshot: {err}"))?;
1989    Ok(StateUpdate { game_view })
1990}
1991
1992#[cfg(forge_backend)]
1993fn deck_card_identities(deck: &Deck) -> Vec<DeckCardIdentity> {
1994    deck.cards
1995        .iter()
1996        .chain(deck.commanders.iter().flatten())
1997        .map(|card| card.identity.clone())
1998        .collect()
1999}
2000
2001#[cfg(forge_backend)]
2002fn commander_names_for_java(deck: &Deck, fallback: Option<&str>) -> Vec<String> {
2003    let names: Vec<String> = deck
2004        .commanders
2005        .iter()
2006        .flatten()
2007        .map(|card| java_card_name(&card.identity.name))
2008        .collect();
2009    if !names.is_empty() {
2010        return names;
2011    }
2012    fallback
2013        .filter(|name| !name.is_empty())
2014        .map(|name| vec![java_card_name(name)])
2015        .unwrap_or_default()
2016}
2017
2018#[cfg(forge_backend)]
2019fn smoke_deck(land_name: &str, spell_name: &str) -> Vec<DeckCardIdentity> {
2020    (0..24)
2021        .map(|_| DeckCardIdentity {
2022            name: land_name.to_string(),
2023            ..Default::default()
2024        })
2025        .chain((0..36).map(|_| DeckCardIdentity {
2026            name: spell_name.to_string(),
2027            ..Default::default()
2028        }))
2029        .collect()
2030}
2031
2032#[cfg(feature = "java-forge")]
2033fn scenario_deck(land_name: &str) -> Vec<DeckCardIdentity> {
2034    (0..60)
2035        .map(|_| DeckCardIdentity {
2036            name: land_name.to_string(),
2037            ..Default::default()
2038        })
2039        .collect()
2040}
2041
2042#[cfg(feature = "java-forge")]
2043enum JavaScenario {
2044    KeepAndPlayLand {
2045        played_land: bool,
2046    },
2047    MulliganOncePlayLand {
2048        mulliganed: bool,
2049        kept_second_hand: bool,
2050        put_back_done: bool,
2051        played_land: bool,
2052    },
2053}
2054
2055#[cfg(feature = "java-forge")]
2056impl JavaScenario {
2057    fn from_name(name: &str) -> Result<Self, String> {
2058        match name {
2059            "keep-and-play-land" => Ok(Self::KeepAndPlayLand { played_land: false }),
2060            "mulligan-once-play-land" => Ok(Self::MulliganOncePlayLand {
2061                mulliganed: false,
2062                kept_second_hand: false,
2063                put_back_done: false,
2064                played_land: false,
2065            }),
2066            _ => Err(format!(
2067                "unknown java-forge scenario '{name}'. Supported scenarios: keep-and-play-land, mulligan-once-play-land"
2068            )),
2069        }
2070    }
2071
2072    fn name(&self) -> &'static str {
2073        match self {
2074            Self::KeepAndPlayLand { .. } => "keep-and-play-land",
2075            Self::MulliganOncePlayLand { .. } => "mulligan-once-play-land",
2076        }
2077    }
2078
2079    fn next_action(
2080        &mut self,
2081        prompt: &Value,
2082        game_view: &GameViewDto,
2083    ) -> Result<Option<PromptOutput>, String> {
2084        match self {
2085            Self::KeepAndPlayLand { played_land } => {
2086                if *played_land && battlefield_contains(game_view, "Swamp") {
2087                    return Ok(None);
2088                }
2089                match prompt_type(prompt) {
2090                    Some("mulligan") => Ok(Some(PromptOutput::Mulligan(
2091                        MulliganOutput::MulliganDecision { keep: true },
2092                    ))),
2093                    Some("chooseAction") => {
2094                        if let Some(action) = play_first_card_action(prompt, "Swamp")? {
2095                            *played_land = true;
2096                            Ok(Some(action))
2097                        } else {
2098                            Ok(Some(PromptOutput::ChooseAction(ChooseActionOutput::Pass {
2099                                until: None,
2100                                exhaust_stack: false,
2101                            })))
2102                        }
2103                    }
2104                    other => Err(format!(
2105                        "scenario '{}' expected mulligan or chooseAction, got {:?}",
2106                        self.name(),
2107                        other
2108                    )),
2109                }
2110            }
2111            Self::MulliganOncePlayLand {
2112                mulliganed,
2113                kept_second_hand,
2114                put_back_done,
2115                played_land,
2116            } => {
2117                if *played_land && battlefield_contains(game_view, "Swamp") {
2118                    return Ok(None);
2119                }
2120                match prompt_type(prompt) {
2121                    Some("mulligan") if !*mulliganed => {
2122                        *mulliganed = true;
2123                        Ok(Some(PromptOutput::Mulligan(MulliganOutput::MulliganDecision { keep: false })))
2124                    }
2125                    Some("mulligan") if !*kept_second_hand => {
2126                        *kept_second_hand = true;
2127                        Ok(Some(PromptOutput::Mulligan(MulliganOutput::MulliganDecision { keep: true })))
2128                    }
2129                    Some("mulliganPutBack") if !*put_back_done => {
2130                        let count = prompt
2131                            .get("input")
2132                            .and_then(|input| input.get("count"))
2133                            .and_then(Value::as_u64)
2134                            .unwrap_or(1) as usize;
2135                        let card_ids = prompt_card_ids(prompt, "handCardIds", count)?;
2136                        *put_back_done = true;
2137                        Ok(Some(PromptOutput::MulliganPutBack(MulliganPutBackOutput::MulliganPutBackDecision { card_ids })))
2138                    }
2139                    Some("chooseAction") => {
2140                        if let Some(action) = play_first_card_action(prompt, "Swamp")? {
2141                            *played_land = true;
2142                            Ok(Some(action))
2143                        } else {
2144                            Ok(Some(PromptOutput::ChooseAction(ChooseActionOutput::Pass { until: None, exhaust_stack: false })))
2145                        }
2146                    }
2147                    other => Err(format!(
2148                        "scenario '{}' expected mulligan, mulliganPutBack, or chooseAction, got {:?}",
2149                        self.name(),
2150                        other
2151                    )),
2152                }
2153            }
2154        }
2155    }
2156}
2157
2158#[cfg(feature = "java-forge")]
2159fn run_scenario_loop<B: JavaBridge>(
2160    session: &mut JavaForgeSession<B>,
2161    mut scenario: JavaScenario,
2162    max_prompts: usize,
2163) -> Result<(), String> {
2164    let mut prompts_seen = 0usize;
2165    let mut last_prompt_json: Option<String> = None;
2166    while prompts_seen < max_prompts {
2167        let Some(prompt_json) = wait_for_prompt(session, 600)? else {
2168            return Err(format!(
2169                "timed out waiting for java-forge scenario '{}' prompt",
2170                scenario.name()
2171            ));
2172        };
2173        if last_prompt_json.as_deref() == Some(prompt_json.as_str()) {
2174            std::thread::sleep(Duration::from_millis(50));
2175            continue;
2176        }
2177        last_prompt_json = Some(prompt_json.clone());
2178        prompts_seen += 1;
2179
2180        let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
2181            .map_err(|err| format!("failed to parse java scenario prompt: {err}"))?;
2182        let player = player_index(&prompt.deciding_player_id);
2183        if player != 0 {
2184            if let Some(output) = auto_action(&prompt) {
2185                session.submit_action(
2186                    &serde_json::to_string(&output).map_err(|err| err.to_string())?,
2187                )?;
2188            }
2189            continue;
2190        }
2191
2192        let game_view: GameViewDto = serde_json::from_str(&session.get_snapshot(Some(0))?)
2193            .map_err(|err| format!("failed to parse java scenario snapshot: {err}"))?;
2194        let normalized_prompt = serde_json::to_value(&prompt).map_err(|err| err.to_string())?;
2195        info!(
2196            scenario = scenario.name(),
2197            prompts_seen,
2198            prompt_type = prompt_type(&normalized_prompt).unwrap_or("<missing>"),
2199            "java-forge scenario prompt"
2200        );
2201        let Some(action) = scenario.next_action(&normalized_prompt, &game_view)? else {
2202            info!(
2203                scenario = scenario.name(),
2204                prompts_seen, "java-forge scenario assertions satisfied"
2205            );
2206            return Ok(());
2207        };
2208        submit_player_action(session, &action)?;
2209    }
2210    Err(format!(
2211        "java-forge scenario '{}' did not complete within {max_prompts} prompts",
2212        scenario.name()
2213    ))
2214}
2215
2216#[cfg(feature = "java-forge")]
2217pub fn run_concede_smoke() -> Result<(), String> {
2218    let config = JavaRuntimeConfig::from_env();
2219    let assets_dir = config.assets_dir.to_string_lossy().to_string();
2220    let bridge = SubprocessBridge::spawn(&config)?;
2221    let mut session = JavaForgeSession::new(bridge);
2222    session.initialize(&assets_dir)?;
2223    run_concede_game(&mut session, 3, 2, 12)?;
2224    run_concede_game(&mut session, 2, 1, 8)?;
2225    Ok(())
2226}
2227
2228#[cfg(not(feature = "java-forge"))]
2229pub fn run_concede_smoke() -> Result<(), String> {
2230    Err(unsupported_message().to_string())
2231}
2232
2233#[cfg(forge_backend)]
2234fn parse_state_revision(value: &str) -> Result<u64, String> {
2235    value
2236        .trim()
2237        .parse()
2238        .map_err(|err| format!("invalid java state revision {value:?}: {err}"))
2239}
2240
2241#[cfg(forge_backend)]
2242fn directive_json(player: usize, directive: DirectiveInput) -> String {
2243    serde_json::json!({ "type": "directive", "directive": directive, "player": player }).to_string()
2244}
2245
2246#[cfg(feature = "java-forge")]
2247fn run_concede_game<B: JavaBridge>(
2248    session: &mut JavaForgeSession<B>,
2249    seats: usize,
2250    conceder: usize,
2251    concede_after: usize,
2252) -> Result<(), String> {
2253    const POST_CONCEDE_DECISIONS: usize = 12;
2254    const STALL_REPEATS: usize = 300;
2255
2256    let cards: Vec<manabrew_protocol::deck_dto::DeckCard> = (0..60)
2257        .map(|_| manabrew_protocol::deck_dto::DeckCard {
2258            identity: DeckCardIdentity {
2259                name: "Mountain".to_string(),
2260                set_code: "M20".to_string(),
2261                ..Default::default()
2262            },
2263            ..Default::default()
2264        })
2265        .collect();
2266    let deck = Deck {
2267        name: "concede-smoke".to_string(),
2268        cards,
2269        ..Default::default()
2270    };
2271    let identities = deck_card_identities(&deck);
2272    let players: Vec<PlayerConfig> = (0..seats)
2273        .map(|i| PlayerConfig::new(format!("Concede {}", i + 1), &identities, Vec::new()))
2274        .collect();
2275    let request = StartGameRequest::new(
2276        format!("concede-smoke-{seats}p"),
2277        String::new(),
2278        20,
2279        7,
2280        players,
2281    );
2282    let session_id = session.start_game(&request)?;
2283    info!(
2284        session_id,
2285        seats, conceder, concede_after, "concede smoke game started"
2286    );
2287
2288    let mut bots: HashMap<usize, SimpleAi> = HashMap::new();
2289    let mut last_prompt_json: Option<String> = None;
2290    let mut acted = 0usize;
2291    let mut acted_after_concede = 0usize;
2292    let mut conceded = false;
2293    let mut repeat_count = 0usize;
2294
2295    for _ in 0..40_000 {
2296        if session.is_game_over()? {
2297            if !conceded {
2298                return Err("concede smoke: game ended before the concede fired".to_string());
2299            }
2300            break;
2301        }
2302        let Some(prompt_json) = session.get_prompt(0)? else {
2303            std::thread::sleep(Duration::from_millis(10));
2304            continue;
2305        };
2306        if last_prompt_json.as_deref() == Some(prompt_json.as_str()) {
2307            repeat_count += 1;
2308            if repeat_count > STALL_REPEATS {
2309                return Err(format!(
2310                    "concede smoke stalled on the same prompt (seats={seats} acted={acted} conceded={conceded} after={acted_after_concede}): {prompt_json}"
2311                ));
2312            }
2313            std::thread::sleep(Duration::from_millis(10));
2314            continue;
2315        }
2316        repeat_count = 0;
2317
2318        let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
2319            .map_err(|err| format!("concede smoke: bad prompt: {err}"))?;
2320        let player = player_index(&prompt.deciding_player_id);
2321
2322        if !conceded && acted >= concede_after {
2323            info!(conceder, acted, "concede smoke: injecting concede");
2324            session.submit_action(&directive_json(conceder, DirectiveInput::Concede))?;
2325            conceded = true;
2326            last_prompt_json = None;
2327            continue;
2328        }
2329        if conceded && player == conceder {
2330            session.submit_action(&directive_json(conceder, DirectiveInput::Concede))?;
2331            last_prompt_json = Some(prompt_json);
2332            continue;
2333        }
2334
2335        if let Some(action) = bots.entry(player).or_default().decide(prompt) {
2336            submit_player_action(session, &action)?;
2337            acted += 1;
2338            if conceded {
2339                acted_after_concede += 1;
2340            }
2341        }
2342        last_prompt_json = Some(prompt_json);
2343        if conceded && seats > 2 && acted_after_concede >= POST_CONCEDE_DECISIONS {
2344            break;
2345        }
2346    }
2347
2348    if !conceded {
2349        return Err("concede smoke: never reached the injection point".to_string());
2350    }
2351    if seats == 2 {
2352        if !session.is_game_over()? {
2353            return Err("concede smoke: 2p concession did not end the game".to_string());
2354        }
2355        info!(acted, "concede smoke: 2p concession ended the game");
2356    } else {
2357        if acted_after_concede < POST_CONCEDE_DECISIONS && !session.is_game_over()? {
2358            return Err(format!(
2359                "concede smoke: game did not progress after the concession (only {acted_after_concede} decisions)"
2360            ));
2361        }
2362        let snapshot = parse_snapshot(session)?;
2363        let status = snapshot
2364            .pointer(&format!("/players/{conceder}/status"))
2365            .and_then(Value::as_str)
2366            .unwrap_or("");
2367        if status != "conceded" {
2368            return Err(format!(
2369                "concede smoke: seat {conceder} has status '{status}', expected 'conceded'"
2370            ));
2371        }
2372        info!(
2373            acted,
2374            acted_after_concede, "concede smoke: game continued past the concession"
2375        );
2376    }
2377    session.end_game()?;
2378    Ok(())
2379}
2380
2381#[cfg(feature = "java-forge")]
2382fn run_self_play_loop<B: JavaBridge>(
2383    session: &mut JavaForgeSession<B>,
2384    max_prompts: usize,
2385) -> Result<(), String> {
2386    const STALL_REPEATS: usize = 100;
2387
2388    let mut bots: HashMap<usize, SimpleAi> = HashMap::new();
2389    let mut last_prompt_json: Option<String> = None;
2390    let mut acted = 0usize;
2391    let mut repeat_count = 0usize;
2392    let mut seen_prompt = false;
2393    let max_iterations = max_prompts.saturating_mul(200).max(2_000);
2394
2395    for _ in 0..max_iterations {
2396        if let Some(prompt_json) = session.get_prompt(0)? {
2397            seen_prompt = true;
2398            if last_prompt_json.as_deref() == Some(prompt_json.as_str()) {
2399                if session.is_game_over()? {
2400                    info!(acted, "java-forge self-play reached game over");
2401                    return Ok(());
2402                }
2403                repeat_count += 1;
2404                if repeat_count > STALL_REPEATS {
2405                    let raw_value: Value =
2406                        serde_json::from_str(&prompt_json).unwrap_or(Value::Null);
2407                    dump_stuck(
2408                        "java re-emitted the same prompt after the bot acted (stall)",
2409                        &raw_value,
2410                        None,
2411                        session,
2412                    );
2413                    return Err(
2414                        "self-play stalled: java re-emitted the same prompt after the bot's action"
2415                            .to_string(),
2416                    );
2417                }
2418                std::thread::sleep(Duration::from_millis(20));
2419                continue;
2420            }
2421            repeat_count = 0;
2422
2423            let prompt: AgentPrompt = serde_json::from_str(&prompt_json)
2424                .map_err(|err| format!("failed to parse java self-play prompt: {err}"))?;
2425            let player = player_index(&prompt.deciding_player_id);
2426            let raw_value: Value = serde_json::from_str(&prompt_json).unwrap_or(Value::Null);
2427            let normalized = raw_value.clone();
2428
2429            match bots.entry(player).or_default().decide(prompt) {
2430                Some(action) => {
2431                    if let Err(err) = submit_player_action(session, &action) {
2432                        dump_stuck(
2433                            "java rejected the bot action",
2434                            &raw_value,
2435                            Some(&normalized),
2436                            session,
2437                        );
2438                        return Err(format!(
2439                            "self-play: java rejected action for player {player}: {err}"
2440                        ));
2441                    }
2442                    acted += 1;
2443                    if acted >= max_prompts {
2444                        dump_stuck(
2445                            "did not reach game over within max prompts",
2446                            &raw_value,
2447                            Some(&normalized),
2448                            session,
2449                        );
2450                        return Err(format!(
2451                            "self-play did not reach game over within {max_prompts} decisions"
2452                        ));
2453                    }
2454                }
2455                None => debug!(
2456                    player,
2457                    prompt_type = prompt_type(&normalized).unwrap_or("<missing>"),
2458                    "self-play: no action for prompt (display-only)"
2459                ),
2460            }
2461            last_prompt_json = Some(prompt_json);
2462            continue;
2463        }
2464
2465        if seen_prompt && session.is_game_over()? {
2466            info!(acted, "java-forge self-play reached game over");
2467            return Ok(());
2468        }
2469        std::thread::sleep(Duration::from_millis(20));
2470    }
2471
2472    dump_stuck(
2473        "self-play exceeded its iteration cap without game over",
2474        &Value::Null,
2475        None,
2476        session,
2477    );
2478    Err("self-play exceeded its iteration cap without reaching game over".to_string())
2479}
2480
2481#[cfg(feature = "java-forge")]
2482fn parse_snapshot<B: JavaBridge>(session: &mut JavaForgeSession<B>) -> Result<Value, String> {
2483    let snapshot_json = session.get_snapshot(Some(0))?;
2484    serde_json::from_str(&snapshot_json)
2485        .map_err(|err| format!("failed to parse java self-play snapshot: {err}"))
2486}
2487
2488#[cfg(feature = "java-forge")]
2489fn dump_stuck<B: JavaBridge>(
2490    reason: &str,
2491    prompt: &Value,
2492    normalized: Option<&Value>,
2493    session: &mut JavaForgeSession<B>,
2494) {
2495    let snapshot = parse_snapshot(session).unwrap_or(Value::Null);
2496    let artifact = json!({
2497        "reason": reason,
2498        "rawPrompt": prompt,
2499        "normalizedPrompt": normalized,
2500        "snapshot": snapshot,
2501    });
2502    let ts = std::time::SystemTime::now()
2503        .duration_since(std::time::UNIX_EPOCH)
2504        .map(|d| d.as_millis())
2505        .unwrap_or(0);
2506    let path = workspace_root().join(format!("target/self-play-stuck-{ts}.json"));
2507    match serde_json::to_string_pretty(&artifact) {
2508        Ok(body) => {
2509            if let Err(error) = std::fs::write(&path, body) {
2510                warn!(%error, reason, "self-play stuck; failed to write artifact");
2511            } else {
2512                warn!(path = %path.display(), reason, "self-play stuck; wrote artifact");
2513            }
2514        }
2515        Err(error) => warn!(%error, reason, "self-play stuck; failed to serialize artifact"),
2516    }
2517}
2518
2519#[cfg(feature = "java-forge")]
2520fn submit_player_action<B: JavaBridge>(
2521    session: &mut JavaForgeSession<B>,
2522    action: &PromptOutput,
2523) -> Result<(), String> {
2524    let action_json = serde_json::to_string(action)
2525        .map_err(|err| format!("failed to serialize scenario action: {err}"))?;
2526    session.submit_action(&action_json)?;
2527    Ok(())
2528}
2529
2530#[cfg(feature = "java-forge")]
2531fn prompt_type(prompt: &Value) -> Option<&str> {
2532    prompt
2533        .get("input")
2534        .and_then(|input| input.get("type"))
2535        .and_then(Value::as_str)
2536}
2537
2538#[cfg(feature = "java-forge")]
2539fn play_first_card_action(prompt: &Value, card_name: &str) -> Result<Option<PromptOutput>, String> {
2540    let Some(action) = prompt
2541        .get("input")
2542        .and_then(|input| input.get("actions"))
2543        .and_then(Value::as_array)
2544        .and_then(|actions| {
2545            actions.iter().find(|action| {
2546                action
2547                    .get("modeLabel")
2548                    .and_then(Value::as_str)
2549                    .is_some_and(|label| label.contains(card_name))
2550            })
2551        })
2552    else {
2553        return Ok(None);
2554    };
2555    let action_id = action
2556        .get("id")
2557        .and_then(Value::as_str)
2558        .ok_or_else(|| format!("playable action for '{card_name}' is missing id"))?;
2559    Ok(Some(PromptOutput::ChooseAction(ChooseActionOutput::Act {
2560        action_id: action_id.to_string(),
2561    })))
2562}
2563
2564#[cfg(feature = "java-forge")]
2565fn prompt_card_ids(prompt: &Value, field: &str, count: usize) -> Result<Vec<String>, String> {
2566    let card_ids = prompt
2567        .get("input")
2568        .and_then(|input| input.get(field))
2569        .and_then(Value::as_array)
2570        .ok_or_else(|| format!("prompt is missing {field}"))?;
2571    if card_ids.len() < count {
2572        return Err(format!(
2573            "prompt field {field} has {} cards, need {count}",
2574            card_ids.len()
2575        ));
2576    }
2577    Ok(card_ids
2578        .iter()
2579        .take(count)
2580        .filter_map(Value::as_str)
2581        .map(str::to_string)
2582        .collect())
2583}
2584
2585#[cfg(feature = "java-forge")]
2586fn battlefield_contains(game_view: &GameViewDto, card_name: &str) -> bool {
2587    use manabrew_agent_interface::game_view_dto::{CardView, ZoneKind};
2588    game_view.zones.iter().any(|zone| {
2589        zone.zone == ZoneKind::Battlefield
2590            && zone.owner_id == "player-0"
2591            && zone.cards.iter().any(|card| match card {
2592                CardView::Visible(dto) => dto.identity.name == card_name,
2593                CardView::Hidden { .. } => false,
2594            })
2595    })
2596}
2597
2598pub trait JavaBridge {
2599    fn initialize(&mut self, assets_dir: &str) -> Result<(), String>;
2600    fn start_game_json(&mut self, request_json: &str) -> Result<String, String>;
2601    fn submit_action(&mut self, session_id: &str, action_json: &str) -> Result<String, String>;
2602    fn get_prompt(
2603        &mut self,
2604        session_id: &str,
2605        player_index: usize,
2606    ) -> Result<Option<String>, String>;
2607    fn get_snapshot(&mut self, session_id: &str, viewer: Option<usize>) -> Result<String, String>;
2608    fn is_game_over(&mut self, session_id: &str) -> Result<bool, String>;
2609    fn drain_checkpoint_metrics(&mut self, session_id: &str) -> Result<String, String>;
2610    fn state_revision(&mut self, session_id: &str) -> Result<u64, String>;
2611    fn end_game(&mut self, session_id: &str) -> Result<(), String>;
2612    fn abort_game(&mut self, session_id: &str) -> Result<(), String>;
2613}
2614
2615pub struct JavaForgeSession<B> {
2616    bridge: B,
2617    session_id: Option<String>,
2618}
2619
2620impl<B: JavaBridge> JavaForgeSession<B> {
2621    pub fn new(bridge: B) -> Self {
2622        Self {
2623            bridge,
2624            session_id: None,
2625        }
2626    }
2627
2628    pub fn initialize(&mut self, assets_dir: &str) -> Result<(), String> {
2629        self.bridge.initialize(assets_dir)
2630    }
2631
2632    pub fn start_game(&mut self, request: &StartGameRequest) -> Result<String, String> {
2633        let request_json = request.to_json().map_err(|err| err.to_string())?;
2634        let response_json = self.bridge.start_game_json(&request_json)?;
2635        let response: StartGameResponse =
2636            serde_json::from_str(&response_json).map_err(|err| err.to_string())?;
2637        self.session_id = Some(response.session_id.clone());
2638        Ok(response.session_id)
2639    }
2640
2641    pub fn submit_action(&mut self, action_json: &str) -> Result<String, String> {
2642        let session_id = self.require_session_id()?.to_string();
2643        self.bridge.submit_action(&session_id, action_json)
2644    }
2645
2646    pub fn get_prompt(&mut self, player_index: usize) -> Result<Option<String>, String> {
2647        let session_id = self.require_session_id()?.to_string();
2648        self.bridge.get_prompt(&session_id, player_index)
2649    }
2650
2651    pub fn get_snapshot(&mut self, viewer: Option<usize>) -> Result<String, String> {
2652        let session_id = self.require_session_id()?.to_string();
2653        self.bridge.get_snapshot(&session_id, viewer)
2654    }
2655
2656    pub fn is_game_over(&mut self) -> Result<bool, String> {
2657        let session_id = self.require_session_id()?.to_string();
2658        self.bridge.is_game_over(&session_id)
2659    }
2660
2661    pub fn end_game(&mut self) -> Result<(), String> {
2662        let Some(session_id) = self.session_id.take() else {
2663            return Ok(());
2664        };
2665        self.bridge.end_game(&session_id)
2666    }
2667
2668    fn require_session_id(&self) -> Result<&str, String> {
2669        self.session_id
2670            .as_deref()
2671            .ok_or_else(|| "java-forge session has not started".to_string())
2672    }
2673}
2674
2675pub struct UnavailableJavaBridge;
2676
2677impl JavaBridge for UnavailableJavaBridge {
2678    fn initialize(&mut self, _assets_dir: &str) -> Result<(), String> {
2679        Err(unsupported_message().to_string())
2680    }
2681
2682    fn start_game_json(&mut self, _request_json: &str) -> Result<String, String> {
2683        Err(unsupported_message().to_string())
2684    }
2685
2686    fn submit_action(&mut self, _session_id: &str, _action_json: &str) -> Result<String, String> {
2687        Err(unsupported_message().to_string())
2688    }
2689
2690    fn get_prompt(
2691        &mut self,
2692        _session_id: &str,
2693        _player_index: usize,
2694    ) -> Result<Option<String>, String> {
2695        Err(unsupported_message().to_string())
2696    }
2697
2698    fn get_snapshot(
2699        &mut self,
2700        _session_id: &str,
2701        _viewer: Option<usize>,
2702    ) -> Result<String, String> {
2703        Err(unsupported_message().to_string())
2704    }
2705
2706    fn is_game_over(&mut self, _session_id: &str) -> Result<bool, String> {
2707        Err(unsupported_message().to_string())
2708    }
2709
2710    fn drain_checkpoint_metrics(&mut self, _session_id: &str) -> Result<String, String> {
2711        Err(unsupported_message().to_string())
2712    }
2713
2714    fn state_revision(&mut self, _session_id: &str) -> Result<u64, String> {
2715        Err(unsupported_message().to_string())
2716    }
2717
2718    fn end_game(&mut self, _session_id: &str) -> Result<(), String> {
2719        Err(unsupported_message().to_string())
2720    }
2721
2722    fn abort_game(&mut self, _session_id: &str) -> Result<(), String> {
2723        Err(unsupported_message().to_string())
2724    }
2725}
2726
2727#[cfg(feature = "java-forge")]
2728#[derive(serde::Deserialize)]
2729struct SubprocessReply {
2730    ok: bool,
2731    #[serde(default)]
2732    result: String,
2733    #[serde(default)]
2734    error: Option<String>,
2735}
2736
2737#[cfg(feature = "java-forge")]
2738const CALL_TIMEOUT: Duration = Duration::from_secs(60);
2739#[cfg(feature = "java-forge")]
2740const SHUTDOWN_GRACE: Duration = Duration::from_secs(5);
2741
2742#[cfg(feature = "java-forge")]
2743pub struct SubprocessBridge {
2744    child: Child,
2745    stdin: BufWriter<ChildStdin>,
2746    stdout_rx: std_mpsc::Receiver<String>,
2747    stdout_handle: Option<std::thread::JoinHandle<()>>,
2748    stderr_handle: Option<std::thread::JoinHandle<()>>,
2749}
2750
2751#[cfg(feature = "java-forge")]
2752impl SubprocessBridge {
2753    fn spawn(config: &JavaRuntimeConfig) -> Result<Self, String> {
2754        config.validate()?;
2755
2756        let java_bin = resolve_java_bin(config);
2757        let jvm_args = config.jvm_args();
2758        info!(target: "self_hosted_node::java", args = %jvm_args.join(" "), "spawning java engine");
2759        let mut cmd = Command::new(&java_bin);
2760        // The JVM applies JAVA_TOOL_OPTIONS before anything on the command line,
2761        // so whatever is set on the host silently governs every flag we do not
2762        // name. Production ran -Xmx512m -XX:+UseSerialGC that way for months
2763        // with nothing in the repo to show it. Use SELF_HOSTED_NODE_JAVA_OPTS
2764        // instead: it is passed here, logged above, and lives in config.
2765        cmd.env_remove("JAVA_TOOL_OPTIONS");
2766        cmd.args(&jvm_args);
2767        cmd.arg("-jar").arg(&config.harness_jar);
2768        cmd.arg("--interactive-server");
2769        cmd.arg("--forge-home")
2770            .arg(format!("{}/", config.assets_dir.display()));
2771
2772        let mut child = cmd
2773            .stdin(Stdio::piped())
2774            .stdout(Stdio::piped())
2775            .stderr(Stdio::piped())
2776            .spawn()
2777            .map_err(|err| format!("failed to spawn java subprocess: {err}"))?;
2778
2779        let stdin = child
2780            .stdin
2781            .take()
2782            .ok_or_else(|| "java subprocess has no stdin".to_string())?;
2783        let stdout = child
2784            .stdout
2785            .take()
2786            .ok_or_else(|| "java subprocess has no stdout".to_string())?;
2787        let stderr = child.stderr.take();
2788
2789        // Bounded so a chatty Java side can't grow the queue without bound.
2790        // Cap is generous — protocol replies are one line per request.
2791        let (stdout_tx, stdout_rx) = std_mpsc::sync_channel::<String>(1024);
2792        let stdout_handle = std::thread::spawn(move || {
2793            let reader = BufReader::new(stdout);
2794            for line in reader.lines().map_while(Result::ok) {
2795                if stdout_tx.send(line).is_err() {
2796                    break;
2797                }
2798            }
2799        });
2800
2801        let stderr_handle = std::thread::spawn(move || {
2802            if let Some(stderr) = stderr {
2803                let reader = BufReader::new(stderr);
2804                for line in reader.lines().map_while(Result::ok) {
2805                    if let Some(pause) = parse_gc_pause(&line) {
2806                        crate::metrics::record_jvm_gc(
2807                            pause.kind,
2808                            Duration::from_secs_f64(pause.millis / 1000.0),
2809                            pause.heap_after_mb,
2810                        );
2811                    }
2812                    if line.contains("Exception") || line.contains("ERROR") {
2813                        warn!(target: "self_hosted_node::java", "[java] {line}");
2814                    } else if line.contains("][gc") {
2815                        // -Xlog:gc*:stderr is opt-in, and debug would drop it before Loki.
2816                        info!(target: "self_hosted_node::java", "[java] {line}");
2817                    } else {
2818                        debug!(target: "self_hosted_node::java", "[java] {line}");
2819                    }
2820                }
2821            }
2822        });
2823
2824        Ok(Self {
2825            child,
2826            stdin: BufWriter::new(stdin),
2827            stdout_rx,
2828            stdout_handle: Some(stdout_handle),
2829            stderr_handle: Some(stderr_handle),
2830        })
2831    }
2832
2833    fn call(&mut self, request_json: &str) -> Result<String, String> {
2834        // Drain anything still queued from a prior request — a previous call()
2835        // that timed out may have left its reply in the channel, and consuming
2836        // it now would shift every subsequent call off-by-one.
2837        loop {
2838            match self.stdout_rx.try_recv() {
2839                Ok(stale) => {
2840                    debug!(target: "self_hosted_node::java", line = %stale, "discarding stale stdout line");
2841                }
2842                Err(TryRecvError::Empty) => break,
2843                Err(TryRecvError::Disconnected) => {
2844                    return Err("java subprocess closed stdout (crashed?)".to_string());
2845                }
2846            }
2847        }
2848
2849        self.stdin
2850            .write_all(request_json.as_bytes())
2851            .map_err(|err| format!("failed to write subprocess stdin: {err}"))?;
2852        self.stdin
2853            .write_all(b"\n")
2854            .map_err(|err| format!("failed to write subprocess newline: {err}"))?;
2855        self.stdin
2856            .flush()
2857            .map_err(|err| format!("failed to flush subprocess stdin: {err}"))?;
2858
2859        let deadline = Instant::now() + CALL_TIMEOUT;
2860        loop {
2861            let remaining = deadline.saturating_duration_since(Instant::now());
2862            if remaining.is_zero() {
2863                return Err(format!(
2864                    "java subprocess timed out after {}s",
2865                    CALL_TIMEOUT.as_secs()
2866                ));
2867            }
2868            match self.stdout_rx.recv_timeout(remaining) {
2869                Ok(line) => {
2870                    let trimmed = line.trim();
2871                    if trimmed.is_empty() {
2872                        continue;
2873                    }
2874                    match serde_json::from_str::<SubprocessReply>(trimmed) {
2875                        Ok(reply) if reply.ok => return Ok(reply.result),
2876                        Ok(reply) => {
2877                            return Err(reply.error.unwrap_or_else(|| "unknown java error".into()));
2878                        }
2879                        Err(_) => {
2880                            debug!(target: "self_hosted_node::java", line = trimmed, "non-protocol stdout line");
2881                        }
2882                    }
2883                }
2884                Err(RecvTimeoutError::Timeout) => {
2885                    return Err(format!(
2886                        "java subprocess timed out after {}s",
2887                        CALL_TIMEOUT.as_secs()
2888                    ));
2889                }
2890                Err(RecvTimeoutError::Disconnected) => {
2891                    return Err("java subprocess closed stdout (crashed?)".to_string());
2892                }
2893            }
2894        }
2895    }
2896
2897    fn reset(&mut self) -> Result<(), String> {
2898        self.call("{\"command\":\"reset\"}").map(|_| ())
2899    }
2900
2901    fn is_alive(&mut self) -> bool {
2902        matches!(self.child.try_wait(), Ok(None))
2903    }
2904
2905    fn shutdown(mut self) {
2906        let _ = self.stdin.write_all(b"{\"command\":\"quit\"}\n");
2907        let _ = self.stdin.flush();
2908        let deadline = Instant::now() + SHUTDOWN_GRACE;
2909        loop {
2910            match self.child.try_wait() {
2911                Ok(Some(_)) => break,
2912                Ok(None) if Instant::now() >= deadline => {
2913                    let _ = self.child.kill();
2914                    let _ = self.child.wait();
2915                    break;
2916                }
2917                Ok(None) => std::thread::sleep(Duration::from_millis(100)),
2918                Err(_) => break,
2919            }
2920        }
2921        if let Some(handle) = self.stdout_handle.take() {
2922            let _ = handle.join();
2923        }
2924        if let Some(handle) = self.stderr_handle.take() {
2925            let _ = handle.join();
2926        }
2927    }
2928}
2929
2930#[cfg(feature = "java-forge")]
2931impl JavaBridge for SubprocessBridge {
2932    fn initialize(&mut self, _assets_dir: &str) -> Result<(), String> {
2933        Ok(())
2934    }
2935
2936    fn start_game_json(&mut self, request_json: &str) -> Result<String, String> {
2937        let body = json!({ "command": "startGame", "payload": request_json });
2938        self.call(&body.to_string())
2939    }
2940
2941    fn submit_action(&mut self, session_id: &str, action_json: &str) -> Result<String, String> {
2942        let body = json!({
2943            "command": "submitAction",
2944            "sessionId": session_id,
2945            "payload": action_json,
2946        });
2947        self.call(&body.to_string())
2948    }
2949
2950    fn get_prompt(
2951        &mut self,
2952        session_id: &str,
2953        player_index: usize,
2954    ) -> Result<Option<String>, String> {
2955        let body = json!({
2956            "command": "getPrompt",
2957            "sessionId": session_id,
2958            "playerIndex": player_index,
2959        });
2960        let prompt = self.call(&body.to_string())?;
2961        Ok((!prompt.is_empty()).then_some(prompt))
2962    }
2963
2964    fn get_snapshot(&mut self, session_id: &str, viewer: Option<usize>) -> Result<String, String> {
2965        let mut body = json!({ "command": "getSnapshot", "sessionId": session_id });
2966        if let Some(viewer) = viewer {
2967            body["viewer"] = json!(viewer);
2968        }
2969        self.call(&body.to_string())
2970    }
2971
2972    fn is_game_over(&mut self, session_id: &str) -> Result<bool, String> {
2973        let body = json!({ "command": "getGameOver", "sessionId": session_id });
2974        let value = self.call(&body.to_string())?;
2975        Ok(value.trim() == "true")
2976    }
2977
2978    fn drain_checkpoint_metrics(&mut self, session_id: &str) -> Result<String, String> {
2979        let body = json!({ "command": "drainCheckpointMetrics", "sessionId": session_id });
2980        self.call(&body.to_string())
2981    }
2982
2983    fn state_revision(&mut self, session_id: &str) -> Result<u64, String> {
2984        let body = json!({ "command": "getStateRevision", "sessionId": session_id });
2985        parse_state_revision(&self.call(&body.to_string())?)
2986    }
2987
2988    fn end_game(&mut self, session_id: &str) -> Result<(), String> {
2989        let body = json!({ "command": "endGame", "sessionId": session_id });
2990        self.call(&body.to_string()).map(|_| ())
2991    }
2992
2993    fn abort_game(&mut self, session_id: &str) -> Result<(), String> {
2994        let body = json!({ "command": "abortGame", "sessionId": session_id });
2995        self.call(&body.to_string()).map(|_| ())
2996    }
2997}
2998
2999#[cfg(feature = "java-forge")]
3000impl Drop for SubprocessBridge {
3001    fn drop(&mut self) {
3002        let _ = self.child.kill();
3003        let _ = self.child.wait();
3004        if let Some(handle) = self.stdout_handle.take() {
3005            let _ = handle.join();
3006        }
3007        if let Some(handle) = self.stderr_handle.take() {
3008            let _ = handle.join();
3009        }
3010    }
3011}
3012
3013#[cfg(feature = "java-forge")]
3014fn resolve_java_bin(config: &JavaRuntimeConfig) -> String {
3015    if let Some(home) = &config.java_home {
3016        let bin = home.join("bin").join("java");
3017        if bin.is_file() {
3018            return bin.to_string_lossy().to_string();
3019        }
3020    }
3021    if let Ok(home) = env::var("JAVA_HOME") {
3022        let bin = PathBuf::from(home).join("bin").join("java");
3023        if bin.is_file() {
3024            return bin.to_string_lossy().to_string();
3025        }
3026    }
3027    "java".to_string()
3028}
3029
3030#[derive(Debug, Clone, Serialize)]
3031#[serde(rename_all = "camelCase")]
3032pub struct StartGameRequest {
3033    game_id: String,
3034    variant: String,
3035    starting_life: i32,
3036    seed: u64,
3037    players: Vec<PlayerConfig>,
3038    checkpoint_metrics: bool,
3039}
3040
3041#[derive(Debug, Clone, Serialize)]
3042#[serde(rename_all = "camelCase")]
3043pub struct PlayerConfig {
3044    name: String,
3045    deck: Vec<CardIdentityForJava>,
3046    commander_names: Vec<String>,
3047    ai: bool,
3048    bot: bool,
3049}
3050
3051#[derive(Debug, Clone, Serialize)]
3052#[serde(rename_all = "camelCase")]
3053pub struct CardIdentityForJava {
3054    name: String,
3055    set_code: Option<String>,
3056    collector_number: Option<String>,
3057    foil: bool,
3058}
3059
3060#[derive(Debug, serde::Deserialize)]
3061#[serde(rename_all = "camelCase")]
3062struct StartGameResponse {
3063    session_id: String,
3064    #[allow(dead_code)]
3065    player_indexes: Vec<usize>,
3066}
3067
3068impl StartGameRequest {
3069    pub fn new(
3070        game_id: String,
3071        variant: String,
3072        starting_life: i32,
3073        seed: u64,
3074        players: Vec<PlayerConfig>,
3075    ) -> Self {
3076        Self {
3077            game_id,
3078            variant,
3079            starting_life,
3080            seed,
3081            players,
3082            checkpoint_metrics: false,
3083        }
3084    }
3085
3086    pub fn to_json(&self) -> Result<String, serde_json::Error> {
3087        serde_json::to_string(self)
3088    }
3089}
3090
3091impl PlayerConfig {
3092    pub fn new(name: String, deck: &[DeckCardIdentity], commander_names: Vec<String>) -> Self {
3093        Self {
3094            name,
3095            deck: deck.iter().map(CardIdentityForJava::from).collect(),
3096            commander_names,
3097            ai: false,
3098            bot: false,
3099        }
3100    }
3101}
3102
3103impl From<&DeckCardIdentity> for CardIdentityForJava {
3104    fn from(identity: &DeckCardIdentity) -> Self {
3105        Self {
3106            name: java_card_name(&identity.name),
3107            set_code: (!identity.set_code.is_empty()).then(|| identity.set_code.clone()),
3108            collector_number: (!identity.card_number.is_empty())
3109                .then(|| identity.card_number.clone()),
3110            foil: identity.foil.unwrap_or(false),
3111        }
3112    }
3113}
3114
3115fn java_card_name(name: &str) -> String {
3116    name.split_once(" // ")
3117        .map(|(front, _)| front.to_string())
3118        .unwrap_or_else(|| name.to_string())
3119}
3120
3121fn env_path(key: &str) -> Option<PathBuf> {
3122    env::var_os(key)
3123        .filter(|value| !value.is_empty())
3124        .map(PathBuf::from)
3125}
3126
3127fn env_sizing(key: &str, default: u64) -> Option<u64> {
3128    let value = match env::var(key) {
3129        Ok(raw) if !raw.trim().is_empty() => match raw.trim().parse::<u64>() {
3130            Ok(parsed) => parsed,
3131            Err(_) => {
3132                tracing::warn!(target: "self_hosted_node::java", key, raw, "ignoring unparseable jvm sizing");
3133                default
3134            }
3135        },
3136        _ => default,
3137    };
3138    (value > 0).then_some(value)
3139}
3140
3141fn env_classpath(key: &str) -> Vec<PathBuf> {
3142    let Some(value) = env::var_os(key) else {
3143        return Vec::new();
3144    };
3145    env::split_paths(&value).collect()
3146}
3147
3148fn require_dir(path: &Path, label: &str) -> Result<(), String> {
3149    if path.is_dir() {
3150        Ok(())
3151    } else {
3152        Err(format!("{label} does not exist: {}", path.display()))
3153    }
3154}
3155
3156fn require_file(path: &Path, label: &str) -> Result<(), String> {
3157    if path.is_file() {
3158        Ok(())
3159    } else {
3160        Err(format!("{label} does not exist: {}", path.display()))
3161    }
3162}
3163
3164/// One `Pause` line from the JVM's unified GC log.
3165struct GcPause {
3166    kind: &'static str,
3167    millis: f64,
3168    heap_after_mb: Option<u64>,
3169}
3170
3171/// Parse a unified-log GC pause, e.g.
3172/// `[12.3s][info][gc] GC(7) Pause Full (Allocation Failure) 240M->171M(247M) 226.856ms`
3173fn parse_gc_pause(line: &str) -> Option<GcPause> {
3174    let kind = if line.contains("Pause Full") {
3175        "full"
3176    } else if line.contains("Pause Young") {
3177        "young"
3178    } else {
3179        return None;
3180    };
3181    let millis = line
3182        .rsplit(' ')
3183        .find_map(|token| token.strip_suffix("ms")?.parse::<f64>().ok())?;
3184    // "240M->171M(247M)": the figure after the arrow is what survived.
3185    let heap_after_mb = line.split_once("->").and_then(|(_, rest)| {
3186        let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
3187        digits.parse::<u64>().ok()
3188    });
3189    Some(GcPause {
3190        kind,
3191        millis,
3192        heap_after_mb,
3193    })
3194}
3195
3196#[cfg(test)]
3197mod gc_log_tests {
3198    use super::{parse_gc_pause, PlayerConfig, StartGameRequest};
3199    use manabrew_protocol::deck_dto::DeckCardIdentity;
3200
3201    #[test]
3202    fn reads_a_full_collection() {
3203        let pause = parse_gc_pause(
3204            "[117.6s][info][gc] GC(21) Pause Full (Allocation Failure) 240M->171M(247M) 226.856ms",
3205        )
3206        .expect("parsed");
3207        assert_eq!(pause.kind, "full");
3208        assert_eq!(pause.heap_after_mb, Some(171));
3209        assert!((pause.millis - 226.856).abs() < f64::EPSILON);
3210    }
3211
3212    #[test]
3213    fn reads_a_young_collection() {
3214        let pause = parse_gc_pause(
3215            "[3.1s][info][gc] GC(2) Pause Young (Allocation Failure) 216M->91M(494M) 17.254ms",
3216        )
3217        .expect("parsed");
3218        assert_eq!(pause.kind, "young");
3219        assert_eq!(pause.heap_after_mb, Some(91));
3220    }
3221
3222    /// The node asks for `-Xlog:gc*:stderr:time,uptime,level,tags`, which is a
3223    /// richer line than plain `-Xlog:gc`. Real production output.
3224    #[test]
3225    fn reads_the_format_the_node_actually_requests() {
3226        let pause = parse_gc_pause(
3227            "[2026-08-18T20:41:42.907+0000][120025.819s][info][gc] GC(1202) Pause Full (Allocation Failure) 494M->487M(494M) 545.344ms",
3228        )
3229        .expect("parsed");
3230        assert_eq!(pause.kind, "full");
3231        assert_eq!(pause.heap_after_mb, Some(487));
3232        assert!((pause.millis - 545.344).abs() < f64::EPSILON);
3233    }
3234
3235    /// `gc*` also emits region and metaspace lines that carry `->`; they must
3236    /// not be mistaken for pauses.
3237    #[test]
3238    fn ignores_the_extra_lines_gc_star_adds() {
3239        assert!(
3240            parse_gc_pause("[120025.819s][info][gc,heap] GC(1202) Eden regions: 10->0(12)")
3241                .is_none()
3242        );
3243        assert!(
3244            parse_gc_pause("[120025.819s][info][gc,metaspace] Metaspace: 48M->48M(1088M)")
3245                .is_none()
3246        );
3247    }
3248
3249    #[test]
3250    fn ignores_other_output() {
3251        assert!(parse_gc_pause("[java] LOGGER ERROR: something").is_none());
3252        assert!(parse_gc_pause("[1.0s][info][gc,init] CardTable entry size: 512").is_none());
3253    }
3254
3255    #[test]
3256    fn serializes_exact_printing_identity_for_java() {
3257        let card = DeckCardIdentity {
3258            name: "Forest".to_string(),
3259            set_code: "EOE".to_string(),
3260            card_number: "266".to_string(),
3261            foil: Some(true),
3262            ..Default::default()
3263        };
3264        let request = StartGameRequest::new(
3265            "printing-test".to_string(),
3266            "Constructed".to_string(),
3267            20,
3268            42,
3269            vec![PlayerConfig::new("Player".to_string(), &[card], Vec::new())],
3270        );
3271        let json = request.to_json().expect("serialized");
3272
3273        assert!(json.contains(
3274            r#""deck":[{"name":"Forest","setCode":"EOE","collectorNumber":"266","foil":true}]"#
3275        ));
3276    }
3277}