XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
"""Combine frozen host/guest evidence without promoting a targeted profile to full acceptance."""
import argparse
import hashlib
import json
import math
import re
import statistics
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
REPORTER = "Tools/CSharpBoot/CreateReport.py"


def require(condition, message):
    if not condition:
        raise ValueError(message)


def read(path):
    return json.loads(Path(path).read_text(encoding="utf-8-sig"))


def digest(path):
    sha = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for chunk in iter(lambda: stream.read(1048576), b""):
            sha.update(chunk)
    return sha.hexdigest()


def project_path(relative):
    path = (ROOT / relative).resolve()
    require(path.is_relative_to(ROOT.resolve()), f"Path escapes project: {relative}")
    return path


def inventory(host=False):
    roots = ["Source", "Samples", "Tests", "Tools/NativeInputPatch", "Tools/JintCleanupPatch", "Tools/GcRuntimePatch", "assets/Browser", "assets/fonts", "assets/branding/console"] if host else [
        "Source", "Samples", "Tools", "assets/DesktopIcons", "assets/Browser", "assets/fonts", "assets/branding/console"]
    ignored = {"bin", "obj", "build"} if host else {"bin", "obj", "build", "target", "__pycache__"}
    native_host = {"NativeWebTransport.cs", "VectorFileIo.cs", "NativeDesktopInput.cs", "NativeKeyboardCapture.cs", "NativePointerCapture.cs"}
    result = {"Directory.Build.targets"}
    for relative_root in roots:
        base = ROOT / relative_root
        for path in base.rglob("*"):
            if not path.is_file() or ignored.intersection(path.relative_to(base).parts):
                continue
            relative = path.relative_to(ROOT).as_posix()
            if host and relative.startswith("Source/XFESystem.Kernel/") and path.name not in native_host:
                continue
            result.add(relative)
    return result


def check_sources(hashes, label, expected_inventory=None):
    require(isinstance(hashes, dict) and hashes, f"{label}: source hashes missing")
    if expected_inventory is not None:
        require(set(hashes) == expected_inventory, f"{label}: source inventory changed")
    for relative, expected in hashes.items():
        if relative == REPORTER:
            continue  # Never compiled; current postprocessor SHA256 is recorded separately.
        path = project_path(relative)
        require(path.is_file() and digest(path) == expected.lower(), f"{label}: source changed: {relative}")


def snapshot(receipt, label, strict):
    path = Path(receipt["SourceSnapshotPath"])
    require(digest(path) == receipt["SourceSnapshotSha256"], f"{label}: snapshot digest mismatch")
    hashes = read(path)
    check_sources(hashes, label, inventory() if strict else None)
    if receipt.get("CurrentHarnessSourceSnapshotPath"):
        current = Path(receipt["CurrentHarnessSourceSnapshotPath"])
        require(digest(current) == receipt["CurrentHarnessSourceSnapshotSha256"], f"{label}: harness snapshot digest mismatch")
        check_sources(read(current), label + " current harness", inventory() if strict else None)
    return hashes


def check_guest(receipt, label):
    require(receipt.get("Passed") is True, f"{label}: guest did not pass")
    require(receipt.get("ImageUnchanged") is True, f"{label}: image changed")
    require(receipt.get("QemuExitCode") == 0, f"{label}: QEMU did not exit cleanly")
    require(digest(receipt["ImagePath"]) == receipt["ImageSha256"], f"{label}: image digest mismatch")
    require(digest(receipt["KernelPath"]) == receipt["KernelSha256"], f"{label}: kernel digest mismatch")
    verification = receipt.get("ImageVerification")
    if verification:
        require(verification.get("GptPrimaryAndBackupVerified") is True and verification.get("FatMirrorsVerified") is True,
                f"{label}: GPT/FAT verification missing")
        require(verification["Files"]["System/Kernel.elf"] == receipt["KernelSha256"], f"{label}: image/kernel binding mismatch")


def coverage(receipt, key, minimum, label):
    checks = receipt.get(key)
    require(isinstance(checks, list) and len(checks) >= minimum, f"{label}: missing {key} coverage (minimum {minimum})")
    require(all(isinstance(check, str) and check.strip() for check in checks), f"{label}: malformed {key}")
    return len(checks)


def monitor_timing(receipt, required=False):
    for line in receipt.get("CompletedGuestMarkers", []):
        match = re.fullmatch(r"XFE_MONITOR_TIMING\|(\d+)\|TargetMilliHz\|(\d+)\|DriverConfirmedHz\|(\d+)\|VSync\|(\d+)\|Origin\|(.+)", line)
        if match:
            names = ["AdvertisedRefreshMilliHz", "RendererTargetMilliHz", "DriverConfirmedHz", "VSync"]
            return dict(zip(names, map(int, match.groups()[:4])), OriginAndTimingSource=match.group(5))
    require(not required, "Monitor timing diagnostic is missing")
    return None


def performance_summary(receipt, label):
    require(isinstance(receipt.get("DesktopPerformance"), dict), f"{label}: performance evidence missing")
    result = {}
    for name in (("Cursor", "Scroll", "Drag", "Resize") if receipt.get("DesktopV4Profile") else ("Cursor", "Scroll")):
        sample = receipt["DesktopPerformance"].get(name)
        require(isinstance(sample, dict) and sample.get("ActiveStableWindows"), f"{label}: {name} stable intervals missing")
        rates, copies = [], []
        for window in sample["ActiveStableWindows"]:
            seconds, frames, rate, pixels = (window[key] for key in
                ("Seconds", "Frames", "RendererFramesPerSecond", "AverageCopiedPixelsPerFrame"))
            require(isinstance(seconds, (int, float)) and math.isfinite(seconds) and seconds > 0
                    and all(isinstance(v, (int, float)) and math.isfinite(v) and v >= 0 for v in (frames, rate, pixels))
                    and (frames > 0 or rate == pixels == 0),
                    f"{label}: invalid performance window")
            require(math.isclose(rate, frames / seconds, rel_tol=1e-9), f"{label}: FPS/interval mismatch")
            require(window["FullCopyFallbacks"] == 0, f"{label}: full-copy fallback in activity")
            rates.append(rate); copies.append(pixels)
        median = statistics.median(rates)
        require(math.isclose(median, sample["ActiveStableMedianRendererFramesPerSecond"], rel_tol=1e-9), f"{label}: median mismatch")
        require(sample["FullCopyFallbacks"] == 0 and sample["PartialFrames"] > 0, f"{label}: partial-copy verification missing")
        require(math.isfinite(sample["LastRenderMilliseconds"]) and sample["LastRenderMilliseconds"] >= 0, f"{label}: invalid render duration")
        require(math.isfinite(sample["AverageCopiedPixelsPerFrame"]) and
                0 < sample["AverageCopiedPixelsPerFrame"] <= sample["FullScreenPixels"], f"{label}: invalid copied pixel count")
        require(math.isfinite(sample["RendererFramesPerSecond"]) and sample["RendererFramesPerSecond"] > 0 and
                sample["SampleWindowSecondsIncludingIdle"] > 0, f"{label}: invalid whole-window rate")
        require(sample["WholeWindowIncludesTrailingIdle"] is True and sample["TargetHz"] > 0, f"{label}: timing meaning missing")
        result[name] = {
            "ActiveStableMedianRendererFramesPerSecond": median,
            "ActiveStableMinimumRendererFramesPerSecond": min(rates), "ActiveStableMaximumRendererFramesPerSecond": max(rates),
            "ActiveStableWindows": sample["ActiveStableWindows"],
            "AverageCopiedPixelsPerFrame": sample["AverageCopiedPixelsPerFrame"],
            "StableAverageCopiedPixelsPerFrameRange": [min(copies), max(copies)],
            "FullScreenPixels": sample["FullScreenPixels"], "LastRenderMilliseconds": sample["LastRenderMilliseconds"],
            "FullCopyFallbacks": sample["FullCopyFallbacks"], "RendererTargetHz": sample["TargetHz"],
            "WholeWindowIncludingIdleRendererFramesPerSecond": sample["RendererFramesPerSecond"],
            "WholeWindowIncludingIdleSeconds": sample["SampleWindowSecondsIncludingIdle"],
            "HostWholeWindowRendererFramesPerSecond": sample.get("HostWholeWindowRendererFramesPerSecond"),
            "HostInputDispatchRateRequested": sample.get("HostInputDispatchRateRequested"),
            "MotionReuses": sample.get("MotionReuses", 0), "MotionPixels": sample.get("MotionPixels", 0),
            "ZeroFrameStableWindows": sample.get("ZeroFrameStableWindows"),
            "MaximumStableStatsGapSeconds": sample.get("MaximumStableStatsGapSeconds"),
            "MaximumObservedStatsGapSeconds": sample.get("MaximumObservedStatsGapSeconds"),
            "Meaning": "Renderer submissions, not display scanout. Whole-window statistics include trailing idle."
        }
    return result


