Files
Dreierpack-Manager/tests/modern_engine_bridge_probe.cpp
T

466 lines
55 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
// Opt-in private-data probe. Never registered as an unconditional CTest.
#include "modern/ui/engine_bridge.hpp"
#include "modern/app/modern_session.hpp"
#include "modern/content/world_package.hpp"
#include "modern/ui/demo_opening.hpp"
#include "modern/game/national.hpp"
#include <iostream>
#include <algorithm>
#include <set>
using namespace bmh;
using namespace bmh::modern_ui;
int main(int argc, char **argv) {
try {
const std::string mode=argc>1?argv[1]:"";
const std::set<std::string> modes{"prepare","prepare-two","prepare-national","prepare-almanac","inspect","inspect-friendlies","inspect-almanac","verify","verify-lineup","verify-sports","verify-bank","verify-commerce","verify-contracts","verify-calendar","verify-friendlies","verify-national","verify-almanac","verify-shootouts","verify-reports","verify-fixtures","verify-other","verify-rankings","prepare-rankings-archived","verify-create","inspect-coach-identity","prepare-coach-identity","verify-coach-almanac"};
if(argc!=4||!modes.contains(mode))throw std::runtime_error("usage: modern_engine_bridge_probe <prepare[-two|-national|-almanac]|inspect[-friendlies|-almanac]|verify[-lineup|-sports|-bank|-commerce|-contracts|-calendar|-friendlies|-national|-almanac|-shootouts]> <world.obw> <new-output-directory>");
const fs::path world = argv[2], out = argv[3]; fs::create_directories(out);
const auto write = [&](const char *file, const Json &j) { editor::write_atomic(out / file, j.dump(2)); };
if (mode == "prepare-almanac" || std::string(argv[1]) == "prepare-national" || std::string(argv[1]) == "prepare" || std::string(argv[1]) == "prepare-two") {
auto package = modern::open_world_package(world);
content::Mount mount(world, package.classic); modern::set_current_world(package.world);
modern::app::ModernSession session(mount.root(), 17u);
ui::SetupOptions options; options.mode = 3; if(mode=="prepare-almanac") options.world=false; if (std::string(argv[1]) == "prepare-national") options.league = false; options.managers = std::string(argv[1]) == "prepare-two" ? 2 : 1;
ui::ManagerChoice manager; manager.name = "Codex Engine QA"; manager.master_club = 0;
std::string error; ui::CareerInitializationResult result;
if (!session.confirm_manager(options, manager, error)) throw std::runtime_error(error);
if (options.managers == 2) { manager.name = "Codex Opponent QA"; manager.master_club = 1; manager.portrait = 1; if (!session.confirm_manager(options, manager, error)) throw std::runtime_error(error); }
if (!session.finish(result, error)) throw std::runtime_error(error);
if (mode == "prepare-national" || mode == "prepare-almanac") {
uint64_t rev = 0; bool found = false; Json expiry = Json::object(), log = Json::array();
for (int k = 0; k < 200; ++k) {
const auto desk = Json::parse(cli::dump_json(session.ui_read(cli::Json::Object{{"kind","desktop"}},rev)));
if (mode=="prepare-national" && desk.at("meta").at("scope").at("role") == "national") { found = true; break; }
if(mode=="prepare-almanac") {const auto index=Json::parse(cli::dump_json(session.read_almanac(cli::Json::Object{{"kind","index"}})));if(index.value("ok",false)&&index.at("years").size()>=2){found=true;break;}}
const auto &meta = desk.at("meta");
const Json command{{"messageType","command"},{"contractVersion",meta.at("contractVersion")},{"requestId","request:prepare-national-"+std::to_string(k)},{"careerId",meta.at("careerId")},{"expectedRevision",meta.at("stateRevision")},{"owner",{{"managerId",meta.at("scope").at("managerId")}}},{"kind","session.advance"},{"payload",{{"contractExpiry",expiry}}}};
const auto reply = Json::parse(cli::dump_json(session.ui_command(cli::parse_json(command.dump()),rev))); log.push_back(reply);
if (reply.value("messageType","") == "command_result") continue;
if (reply.value("code","") == "decision_pending") { const auto id = reply.at("message").at("args").at("playerId").get<std::string>(); expiry[id]={{"action","release"}}; continue; }
throw std::runtime_error(reply.dump());
}
write("preparation-advance.json",log);
if (!found) throw std::runtime_error("requested fixture not reached through session.advance: "+mode);
}
if (!session.save_game(out / "input.obs", 0, false, error)) throw std::runtime_error(error);
modern::set_current_world(nullptr);
}
if(mode=="prepare-rankings-archived") {
std::string person,league;
{
auto package=modern::open_world_package(world);content::Mount mount(world,package.classic);modern::set_current_world(package.world);
modern::app::ModernSession session(mount.root(),1u,out/"input.obs",false);auto &g=session.state();league=g.world_league_id.at(0);
const auto read=Json::parse(cli::dump_json(session.ui_read(cli::Json::Object{{"kind","player-rankings"},{"leagueId",league},{"scope",0}},0)));
person=read.at("data").at("categories")[0][0].at("player").at("id");
const auto found=std::find(g.world_player_id.begin(),g.world_player_id.end(),person);if(found==g.world_player_id.end())throw std::runtime_error("archive fixture player missing");const auto player=size_t(found-g.world_player_id.begin());
for(auto &slot:g.squad_slots)if((slot&0x0fff)==player)slot=kEmptySlot;
std::string error;if(!session.save_game(out/"archived.obs",0,false,error))throw std::runtime_error(error);
write("synthetic-mutation.json",{{"qa_only",true},{"kind","remove-current-squad-membership"},{"playerId",person},{"archive","unchanged"},{"real_retirement",false}});
}
modern::set_current_world(nullptr);auto fixture=EngineBridge::open(world,out/"archived.obs");const auto bundle=fixture->snapshot(),index=fixture->read({{"kind","report-index"}}),read=fixture->read({{"kind","player-rankings"},{"leagueId",league},{"scope",0}});const auto value=engine_rankings_projection(bundle,index,read,league,0);
if(value.at("categories")[0][0].at("player")!=person||!value.at("categories")[0][0].at("currentTeam").is_null())throw std::runtime_error("archived-only counterexample not retained");write("rankings.json",read);std::cout<<"synthetic archived-only rankings fixture passed\n";return 0;
}
if(mode=="verify-create") {
const auto package=modern::open_world_package(world);Json clubs=Json::array();for(int league=0;league<5;++league)for(const auto &l:package.world->leagues)if(l.index==league&&!l.members.empty())clubs.push_back(l.members.front());
const std::array<std::string,4> names{"Jörg Müller","Zoë García","Alex Berger","Mina Öztürk"};Json cases=Json::array();
for(int count:{1,2,4}) {
Json setup={{"duration",5},{"difficulty",3},{"players",count},{"mode",3},{"league",true},{"world",true}},managers=Json::array();
for(int i=0;i<count;++i)managers.push_back({{"name",names[size_t(i)]},{"club",clubs.at(size_t(i))},{"portrait",i},{"portrait_style",i%2?"photo":"painted"},{"strength_choice",1}});
auto created=EngineBridge::create(world,setup,managers,17);const auto before=created->snapshot(),opening=created->read({{"kind","opening"}});write(("created-"+std::to_string(count)+".json").c_str(),before);write(("opening-"+std::to_string(count)+".json").c_str(),opening);auto state=engine_opening_projection(before,opening);
if(before.at("session").at("data").at("managers").size()!=size_t(count))throw std::runtime_error("wrong human manager count");
for(int i=0;i<count;++i){const auto &m=before.at("session").at("data").at("managers").at(size_t(i));if(m.at("name")!=names[size_t(i)]||m.at("teamId")!=clubs.at(size_t(i))||m.at("portraitStyle")!=(i%2?"photo":"painted"))throw std::runtime_error("new career manager mapping differs");}
write(("saved-initial-"+std::to_string(count)+".json").c_str(),created->save_copy(out/("initial-"+std::to_string(count)+".obs")));
for(int page=0;page<3;++page){const auto error=advance_opening_presentation(state["opening_flow"],"next");if(!error.empty())throw std::runtime_error(error);}
if(!advance_opening_presentation(state["opening_flow"],"skip").empty()||!advance_opening_presentation(state["opening_flow"],"finish").empty())throw std::runtime_error("opening presentation failed");
if(created->snapshot()!=before)throw std::runtime_error("intro presentation modified career");
const auto saved=out/("created-"+std::to_string(count)+".obs");write(("saved-"+std::to_string(count)+".json").c_str(),created->save_copy(saved));created.reset();created=EngineBridge::open(world,saved);
if(created->snapshot().at("session").at("data")!=before.at("session").at("data")||created->read({{"kind","opening"}}).at("data")!=opening.at("data"))throw std::runtime_error("created career lost managers or draw after restart");
cases.push_back({{"managers",count},{"sameManagersAfterReload",true},{"sameDrawAfterReload",true},{"presentationIsReadOnly",true}});created.reset();
}
Json setup={{"duration",5},{"difficulty",3},{"players",1},{"mode",3},{"league",false},{"world",true}},managers={{{"name","National QA"},{"club",clubs[0]},{"portrait",0},{"portrait_style","photo"},{"strength_choice",1}}};
{auto c=EngineBridge::create(world,setup,managers,17);const auto o=c->read({{"kind","opening"}});if(o.at("data").at("enabled")!=false)throw std::runtime_error("national-only created club intro");write("national-only.json",c->snapshot());write("saved-national.json",c->save_copy(out/"national-only.obs"));}
setup["league"]=true;
for(int fault=0;fault<7;++fault){auto bad_setup=setup,bad_managers=managers;if(fault==0){bad_setup["league"]=false;bad_setup["world"]=false;}if(fault==1)bad_setup["mode"]=2;if(fault==2)bad_managers[0]["club"]="club:missing";if(fault==3)bad_managers[0]["name"]="";if(fault==4)bad_managers[0]["portrait"]=12;if(fault==5)bad_managers[0]["strength_choice"]=3;if(fault==6){bad_setup["players"]=2;bad_managers.push_back(bad_managers[0]);bad_managers[1]["portrait"]=1;}
bool rejected=false;try{auto invalid=EngineBridge::create(world,bad_setup,bad_managers,17);}catch(const std::exception&){rejected=true;}if(!rejected||modern::current_world())throw std::runtime_error("invalid creation retained an active session");
}
write("receipt.json",{{"status","passed"},{"cases",cases},{"invalidRequests",7},{"nationalOnly",true}});std::cout<<"real career creation, multiple managers, UTF-8, portrait styles and reload passed\n";return 0;
}
if(mode=="inspect-coach-identity") {
auto package=modern::open_world_package(world);content::Mount mount(world,package.classic);modern::set_current_world(package.world);modern::app::ModernSession session(mount.root(),1u,out/"input.obs",false);
auto &g=session.state();modern::UiContext context;context.manager=0;
const auto before=Json::parse(cli::dump_json(modern::ui_read(g,context,cli::Json::Object{{"kind","session"}})));write("before.json",before);const auto expected=before.at("data").at("managers").at(2);
for(int i=0;i<4;++i)g.manager_records[size_t(i)*0xb0c+0x21c]=i==2?1:0;
modern::national_coach_take_over(g,0,2);
const auto after=Json::parse(cli::dump_json(modern::ui_read(g,context,cli::Json::Object{{"kind","desktop"}})));write("after.json",after);
const auto session_after=Json::parse(cli::dump_json(modern::ui_read(g,context,cli::Json::Object{{"kind","session"}})));write("session-after.json",session_after);
write("observations.json",{{"qa_only_eligibility_flags",true},{"chosenHumanSlot",2},{"expected",expected},{"actual",after.at("data").at("manager")},{"ownerMatches",after.at("meta").at("scope").at("managerId")==expected.at("id")},{"nameMatches",after.at("data").at("manager").at("name")==expected.at("name")}});
const auto records=g.manager_records;const auto repeated=Json::parse(cli::dump_json(modern::ui_read(g,context,cli::Json::Object{{"kind","desktop"}})));if(repeated!=after||g.manager_records!=records)throw std::runtime_error("coach projection changed records");
modern::national_coach_hand_back(g);const auto returned=Json::parse(cli::dump_json(modern::ui_read(g,context,cli::Json::Object{{"kind","session"}})));write("returned.json",returned);
if(after.at("meta").at("scope").at("managerId")!=expected.at("id")||after.at("data").at("manager").at("name")!=expected.at("name")||returned.at("data")!=before.at("data"))throw std::runtime_error("coach identity or handback changed humans");
if(session_after.at("data").at("managers").size()!=4)throw std::runtime_error("waiting human managers disappeared");
modern::set_current_world(nullptr);std::cout<<"coach identity and handback verified\n";return 0;
}
if(mode=="prepare-coach-identity") {
{
auto package=modern::open_world_package(world);content::Mount mount(world,package.classic);modern::set_current_world(package.world);modern::app::ModernSession session(mount.root(),1u,out/"input.obs",false);uint64_t revision=0;Json expiry=Json::object(),log=Json::array();bool found=false;
for(int turn=0;turn<400;++turn) {
auto &g=session.state();if(g.manager_teams.size()==4)for(int i=0;i<4;++i)g.manager_records[size_t(i)*0xb0c+0x21c]=i==2?1:0;
const auto desk=Json::parse(cli::dump_json(session.ui_read(cli::Json::Object{{"kind","desktop"}},revision)));
if(desk.at("meta").at("scope").at("role")=="national") {write("national.json",desk);if(desk.at("data").at("manager").at("id")!="manager:3")throw std::runtime_error("unexpected coach in controlled career");found=true;break;}
const auto &meta=desk.at("meta");const Json command={{"messageType","command"},{"contractVersion",meta.at("contractVersion")},{"requestId","request:coach-advance-"+std::to_string(turn)},{"careerId",meta.at("careerId")},{"expectedRevision",meta.at("stateRevision")},{"owner",{{"managerId",meta.at("scope").at("managerId")}}},{"kind","session.advance"},{"payload",{{"contractExpiry",expiry}}}};
const auto reply=Json::parse(cli::dump_json(session.ui_command(cli::parse_json(command.dump()),revision)));log.push_back(reply);
if(reply.value("messageType","")=="command_result")continue;if(reply.value("code","")=="decision_pending"){expiry[reply.at("message").at("args").at("playerId").get<std::string>()]={{"action","release"}};continue;}throw std::runtime_error(reply.dump());
}
write("advance.json",log);if(!found)throw std::runtime_error("controlled national desk not reached");std::string error;if(!session.save_game(out/"national.obs",0,false,error))throw std::runtime_error(error);
const auto presentations=session.state().manager_presentations;session.state().manager_presentations.clear();if(!session.save_game(out/"national-legacy.obs",0,false,error))throw std::runtime_error(error);session.state().manager_presentations=presentations;
}
modern::set_current_world(nullptr);auto loaded=EngineBridge::open(world,out/"national.obs");const auto read=loaded->snapshot();write("loaded.json",read);if(read.at("desktop").at("data").at("manager").at("id")!="manager:3"||read.at("session").at("data").at("managers").size()!=4)throw std::runtime_error("coach identity lost on reload");std::cout<<"controlled real national desk with third human saved and reloaded\n";return 0;
}
if(mode=="verify-coach-almanac") {
auto package=modern::open_world_package(world);content::Mount mount(world,package.classic);modern::set_current_world(package.world);modern::app::ModernSession session(mount.root(),1u,out/"input.obs",false);uint64_t revision=0;
const auto initial=session.state().almanac.current.matches.size();const auto desk=Json::parse(cli::dump_json(session.ui_read(cli::Json::Object{{"kind","desktop"}},revision)));const auto &meta=desk.at("meta");
const Json command={{"messageType","command"},{"contractVersion",meta.at("contractVersion")},{"requestId","request:coach-match"},{"careerId",meta.at("careerId")},{"expectedRevision",meta.at("stateRevision")},{"owner",{{"managerId",meta.at("scope").at("managerId")}}},{"kind","session.advance"},{"payload",Json::object()}};
const auto reply=Json::parse(cli::dump_json(session.ui_command(cli::parse_json(command.dump()),revision)));write("advance.json",reply);if(reply.value("messageType","")!="command_result")throw std::runtime_error(reply.dump());
const auto &season=session.state().almanac.current;bool found=false;Json recorded=Json::array();for(size_t i=initial;i<season.matches.size();++i){const auto &match=season.matches[i];for(int manager:{int(match.home_manager),int(match.away_manager)})if(manager>=0){const auto &person=season.managers.at(size_t(manager));recorded.push_back({{"managerIndex",person.index},{"name",person.name},{"matchType",match.type}});if(match.type==7||match.type==8){if(person.index!=2||person.name!="Alex Berger")throw std::runtime_error("national archive used another human");found=true;}}}
if(!found)throw std::runtime_error("no human national match recorded");write("recorded-managers.json",recorded);write("returned.json",Json::parse(cli::dump_json(session.ui_read(cli::Json::Object{{"kind","session"}},revision))));std::string error;const int active=session.state().memory.u8(::bmh::layout::ActiveManager);if(!session.save_game(out/"after-national.obs",active,false,error))throw std::runtime_error(error);modern::set_current_world(nullptr);std::cout<<"national archive attributed to third human\n";return 0;
}
auto link = EngineBridge::open(world, out / "input.obs");
const auto before = link->snapshot(); write("before.json", before);
if (before != link->snapshot()) throw std::runtime_error("reads changed the engine projection");
if (std::string(argv[1]) == "inspect-friendlies") {
const auto &opponents=before.at("friendly-plan").at("data").at("opponents");
if(opponents.empty())throw std::runtime_error("no friendly opponents");
const auto id=opponents[0].at("team").at("id");
write("home-quote.json",link->read({{"kind","friendly"},{"opponentId",id},{"home",true}}));
write("away-quote.json",link->read({{"kind","friendly"},{"opponentId",id},{"home",false}}));
if(link->snapshot()!=before)throw std::runtime_error("friendly previews mutated session");
}
if (std::string(argv[1]) == "verify") {
auto camp = before.at("camps").at("data").at("camps").front();
const auto command = engine_camp_command(before, camp.at("id"), {{"condition", 3}, {"technique", 4}, {"play", 5}}, "request:probe-book");
const auto response = link->command(command); write("command.json", command); write("response.json", response);
if (response.value("messageType", "") != "command_result") throw std::runtime_error(response.dump());
if (link->command(command) != response) throw std::runtime_error("identical request was not idempotent");
const auto after = link->snapshot(); write("after.json", after);
if (!after.at("camps").at("data").at("bookedThisWeek").get<bool>()) throw std::runtime_error("camp not booked");
const auto delta = engine_money_minor(before.at("desktop").at("data").at("accounts").at("cash")) - engine_money_minor(after.at("desktop").at("data").at("accounts").at("cash"));
if (delta != engine_money_minor(camp.at("quote").at("total"))) throw std::runtime_error("wrong actual booking cost");
write("saved.json", link->save_copy(out / "booked.obs")); link.reset();
link = EngineBridge::open(world, out / "booked.obs"); const auto loaded = link->snapshot(); write("loaded.json", loaded);
if (loaded.at("desktop").at("data").at("accounts") != after.at("desktop").at("data").at("accounts") || !loaded.at("camps").at("data").at("bookedThisWeek").get<bool>()) throw std::runtime_error("OBS round trip lost booking");
}
if (std::string(argv[1]) == "verify-lineup") {
(void)engine_lineup_projection(before);
auto order = before.at("lineup").at("data").at("order");
std::swap(order[0], order[11]);
const auto request = engine_lineup_command(before, order, "request:lineup-probe");
const auto response = link->command(request); write("lineup-command.json", request); write("lineup-response.json", response);
if (response.value("messageType", "") != "command_result") throw std::runtime_error(response.dump());
if (link->command(request) != response) throw std::runtime_error("lineup request replay changed response");
const auto after = link->snapshot(); write("lineup-after.json", after);
if (after.at("lineup").at("data").at("order") != order || after.at("desktop").at("data").at("accounts") != before.at("desktop").at("data").at("accounts"))
throw std::runtime_error("lineup order not applied exactly or account changed");
auto stale = request; stale["requestId"] = "request:stale-lineup";
const auto rejected = link->command(stale); write("lineup-rejected.json", rejected);
if (rejected.value("code", "") != "stale_revision" || link->snapshot() != after) throw std::runtime_error("stale lineup changed engine state");
write("lineup-saved.json", link->save_copy(out / "lineup.obs")); link.reset();
link = EngineBridge::open(world, out / "lineup.obs"); const auto loaded = link->snapshot(); write("lineup-loaded.json", loaded);
if (loaded.at("lineup").at("data").at("order") != order) throw std::runtime_error("lineup lost during OBS round trip");
}
if (std::string(argv[1]) == "verify-sports") {
auto tactics = engine_tactics_projection(before); tactics["values"][0] = 1; tactics["values"][7] = 7;
const auto tc = engine_tactics_command(before, tactics.at("values"), "request:sports-tactics");
const auto tr = link->command(tc); write("tactics-command.json", tc); write("tactics-response.json", tr);
if (tr.value("messageType", "") != "command_result" || link->command(tc) != tr) throw std::runtime_error(tr.dump());
const auto tactic_after = link->snapshot(); write("tactics-after.json", tactic_after);
if (engine_tactics_projection(tactic_after).at("values") != tactics.at("values")) throw std::runtime_error("tactics not applied");
auto training = engine_training_projection(tactic_after);
training["types"] = Json::array({1,3,2,2}); training["areas"] = Json::array({1,3,3,1,2,2,2,2,2});
const auto player = training.at("roster")[0].at("id").get<std::string>(); training["players"][player]["intensity"] = 3;
const auto pc = engine_training_command(tactic_after, training, "request:sports-training");
const auto pr = link->command(pc); write("training-command.json", pc); write("training-response.json", pr);
if (pr.value("messageType", "") != "command_result" || link->command(pc) != pr) throw std::runtime_error(pr.dump());
const auto after = link->snapshot(); write("sports-after.json", after); const auto actual = engine_training_projection(after);
if (actual.at("types") != training.at("types") || actual.at("areas") != training.at("areas") || actual.at("players").at(player).at("intensity") != 3 || !actual.at("initialized").get<bool>()) throw std::runtime_error("training not applied");
if (after.at("desktop").at("data").at("accounts") != before.at("desktop").at("data").at("accounts")) throw std::runtime_error("sports changed account");
auto stale = pc; stale["requestId"] = "request:stale-sports";
const auto rejected = link->command(stale); write("sports-rejected.json", rejected);
if (rejected.value("code", "") != "stale_revision" || link->snapshot() != after) throw std::runtime_error("stale sports request changed state");
write("sports-saved.json", link->save_copy(out / "sports.obs")); link.reset();
link = EngineBridge::open(world, out / "sports.obs"); const auto loaded = link->snapshot(); write("sports-loaded.json", loaded);
if (engine_tactics_projection(loaded).at("values") != tactics.at("values") || engine_training_projection(loaded).at("types") != training.at("types") || engine_training_projection(loaded).at("areas") != training.at("areas")) throw std::runtime_error("sports lost in OBS round trip");
}
if (std::string(argv[1]) == "verify-bank") {
const auto M = [](int n) { return Json{{"currency","EUR"},{"minorUnits",2},{"minor",std::to_string(int64_t(n)*100)}}; };
const auto run = [&](const Json &payload, const std::string &id) {
const auto request = engine_bank_command(link->snapshot(),payload,id);
const auto response = link->command(request); write((id.substr(8)+"-response.json").c_str(),response);
if (response.value("messageType","") != "command_result" || link->command(request) != response) throw std::runtime_error(response.dump());
};
run({{"action","deposit"},{"amount",M(10000)}},"request:deposit");
run({{"action","withdraw"},{"amount",M(2500)}},"request:withdraw");
const auto deposited = link->snapshot();
if (engine_money_minor(deposited.at("bank").at("data").at("accounts").at("deposit")) != 750000) throw std::runtime_error("deposit arithmetic wrong");
run({{"action","buy"},{"assetId","stock:0"},{"count",10}},"request:stock-buy");
run({{"action","sell"},{"assetId","stock:0"},{"count",3}},"request:stock-sell");
run({{"action","buy"},{"assetId","fund:0"},{"count",1}},"request:property-buy");
run({{"action","sell"},{"assetId","fund:0"},{"count",1}},"request:property-sell");
auto now = link->snapshot();
const auto tc = engine_ticket_command(now,25,"request:ticket");
const auto tr = link->command(tc); write("ticket-response.json",tr);
if (tr.value("messageType","") != "command_result" || link->command(tc) != tr) throw std::runtime_error(tr.dump());
now = link->snapshot();
auto stale = tc; stale["requestId"] = "request:stale-bank";
if (link->command(stale).value("code","") != "stale_revision" || link->snapshot() != now) throw std::runtime_error("stale bank command changed state");
Json edits = Json::array({{{"field",0},{"value",1000000}}});
auto preview = link->read({{"kind","credit"},{"edits",edits}}); write("credit-preview.json",preview);
(void)engine_credit_projection(now,preview);
if (now != link->snapshot()) throw std::runtime_error("credit preview mutated state");
const auto cc = engine_credit_command(now,preview,edits,"request:credit");
auto cr = link->command(cc); write("credit-response.json",cr);
if (cr.value("messageType","") != "command_result" || link->command(cc) != cr) throw std::runtime_error(cr.dump());
const auto after = link->snapshot(); write("bank-after.json",after);
write("bank-saved.json",link->save_copy(out / "bank.obs")); link.reset();
link = EngineBridge::open(world,out / "bank.obs"); const auto loaded = link->snapshot(); write("bank-loaded.json",loaded);
for (const auto *kind : {"bank","credit","stadium"}) if (loaded.at(kind).at("data") != after.at(kind).at("data")) throw std::runtime_error("finance lost during OBS round trip");
}
if (std::string(argv[1]) == "verify-commerce") {
const auto run = [&](const Json &request, const std::string &name) {
const auto response=link->command(request);write((name+"-response.json").c_str(),response);
if(response.value("messageType","")!="command_result" || link->command(request)!=response)throw std::runtime_error(response.dump());
};
run(engine_environment_command(before,"environment:doctor",3,"request:environment"),"environment");
const auto env=link->snapshot();write("environment-after.json",env);
if(env.at("desktop").at("data").at("accounts")!=before.at("desktop").at("data").at("accounts"))throw std::runtime_error("monthly environment budget debited immediately");
for(int slot:{0,14,15}) {
const auto now=link->snapshot(),view=engine_advertising_projection(now);
const auto &choices=view.at("slots")[size_t(slot)].at("choices");
auto chosen=std::find_if(choices.begin(),choices.end(),[](const auto &q){return q.at("can_accept")==true;});
if(chosen==choices.end())throw std::runtime_error("no test advertising offer");
run(engine_advertising_command(now,chosen->at("offer_id"),"request:ad-"+std::to_string(slot)),"ad-"+std::to_string(slot));
}
for(const auto *id:{"budget:press","budget:fans","budget:merchandise"}) {
run(engine_budget_command(link->snapshot(),id,1000,std::string("request:")+id),std::string(id).substr(7));
}
const auto after=link->snapshot();write("commerce-after.json",after);
auto stale=engine_environment_command(before,"environment:doctor",4,"request:commerce-stale");
const auto rejected=link->command(stale);write("stale-rejected.json",rejected);
if(rejected.value("code","")!="stale_revision" || link->snapshot()!=after)throw std::runtime_error("stale commerce command mutated state");
write("commerce-saved.json",link->save_copy(out/"commerce.obs"));link.reset();link=EngineBridge::open(world,out/"commerce.obs");
const auto loaded=link->snapshot();write("commerce-loaded.json",loaded);
for(const auto *kind:{"environment","advertising","bank"})if(loaded.at(kind).at("data")!=after.at(kind).at("data"))throw std::runtime_error("commerce OBS round trip lost state");
}
if(std::string(argv[1])=="verify-contracts") {
const auto run=[&](const Json &request,const std::string &name){auto response=link->command(request);write((name+"-response.json").c_str(),response);if(response.value("messageType","")!="command_result"||link->command(request)!=response)throw std::runtime_error(response.dump());return response;};
const auto players=engine_contracts_projection(before).at("rows");const auto first=players[0].at("id").get<std::string>(),second=players[1].at("id").get<std::string>();
run(engine_contract_request(before,first,"request:quote-one"),"quote-one");const auto queried=link->snapshot();write("queried.json",queried);
if(queried!=link->snapshot() || queried.at("contracts").at("data").at("players")!=before.at("contracts").at("data").at("players"))throw std::runtime_error("pure reads/demands changed actual contracts");
write("queried-saved.json",link->save_copy(out/"queried.obs"));
const auto q=engine_contracts_projection(queried).at("quote");auto cancel=engine_contract_cancel(queried,q.at("id"),"request:cancel");
auto bad=cancel;bad["payload"]["quoteId"]="quote:contract-999999";bad["requestId"]="request:wrong-quote";if(link->command(bad).value("code","")!="stale_quote"||link->snapshot()!=queried)throw std::runtime_error("wrong quote cancellation changed owner");
bad=cancel;bad["owner"]["managerId"]="manager:foreign";bad["requestId"]="request:wrong-owner";if(link->command(bad).value("messageType","")!="error"||link->snapshot()!=queried)throw std::runtime_error("foreign owner closed quote");
run(cancel,"cancel");const auto cancelled=link->snapshot();write("cancelled.json",cancelled);if(!cancelled.at("contracts").at("data").at("quote").is_null()||cancelled.at("contracts").at("data").at("players")!=before.at("contracts").at("data").at("players"))throw std::runtime_error("cancel did not clear quote or edited salaries");
write("cancelled-saved.json",link->save_copy(out/"cancelled.obs"));
bad=cancel;bad["requestId"]="request:old-revision";if(link->command(bad).value("code","")!="stale_revision"||link->snapshot()!=cancelled)throw std::runtime_error("stale cancel changed state");
run(engine_ticket_command(cancelled,21,"request:owner-released"),"owner-released");
run(engine_contract_request(link->snapshot(),first,"request:quote-reject"),"quote-reject");auto now=link->snapshot();auto q2=engine_contracts_projection(now).at("quote");int year=1;while(year<=4&&q2.at("demands")[size_t(year-1)].is_null())++year;if(year>4)throw std::runtime_error("no available rejection term");
const auto refused=run(engine_contract_offer(now,first,q2.at("id"),year,0,"request:offer-reject"),"offer-reject");if(refused.value("outcome","")!="offer_rejected")throw std::runtime_error("zero offer not actually rejected");
run(engine_contract_request(link->snapshot(),second,"request:quote-accept"),"quote-accept");now=link->snapshot();q2=engine_contracts_projection(now).at("quote");year=3;while(year<=4&&q2.at("demands")[size_t(year-1)].is_null())++year;if(year>4)year=1;
const int64_t salary=q2.at("max_salary").get<int64_t>()/100;
const auto accepted=run(engine_contract_offer(now,second,q2.at("id"),year,salary,"request:offer-accept"),"offer-accept");if(accepted.value("outcome","")=="offer_rejected")throw std::runtime_error("maximum salary unexpectedly rejected");
const auto after=link->snapshot();write("contracts-after.json",after);bool found=false;const auto final_contracts=engine_contracts_projection(after);for(const auto &p:final_contracts.at("rows"))if(p.at("id")==second)found=p.at("salary")==salary*100&&p.at("months")==year*12;
if(!found||!after.at("contracts").at("data").at("quote").is_null())throw std::runtime_error("actual accepted contract wrong or quote retained");
write("saved.json",link->save_copy(out/"contracts.obs"));link.reset();link=EngineBridge::open(world,out/"contracts.obs");auto loaded=link->snapshot();write("loaded.json",loaded);if(loaded.at("contracts").at("data")!=after.at("contracts").at("data"))throw std::runtime_error("contract OBS round trip lost state");
}
if(std::string(argv[1])=="verify-calendar") {
const auto run=[&](const Json &request,const std::string &name){auto response=link->command(request);write((name+"-response.json").c_str(),response);if(response.value("messageType","")!="command_result"||link->command(request)!=response)throw std::runtime_error(response.dump());return response;};
const auto calendar=engine_calendar_projection(before),schedule=engine_scheduling_projection(before);
const Json *chosen=nullptr;for(const auto &r:schedule.at("movable"))if(!r.at("targetDates").empty()){chosen=&r;break;}if(!chosen)throw std::runtime_error("no actual movable fixture");
const auto row=*chosen;const std::string target=row.at("targetDates")[0];write("chosen.json",{{"source",row},{"target",target}});
const auto request=engine_reschedule_command(before,row.at("id"),target,"request:move");run(request,"move");const auto moved=link->snapshot();write("moved.json",moved);
bool found=false;for(const auto &f:moved.at("calendar").at("data").at("fixtures"))if(f.at("round")==row.at("round")&&f.at("home").at("id")==row.at("home").at("id")&&f.at("away").at("id")==row.at("away").at("id"))found=f.at("scheduledDate")==target&&f.at("originalDate")==row.at("date")&&f.at("status")=="rescheduled";
if(!found)throw std::runtime_error("fixture did not actually move");
auto stale=request;stale["requestId"]="request:stale-move";if(link->command(stale).value("code","")!="stale_revision"||link->snapshot()!=moved)throw std::runtime_error("stale move changed state");
const auto after_schedule=engine_scheduling_projection(moved);if(!after_schedule.at("movable").empty()){auto bad=request;bad["requestId"]="request:invalid-target";bad["expectedRevision"]=moved.at("desktop").at("meta").at("stateRevision");bad["payload"]={{"matchId",after_schedule.at("movable")[0].at("id")},{"date",after_schedule.at("movable")[0].at("date")}};const auto rejected=link->command(bad);write("invalid-target.json",rejected);if(rejected.value("messageType","")!="error"||link->snapshot()!=moved)throw std::runtime_error("invalid target changed state");}
write("moved-saved.json",link->save_copy(out/"moved.obs"));link.reset();link=EngineBridge::open(world,out/"moved.obs");const auto loaded=link->snapshot();write("loaded-move.json",loaded);if(loaded.at("calendar").at("data")!=moved.at("calendar").at("data")||loaded.at("scheduling").at("data")!=moved.at("scheduling").at("data"))throw std::runtime_error("move lost in OBS round trip");
run(engine_reschedule_undo(loaded,target,"request:undo"),"undo");const auto undone=link->snapshot();write("undone.json",undone);
if(undone.at("calendar").at("data").at("fixtures")!=before.at("calendar").at("data").at("fixtures")||!undone.at("scheduling").at("data").at("moved").empty()||undone.at("desktop").at("data").at("accounts")!=before.at("desktop").at("data").at("accounts")||undone.at("scheduling").at("data")!=before.at("scheduling").at("data"))throw std::runtime_error("undo did not restore fixture/calendar or changed account");
write("undone-saved.json",link->save_copy(out/"undone.obs"));link.reset();link=EngineBridge::open(world,out/"undone.obs");const auto final=link->snapshot();write("loaded-undo.json",final);if(final.at("calendar").at("data").at("fixtures")!=before.at("calendar").at("data").at("fixtures")||!final.at("scheduling").at("data").at("moved").empty())throw std::runtime_error("undo not persisted");
}
if(std::string(argv[1])=="verify-friendlies") {
const auto run=[&](const Json &request,const std::string &name){auto response=link->command(request);write((name+"-response.json").c_str(),response);if(response.value("messageType","")!="command_result"||link->command(request)!=response)throw std::runtime_error(response.dump());return response;};
const auto plan=engine_friendly_plan(before);std::set<std::string> humans;const auto own=before.at("desktop").at("meta").at("scope").at("teamId");for(const auto &r:before.at("session").at("data").at("humanOwnership"))if(r.at("controller")=="human")humans.insert(r.at("teamId").get<std::string>());
std::string ai;for(const auto &r:plan.at("opponents"))if(!humans.contains(r.at("team").at("id").get<std::string>())){ai=r.at("team").at("id");break;}if(ai.empty())throw std::runtime_error("no AI opponent");
for(bool home:{true,false}) {
const auto now=link->snapshot(),read=link->read({{"kind","friendly"},{"opponentId",ai},{"home",home}});write(home?"home-quote.json":"away-quote.json",read);const auto quote=engine_friendly_projection(now,read,ai,home);
if(link->snapshot()!=now||link->read({{"kind","friendly"},{"opponentId",ai},{"home",home}})!=read)throw std::runtime_error("preview mutated source or RNG");
if(quote.at("dates").empty())throw std::runtime_error("no actual available date");const auto cmd=engine_friendly_command(now,read,ai,home,quote.at("dates")[0],true,false,home?"request:friendly-home":"request:friendly-away");
if(home){auto bad=cmd;bad["requestId"]="request:no-cost-consent";bad["payload"]["acceptCost"]=false;const auto refused=link->command(bad);write("no-cost-consent.json",refused);if(refused.value("messageType","")!="error"||link->snapshot()!=now)throw std::runtime_error("unapproved cost changed state");}
run(cmd,home?"home-booked":"away-booked");const auto after=link->snapshot();write(home?"home-after.json":"away-after.json",after);const auto delta=engine_money_minor(now.at("desktop").at("data").at("accounts").at("cash"))-engine_money_minor(after.at("desktop").at("data").at("accounts").at("cash"));if(delta!=(home?quote.at("cost").get<int64_t>():0))throw std::runtime_error("actual payer debit differs from quote");
auto stale=cmd;stale["requestId"]=home?"request:stale-home":"request:stale-away";if(link->command(stale).value("code","")!="stale_revision"||link->snapshot()!=after)throw std::runtime_error("stale booking changed state");
}
for(const auto &r:before.at("session").at("data").at("humanOwnership"))if(r.at("teamId")!=own&&r.at("controller")=="human") {
const auto id=r.at("teamId").get<std::string>(); const auto now=link->snapshot();const auto read=link->read({{"kind","friendly"},{"opponentId",id},{"home",false}});const auto quote=engine_friendly_projection(now,read,id,false);write("human-quote.json",read);if(quote.at("dates").empty())throw std::runtime_error("no human date");const auto cmd=engine_friendly_command(now,read,id,false,quote.at("dates")[0],true,true,"request:human-friendly");
auto bad=cmd;bad["requestId"]="request:missing-opponent-consent";bad["payload"]["opponentConsent"]=false;const auto refused=link->command(bad);write("missing-opponent-consent.json",refused);if(refused.value("messageType","")!="error"||link->snapshot()!=now)throw std::runtime_error("missing opponent consent mutated source");
run(cmd,"human-booked");const auto after=link->snapshot();if(after.at("desktop").at("data").at("accounts")!=now.at("desktop").at("data").at("accounts"))throw std::runtime_error("away human booking charged wrong manager");break;
}
const auto after=link->snapshot();write("friendlies-after.json",after);write("friendlies-saved.json",link->save_copy(out/"friendlies.obs"));link.reset();link=EngineBridge::open(world,out/"friendlies.obs");const auto loaded=link->snapshot();write("friendlies-loaded.json",loaded);
if(loaded.at("friendly-plan").at("data")!=after.at("friendly-plan").at("data")||loaded.at("calendar").at("data")!=after.at("calendar").at("data")||loaded.at("desktop").at("data").at("accounts")!=after.at("desktop").at("data").at("accounts"))throw std::runtime_error("bookings or money lost at OBS restart");
}
if (std::string(argv[1]) == "verify-national") {
const auto plan=engine_friendly_plan(before);
if(plan.at("national")!=true||plan.at("opponents").empty())throw std::runtime_error("national desk required");
const auto own=before.at("desktop").at("meta").at("scope").at("teamId");
for(const auto &row:plan.at("opponents")) {
const auto opponent=row.at("team").at("id").get<std::string>();
for(bool home:{true,false}) {
const auto read=link->read({{"kind","friendly"},{"opponentId",opponent},{"home",home}});
(void)engine_friendly_projection(before,read,opponent,home);
if(link->read({{"kind","friendly"},{"opponentId",opponent},{"home",home}})!=read)throw std::runtime_error("national quote changed on repeat");
}
}
if(link->snapshot()!=before)throw std::runtime_error("national previews changed source");
write("national-preview-saved.json",link->save_copy(out/"preview.obs"));
for(bool home:{true,false}) {
const auto now=link->snapshot();const auto opponent=plan.at("opponents")[home?0:1].at("team").at("id").get<std::string>();
const auto read=link->read({{"kind","friendly"},{"opponentId",opponent},{"home",home}});
write(home?"home-quote.json":"away-quote.json",read);
const auto quote=engine_friendly_projection(now,read,opponent,home);
if(quote.at("dates").empty())throw std::runtime_error("no national date available");
const auto command=engine_friendly_command(now,read,opponent,home,quote.at("dates")[0],true,false,home?"request:national-home":"request:national-away");
if(home) {
auto refused=command;refused["requestId"]="request:no-cost-consent";refused["payload"]["acceptCost"]=false;
const auto reply=link->command(refused);write("no-cost-consent.json",reply);
if(reply.value("messageType","")!="error"||link->snapshot()!=now)throw std::runtime_error("declined national booking changed source");
auto unavailable=command;unavailable["requestId"]="request:unavailable-date";unavailable["payload"]["date"]=now.at("desktop").at("meta").at("date");
const auto rejected=link->command(unavailable);write("unavailable-date.json",rejected);
if(rejected.value("messageType","")!="error"||link->snapshot()!=now)throw std::runtime_error("unavailable date changed source");
write("refused-saved.json",link->save_copy(out/"refused.obs"));
}
const auto reply=link->command(command);write(home?"home-command.json":"away-command.json",command);write(home?"home-response.json":"away-response.json",reply);
if(reply.value("messageType","")!="command_result"||link->command(command)!=reply)throw std::runtime_error("national booking failed or replay differed");
const auto after=link->snapshot();write(home?"home-after.json":"away-after.json",after);
const auto &bookings=after.at("friendly-plan").at("data").at("bookings");
if(bookings.size()!=now.at("friendly-plan").at("data").at("bookings").size()+1)throw std::runtime_error("national booking missing from saved plan");
const auto delta=engine_money_minor(now.at("desktop").at("data").at("accounts").at("cash"))-engine_money_minor(after.at("desktop").at("data").at("accounts").at("cash"));
if(delta!=(home?quote.at("cost").get<int64_t>():0))throw std::runtime_error("wrong national payer or amount");
auto stale=command;stale["requestId"]=home?"request:stale-home":"request:stale-away";
if(link->command(stale).value("code","")!="stale_revision"||link->snapshot()!=after)throw std::runtime_error("stale national quote changed source");
}
const auto after=link->snapshot();write("national-after.json",after);write("national-saved.json",link->save_copy(out/"national.obs"));link.reset();
link=EngineBridge::open(world,out/"national.obs");const auto loaded=link->snapshot();write("national-loaded.json",loaded);
for(const auto *kind:{"friendly-plan","calendar"})if(loaded.at(kind).at("data")!=after.at(kind).at("data"))throw std::runtime_error("national plan/calendar lost on restart");
if(loaded.at("desktop").at("data").at("accounts")!=after.at("desktop").at("data").at("accounts"))throw std::runtime_error("national funds lost on restart");
}
if(mode=="inspect-almanac"||mode=="verify-almanac"||mode=="verify-shootouts") {
const auto run=[&](const Json &q){const auto read=link->read({{"kind","almanac"},{"query",q}});if(link->read({{"kind","almanac"},{"query",q}})!=read)throw std::runtime_error("archive read changed on repeat");return std::pair{read,engine_almanac_projection(before,read,q)};};
const auto [index_read,index]=run({{"kind","index"}});write("index-read.json",index_read);
Json catalogue=Json::array();int total=0;
for(const auto &year:index.at("years")) {
const auto [cr,calendar]=run({{"kind","calendar"},{"year",year}});write(("calendar-"+std::to_string(year.get<int>())+".json").c_str(),cr);
for(const auto &day:calendar.at("days")) {
const auto [dr,d]=run({{"kind","day"},{"date",day.at("date")}});if(d.at("matches").size()!=size_t(day.at("count").get<int>()))throw std::runtime_error("archive day count mismatch");total+=day.at("count").get<int>();
for(const auto &m:d.at("matches")) {
if(mode=="verify-shootouts") {
int goals[2]={},penalties[2]={};int kicks=0;
for(const auto &e:m.at("events")){const int side=e.at("side")=="away"?1:0;if(e.at("kind")=="goal"){if(e.at("minute")==121)throw std::runtime_error("shoot-out goal counted as normal goal");++goals[side];}if(e.at("kind")=="shootout"){++kicks;if(e.at("detail")==1)++penalties[side];}}
if(m.at("result").at("final")!=Json::array({goals[0],goals[1]}))throw std::runtime_error("normal goals differ from recorded match events");
if(m.at("result").at("penalties_played")==true && (!kicks||penalties[0]==penalties[1]||m.at("result").at("penalties")!=Json::array({penalties[0],penalties[1]})))throw std::runtime_error("shoot-out score differs from actual kicks");
}
catalogue.push_back({{"id",m.at("id")},{"date",m.at("date")},{"home",m.at("home")},{"away",m.at("away")},{"result",m.at("result")},{"events",m.at("events").size()},{"competition",m.at("competition")}});
}
}
}
if(total!=index.at("match_count"))throw std::runtime_error("archive index count differs from calendars");write("catalogue.json",catalogue);
Json selected=Json::array();std::set<std::string> selected_ids;
for(const auto &m:catalogue) {
const bool human=!m.at("home").at("manager").is_null()||!m.at("away").at("manager").is_null();
if(selected.size()<2 || (human&&std::none_of(selected.begin(),selected.end(),[](const auto &r){return r.value("human",false);})) || (m.at("result").at("extra_played")==true&&std::none_of(selected.begin(),selected.end(),[](const auto &r){return r.value("extra",false);})) || (m.at("result").at("penalties_played")==true&&std::none_of(selected.begin(),selected.end(),[](const auto &r){return r.value("penalties",false);})) || (m.at("date").get<std::string>().substr(0,4)=="2027"&&std::none_of(selected.begin(),selected.end(),[](const auto &r){return r.at("date").template get<std::string>().substr(0,4)=="2027";}))) {
if(!selected_ids.insert(m.at("id").get<std::string>()).second)continue;
const auto [read,record]=run({{"kind","match"},{"id",m.at("id")}});write(("match-"+std::to_string(selected.size())+".json").c_str(),read);
selected.push_back({{"id",m.at("id")},{"date",m.at("date")},{"human",human},{"extra",m.at("result").at("extra_played")},{"penalties",m.at("result").at("penalties_played")}});
}
}
write("selected.json",selected);
if(link->snapshot()!=before)throw std::runtime_error("archive browsing changed engine or RNG projection");
const auto unknown=link->read({{"kind","almanac"},{"query",{{"kind","match"},{"id","match:unknown"}}}});write("unknown-match.json",unknown);if(unknown.value("messageType","")!="error")throw std::runtime_error("unknown archived match not rejected");
const auto foreign=link->read({{"kind","almanac"},{"managerId","manager:not-active"},{"query",{{"kind","index"}}}});write("foreign-owner.json",foreign);if(foreign.value("code","")!="manager_not_active")throw std::runtime_error("foreign archive scope accepted");
write("saved.json",link->save_copy(out/"reads.obs"));link.reset();link=EngineBridge::open(world,out/"reads.obs");const auto loaded=link->snapshot();write("loaded.json",loaded);
if(loaded.at("desktop").at("data")!=before.at("desktop").at("data")||link->read({{"kind","almanac"},{"query",{{"kind","index"}}}}).at("data")!=index_read.at("data"))throw std::runtime_error("archive or desk changed across OBS restart");
}
if(mode=="verify-reports") {
const auto index_read=link->read({{"kind","report-index"}}),index=engine_report_index(before,index_read);write("report-index.json",index_read);
Json all=Json::array();
for(const auto &league:index.at("leagues")) {
const auto id=league.at("id").get<std::string>();std::vector<Json> views;
for(int filter=0;filter<5;++filter) {
const Json request={{"kind","league-report"},{"leagueId",id},{"filter",filter}};const auto read=link->read(request);const auto value=engine_report_projection(before,index_read,read,id,filter);
if(link->read(request)!=read)throw std::runtime_error("report read not repeatable");
views.push_back(value);all.push_back(read);
}
for(int f=1;f<5;++f)if(views[size_t(f)].at("strengths")!=views[0].at("strengths"))throw std::runtime_error("table filter changed squad strengths");
for(const auto &r:views[0].at("table"))for(const auto *k:{"played","wins","draw","loss","gf","ga"}) {
const auto n=r.at(k).get<int>();int venue=0,halves=0;
for(const auto &q:views[3].at("table"))if(q.at("club")==r.at("club"))venue+=q.at(k).get<int>();for(const auto &q:views[4].at("table"))if(q.at("club")==r.at("club"))venue+=q.at(k).get<int>();
for(const auto &q:views[1].at("table"))if(q.at("club")==r.at("club"))halves+=q.at(k).get<int>();for(const auto &q:views[2].at("table"))if(q.at("club")==r.at("club"))halves+=q.at(k).get<int>();
if(n!=venue||n!=halves)throw std::runtime_error("table subsets do not sum to total");
}
const auto team=league.at("members")[0].get<std::string>();const auto squad=link->read({{"kind","squad"},{"teamId",team}});(void)engine_report_squad(before,squad,team);write(("squad-"+std::to_string(all.size()/5)+".json").c_str(),squad);
}
write("reports.json",all);
if(link->snapshot()!=before)throw std::runtime_error("report reads changed engine");
write("saved.json",link->save_copy(out/"reports.obs"));link.reset();link=EngineBridge::open(world,out/"reports.obs");
if(link->read({{"kind","report-index"}}).at("data")!=index_read.at("data"))throw std::runtime_error("report index changed after OBS restart");
}
if(mode=="verify-rankings") {
const auto index=link->read({{"kind","report-index"}}),catalogue=engine_report_index(before,index);write("rankings-index.json",index);Json all=Json::array();
for(const auto &league:catalogue.at("leagues"))for(int scope=0;scope<2;++scope){const Json request={{"kind","player-rankings"},{"leagueId",league.at("id")},{"scope",scope}};const auto read=link->read(request);write("latest-read.json",read);(void)engine_rankings_projection(before,index,read,league.at("id"),scope);if(link->read(request)!=read)throw std::runtime_error("rankings read is not repeatable");all.push_back(read);}
const auto fair=link->read({{"kind","fairplay"}});write("fairplay.json",fair);(void)engine_fairplay_projection(before,index,fair);write("all-rankings.json",all);
if(link->snapshot()!=before)throw std::runtime_error("rankings changed engine");write("saved.json",link->save_copy(out/"rankings.obs"));link.reset();link=EngineBridge::open(world,out/"rankings.obs");
if(link->read({{"kind","fairplay"}}).at("data")!=fair.at("data"))throw std::runtime_error("fairplay changed after OBS restart");
}
if(mode=="verify-other") {
const auto index=link->read({{"kind","other-index"}}),data=engine_other_index(before,index);write("other-index.json",index);Json all=Json::array();
for(const auto &v:data.at("views"))for(int round=1;round<=v.at("rounds").get<int>();++round) {
const Json request={{"kind","other-fixtures"},{"viewId",v.at("id")},{"round",round}};
const auto read=link->read(request);(void)engine_other_projection(before,index,read,v.at("id"),round);
if(link->read(request)!=read)throw std::runtime_error("cup read changed on repetition");all.push_back(read);
}
write("all-rounds.json",all);if(link->snapshot()!=before)throw std::runtime_error("cup reads mutated session");
write("saved.json",link->save_copy(out/"other.obs"));link.reset();link=EngineBridge::open(world,out/"other.obs");
if(link->read({{"kind","other-index"}}).at("data")!=index.at("data"))throw std::runtime_error("cup index changed on restart");
}
if(mode=="verify-fixtures") {
const auto ir=link->read({{"kind","report-index"}}),idx=engine_report_index(before,ir);write("fixture-index.json",ir);Json rounds=Json::array();
for(const auto &l:idx.at("leagues")) {
const auto id=l.at("id").get<std::string>();const int count=l.at("matchdays");
const auto next=link->read({{"kind","league-fixtures"},{"leagueId",id}});
if(next.at("data").at("round")!=std::min(l.at("played").get<int>()+1,count))throw std::runtime_error("incorrect default fixture round");
for(int round=1;round<=count;++round) {
const Json request={{"kind","league-fixtures"},{"leagueId",id},{"round",round}};const auto r=link->read(request);(void)engine_fixtures_projection(before,ir,r,id,round);if(link->read(request)!=r)throw std::runtime_error("fixture read not pure/repeatable");rounds.push_back(r);
}
}
write("all-rounds.json",rounds);if(link->snapshot()!=before)throw std::runtime_error("fixture reads changed state");
const auto schedule=engine_scheduling_projection(before);
if(!schedule.at("movable").empty()) {
const auto &m=schedule.at("movable")[0];const auto command=engine_reschedule_command(before,m.at("id"),m.at("targetDates")[0],"request:fixture-move");
const auto response=link->command(command);write("move-response.json",response);if(response.value("messageType","")!="command_result")throw std::runtime_error(response.dump());
const auto moved=link->snapshot();write("moved.json",moved);
const auto &owner=moved.at("desktop").at("meta").at("scope").at("teamId");
std::string league;for(const auto &l:idx.at("leagues"))if(std::find(l.at("members").begin(),l.at("members").end(),owner)!=l.at("members").end())league=l.at("id");
const auto read=link->read({{"kind","league-fixtures"},{"leagueId",league},{"round",m.at("round")}});write("moved-fixtures.json",read);
bool found=false;for(const auto &r:read.at("data").at("matches"))if(r.at("home").at("id")==m.at("home").at("id")&&r.at("away").at("id")==m.at("away").at("id")){found=true;if(r.at("status")!="rescheduled"||!r.at("result").is_null())throw std::runtime_error("reschedule marker displayed as score");}
if(!found)throw std::runtime_error("moved fixture identity missing");write("moved-saved.json",link->save_copy(out/"moved.obs"));
}
write("saved.json",link->save_copy(out/"fixtures.obs"));
}
std::cout << "engine bridge " << argv[1] << " passed\n"; return 0;
} catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
}