Files
Dreierpack-Manager/tests/modern_engine_bridge_probe.cpp
T

343 lines
38 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 <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"};
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);
}
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");
}
std::cout << "engine bridge " << argv[1] << " passed\n"; return 0;
} catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
}