saints-mile 1.0.2

A frontier JRPG for the adults who loved those games first
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! State store — RON-backed persistence with versioned save envelope.
//!
//! Hard rule: never let load logic "repair" morally important ambiguity
//! into certainty. If a witness is compromised, partial, unverified, or
//! branch-dependent, the save/load layer preserves that exact mess.

use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use tracing::info;

use super::types::GameState;
use crate::scene::types::StateEffect;

/// Current save format version. Bump when GameState shape changes.
pub const SAVE_VERSION: u32 = 1;

/// Versioned save envelope — wraps GameState with metadata.
/// The envelope is what gets serialized to disk. GameState is the truth.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaveEnvelope {
    /// Schema version — checked on load.
    pub version: u32,
    /// Human-readable label for the save slot.
    pub label: String,
    /// When this save was written (unix timestamp).
    pub timestamp: u64,
    /// The actual game state — the biography.
    pub state: GameState,
}

impl SaveEnvelope {
    /// Create a new save envelope from current game state.
    pub fn new(state: GameState, label: impl Into<String>) -> Self {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_else(|_| {
                eprintln!("warning: system clock unavailable, save timestamp set to 0");
                std::time::Duration::ZERO
            })
            .as_secs();

        Self {
            version: SAVE_VERSION,
            label: label.into(),
            timestamp,
            state,
        }
    }
}

/// The state store — owns the live GameState and handles persistence.
#[derive(Debug)]
pub struct StateStore {
    /// The live game state. This is the single source of truth.
    state: GameState,
    /// Save directory path.
    save_dir: PathBuf,
}

impl StateStore {
    /// Create a new store with a fresh game state.
    pub fn new_game(save_dir: impl Into<PathBuf>) -> Self {
        let state = GameState::new_game();
        info!(chapter = %state.chapter, beat = %state.beat, "new game started");
        Self {
            state,
            save_dir: save_dir.into(),
        }
    }

    /// Create a store from an existing state (for fixtures/quickstart).
    pub fn from_state(state: GameState, save_dir: impl Into<PathBuf>) -> Self {
        Self {
            state,
            save_dir: save_dir.into(),
        }
    }

    /// Load from a save file. Returns an error if the version is incompatible.
    pub fn load(path: &Path) -> Result<Self> {
        let contents = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read save file: {}", path.display()))?;

        let envelope: SaveEnvelope = ron::from_str(&contents)
            .with_context(|| "save file is corrupt or uses an unknown format")?;

        if envelope.version != SAVE_VERSION {
            anyhow::bail!(
                "save version mismatch: file is v{}, game expects v{}. \
                 Save migration is not yet supported.",
                envelope.version,
                SAVE_VERSION,
            );
        }

        // Fallback to "." if path has no parent (e.g. bare filename with no directory).
        let save_dir = path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf();

        info!(
            version = envelope.version,
            label = %envelope.label,
            chapter = %envelope.state.chapter,
            beat = %envelope.state.beat,
            "save loaded"
        );

        Ok(Self {
            state: envelope.state,
            save_dir,
        })
    }

    /// Save current state to a file.
    ///
    /// Uses write-to-temp + rename for atomic writes. If a previous save exists,
    /// it is backed up to `<slot>.ron.bak` (at most 1 backup per slot).
    pub fn save(&self, slot_name: &str) -> Result<PathBuf> {
        std::fs::create_dir_all(&self.save_dir)
            .with_context(|| format!("failed to create save directory: {}", self.save_dir.display()))?;

        let label = format!(
            "{}{} ({})",
            self.state.chapter, self.state.beat, self.state.age_phase_label()
        );

        let envelope = SaveEnvelope::new(self.state.clone(), label);

        let path = self.save_dir.join(format!("{}.ron", slot_name));
        let tmp_path = self.save_dir.join(format!("{}.ron.tmp", slot_name));
        let bak_path = self.save_dir.join(format!("{}.ron.bak", slot_name));

        let serialized = ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default())
            .context("failed to serialize game state")?;

