From aabb3499c74c6c7010859f6f3ca1101da7215fa3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 1/7] AutoStory engine: no retry after a SAVE step saved part-way A reload after that save would land mid-checkpoint while the retry runs from step 1. The engine now records the save and ends the checkpoint's attempts there. --- .../AutoStory/Engine/Pokemon_StoryEngine.cpp | 21 +++++++--- .../AutoStory/Engine/Pokemon_StoryEngine.h | 11 +++-- .../Engine/Pokemon_StoryEnginePolicy.h | 3 ++ .../Engine/Pokemon_StoryEngineRuns_Tests.cpp | 41 ++++++++++++++++--- 4 files changed, 62 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp index a0db19df53..ccfd146863 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp @@ -68,12 +68,12 @@ class RunnerExecutor : public StoryStepExecutor{ // `game` with its SAVE step "save" saving `current` only while `mode` is // PER_CHECKPOINT: a checkpoint under test or verification must not save -// part-way. +// part-way. Sets `saved` when it saves. template StoryGame with_gated_save_step( - StoryGame game, const StorySaveMode& mode, const StoryCheckpoint* const& current + StoryGame game, const StorySaveMode& mode, const StoryCheckpoint* const& current, bool& saved ){ - StoryActionHandler gated = [&mode, ¤t, save = game.save]( + StoryActionHandler gated = [&mode, ¤t, &saved, save = game.save]( StoryBackend& backend, const StoryActionCall&, RunState& ){ if (mode != StorySaveMode::PER_CHECKPOINT){ @@ -83,7 +83,9 @@ StoryGame with_gated_save_step( if (!save || current == nullptr){ return outcome_failed("unsupported_step", "save needs StoryGame::save"); } - return save(backend, *current); + Outcome outcome = save(backend, *current); + saved = saved || outcome.succeeded(); + return outcome; }; game.actions.push_back({.spec = {.kind = StoryStepKind::SAVE, .name = "save", .args = {}}, .handler = std::move(gated)}); return game; @@ -181,7 +183,7 @@ ObservedState observed_state(const Observation& observation){ template StoryEngine::StoryEngine(const StoryGame& game, StoryBackend& backend) - : m_game(with_gated_save_step(game, m_save_mode, m_checkpoint)) + : m_game(with_gated_save_step(game, m_save_mode, m_checkpoint, m_saved_part_way)) , m_backend(backend) , m_registry(m_game) , m_runner(m_registry, backend) @@ -222,7 +224,9 @@ StoryEngineReport StoryEngine::run_once( m_backend.log(report.save.reason); m_save_mode = report.save.mode; m_checkpoint = &checkpoint; + m_saved_part_way = false; report.run = run_steps(checkpoint, state); + report.saved_part_way = m_saved_part_way; m_save_mode = StorySaveMode::NONE; m_checkpoint = nullptr; if (!report.run.completed){ @@ -266,6 +270,13 @@ StoryEngineReport StoryEngine::run_with_retries( if (report.verdict == CheckpointVerdict::PASSED){ return AttemptResult::PASSED; } + if (report.saved_part_way){ + m_backend.log(std::format( + "[Checkpoint] {}: a save step saved part-way, so a reload would not return to its start: no retry", + checkpoint.id + )); + return AttemptResult::FINAL; + } return repeats_on_reload(report.run.failure) ? AttemptResult::FINAL : AttemptResult::FAILED; }, .reset = [&](size_t next_attempt){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h index e7cabbcf9a..185ab5dc52 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h @@ -70,9 +70,10 @@ class StoryEngine{ // `attempts_per_checkpoint` runs, only when a reload returns to the // save it started from: the first checkpoint's, or one the checkpoint // before it saved at its end. In none and after_verification modes - // (#329) that leaves only the first. No reload either for a failure - // every attempt would repeat: a lint, a console_only action, the game - // not running. Logs "[Segment] : ..." lines. + // that leaves only the first. No reload once a SAVE step has saved + // part-way through the attempt (the reload would land there), nor for + // a failure every attempt would repeat: a lint, a console_only action, + // the game not running. Logs "[Segment] : ..." lines. SegmentReport run_segment( std::string_view id, std::span checkpoints, size_t attempts_per_checkpoint, RunState& state @@ -109,9 +110,11 @@ class StoryEngine{ const StoryCheckpoint& checkpoint, SavePoint point, size_t attempts, RunState& state, CheckpointRun& run ); - // Declared first: m_game's save step reads them. + // Declared first: m_game's save step reads them, and sets + // m_saved_part_way when it saves. StorySaveMode m_save_mode = StorySaveMode::NONE; const StoryCheckpoint* m_checkpoint = nullptr; + bool m_saved_part_way = false; StoryGame m_game; StoryBackend& m_backend; StoryActionRegistry m_registry; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy.h index 0856147d0b..197fce0023 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy.h @@ -52,6 +52,9 @@ struct StoryEngineReport{ // Checked after steps that completed. std::optional postconditions = std::nullopt; bool saved = false; + // A SAVE step among its steps saved: a reload now returns there, not + // to the save the checkpoint started from. + bool saved_part_way = false; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index 851f380bcc..ecfc8a691b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -7,7 +7,7 @@ * the heading reading, the choice and interact events, a screen machine * over observations, the step in an action's call, the checkpoint in the * save, the segment and verify loops, console-only actions, declared poses - * read as the game's pose type, and tile actions only for tile games. + * of the game's kind only, and tile actions only for tile games. * Then what PLZA found on the engine: readers opt in to the postcondition * check, inputs logged by button name, waiting states may stay still, and * the stick's release. @@ -517,15 +517,21 @@ std::string handler_sees_step(CancellableScope& scope){ return *seen == "opening / the long intro" ? "" : std::format("expected the step, got \"{}\"", *seen); } +StoryStep save_step(std::string name){ + StoryStep step; + step.kind = StoryStepKind::SAVE; + step.name = std::move(name); + return step; +} + // Gap 6: the save is told its checkpoint, at the end and at a SAVE step. std::string save_gets_checkpoint(CancellableScope& scope){ StoryGame game = flaky_game(0); FakeStoryBackend backend({.looks = {look({ScreenEvent::PLAYER_CAN_MOVE})}}, scope); StoryEngine engine(game, backend); - StoryStep save; - save.kind = StoryStepKind::SAVE; - save.name = "save_here"; - const StoryCheckpoint checkpoint = in_phase(checkpoint_of("02.01", {game_step("walk", "fine"), save}), StoryPhase::REPRODUCTION, engine); + const StoryCheckpoint checkpoint = in_phase( + checkpoint_of("02.01", {game_step("walk", "fine"), save_step("save_here")}), StoryPhase::REPRODUCTION, engine + ); RunState state; const StoryEngineReport report = engine.run_checkpoint(checkpoint, SavePoint::CHECKPOINT_END, state); if (!report.saved){ @@ -535,6 +541,30 @@ std::string save_gets_checkpoint(CancellableScope& scope){ return saves == 2 ? "" : std::format("expected 2 saves of 02.01, got {}: {}", saves, joined(backend.lines())); } +// A SAVE step part-way through a checkpoint moves the save: a reload +// after a later failure would not return to the checkpoint's start, so +// the segment stops there instead of retrying from step 1. +std::string no_retry_after_a_save_step(CancellableScope& scope){ + StoryGame game = flaky_game(1); + FakeStoryBackend backend({.looks = {look({ScreenEvent::PLAYER_CAN_MOVE})}}, scope); + StoryEngine engine(game, backend); + const std::vector checkpoints{in_phase( + checkpoint_of("02.01", {game_step("walk", "fine"), save_step("save_here"), game_step("talk", "flaky")}), + StoryPhase::REPRODUCTION, engine + )}; + RunState state; + const SegmentReport report = engine.run_segment("seg", checkpoints, 3, state); + if (report.completed || report.failed_event != "talk" || report.failure.failure != "flaky_failed"){ + return std::format("expected the segment to stop at talk, got {}: {}", to_string(report.failure), joined(backend.lines())); + } + if (count_lines(backend, "[Test] reload") != 0){ + return std::format("expected no reload: {}", joined(backend.lines())); + } + return has_line(backend, "[Checkpoint] 02.01: a save step saved part-way, so a reload would not return to its start: no retry") + ? "" + : std::format("expected the no-retry line: {}", joined(backend.lines())); +} + // Gap 8: a console_only action is refused, before any input, on a backend // that is no console; it runs on one. StoryGame console_game(){ @@ -913,6 +943,7 @@ const RunsCase RUNS_CASES[] = { {.name = "observation machine fails", .input = {.check = &observation_machine_fails}, .expectation = {}}, {.name = "handler sees its step", .input = {.check = &handler_sees_step}, .expectation = {}}, {.name = "save gets its checkpoint", .input = {.check = &save_gets_checkpoint}, .expectation = {}}, + {.name = "no retry after a save step", .input = {.check = &no_retry_after_a_save_step}, .expectation = {}}, {.name = "console_only refused off console", .input = {.check = &console_only_refused}, .expectation = {}}, {.name = "no reload for console_only", .input = {.check = &segment_no_reload_for_console_only}, .expectation = {}}, {.name = "verify saves after all passed", .input = {.check = &verify_saves_after_all_passed}, .expectation = {}}, From 77ece85c57402f0a4c1c0ae649c84868cc02ee2a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 2/7] AutoStory: SAVE steps in testing, once_per_save in JSON, save option text A test pins that the engine's SAVE step saves nothing in a testing run; StoryStepExecutor::run says a game off the engine must gate it itself. The step reader accepts once_per_save. The Save and Verify Mode texts say when After verification saves. --- .../Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp | 7 ++++++- .../AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp | 6 ++++++ .../AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp | 2 ++ .../Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h | 7 +++++-- .../Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h | 4 ++-- .../Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h | 2 +- .../Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp | 8 +++++--- .../Source/Pokemon/Options/Pokemon_StoryRunOptions.h | 7 ++++--- 8 files changed, 31 insertions(+), 12 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 3d39269e07..095cbd5014 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -324,7 +324,9 @@ DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source) } StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ - const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after"}, source); + const JsonObject& root = fields( + value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after", "once_per_save"}, source + ); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -344,6 +346,9 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source, std:: if (const JsonValue* field = root.get_value("declared_after")){ result.pose_after = read_declared_pose(*field, source); } + if (const JsonValue* field = root.get_value("once_per_save")){ + result.once_per_save = field->to_boolean_throw(std::string(source)); + } return result; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 69f213ad13..5af96acd8f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -79,6 +79,12 @@ const WireCase CASES[] = { return expect(step.kind == StoryStepKind::GAME && step.why == "source reason" && step.action == "profile" && step.skip_if == std::vector{"flag"} && step.pose_after == after, "every shared field read"); }}}, + {.input = {.name = "once per save", .json = R"({"id":"heal","kind":"game_action","action":"profile","once_per_save":true})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(step_of(record).once_per_save, "a once_per_save step"); + }}}, + {.input = {.name = "every time by default", .json = R"({"id":"heal","kind":"game_action","action":"profile"})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(!step_of(record).once_per_save, "a step run every time"); + }}}, {.input = {.name = "route fills its fallback", .json = R"({"id":"r","kind":"route","args":{"target":{"map":"A","tiles":[[1,2]]}}})"}, .expectation = {.check = [](const ReadRecord& record){ const StoryActionArgs expected = {{"fight_wild", false}, {"target", GridPose{.map = "A", .tiles = {{1, 2}}, .facing = std::nullopt}}}; return expect(step_of(record).args == expected, "the target and fight_wild false"); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp index e65b730dbf..c1f7b74094 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp @@ -131,6 +131,8 @@ const EngineCase ENGINE_CASES[] = { {.name = "failed run never saves", .input = {.phase = "reproduction", .end_map = ""}, .expectation = {.mode = StorySaveMode::PER_CHECKPOINT, .verdict = CheckpointVerdict::FAILED, .saves = 0, .line = "[Save] 00.31: run failed: not saved"}}, + {.name = "save step skipped while testing", .input = {.phase = "testing", .steps = SAVE_STEPS}, + .expectation = {.mode = StorySaveMode::NONE, .saves = 0, .line = "[Save] save step skipped: save mode none"}}, {.name = "save step skipped while verifying", .input = {.phase = "verification", .steps = SAVE_STEPS}, .expectation = {.mode = StorySaveMode::AFTER_VERIFICATION, .saves = 1, .line = "[Save] save step skipped: save mode after_verification"}}, {.name = "save step saves in reproduction", .input = {.phase = "reproduction", .steps = SAVE_STEPS}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h index 1e00c6840d..dfc22dd35b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -51,7 +51,7 @@ namespace Pokemon{ // How a game does its story steps: an interface with no data. run() is the // game's: it does the step's kind its own way (FRLG and BDSP bind kinds and -// variants to actions in a table), and returns unsupported_step() for a +// action names to handlers in a table), and returns unsupported_step() for a // kind it has no way of doing. class StoryStepExecutor{ public: @@ -62,7 +62,10 @@ class StoryStepExecutor{ // who can see us again, the row's own settings). Does nothing by default. virtual void begin_attempt(const StoryCheckpoint& data); - // Does `step`, from the run so far. + // Does `step`, from the run so far. A SAVE step must save only when + // the run's save mode allows a save part-way (PER_CHECKPOINT): nothing + // here knows the mode. The story engine's own SAVE action does this + // for a game on the engine. virtual Outcome run(const StoryStep& step, RunState& state) = 0; // Whether the condition named in a step's skip_if holds: by default, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h index 04ad331908..c06b0f52c5 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h @@ -3,8 +3,8 @@ * From: https://github.com/PokemonAutomation/ * * When an AutoStory run may save the game. A run's own verdict can be - * wrong (FRLG 00.31, 2026-11-10: a warp leg confirmed B3F while still on - * B4F), and a save made then overwrites the only good one. So a segment + * wrong (a warp confirmed on the next floor while the player is still on + * the one before), and a save made then overwrites the only good one. So a segment * under test never saves, a verified one saves once at its end, and only * a playthrough of verified segments saves at each checkpoint. * diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h index 2e43aa8118..a3670b8c6c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -32,7 +32,7 @@ enum class StoryStepKind{ SHOP, // `items` from a shop SAVE, // save the game where the player stands READY, // before a big battle: items, and the nurse at `target` if they can't - GAME, // a step only this game has, named by `variant` + GAME, // a step only this game has, named by `action` }; // Returns the readable string representation of a story step kind. diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp index c1217c26fd..5f401eebc5 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -51,7 +51,8 @@ std::string story_checkpoint_label(const StoryCheckpoint& checkpoint){ StoryVerifyOptions::StoryVerifyOptions() : GroupOption( - "Verify Mode: run the start checkpoint (also the end) from its save several times, never saving at its end", + "Verify Mode: run the start checkpoint (also the end) from its save several times. " + "Only with Save set to After verification does the last run save at its end, when every run passed", LockMode::LOCK_WHILE_RUNNING, EnableMode::DEFAULT_DISABLED ) @@ -108,8 +109,9 @@ StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints, const ) , SAVE_MODE( "Save:
When the run saves the game. A failed run never saves. " - "None keeps the save the run started from; After verification saves once at the end, after the checkpoint " - "passed 2-3 times; Each checkpoint is for a playthrough of verified checkpoints.", + "None keeps the save the run started from. After verification saves once, at the end of a run that passed " + "(in Verify Mode, at the end of the last run, when every run passed). Each checkpoint saves after each " + "checkpoint that passed, for a playthrough of verified checkpoints.", StorySaveMode_Database(), LockMode::LOCK_WHILE_RUNNING, StorySaveMode::NONE diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h index 178985d2f0..fb8a1b704c 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -44,9 +44,10 @@ std::string story_checkpoint_label(const StoryCheckpoint& checkpoint); // Verify mode, off by default (verify_checkpoint()): the start checkpoint -// RUNS times from its save, never saving at its end; verified when at -// least PASSES pass. For a battle that has lost twice or more, given its -// own checkpoint saved right before it. +// RUNS times from its save; verified when at least PASSES pass. Only the +// last run may save, at its end, when SAVE_MODE is After verification +// and every run passed. For a battle that has lost twice or more, given +// its own checkpoint saved right before it. class StoryVerifyOptions : public GroupOption{ public: StoryVerifyOptions(); From 8cd38a88d719fa403b2db0227b9beb7d33d5e382 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 3/7] AutoStory engine: drop the unused StoryPoseTraits::from_declared() Declared poses reach the run as the event layer's pose; a zone's spot and heading are not carried until a game has a position reader. --- .../Pokemon/AutoStory/Engine/MIGRATION.md | 6 +++--- .../Engine/Pokemon_StoryPoseConcept.h | 19 ++++++++----------- .../AutoStory/Engine/Pokemon_ZonePose.h | 3 --- 3 files changed, 11 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/MIGRATION.md b/SerialPrograms/Source/Pokemon/AutoStory/Engine/MIGRATION.md index c2c674c1bb..eef09ecdc4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/MIGRATION.md +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/MIGRATION.md @@ -69,13 +69,13 @@ Each move deletes that game's executor; the last one deletes `StoryStepExecutor` readers. - **PLZA** (ZonePose, in the engine with its instantiations and `observed_state()`): a declared pose (`"start"`, a step's `"declared_after"`) is a place, `{"place": "HotelZ"}` with an - optional `"spot"` and `"heading"` (`ZoneDeclared`, read by - `StoryPoseTraits::from_declared()`). Walks are `TIMED_LEGS` args; tile args fail + optional `"spot"` and `"heading"` (`ZoneDeclared`). The run keeps only the place, as a map + with no tiles; spot and heading wait for a position reader. Walks are `TIMED_LEGS` args; tile args fail the lint. Turns are `stick()` after the camera recenter; the minimap arrow is the `"heading"` reading. A new pose type: a struct with `pose_matches` / `pose_text`, a `StoryPoseTraits` specialization -(`TILE_MOVES`, `Declared`, `from_declared()`), and an explicit instantiation line in each engine +(`TILE_MOVES`, `Declared`), and an explicit instantiation line in each engine `.cpp`. ## Moves in shared code when the last executor goes diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h index 653e881f2d..6969ff5290 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h @@ -6,7 +6,7 @@ * off the game is a target, a line of text for the log, and its traits * (StoryPoseTraits): whether the player moves tile by tile, and which kind * of declared pose (Types/Pokemon_DeclaredPose.h) a checkpoint declares - * for it (its start, a step's end) and how that reads as this type. The + * for it (its start, a step's end). The * tile games (FRLG, BDSP) use GridPose; a game that moves freely brings * its own type (PLZA: ZonePose, a zone until it has a position reader). * @@ -37,8 +37,11 @@ namespace Pokemon{ // The kind of pose a checkpoint of this game declares in its JSON // ("start", a step's "declared_after"). The lint fails a // checkpoint that declares the other kind (check_declared()). -// static PoseType from_declared(const Declared& declared); -// That declared pose as this type. +// +// A declared pose reaches the run as the event layer's pose +// (grid_pose_of() in Pokemon_StoryStepExecutor.h): a zone's place reads +// as a map with no tiles, and its spot and heading are not carried. They +// wait for a game with a position reader to compare them against. template struct StoryPoseTraits; @@ -47,22 +50,16 @@ template <> struct StoryPoseTraits{ static constexpr bool TILE_MOVES = true; using Declared = TileDeclared; - static GridPose from_declared(const TileDeclared& declared){ - return GridPose{.map = declared.map, .tiles = declared.tiles, .facing = declared.facing}; - } }; // A pose the engine can carry: pose_matches(actual, target) and // pose_text(pose), found by argument-dependent lookup, and its traits. template -concept StoryPose = std::copyable && requires( - const PoseType& actual, const PoseType& target, - const typename StoryPoseTraits::Declared& declared -){ +concept StoryPose = std::copyable && requires(const PoseType& actual, const PoseType& target){ { pose_matches(actual, target) } -> std::convertible_to; { pose_text(actual) } -> std::convertible_to; { StoryPoseTraits::TILE_MOVES } -> std::convertible_to; - { StoryPoseTraits::from_declared(declared) } -> std::same_as; + typename StoryPoseTraits::Declared; }; // Whether `declared` is the kind of pose a game of `PoseType` declares. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h index 2931604251..13993e1ef5 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h @@ -42,9 +42,6 @@ template <> struct StoryPoseTraits{ static constexpr bool TILE_MOVES = false; using Declared = ZoneDeclared; - static ZonePose from_declared(const ZoneDeclared& declared){ - return ZonePose{.zone = declared.place}; - } }; From 0825ffb67703a5310948fc648b60fbc072927be0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 4/7] AutoStory: tell INTEGER_ROWS from TIMED_LEGS; assert one arg type per value INTEGER_ROWS stays: FRLG's foe_threats and BDSP's avoid args use it. --- .../Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h index 8e47cbbbed..f1a9fb5d50 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h @@ -75,9 +75,10 @@ using StoryArgValue = std::variant< std::vector, // LEGS std::vector, // WORDS std::vector, // ITEMS - std::vector>, // INTEGER_ROWS: [[0, 4500], [90, 0]] - std::vector // TIMED_LEGS: [[0, 4500], [90, 1200]] + std::vector>, // INTEGER_ROWS: rows of any length, [[12, 7], [3, 9, 1], []] + std::vector // TIMED_LEGS: [turn degrees, ms] pairs, [[0, 4500], [90, 1200]] >; +static_assert(std::variant_size_v == (size_t)StoryArgType::TIMED_LEGS + 1, "one StoryArgType per StoryArgValue type"); // A step's arguments by key. using StoryActionArgs = std::map>; From c4a58f79c43372c96f01ab1e5bef28052e6f3b65 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 5/7] AutoStory story files: check reload_when_chained in a user's run too A user's run skips dev-only rows, so the row a reload follows there must autosave as well. --- .../AutoStory/Data/Pokemon_StoryFiles.cpp | 28 +++++++++++++---- .../AutoStory/Data/Pokemon_StoryFiles.h | 30 ++++++++++++++----- .../Data/Pokemon_StoryFiles_Tests.cpp | 18 +++++++++++ 3 files changed, 63 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp index cb1824b759..b7b108c311 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp @@ -61,19 +61,35 @@ void check_in_story_order( } } +namespace{ + +// Throws ParseException naming `source` unless `previous` ends on the +// game's autosave in `rows`; `run` says in whose run ("" or " in a +// user's run"). +void check_reload_after( + std::optional previous, const StoryRows& rows, std::string_view run, std::string_view source +){ + if (!previous || !rows.autosaves.contains(*previous)){ + throw ParseException(std::format( + "{}: reload_when_chained after a checkpoint that does not end on the game's autosave{}: the reload would load an older save", + source, run + )); + } +} + +} // namespace + void add_story_row( std::string_view id, const StoryRowExecution& execution, RowSave start, - std::optional previous_id, std::string_view source, StoryRows& rows + const PreviousRows& previous, std::string_view source, StoryRows& rows ){ if (execution.reload != StoryReload::NEVER){ if (start == RowSave::WITHOUT_SAVE){ throw ParseException(std::format("{}: reload_when_chained on a checkpoint with no save to reload", source)); } - if (!previous_id || !rows.autosaves.contains(*previous_id)){ - throw ParseException(std::format( - "{}: reload_when_chained after a checkpoint that does not end on the game's autosave: the reload would load an older save", - source - )); + check_reload_after(previous.in_dev_run, rows, "", source); + if (!execution.dev_only && previous.in_user_run != previous.in_dev_run){ + check_reload_after(previous.in_user_run, rows, " in a user's run", source); } rows.reload_when_chained.emplace(id); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h index 7b423becd6..f6d2b1da3a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h @@ -121,13 +121,21 @@ enum class RowSave{ WITHOUT_SAVE, // a new game }; +// The rows a row follows in play: in a developer's run, and in a user's, +// which skips the dev-only rows. None for the first row. +struct PreviousRows{ + std::optional in_dev_run; + std::optional in_user_run; +}; + // Adds row `id` to the sets of `rows`. Throws ParseException naming -// `source` when it reloads and starts WITHOUT_SAVE or the row before it, -// `previous_id`, does not end on the game's autosave: a reload loads the -// last save, which must be that autosave. +// `source` when it reloads and starts WITHOUT_SAVE or a row it follows +// (`previous`: in a developer's run; and in a user's, unless it is +// dev-only itself) does not end on the game's autosave: a reload loads +// the last save, which must be that autosave. void add_story_row( std::string_view id, const StoryRowExecution& execution, RowSave start, - std::optional previous_id, std::string_view source, StoryRows& rows + const PreviousRows& previous, std::string_view source, StoryRows& rows ); // The dev file `dev`'s row, in place of the built-in file `builtin_name`: @@ -182,15 +190,23 @@ StoryData load_story_data( return reader.plays_before(a.row.checkpoint, b.row.checkpoint); }); } - // A reload loads the save the row before it in play ends on. + // A reload loads the save the row before it in play ends on, in a + // developer's run and in a user's. + std::optional last_user_row; for (auto& [row, source] : rows){ const bool new_game = reader.starts_without_save && reader.starts_without_save(row.checkpoint); + const detail::PreviousRows previous{ + .in_dev_run = data.checkpoints.empty() ? std::nullopt : std::optional(data.checkpoints.back().id), + .in_user_run = last_user_row ? std::optional(data.checkpoints[*last_user_row].id) : std::nullopt, + }; detail::add_story_row( row.checkpoint.id, row.execution, new_game ? detail::RowSave::WITHOUT_SAVE : detail::RowSave::FROM_SAVE, - data.checkpoints.empty() ? std::nullopt : std::optional(data.checkpoints.back().id), - source, data + previous, source, data ); + if (!row.execution.dev_only){ + last_user_row = data.checkpoints.size(); + } data.checkpoints.push_back(std::move(row.checkpoint)); } return data; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp index 5ba2235da8..8b1d06bb5a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp @@ -184,6 +184,24 @@ const LoadCase LOAD_CASES[] = { .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "menu"})")}, ROW_1}}, .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave"}, }, + { + .name = "reload_when_chained after a dev-only autosave row, the user's row before it not autosaving, fails", + .input = {.builtin = { + {"test-01.00.plan", file_text("01.00", R"({"save": "menu"})")}, + {"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")}, + ROW_1, + }}, + .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave in a user's run"}, + }, + { + .name = "reload_when_chained after a dev-only row, both rows before it autosaving", + .input = {.builtin = { + ROW_0, + {"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")}, + ROW_1, + }}, + .expectation = {.summary = "rows 01.00 01.005 01.01 | titles Row Row Row | autosave 01.00 01.005 | chained 01.01 | always | dev_only 01.005 | dev "}, + }, { .name = "reload_when_chained on the first row fails", .input = {.builtin = {ROW_1}}, From 644442dbbe676e2a4536d7c06daebdf0a077c4c5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:54 -0800 Subject: [PATCH 6/7] AutoStory failure classes: function-local table, checked lookup story_failure_class_info() throws for a class with no row in its place, and a test checks every class has one. --- .../AutoStory/Pokemon_StoryFailureClasses.cpp | 397 ++++++++++-------- .../AutoStory/Pokemon_StoryFailureClasses.h | 4 +- .../Pokemon_StoryFailureClasses_Tests.cpp | 15 + 3 files changed, 239 insertions(+), 177 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp index ec7b5f582d..02e34cea33 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include "Common/Cpp/Exceptions.h" #include "Pokemon_StoryFailureClasses.h" namespace PokemonAutomation{ @@ -20,186 +22,222 @@ constexpr std::string_view TAG_PREFIX = "class="; using C = StoryFailureClass; using R = StoryFailureClassInfo::Retry; -const std::vector CLASSES{ - // The run and the console. - { - C::GAME_NOT_RUNNING, "game_not_running", - "the Switch HOME menu shows instead of the game", - "the HOME menu read at a step's start or after a failure", - {}, {"game_not_running"}, R::STOP, - }, - { - C::LAUNCH_FAILED, "launch_failed", - "getting from HOME to the game's overworld failed", - "the launch driver: no game tile, a screen that ignores its press, no overworld in time", - {}, {"launch_failed"}, R::STOP, - }, - { - C::WRONG_START, "wrong_start", - "the game is not at the checkpoint's start: another save, an older one, another place", - "the checkpoint's start checks and the preflight", - {}, {"start_failed", "wrong_save", "precondition_failed"}, R::STOP, - }, - { - C::RELOAD_FAILED, "reload_failed", - "reloading the checkpoint's save failed", - "the game's reload hook", - {}, {"reload_failed"}, R::STOP, - }, - { - C::SAVE_FAILED, "save_failed", - "saving at the checkpoint's end failed", - "the game's save hook", - {}, {"save_failed"}, R::RELOAD, - }, - { - C::STORY_ERROR, "story_error", - "the story's data or code is wrong: a step, range or action the program cannot run", - "the engine's lint and lookups, before or as a step starts", - {}, +// The run and the console. +std::vector run_rows(){ + return { { - "unsupported_step", "unknown_checkpoint", "bad_range", "empty_segment", - "bad_verify_policy", "lint_failed", "no_save_hook", "console_only", + C::GAME_NOT_RUNNING, "game_not_running", + "the Switch HOME menu shows instead of the game", + "the HOME menu read at a step's start or after a failure", + {}, {"game_not_running"}, R::STOP, }, - R::STOP, - }, + { + C::LAUNCH_FAILED, "launch_failed", + "getting from HOME to the game's overworld failed", + "the launch driver: no game tile, a screen that ignores its press, no overworld in time", + {}, {"launch_failed"}, R::STOP, + }, + { + C::WRONG_START, "wrong_start", + "the game is not at the checkpoint's start: another save, an older one, another place", + "the checkpoint's start checks and the preflight", + {}, {"start_failed", "wrong_save", "precondition_failed"}, R::STOP, + }, + { + C::RELOAD_FAILED, "reload_failed", + "reloading the checkpoint's save failed", + "the game's reload hook", + {}, {"reload_failed"}, R::STOP, + }, + { + C::SAVE_FAILED, "save_failed", + "saving at the checkpoint's end failed", + "the game's save hook", + {}, {"save_failed"}, R::RELOAD, + }, + { + C::STORY_ERROR, "story_error", + "the story's data or code is wrong: a step, range or action the program cannot run", + "the engine's lint and lookups, before or as a step starts", + {}, + { + "unsupported_step", "unknown_checkpoint", "bad_range", "empty_segment", + "bad_verify_policy", "lint_failed", "no_save_hook", "console_only", + }, + R::STOP, + }, + + }; +} - // Walking. - { - C::LOST_TAP, "lost_tap", - "a tap the game drops", - "the walker reads the player where the tap started", - {FaultClass::LOST_TAP}, {}, R::RETRY_STEP, - }, - { - C::UNSEEN_STEP, "unseen_step", - "a step tap that moved the player, read as not moved", - "the walker finds the player a tile past where it read", - {FaultClass::UNSEEN_STEP}, {}, R::RETRY_STEP, - }, - { - C::WALK_SHORT, "walk_short", - "a walk or hold ended short of its tile", - "the walker's position check at a wall or landmark", - {}, {}, R::RETRY_STEP, - }, - { - C::BLOCKED, "blocked", - "something on the way stops the walk: a person, a wall the map does not have", - "the walker's progress check: no tile gained", - {}, {}, R::RETRY_STEP, - }, - { - C::MOUNT_LOST, "mount_lost", - "off the Bicycle (or another mount) at a leg that rides", - "the walker's tiles per tap", - {FaultClass::MOUNT_LOST}, {}, R::RETRY_STEP, - }, - { - C::POSE_LOST, "pose_lost", - "where the player is or faces is unknown or not what the map says", - "the localizer: no pose, another map, another facing", - {}, {}, R::RELOAD, - }, +// Walking. +std::vector walk_rows(){ + return { + { + C::LOST_TAP, "lost_tap", + "a tap the game drops", + "the walker reads the player where the tap started", + {FaultClass::LOST_TAP}, {}, R::RETRY_STEP, + }, + { + C::UNSEEN_STEP, "unseen_step", + "a step tap that moved the player, read as not moved", + "the walker finds the player a tile past where it read", + {FaultClass::UNSEEN_STEP}, {}, R::RETRY_STEP, + }, + { + C::WALK_SHORT, "walk_short", + "a walk or hold ended short of its tile", + "the walker's position check at a wall or landmark", + {}, {}, R::RETRY_STEP, + }, + { + C::BLOCKED, "blocked", + "something on the way stops the walk: a person, a wall the map does not have", + "the walker's progress check: no tile gained", + {}, {}, R::RETRY_STEP, + }, + { + C::MOUNT_LOST, "mount_lost", + "off the Bicycle (or another mount) at a leg that rides", + "the walker's tiles per tap", + {FaultClass::MOUNT_LOST}, {}, R::RETRY_STEP, + }, + { + C::POSE_LOST, "pose_lost", + "where the player is or faces is unknown or not what the map says", + "the localizer: no pose, another map, another facing", + {}, {}, R::RELOAD, + }, - // Warps and fades. - { - C::WARP_NO_OP, "warp_no_op", - "a step onto a warp shows the fade's black but does not warp", - "the map or tile after the fade is the one before it", - {FaultClass::WARP_NO_OP}, {}, R::RETRY_STEP, - }, - { - C::LATE_FADE, "late_fade", - "a warp's fade shows late or is missed", - "the fade watcher: the warp unconfirmed, the player on a map the walk did not plan", - {FaultClass::LATE_FADE}, {}, R::RETRY_STEP, - }, - { - C::SLOW_FADE_IN, "slow_fade_in", - "a warp's fade-in runs long: a move right after it goes nowhere", - "the first move after a fade does not move the player", - {FaultClass::SLOW_FADE_IN}, {}, R::RETRY_STEP, - }, - { - C::DARK_MAP, "dark_map", - "a dark map (a cave without Flash) the readers cannot see", - "the floor reads dim; the walker's and the scene's reads fail there", - {FaultClass::DARK_CAVE}, {}, R::STOP, - }, + }; +} - // Scenes, talks and battles. - { - C::SCENE_END_POSE, "scene_end_pose", - "a step whose end the game sets leaves the player on a tile next to the expected one", - "the next walk starts or ends a tile off", - {FaultClass::SCENE_END_POSE}, {}, R::RETRY_STEP, - }, - { - C::SCENE_EARLY, "scene_early", - "a scene starts on the last tiles of the walk before it", - "the walk is interrupted by the scene's dialogue", - {FaultClass::SCENE_EARLY}, {}, R::RETRY_STEP, - }, - { - C::BATTLE_OPENING, "battle_opening", - "a battle's opening is still playing when a step starts", - "the step's first read is not the overworld or battle menu it expects", - {FaultClass::BATTLE_OPENING}, {}, R::RETRY_STEP, - }, - { - C::WILD_BATTLES, "wild_battles", - "more wild battles than a clean run meets", - "the interrupt handler clears each; too many in a step fail it", - {FaultClass::WILD_BATTLES}, {"too_many_interrupts"}, R::RETRY_STEP, - }, - { - C::INTERRUPT_FAILED, "interrupt_failed", - "something interrupted a step and was not cleared", - "the interrupt handler: no handler, a failed clear, the screen not settled", - {}, {"unhandled_interrupt", "interrupt_failed", "interrupt_unsettled", "interrupted"}, R::RELOAD, - }, - { - C::SCREEN_UNREAD, "screen_unread", - "a screen the step waits for (dialogue, banner, overworld, prompt) is not seen", - "the step's detector times out", - {}, {"talk_no_text", "mash_no_overworld"}, R::RELOAD, - }, - { - C::MENU_FAILED, "menu_failed", - "a menu action (mart, PC, item, TM, Fly) did not do what it was to", - "the menu's readers: the item, count or choice not as planned", - {}, {}, R::RELOAD, - }, - { - C::BATTLE_LOST, "battle_lost", - "a battle lost or not won: a blackout", - "the battle's end screen or the blackout's heal spot", - {}, {}, R::RELOAD, - }, - { - C::STATE_CHECK_FAILED, "state_check_failed", - "a check of the game's state failed: an event's expects, the checkpoint's end", - "the event's expects and requires, the checkpoint's end and postconditions", - {}, {"expect_failed", "require_failed", "end_failed", "postconditions_failed"}, R::RELOAD, - }, - { - C::OPERATION_FAILED, "operation_failed", - "a game's action threw, with no class of its own", - "an OperationFailedException out of a step", - {}, {"operation_failed"}, R::RELOAD, - }, - { - C::SIM_MISMATCH, "sim_mismatch", - "a simulated run left the story: the sim and the table disagree", - "the story sim's end checks (sim runs only)", - {}, {}, R::STOP, - }, -}; +// Warps and fades. +std::vector warp_rows(){ + return { + { + C::WARP_NO_OP, "warp_no_op", + "a step onto a warp shows the fade's black but does not warp", + "the map or tile after the fade is the one before it", + {FaultClass::WARP_NO_OP}, {}, R::RETRY_STEP, + }, + { + C::LATE_FADE, "late_fade", + "a warp's fade shows late or is missed", + "the fade watcher: the warp unconfirmed, the player on a map the walk did not plan", + {FaultClass::LATE_FADE}, {}, R::RETRY_STEP, + }, + { + C::SLOW_FADE_IN, "slow_fade_in", + "a warp's fade-in runs long: a move right after it goes nowhere", + "the first move after a fade does not move the player", + {FaultClass::SLOW_FADE_IN}, {}, R::RETRY_STEP, + }, + { + C::DARK_MAP, "dark_map", + "a dark map (a cave without Flash) the readers cannot see", + "the floor reads dim; the walker's and the scene's reads fail there", + {FaultClass::DARK_CAVE}, {}, R::STOP, + }, + + }; +} + +// Scenes, talks and battles. +std::vector scene_rows(){ + return { + { + C::SCENE_END_POSE, "scene_end_pose", + "a step whose end the game sets leaves the player on a tile next to the expected one", + "the next walk starts or ends a tile off", + {FaultClass::SCENE_END_POSE}, {}, R::RETRY_STEP, + }, + { + C::SCENE_EARLY, "scene_early", + "a scene starts on the last tiles of the walk before it", + "the walk is interrupted by the scene's dialogue", + {FaultClass::SCENE_EARLY}, {}, R::RETRY_STEP, + }, + { + C::BATTLE_OPENING, "battle_opening", + "a battle's opening is still playing when a step starts", + "the step's first read is not the overworld or battle menu it expects", + {FaultClass::BATTLE_OPENING}, {}, R::RETRY_STEP, + }, + { + C::WILD_BATTLES, "wild_battles", + "more wild battles than a clean run meets", + "the interrupt handler clears each; too many in a step fail it", + {FaultClass::WILD_BATTLES}, {"too_many_interrupts"}, R::RETRY_STEP, + }, + }; +} + +// Interrupts, reads, menus and checks. +std::vector check_rows(){ + return { + { + C::INTERRUPT_FAILED, "interrupt_failed", + "something interrupted a step and was not cleared", + "the interrupt handler: no handler, a failed clear, the screen not settled", + {}, {"unhandled_interrupt", "interrupt_failed", "interrupt_unsettled", "interrupted"}, R::RELOAD, + }, + { + C::SCREEN_UNREAD, "screen_unread", + "a screen the step waits for (dialogue, banner, overworld, prompt) is not seen", + "the step's detector times out", + {}, {"talk_no_text", "mash_no_overworld"}, R::RELOAD, + }, + { + C::MENU_FAILED, "menu_failed", + "a menu action (mart, PC, item, TM, Fly) did not do what it was to", + "the menu's readers: the item, count or choice not as planned", + {}, {}, R::RELOAD, + }, + { + C::BATTLE_LOST, "battle_lost", + "a battle lost or not won: a blackout", + "the battle's end screen or the blackout's heal spot", + {}, {}, R::RELOAD, + }, + { + C::STATE_CHECK_FAILED, "state_check_failed", + "a check of the game's state failed: an event's expects, the checkpoint's end", + "the event's expects and requires, the checkpoint's end and postconditions", + {}, {"expect_failed", "require_failed", "end_failed", "postconditions_failed"}, R::RELOAD, + }, + { + C::OPERATION_FAILED, "operation_failed", + "a game's action threw, with no class of its own", + "an OperationFailedException out of a step", + {}, {"operation_failed"}, R::RELOAD, + }, + { + C::SIM_MISMATCH, "sim_mismatch", + "a simulated run left the story: the sim and the table disagree", + "the story sim's end checks (sim runs only)", + {}, {}, R::STOP, + }, + }; +} + +// Every class, in the enum's order. Function-local, so a static +// initializer in another file may read it. +const std::vector& class_rows(){ + static const std::vector CLASSES = []{ + std::vector rows; + for (std::vector group : {run_rows(), walk_rows(), warp_rows(), scene_rows(), check_rows()}){ + rows.insert(rows.end(), std::make_move_iterator(group.begin()), std::make_move_iterator(group.end())); + } + return rows; + }(); + return CLASSES; +} // The class whose id is `id`; nothing for an unknown id. std::optional find_story_failure_class(std::string_view id){ - for (const StoryFailureClassInfo& info : CLASSES){ + for (const StoryFailureClassInfo& info : class_rows()){ if (info.id == id){ return info.failure_class; } @@ -211,15 +249,22 @@ std::optional find_story_failure_class(std::string_view id){ const std::vector& story_failure_classes(){ - return CLASSES; + return class_rows(); } const StoryFailureClassInfo& story_failure_class_info(StoryFailureClass failure_class){ - return CLASSES[static_cast(failure_class)]; + const std::vector& classes = class_rows(); + const size_t index = static_cast(failure_class); + if (index >= classes.size() || classes[index].failure_class != failure_class){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, std::format("Story failure class {} has no row in its place.", index) + ); + } + return classes[index]; } std::optional story_failure_class_of(FaultClass fault){ - for (const StoryFailureClassInfo& info : CLASSES){ + for (const StoryFailureClassInfo& info : class_rows()){ if (std::ranges::find(info.injected_by, fault) != info.injected_by.end()){ return info.failure_class; } @@ -228,7 +273,7 @@ std::optional story_failure_class_of(FaultClass fault){ } std::optional story_failure_class_of_outcome(std::string_view failure){ - for (const StoryFailureClassInfo& info : CLASSES){ + for (const StoryFailureClassInfo& info : class_rows()){ if (std::ranges::find(info.outcomes, failure) != info.outcomes.end()){ return info.failure_class; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h index 4cf5f9003d..5537ef88df 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h @@ -54,6 +54,7 @@ enum class StoryFailureClass{ BATTLE_LOST, STATE_CHECK_FAILED, OPERATION_FAILED, + // The last: the tests check that every class up to it has a row. SIM_MISMATCH, }; @@ -87,7 +88,8 @@ struct StoryFailureClassInfo{ // Every class, in the enum's order. const std::vector& story_failure_classes(); -// The row of `failure_class`. +// The row of `failure_class`. Throws InternalProgramError when the list +// has no row for it in the enum's place. const StoryFailureClassInfo& story_failure_class_info(StoryFailureClass failure_class); // The class a sim fault injects. Every FaultClass has one (the tests diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp index df17c2aefd..07fbd66ff3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon_StoryFailureClasses.h" @@ -151,6 +152,19 @@ UnitTestResult rows_in_enum_order(){ return true; } +UnitTestResult every_class_has_a_row(){ + const size_t count = static_cast(StoryFailureClass::SIM_MISMATCH) + 1; + if (story_failure_classes().size() != count){ + return std::format("{} rows for {} classes", story_failure_classes().size(), count); + } + try{ + story_failure_class_info(static_cast(count)); + }catch (const InternalProgramError&){ + return true; + } + return std::string("a class past the last row did not throw"); +} + UnitTestResult every_sim_fault_maps_to_one_class(){ for (FaultClass fault : fault_classes()){ size_t rows = 0; @@ -236,6 +250,7 @@ UnitTestResult no_class_without_a_tag(){ const ListCheckTestCase LIST_CHECKS[] = { {.name = "rows in the enum's order", .input = {rows_in_enum_order}, .expectation = {"story_failure_class_info() indexes by the enum"}}, + {.name = "every class has a row", .input = {every_class_has_a_row}, .expectation = {"no class reads past the table"}}, {.name = "every sim fault maps to one class", .input = {every_sim_fault_maps_to_one_class}, .expectation = {"the sweeps' faults all have a class"}}, {.name = "no outcome name in two classes", .input = {no_outcome_in_two_classes}, .expectation = {"a failure name has one class"}}, {.name = "ids round-trip", .input = {ids_round_trip}, .expectation = {"each id is unique and its tag alone reads back"}}, From a80d9f3d71567cc6bd1d3a7f34142ad5d7b96c25 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 14:43:55 -0800 Subject: [PATCH 7/7] ScreenEvents: assert the event count; ScreenEventLog tests Covers the first frame's rises, rose/fell edges, the capacity drop and describe(). --- .../ScreenEvents/ScreenEventTypes.h | 1 + .../ScreenEvents/ScreenEvents_Tests.cpp | 91 +++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h index 73b4b12a77..e9d05d5052 100644 --- a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h @@ -36,6 +36,7 @@ enum class ScreenEvent : uint8_t{ }; // How many ScreenEvent values there are. constexpr size_t SCREEN_EVENT_COUNT = 11; +static_assert((size_t)ScreenEvent::SWITCH_HOME_MENU + 1 == SCREEN_EVENT_COUNT, "SWITCH_HOME_MENU is the last ScreenEvent"); // "dialog box", for the log. std::string screen_event_name(ScreenEvent event); diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp index 14a1483558..04720d2aa6 100644 --- a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp @@ -11,8 +11,10 @@ #include #include #include +#include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ScreenEventLog.h" #include "ScreenEventTypes.h" #include "ScreenFades.h" #include "ScreenEvents.h" @@ -179,10 +181,99 @@ const ScreenEventsCase SCREEN_EVENTS_CASES[] = { }, }; +namespace{ + +// A stream of frames into a ScreenEventLog, and its describe() text. +struct ScreenEventLogCase{ + struct Frame{ + int ms; + std::vector events; + }; + struct Input{ + size_t capacity; + std::vector frames; + }; + struct Expectation{ + // describe() of the log, times from the first frame. + std::string text; + size_t dropped; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_ScreenEventLog : public UnitTest{ +public: + explicit Test_ScreenEventLog(ScreenEventLogCase test_case) + : UnitTest(std::format("CommonTools::ScreenEventLog - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + ScreenEventLog log(m_case.input.capacity); + const WallClock origin = current_time(); + for (const ScreenEventLogCase::Frame& frame : m_case.input.frames){ + ScreenEvents events; + for (ScreenEvent event : frame.events){ + events.set(event, true); + } + log.record(events, origin + Milliseconds(frame.ms)); + } + if (log.dropped() != m_case.expectation.dropped){ + return std::format("dropped(): expected {}, got {}", m_case.expectation.dropped, log.dropped()); + } + return expect_equal("describe()", describe(log, origin), m_case.expectation.text); + } + +private: + ScreenEventLogCase m_case; +}; + +} // namespace + +const ScreenEventLogCase SCREEN_EVENT_LOG_CASES[] = { + { + .name = "no frames", + .input = {.capacity = 8, .frames = {}}, + .expectation = {.text = "no changes", .dropped = 0}, + }, + { + .name = "the first frame's events all rise", + .input = {.capacity = 8, .frames = {{.ms = 0, .events = {ScreenEvent::DIALOG_BOX, ScreenEvent::SCREEN_STILL}}}}, + .expectation = {.text = "+0 ms dialog box rose\n+0 ms screen still rose\n", .dropped = 0}, + }, + { + .name = "only changes are kept, rising and falling", + .input = {.capacity = 8, .frames = { + {.ms = 0, .events = {ScreenEvent::PLAYER_CAN_MOVE}}, + {.ms = 100, .events = {ScreenEvent::PLAYER_CAN_MOVE}}, + {.ms = 200, .events = {ScreenEvent::FADE_BLACK}}, + {.ms = 900, .events = {}}, + }}, + .expectation = { + .text = "+0 ms player can move rose\n+200 ms black fade rose\n+200 ms player can move fell\n+900 ms black fade fell\n", + .dropped = 0, + }, + }, + { + .name = "the oldest changes drop past the capacity", + .input = {.capacity = 2, .frames = { + {.ms = 0, .events = {ScreenEvent::DIALOG_BOX}}, + {.ms = 100, .events = {}}, + {.ms = 200, .events = {ScreenEvent::CHOICE_BOX}}, + }}, + .expectation = {.text = "(1 older changes dropped)\n+100 ms dialog box fell\n+200 ms choice box rose\n", .dropped = 1}, + }, +}; + void add_tests_ScreenEvents(UnitTestDatabase& database){ for (const auto& item : SCREEN_EVENTS_CASES){ database.add(item); } + for (const auto& item : SCREEN_EVENT_LOG_CASES){ + database.add(item); + } }