def icon_provenance():
    base = ROOT / "assets/DesktopIcons"
    manifest, provenance = read(base / "Manifest.json"), read(base / "Provenance.json")
    require(provenance["Tool"] == "image_gen.imagegen" and provenance["Mode"] == "BuiltIn", "Icon tool provenance mismatch")
    require(provenance["TransparentBackground"] is True and provenance["WebReferences"] == [], "Icon source policy mismatch")
    require(digest(base / "Provenance.json") == manifest["ProvenanceSha256"], "Icon provenance changed")
    atlas = base / manifest["Atlas"]
    require(digest(atlas) == manifest["AtlasSha256"] and atlas.stat().st_size == manifest["AtlasByteLength"], "Icon atlas changed")
    require(manifest["IconCount"] == len(manifest["Icons"]) == len(provenance["Assets"]) == 9, "Incomplete icon family")
    originals = []
    with atlas.open("rb") as stream:
        for compiled, original in zip(manifest["Icons"], provenance["Assets"]):
            require(compiled["Name"] == original["Name"], "Icon order mismatch")
            path = (base / compiled["Source"]).resolve()
            require(path.is_relative_to(base.resolve()) and digest(path) == compiled["SourceSha256"], "Original generated PNG changed")
            stream.seek(compiled["ByteOffset"])
            require(hashlib.sha256(stream.read(compiled["ByteLength"])).hexdigest() == compiled["CompiledSha256"], "Compiled icon changed")
            tool_path = Path(original["BuiltInOutputPath"])
            if tool_path.exists():
                require(digest(tool_path) == compiled["SourceSha256"], "PNG copy differs from original built-in output")
            originals.append({"Name": compiled["Name"], "Source": path.relative_to(ROOT).as_posix(),
                              "SourceSha256": compiled["SourceSha256"], "CompiledSha256": compiled["CompiledSha256"],
                              "Prompt": original["Prompt"]})
    return {"Tool": "image_gen.imagegen", "Mode": "BuiltIn", "WebReferences": [], "OriginalPNGsUnchanged": True,
            "OriginalIcons": originals, "ProvenancePath": "assets/DesktopIcons/Provenance.json",
            "ProvenanceSha256": digest(base / "Provenance.json"), "ManifestSha256": digest(base / "Manifest.json"),
            "AtlasSha256": digest(atlas), "AssetNoticeSha256": digest(base / "AssetNotice.md"),
            "Compilation": manifest["Resampling"], "CreativePixelEditing": False}


def shim_provenance(boot, boot_path, required):
    path = boot_path.parent / "BootShimReceipt.json"
    if not path.exists():
        require(not required, "C# EFI helper receipt missing")
        return None
    require(digest(path) == boot["BootShimReceiptSha256"], "EFI helper receipt changed")
    receipt = read(path)
    require(digest(receipt["ArtifactPath"]) == receipt["ArtifactSha256"] == boot["BootShimSha256"], "EFI helper artifact binding mismatch")
    require(boot["ImageVerification"]["Files"]["EFI/BOOT/BOOTX64.EFI"] == receipt["ArtifactSha256"], "Image EFI helper mismatch")
    require(receipt["Language"] == "C# UEFI" and receipt["KernelLanguage"] == "C# NativeAOT", "EFI helper language boundary mismatch")
    check_sources(receipt["SourceSha256"], "EFI helper")
    return {"Language": "C#", "Role": "C# UEFI GOP/EDID initializer, then chainload Limine",
            "SourceDirectory": "Source/XFESystem.Boot", "SourceSha256": receipt["SourceSha256"],
            "ArtifactSha256": receipt["ArtifactSha256"], "ReceiptPath": str(path.resolve()), "ReceiptSha256": digest(path),
            "Toolchain": receipt["Toolchain"], "ChainloadPath": receipt["ChainloadPath"], "ImplementsVSync": False}


def build_warnings(path):
    if path is None:
        return {"KnownWarningCount": 100, "BuildLogBound": False,
                "Meaning": "Known NativeAOT/trimming limitations; this invocation did not bind a compiler log."}
    text = path.read_text(encoding="utf-8-sig", errors="replace")
    warnings = re.findall(r"^\s*(\d+)\s*(?:个警告|Warning\(s\)|warnings?)\s*$", text, re.M | re.I)
    errors = re.findall(r"^\s*(\d+)\s*(?:个错误|Error\(s\)|errors?)\s*$", text, re.M | re.I)
    require(warnings and errors and int(errors[-1]) == 0, "Native build warning/error summary missing or failed")
    return {"KnownWarningCount": int(warnings[-1]), "ErrorSummaryCount": 0, "BuildLogBound": True,
            "Path": str(path.resolve()), "Sha256": digest(path),
            "Meaning": "NativeAOT/trimming warnings remain; tested paths do not establish unrestricted dynamic/reflection compatibility."}


def validate_evidence(boot, display, host, dom, strict):
    require(host.get("Passed") is True and dom.get("Passed") is True, "Host/DOM did not pass")
    require(boot.get("TargetedDesktopProfile") is not True, "TargetedDesktopProfile cannot count as full Boot acceptance")
    require(boot.get("NativeHttpPassed") is True and boot.get("ManagedIlSucceeded") is True, "Full HTTP/managed coverage missing")
    check_guest(boot, "Boot"); check_guest(display, "Display")
    require(boot["KernelSha256"] == display["KernelSha256"], "Boot/Display kernels differ")
    require(display["DisplayMarker"] == "XFE_DISPLAY_NATIVE|3840|2160|ScalePercent|200", "4K/200% proof missing")
    boot_sources = snapshot(boot, "Boot", strict)
    display_sources = snapshot(display, "Display", strict)
    check_sources(host["SourceHashes"], "Host", inventory(host=True) if strict else None)
    for name, sources in (("Host", host["SourceHashes"]), ("Display", display_sources)):
        for relative in set(boot_sources).intersection(sources):
            require(relative == REPORTER or boot_sources[relative] == sources[relative], f"Boot/{name} source disagreement: {relative}")
    total = 0
    for suite in host["Suites"]:
        require(suite["Failed"] == 0 and suite["Passed"] > 0, "Host suite failed or empty")
        total += suite["Passed"]
    require(total > 0, "Host suites missing")
    for check in dom.get("Checks", []):
        require(check.get("Passed") is True, "DOM case failed")
    if dom.get("SourceHashes"):
        check_sources({"Source/XFESystem.Documents/" + key: value for key, value in dom["SourceHashes"].items()}, "Host DOM")
    counts = {"Baseline": coverage(boot, "Checks", 13 if strict else 1, "Boot"),
              "Http": coverage(boot, "NativeHttpChecks", 10 if strict else 1, "Boot"), "Desktop": 0, "ComparisonDesktop": 0}
    timing, other_timing = monitor_timing(boot, strict), monitor_timing(display, strict)
    performance = {}
    if strict:
        require(boot.get("Acceleration") == "whpx" and display.get("Acceleration") == "tcg", "V2 requires WHPX full plus TCG comparison")
        require(boot.get("DesktopUiPassed") is True and display.get("DesktopUiPassed") is True, "Desktop UI did not pass")
        require(boot["DisplayMarker"] == display["DisplayMarker"], "Performance comparison native geometry/scale differs")
        require(display.get("TargetedDesktopProfile") is True and display.get("NativeHttpPassed") is False, "TCG must be identified as UI-only")
        require(boot["ImageSha256"] == display["ImageSha256"], "Comparison image differs")
        require(boot["SourceSnapshotSha256"] == display["SourceSnapshotSha256"], "Comparison not bound to compiled-image snapshot")
        require(timing["VSync"] == other_timing["VSync"] == 0, "Explicit VSync=0 diagnostic missing")
        require(timing["RendererTargetMilliHz"] == other_timing["RendererTargetMilliHz"], "Comparison targets differ")
        counts["Desktop"] = coverage(boot, "DesktopUiChecks", 12, "Boot")
        counts["ComparisonDesktop"] = coverage(display, "DesktopUiChecks", 12, "Display")
        performance = {"WHPX": performance_summary(boot, "Boot"), "TCG": performance_summary(display, "Display")}
    return {"HostTotal": total, "Counts": counts, "Timing": timing, "ComparisonTiming": other_timing, "Performance": performance}