        // Write to temp file first
        std::fs::write(&tmp_path, &serialized)
            .with_context(|| format!("failed to write temp save file: {}", tmp_path.display()))?;

        // If existing save exists, back it up (overwrite previous backup)
        if path.exists() {
            // Best-effort backup — don't fail the save if backup fails
            let _ = std::fs::rename(&path, &bak_path);
        }

        // Atomic rename: temp → final
        std::fs::rename(&tmp_path, &path)
            .with_context(|| format!("failed to rename temp save to final: {}", path.display()))?;

        info!(slot = slot_name, path = %path.display(), "game saved");
        Ok(path)
    }

    /// Delete a save file from a slot.
    pub fn delete_save(slot: &str, save_dir: &Path) -> Result<(), String> {
        let path = save_dir.join(format!("{}.ron", slot));
        if !path.exists() {
            return Err(format!("Save slot '{}' is already empty.", slot));
        }
        // Validate resolved path is within save directory
        if let (Ok(canonical_dir), Ok(canonical_path)) = (
            std::fs::canonicalize(save_dir),
            std::fs::canonicalize(&path),
        ) {
            if !canonical_path.starts_with(&canonical_dir) {
                return Err("Invalid save path.".to_string());
            }
        }
        std::fs::remove_file(&path)
            .map_err(|e| format!("Failed to delete save: {}", e))?;
        info!(slot = slot, "save deleted");
        Ok(())
    }

    /// Save directory path.
    pub fn save_dir(&self) -> &Path {
        &self.save_dir
    }

    // --- State access ---

    /// Get immutable reference to the live state.
    pub fn state(&self) -> &GameState {
        &self.state
    }

    /// Get mutable reference to the live state.
    pub fn state_mut(&mut self) -> &mut GameState {
        &mut self.state
    }

    // --- State mutation with audit trail ---

    /// Apply a single state effect with tracing.
    pub fn apply_effect(&mut self, effect: &StateEffect) {
        tracing::debug!(?effect, "applying state effect");
        self.state.apply_effect(effect);
    }

    /// Apply multiple state effects with tracing.
    pub fn apply_effects(&mut self, effects: &[StateEffect]) {
        for effect in effects {
            self.apply_effect(effect);
        }
    }

    /// Check a condition against current state.
    pub fn check(&self, condition: &crate::scene::types::Condition) -> bool {
        self.state.check_condition(condition)
    }

    /// Check all conditions — all must be true.
    pub fn check_all(&self, conditions: &[crate::scene::types::Condition]) -> bool {
        self.state.check_all(conditions)
    }
}

/// Auto-save the current game state to a dedicated autosave slot.
///
/// Called at chapter transitions and before combat encounters.
/// Uses the "autosave" slot name, separate from player save slots.
pub fn auto_save(state: &GameState, save_dir: &Path) -> Result<PathBuf> {
    std::fs::create_dir_all(save_dir)
        .with_context(|| format!("failed to create save directory: {}", save_dir.display()))?;

    let label = format!(
        "Auto — {}{} ({})",
        state.chapter, state.beat, state.age_phase_label()
    );

    let envelope = SaveEnvelope::new(state.clone(), label);
    let path = save_dir.join("autosave.ron");
    let serialized = ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default())
        .context("failed to serialize game state for autosave")?;

    std::fs::write(&path, &serialized)
        .with_context(|| format!("failed to write autosave: {}", path.display()))?;

    info!(path = %path.display(), "autosave written");
    Ok(path)
}

