Play your Steam library's Windows games on a jailbroken PS5.
C++
Republish games after they move to /data/playden-games
Leonardo Lobato80ca700c9607
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex 7ccc076..6815adc 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -247,7 +247,7 @@ target_include_directories(playden_homebrew_runtime_host PUBLIC "${CMAKE_SOURCE_target_link_libraries(playden_homebrew_runtime_host PUBLIC playden_native_coordinator playden_runtime_settings_publicationplayden_runtime_installs playden_runtime_install_service playden_runtime_package_installerplayden_runtime_private_directories playden_runtime_launch_service playden_runtime_session_reconciler- playden_storage playden_steam_cm_codec playden_runtime_steamworks)+ playden_storage playden_steam_cm_codec playden_runtime_steamworks playden_runtime_layout_migration)add_library(playden_homebrew_artwork STATIC"${CMAKE_SOURCE_DIR}/src/homebrew/artwork.cpp"diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 75af3f2..8224f74 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -1062,6 +1062,10 @@ void Controller::TickRuntime() {play_queued_.empty() && !sync_before_play_.count(id);if (const auto note = play_notes_.find(id); note != play_notes_.end() && !launching) game.play_detail = note->second;if (sync_before_play_.count(id)) game.play_status = "Checking saves…";+ // Play's own work before the launch (a game moved in 0.5 is republished first).+ if (const auto progress = snapshot.play_progress.find(id); progress != snapshot.play_progress.end()) {+ game.play_status = progress->second; game.can_play = false; game.can_prepare = false;+ }if (const auto pending = play_after_prepare_.find(id); pending != play_after_prepare_.end()) {game.play_status = pending->second.words; game.can_prepare = false;}diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex e8c0baa..d5d90f0 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -9,6 +9,7 @@#include "runtime/settings_publication_journal.h"#include "runtime/dotnet_heap.h"#include "runtime/install_script.h"+#include "runtime/layout_migration.h"#include "runtime/redist_install.h"#include "runtime/settings_publication_owner.h"#include "runtime/session_storage.h"@@ -80,6 +81,72 @@ bool AwaitingRegistration(const rt::RuntimeInstall& record) {return record.journal && (record.journal->step == "register" || record.journal->step == "await-native") &&(!record.last_failure || record.last_failure->code == "registration-uncertain");}++// Rewrites the game_root= and prefix_root= lines of each <saves>/<id>/cloud-index.txt (the format+// steam/backend/cloud_sync.cpp WriteIndex writes) that lie inside `from` to the same place inside+// `to`, so a moved game keeps its quick-check index. Idempotent; returns how many changed.+std::size_t RebaseCloudIndexes(const std::filesystem::path& saves, const std::string& from, const std::string& to) {+ constexpr off_t kMaxIndexBytes = 16 * 1024 * 1024;+ std::size_t changed = 0;+ std::error_code error;+ for (std::filesystem::directory_iterator it(saves, error), end; !error && it != end; it.increment(error)) {+ std::error_code type_error;+ if (it->is_symlink(type_error) || !it->is_directory(type_error)) continue;+ const auto path = it->path() / "cloud-index.txt";+ const int fd = open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) continue;+ struct stat info{};+ std::string text;+ if (fstat(fd, &info) == 0 && S_ISREG(info.st_mode) && info.st_size <= kMaxIndexBytes) {+ text.resize(static_cast<std::size_t>(info.st_size));+ std::size_t done = 0;+ while (done < text.size()) {+ const auto count = read(fd, text.data() + done, text.size() - done);+ if (count <= 0) break;+ done += static_cast<std::size_t>(count);+ }+ text.resize(done);+ }+ close(fd);+ if (text.rfind("version=1\n", 0) != 0) continue;+ std::string rewritten;+ bool any = false;+ for (std::size_t start = 0; start < text.size();) {+ auto stop = text.find('\n', start);+ stop = stop == std::string::npos ? text.size() : stop + 1;+ std::string line = text.substr(start, stop - start);+ start = stop;+ for (const char* key : {"game_root=", "prefix_root="}) {+ const std::string_view name(key);+ if (line.compare(0, name.size(), name) != 0) continue;+ const bool newline = !line.empty() && line.back() == '\n';+ const auto value = line.substr(name.size(), line.size() - name.size() - (newline ? 1 : 0));+ if (const auto moved = rt::RebaseInstallPath(value, from, to)) {+ line = std::string(name) + *moved + (newline ? "\n" : "");+ any = true;+ }+ }+ rewritten += line;+ }+ if (!any) continue;+ const auto temporary = path.string() + ".playden-partial";+ const int out = open(temporary.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, info.st_mode & 0777);+ if (out < 0) continue;+ std::size_t written = 0;+ while (written < rewritten.size()) {+ const auto count = write(out, rewritten.data() + written, rewritten.size() - written);+ if (count <= 0) break;+ written += static_cast<std::size_t>(count);+ }+ const bool ok = written == rewritten.size() && fsync(out) == 0;+ if (close(out) != 0 || !ok || rename(temporary.c_str(), path.c_str()) != 0) {+ unlink(temporary.c_str());+ continue;+ }+ ++changed;+ }+ return changed;+}} // namespace// Newest wrapper session log under <data root>/library/logs, first 32 KiB and last 128 KiB.@@ -245,6 +312,8 @@ struct RuntimeHost::Composition {std::unique_ptr<rt::LaunchService> launch;// Last worker preflight per install, with its time, for Handoff.std::map<std::string, std::pair<rt::LaunchPreflight, std::int64_t>> preflights;+ // The old and new games root while the 0.5 games move is unfinished.+ std::optional<std::pair<std::string, std::string>> games_move;};RuntimeHost::RuntimeHost(RuntimeHostConfig config) : config_(std::move(config)) {@@ -255,6 +324,14 @@ RuntimeHost::RuntimeHost(RuntimeHostConfig config) : config_(std::move(config))return static_cast<std::int64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());};+ if (!config_.moved_games_root)+ config_.moved_games_root = [state = config_.state_root]() -> std::optional<std::pair<std::string, std::string>> {+ const auto journal = rt::LoadLayoutJournal(state);+ if (!journal || journal->step != "games-moved") return std::nullopt;+ return std::make_pair(journal->from, journal->to);+ };+ if (!config_.finish_games_move)+ config_.finish_games_move = [state = config_.state_root](std::string* error) { return rt::MarkLayoutDone(state, error); };application_thread_ = pthread_self();}RuntimeHost::~RuntimeHost() { Shutdown(); }@@ -876,9 +953,14 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstfor (const auto& candidate : c.recipes)if (candidate.app_id == record.app_id && candidate.id == record.recipe_id)if (const auto lacks = KitLacksForRecipe(candidate, c.kit->view); !lacks.empty()) return lacks;+ // A game whose folder moved (RuntimeInstall::moved_from) is published again at its revision, so+ // its descriptor, profile and dxvk.conf name the new folder.+ const bool moved = !record.moved_from.empty();// "Steam features" only swaps the game's own files, so it follows the saved value at once.- if (saved.revision <= record.settings_revision) return ApplySteamworks(c, record);+ if (saved.revision <= record.settings_revision && !moved) return ApplySteamworks(c, record);if (!c.kit) return "No verified compatibility kit is installed.";+ if (saved.revision < record.settings_revision)+ return "The game's saved settings are older than its PS5 title's; prepare it again.";const rt::GameRecipe* recipe = nullptr;for (const auto& candidate : c.recipes)if (candidate.app_id == record.app_id && candidate.id == record.recipe_id &&@@ -989,13 +1071,54 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstconst auto resumed = c.owner->ResumeRequested(*armed, c.request_directory, config_.host_namespace_prefix);Log("settings update resume app=" + std::to_string(record.app_id) + " state=" +std::to_string(static_cast<int>(resumed.state)) + " code=" + resumed.code + " message=" + resumed.message);+ // The title's start check now finds the new folder.+ if (moved && resumed.state == rt::PackageActionState::kComplete)+ if (const auto current = c.records.Find(record.install_id))+ c.admission[record.install_id] = c.installer->QuickAdmission(*current);PublishInstalls(c, record.install_id);// A failed update keeps its journal, so Play waits until Resume on the PS5 title finishes it.if (resumed.state != rt::PackageActionState::kComplete) return "The settings could not be applied: " + resumed.message;if (published) *published = true;+ if (moved) FinishGamesMove(c);return {};}+void RuntimeHost::MoveGameRecords(Composition& c) {+ c.games_move = config_.moved_games_root ? config_.moved_games_root() : std::nullopt;+ if (!c.games_move) return;+ const auto& [from, to] = *c.games_move;+ // Records on other drives (USB, M.2) stay; the ones under the old root name the new one and+ // keep the old one until a publication names the new folder.+ std::vector<rt::RuntimeInstall> moved;+ for (auto record : c.repository.Snapshot()) {+ const auto path = rt::RebaseInstallPath(record.install_path, from, to);+ if (!path) continue;+ record.moved_from = record.install_path;+ record.install_path = *path;+ moved.push_back(std::move(record));+ }+ if (!moved.empty()) {+ const auto written = c.repository.UpdateAll(moved);+ Log("layout move records=" + std::to_string(moved.size()) + " from=" + from + " to=" + to + " " ++ (written.ok() ? std::string("rewritten") : "failed: " + written.message()));+ // Nothing is marked done while the records still name the old root.+ if (!written.ok()) { c.games_move.reset(); return; }+ }+ const auto indexes = RebaseCloudIndexes(HostPath(to) / ".playden-saves", from, to);+ if (indexes) Log("layout move cloud indexes=" + std::to_string(indexes));+}++void RuntimeHost::FinishGamesMove(Composition& c) {+ if (!c.games_move) return;+ // Games not prepared yet (or failed) keep their mark; their next preparation publishes the new folder.+ for (const auto& record : c.repository.Snapshot())+ if (!record.moved_from.empty() && record.state == rt::PreparationState::kReady) return;+ std::string error;+ const bool done = config_.finish_games_move && config_.finish_games_move(&error);+ Log(std::string("layout move ") + (done ? "done" : "not marked done: " + error));+ if (done) c.games_move.reset();+}+// Fresh facts for one launch, from the package layer, the bottle's start check// and the console's inventory and activity. Runs on the worker; the application// thread reuses the worker's latest result while it is fresh.@@ -1120,7 +1243,22 @@ void RuntimeHost::RunPlay(Composition& c, std::uint32_t app_id) {record->state == rt::PreparationState::kReady &&c.coordinator->Activity(record->title_id) == rt::NativeActivity::kStopped;}- const auto settings = idle ? RepublishSettings(c, *record) : std::string();+ std::string settings;+ if (!record->moved_from.empty()) {+ // Its folder moved in 0.5: the title starts only once its publication names the new one.+ if (!idle) {+ auto busy = MaintenanceRefusal(c, *record);+ settings = "This game needs an update for Playden 0.5 first: " + (busy.empty() ? "Close the game first." : busy);+ } else {+ Publish([&](RuntimeSnapshot& s) { s.play_progress[app_id] = kPlayUpdatingForLayout; });+ settings = RepublishSettings(c, *record);+ Publish([&](RuntimeSnapshot& s) { s.play_progress.erase(app_id); });+ if (!settings.empty()) settings = "This game could not be updated for Playden 0.5: " + settings;+ Log("play moved app=" + std::to_string(app_id) + " " + (settings.empty() ? "republished" : settings));+ }+ } else if (idle) {+ settings = RepublishSettings(c, *record);+ }result = settings.empty() ? c.launch->Request(record->install_id): rt::LaunchResult::Failure(rt::LaunchError::kPreflight, settings);}@@ -1579,6 +1717,14 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&if (refreshed.state != rt::PackageActionState::kComplete) return refreshed.message;changed = true;}+ // A game whose folder moved in 0.5 is published again for the new folder first.+ if (!existing->moved_from.empty()) {+ if (const auto refused = RepublishSettings(c, *existing); !refused.empty()) return refused;+ const auto install_id = existing->install_id;+ existing = c.records.Find(install_id);+ if (!existing) return "The game's install record is missing.";+ changed = true;+ }auto admission = c.installer->AdmissionDiagnostic(*existing);if (admission != "ok") {const auto repaired = c.installer->RepairBottle(*existing);@@ -1992,8 +2138,13 @@ std::string RuntimeHost::RunMaintenance(Composition& c, std::uint32_t app, Runti" code=" + repaired.code + " admission=" + admission);PublishInstalls(c, record->install_id);if (repaired.state != rt::PackageActionState::kComplete) return "The bottle could not be repaired: " + repaired.message;- if (admission != "ok") return "The PS5 title still fails its start check: " + admission;+ // A game whose folder moved fails the check until it is published again, just below.+ if (admission != "ok" && record->moved_from.empty()) return "The PS5 title still fails its start check: " + admission;if (auto refused = RepublishSettings(c, *record); !refused.empty()) return refused;+ if (!record->moved_from.empty())+ if (const auto current = c.records.Find(record->install_id))+ if (const auto checked = c.installer->AdmissionDiagnostic(*current); checked != "ok")+ return "The PS5 title still fails its start check: " + checked;*ok = true;if (!c.installer->TitleCurrent(*record) || !c.installer->TitleMetadataCurrent(*record))return "Repaired. The PS5 title also has an update: press Update on the game page.";@@ -2420,6 +2571,7 @@ void RuntimeHost::Run() {// Startup only reads durable state. Records with a journal wait for an// explicit recovery action; nothing resumes, registers or rebuilds here.Log("startup records loaded installs=" + std::to_string(c.repository.Snapshot().size()));+ MoveGameRecords(c);LoadGeneratedRecipes(c);Log("startup generated recipes loaded");PublishInstalls(c);@@ -2490,13 +2642,25 @@ void RuntimeHost::Run() {std::lock_guard<std::mutex> lock(mutex_);launch_poll_ = true;}+ // Games whose folder moved with the games root (0.5) start from Home only once their+ // publication names the new folder: republished now, busy titles wait for Play.+ for (const auto& record : c.repository.Snapshot()) {+ if (record.moved_from.empty() || record.state != rt::PreparationState::kReady) continue;+ const auto busy = c.kit ? MaintenanceRefusal(c, record) : std::string("no verified kit");+ bool published = false;+ const auto refused = busy.empty() ? RepublishSettings(c, record, &published) : busy;+ Log("startup moved app=" + std::to_string(record.app_id) + " " ++ (published ? std::string("republished") : (busy.empty() ? "failed: " : "waits: ") + refused));+ }+ FinishGamesMove(c);// Settings saved while Playden was closed, or before a title was stopped, are published// now, so a start from the PS5 Home screen uses them too. Busy titles wait for Play.if (c.kit)for (const auto& record : c.repository.Snapshot()) {// Only newer settings: the Steam account is not known yet, so Steam files wait for Play.const auto saved = config_.settings_record ? config_.settings_record(record.app_id) : std::nullopt;- if (!saved || saved->revision <= record.settings_revision || !MaintenanceRefusal(c, record).empty()) continue;+ if (!saved || saved->revision <= record.settings_revision || !record.moved_from.empty() ||+ !MaintenanceRefusal(c, record).empty()) continue;bool published = false;const auto refused = RepublishSettings(c, record, &published);if (published || !refused.empty())@@ -2698,6 +2862,8 @@ void RuntimeHost::Run() {s.refusals.erase(request.app_id);});refusal = RunPrepare(*composition, request, &awaiting);+ // A resumed publication of a moved game may have been the last the 0.5 move waited for.+ FinishGamesMove(*composition);// A game prepared again gets back the saves it kept when it was uninstalled,// before it can first be started (from Home, while it waits for registration).if (refusal.empty()) refusal = RestoreKeptSaves(*composition, request.app_id);diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex e2f4e5d..04c959a 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -121,6 +121,13 @@ struct RuntimeHostConfig {std::function<std::int64_t()> now_ms;// How long a started title may take to report its session before Play gives up.std::int64_t launch_evidence_wait_ms = 60000;+ // The 0.5 layout's games move (runtime/layout_migration.h), finished on the worker.+ // moved_games_root: the old and new games root (console paths) while the journal is at+ // "games-moved"; nothing otherwise. finish_games_move: called once every moved Ready game is+ // republished; false keeps the move pending for the next start. Empty: LoadLayoutJournal and+ // MarkLayoutDone on state_root.+ std::function<std::optional<std::pair<std::string, std::string>>()> moved_games_root;+ std::function<bool(std::string* error)> finish_games_move;// SQLite and the native readers run on this worker. PS5 std::thread stacks are// too small for them, so the worker uses an explicit stack size.std::size_t stack_bytes = 1024 * 1024;@@ -254,8 +261,13 @@ struct RuntimeSnapshot {std::uint64_t maintenance_handled = 0;// Bytes in each game's Windows user folders (installed and kept), from the latest MeasureSaves.std::map<std::uint32_t, std::uint64_t> save_bytes;+ // What Play does before the launch is requested, per Steam app, while it runs: a game whose+ // folder moved in Playden 0.5 is republished first (kPlayUpdatingForLayout).+ std::map<std::uint32_t, std::string> play_progress;};+inline constexpr const char* kPlayUpdatingForLayout = "Updating this game for Playden 0.5…";+// A downloaded game to prepare. The game files stay at install_path.struct RuntimePrepareRequest {std::uint32_t app_id = 0;@@ -341,6 +353,10 @@ class RuntimeHost {// whether an update ran. The title keeps the launch entry it was prepared with.std::string RepublishSettings(Composition& composition, const runtime::RuntimeInstall& record,bool* published = nullptr);+ // The 0.5 games move: rewrites the records and Cloud indexes under the old games root at startup,+ // and marks the move done once no moved Ready game is left to republish.+ void MoveGameRecords(Composition& composition);+ void FinishGamesMove(Composition& composition);// Empty when the game's Ready title is stopped with no launch pending, otherwise why not.std::string MaintenanceRefusal(Composition& composition, const runtime::RuntimeInstall& record);// Runs one maintenance action; empty message on refusal means none; *ok tells success.diff --git a/src/runtime/game_install.cpp b/src/runtime/game_install.cppindex c68c402..28a7078 100644--- a/src/runtime/game_install.cpp+++ b/src/runtime/game_install.cpp@@ -188,6 +188,8 @@ bool ValidRecord(const RuntimeInstall& record) {if (record.journal &&(!IsSimpleId(record.journal->operation_id) || !IsSimpleId(record.journal->operation) ||!IsSimpleId(record.journal->step))) return false;+ if (!record.moved_from.empty() &&+ (!IsAbsoluteNormalizedPath(record.moved_from) || record.moved_from == record.install_path)) return false;return true;}@@ -262,6 +264,10 @@ std::optional<RuntimeInstall> ParseRecord(const JsonValue& value, RepositoryErroif (!operation_id || !operation || !step) return std::nullopt;record.journal = PreparationJournal{operation_id->text(), operation->text(), step->text()};}+ if (const auto* moved = value.Find("moved_from")) {+ if (!moved->is_string() || moved->text().empty()) return std::nullopt;+ record.moved_from = moved->text();+ }if (!ValidRecord(record)) return std::nullopt;return record;}@@ -297,6 +303,7 @@ void WriteRecord(TextOutput& output, const RuntimeInstall& record) {StringField(output, "operation", record.journal->operation);StringField(output, "step", record.journal->step, false); output << '}'; }else output << "null";+ if (!record.moved_from.empty()) { output << ','; StringField(output, "moved_from", record.moved_from, false); }output << '}';}@@ -316,6 +323,15 @@ bool SameRuntimeInstallIdentity(const RuntimeInstall& a, const RuntimeInstall& ba.app_id == b.app_id && a.data_root == b.data_root && a.install_path == b.install_path;}+std::optional<std::string> RebaseInstallPath(const std::string& path, std::string from, std::string to) {+ while (from.size() > 1 && from.back() == '/') from.pop_back();+ while (to.size() > 1 && to.back() == '/') to.pop_back();+ if (from.empty() || to.empty() || path.compare(0, from.size(), from) != 0) return std::nullopt;+ if (path.size() == from.size()) return to;+ if (path[from.size()] != '/') return std::nullopt;+ return to + path.substr(from.size());+}+RuntimeInstallRepository::RuntimeInstallRepository(Storage& storage, std::string relative_path,NativeAvailabilityQuery native_availability): storage_(storage), relative_path_(std::move(relative_path)),@@ -509,6 +525,28 @@ RepositoryResult<void> RuntimeInstallRepository::Update(const RuntimeInstall& rereturn RepositoryResult<void>::Success();}+RepositoryResult<void> RuntimeInstallRepository::UpdateAll(const std::vector<RuntimeInstall>& records) {+ if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");+ std::unordered_map<std::string, RuntimeInstall> next = installs_;+ for (const auto& record : records) {+ const auto found = next.find(record.install_id);+ if (found == next.end()) return Failure(RepositoryError::kNotFound, "runtime install does not exist");+ auto normalized = record;+ if (!NormalizeLaunchPaths(normalized) || !ValidRecord(normalized))+ return Failure(RepositoryError::kInvalidRecord, "runtime install record is invalid");+ const auto& current = found->second;+ if (record.title_id != current.title_id || record.app_id != current.app_id ||+ record.data_root != current.data_root || record.schema_version != current.schema_version)+ return Failure(RepositoryError::kConflict, "runtime install identity is immutable");+ found->second = std::move(normalized);+ }+ auto previous = std::move(installs_);+ installs_ = std::move(next);+ const auto persisted = Persist();+ if (!persisted.ok()) { installs_ = std::move(previous); return persisted; }+ return RepositoryResult<void>::Success();+}+RepositoryResult<void> RuntimeInstallRepository::EraseAfterUnregister(const std::string& install_id) {if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");const auto found = installs_.find(install_id);diff --git a/src/runtime/game_install.h b/src/runtime/game_install.hindex 7415a12..18406d0 100644--- a/src/runtime/game_install.h+++ b/src/runtime/game_install.h@@ -75,6 +75,11 @@ struct RuntimeInstall {std::vector<RuntimeArtifactIdentity> artifacts;std::optional<RuntimeFailure> last_failure;std::optional<PreparationJournal> journal;+ // Set when the game folder moved with the games root (the 0.5 layout): its earlier+ // install_path, which the committed publication still names. The game needs a+ // republication against install_path; a committed publication clears it. Stored only+ // when set, so older readers (which ignore unknown keys) are unaffected.+ std::string moved_from;};// Shared OWNER record validation; this grants no filesystem ownership or readiness.@@ -83,6 +88,9 @@ bool ValidateRuntimeInstallRecord(const RuntimeInstall& record);// artifacts, recipe and launch fields are not compared (a kit respin may change// them). State, revision, journal and failure are checked separately.bool SameRuntimeInstallIdentity(const RuntimeInstall& first, const RuntimeInstall& second);+// path with its leading `from` replaced by `to`, when path is from or inside it (whole+// path components: /a/games-old is not inside /a/games); nothing otherwise.+std::optional<std::string> RebaseInstallPath(const std::string& path, std::string from, std::string to);struct ReserveRequest {std::string install_id;@@ -193,6 +201,8 @@ class RuntimeInstallRepository {RepositoryResult<RuntimeInstall> Reserve(const ReserveRequest& request);RepositoryResult<RuntimeInstall> Adopt(const LegacyInstall& legacy);RepositoryResult<void> Update(const RuntimeInstall& record);+ // Several updates in one durable write: all of them or none.+ RepositoryResult<void> UpdateAll(const std::vector<RuntimeInstall>& records);RepositoryResult<void> EraseAfterUnregister(const std::string& install_id);// Same, with the caller's fresh observation instead of the availability query:// removal confirms with the console inventory and the source folder whilediff --git a/src/runtime/settings_publication.cpp b/src/runtime/settings_publication.cppindex 157ddc0..8883843 100644--- a/src/runtime/settings_publication.cpp+++ b/src/runtime/settings_publication.cpp@@ -125,6 +125,78 @@ ReceiptRead ReadReceipt(const std::filesystem::path& control, const ManagedDirecif (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size(), &parsed) != PW_OK) return {};return {true, false, std::move(bytes)};}+// The game folder a title's live descriptor names, or nothing when it can't be read.+std::optional<std::string> LiveGameRoot(const std::string& title_id, const std::filesystem::path& prefix) {+ const auto host = prefix.string(); PwTitlePublicationPlatform platform{};+ platform.host_root = host.empty() ? nullptr : host.c_str(); platform.owner_uid = geteuid();+ PwTitlePublicationDescriptor descriptor{}; char error[256]{};+ if (pw_title_publication_read_descriptor(("/data/homebrew/" + title_id + "/game-launch.json").c_str(), title_id.c_str(),+ &platform, &descriptor, error, sizeof(error)) != PW_OK)+ return std::nullopt;+ return std::string(descriptor.launch.game_root);+}+// Whether the previous publication of `title_id` is the one a moved game folder left behind.+bool NamesMovedRoot(const GameRootMove* moved, const std::string& title_id, const std::filesystem::path& prefix) {+ if (!moved) return false;+ const auto root = LiveGameRoot(title_id, prefix);+ return root && *root == moved->from;+}+}+std::optional<GameRootMove> GameRootMoveOf(const RuntimeInstall& record) {+ if (record.moved_from.empty() || record.moved_from == record.install_path) return std::nullopt;+ return GameRootMove{record.moved_from, record.install_path};+}+PackageActionResult VerifyMovedPublication(const RuntimeInstall& r, const GameRootMove& move,+ const std::string& receipt_bytes, const std::string& metadata_bytes, const std::filesystem::path& prefix) {+ const auto refuse = [](const char* message) { return Failure("publication-moved", message); };+ if (!prefix.empty() && (!prefix.is_absolute() || prefix != prefix.lexically_normal()))+ return refuse("Invalid canonical namespace.");+ PwTitlePublication receipt{}; PwTitlePublicationMetadata m{};+ const auto metadata_digest = HashArtifactBytes(metadata_bytes);+ if (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt_bytes.data()), receipt_bytes.size(), &receipt) != PW_OK ||+ receipt.phase != PW_TITLE_PUBLICATION_COMMITTED || receipt.install_id != r.install_id || receipt.title_id != r.title_id ||+ !metadata_digest || *metadata_digest != receipt.publication_sha256)+ return refuse("The moved game's publication receipt does not bind its metadata.");+ if (pw_title_publication_metadata_parse(reinterpret_cast<const uint8_t*>(metadata_bytes.data()), metadata_bytes.size(), &m) != PW_OK ||+ m.install_id != r.install_id || m.title_id != r.title_id || m.data_root != r.data_root ||+ m.settings_revision != receipt.settings_revision)+ return refuse("The moved game's publication metadata names another install.");+ const auto host = prefix.string(); PwTitlePublicationPlatform platform{};+ platform.host_root = host.empty() ? nullptr : host.c_str(); platform.owner_uid = geteuid();+ PwTitlePublicationDescriptor descriptor{}; char error[256]{};+ const auto descriptor_digest = [&] {+ return HashArtifactBytes(std::string_view(reinterpret_cast<const char*>(descriptor.bytes), descriptor.length));+ };+ if (pw_title_publication_read_descriptor(("/data/homebrew/" + r.title_id + "/game-launch.json").c_str(), r.title_id.c_str(),+ &platform, &descriptor, error, sizeof(error)) != PW_OK ||+ descriptor.launch.app_id != r.app_id || descriptor.launch.install_id != r.install_id ||+ descriptor.launch.data_root != r.data_root || descriptor.launch.game_root != move.from ||+ descriptor_digest() != std::optional<std::string>(m.descriptor_sha256))+ return refuse("The moved game's descriptor does not match its publication.");+ // Profile and catalog live in the private data root, which did not move.+ auto profiles = ManagedDirectory::Open(Map(prefix, r.data_root + "/library/profiles"), DirectoryPolicy::kPrivate);+ auto profile_bytes = profiles ? ReadPublicationFile(*profiles, std::string(m.profile_id) + ".profile", 256 * 1024) : std::nullopt;+ auto catalog = profiles ? ReadPublicationFile(*profiles, "profiles.lst", 4096) : std::nullopt;+ PwGameProfile profile{};+ if (!profile_bytes || !profile_bytes->present || HashArtifactBytes(profile_bytes->bytes) != std::optional<std::string>(m.profile_sha256) ||+ pw_game_profile_parse(reinterpret_cast<const uint8_t*>(profile_bytes->bytes.data()), profile_bytes->bytes.size(), &profile) != PW_OK ||+ profile.app.id != std::string(m.profile_id) || !catalog || !catalog->present ||+ HashArtifactBytes(catalog->bytes) != std::optional<std::string>(m.catalog_sha256))+ return refuse("The moved game's profile does not match its publication.");+ // The profile's program and folder were inside the old game folder; the folder is checked at its new place.+ char working[1024]{}, executable[1024]{};+ const auto bottle = r.data_root + "/library/prefixes/game";+ if (pw_wine_launch_host_dir(bottle.c_str(), profile.app.working_directory, working, sizeof(working)) ||+ pw_wine_launch_host_dir(bottle.c_str(), profile.app.executable, executable, sizeof(executable)) ||+ std::string(m.dxvk_path) != std::string(working) + "/dxvk.conf" ||+ !RebaseInstallPath(executable, move.from, move.to))+ return refuse("The moved game's profile names a program outside its game folder.");+ const auto moved_working = RebaseInstallPath(working, move.from, move.to);+ struct stat info{};+ if (!moved_working || lstat(Map(prefix, *moved_working).c_str(), &info) != 0 ||+ !OwnedGameDirectory(info, m.game_root_unowned != 0))+ return refuse("The moved game's working folder is missing at its new place.");+ return {PackageActionState::kComplete, {}, {}};}PackageActionResult PublishSettingsOperation(const SettingsPublicationOperation& o,const PublicationPaths& paths, PublicationDependencies& deps) {@@ -168,7 +240,12 @@ PackageActionResult PublishSettingsOperation(const SettingsPublicationOperation&Map(deps.host_namespace_prefix, previous.install.data_root + "/library/input"),Map(deps.host_namespace_prefix, "/data/homebrew/" + previous.install.title_id + "/game-launch.json"),Map(deps.host_namespace_prefix, profile_root + ".playden-publication")};- result = deps.verify_files(previous, previous_paths, lease->fd(), true); if (!Complete(result)) return result;+ // A journal left by a game folder that moved names the old folder, which no longer exists.+ result = deps.moved_root && previous.install.install_path == deps.moved_root->from+ ? VerifyMovedPublication(o.install, *deps.moved_root, previous.committed_receipt_bytes, previous.metadata_bytes,+ deps.host_namespace_prefix)+ : deps.verify_files(previous, previous_paths, lease->fd(), true);+ if (!Complete(result)) return result;result = deps.authorize_retirement(previous, o); if (!Complete(result)) return result;if (!ArchiveSettingsPublicationOperation(control, previous).ok() || !held())return Failure("publication-archive", "Previous journal archival requires fresh recovery.");@@ -467,7 +544,7 @@ PackageActionResult ApplyPendingPublicationFiles(const SettingsPublicationOperatreturn publish(*profiles, paths.metadata, o.metadata_bytes, previous_digest);}PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperation& o,- const PublicationPaths& paths, int borrowed, const std::filesystem::path& prefix) {+ const PublicationPaths& paths, int borrowed, const std::filesystem::path& prefix, const GameRootMove* moved) {std::string reason;if (!EncodeSettingsPublicationOperation(o, &reason) || !PathsMatch(o, paths, prefix))return Failure("publication-invalid", "Frozen preflight operation or canonical paths are invalid.");@@ -492,7 +569,10 @@ PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperat// Destinations without a previous committed version are not refused: an earlier// apply's leftovers (presets switched A -> B -> A, an interrupted first setup) are// Playden's own files and are written over.- if (!initial) {+ if (!initial && NamesMovedRoot(moved, o.install.title_id, prefix)) {+ auto checked = VerifyMovedPublication(o.install, *moved, o.previous_receipt_bytes, o.previous_metadata_bytes, prefix);+ if (!Complete(checked)) return {PackageActionState::kFailed, "publication-preflight-previous", checked.message};+ } else if (!initial) {const auto host = prefix.string(); PwTitlePublicationPlatform platform{};platform.host_root = host.empty() ? nullptr : host.c_str(); platform.owner_uid = geteuid();PwTitlePublicationDescriptor descriptor{}; PwTitlePublicationContents contents{}; char error[256]{};@@ -540,7 +620,7 @@ PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperat}Result<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const RuntimeInstall& r,const SettingsLaunchPlan& plan, const std::string& kit_id, const std::string& transaction,- std::int64_t unix_time, int borrowed, const std::filesystem::path& prefix) {+ std::int64_t unix_time, int borrowed, const std::filesystem::path& prefix, const GameRootMove* moved) {auto fail = [](const std::string& message) {return Result<SettingsPublicationOperation>::Failure(StorageError::kInvalidData, message);};@@ -646,7 +726,12 @@ Result<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const Rplatform.host_root = host.empty() ? nullptr : host.c_str(); platform.owner_uid = geteuid(); char error[256]{};auto profiles = library->OpenChild("profiles", DirectoryPolicy::kPrivate);auto prior = profiles ? ReadPublicationFile(*profiles, ".playden-publication", 32768) : std::nullopt;- if (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt.bytes.data()), receipt.bytes.size(), &parsed) != PW_OK ||+ if (prior && prior->present && NamesMovedRoot(moved, r.title_id, prefix)) {+ auto checked = VerifyMovedPublication(r, *moved, receipt.bytes, prior->bytes, prefix);+ if (!Complete(checked) || pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt.bytes.data()),+ receipt.bytes.size(), &parsed) != PW_OK)+ return fail("Before state is not the verified publication of the moved game folder: " + checked.message);+ } else if (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt.bytes.data()), receipt.bytes.size(), &parsed) != PW_OK ||parsed.phase != PW_TITLE_PUBLICATION_COMMITTED || !prior || !prior->present ||pw_title_publication_read_descriptor(("/data/homebrew/" + r.title_id + "/game-launch.json").c_str(), r.title_id.c_str(),&platform, &descriptor, error, sizeof(error)) != PW_OK || descriptor.launch.app_id != r.app_id ||@@ -696,7 +781,7 @@ Result<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const RPublicationPaths paths{Map(prefix, profiles + plan.profile_id + ".profile"), Map(prefix, profiles + "profiles.lst"),Map(prefix, r.data_root + "/library/input"), Map(prefix, "/data/homebrew/" + r.title_id + "/game-launch.json"),Map(prefix, profiles + ".playden-publication")};- auto preflight = PreflightSettingsPublication(*frozen, paths, borrowed, prefix);+ auto preflight = PreflightSettingsPublication(*frozen, paths, borrowed, prefix, moved);if (!Complete(preflight) || !held()) return fail(preflight.message.empty() ? "Captured operation preflight failed." : preflight.message);return Result<SettingsPublicationOperation>::Success(std::move(*frozen));}diff --git a/src/runtime/settings_publication.h b/src/runtime/settings_publication.hindex 0c3908a..9cfdf10 100644--- a/src/runtime/settings_publication.h+++ b/src/runtime/settings_publication.h@@ -26,6 +26,21 @@ inline void FillProfilePublication(const SettingsLaunchPlan& plan, ProfilePublic}}+// A game folder that moved as a whole (the 0.5 layout, RuntimeInstall::moved_from): its+// committed publication names `from`, the install record names `to`. The publication that+// replaces it checks the old one with the game folder at `to`.+struct GameRootMove {+ std::string from, to;+};+// The record's move, while it is marked; nothing otherwise.+std::optional<GameRootMove> GameRootMoveOf(const RuntimeInstall& record);+// The committed publication a moved game folder left, checked like the title checks it, except+// the game folder (descriptor game_root, profile paths, dxvk.path), which names move.from and is+// checked at move.to. Profile, catalog and metadata in the private data root are hash-checked.+PackageActionResult VerifyMovedPublication(const RuntimeInstall& record, const GameRootMove& move,+ const std::string& receipt_bytes, const std::string& metadata_bytes,+ const std::filesystem::path& host_namespace_prefix = {});+enum class PublicationStep {kOwnerBlocked, kJournalDurable, kPendingDurable, kFilesApplied,kPendingVerified, kCommitDurable, kCommitVerified, kPreviousArchived,@@ -55,6 +70,9 @@ struct PublicationDependencies {// record is durably Ready at its revision). Missing callback refuses retirement.std::function<PackageActionResult(const SettingsPublicationOperation& previous,const SettingsPublicationOperation& next)> authorize_retirement;+ // Set while the record is marked moved: the journal being retired then names the old game+ // folder and is checked with VerifyMovedPublication instead of verify_files.+ std::optional<GameRootMove> moved_root;// Optional diagnostic fault seam after durable effects. False stops the call;// caller must reconstruct/reload. Production leaves this empty.std::function<bool(PublicationStep)> after_step;@@ -92,9 +110,10 @@ PackageActionResult ApplyPendingPublicationFiles(const SettingsPublicationOperat// prior committed complete set; live dxvk.conf and user.reg must equal their frozen// before-snapshots. Leftover files at new destinations are not refused (the apply// writes over them). Never writes.+// With moved, a previous publication that names moved->from is checked with VerifyMovedPublication.PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperation& operation,const PublicationPaths& paths, int borrowed_publisher_fd,- const std::filesystem::path& host_namespace_prefix = {});+ const std::filesystem::path& host_namespace_prefix = {}, const GameRootMove* moved = nullptr);// Builds and freezes one operation from the exact supplied plan and live before// snapshots. Caller independently approves reserved OWNER/package provenance,// positively stopped activity and the borrowed exclusive lease. Control/lock@@ -102,5 +121,6 @@ PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperatResult<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const RuntimeInstall& record, const SettingsLaunchPlan& plan, const std::string& kit_id,const std::string& transaction_id, std::int64_t registry_unix_time,- int borrowed_publisher_fd, const std::filesystem::path& host_namespace_prefix = {});+ int borrowed_publisher_fd, const std::filesystem::path& host_namespace_prefix = {},+ const GameRootMove* moved = nullptr);} // namespace playden::runtimediff --git a/src/runtime/settings_publication_owner.cpp b/src/runtime/settings_publication_owner.cppindex 85ad136..0035073 100644--- a/src/runtime/settings_publication_owner.cpp+++ b/src/runtime/settings_publication_owner.cpp@@ -39,6 +39,11 @@ PublicationPaths OperationPaths(const SettingsPublicationOperation& operation, cmap("/data/homebrew/" + operation.install.title_id + "/game-launch.json"),map(profiles + ".playden-publication")};}+// A Ready update publishes a newer revision, or the same one again when the game folder+// moved (RuntimeInstall::moved_from): its publication must then name the new folder.+bool UpdateRevisionAllowed(const RuntimeInstall& current, std::uint64_t requested) {+ return requested > current.settings_revision || (requested == current.settings_revision && !current.moved_from.empty());+}bool MatchingJournal(const RuntimeInstall& r, const SettingsPublicationOperation& o) {return r.journal && r.journal->operation == "settings-publication" && r.journal->operation_id == o.transaction_id;}@@ -52,7 +57,7 @@ PackageActionResult SettingsPublicationOwner::Request(const SettingsPublicationRconst bool update = current && current->state == PreparationState::kReady;const bool armed = current && current->journal && current->journal->operation == "settings-request";if (!expected || !current || !SameRuntimeInstallIdentity(*current, request.install) ||- (update ? request.plan.settings_revision <= current->settings_revision :+ (update ? !UpdateRevisionAllowed(*current, request.plan.settings_revision) :request.plan.settings_revision != current->settings_revision) ||(update ? !ReadyCaptureAllowed(*current, request.transaction_id) :current->state != PreparationState::kPreparing || !current->journal ||@@ -102,7 +107,7 @@ PackageActionResult SettingsPublicationOwner::ResumeRequested(const RuntimeInstaauto loaded = LoadSettingsPublicationRequest(directory, current->journal->operation_id);if (loaded.state != PublicationRecoveryState::kValid || !loaded.request ||!SameRuntimeInstallIdentity(loaded.request->install, *current) ||- (current->state == PreparationState::kReady ? loaded.request->plan.settings_revision <= current->settings_revision :+ (current->state == PreparationState::kReady ? !UpdateRevisionAllowed(*current, loaded.request->plan.settings_revision) :loaded.request->plan.settings_revision != current->settings_revision))return Failure("publication-request-unavailable", "Requested plan is missing, altered or does not match OWNER; preserve all evidence.");const auto& request = *loaded.request;@@ -111,7 +116,7 @@ PackageActionResult SettingsPublicationOwner::ResumeRequested(const RuntimeInsta// Capture durably freezes snapshots/backups. Publication reacquires the// qualified lease, verifies prior committed semantics and rechecks OWNER// before any effects. The Ready request arm blocks Play during this handoff.- auto dependencies = Dependencies(prefix);+ auto dependencies = Dependencies(prefix, GameRootMoveOf(*current));return PublishSettingsOperation(prepared.value(), OperationPaths(prepared.value(), prefix), dependencies);}PackageActionResult SettingsPublicationOwner::InitializeControl(const RuntimeInstall& record, const std::string& transaction,@@ -267,7 +272,9 @@ Result<SettingsPublicationOperation> SettingsPublicationOwner::Prepare(const Run// rest is the durable record's.auto snapshot = *current; snapshot.settings_revision = record.settings_revision;CommitLaunch(&snapshot, record);- auto captured = CaptureSettingsPublicationOperation(snapshot, plan, kit, transaction, time, lease->fd(), prefix);+ const auto moved = GameRootMoveOf(*current);+ auto captured = CaptureSettingsPublicationOperation(snapshot, plan, kit, transaction, time, lease->fd(), prefix,+ moved ? &*moved : nullptr);if (!captured.ok()) return captured;if (!lease->Validate(*control, "publication.lock"))return fail("The publication lock changed before the capture was saved.");@@ -339,7 +346,7 @@ PackageActionResult SettingsPublicationOwner::Resume(const RuntimeInstall& recorconst PublicationPaths paths{map(profiles + operation->plan.profile_id + ".profile"), map(profiles + "profiles.lst"),map(operation->install.data_root + "/library/input"),map("/data/homebrew/" + operation->install.title_id + "/game-launch.json"), map(profiles + ".playden-publication")};- auto dependencies = Dependencies(prefix);+ auto dependencies = Dependencies(prefix, GameRootMoveOf(*current));return PublishSettingsOperation(*operation, paths, dependencies);}PackageActionResult SettingsPublicationOwner::Persist(const RuntimeInstall& record) {@@ -388,7 +395,8 @@ PackageActionResult SettingsPublicationOwner::Reconcile(const SettingsPublicatioif (!o.previous_receipt_bytes.empty()) {record->state = PreparationState::kReady; record->settings_revision = o.plan.settings_revision;CommitLaunch(&*record, o.install);- record->journal.reset(); record->last_failure.reset();+ // Built from the record's install_path: a moved game folder is now the one published.+ record->journal.reset(); record->last_failure.reset(); record->moved_from.clear();return Persist(*record);}auto status = native_.QueryOwnership(o.install);@@ -419,7 +427,7 @@ PackageActionResult SettingsPublicationOwner::Reconcile(const SettingsPublicatio}record->state = PreparationState::kReady; record->settings_revision = o.plan.settings_revision;CommitLaunch(&*record, o.install);- record->journal.reset(); record->last_failure.reset();+ record->journal.reset(); record->last_failure.reset(); record->moved_from.clear();return Persist(*record);}PackageActionResult SettingsPublicationOwner::AuthorizeRetirement(const SettingsPublicationOperation& previous,@@ -428,17 +436,24 @@ PackageActionResult SettingsPublicationOwner::AuthorizeRetirement(const Settings// Retiring the previous journal needs only that it was committed: the record is// Ready at its revision with this update's request armed. Ownership is checked// once, by Block, before this apply changes anything.- if (!record || !SameRuntimeInstallIdentity(*record, previous.install) || !SameRuntimeInstallIdentity(*record, next.install) ||+ // The journal of a game folder that moved names the old folder.+ auto earlier = previous.install;+ if (const auto moved = record ? GameRootMoveOf(*record) : std::nullopt; moved && earlier.install_path == moved->from)+ earlier.install_path = moved->to;+ if (!record || !SameRuntimeInstallIdentity(*record, earlier) || !SameRuntimeInstallIdentity(*record, next.install) ||!ReadyCaptureAllowed(*record, next.transaction_id) ||record->settings_revision != previous.plan.settings_revision)return Failure("publication-retirement-owner", "Previous operation lacks a coherent durable Ready OWNER record.");return {PackageActionState::kComplete, {}, {}};}-PublicationDependencies SettingsPublicationOwner::Dependencies(const std::filesystem::path& prefix) {- PublicationDependencies deps; deps.host_namespace_prefix = prefix;+PublicationDependencies SettingsPublicationOwner::Dependencies(const std::filesystem::path& prefix,+ std::optional<GameRootMove> moved) {+ PublicationDependencies deps; deps.host_namespace_prefix = prefix; deps.moved_root = moved;deps.activity = [this](const RuntimeInstall& r) { return native_.Activity(r.title_id); };deps.block_owner = [this](const auto& o) { return Block(o); };- deps.preflight = [prefix](const auto& o, const auto& paths, int fd) { return PreflightSettingsPublication(o, paths, fd, prefix); };+ deps.preflight = [prefix, moved](const auto& o, const auto& paths, int fd) {+ return PreflightSettingsPublication(o, paths, fd, prefix, moved ? &*moved : nullptr);+ };deps.apply_files = [prefix](const auto& o, const auto& paths, int fd) { return ApplyPendingPublicationFiles(o, paths, fd, prefix); };deps.verify_files = [prefix](const auto& o, const auto& paths, int fd, bool committed) {return VerifySettingsPublicationFiles(o, paths, fd, committed, prefix);diff --git a/src/runtime/settings_publication_owner.h b/src/runtime/settings_publication_owner.hindex 3e8e678..e692fc1 100644--- a/src/runtime/settings_publication_owner.h+++ b/src/runtime/settings_publication_owner.h@@ -33,7 +33,9 @@ class SettingsPublicationOwner {// coordinator rechecks ownership/receipt and reconciles durable Ready.PackageActionResult Resume(const RuntimeInstall& record,const std::filesystem::path& host_namespace_prefix = {});- PublicationDependencies Dependencies(const std::filesystem::path& host_namespace_prefix = {});+ // With moved (the record's GameRootMoveOf), the previous publication may name the old game folder.+ PublicationDependencies Dependencies(const std::filesystem::path& host_namespace_prefix = {},+ std::optional<GameRootMove> moved = std::nullopt);private:PackageActionResult Block(const SettingsPublicationOperation& operation);PackageActionResult Reconcile(const SettingsPublicationOperation& operation);diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 03ff900..db85dda 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -1,6 +1,7 @@#include "homebrew/runtime_host.hpp"#include "platform/managed_directory.h"#include "platform/storage.h"+#include "runtime/layout_migration.h"#include "runtime/artifact_hash.h"#include <algorithm>@@ -2227,6 +2228,337 @@ void ShippedRecipeRequirementsFollowTheKit(bool template_audio_ps5) {host.Shutdown();}+// The 0.5 layout moves /data/homebrew/FAKE77031/games to /data/playden-games in one rename at+// startup. The runtime host then rewrites the records and republishes each moved Ready game, so+// its descriptor, profile and dxvk.conf name the new folder and it starts from Home again.+struct GamesMove {+ std::mutex mutex;+ std::optional<std::pair<std::string, std::string>> journal; // at "games-moved"+ int done = 0;+ std::vector<std::string> lines;+ void Wire(RuntimeHostConfig& config) {+ config.moved_games_root = [this] { std::lock_guard<std::mutex> lock(mutex); return journal; };+ config.finish_games_move = [this](std::string*) {+ std::lock_guard<std::mutex> lock(mutex);+ journal.reset(); ++done;+ return true;+ };+ config.log = [this](const std::string& line) { std::lock_guard<std::mutex> lock(mutex); lines.push_back(line); };+ }+ bool Logged(const std::string& prefix) {+ std::lock_guard<std::mutex> lock(mutex);+ return std::any_of(lines.begin(), lines.end(), [&](const std::string& line) { return line.rfind(prefix, 0) == 0; });+ }+ int Done() { std::lock_guard<std::mutex> lock(mutex); return done; }+};+constexpr const char* kOldGames = "/data/homebrew/FAKE77031/games";+constexpr const char* kNewGames = "/data/playden-games";++RuntimeHostConfig MoveConfig(Fixture& fixture, const RuntimeKit& kit, unsigned* uuids, GamesMove& move) {+ auto config = fixture.Config();+ config.host_namespace_prefix = fixture.root;+ config.session_data_root = fixture.root / "data";+ config.package_paths.console_data_root = "/data";+ config.package_paths.host_data_root = fixture.root / "data";+ config.package_operations.hash_file = HashArtifactFile;+ config.package_operations.hash_bytes = HashArtifactBytes;+ config.package_operations.free_space_unverifiable = true;+ config.package_operations.validate_bottle = [](const fs::path& bottle) {+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");+ };+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };+ config.uuid = [uuids]() -> std::optional<std::string> {+ char id[37]; std::snprintf(id, sizeof(id), "00000000-0000-4000-8000-%012u", ++*uuids);+ return std::string(id);+ };+ config.unix_time = [] { return std::int64_t{1760000000}; };+ config.settings_record = [](std::uint32_t) -> std::optional<GameSettingsRecord> {+ GameSettingsRecord saved; saved.revision = 1; saved.overrides = {{"resolution", "1280x720"}};+ return saved;+ };+ config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };+ move.Wire(config);+ return config;+}++// HL2 prepared under the old games root, with an install script and a Cloud index; then the+// startup rename moves the tree, and the journal says so.+void PrepareThenMoveGames(Fixture& fixture, const RuntimeHostConfig& config, GamesMove& move) {+ const auto old_games = fixture.root / "data/homebrew/FAKE77031/games";+ Write(old_games / "220/hl2.exe", "existing-game", 0644);+ CHECK(chmod((old_games / "220").c_str(), 0755) == 0);+ Write(old_games / "220/installscript.vdf",+ "\"InstallScript\"\n{\n \"Registry\"\n {\n \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Valve\\\\HL2\"\n {\n"+ " \"string\"\n {\n \"Installed Path\" \"%INSTALLDIR%\\\\\"\n }\n }\n }\n}\n", 0644);+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kit_available);+ host.Prepare(Hl2());+ const auto ready = WaitFor(host, [](const RuntimeSnapshot& s) {+ return !s.preparing_app && (s.refusals.count(220) || (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));+ }, 60);+ if (ready.refusals.count(220)) std::fprintf(stderr, "Prepare refused: %s\n", ready.refusals.at(220).c_str());+ CHECK(!ready.refusals.count(220) && ready.installs[0].settings_revision == 1);+ host.Shutdown();+ }+ const auto system_reg = Read(fixture.root / "data/playden/games/steam-220/library/prefixes/game/system.reg");+ CHECK(system_reg.find("FAKE77031\\\\games\\\\220") != std::string::npos);+ Write(old_games / ".playden-saves/220/cloud-index.txt",+ "version=1\naccount=a\nchange=7\ngame_root=/data/homebrew/FAKE77031/games/220\n"+ "prefix_root=/data/playden/games/steam-220/library/prefixes/game\nrule\tg\t1\tsave\t*\tsave/\n"+ "file\tg\t3\t5\tsave/game_root=/data/homebrew/FAKE77031/games/220\n", 0644);+ fs::rename(old_games, fixture.root / "data/playden-games");+ std::lock_guard<std::mutex> lock(move.mutex);+ move.journal = std::make_pair(std::string(kOldGames), std::string(kNewGames));+}++// What the moved game's published files and record name after the move finished.+void CheckRepublishedAtNewRoot(Fixture& fixture) {+ const auto records = Read(fixture.root / "data/runtime-state/installs.json");+ CHECK(records.find(R"("install_path":"/data/playden-games/220")") != std::string::npos);+ CHECK(records.find("moved_from") == std::string::npos && records.find("FAKE77031") == std::string::npos);+ const auto descriptor = Read(fixture.root / "data/homebrew/FAKE78001/game-launch.json");+ CHECK(descriptor.find(R"("game_root":"/data/playden-games/220")") != std::string::npos);+ CHECK(descriptor.find(R"("settings_revision":1)") != std::string::npos);+ const auto profiles = fixture.root / "data/playden/games/steam-220/library/profiles";+ const auto profile = Read(profiles / "playden-steam-220.profile");+ CHECK(profile.find("playden-games") != std::string::npos && profile.find("FAKE77031") == std::string::npos);+ CHECK(profile.find("desktop = 1280x720") != std::string::npos); // the saved settings are kept+ // The metadata keeps paths in hex.+ const auto hex = [](const std::string& text) {+ std::string out;+ for (const unsigned char c : text) { char pair[3]; std::snprintf(pair, sizeof(pair), "%02x", c); out += pair; }+ return out;+ };+ const auto metadata = Read(profiles / ".playden-publication");+ CHECK(metadata.find("dxvk.path_hex=" + hex("/data/playden-games/220/dxvk.conf") + "\n") != std::string::npos);+ // The install script's path follows the folder (ApplySteamworks runs in the republication).+ const auto system_reg = Read(fixture.root / "data/playden/games/steam-220/library/prefixes/game/system.reg");+ CHECK(system_reg.find("playden-games\\\\220") != std::string::npos && system_reg.find("FAKE77031") == std::string::npos);+}++void MigrationRewritesInstallPathsAndRepublishes() {+ Fixture fixture;+ GamesMove move;+ auto kit = SyntheticKit(fixture.root / "kit");+ kit.capabilities = {"dxvk", "offline_bottle", "per_game_title", kKitDxvkConfig, "wow64_i386"};+ unsigned uuids = 0;+ const auto config = MoveConfig(fixture, kit, &uuids, move);+ PrepareThenMoveGames(fixture, config, move);+ const auto registrations = fixture.registry_mutations;++ RuntimeHost host(config);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.installs.size() == 1 && started.installs[0].state == PreparationState::kReady);+ CHECK(started.installs[0].admission == "ok" && started.installs[0].settings_revision == 1);+ CHECK(move.Logged("startup moved app=220 republished") && move.Done() == 1);+ CheckRepublishedAtNewRoot(fixture);+ // No new registration: the title stays the one Home lists.+ CHECK(fixture.registry_mutations == registrations);+ // The Cloud index follows the game folder; the bottle (prefix_root) did not move.+ const auto index = Read(fixture.root / "data/playden-games/.playden-saves/220/cloud-index.txt");+ CHECK(index == "version=1\naccount=a\nchange=7\ngame_root=/data/playden-games/220\n"+ "prefix_root=/data/playden/games/steam-220/library/prefixes/game\nrule\tg\t1\tsave\t*\tsave/\n"+ "file\tg\t3\t5\tsave/game_root=/data/homebrew/FAKE77031/games/220\n");+ // Play passes the title's whole start check.+ host.Play(220);+ const auto played = WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready || s.play_refusals.count(220); }, 30);+ if (played.play_refusals.count(220)) std::fprintf(stderr, "Play refused: %s\n", played.play_refusals.at(220).c_str());+ CHECK(played.handoff_ready);+ host.Shutdown();+ // Nothing is left to do on the next start.+ RuntimeHost again(config);+ CHECK(again.Start());+ WaitFor(again, Started);+ CHECK(move.Done() == 1);+ again.Shutdown();+}++// A moved game whose title was busy at startup is republished by Play first, which says so.+void PlayBeforeRepublishRepublishesFirst() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ auto config = MoveConfig(fixture, kit, &uuids, move);+ std::vector<std::string> progress;+ std::shared_ptr<RuntimeHost*> current = std::make_shared<RuntimeHost*>(nullptr);+ const auto log = config.log;+ config.log = [log, current, &progress](const std::string& line) {+ log(line);+ // Settings update requests run inside Play's republication; its progress text is up meanwhile.+ if (line.rfind("settings update request app=220", 0) == 0 && *current) {+ const auto shared = (*current)->Shared();+ if (const auto found = shared->play_progress.find(220); found != shared->play_progress.end())+ progress.push_back(found->second);+ }+ };+ PrepareThenMoveGames(fixture, config, move);+ fixture.activity->store(static_cast<int>(NativeActivity::kActive));+ RuntimeHost host(config);+ *current = &host;+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(move.Logged("startup moved app=220 waits: Close the game first.") && move.Done() == 0);+ // The mark is durable; the published descriptor still names the old folder.+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find(R"("moved_from":"/data/homebrew/FAKE77031/games/220")") !=+ std::string::npos);+ CHECK(started.installs[0].state == PreparationState::kReady);+ CHECK(Read(fixture.root / "data/homebrew/FAKE78001/game-launch.json").find(kOldGames) != std::string::npos);+ // While it runs, Play says why it can't update the game.+ host.Play(220);+ const auto refused = WaitFor(host, [](const RuntimeSnapshot& s) { return s.play_refusals.count(220) != 0; });+ CHECK(refused.play_refusals.at(220) == "This game needs an update for Playden 0.5 first: Close the game first.");+ fixture.activity->store(static_cast<int>(NativeActivity::kStopped));+ host.Play(220);+ const auto played = WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready; }, 30);+ CHECK(played.play_progress.empty() && !played.play_refusals.count(220));+ CHECK(progress == std::vector<std::string>{kPlayUpdatingForLayout});+ CHECK(move.Logged("play moved app=220 republished") && move.Done() == 1);+ CheckRepublishedAtNewRoot(fixture);+ CHECK(host.Handoff());+ *current = nullptr;+ host.Shutdown();+}++// USB and M.2 installs, and folders that only share the old root's spelling, keep their paths.+void MigrationSkipsRecordsOutsideOldPrefix() {+ Fixture fixture;+ auto config = fixture.Config(); // no kit: the records are rewritten all the same+ // The real layout journal on state_root (no injected callbacks).+ fs::create_directories(config.state_root); CHECK(chmod(config.state_root.c_str(), 0700) == 0);+ const std::vector<std::pair<std::uint32_t, std::string>> games = {+ {400, "/mnt/usb1/playden-games/400"}, {500, "/mnt/ext1/playden-games/500"},+ {600, "/data/homebrew/FAKE77031/games-old/600"}, {700, "/data/homebrew/FAKE77031/games"},+ {220, "/data/homebrew/FAKE77031/games/220"}};+ {+ playden::Storage storage(config.state_root.string());+ RuntimeInstallRepository repository(storage, "installs.json", [](const std::string&) {+ return NativeTitleAvailability{TitleAvailability::kFree, TitleAvailability::kFree};+ });+ CHECK(repository.Load().ok());+ int title = 1;+ for (const auto& [app, path] : games) {+ auto record = Record();+ ReserveRequest request;+ request.install_id = "steam-" + std::to_string(app); request.app_id = app;+ request.default_profile_id = record.default_profile_id; request.runtime_bundle_id = record.runtime_bundle_id;+ request.recipe_id = record.recipe_id; request.recipe_version = record.recipe_version;+ request.launch_entry_id = record.launch_entry_id; request.launch_path = record.launch_path;+ request.install_path = path; request.volume_id = record.volume_id;+ char id[10]; std::snprintf(id, sizeof(id), "FAKE78%03d", title++);+ request.kit_title_variants = {id};+ CHECK(repository.Reserve(request).ok());+ }+ }+ {+ // A trailing slash on the old root is ignored.+ const std::string journal = std::string(R"({"step":"games-moved","from":")") + kOldGames + R"(/","to":")" + kNewGames ++ R"(","postponed":0})";+ CHECK(playden::Storage(config.state_root.string()).WriteDurable(kLayoutJournal, playden::Bytes(journal.begin(), journal.end())).ok());+ }+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ host.Shutdown();+ playden::Storage storage(config.state_root.string());+ RuntimeInstallRepository repository(storage, "installs.json", {});+ CHECK(repository.Load().ok());+ std::map<std::uint32_t, RuntimeInstall> records;+ for (const auto& record : repository.Snapshot()) records[record.app_id] = record;+ CHECK(records.size() == 5);+ for (const std::uint32_t app : {400u, 500u, 600u}) {+ CHECK(records[app].moved_from.empty());+ CHECK(records[app].install_path == std::find_if(games.begin(), games.end(), [app](const auto& g) { return g.first == app; })->second);+ }+ CHECK(records[700].install_path == kNewGames && records[700].moved_from == "/data/homebrew/FAKE77031/games");+ CHECK(records[220].install_path == "/data/playden-games/220" && records[220].moved_from == "/data/homebrew/FAKE77031/games/220");+ // None was Ready, so nothing waits for a republication; the marks stay for their preparation.+ const auto finished = LoadLayoutJournal(config.state_root);+ CHECK(finished && finished->step == "done");+}++// The mark survives restarts: a start that can't republish (busy title) and one interrupted in+// the middle of the republication both leave the move to the next one, which finishes it.+void RestartDuringRepublishResumes() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ auto config = MoveConfig(fixture, kit, &uuids, move);+ PrepareThenMoveGames(fixture, config, move);+ fixture.activity->store(static_cast<int>(NativeActivity::kActive));+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ CHECK(move.Logged("startup moved app=220 waits:") && move.Done() == 0);+ host.Shutdown();+ }+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find("moved_from") != std::string::npos);+ // The next start's republication is cut off after its request is saved: the console stops+ // answering whether the title runs.+ fixture.activity->store(static_cast<int>(NativeActivity::kStopped));+ auto interrupted = config;+ const auto log = config.log;+ auto activity = fixture.activity;+ interrupted.log = [log, activity](const std::string& line) {+ log(line);+ if (line.rfind("settings update request app=220", 0) == 0) activity->store(static_cast<int>(NativeActivity::kUnknown));+ };+ {+ RuntimeHost host(interrupted);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(move.Logged("startup moved app=220 failed:") && move.Done() == 0);+ CHECK(started.installs[0].recovery_pending);+ host.Shutdown();+ }+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find("moved_from") != std::string::npos);+ // Restarted: the saved request is recovery, which Update resumes; Play says what is missing.+ fixture.activity->store(static_cast<int>(NativeActivity::kStopped));+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ CHECK(move.Done() == 0);+ host.Play(220);+ const auto refused = WaitFor(host, [](const RuntimeSnapshot& s) { return s.play_refusals.count(220) != 0; });+ CHECK(refused.play_refusals.at(220).rfind("This game needs an update for Playden 0.5 first: ", 0) == 0);+ host.Prepare({220, "/data/playden-games/220", "internal", "Half-Life \"2\""});+ const auto resumed = WaitFor(host, [](const RuntimeSnapshot& s) {+ return !s.preparing_app && s.prepares_handled > 0 && !s.installs.empty() && !s.installs[0].recovery_pending;+ }, 60);+ if (resumed.refusals.count(220)) std::fprintf(stderr, "Resume refused: %s\n", resumed.refusals.at(220).c_str());+ CHECK(!resumed.refusals.count(220) && resumed.installs[0].state == PreparationState::kReady);+ CHECK(move.Done() == 1);+ CheckRepublishedAtNewRoot(fixture);+ host.Play(220);+ CHECK(WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready; }, 30).handoff_ready);+ CHECK(host.Handoff());+ host.Shutdown();+}++// A moved game whose folder is gone from the new place is not published over: it keeps its mark+// and the move stays unfinished.+void MovedGameMissingAtNewRootKeepsTheMove() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ const auto config = MoveConfig(fixture, kit, &uuids, move);+ PrepareThenMoveGames(fixture, config, move);+ fs::remove_all(fixture.root / "data/playden-games/220");+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ CHECK(move.Logged("startup moved app=220 failed:") && move.Done() == 0);+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find("moved_from") != std::string::npos);+ CHECK(Read(fixture.root / "data/homebrew/FAKE78001/game-launch.json").find(kOldGames) != std::string::npos);+ host.Shutdown();+}+int main(int argc, char** argv) {CHECK(argc == 2);g_runtime_dir = argv[1];@@ -2260,6 +2592,11 @@ int main(int argc, char** argv) {ShippedRecipePreparesWithAnotherKitsRecipe();ShippedRecipeRequirementsFollowTheKit(false);ShippedRecipeRequirementsFollowTheKit(true);+ MigrationRewritesInstallPathsAndRepublishes();+ PlayBeforeRepublishRepublishesFirst();+ MigrationSkipsRecordsOutsideOldPrefix();+ RestartDuringRepublishResumes();+ MovedGameMissingAtNewRootKeepsTheMove();std::puts("runtime host tests passed");return 0;}diff --git a/tests/runtime_game_install_test.cpp b/tests/runtime_game_install_test.cppindex 9e28137..26bbcf5 100644--- a/tests/runtime_game_install_test.cpp+++ b/tests/runtime_game_install_test.cpp@@ -11,6 +11,7 @@#include <filesystem>#include <fstream>#include <limits>+#include <optional>#include <string>#include <unistd.h>#include <unordered_map>@@ -485,6 +486,48 @@ void RegistryRejectsSymlinksAndDoesNotTouchOldTemporaryFiles() {} // namespace+// The 0.5 games move: records under the old root are rewritten together, keep the old path as+// their mark (written only when set), and an invalid one leaves every record as it was.+void MovedRecordsRewriteTogetherAndKeepTheirMark() {+ CHECK(RebaseInstallPath("/data/homebrew/FAKE77031/games/220", "/data/homebrew/FAKE77031/games", "/data/playden-games") ==+ std::optional<std::string>("/data/playden-games/220"));+ CHECK(RebaseInstallPath("/data/homebrew/FAKE77031/games", "/data/homebrew/FAKE77031/games/", "/data/playden-games") ==+ std::optional<std::string>("/data/playden-games"));+ CHECK(!RebaseInstallPath("/data/homebrew/FAKE77031/games-old/1", "/data/homebrew/FAKE77031/games", "/data/playden-games"));+ CHECK(!RebaseInstallPath("/mnt/usb1/games/1", "/data/homebrew/FAKE77031/games", "/data/playden-games"));++ TemporaryDirectory directory;+ playden::Storage storage(directory.path);+ CHECK(storage.EnsureRootDirectory().ok());+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ auto first = Request("install-a"); first.install_path = "/data/homebrew/FAKE77031/games/220";+ auto second = Request("install-b"); second.app_id = 400; second.install_path = "/data/homebrew/FAKE77031/games/400";+ CHECK(repository.Reserve(first).ok() && repository.Reserve(second).ok());+ const auto unmarked = storage.ReadDurable("installs.json", 1 << 20);+ CHECK(unmarked.ok() && std::string(unmarked.value().begin(), unmarked.value().end()).find("moved_from") == std::string::npos);++ auto a = *repository.Find("install-a"), b = *repository.Find("install-b");+ a.moved_from = a.install_path; a.install_path = "/data/playden-games/220";+ b.moved_from = b.install_path; b.install_path = "/data/playden-games/400";+ auto invalid = b; invalid.moved_from = invalid.install_path; // the mark must name another place+ CHECK(!repository.UpdateAll({a, invalid}).ok());+ CHECK(repository.Find("install-a")->install_path == "/data/homebrew/FAKE77031/games/220");+ auto renamed = b; renamed.data_root = "/data/playden/games/other";+ CHECK(!repository.UpdateAll({a, renamed}).ok());+ CHECK(repository.UpdateAll({a, b}).ok());++ RuntimeInstallRepository restarted(storage, "installs.json", Free);+ CHECK(restarted.Load().ok());+ CHECK(restarted.Find("install-a")->install_path == "/data/playden-games/220" &&+ restarted.Find("install-a")->moved_from == "/data/homebrew/FAKE77031/games/220");+ CHECK(restarted.Find("install-b")->moved_from == "/data/homebrew/FAKE77031/games/400");+ auto cleared = *restarted.Find("install-a"); cleared.moved_from.clear();+ CHECK(restarted.Update(cleared).ok());+ RuntimeInstallRepository again(storage, "installs.json", Free);+ CHECK(again.Load().ok() && again.Find("install-a")->moved_from.empty() && !again.Find("install-b")->moved_from.empty());+}+int main() {JournalSyncFailureRequiresReloadBeforeFurtherEffects();JournalUpdateSyncFailureReconcilesPublishedState();@@ -500,6 +543,7 @@ int main() {DescriptorIdentifiersMatchTheNativeGrammar();RecordLimitDoesNotPublishAnUnreadableRepository();LaunchPathsUseTheSharedSteamPathContract();+ MovedRecordsRewriteTogetherAndKeepTheirMark();std::puts("runtime_game_install_test: all assertions passed");return EXIT_SUCCESS;}