def performance_markdown(performance):
    if not performance:
        return "此旧版组合未计入第二轮窗口性能对照。"
    rows = ["| 加速器 / 活动 | 稳态提交 FPS 中位数(区间) | 平均复制像素/帧 | 最近绘制 ms | 含空闲整窗 FPS |",
            "| --- | --- | --- | --- | --- |"]
    for acceleration, workloads in performance.items():
        for name, sample in workloads.items():
            activity = {"Cursor": "鼠标移动", "Scroll": "文档滚动", "Drag": "窗口拖动", "Resize": "窗口缩放"}.get(name, name)
            rows.append(f"| {acceleration} / {activity} | "
                        f"{sample['ActiveStableMedianRendererFramesPerSecond']:.2f} "
                        f"({sample['ActiveStableMinimumRendererFramesPerSecond']:.2f}–{sample['ActiveStableMaximumRendererFramesPerSecond']:.2f}) | "
                        f"{sample['AverageCopiedPixelsPerFrame']:.0f} | {sample['LastRenderMilliseconds']:.3f} | "
                        f"{sample['WholeWindowIncludingIdleRendererFramesPerSecond']:.2f} |")
    return "\n".join(rows)


def validate_visual_evidence(receipt, label, desktop_v4=False):
    coverage(receipt, "DesktopUiChecks", 28 if desktop_v4 else 23, label)
    visual = receipt.get("DesktopVisualEvidence")
    require(isinstance(visual, dict), f"{label}: native visual evidence missing")
    for key in ("DesktopButton", "FilesToolbar", "SettingsDarkButton", "SettingsLightButton", "SettingsAccentField"):
        item = visual.get(key, {})
        require(item.get("HoverChangedNativePixels", 0) > 12 and item.get("PressedChangedNativePixels", 0) > 12,
                f"{label}: {key} hover/press pixel proof missing")
    caption = visual.get("Caption", {})
    require(caption.get("FormerMaximizeSquarePixels") == 0 and caption.get("NativeCornerDistinctColors", 0) >= 8,
            f"{label}: two-button caption/antialiasing proof missing")
    pointer = visual.get("ArrowCursor", {})
    require(pointer.get("DistinctBlendedColors", 0) >= 16 and pointer.get("BlueCorePixels", 0) > 0,
            f"{label}: native pointer coverage proof missing")
    band = visual.get("NativeTaskbarBand", {})
    require(band.get("FrameSize") == [3840, 2160] and band.get("NativeBottomPixel") != band.get("NativeDesktopPixel"),
            f"{label}: native bottom taskbar proof missing")
    appearance = visual.get("Appearance", {})
    require(appearance.get("DarkDesktopPixel") == [9, 18, 27] and appearance.get("CustomAccent") == "#14A8B4"
            and appearance.get("ChangedAccentNativePixels" if desktop_v4 else "ChangedHeaderNativePixels", 0) > 20 and appearance.get("Persistent") is False,
            f"{label}: legacy dark theme/custom accent/RAM scope proof missing")
    if desktop_v4:
        require(receipt.get("DesktopV4Profile") is True, f"{label}: V4 native profile was not executed")
        no_bar = visual.get("NoTopbar", {})
        require(no_bar.get("NativeTopPixel") == no_bar.get("NativeDesktopPixel") and no_bar.get("NativeTopPixel") is not None,
                f"{label}: no-topbar native pixel proof missing")
        for control in ("Minimize", "Close"):
            animation = visual.get("CaptionMotion", {}).get(control, {})
            for key in ("EnteringChangedPixels", "ReverseIntermediateChangedPixels", "EnteringToEndChangedPixels", "EnteringToReverseChangedPixels"):
                require(animation.get(key, 0) > 3, f"{label}: {control} real intermediate/reverse pixels missing")
            values = animation.get("ProgressPermille", [])
            require(values and all(isinstance(value, int) and 0 <= value <= 1000 for value in values)
                    and any(0 < last < first < 1000 for first, last in zip(values, values[1:])),
                    f"{label}: {control} continuous descending phase not observed")
            require(animation.get("RestoredDifferencePixels") == 0 and animation.get("RawCaptureBeforePngCompression") is True,
                    f"{label}: {control} raw-frame restoration evidence missing")
        for activity in ("Drag", "Resize"):
            motion = visual.get(activity + "Motion", {})
            require(motion.get("FullRedrawDifferencePixels") == 0 and motion.get("SameWindowBounds") is True,
                    f"{label}: {activity} full-redraw residue comparison failed")
        drag = receipt.get("DesktopPerformance", {}).get("Drag", {})
        require(drag.get("MotionReuses", 0) > 0 and drag.get("MotionPixels", 0) > 0,
                f"{label}: actual native pointer-free body reuse not exercised")
    return visual


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("Boot", "Display", "Host", "Dom", "Output"):
        parser.add_argument("--" + name, type=Path, required=True)
    parser.add_argument("--DesktopV2", action="store_true", help="Require complete WHPX acceptance plus identical-image TCG UI-only comparison")
    parser.add_argument("--DesktopV3", action="store_true", help="Also require themes, hover/press, native antialiasing and viewport plan evidence")
    parser.add_argument("--DesktopV4", action="store_true", help="Require caption intermediate/reverse frames, no-topbar desktop, measured motion and zero residue")
    parser.add_argument("--ViewportPlan", type=Path, help="Read-only PowerShell 5 launcher viewport regression receipt")
    parser.add_argument("--BuildLog", type=Path, help="Bind compiler warning/error summary and log SHA256")
    parser.add_argument("--BrowserNative", type=Path, help="Same-image native CSS/events/real Monaco receipt")
    parser.add_argument("--MonacoHost", type=Path, help="Independent production browser compatibility probe")
    parser.add_argument("--RuntimePatchHost", type=Path, help="Independent private GC/EH patch structural and host control receipt")
    parser.add_argument("--OomNegative", type=Path, help="Same-image deliberately halted native allocation-failure test")
    parser.add_argument("--WebsiteReference", type=Path, help="Chromium reference of the unmodified website article component")
    parser.add_argument("--WebsiteComparison", type=Path, help="Original-pixel QEMU versus website screenshot comparison")
    parser.add_argument("--CSharpReference", type=Path, help="Real website static code-block reference for the identical C# source")
    parser.add_argument("--CSharpComparison", type=Path, help="Native Monaco versus static website screenshot comparison, without UI parity claims")
    parser.add_argument("--PreviewPerformance", type=Path, help="Same-image physical-input Markdown responsiveness proof")
    parser.add_argument("--PreviewBaseline", type=Path, help="Older accepted image measured with the same physical-input profile")
    parser.add_argument("--GpuBoundary", type=Path, help="Source-bound GPU inventory and explicit native CUDA implementation boundary")
    parser.add_argument("--FirstPaintTcg", type=Path, help="Same-image real Markdown first-presentation proof before enhancement scripts (TCG)")
    parser.add_argument("--FirstPaintWhpx", type=Path, help="Same-image real Markdown first-presentation proof before enhancement scripts (WHPX)")
    parser.add_argument("--NativeDiscovery", type=Path, help="Native NVIDIA discovery scope and source-bound resource-validation checks; never CUDA acceptance")
    parser.add_argument("--RasterOracle", type=Path, help="Host-only full software-painter pixel comparison against the frozen baseline")
    parser.add_argument("--AncillaryChecks", type=Path, help="Font bytes, first-frame negative controls, media safety mocks and C# prerequisites")
    args = parser.parse_args()
    output = args.Output.resolve()
    require(output.is_relative_to((ROOT / "Validation").resolve()) and output.suffix.lower() == ".json", "Output must be a new JSON inside Validation")
    require(not output.exists() and not output.with_suffix(".md").exists(), "Refusing to overwrite existing report files")
    boot, display, host, dom = [read(path) for path in (args.Boot, args.Display, args.Host, args.Dom)]
    desktop_v4 = args.DesktopV4 or boot.get("DesktopV4Profile") is True
    desktop_v3 = desktop_v4 or args.DesktopV3 or bool(boot.get("DesktopVisualEvidence"))
    strict = desktop_v3 or args.DesktopV2 or boot.get("DesktopUiPassed") is True
    evidence = validate_evidence(boot, display, host, dom, strict)
    visuals = {"WHPX": validate_visual_evidence(boot, "Boot", desktop_v4), "TCG": validate_visual_evidence(display, "Display", desktop_v4)} if desktop_v3 else None
    viewport = None
    if desktop_v3:
        require(args.ViewportPlan is not None, "V3 requires the viewport plan receipt")
        viewport = read(args.ViewportPlan)
        require(viewport.get("Passed") is True and len(viewport.get("Checks", [])) >= 6, "Viewport plan regression failed")
        plans = {plan["Profile"]: plan["Display"] for plan in viewport.get("Plans", [])}
        require(plans.get("Default", {}).get("ZoomToFit") is True and plans["Default"].get("GuestFramebufferResolutionUnchanged") is True
                and plans["Default"].get("RequestedWindowStyle") == "Maximized", "Default viewport still clips the desktop")
        require(plans.get("NativePixels", {}).get("ZoomToFit") is False, "NativePixels opt-in proof missing")
        if desktop_v4:
            require(len(viewport.get("Checks", [])) >= 8 and viewport.get("ImageSha256") == boot["ImageSha256"], "V4 viewport plans belong to another image")
            require(all(plan.get("Acceleration") == "tcg" and plan.get("VerifiedTcgComparisonImageMatch") is True
                        and plan.get("VerifiedTcgReceiptSha256") == digest(args.Display) for plan in plans.values()),
                    "Interactive auto is not bound to the identical-image TCG proof")
        if args.FirstPaintWhpx:
            sdl_plans = viewport.get("SdlPlans", [])
            require(len(sdl_plans) == 2 and all(plan["Display"].get("DisplayBackend") == "sdl"
                    and plan["Display"].get("QemuDisplayArgument") == "sdl,gl=off"
                    and plan["Display"].get("HostGlEnabled") is False
                    and plan["Display"].get("VerifiedTcgComparisonImageMatch") is True for plan in sdl_plans),
                    "SDL launcher plans did not preserve the verified-image policy or disabled host GL")
    icons = icon_provenance() if strict else None
    shim = shim_provenance(boot, args.Boot.resolve(), strict)
    warnings = build_warnings(args.BuildLog)
    browser_native = monaco_host = runtime_patch_host = None
    if args.BrowserNative or args.MonacoHost:
        require(args.BrowserNative is not None and args.MonacoHost is not None, "Browser preview requires both native and host evidence")
        browser_native, monaco_host = read(args.BrowserNative), read(args.MonacoHost)
        check_guest(browser_native, "BrowserNative")
        require(browser_native["KernelSha256"] == boot["KernelSha256"] and browser_native["ImageSha256"] == boot["ImageSha256"], "Browser native proof uses a different image")
        require(browser_native["SourceSnapshotSha256"] == boot["SourceSnapshotSha256"], "Browser native source snapshot differs")
        snapshot(browser_native,"BrowserNative",strict)
        pipeline = browser_native.get("BrowserPipeline", {})
        require(pipeline.get("Passed") is True, "Native browser pipeline failed")
        coverage(pipeline,"Checks",8,"BrowserNative")
        require(pipeline.get("MonacoPointerExcluded",{}).get("OutsideCodeBands") is True
                and pipeline.get("MonacoReadyPaint",{}).get("ReadyPainted") is True
                and pipeline.get("MonacoEditedPaint",{}).get("Passed") is True,
                "Native Monaco glyph distribution and edited fourth-line ink evidence missing")
        require(pipeline.get("MonacoSyntaxPixels",0) > 0 and pipeline.get("MonacoInitialValue") != pipeline.get("MonacoEditedValue")
                and "xfenativeedit" in pipeline.get("MonacoEditedValue",""), "Actual native Monaco painting/editing proof missing")
        for shot in pipeline.get("Screenshots",[]):
            require(digest(shot["Path"]) == shot["Sha256"], "Native browser screenshot changed")
        require(monaco_host.get("Created") is True and monaco_host.get("SourceUnchangedDuringRun") is True
                and monaco_host.get("ManualWindowApiShims") is False and monaco_host.get("FakeMonacoObjects") is False
                and monaco_host.get("HostBrowserUsed") is False, "Host Monaco probe is not the production path")
        require(monaco_host.get("Stages") and all(stage.get("Passed") is True for stage in monaco_host["Stages"]), "Host Monaco stage failed")
        for source in monaco_host.get("BrowserSources",[]):
            require(digest(project_path(source["Path"])) == source["Sha256"], "Host Monaco probe source changed")
        for native in (boot,display,browser_native):
            require(native.get("MemoryMiB") == 1024,"Monaco preview requires the declared 1 GiB guest acceptance profile")
            markers = native.get("CompletedGuestMarkers",[])
            require("XFE_GC_DEEP_RESULT|True|Frames|321|Collections|2|FailureDepth|-1" in markers
                    and "XFE_EH_DEEP_RETHROW_OK|Frames|81|Post|4" in markers
                    and "XFE_BROWSER_EVENT_REGRESSION|Complete|PASS" in markers,"Native GC/event recovery regression missing")
            patches=native.get("PrivateRuntimePatches",{})
            require(set(patches)=={"Input","JintCleanup","GcTail"},"Native private runtime patch records missing")
            for name,attachment in patches.items():
                require(digest(attachment["Path"]) == attachment["Sha256"],"Runtime patch receipt changed")
                record=read(attachment["Path"])
                require(record.get("GlobalPackageCacheModified") is False and record["AfterSha256"]==attachment["RuntimeSha256"],"Runtime patch provenance invalid")
                if name=="JintCleanup": require(record["Version"]==2,"Jint cleanup V2 loop-reset guard missing")
                if name=="GcTail": require(record.get("EhCatchTrackingLimit")==4096 and record.get("EhOverflowFailFast") is True,
                                           "Native deep catch/rethrow safety fix missing")
                if name=="GcTail": require(record.get("AllocationGuardCount")==2 and record.get("ManagedAllocationGuardAfterIrqRestore") is True
                                           and record.get("PreGcAllocationGuardBeforeMemSet") is True, "Native allocation failure guards missing")
        require(monaco_host.get("ResourceOverrideUsed") is False and monaco_host.get("ExactCoreResourcesVerified") is True,"Host must exercise the default embedded core resources")
        require(args.RuntimePatchHost is not None, "GC/EH patch host verification is required")
        runtime_patch_host = read(args.RuntimePatchHost)
        require(runtime_patch_host.get("Passed") is True and runtime_patch_host.get("NativeGuestTested") is False
                and len(runtime_patch_host.get("Checks",[])) >= 36
                and all(check.get("Passed") is True for check in runtime_patch_host["Checks"]), "GC/EH patch structural verification failed")
        require(runtime_patch_host.get("PatchedSha256") == boot["PrivateRuntimePatches"]["GcTail"]["RuntimeSha256"],
                "GC/EH host verification uses a different private runtime")
    website = None
    if args.WebsiteReference or args.WebsiteComparison:
        require(args.WebsiteReference is not None and args.WebsiteComparison is not None and browser_native is not None,
                "V6 requires website reference, actual native browser and screenshot comparison")
        reference, comparison = read(args.WebsiteReference), read(args.WebsiteComparison)
        require(reference.get("Passed") is True and reference.get("GuestAcceptance") is False,
                "The website reference must be identified as host-only")
        require(comparison.get("ComparisonCompleted") is True and comparison.get("OriginalPixelsPreserved") is True
                and comparison.get("ImagesResized") is False and comparison.get("HostImageCountsAsNativeProof") is False,
                "The screenshot comparison must preserve original native/reference pixels")
        require(comparison["Native"]["ImageSha256"] == boot["ImageSha256"]
                and comparison["Native"]["AcceptancePassed"] is True, "Comparison is not from this accepted native image")
        for side in ("Native", "WebsiteReference"):
            require(digest(comparison[side]["ScreenshotPath"]) == comparison[side]["ScreenshotSha256"], "Compared screenshot changed")
        source_manifest = ROOT / "Source/XFESystem.Documents/Assets/Website/Exact/SourceManifest.json"
        require(comparison["WebsiteReference"]["WebsiteSourceManifestSha256"] == digest(source_manifest), "Website source manifest differs")
        doc = boot.get("WebsiteDocument", {})
        require(doc.get("Passed") is True and doc.get("HostReferenceCountsAsNativeProof") is False,
                "The Markdown fixture has not passed actual native input/paint checks")
        coverage(doc, "Checks", 4, "Native website document")
        require(doc.get("LightArticleBackground", {}).get("Passed") is True, "Native light-theme pixel checks missing")
        require(boot.get("EditorJavaScriptWebsitePreview", {}).get("Passed") is True
                and boot.get("EditorMarkdownWebsitePreview", {}).get("Passed") is True,
                "Actual desktop file preview proof missing")
        coverage(browser_native["BrowserPipeline"], "Checks", 12, "Native C# Monaco")
        require(browser_native["BrowserPipeline"].get("MonacoCSharp", {}).get("Passed") is True,
                "Actual C# model, token colors and framebuffer editing proof missing")
        require(monaco_host.get("Passed") is True and len(monaco_host.get("Stages", [])) >= 18,
                "Production C# host compatibility checks missing")
        bind = read(boot["PrivateRuntimePatches"]["JintCleanup"]["Path"])
        require(bind.get("BoundCallablePatchVersion") == 1, "Jint bound-callable fix is not verified in the native image")
        manifest = read(source_manifest)
        for item in manifest["Entries"]:
            require(item["SourceSha256"] == item["SnapshotSha256"], "An exact website source was transformed")
        website = {"NativeDocument": doc, "Reference": reference, "ScreenshotComparison": comparison,
                   "ExactWebsitePixelParityAccepted": comparison.get("ExactPixelMatch") is True,
                   "UserRequestedFullParityComplete": False,
                   "OriginalWebsiteResourceCount": len(manifest["Entries"]),
                   "WebsiteSourceManifestSha256": digest(source_manifest),
                   "ActualWebFontFallbacks": read(ROOT / "assets/fonts/lato-2.015/Manifest.json")["ActualWebFallbacks"],
                   "WebCjkFont": read(ROOT / "assets/fonts/noto-sans-sc-2.004/Manifest.json"),
                   "WebsiteIconFont": read(ROOT / "assets/fonts/bootstrap-icons-1.11.3/Manifest.json"),
                   "Scope": "Website article component and C# token classification; not the complete MVC site or a complete web platform"}
        if args.CSharpReference or args.CSharpComparison:
            require(args.CSharpReference is not None and args.CSharpComparison is not None, "C# screenshot evidence must include both sides")
            csharp_reference, csharp_comparison = read(args.CSharpReference), read(args.CSharpComparison)
            require(csharp_reference.get("Passed") is True and csharp_reference.get("GuestAcceptance") is False
                    and csharp_reference.get("Component") == "WebsiteStaticCSharpCodeBlock", "C# reference is not the actual static website component")
            require(csharp_comparison.get("ComparisonCompleted") is True and csharp_comparison.get("ImagesResized") is False
                    and csharp_comparison["Native"]["ImageSha256"] == boot["ImageSha256"], "C# screenshot is not from the accepted native image")
            native_source = browser_native["BrowserPipeline"]["MonacoCSharp"]["InitialDomReadback"]["ModelValue"]
            require(csharp_reference["ProductionSample"]["CodeSha256"] == __import__("hashlib").sha256(native_source.encode("utf-8")).hexdigest(), "C# screenshot sources differ")
            website["CSharpReference"] = csharp_reference
            website["CSharpScreenshotComparison"] = csharp_comparison
    counts = evidence["Counts"]
    oom_negative = read(args.OomNegative) if args.OomNegative else None
    if browser_native:
        require(oom_negative is not None and oom_negative.get("Kind") == "NativeOomNegativeProof"
                and oom_negative.get("Passed") is False and oom_negative.get("ImageUnchanged") is True
                and oom_negative.get("QemuExitCode") == 0 and oom_negative.get("MemoryMiB") == 512
                and oom_negative.get("ImageSha256") == boot["ImageSha256"]
                and oom_negative.get("KernelSha256") == boot["KernelSha256"]
                and oom_negative.get("SourceSnapshotSha256") == boot["SourceSnapshotSha256"], "Native OOM negative evidence does not match the image")
        failure = oom_negative.get("NativeOomNegative",{})
        require(failure.get("ExpectedAllocationFailureObserved") is True and failure.get("ArbitraryPageFault") is False
                and failure.get("ApplicationOrGuiRecovered") is False and failure.get("HostBrowserUsed") is False,
                "Native allocation guard was not actually exercised")
        snapshot(oom_negative,"OomNegative",strict)
    preview_performance = None
    gpu_boundary = None
    if args.PreviewPerformance or args.PreviewBaseline or args.GpuBoundary:
        require(all((args.PreviewPerformance,args.PreviewBaseline,args.GpuBoundary)), "Preview performance requires baseline, current and GPU boundary records")
        current, baseline, gpu_boundary = [read(path) for path in (args.PreviewPerformance,args.PreviewBaseline,args.GpuBoundary)]
        for label, receipt in (("Current preview",current),("Baseline preview",baseline)):
            check_guest(receipt,label)
            require(receipt.get("TargetedPreviewProfile") is True and receipt.get("Acceleration")=="tcg"
                    and receipt.get("MemoryMiB")==1024 and receipt.get("ResolutionRequested")=="3840x2160", label+": different performance configuration")
            measured=receipt.get("PreviewPerformance",{})
            require(measured.get("Passed") is True and measured.get("AutomaticDomInjection") is False
                    and len(measured.get("Samples",[]))==2,label+": actual input/paint evidence missing")
            for sample in measured["Samples"]:
                for key in ("ClickToActualDocumentSeconds","ClickToFirstVerifiedPaintSeconds","WinDResponseSeconds","CloseResponseSeconds"):
                    require(isinstance(sample.get(key),(int,float)) and math.isfinite(sample[key]) and sample[key]>0,label+": invalid timing")
        require(current["ImageSha256"]==boot["ImageSha256"] and current["KernelSha256"]==boot["KernelSha256"]
                and current["SourceSnapshotSha256"]==boot["SourceSnapshotSha256"],"Responsiveness proof differs from final image/source")
        snapshot(current,"PreviewPerformance",strict)
        require(gpu_boundary.get("Passed") is True and gpu_boundary.get("ActualGuestRasterization")=="CPU"
                and gpu_boundary.get("NativeCudaBackendImplemented") is False and gpu_boundary.get("NativeGpuBackendImplemented") is False
                and gpu_boundary.get("GuestCudaAcceleration")==0 and gpu_boundary.get("CudaRequestComplete") is False,
                "GPU boundary must not promote a selection policy to native acceleration")
        gpu_sources=gpu_boundary["CurrentSourceSnapshot"]
        require(digest(gpu_sources["Path"])==gpu_sources["Sha256"],"GPU source snapshot changed")
        for item in read(gpu_sources["Path"]):
            require(digest(project_path(item["Path"]))==item["Sha256"],"GPU boundary source changed: "+item["Path"])
        for attachment in gpu_boundary.get("Artifacts",[]):
            require(digest(attachment["Path"])==attachment["Sha256"],"GPU boundary attachment changed")
        keys=("ClickToActualDocumentSeconds","ClickToFirstVerifiedPaintSeconds","WinDResponseSeconds","CloseResponseSeconds")
        preview_performance={"Configuration":"TCG / 3840x2160 / 1 GiB / physical QMP input", "ActualGuestRasterization":"CPU",
            "BaselineImageSha256":baseline["ImageSha256"],"CurrentImageSha256":current["ImageSha256"],
            "Baseline":baseline["PreviewPerformance"],"Current":current["PreviewPerformance"],
            "BaselineMedianSeconds":{key:statistics.median(s[key] for s in baseline["PreviewPerformance"]["Samples"]) for key in keys},
            "CurrentMedianSeconds":{key:statistics.median(s[key] for s in current["PreviewPerformance"]["Samples"]) for key in keys},
            "ScrollHostSecondsIsFps":False,"ColdInitializationStillSlow":True,
            "BenchmarkConditions":"Sequential runs on the same host; not a deterministic CPU scheduling benchmark or scanout FPS measurement"}
        for key in ("WinDResponseSeconds","CloseResponseSeconds"):
            require(preview_performance["CurrentMedianSeconds"][key] < preview_performance["BaselineMedianSeconds"][key],
                    "Preview desktop response did not improve: "+key)
    first_paint = None
    if args.FirstPaintTcg or args.FirstPaintWhpx:
        require(args.FirstPaintTcg and args.FirstPaintWhpx, "First presentation requires both TCG and WHPX records")
        first_paint = {}
        for accelerator, path in (("tcg", args.FirstPaintTcg), ("whpx", args.FirstPaintWhpx)):
            receipt = read(path)
            check_guest(receipt, "FirstPaint " + accelerator)
            snapshot(receipt, "FirstPaint " + accelerator, strict)
            require(receipt["ImageSha256"] == boot["ImageSha256"] and receipt["KernelSha256"] == boot["KernelSha256"]
                    and receipt["SourceSnapshotSha256"] == boot["SourceSnapshotSha256"], "First paint uses a different image/source")
            require(receipt["Acceleration"] == accelerator and receipt["MemoryMiB"] == 1024
                    and receipt["NativeWidth"] == 3840 and receipt["NativeHeight"] == 2160, "First paint configuration differs")
            if accelerator == "whpx":
                require(receipt.get("DisplayBackend") == "sdl" and receipt.get("VisibleWindow", {}).get("Observed") is True
                        and receipt.get("HostGlEnabled") is False, "WHPX first paint needs an actual visible SDL window, with host GL disabled")
            measured = receipt.get("DocumentFirstPaint", {})
            require(measured.get("Passed") is True and measured.get("DomInjection") is False
                    and measured.get("GpuRendering") is False and measured.get("CudaExecution") is False
                    and len(measured.get("Samples", [])) == 2, "Missing first-paint actual-content proof")
            require(digest(measured["FixturePath"]) == measured["FixtureSha256"], "First-paint fixture changed")
            for sample in measured["Samples"]:
                for key in ("NativeClickToPresentedSeconds", "HostButtonDownToPresentationMarkerSeconds", "CloseAfterFirstFrameSeconds"):
                    require(isinstance(sample.get(key), (int, float)) and math.isfinite(sample[key]) and sample[key] > 0, "Invalid first-paint timing")
                require(sample["Frame"]["PixelEvidence"].get("HeadingAndParagraphPainted") is True
                        and digest(sample["Frame"]["Path"]) == sample["Frame"]["Sha256"], "First-paint actual screenshot changed or has no text")
                require(sample["Frame"].get("FirstFrameBinding", {}).get("FirstPresentedScanoutRegionsMatchScreenshot") is True,
                        "First-frame scanout bytes are not bound to the actual screenshot")
                require(sample["Proof"]["OriginalStyleCount"] == 9 and sample["Proof"]["ExecutedScriptCount"] == 0, "First stage omitted CSS or executed scripts")
                require(sample["UnderOneSecond"] == (sample["NativeClickToPresentedSeconds"] < 1 and sample["HostButtonDownToPresentationMarkerSeconds"] < 1), "First-paint timing objective misreported")
            require(measured["FirstPaintRequirementMet"] == all(sample["UnderOneSecond"] for sample in measured["Samples"]), "First-paint summary differs")
            first_paint[accelerator.upper()] = measured
        first_paint["BothConfigurationsUnderOneSecond"] = all(first_paint[key]["FirstPaintRequirementMet"] for key in ("TCG", "WHPX"))
        first_paint["EnhancementScriptsPreemptible"] = False
        first_paint["GpuAccelerationVerified"] = False
    discovery = raster_oracle = ancillary = None
    if args.NativeDiscovery:
        discovery = read(args.NativeDiscovery)
        require(discovery.get("Failed") == 0 and discovery.get("ResourceValidationTests", 0) >= 9
                and discovery.get("GpuRenderingImplemented") is False and discovery.get("CudaSubmissionVerified") is False
                and discovery.get("NoHostDriverChanges") is True, "NVIDIA discovery must not claim GPU execution")
        for source in discovery["SourceFiles"]:
            require(digest(project_path(source["Path"])) == source["Sha256"], "Native discovery source changed")
        require(any(line.startswith("XFE_NVIDIA_NATIVE_DISCOVERY|Count|0|CudaAcceleration|0|GpuRasterization|0")
                    for line in boot.get("NativeGpuDiagnostics", [])), "Actual virtual guest GPU-discovery diagnostic is missing")
    if args.RasterOracle:
        raster_oracle = read(args.RasterOracle)
        require(raster_oracle.get("Passed") is True and raster_oracle.get("HostOnly") is True
                and raster_oracle.get("GuestAcceptance") is False and len(raster_oracle.get("Cases", [])) == 2,
                "Full-pixel software oracle did not pass or is mislabeled")
        require(all(case.get("DifferingPixels") == 0 and case.get("ExactPixels") is True
                    and case["BaselinePixelsSha256"] == case["CurrentPixelsSha256"] for case in raster_oracle["Cases"]),
                "Software raster optimization changed pixels")
        check_sources(raster_oracle["SourceHashes"], "Software pixel oracle")
    if args.AncillaryChecks:
        ancillary = read(args.AncillaryChecks)
        require(ancillary.get("Passed") is True and ancillary.get("PhysicalDiskAccess") is False
                and len(ancillary.get("Checks", [])) >= 4, "Ancillary verification failed")
        for check in ancillary["Checks"]:
            require(check["Passed"] is True and check["ExitCode"] == 0 and digest(check["Path"]) == check["Sha256"], "Ancillary check/log failed")
    receipts = [("Boot", args.Boot), ("Display", args.Display), ("Host", args.Host), ("HostDom", args.Dom)]
    for name, path in (("NativeDiscovery", args.NativeDiscovery), ("RasterOracle", args.RasterOracle), ("AncillaryChecks", args.AncillaryChecks)):
        if path:
            receipts.append((name, path))
    if first_paint:
        receipts.extend([("FirstPaintTCG", args.FirstPaintTcg), ("FirstPaintWHPX", args.FirstPaintWhpx)])
    if preview_performance:
        receipts.extend([("PreviewPerformance",args.PreviewPerformance),("PreviewBaseline",args.PreviewBaseline),("GpuBoundary",args.GpuBoundary)])
    if browser_native:
        receipts.extend([("BrowserNative",args.BrowserNative),("MonacoHost",args.MonacoHost),
                         ("MonacoManifest",ROOT/"assets/Browser/Monaco/0.52.2/Manifest.json"),
                         ("MonacoCoreManifest",ROOT/"assets/Browser/Monaco/0.52.2/Core/TransformationManifest.json")])
        receipts.extend((name+"RuntimePatch",Path(item["Path"])) for name,item in boot["PrivateRuntimePatches"].items())
        receipts.append(("RuntimePatchHost",args.RuntimePatchHost))
        receipts.append(("OomNegative",args.OomNegative))
    if website:
        receipts.extend([("WebsiteReference", args.WebsiteReference), ("WebsiteComparison", args.WebsiteComparison),
                         ("WebsiteSourceManifest", ROOT / "Source/XFESystem.Documents/Assets/Website/Exact/SourceManifest.json"),
                         ("WebsiteCodeManifest", ROOT / "assets/Browser/WebsiteCode/Manifest.json"),
                         ("WebFontManifest", ROOT / "assets/fonts/lato-2.015/Manifest.json"),
                         ("WebCjkManifest", ROOT / "assets/fonts/noto-sans-sc-2.004/Manifest.json"),
                         ("WebsiteIconFontManifest", ROOT / "assets/fonts/bootstrap-icons-1.11.3/Manifest.json")])
        if args.CSharpReference:
            receipts.extend([("CSharpWebsiteReference", args.CSharpReference), ("CSharpScreenshotComparison", args.CSharpComparison)])
    if strict:
        receipts.extend([("IconManifest", ROOT / "assets/DesktopIcons/Manifest.json"),
                         ("IconProvenance", ROOT / "assets/DesktopIcons/Provenance.json"),
                         ("IconAssetNotice", ROOT / "assets/DesktopIcons/AssetNotice.md")])
    if shim:
        receipts.append(("EfiDisplayHelper", Path(shim["ReceiptPath"])))
    if args.BuildLog:
        receipts.append(("NativeBuildLog", args.BuildLog))
    if args.ViewportPlan:
        receipts.append(("ViewportPlan", args.ViewportPlan))
    for _, path in receipts:
        require(path.resolve().is_relative_to(ROOT.resolve()), "Receipt attachments must stay inside the project")
    removed_rust_roots = [".cargo", "boot", "crates", "kernel", "user", "xtask", "targets"]
    removed_rust_manifests = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml"]
    require(not any((ROOT / relative).exists() for relative in removed_rust_roots + removed_rust_manifests),
            "Legacy Rust source/build roots remain in the active tree")
    require(not any(project_path(relative).suffix.lower() == ".rs" for relative in inventory()), "Rust source remains in the active source inventory")
    proof = {
        "Schema": "XFESystem.CSharpPreview.Validation.V7" if first_paint else "XFESystem.CSharpPreview.Validation.V6" if website else "XFESystem.CSharpPreview.Validation.V5" if browser_native else "XFESystem.CSharpPreview.Validation.V4" if desktop_v4 else "XFESystem.CSharpPreview.Validation.V3" if desktop_v3 else "XFESystem.CSharpPreview.Validation.V2",
        "ValidationProfile": "CSharpOnlyPreview7.NativeFirstPresentationAndBrowser" if first_paint else "BrowserPreview6.WebsiteMarkdownAndCSharp" if website else "BrowserPreview5.CssEventsOfficialMonaco" if browser_native else "DesktopPreview4.MotionAndCaptionFrames" if desktop_v4 else "DesktopPreview3.AppearanceAndCoverage" if desktop_v3 else "DesktopPreview2.WHPX.FullPlusTCG.UiOnly" if strict else "LegacyPreview",
        "Branch": "codex/csharp-system", "Solution": "XFESystem.slnx",
        "PreviewValidated": True, "DesktopPreview2Validated": bool(strict), "CompleteSystemRewrite": False,
        "DesktopPreview3Validated": desktop_v3,
        "DesktopPreview4Validated": desktop_v4,
        "BrowserPreview5Validated": browser_native is not None,
        "BrowserPreview6Validated": website is not None,
        "WebsiteParity": website,
        "NativeBrowserPipeline": browser_native.get("BrowserPipeline") if browser_native else None,
        "MarkdownPreviewPerformance": preview_performance,
        "MarkdownFirstPresentation": first_paint,
        "NativeNvidiaDiscovery": discovery,
        "SoftwareRasterPixelOracle": raster_oracle,
        "AncillaryChecks": ancillary,
        "LatestUserRequirementsComplete": False,
        "SourceMigration": {"PrimarySystemLanguage": "C#", "LegacyRustSourceRemoved": True,
            "LegacyRustRootsRemoved": removed_rust_roots, "LegacyRustManifestsRemoved": removed_rust_manifests,
            "RustCompilerRequired": False, "CSharpEfiBootVerified": shim is not None,
            "HistoricalReleaseArtifactsPreserved": True, "OtherArchitectureCSharpSupportAccepted": False},
        "GpuDeliveryBoundary": gpu_boundary,
        "NativeGpuAccelerationImplemented": False, "NativeCudaAccelerationImplemented": False,
        "MonacoHostCompatibility": monaco_host,
        "RuntimePatchHostControl": runtime_patch_host,
        "NativeOomNegative": oom_negative.get("NativeOomNegative") if oom_negative else None,
        "Kernel": "C# NativeAOT with pinned Cosmos 3.0.94 runtime, GC and HAL",
        "LinuxGuestKernel": False, "WindowsGuestKernel": False, "Architecture": "x86_64",
        "FullDotNet10": False, "CoreClr": False, "Framework48": False, "ManagedProfile": "XFESystem.Net10.ConsoleIL.v1",
        "HostTestsPassed": evidence["HostTotal"], "HostDomPassed": True,
        "DefaultDesktopTheme": boot.get("DefaultAppearance", {}).get("Mode"),
        "DefaultAppearance": boot.get("DefaultAppearance"),
        "GuestGuiCheckCount": counts["Baseline"], "GuestHttpCheckCount": counts["Http"],
        "GuestDesktopUiCheckCount": counts["Desktop"], "ComparisonDesktopUiCheckCount": counts["ComparisonDesktop"],
        "ComparisonIncludesHttpAcceptance": False, "GuestHttpPassed": True, "GuestHttps": False, "GuestManagedDllPassed": True,
        "KernelSha256": boot["KernelSha256"], "ImagePath": boot["ImagePath"], "ImageSha256": boot["ImageSha256"],
        "MemoryMiB": boot.get("MemoryMiB"), "Monaco512MiBAccepted": False,
        "ComparisonImageSha256": display["ImageSha256"], "IdenticalComparisonImage": boot["ImageSha256"] == display["ImageSha256"],
        "ManagedApplicationSha256": boot["ManagedSampleSha256"], "SourceSnapshotSha256": boot["SourceSnapshotSha256"],
        "SourceValidation": {"CurrentInventoryChecked": bool(strict), "HostBootOverlapMatched": True,
                             "OnlyHashExemption": REPORTER, "ReporterCompiledIntoKernel": False},
        "PostprocessorSha256": digest(Path(__file__)), "Display4K": display["DisplayMarker"],
        "MonitorTiming": evidence["Timing"], "ComparisonMonitorTiming": evidence["ComparisonTiming"],
        "DesktopPerformance": evidence["Performance"], "GeneratedIcons": icons, "EfiDisplayHelper": shim,
        "DesktopVisualEvidence": visuals, "ViewportPlanEvidence": viewport,
        "AppearanceSettingsPath": "X:\\System\\Settings\\Appearance.json" if desktop_v3 else None,
        "AppearanceIsPersistent": False,
        "InteractiveAccelerationPolicy": "Identical-image verified TCG preferred for GTK; WHPX remains explicit opt-in" if desktop_v4 else None,
        "NativeBuildWarnings": warnings,
        "PrivateRuntimePatches": boot.get("PrivateRuntimePatches"),
        "Receipts": {name: {"Path": str(path.resolve()), "Sha256": digest(path)} for name, path in receipts},
        "Limits": ["RAM live; no persistent C# filesystem", "bounded Console IL, not full CoreCLR/.NET 10 or Framework 4.8",
                   "shared kernel address space; no application isolation", "bounded original CSS/DOM/classic JS; no complete web platform",
                   "Monaco core editing/Monarch; no Web Workers or TypeScript language services",
                   "native HTTPS not ported; certificate verification never bypassed", "website article CSS/JS and real guest DOM; full CSS/SVG/font/pixel parity remains incomplete" if website else "guest Markdown is text from real website pipeline",
                   "upstream finally semantics incomplete; out of memory explicitly halts the guest", "NativeAOT/trimming analysis warnings remain",
                   "renderer target/submission FPS is not scanout; VSync=0", "x86_64 QEMU; physical USB/multimonitor/other architectures pending"],
        "UsbUpdated": False,
        "UsbUpdateReason": "C# English QEMU preview has not passed physical USB keyboard and Chinese RAM-live release acceptance; the verified dedicated USB image is preserved.",
    }
    tick = chr(96)
    target = evidence["Timing"]["RendererTargetMilliHz"] / 1000 if evidence["Timing"] else None
    target_text = f"{target:g} Hz" if target else "未提供独立时序记录"
    icon_text = f"内置 Imagegen 生成9个透明原图,提示词、原图/Atlas哈希已核对;Atlas SHA256:{tick}{icons['AtlasSha256']}{tick}。" if icons else "旧版组合未计入第二轮图标验收。"
    shim_text = f"通过本项目 {tick}Source/XFESystem.Boot{tick} 的 C# UEFI 显示初始化程序进入 Limine,引导程序 SHA256:{tick}{shim['ArtifactSha256']}{tick}。" if shim else "旧版组合无独立 EFI 显示初始化记录。"
    window_text = ("窗口支持拖动、双击最大化/还原、右下角调整大小、任务栏及开始菜单;Win 与 Alt+Tab 通过实际 make/break 输入验证。宿主系统仍可能截获未被虚拟机捕获的组合键。"
                   if strict else "此旧版组合未新增计入第二轮窗口管理、任务栏与 Win/Alt+Tab 验收。")
    appearance_text = ("本轮系统设置提供 Light/Dark、5个主题色及自定义 #RRGGBB。深色沿用 #09121B 背景、#102538 面板和 #285171 蓝色标题,终端默认 #75C9F5 / #0C1321。右上角只保留最小化与关闭;按钮、任务栏、文件列表、设置选项有悬停和按下反馈。窗口/线条在原生像素上抗锯齿,光标使用真实背景上的 alpha 光晕。配置写入 X:\\System\\Settings\\Appearance.json,当前只保留于本次 RAM 会话。QEMU 默认最大化普通窗口并适配完整桌面;这会重采样宿主视口,来宾 framebuffer 仍为4K。-NativePixels 显式恢复1:1,窗口放不下时可裁切。PlanOnly证据不替代最终可见窗口确认。"
                       if desktop_v3 else "")
    if desktop_v4:
        appearance_text += "\n\n本轮移除系统顶部栏,Settings 位于桌面及任务栏;最大化使用顶部空间。最小化/关闭悬停在180ms内平滑旋转,中途离开连续反向;原始PPM捕获了真实中间和反向帧。窗口拖动和缩放分别进行密集输入性能采样,settle后与Win+D完整重绘同状态帧比较,差异像素为0;Drag实际MotionReuses与MotionPixels大于0。交互auto核对同镜像TCG记录后使用TCG,因为本机历史WHPX+GTK在固件阶段超时而headless验收正常。显式whpx可选,其headless证明不算GTK启动证明。"
    browser_text = (f"本轮自研 CSS 布局、外部经典脚本和 DOM 事件在同镜像裸机来宾通过 {len(browser_native['BrowserPipeline']['Checks'])} 组验收。官方 Monaco 0.52.2 已实际绘制 JavaScript 着色文字,鼠标/键盘输入后真实 getValue() 改变;截图像素、网络资源及模型前后值见 BrowserNative。宿主生产管线兼容探针另列,未借宿主浏览器代跑。没有完整 CSS/Web 平台、Worker、TypeScript 语言服务或原生 HTTPS。" if browser_native else "")
    website_text = ""
    if website:
        comparison = website["ScreenshotComparison"]
        browser_text += "\n\nC# 使用网站原 highlight.js、自定义 csharp.js 及从 code-style.css 派生的相同调色板提供 Monaco TokensProvider。真实模型、逐 span 色值、键盘编辑及编辑后原生着色帧另有独立验证。网站本身没有 Monaco;此适配器属于系统新增实现。"
        website_text = (f"\n\n本轮 Markdown F5 预览已改为自研 Web 布局和原始网站 CSS/JS,实际原生来宾通过 {len(website['NativeDocument']['Checks'])} 组文档/着色/滚轮/行号按钮检查。"
                        f" {website['OriginalWebsiteResourceCount']} 份来源快照逐项记录 SHA256,未改写原 CSS/JS。"
                        f"同尺寸、同设备倍率的 QEMU 原像素与网站文章组件 Chromium 参考图已对照,ExactPixelMatch={comparison.get('ExactPixelMatch')},"
                        f"平均通道绝对误差={comparison.get('MeanAbsoluteChannelError')}。原始图、并排图和差分图见 WebsiteComparison。"
                        "字体当前实际回退为 Lato/Cascadia Mono,Web 中文使用 Noto Sans SC 派生轮廓;完整 SVG、Web 字体、CSS 与栅格细节仍存在差异;本轮没有通过用户要求的完全一致验收。"
                        f"文档观察到的功能缺口:{website['NativeDocument'].get('ObservedFeatureGaps', [])}。")
    preview_text = ""
    if first_paint:
        preview_text = ("## Markdown 首屏专项\n\n真实 Preview 点击后,先呈现正文和 9 份原始 CSS,再分阶段加载增强脚本。截图核对标题和首段的实际字形,不使用占位内容。\n\n"
            "| 配置 | 首次/再次来宾秒 | 首次/再次宿主观测秒 | 两次均小于 1 秒 |\n| --- | --- | --- | --- |\n" +
            "".join("| " + ("WHPX + SDL(实际可见窗口)" if key == "WHPX" else key) + " | " + "/".join(f"{sample['NativeClickToPresentedSeconds']:.3f}" for sample in first_paint[key]["Samples"]) +
                    " | " + "/".join(f"{sample['HostButtonDownToPresentationMarkerSeconds']:.3f}" for sample in first_paint[key]["Samples"]) +
                    " | " + str(first_paint[key]["FirstPaintRequirementMet"]) + " |\n" for key in ("TCG", "WHPX")) +
            "\n单个增强脚本仍不能中途抢占;首帧成功不代表脚本加载期间全部交互流畅。实际仍为 CPU 绘制,真正 CUDA/GPU 渲染未实现,最新要求尚未全部完成。\n\n")
    if preview_performance:
        before,after=preview_performance["BaselineMedianSeconds"],preview_performance["CurrentMedianSeconds"]
        preview_text=("## Markdown 预览响应专项\n\n真实 QEMU TCG、3840×2160、1 GiB,使用实际鼠标/键盘打开两次 Markdown,截图核对正文已绘制。"
            "\n\n| 中位耗时 | 旧版秒 | 本版秒 |\n| --- | ---: | ---: |\n"+
            "".join(f"| {title} | {before[key]:.3f} | {after[key]:.3f} |\n" for title,key in (("首次实际文档","ClickToActualDocumentSeconds"),("验证首绘","ClickToFirstVerifiedPaintSeconds"),("Win+D响应","WinDResponseSeconds"),("关闭预览","CloseResponseSeconds")))+
            "\n缓存、样式候选索引、重复脚本AST复用及输入到达时暂停绘制已进入实际来宾。首次完整脚本和布局初始化仍然慢;未宣称所有滚动均流畅或达到240 FPS。滚轮宿主发送耗时不是FPS。"
            "\n\n**实际仍为 CPU 渲染;CUDA/GPU 加速未实现,VSync未验证。** 后端选择策略优先已通过初始化、绘制与呈现自检的独显,其次核显;策略测试不等于设备驱动或CUDA任务提交。宿主Windows的显卡驱动不能直接作为裸机来宾驱动。\n\n")
    markdown = f"""# XFESystem C# 开发预览验收 {'V7' if first_paint else 'V6' if website else 'V5' if browser_native else 'V4' if desktop_v4 else 'V3' if desktop_v3 else 'V2'}(2026-10-14)

分支 {tick}codex/csharp-system{tick},解决方案 {tick}XFESystem.slnx{tick}。本记录验证 C# 裸机迁移当前阶段,完整系统重构尚未完成。验收配置:{tick}{proof['ValidationProfile']}{tick}。

| 检查 | 结果 |
| --- | --- |
| 宿主单元/协议检查 | {evidence['HostTotal']} 项通过 |
| 独立宿主文档浏览器 | 通过;完整网站资源属于宿主验收 |
| 完整来宾启动和基线图形交互 | {counts['Baseline']} 组通过 |
| 完整来宾 HTTP、中文、JS、正文与失败恢复 | {counts['Http']} 组通过 |
| 完整来宾窗口、视觉与性能检查 | {counts['Desktop']} 组通过 |
| TCG 对照窗口检查 | {counts['ComparisonDesktop']} 组;UI-only,不计作完整 HTTP/基线验收 |
| 独立 net10.0 DLL | 来宾 PE/IL、Console/ANSI/真实 XFEConsole 执行成功 |
| 原生分辨率与界面倍率 | 3840×2160,200% |
| 首次启动默认主题 | {boot.get('DefaultAppearance', {}).get('Mode', '见原生启动记录')} |
| 本轮 C# / Monaco 内存配置 | 1 GiB;512 MiB 完整编辑未通过,未计作达标 |
| 清理与完整性 | 验收 QEMU 退出 0,镜像各次前后 SHA256 一致 |
| NativeAOT 已知限制 | {warnings['KnownWarningCount']} 项分析警告,未宣称无警告 |

内核 SHA256:{tick}{boot['KernelSha256']}{tick}。

系统镜像 SHA256:{tick}{boot['ImageSha256']}{tick}。

托管示例 SHA256:{tick}{boot['ManagedSampleSha256']}{tick}。

{'WHPX 完整验收与 TCG UI-only 对照使用同一个 ELF 和逐字节相同的镜像。' if strict else '旧版组合仅要求同一个 ELF,不将不同配置镜像声明为逐字节相同。'} 宿主与来宾源码逐项核对,第二轮同时检查文件清单;唯一允许改变的是不参与编译的本报告后处理器,其最终哈希单列。串口、截图、受控 HTTP nonce 和详细结果见 JSON 的 Receipts。

## 绘制性能与刷新边界

{preview_text}

绘制目标为 {target_text}。EDID 声明、驱动确认值、绘制目标与实际提交速度分别记录。稳态中位数和区间来自完整活动时间段;整窗速度另含尾部空闲,不代替稳态数据。

{performance_markdown(evidence['Performance'])}

以上为来宾渲染提交速度,不能据此判断物理屏幕扫描率。VSync 为 0,未保证最高刷新率同步输出;WHPX/TCG、QEMU 显示设备、GTK 与计时校准均可能影响可见结果。最近一次绘制耗时不是整段平均帧时间,复制像素也不是实际总线带宽。

## 实现与资产来源

当前工作树已删除旧 Rust 内核、驱动、用户程序、Cargo 工程及构建入口;项目自有 UEFI 显示初始化也已迁移为 C#。历史镜像、ZIP、验收与 Git 历史保留;旧多架构或实体驱动记录不作为当前 C# 的通过证明。

内核及桌面使用 C# NativeAOT,复用固定 Cosmos 3.0.94 运行时、GC 与 HAL,没有使用 Linux/Windows 来宾内核。{shim_text} JSON 记录其实际源码、构建记录与产物哈希。

{icon_text} 每个原图的精确提示词和哈希保留在 GeneratedIcons 与资产目录。编译仅作确定性采样和 RGBA 打包,原始 PNG 未修改。

{window_text}

{appearance_text}

{browser_text}

{website_text}

## 仍未完成的能力

程序集仅支持受限 {tick}XFESystem.Net10.ConsoleIL.v1{tick},没有完整 CoreCLR、JIT 或 .NET Framework 4.8。文件为 RAM live,关机后消失;应用与内核共享地址空间。网页管线仍为有限子集,原生 HTTPS 尚未移植并明确拒绝;不会跳过证书验证。{'Markdown 已在真实来宾使用网站文章组件和脚本;DOM 生成不等于数学、SVG 与所有网站像素均已兼容,具体差异见上述实测。' if website else 'Markdown 使用网站真实 Markdig/清理管线,来宾文档预览仍呈现文本,完整数学/流程图资源属于单独宿主浏览器验收。'}

上游异常展开尚缺完整 finally 语义。已验证的显式恢复路径不证明通用资源回收完成;NativeAOT/trimming 警告涉及未全面覆盖的动态/反射路径,当前验收不推广到任意程序集和浏览器功能。

实体 USB 输入、多显示器、原生 GPU/VSync、其他架构、完整账号及持久化仍需移植。未更新专用 U 盘,旧发行目录和镜像保留。
"""
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("x", encoding="utf-8") as stream:
        json.dump(proof, stream, ensure_ascii=False, indent=2); stream.write("\n")
    with output.with_suffix(".md").open("x", encoding="utf-8") as stream:
        stream.write(markdown)
    print(json.dumps({"Report": str(output), "HostTestsPassed": evidence["HostTotal"],
                      "DesktopPreview2Validated": bool(strict)}, ensure_ascii=False))


if __name__ == "__main__":
    main()