impl GameState {
    /// Human-readable age phase label for save descriptions.
    pub fn age_phase_label(&self) -> &'static str {
        match self.age_phase {
            crate::types::AgePhase::Youth => "Age 19",
            crate::types::AgePhase::YoungMan => "Age 24",
            crate::types::AgePhase::Adult => "Age 34",
            crate::types::AgePhase::Older => "Age 50+",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::*;
    use crate::scene::types::*;
    use crate::state::types::*;
    use tempfile::TempDir;

    /// Find a party member by string ID — avoids repeated `.find(|m| m.id.0 == ...)` in tests.
    fn find_member<'a>(state: &'a GameState, id: &str) -> Option<&'a PartyMemberState> {
        state.party.members.iter().find(|m| m.id.0 == id)
    }

    /// Round-trip: new game → save → load → verify identical.
    #[test]
    fn round_trip_new_game() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());

        // Save
        let path = store.save("test_slot").unwrap();
        assert!(path.exists());

        // Load
        let loaded = StateStore::load(&path).unwrap();

        // Verify critical fields survive
        assert_eq!(loaded.state().chapter.0, "prologue");
        assert_eq!(loaded.state().beat.0, "p1");
        assert_eq!(loaded.state().age_phase, AgePhase::Adult);
        assert_eq!(loaded.state().party.members.len(), 2);
        assert!(loaded.state().party.has_member(&CharacterId::new("galen")));
        assert!(loaded.state().party.has_member(&CharacterId::new("eli")));
        assert_eq!(loaded.state().prologue_choice, None);
        assert_eq!(loaded.state().relay_branch, None);
    }

    /// Version mismatch produces a clear error.
    #[test]
    fn version_mismatch_fails_cleanly() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());
        let path = store.save("test_slot").unwrap();

        // Tamper with version
        let mut contents = std::fs::read_to_string(&path).unwrap();
        contents = contents.replace(
            &format!("version: {}", SAVE_VERSION),
            "version: 999",
        );
        std::fs::write(&path, &contents).unwrap();

        let result = StateStore::load(&path);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("version mismatch"), "error was: {}", err);
    }

    /// Delete save removes the file.
    #[test]
    fn delete_save_removes_file() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());
        let path = store.save("to_delete").unwrap();
        assert!(path.exists());
        StateStore::delete_save("to_delete", dir.path()).unwrap();
        assert!(!path.exists());
    }

    /// Delete of empty slot returns error.
    #[test]
    fn delete_empty_slot_fails() {
        let dir = TempDir::new().unwrap();
        let result = StateStore::delete_save("nonexistent", dir.path());
        assert!(result.is_err());
    }

    /// Auto-save writes to autosave.ron.
    #[test]
    fn auto_save_creates_file() {
        let dir = TempDir::new().unwrap();
        let state = GameState::new_game();
        let path = super::auto_save(&state, dir.path()).unwrap();
        assert!(path.exists());
        assert!(path.file_name().unwrap().to_str().unwrap().contains("autosave"));

        // Verify it loads correctly
        let loaded = StateStore::load(&path).unwrap();
        assert_eq!(loaded.state().chapter.0, "prologue");
    }

    /// Save creates backup of existing file.
    #[test]
    fn save_creates_backup() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());

        // First save — no backup expected
        let path = store.save("backup_test").unwrap();
        assert!(path.exists());
        let bak_path = dir.path().join("backup_test.ron.bak");
        assert!(!bak_path.exists(), "no backup on first save");

        // Second save — backup should be created
        let path2 = store.save("backup_test").unwrap();
        assert!(path2.exists());
        assert!(bak_path.exists(), "backup created on second save");

        // Both load correctly
        let loaded = StateStore::load(&path2).unwrap();
        assert_eq!(loaded.state().chapter.0, "prologue");
        let loaded_bak = StateStore::load(&bak_path).unwrap();
        assert_eq!(loaded_bak.state().chapter.0, "prologue");
    }

    /// No temp files left after save.
    #[test]
    fn save_no_leftover_tmp() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());
        store.save("tmp_test").unwrap();

        let tmp_path = dir.path().join("tmp_test.ron.tmp");
        assert!(!tmp_path.exists(), "temp file should be renamed away");
    }

    /// Eli's Loyalty line: grayed out but known. Skills not present, line exists in schema.
    #[test]
    fn eli_loyalty_line_grayed_out() {
        let dir = TempDir::new().unwrap();
        let store = StateStore::new_game(dir.path());

        // Eli has no Loyalty skills unlocked
        let eli = find_member(store.state(), "eli").unwrap();
        assert!(eli.unlocked_skills.is_empty());

        // But the SkillLine::Loyalty variant exists in the type system
        // (this is a compile-time guarantee, not a runtime check)
        let _loyalty = crate::combat::types::SkillLine::Loyalty;
    }

    /// Dead Drop persists once unlocked.
    #[test]
    fn dead_drop_persists() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Unlock Dead Drop on Galen
        let effect = StateEffect::UnlockSkill {
            character: CharacterId::new("galen"),
            skill: SkillId::new("dead_drop"),
        };
        store.apply_effect(&effect);

        // Verify it's there
        assert!(store.state().party.has_skill(
            &CharacterId::new("galen"),
            &SkillId::new("dead_drop"),
        ));

        // Save and reload
        let path = store.save("dead_drop_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();
        assert!(loaded.state().party.has_skill(
            &CharacterId::new("galen"),
            &SkillId::new("dead_drop"),
        ));
    }

    /// Evidence integrity survives round-trip.
    #[test]
    fn evidence_integrity_survives() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Add evidence with partial integrity (scorched relay papers)
        store.state_mut().evidence.push(EvidenceItem {
            id: EvidenceId::new("relay_manifest"),
            evidence_type: EvidenceType::Documentary,
            source_chapter: ChapterId::new("ch2"),
            integrity: 45, // scorched, partial
            verified_against: vec![EvidenceId::new("archive_original")],
        });

        let path = store.save("evidence_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();

        let evidence = loaded.state().evidence.iter()
            .find(|e| e.id.0 == "relay_manifest").unwrap();
        assert_eq!(evidence.integrity, 45);
        assert_eq!(evidence.verified_against.len(), 1);
        assert_eq!(evidence.verified_against[0].0, "archive_original");
    }

    /// Witness state survives branching outcomes.
    #[test]
    fn witness_state_branching() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Set witness states from the relay
        store.apply_effect(&StateEffect::SetWitnessState {
            id: WitnessId::new("tom_reed"),
            alive: true,
            integrity: 80,
        });
        store.apply_effect(&StateEffect::SetWitnessState {
            id: WitnessId::new("nella_creed"),
            alive: false,
            integrity: 0,
        });

        let path = store.save("witness_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();

        let tom = loaded.state().witness_states.get("tom_reed").unwrap();
        assert!(tom.alive);
        assert_eq!(tom.integrity, 80);

        let nella = loaded.state().witness_states.get("nella_creed").unwrap();
        assert!(!nella.alive);
        assert_eq!(nella.integrity, 0);
    }

    /// Hand injury field persists.
    #[test]
    fn hand_injury_persists() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Damage Galen's hand
        if let Some(galen) = store.state_mut().party.members.iter_mut()
            .find(|m| m.id.0 == "galen")  // mutable access — can't use find_member helper
        {
            galen.hand_state = HandState::Damaged;
        }

        let path = store.save("hand_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();

        let galen = find_member(loaded.state(), "galen").unwrap();
        assert_eq!(galen.hand_state, HandState::Damaged);
    }

    /// Memory objects survive and can echo.
    #[test]
    fn memory_objects_persist() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Add memory objects
        store.apply_effect(&StateEffect::AddMemoryObject(
            MemoryObjectId::new("wanted_poster"),
        ));
        store.apply_effect(&StateEffect::AddMemoryObject(
            MemoryObjectId::new("biscuit_cloth"),
        ));

        // Transform one
        store.apply_effect(&StateEffect::TransformMemoryObject {
            id: MemoryObjectId::new("biscuit_cloth"),
            new_state: "bloodstained".to_string(),
        });

        let path = store.save("memory_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();

        assert_eq!(loaded.state().memory_objects.len(), 2);

        let poster = loaded.state().memory_objects.iter()
            .find(|o| o.id.0 == "wanted_poster").unwrap();
        assert_eq!(poster.state, "active");

        let cloth = loaded.state().memory_objects.iter()
            .find(|o| o.id.0 == "biscuit_cloth").unwrap();
        assert_eq!(cloth.state, "bloodstained");
    }

    /// Condition checking works correctly.
    #[test]
    fn condition_checking() {
        let mut state = GameState::new_game();

        // Set prologue choice
        state.prologue_choice = Some(PrologueChoice::HomesteadFirst);

        // Check prologue condition
        assert!(state.check_condition(&Condition::PrologueChoice(PrologueChoice::HomesteadFirst)));
        assert!(!state.check_condition(&Condition::PrologueChoice(PrologueChoice::TownDirect)));

        // Set a flag
        state.apply_effect(&StateEffect::SetFlag {
            id: FlagId::new("bitter_cut_pulled_punches"),
            value: FlagValue::Bool(true),
        });

        assert!(state.check_condition(&Condition::Flag {
            id: FlagId::new("bitter_cut_pulled_punches"),
            value: FlagValue::Bool(true),
        }));

        // Reputation check
        state.apply_effect(&StateEffect::AdjustReputation {
            axis: ReputationAxis::Rancher,
            delta: 15,
        });

        assert!(state.check_condition(&Condition::Reputation {
            axis: ReputationAxis::Rancher,
            op: CompareOp::Gte,
            threshold: 10,
        }));
        assert!(!state.check_condition(&Condition::Reputation {
            axis: ReputationAxis::Rancher,
            op: CompareOp::Gte,
            threshold: 20,
        }));
    }

    /// Relay branch as first-class state axis.
    #[test]
    fn relay_branch_first_class() {
        let dir = TempDir::new().unwrap();
        let mut store = StateStore::new_game(dir.path());

        // Set relay branch
        store.state_mut().relay_branch = Some(RelayBranch::Nella);
        store.state_mut().nella_alive = Some(true);
        store.state_mut().tom_alive = Some(false);

        // Check condition
        assert!(store.check(&Condition::RelayBranch(RelayBranch::Nella)));
        assert!(!store.check(&Condition::RelayBranch(RelayBranch::Tom)));

        // Persists
        let path = store.save("relay_test").unwrap();
        let loaded = StateStore::load(&path).unwrap();
        assert_eq!(loaded.state().relay_branch, Some(RelayBranch::Nella));
        assert_eq!(loaded.state().nella_alive, Some(true));
        assert_eq!(loaded.state().tom_alive, Some(false));
    }

    /// Effect application: complex multi-effect sequence.
    #[test]
    fn complex_effect_sequence() {
        let mut state = GameState::new_game();

        // Simulate the prologue's Beat 5 choice + consequences
        let effects = vec![
            StateEffect::SetFlag {
                id: FlagId::new("beat5_choice"),
                value: FlagValue::Text("homestead_first".to_string()),
            },
            StateEffect::AdjustReputation { axis: ReputationAxis::Rancher, delta: 10 },
            StateEffect::AdjustReputation { axis: ReputationAxis::TownLaw, delta: -5 },
            StateEffect::AddMemoryObject(MemoryObjectId::new("wanted_poster")),
            StateEffect::AdjustResource { resource: ResourceKind::Water, delta: -30 },
            StateEffect::AdjustResource { resource: ResourceKind::HorseStamina, delta: -40 },
            StateEffect::SetRelationship {
                a: CharacterId::new("galen"),
                b: CharacterId::new("eli"),
                value: 15,
            },
        ];

        state.apply_all(&effects);

        assert_eq!(state.reputation.get(ReputationAxis::Rancher), 10);
        assert_eq!(state.reputation.get(ReputationAxis::TownLaw), -5);
        assert_eq!(state.memory_objects.len(), 1);
        assert_eq!(state.resources.water, 70);
        assert_eq!(state.resources.horse_stamina, 60);
        assert_eq!(*state.party.relationships.get("galen:eli").unwrap(), 15);
    }
}