Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

chore: establish Veyra baseline

Veyra Goal Agent2086282478ae
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..79ccf104
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,26 @@
+# Proprietary and local-only inputs
+/nvngx_dlssnr.dll
+/renodx-dlss5-1.addon64
+/runtime_local/
+/third_party_local/
+/reference_local/
+
+# Build outputs and local presets
+/out/
+/build/
+/.vs/
+/vcpkg_installed/
+CMakeUserPresets.json
+
+# Diagnostics and captures
+/captures/
+/logs/
+*.pdb
+*.ilk
+*.dmp
+*.etl
+
+# Unattended loop local control and scratch
+/loop/STOP
+/loop/tmp/
+/loop/local/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..d43122b6
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,108 @@
+# Veyra 项目 Agent 执行规则
+
+本文件对在本目录工作的所有 Agent 生效。不要只扫标题;开工前必须完整阅读:
+
+1. `README.md`——当前状态和唯一入口;
+2. `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md`——唯一施工手册;
+3. `VEYRA_PRODUCT_SPEC_V1.md`——产品与技术边界;
+4. 当前阶段的 `docs/WORKLOG.md`——已完成、失败记录和下一步。
+
+如果任务以 Goal/无人值守模式运行,还必须先完整阅读:
+
+5. `loop/LOOP_ENGINE.md`——循环、恢复、审查和停机协议;
+6. `loop/STATE.json`——当前真实阶段和下一动作;
+7. `loop/BACKLOG.md` 与 `loop/INBOX.md`——唯一任务队列和人工阻塞;
+8. `loop/REVIEW_PROMPT.md`——阶段独立复核的固定只读任务。
+
+Goal 启动后,`.gitignore`、上述规则/方案、`loop/CONTROL_HASHES.json`、
+基础 `scripts/loop-gate.ps1` 和 `scripts/gates/README.md` 都是只读控制面。
+preflight 报控制面 hash 漂移时必须停下,不得改 manifest 或 gate 自我放行。
+
+若施工手册与 Product Spec 冲突,以施工手册中更具体、更新的实现指令为准;若本文件与施工手册冲突,以本文件的安全、许可证和阶段门禁为准。
+
+## 不可擅自改变的决定
+
+- V1 是 Windows x64、C++20、Win32、D3D12 项目。
+- V1 直接调用 NGX;不要同时接入 Streamline。Streamline 仅作未来替换方案和文档参考。
+- 固定帧 harness 分两步:Phase 1 直接生成 RGBA8 Proxy → Feature 18 → Raw 抓帧;Phase 2 才加入 Original → Parity Encode → Feature 18 → Parity Decode。不是先做完整播放器。
+- `nvngx_dlssnr.dll` 是 DLSSNR 运行时;只从项目根目录的已知文件复制到 `runtime_local`,不得联网寻找“更新偷跑版”、不得修改、重签名或提交 Git。
+- `renodx-dlss5-1.addon64` 是未签名的 ReShade/RenoDX 二进制 add-on,不是配置文件。它只准用于隔离的参考/对照环境,最终程序不得加载、注入、链接或随包分发它。
+- 最终主线不依赖 ReShade。所谓“类似 ReShade”指独立复现它的前后颜色传递、参数映射和输出处理。
+- V1 先做 SDR、同分辨率 DLSSNR、Zero Guidance,再按阶段做 DLSS SR、NVOF、DLSSG 2X。HDR、3X/4X、采集卡、Depth Anything、FRUC 都不是 V1 主线。
+- 已接受 Magpie Experimental 对“可调用”的可行性证明,不再做市场/画质可行性研究。但 Create/Evaluate、格式、状态、时序、资源生命周期仍必须做工程验证。
+
+## 二进制身份,任何不一致都立即停工
+
+```text
+nvngx_dlssnr.dll
+ SHA256: E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E
+ Size: 165840496 bytes
+ Version: 310.8.0.0
+ Signature: Valid, NVIDIA
+
+renodx-dlss5-1.addon64
+ SHA256: 837B6A34D41C0EB75CB105AFEB5B985CFC72CB7F3A786C5DBB3F5415C45C978F
+ Size: 359424 bytes
+ Signature: NotSigned
+```
+
+如果 hash 不同,不要“先试试看”;记录实际值并询问用户。
+
+## 阶段门禁
+
+严格按 Playbook 的 Phase 0→7 完成 V1;Phase 7 通过后停止,不再自动扩展。每个阶段必须同时满足:
+
+1. 代码可构建;
+2. 本阶段列出的自动或手工检查通过;
+3. `docs/WORKLOG.md` 写明命令、结果、日志路径、失败与修复;
+4. 没有把 proprietary runtime 或本地 SDK 提交进版本控制;
+5. 下一阶段没有建立在未验证假设上。
+
+Phase 1 没有完成连续 300 次 Feature 18 Evaluate,就禁止开始 FFmpeg、UI、音频、SR 或 FG。
+
+## 无人值守 Goal Loop
+
+- 用户以 `loop/GOAL_PROMPT.md` 启动 Goal 时,允许在阶段硬门禁和独立 Reviewer 均通过后自动进入下一 Phase;安全、许可证和验收规则没有自动豁免。
+- 主 Agent 是唯一写入者。禁止多个 Agent 同时修改同一 checkout;阶段 Reviewer 必须是新上下文、只读,不能替 Maker 改代码。
+- 每个 cycle 只处理 `loop/BACKLOG.md` 当前 Phase 的第一个可执行原子任务。改动前写 `loop/JOURNAL.md`,改动后运行当前 gate。
+- 统一 gate 入口:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate phaseN`。
+- 同一 failure fingerprint 最多尝试 3 个真正不同、能增加证据的方案;连续 5 轮无新证据或总计 80 轮后必须留档停机,不得空转。
+- `loop/STOP` 是用户停机开关。看到它就更新状态并退出,Agent 不得删除。
+- 未实际获得独立 Reviewer 结论时只能标 `needs_review`;不能降级成“自己再看一遍”后自动放行。
+- 只准本地 checkpoint commit。禁止无人值守 push、PR、发布、上传 artifact 或制作安装包。
+
+## 实现纪律
+
+- 先检查现状:`git status`、`rg --files`、hash、工具版本。不要覆盖用户已有改动。
+- 每次只实现当前阶段最小闭环,不顺手重构整个工程。
+- 任何 NGX/NVOF 返回值、HRESULT、SEH、资源尺寸/格式和 GPU timestamp 都必须进入日志。
+- 所有历史型模块在 open/seek/resize/pause-resume/scene-cut/device-lost 时显式 reset。
+- 正常播放路径禁止 GPU→CPU 像素回读、每 pass CPU fence wait、无界帧队列和多份隐式颜色转换。
+- 创建 Feature 可以等待一次;逐帧执行用 3–4 个 command slots/fence values 轮转,不能每帧 `WaitForSingleObject`。
+- NGX 参数名和参数类型必须逐项照 Playbook;不要凭名字猜 `int`/`uint32_t`/`float`/resource。
+- 所有 DLL 用绝对路径、`LoadLibraryExW` 和受限 search flags 加载;禁止依赖当前工作目录搜索。
+- 不允许把 `renodx-dlss5-1.addon64` 改名为 DLL,不允许尝试从中 `GetProcAddress` 当普通库调用。
+- 不允许在磁盘上 patch `nvngx_dlssnr.dll`。调用方兼容层必须独立封装、运行时可关闭,并明确标记 local experimental only。
+- C++ 层保持 RAII;逆序释放 Feature、parameter block、runtime、NGX Core、D3D12 resources。
+- Shader 先独立测试。颜色结果异常时先查 transfer、range、resource format、subrect、state barrier,别先调“画质参数”。
+
+## 许可证与分发红线
+
+- Magpie 是 GPLv3。闭源 Veyra 不得复制其源码或做机械改名;只可把其公开行为当作黑盒/接口参考后独立实现。若要直接复用,先让用户明确接受 GPLv3 以及对应源码义务。
+- NVIDIA SDK/runtime 和当前 DLSSNR 文件的分发权不能假定。默认只做本机研发,`runtime_local/`、`third_party_local/`、抓帧和 SDK 压缩包必须 gitignore。
+- 不得上传、发布、打包或向第三方发送项目中的两个二进制。
+- 任何准备公开发布、签名安装包或 CI 上传 artifact 的动作,都必须先停下并让用户确认许可证与分发来源。
+
+## 每次交付必须报告
+
+- 当前 Phase 与完成门槛;
+- 修改的文件;
+- 实际运行过的构建/测试命令;
+- Create/Evaluate 或失败码的真实日志,不得用“应该可以”代替;
+- 已知风险和下一条唯一任务;
+- 若没实际在 RTX/NVIDIA runtime 上执行,明确写“未执行”,绝不能声称成功。
+- Goal 模式还必须同步更新 `loop/STATE.json`、`loop/EVIDENCE.md` 和 `loop/JOURNAL.md`,保证上下文压缩或进程中断后可从磁盘恢复。
+
+## 禁止用假完成糊弄
+
+以下均不算完成:只写接口桩、只编译未运行、仅显示理论 FPS、把 Raw NR 直接展示却声称完成 RenoDX parity、以 Zero Motion 冒充 NVOF、以重复上一帧冒充 DLSSG、或捕获到黑图仍把返回码 0 当成功。
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..458d147f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,25 @@
+# Veyra DLSS Video Player
+
+当前状态:只有经过审查的产品/施工文档、无人值守 Loop Engine 和两个本地参考二进制;应用源码尚未建立,当前 Phase 是 0。
+
+## 唯一入口
+
+- 产品边界:`VEYRA_PRODUCT_SPEC_V1.md`
+- 技术施工:`VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md`
+- Agent 规则:`AGENTS.md`
+- 无人值守目标:`loop/GOAL_PROMPT.md`
+- 当前状态:`loop/STATE.json`
+- 实际记录:`docs/WORKLOG.md`
+
+不要使用历史方案或另写一套路线。Agent 开工前先运行:
+
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
+
+## 二进制边界
+
+- `nvngx_dlssnr.dll`:用户提供、NVIDIA 签名的本地实验 runtime;只复制进已忽略的 `runtime_local/`,不提交、不发布、不自动替换。
+- `renodx-dlss5-1.addon64`:未签名 RenoDX/ReShade 二进制 add-on,不是配置文件;只作隔离参考,Veyra 不加载、不链接、不分发。
+
+项目接受 Magpie 对“能调用”的可行性证明,不再重复主观画质研究;本项目仍必须验证自身的 API 参数、颜色 parity、资源状态、时序、延迟和稳定性。
+
+V1 只有 Phase 0–7。采集卡、HDR、3X/4X、Depth Anything、FRUC、安装包和公开发布不在当前执行范围。
diff --git a/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
new file mode 100644
index 00000000..436bb0e4
--- /dev/null
+++ b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
@@ -0,0 +1,2191 @@
+# Veyra DLSS Video Player
+
+## Agent 施工手册 V1
+
+文档日期:2026-09-01
+适用目录:`C:\Users\123\Desktop\Veyra DLSS Video Player`
+产品方案基线:`VEYRA_PRODUCT_SPEC_V1.md`
+
+这不是概念方案,而是交给下一位 Agent 的执行合同。目标是让能力一般的模型也能按固定顺序搭建、调用、验收,并且在失败时知道停在哪里。除非用户明确改需求,不准擅自换技术栈、扩大 V1 或跳阶段。
+
+---
+
+# 0. 先说结论
+
+Veyra V1 采用下面这条唯一主线:
+
+~~~text
+FFmpeg demux/decode
+ ↓
+D3D12VA surface(早期 harness 可临时 CPU upload)
+ ↓
+YUV → linear working RGB
+ ↓
+可选 DLSS Super Resolution
+ ↓
+保留 Original FP16
+ ↓
+RenoDX-equivalent Proxy Encode
+ ↓
+动态加载 nvngx_dlssnr.dll
+ ↓
+NGX Feature 18 Create/Evaluate
+ ↓
+RenoDX-equivalent Parity Decode
+ ↓
+可选 DLSS Frame Generation 2X
+ ↓
+最后叠加播放器 UI
+ ↓
+DXGI Present
+~~~
+
+关键工程决定:
+
+- Windows x64、C++20、Win32、D3D12。
+- 所有 GPU 阶段共用一个 DXGI adapter、一个 `ID3D12Device` 和主 direct queue。
+- V1 直接用 NGX SDK。不要同时集成 Streamline;那会增加 swapchain、resource tagging、plugin lifecycle 和本地 Feature 18 adapter 之间的变量。
+- `nvngx_dlssnr.dll` 不是链接库,必须用 `LoadLibraryExW` 动态加载并解析导出。
+- `renodx-dlss5-1.addon64` 不是配置文件,更不是播放器依赖。它只用于确认参数名、shader 数学和参考输出。
+- “类似 ReShade”不是实现通用 ReShade shader 加载器;只复现当前 RenoDX DLSS5 add-on 的颜色代理编码、Feature 18 参数和输出恢复。
+- 第一件事不是完整播放器,而是固定帧的 `veyra_nr_harness`。连续 300 帧成功之前,不做 FFmpeg/UI/音频/SR/FG。
+- 已接受 Magpie Experimental 对“Feature 18 能调用、DLSSG 能执行”的可行性证明。这里仍要做接口和时序回归测试,因为“别人跑通过”不等于本工程不会写错参数。
+
+---
+
+# 1. 当前项目里有什么
+
+当前目录还不是代码仓库,也没有应用源码。有效控制面、方案和本地二进制是:
+
+~~~text
+README.md
+AGENTS.md
+VEYRA_PRODUCT_SPEC_V1.md
+VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
+loop/
+scripts/
+docs/WORKLOG.md
+nvngx_dlssnr.dll
+renodx-dlss5-1.addon64
+~~~
+
+不存在仍有效的历史方案;不要联网找旧副本,也不要从旧文档恢复被当前边界否决的功能。
+
+## 1.1 DLSSNR 文件
+
+~~~text
+File: nvngx_dlssnr.dll
+Size: 165840496 bytes
+SHA256: E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E
+Version: 310.8.0.0
+Description: NVIDIA DLSSNR - DVS PRODUCTION
+Signature: Valid NVIDIA Authenticode signature
+Timestamp: 2026-08-12 04:29:33
+Min driver: 615.00(来自文件 version resource)
+GPU target: Blackwell2(来自文件 version resource)
+NGX API: 0x0000013(来自文件 version resource)
+~~~
+
+已确认的 D3D12 导出:
+
+~~~text
+NVSDK_NGX_D3D12_Init_Ext
+NVSDK_NGX_D3D12_CreateFeature
+NVSDK_NGX_D3D12_EvaluateFeature
+NVSDK_NGX_D3D12_ReleaseFeature
+NVSDK_NGX_D3D12_Shutdown1
+~~~
+
+注意:文件也含 D3D11/Vulkan/CUDA 通用符号,但内部文本明确显示当前 D3D11 路径未完成。V1 不碰 D3D11 Feature 18。
+
+## 1.2 RenoDX 文件
+
+~~~text
+File: renodx-dlss5-1.addon64
+Size: 359424 bytes
+SHA256: 837B6A34D41C0EB75CB105AFEB5B985CFC72CB7F3A786C5DBB3F5415C45C978F
+Version: 0.2026.0827.2036
+Signature: NotSigned
+Internal: RenoDX.DLSS5 / DLSS 5 Neural Rendering
+~~~
+
+它是 ReShade binary add-on,通过 ReShade add-on API 保存配置和 hook NGX。最终 Veyra 不加载它。它已经给出三个重要事实:
+
+1. 插入点是游戏 DLSS 输出之后、UI 之前;
+2. Feature 18 的参数字符串和资源合同;
+3. Control-compatible soft-clip/sRGB/UpgradeToneMap codec 的 shader 数学。
+
+## 1.3 当前机器
+
+~~~text
+OS: Windows 11 Pro for Workstations, build 26200
+GPU: NVIDIA GeForce RTX 5070
+Driver: 616.56
+VRAM: 12227 MiB
+Compute: 12.0
+nvofapi64: 32.0.16.1656, signed, present in System32
+~~~
+
+这台机器满足当前 DLL 标注的 driver/GPU 条件。不要把这个事实扩张成“所有 NVIDIA GPU 都支持”。V1 对修改过的 Ada runtime 不提供支持。
+
+## 1.4 开发工具,已安装但多数不在普通 PATH
+
+~~~text
+Visual Studio Build Tools:
+C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools
+
+MSVC:
+C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.44.35207
+
+CMake 3.31.6:
+C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe
+
+Ninja 1.12.1:
+C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\Ninja\ninja.exe
+
+MSBuild:
+C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\MSBuild.exe
+
+DXC:
+C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe
+
+Git:
+C:\Program Files\Git\cmd\git.exe
+~~~
+
+普通终端找不到 `cmake` 不代表没装。优先用以上绝对路径或从 VS Developer PowerShell 启动。
+
+---
+
+# 2. 真源、参考源和不能抄的东西
+
+按下面优先级判断事实:
+
+1. 本目录两个二进制的 hash、导出、内嵌参数/数学;
+2. 本文与 Product Spec 的已锁定产品边界;
+3. NVIDIA 官方 SDK 头文件、sample 和文档;
+4. Magpie Experimental 的可观察调用顺序;
+5. 其他博客、论坛和一键整合包一律不作为实现真源。
+
+## 2.1 Magpie 只作行为参考
+
+固定参考:
+
+~~~text
+Repo: https://github.com/SAOG0721/Magpie
+Branch: experimental
+Commit: e15394a9e15b996b52ad92c6bf22747b2e7ae46d
+License: GPLv3
+~~~
+
+重点阅读文件:
+
+~~~text
+src/Magpie.Core/NgxD3D12Core.cpp
+src/Magpie.Core/NgxD3D12Core.h
+src/Magpie.Core/DLSSNRFilter.cpp
+src/Magpie.Core/DLSSNRFilter.h
+src/Magpie.Core/DLSSFrameGenerator.cpp
+src/Magpie.Core/DLSSFrameGenerator.h
+src/Magpie.Core/FrameGuidanceTypes.h
+src/Magpie.Core/NvidiaOpticalFlowProvider.cpp
+~~~
+
+闭源 Veyra 不得复制这些文件或机械改名。应依据公开 NGX/NVOF 接口和本文列出的行为独立实现。如果用户决定整个项目接受 GPLv3,再单独评估复用。
+
+不要复用 Magpie 的 NGX Project ID。Veyra 必须使用自己的 Project ID;本地实验可生成一个持久 GUID,发布前必须换成 NVIDIA 分配/允许的身份。
+
+## 2.2 不从非官方来源拿 DLL
+
+不要去 Discord、网盘、论坛或所谓“一键包”下载别的 `nvngx_dlssnr.dll`、`nvngx_dlss.dll`、patched Ada DLL。只使用当前根目录已给出的 DLSSNR 文件和 NVIDIA 官方 DLSS SDK 里的公开 SR/FG runtime。
+
+---
+
+# 3. 依赖从哪里拿、拿什么、放哪里
+
+## 3.1 目录约定
+
+创建以下三个本地目录,并全部加入 `.gitignore`:
+
+~~~text
+runtime_local/ # 本机 proprietary feature DLL 和 manifest
+third_party_local/ # 下载/解压的 SDK 与 vcpkg
+reference_local/ # Magpie 源码快照、ReShade 对照材料
+~~~
+
+公开的本项目源码放在 `src/`、`shaders/`、`tools/`、`tests/`;第三方 SDK 不复制进这些目录。
+
+## 3.2 NVIDIA DLSS SDK 310.7.0
+
+来源:
+
+~~~text
+Release: https://github.com/NVIDIA/DLSS/releases/tag/v310.7.0
+Repo: https://github.com/NVIDIA/DLSS
+Tag: v310.7.0
+~~~
+
+下载 release ZIP 或 clone 后 checkout tag,解压到:
+
+~~~text
+third_party_local/nvidia/DLSS_SDK_310.7.0/
+~~~
+
+至少确认这些文件存在:
+
+~~~text
+include/nvsdk_ngx.h
+include/nvsdk_ngx_defs.h
+include/nvsdk_ngx_helpers.h
+include/nvsdk_ngx_helpers_dlssg.h
+include/nvsdk_ngx_params.h
+include/nvsdk_ngx_params_dlssg.h
+
+lib/Windows_x86_64/x64/nvsdk_ngx_s.lib
+lib/Windows_x86_64/rel/nvngx_dlss.dll
+lib/Windows_x86_64/rel/nvngx_dlssg.dll
+~~~
+
+用途:
+
+- `nvsdk_ngx_s.lib`:NGX D3D12 core 入口;
+- `nvsdk_ngx_helpers.h`:DLSS Super Resolution helper;
+- `nvsdk_ngx_helpers_dlssg.h`:DLSS Frame Generation helper;
+- `nvngx_dlss.dll` / `nvngx_dlssg.dll`:Phase 4/6 的公开 feature runtime。
+
+不要用 SDK 的 `dev` DLL 做验收;正常使用 `rel`。不要用它覆盖根目录 `nvngx_dlssnr.dll`,这不是同一个 feature。
+
+## 3.3 NVIDIA Optical Flow SDK 5.0
+
+来源:
+
+~~~text
+Download: https://developer.nvidia.com/opticalflow/download
+Docs: https://docs.nvidia.com/video-technologies/optical-flow-sdk/index.html
+Guide: https://docs.nvidia.com/video-technologies/optical-flow-sdk/nvofa-programming-guide/index.html
+~~~
+
+下载需要 NVIDIA Developer Program 登录并接受 EULA,Agent 不得绕过。让用户在官方页面下载,然后解压到:
+
+~~~text
+third_party_local/nvidia/Optical_Flow_SDK_5.0/
+~~~
+
+解压后用 `rg --files` 找并确认:
+
+~~~text
+nvOpticalFlowCommon.h
+nvOpticalFlowD3D12.h
+NvOFUtils...D3D12...(名称以 SDK 实际 sample 为准)
+D3D12 optical-flow sample
+~~~
+
+运行时 `nvofapi64.dll` 来自 NVIDIA 驱动的 System32,不从 SDK 随包复制。程序用:
+
+~~~text
+LoadLibraryExW(L"nvofapi64.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)
+GetProcAddress(..., "NvOFAPICreateInstanceD3D12")
+GetProcAddress(..., "NvOFGetMaxSupportedApiVersion")
+~~~
+
+不要链接或分发一个来路不明的 `nvofapi64.dll`。
+
+## 3.4 FFmpeg 9.0.1 与 Dear ImGui 1.92.8
+
+V1 用 vcpkg manifest 锁版本。固定 registry baseline:
+
+~~~text
+vcpkg commit:
+30ef65cad98f08e7197c9a1656fbd871bcb72f2d
+
+该 baseline 的 port:
+ffmpeg 9.0.1#1
+imgui 1.92.8#1
+~~~
+
+将 vcpkg clone 到:
+
+~~~powershell
+git clone https://github.com/microsoft/vcpkg.git third_party_local/vcpkg
+git -C third_party_local/vcpkg checkout 30ef65cad98f08e7197c9a1656fbd871bcb72f2d
+& .\third_party_local\vcpkg\bootstrap-vcpkg.bat -disableMetrics
+~~~
+
+项目根目录的 `vcpkg.json` 使用:
+
+~~~json
+{
+ "name": "veyra-dlss-video-player",
+ "version-string": "0.1.0",
+ "builtin-baseline": "30ef65cad98f08e7197c9a1656fbd871bcb72f2d",
+ "dependencies": [
+ {
+ "name": "ffmpeg",
+ "default-features": false,
+ "features": [
+ "avcodec",
+ "avformat",
+ "swresample",
+ "swscale"
+ ]
+ },
+ {
+ "name": "imgui",
+ "features": [
+ "dx12-binding",
+ "win32-binding"
+ ]
+ }
+ ]
+}
+~~~
+
+不要启用 `gpl`、`nonfree`、`x264`、`x265` 或 `fdk-aac`。播放器只需要解码、封装、重采样和早期软件转换 fallback。
+
+FFmpeg CMake 接法:
+
+~~~cmake
+find_package(FFMPEG REQUIRED)
+target_include_directories(veyra_media PRIVATE ${FFMPEG_INCLUDE_DIRS})
+target_link_directories(veyra_media PRIVATE ${FFMPEG_LIBRARY_DIRS})
+target_link_libraries(veyra_media PRIVATE ${FFMPEG_LIBRARIES})
+~~~
+
+ImGui 接法:
+
+~~~cmake
+find_package(imgui CONFIG REQUIRED)
+target_link_libraries(veyra_ui PRIVATE imgui::imgui)
+~~~
+
+用 `x64-windows` 动态 triplet,避免把 FFmpeg 静态链接义务藏进可执行文件。发布阶段仍需附 LGPL notice 和对应动态库许可证。
+
+## 3.5 Streamline
+
+参考版本:
+
+~~~text
+https://github.com/NVIDIA-RTX/Streamline/releases/tag/v2.12.0
+~~~
+
+V1 不下载、不链接、不初始化 Streamline。原因不是它不能用,而是当前主线已经用直接 NGX,混用会把 swapchain proxy、resource tagging、plugin lifecycle 和本地 Feature 18 adapter 搅在一起。等直接 NGX 的 SR/NR/FG 全部稳定后,才允许另开分支评估 Streamline。
+
+---
+
+# 4. 第一次开工的精确步骤
+
+## 4.1 先保护二进制,再初始化 Git
+
+当前目录不是 Git 仓库。必须先创建 `.gitignore`,至少包含:
+
+~~~gitignore
+# Proprietary / local-only
+/nvngx_dlssnr.dll
+/renodx-dlss5-1.addon64
+/runtime_local/
+/third_party_local/
+/reference_local/
+
+# Build
+/out/
+/build/
+/.vs/
+/vcpkg_installed/
+CMakeUserPresets.json
+
+# Diagnostics and captures
+/captures/
+/logs/
+*.pdb
+*.ilk
+*.dmp
+*.etl
+~~~
+
+确认忽略规则后才执行。Goal 模式必须同时遵守 `loop/LOOP_ENGINE.md` 的 P0.2 baseline/branch 流程:
+
+~~~powershell
+git init -b main
+git status --short --ignored
+git check-ignore -v --no-index -- nvngx_dlssnr.dll renodx-dlss5-1.addon64 runtime_local/.probe third_party_local/.probe reference_local/.probe captures/.probe logs/.probe loop/STOP
+~~~
+
+如果上述任一敏感路径没有显示为 ignored,禁止 staging。初始化 baseline 时只显式 `git add` 已审查的源码/文档路径并先检查 `git diff --cached --name-only`;不要使用 `git add .`。若仓库已存在,不重新 init、不重写历史。
+
+## 4.2 验证本地输入
+
+从根目录运行:
+
+~~~powershell
+Get-Item -LiteralPath '.\nvngx_dlssnr.dll','.\renodx-dlss5-1.addon64' | Select-Object Name,Length
+Get-FileHash -Algorithm SHA256 -LiteralPath '.\nvngx_dlssnr.dll','.\renodx-dlss5-1.addon64'
+Get-AuthenticodeSignature -LiteralPath '.\nvngx_dlssnr.dll','.\renodx-dlss5-1.addon64' | Select-Object Path,Status,StatusMessage
+nvidia-smi --query-gpu=name,driver_version,memory.total,compute_cap --format=csv,noheader
+~~~
+
+必须得到第 1 节列出的 size/hash。DLSSNR 必须 `Valid`;addon 预期 `NotSigned`。任何变化都写入 `docs/WORKLOG.md` 并停工。
+
+## 4.3 建立 runtime_local
+
+只复制,不移动根目录原件:
+
+~~~text
+runtime_local/
+└─ nvidia/
+ ├─ nvngx_dlssnr.dll # 从项目根目录复制
+ ├─ nvngx_dlss.dll # Phase 4 才从官方 DLSS 310.7 rel 复制
+ ├─ nvngx_dlssg.dll # Phase 6 才从官方 DLSS 310.7 rel 复制
+ └─ runtime-manifest.json
+~~~
+
+Phase 1 只放 `nvngx_dlssnr.dll`。不要为了“看起来齐全”提前塞入论坛里的 310.8 SR/FG DLL。
+
+`runtime-manifest.json` 初始内容:
+
+~~~json
+{
+ "schema": 1,
+ "mode": "local-experimental-only",
+ "files": [
+ {
+ "name": "nvngx_dlssnr.dll",
+ "size": 165840496,
+ "sha256": "E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E",
+ "fileVersion": "310.8.0.0",
+ "authenticode": "Valid",
+ "source": "user-provided workspace file",
+ "redistributable": false
+ }
+ ]
+}
+~~~
+
+Phase 4/6 加 DLL 时,Agent 必须计算各自 hash 并追加 manifest,不能写“latest”。
+
+## 4.4 创建本地 NGX 身份
+
+不要复用 Magpie 的 Project ID。执行一次:
+
+~~~powershell
+New-Item -ItemType Directory -Force '.\runtime_local\config'
+$id = [guid]::NewGuid().ToString()
+@{
+ ngxProjectId = $id
+ engineType = 'custom'
+ engineVersion = 'Veyra-Experimental-0.1.0'
+} | ConvertTo-Json | Set-Content '.\runtime_local\config\ngx-local.json' -Encoding utf8
+~~~
+
+这是本机研发身份,不代表 NVIDIA 授权的发行身份。准备发布前,必须替换为合规 Project ID。
+
+## 4.5 建立工程骨架
+
+最终目录:
+
+~~~text
+Veyra DLSS Video Player/
+├─ README.md
+├─ AGENTS.md
+├─ VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
+├─ VEYRA_PRODUCT_SPEC_V1.md
+├─ loop/
+├─ scripts/
+├─ CMakeLists.txt
+├─ CMakePresets.json
+├─ vcpkg.json
+├─ .gitignore
+├─ cmake/
+│ ├─ VeyraWarnings.cmake
+│ ├─ VeyraShaders.cmake
+│ └─ VeyraRuntime.cmake
+├─ config/
+│ ├─ nr-default.json
+│ ├─ parity-default.json
+│ └─ player-default.json
+├─ docs/
+│ ├─ WORKLOG.md
+│ ├─ DECISIONS.md
+│ └─ RUNTIME_REPORT.md
+├─ include/veyra/
+│ ├─ Result.h
+│ ├─ Log.h
+│ └─ FrameTypes.h
+├─ src/
+│ ├─ app/
+│ ├─ gfx/
+│ ├─ media/
+│ ├─ ngx/
+│ ├─ parity/
+│ ├─ guidance/
+│ ├─ player/
+│ └─ ui/
+├─ shaders/
+│ ├─ GenerateTestPattern.hlsl
+│ ├─ YuvToLinearRgb.hlsl
+│ ├─ ParityEncode.hlsl
+│ ├─ ParityDecode.hlsl
+│ ├─ NvofVectorConvert.hlsl
+│ └─ Present.hlsl
+├─ tools/
+│ ├─ runtime_probe/
+│ ├─ nr_harness/
+│ └─ parity_capture/
+├─ tests/
+│ ├─ unit/
+│ └─ integration/
+├─ validation/
+│ ├─ manifests/
+│ ├─ fixed_frames/
+│ └─ fixed_clips/
+├─ scripts/
+│ ├─ configure.ps1
+│ ├─ build.ps1
+│ ├─ stage-runtime.ps1
+│ └─ verify-runtime.ps1
+├─ runtime_local/ # ignored
+├─ third_party_local/ # ignored
+├─ reference_local/ # ignored
+└─ out/ # ignored
+~~~
+
+不要一开始创建几十个空类。Phase 0 只建立实际要编译的 `gfx`、`ngx`、`tools/runtime_probe` 和 `tools/nr_harness`。
+
+---
+
+# 5. CMake 和构建方式
+
+## 5.1 CMake cache 变量
+
+根 `CMakeLists.txt` 必须定义:
+
+~~~cmake
+set(VEYRA_DLSS_SDK_ROOT "" CACHE PATH "NVIDIA DLSS SDK root")
+set(VEYRA_NVOF_SDK_ROOT "" CACHE PATH "NVIDIA Optical Flow SDK root")
+set(VEYRA_RUNTIME_ROOT "" CACHE PATH "Local NVIDIA runtime root")
+
+option(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR
+ "Enable local-only experimental Feature 18 adapter" OFF)
+option(VEYRA_ENABLE_DLSS_SR "Enable public DLSS SR backend" OFF)
+option(VEYRA_ENABLE_DLSS_FG "Enable public DLSSG backend" OFF)
+option(VEYRA_ENABLE_NVOF "Enable NVIDIA Optical Flow guidance" OFF)
+option(VEYRA_ENABLE_D3D12_DEBUG "Enable D3D12 debug layer" ON)
+~~~
+
+如果启用 NR 而 SDK/runtime 路径缺失,配置阶段直接 `message(FATAL_ERROR)`。不要拖到运行时才报头文件或 DLL 找不到。
+
+## 5.2 编译目标
+
+按阶段创建:
+
+~~~text
+veyra_base logging/result/config/hash/signature
+veyra_gfx D3D12 device/queue/resources/barriers/profiler
+veyra_ngx NGX core + NR runtime adapter + later SR/FG
+veyra_parity parity shaders/profile/capture
+veyra_guidance zero guidance + later NVOF
+veyra_media FFmpeg demux/decode/audio
+veyra_player_core scheduler/pipeline
+veyra_ui Win32/ImGui
+
+veyra_runtime_probe.exe
+veyra_nr_harness.exe
+veyra_parity_tests.exe
+veyra_player.exe
+~~~
+
+不要让 `veyra_player.exe` 直接拥有 Feature 18 调用细节。它只面向 `IDlssNrBackend`。
+
+## 5.3 系统库
+
+基础链接:
+
+~~~cmake
+target_link_libraries(veyra_gfx PUBLIC
+ d3d12
+ dxgi
+ dxguid
+)
+
+target_link_libraries(veyra_base PUBLIC
+ bcrypt
+ wintrust
+ crypt32
+ version
+ shlwapi
+)
+~~~
+
+全项目:
+
+~~~cmake
+target_compile_features(veyra_base PUBLIC cxx_std_20)
+target_compile_definitions(veyra_base PRIVATE
+ UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+~~~
+
+MSVC 警告至少 `/W4 /permissive- /Zc:__cplusplus`。不要全局 `/WX` 阻塞第三方头;只对本项目 target 开启。
+
+NGX:
+
+~~~cmake
+target_include_directories(veyra_ngx PRIVATE
+ "${VEYRA_DLSS_SDK_ROOT}/include")
+target_link_libraries(veyra_ngx PRIVATE
+ "${VEYRA_DLSS_SDK_ROOT}/lib/Windows_x86_64/x64/nvsdk_ngx_s.lib")
+~~~
+
+## 5.4 Shader 编译
+
+使用已安装 DXC:
+
+~~~text
+C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe
+~~~
+
+目标:
+
+~~~text
+Entry: main
+Target: cs_6_0
+Debug: -Zi -Qembed_debug -Od
+Release:-O3 -Qstrip_debug -Qstrip_reflect
+~~~
+
+CMake custom command 将每个 HLSL 编译为 `out/<preset>/shaders/*.dxil`。运行时不调用 D3DCompile 编译字符串;这样 shader 错误在构建阶段暴露。
+
+## 5.5 Preset
+
+至少提供:
+
+~~~text
+x64-debug
+x64-release
+~~~
+
+生成命令示例:
+
+~~~powershell
+$cmake = 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
+$vcpkgToolchain = (Resolve-Path '.\third_party_local\vcpkg\scripts\buildsystems\vcpkg.cmake')
+$dlssRoot = (Resolve-Path '.\third_party_local\nvidia\DLSS_SDK_310.7.0')
+$runtimeRoot = (Resolve-Path '.\runtime_local\nvidia')
+& $cmake --preset x64-debug -DCMAKE_TOOLCHAIN_FILE="$vcpkgToolchain" -DVCPKG_TARGET_TRIPLET=x64-windows -DVEYRA_DLSS_SDK_ROOT="$dlssRoot" -DVEYRA_RUNTIME_ROOT="$runtimeRoot" -DVEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON
+& $cmake --build --preset x64-debug
+& $cmake --build --preset x64-debug --target veyra_nr_harness
+~~~
+
+不要把这些机器绝对路径提交进 `CMakePresets.json`。共享 preset 用 cache variable 占位;本机覆盖放 ignored 的 `CMakeUserPresets.json` 或让 `scripts/configure.ps1` 解析。
+
+---
+
+# 6. GPU 基础层,必须先写对
+
+## 6.1 Adapter 和 device
+
+`D3D12DeviceContext` 初始化顺序:
+
+1. 可选启用 `ID3D12Debug`;
+2. `CreateDXGIFactory2`;
+3. `IDXGIFactory6::EnumAdapterByGpuPreference(HIGH_PERFORMANCE)`;
+4. 只选 `VendorId == 0x10DE` 且非 software adapter;
+5. `D3D12CreateDevice`,最低 feature level 12_0;
+6. 创建 direct command queue;
+7. 创建 fence/event;
+8. 记录 adapter description、LUID、dedicated memory、driver/runtime report。
+
+不要偷偷 fallback 到 WARP 后继续报告“DLSS 已启用”。runtime probe 可显示 WARP,但 NR backend 必须返回 unsupported。
+
+## 6.2 Command slots
+
+创建 4 个 slot,每个拥有:
+
+~~~text
+ID3D12CommandAllocator
+fenceValue
+2 个 timestamp query index
+临时 descriptor range
+保持本帧 AVFrame/texture 存活的引用
+~~~
+
+每帧只等待“将要复用的 slot 的 fence”,不是等待刚提交的当前帧。正常队列深度最多 1 个待处理 real frame。Phase 1 创建 Feature 后允许同步等待一次。
+
+## 6.3 Barrier 原则
+
+建立统一 `ResourceStateTracker`,不要在各 backend 猜状态。NR Evaluate 前:
+
+~~~text
+Color / MVec / Depth:
+ D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE
+
+Output:
+ D3D12_RESOURCE_STATE_UNORDERED_ACCESS
+~~~
+
+Evaluate 后对 Output 发 UAV barrier,再转为后续 parity shader 的 `NON_PIXEL_SHADER_RESOURCE`。如果官方对应 SDK 版本明确要求不同状态,以官方头/sample 为准,同时更新本表和 WORKLOG;禁止一个资源在代码里同时被两套 state tracker 管。
+
+所有 NR/parity pass 放在同一 direct command list/queue,避免跨 queue fence 增加延迟。
+
+## 6.4 纹理合同
+
+Phase 1 只要求 Proxy/Neural/Zero Guidance;Phase 2 再加入 Original/Final:
+
+~~~text
+Proxy: R8G8B8A8_UNORM, 1920x1080, ALLOW_UNORDERED_ACCESS,Phase 1 直接生成
+Neural: R8G8B8A8_UNORM, 1920x1080, ALLOW_UNORDERED_ACCESS
+ZeroMotion: R16G16_FLOAT, 1920x1080, 全 0
+ZeroDepth: R32_FLOAT, 1920x1080, 全 0
+Confidence: R8_UNORM, 1920x1080, 全 0,仅 guidance 内部
+
+Original: R16G16B16A16_FLOAT, 1920x1080, ALLOW_UNORDERED_ACCESS,Phase 2 加入
+Final: R16G16B16A16_FLOAT, 1920x1080, ALLOW_UNORDERED_ACCESS,Phase 2 加入
+~~~
+
+不允许把 motion/depth 设为 null。即使不用真实 guidance,也传入尺寸正确、格式正确、全零的纹理。
+
+---
+
+# 7. NGX Core Host
+
+文件:
+
+~~~text
+src/ngx/NgxCoreHost.h
+src/ngx/NgxCoreHost.cpp
+src/ngx/NgxResult.cpp
+src/ngx/NgxParameters.h
+~~~
+
+## 7.1 一进程一次
+
+`NgxCoreHost` 对一个 D3D12 device 只初始化一次。SR、NR、FG 是 consumer,不得各自调用一套 core Init/Shutdown。
+
+初始化伪代码:
+
+~~~cpp
+const wchar_t* featurePaths[] = { runtimeDir.c_str() };
+NVSDK_NGX_FeatureCommonInfo common{};
+common.PathListInfo.Path = featurePaths;
+common.PathListInfo.Length = 1;
+
+auto result = NVSDK_NGX_D3D12_Init_with_ProjectID(
+ veyraProjectId.c_str(),
+ NVSDK_NGX_ENGINE_TYPE_CUSTOM,
+ "Veyra-Experimental-0.1.0",
+ runtimeDir.c_str(),
+ device,
+ &common,
+ NVSDK_NGX_Version_API);
+~~~
+
+所有参数块统一由 core 创建/销毁:
+
+~~~text
+NVSDK_NGX_D3D12_AllocateParameters
+NVSDK_NGX_D3D12_GetCapabilityParameters
+NVSDK_NGX_D3D12_DestroyParameters
+~~~
+
+最终 consumer 和 parameter block 都释放后,才调用:
+
+~~~text
+NVSDK_NGX_D3D12_Shutdown1(device)
+~~~
+
+## 7.2 外部调用保护
+
+当前 runtime 是实验构建。每个 NGX 外部入口包在 MSVC SEH 边界:
+
+~~~cpp
+__try {
+ result = external_call(...);
+} __except(EXCEPTION_EXECUTE_HANDLER) {
+ sehCode = GetExceptionCode();
+ result = NVSDK_NGX_Result_FAIL_PlatformError;
+}
+~~~
+
+SEH 不是正常控制流。每次触发都视为失败,记录 operation、feature、result hex、SEH code,停止当前 backend,不能吞掉后继续 present 垃圾纹理。
+
+---
+
+# 8. Feature 18 Runtime Adapter:精确调用协议
+
+文件:
+
+~~~text
+src/ngx/DlssNrBackend.h
+src/ngx/DlssNrBackend.cpp
+src/ngx/DlssNrRuntimeAdapter.h
+src/ngx/DlssNrRuntimeAdapter.cpp
+src/ngx/DlssNrParameters.h
+~~~
+
+`DlssNrRuntimeAdapter.cpp` 是项目里唯一允许知道以下内容的文件:
+
+- Feature ID 18;
+- signed snippet application ID;
+- DLL 导出函数签名;
+- caller-name compatibility;
+- 本地 runtime 路径和实验开关。
+
+这样未来 NVIDIA 正式 SDK 到来时,只替换 adapter,不拆整个播放器。
+
+## 8.1 编译门
+
+只有 `VEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON` 才编译 adapter。Release/发行 preset 默认 OFF。本地启用时启动日志必须明确显示:
+
+~~~text
+EXPERIMENTAL LOCAL-ONLY DLSSNR ADAPTER ENABLED
+~~~
+
+## 8.2 加载方式
+
+绝对路径:
+
+~~~cpp
+runtimeDir / L"nvngx_dlssnr.dll"
+~~~
+
+先验证 size/hash/signature,再:
+
+~~~cpp
+LoadLibraryExW(
+ absoluteDllPath.c_str(),
+ nullptr,
+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
+ LOAD_LIBRARY_SEARCH_SYSTEM32);
+~~~
+
+`absoluteDllPath` 必须先经 `GetFullPathNameW`/`std::filesystem::canonical` 解析并确认仍位于配置的 `runtime_local/nvidia`。`LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR` 只给同目录依赖,`LOAD_LIBRARY_SEARCH_SYSTEM32` 只给系统依赖;不要用 `LOAD_WITH_ALTERED_SEARCH_PATH`、裸 `LoadLibraryW` 或进程当前目录。
+
+解析并逐项非空检查:
+
+~~~cpp
+using InitExtFn = NVSDK_NGX_Result(NVSDK_CONV*)(
+ unsigned long long,
+ const wchar_t*,
+ ID3D12Device*,
+ NVSDK_NGX_Version,
+ const NVSDK_NGX_Parameter*);
+
+using CreateFeatureFn = NVSDK_NGX_Result(NVSDK_CONV*)(
+ ID3D12GraphicsCommandList*,
+ NVSDK_NGX_Feature,
+ NVSDK_NGX_Parameter*,
+ NVSDK_NGX_Handle**);
+
+using EvaluateFeatureFn = NVSDK_NGX_Result(NVSDK_CONV*)(
+ ID3D12GraphicsCommandList*,
+ const NVSDK_NGX_Handle*,
+ const NVSDK_NGX_Parameter*,
+ PFN_NVSDK_NGX_ProgressCallback);
+
+using ReleaseFeatureFn =
+ NVSDK_NGX_Result(NVSDK_CONV*)(NVSDK_NGX_Handle*);
+
+using ShutdownFn =
+ NVSDK_NGX_Result(NVSDK_CONV*)(ID3D12Device*);
+~~~
+
+导出名必须逐字一致:
+
+~~~text
+NVSDK_NGX_D3D12_Init_Ext
+NVSDK_NGX_D3D12_CreateFeature
+NVSDK_NGX_D3D12_EvaluateFeature
+NVSDK_NGX_D3D12_ReleaseFeature
+NVSDK_NGX_D3D12_Shutdown1
+~~~
+
+不要静态 link `nvngx_dlssnr.dll`,不要依赖当前目录搜索,不要改名为 `nvngx.dll`。
+
+## 8.3 caller-name compatibility 隔离层
+
+当前 signed snippet 会检查 caller module name。Magpie 的已验证路径在 DLL 的 `GetModuleFileNameW` import slot 上装一个最小兼容 shim:只有当查询的是 Veyra caller module 时返回 `nvngx.dll`,其他调用全部转发原始 `GetModuleFileNameW`。
+
+实现要求:
+
+1. 解析已加载 signed snippet 的 PE import table;
+2. 只寻找 KERNEL32/API-set 下名为 `GetModuleFileNameW` 的 IAT slot;
+3. 全局只允许一个 adapter session 持有该 slot;
+4. 保存原函数指针和旧页面保护;
+5. `VirtualProtect` 只覆盖一个指针宽度;
+6. `InterlockedExchangePointer` 安装 shim;
+7. 恢复页面保护并 `FlushInstructionCache`;
+8. shim 只对本模块 handle 返回字面量 `nvngx.dll`,并严格模拟 `GetModuleFileNameW` 的 buffer/return/error 语义;
+9. 所有其他 module handle 调原函数;
+10. Release/Shutdown 后必须逆序恢复原 IAT,再 `FreeLibrary`。
+
+Veyra caller module handle 用 shim 函数地址解析,不按 exe 文件名猜:
+
+~~~cpp
+GetModuleHandleExW(
+ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+ reinterpret_cast<LPCWSTR>(shimFunctionAddress),
+ &callerModule);
+~~~
+
+shim 的边界测试必须覆盖:`hModule == callerModule`、`nullptr`、`nSize == 0`、刚好容纳 10 个 wchar(9 字符加 NUL)、过小 buffer 和非 caller module。`nSize == 0` 时返回 0、不得访问 buffer、不得改变 last-error;过小 buffer 必须 NUL 截断、返回 `nSize` 并设置 `ERROR_INSUFFICIENT_BUFFER`;正常返回 9(不含 NUL)。测试要先写入 sentinel last-error,分别验证成功、截断和零长度路径。禁止 `wcscpy` 和越界写。所有非 caller 情况原样转发保存的真实函数指针。
+
+不要 patch DLL 文件,不要全局 hook Kernel32,不要影响进程内其他模块。这个兼容层是未公开、脆弱、只限本机实验的东西,必须能通过一个编译开关完全移除。
+
+如果 IAT 中没有目标 import、已有其他 owner、`VirtualProtect` 失败或不能恢复,立即报错并停止 NR;不允许退化成更宽泛的 hook。
+
+独立实现时只参考 Magpie 对外行为,不复制 GPL 源码。参考位置:
+
+~~~text
+Magpie experimental:
+src/Magpie.Core/DLSSNRFilter.cpp
+ SnippetGetModuleFileNameW
+ FindImportedFunctionSlot
+ InstallSnippetCallerCompatibility
+ RestoreSnippetCallerCompatibility
+~~~
+
+## 8.4 signed snippet 初始化
+
+常量:
+
+~~~cpp
+constexpr auto kDlssNrFeature =
+ static_cast<NVSDK_NGX_Feature>(18);
+constexpr unsigned long long kSignedSnippetAppId = 0x0876232Cull;
+~~~
+
+这个 App ID 来自当前 signed snippet 的已验证调用合同;它不是 Veyra NGX Project ID,二者不能混用。
+
+调用:
+
+~~~cpp
+snippetInitExt(
+ 0x0876232Cull,
+ runtimeDir.c_str(),
+ device,
+ NVSDK_NGX_Version_API,
+ nullptr);
+~~~
+
+顺序必须是:
+
+~~~text
+NgxCoreHost Init
+→ Load signed snippet
+→ install narrow caller compatibility
+→ signed snippet Init_Ext
+→ core AllocateParameters
+→ set create parameters
+→ signed snippet CreateFeature(feature 18)
+→ close/execute init command list
+→ wait once for creation
+~~~
+
+不要默认走 core 的 `NVSDK_NGX_D3D12_CreateFeature(18)`。在 Magpie 当前实现中,core Feature 18 路径只保留为显式 diagnostic,正常路径是 signed snippet export。
+
+## 8.5 Create 参数,名字和类型
+
+所有字符串集中在 `DlssNrParameters.h`,禁止散落:
+
+| 参数 | 类型 | Phase 1 值 |
+|---|---:|---:|
+| `DLSSNR.Width` | uint32 | width |
+| `DLSSNR.Height` | uint32 | height |
+| `DLSSNR.InputWidth` | uint32 | width |
+| `DLSSNR.InputHeight` | uint32 | height |
+| `DLSSNR.OutputWidth` | uint32 | width |
+| `DLSSNR.OutputHeight` | uint32 | height |
+| `DLSSNR.Output.Width` | uint32 | width |
+| `DLSSNR.Output.Height` | uint32 | height |
+| `DLSSNR.Upscaling` | uint32 | 0 |
+| `DLSSNR.Scale` | float | 1.0 |
+| `DLSSNR.ScalingRatio` | float | 1.0 |
+| `DLSSNRComputeScalingRatioCallback` | void* callback | callback sets ratio 1.0 |
+| `DLSSNR.Hint.Render.Preset` | int | profile preset |
+| `Width` / NGX standard width | uint32 | width |
+| `Height` / NGX standard height | uint32 | height |
+| `PerfQualityValue` | int | Balanced |
+| `CreationNodeMask` | uint32 | 1 |
+| `VisibilityNodeMask` | uint32 | 1 |
+
+不要省略那些看似重复的 width/height。当前实验 runtime 同时观察 DLSSNR 自定义名和 NGX 标准名。
+
+`DLSSNRComputeScalingRatioCallback` 签名接受 `NVSDK_NGX_Parameter*`,内部只设置:
+
+~~~cpp
+params->Set("DLSSNR.ScalingRatio", 1.0f);
+return NVSDK_NGX_Result_Success;
+~~~
+
+## 8.6 Evaluate 参数,名字和类型
+
+资源:
+
+| 参数 | 类型 | 值 |
+|---|---|---|
+| `DLSSNR.Color` | ID3D12Resource* | Proxy |
+| `DLSSNR.Output` | ID3D12Resource* | Neural |
+| `DLSSNR.MVec` | ID3D12Resource* | Motion 或 ZeroMotion |
+| `DLSSNR.Depth` | ID3D12Resource* | Depth 或 ZeroDepth |
+
+每个资源都设置完整 subrect,类型为 uint32:
+
+~~~text
+DLSSNR.ColorSubrectBaseX/Y/Width/Height
+DLSSNR.OutputSubrectBaseX/Y/Width/Height
+DLSSNR.MVecSubrectBaseX/Y/Width/Height
+DLSSNR.DepthSubrectBaseX/Y/Width/Height
+~~~
+
+Phase 1 均为 `0, 0, width, height`。
+
+其他参数:
+
+| 参数 | 类型 | 默认 |
+|---|---:|---:|
+| `DLSSNR.MVecScaleX` | float | 1.0 |
+| `DLSSNR.MVecScaleY` | float | 1.0 |
+| `DLSSNR.DepthInverted` | int | 1 |
+| `DLSS.Indicator.Invert.X.Axis` | int | 0 |
+| `DLSS.Indicator.Invert.Y.Axis` | int | 0 |
+| `DLSSNR.Enabled` | int | 1 |
+| `DLSSNR.Reset` | int | 首帧/seek/resize/scene cut 为 1,否则 0 |
+| `DLSSNR.Style` | int | 0 |
+| `DLSSNR.Intensity` | float | 1.0 |
+| `DLSSNR.LocalToneStrength` | float | 1.0 |
+| `DLSSNR.LocalStructureStrength` | float | 1.0 |
+| `DLSSNR.SkinStructureStrength` | float | -1.0 |
+| `DLSSNR.UseAutoMask` | int | 0 |
+| `DLSSNR.UICorrection` | int | 0 |
+
+这些默认值与当前 Magpie Experimental 的 baseline 一致。不要先发明 slider 范围。Phase 1 用 JSON profile 直接写值;等通过 reference capture 确认 UI 合法范围后再加 clamp。
+
+## 8.7 每帧执行
+
+Phase 1 一个 frame 的 command list:
+
+~~~text
+reset reusable slot
+→ GenerateTestPattern 直接写 Proxy RGBA8
+→ barriers
+→ set every Evaluate parameter
+→ signed snippet EvaluateFeature(cmd, handle, params, nullptr)
+→ UAV barrier on Neural
+→ timestamp resolves
+→ close and submit once
+→ signal slot fence
+~~~
+
+Phase 2 再把前半段换成“生成/加载 Original → ParityEncode 写 Proxy”,并在 Neural 后接 ParityDecode 写 Final。Phase 1 不得为了提前追求最终观感而把 parity bug 混进 Feature 18 调用验证。
+
+Evaluate 返回成功只表示命令记录成功,不表示像素一定正确。Phase 1 同时检查:
+
+- output 非全黑/非全常数;
+- 无 NaN/Inf;
+- 修改 Style/Intensity 时 output hash 会变化;
+- 300 次 evaluateSuccessCount == 300;
+- D3D12 debug layer 无 resource-state error;
+- GPU timestamp 非 0。
+
+## 8.8 释放顺序
+
+~~~text
+drain GPU slots
+→ signed snippet ReleaseFeature
+→ core DestroyParameters
+→ signed snippet Shutdown1(device)
+→ restore caller IAT
+→ FreeLibrary(snippet)
+→ release NR textures
+→ release NR consumer from NgxCoreHost
+→ all NGX consumers gone后 core Shutdown1(device)
+~~~
+
+每一步即使前一步失败也要尝试安全清理剩余已初始化对象。用显式 init-state bitmask/RAII,不用一个 `initialized=true` 糊住部分初始化。
+
+---
+
+# 9. RenoDX Parity Codec:如何做到“类似 ReShade”
+
+这部分才是“类似 ReShade”的核心。Feature 18 只输出 neural proxy;RenoDX 的观感还来自前后的颜色传递。直接把播放器线性 FP16 喂给 NR 或把 Raw Neural 直接 present,都会发生 gamma、亮度和高光错误。
+
+文件:
+
+~~~text
+shaders/ParityEncode.hlsl
+shaders/ParityDecode.hlsl
+src/parity/RenoDxParityCodec.*
+src/parity/RenoDxParityProfile.*
+tests/unit/ParityCpuReference.*
+~~~
+
+## 9.1 固定资源
+
+~~~text
+Original = 线性 BT.709 working RGB,R16G16B16A16_FLOAT
+Proxy = encode 后,R8G8B8A8_UNORM
+Neural = Feature 18 raw output,R8G8B8A8_UNORM
+Final = decode/reconstruct 后,R16G16B16A16_FLOAT
+~~~
+
+四个阶段必须可抓:
+
+~~~text
+00_original
+01_proxy_input
+02_raw_dlssnr
+03_final_parity_output
+~~~
+
+## 9.2 Parity Encode 的确定数学
+
+对每个 RGB 分量:
+
+~~~text
+linear = max(Original.rgb, 0) / PaperWhiteScale
+
+shoulder(x) =
+ 0.75 + 0.25 * (1 - exp(-5.7780 * (x - 0.75)))
+
+proxyLinear =
+ x <= 0.75 ? x : shoulder(x)
+
+Proxy.rgb = sRGBEncode(proxyLinear)
+Proxy.a = Original.a
+~~~
+
+`5.7780` 是当前 addon binary 中可观察到的 codec 常数。不要随意换成 filmic curve。
+
+标准 sRGB:
+
+~~~text
+Encode(c):
+ c <= 0.0031308
+ ? 12.92 * c
+ : 1.055 * pow(c, 1/2.4) - 0.055
+
+Decode(c):
+ c <= 0.04045
+ ? c / 12.92
+ : pow((c + 0.055) / 1.055, 2.4)
+~~~
+
+dispatch:
+
+~~~text
+[numthreads(16,16,1)]
+groupsX = ceil(width / 16)
+groupsY = ceil(height / 16)
+越界线程必须 return
+~~~
+
+## 9.3 Parity Decode 的确定数学
+
+亮度:
+
+~~~text
+Y = dot(rgb, (0.212639, 0.715169, 0.072192))
+~~~
+
+读取:
+
+~~~text
+original = max(Original.rgb, 0) / PaperWhiteScale
+proxy = sRGBDecode(Proxy.rgb)
+neural = sRGBDecode(Neural.rgb)
+~~~
+
+OkLab 矩阵必须按下面数值、以 `mul(matrix, vector)` 的方向使用,别转置:
+
+~~~text
+RGB → LMS
+0.4122214708 0.5363325363 0.0514459929
+0.2119034982 0.6806995451 0.1073969566
+0.0883024619 0.2817188376 0.6299787005
+
+cuberoot(LMS) → OkLab
+0.2104542553 0.7936177850 -0.0040720468
+1.9779984951 -2.4285922050 0.4505937099
+0.0259040371 0.7827717662 -0.8086757660
+
+OkLab → LMS'
+1.0 0.3963377774 0.2158037573
+1.0 -0.1055613458 -0.0638541728
+1.0 -0.0894841775 -1.2914855480
+
+LMS³ → RGB
+ 4.0767416621 -3.3077115913 0.2309699292
+-1.2684380046 2.6097574011 -0.3413193965
+-0.0041960863 -0.7034186147 1.7076147010
+~~~
+
+cuberoot 必须是 signed:
+
+~~~text
+sign(x) * pow(abs(x), 1/3)
+~~~
+
+AP1 gamut clamp:
+
+~~~text
+BT.709 → AP1
+0.613097 0.339523 0.047379
+0.070194 0.916354 0.013452
+0.020616 0.109570 0.869815
+
+AP1 → BT.709
+ 1.705051 -0.621792 -0.083259
+-0.130256 1.140805 -0.010548
+-0.024003 -0.128969 1.152972
+
+ClampAp1(c) = AP1To709(max(0, BT709ToAP1(c)))
+~~~
+
+HueOkLab:
+
+~~~text
+incorrectLab = ToOkLab(incorrect)
+correctLab = ToOkLab(correct)
+incorrectChroma = length(incorrectLab.ab)
+correctChroma = length(correctLab.ab)
+incorrectLab.ab =
+ correctLab.ab *
+ (correctChroma == 0 ? 1 : incorrectChroma / correctChroma)
+return ClampAp1(FromOkLab(incorrectLab))
+~~~
+
+UpgradeToneMap:
+
+~~~text
+originalY = Luminance(original)
+proxyY = Luminance(proxy)
+neuralY = Luminance(neural)
+
+if originalY < proxyY:
+ ratio = originalY / proxyY
+else:
+ newY = neuralY + max(0, originalY - proxyY)
+ ratio = neuralY > 0 ? newY / neuralY : 0
+
+scaled = HueOkLab(neural * ratio, neural)
+upgraded = lerp(original, scaled, TransferStrength)
+~~~
+
+最终:
+
+~~~text
+originalY = Luminance(original)
+upgradedY = Luminance(upgraded)
+ratio = originalY == 0 ? 1 : upgradedY / originalY
+luminanceOnly = original * ratio
+result = lerp(luminanceOnly, upgraded, ColorStrength)
+Final = float4(result * PaperWhiteScale, Original.a)
+~~~
+
+## 9.4 Parity 配置
+
+三个 codec 参数和 NR 参数分开:
+
+~~~json
+{
+ "schema": 1,
+ "paperWhiteScale": 1.0,
+ "transferStrength": 1.0,
+ "colorStrength": 1.0,
+ "nr": {
+ "preset": 0,
+ "style": 0,
+ "intensity": 1.0,
+ "localToneStrength": 1.0,
+ "localStructureStrength": 1.0,
+ "skinStructureStrength": -1.0,
+ "useAutoMask": false,
+ "uiCorrection": false
+ }
+}
+~~~
+
+`paperWhiteScale/transferStrength/colorStrength = 1.0` 是 V1 的规范化中性工程 baseline,不得谎称它就是 addon 所有环境下的 UI 默认。当前项目没有 ReShade/RenoDX preset;`renodx-dlss5-1.addon64` 是二进制 add-on,不是 profile。Phase 2 必须把这三个 baseline 值、addon hash、输入/输出分辨率和 capture hash 一起记录。若用户以后提供真实 preset,只把它导入为单独命名的可选 reference profile;preset 缺失不阻塞 V1,也禁止通过加载 addon 取值。
+
+## 9.5 单元测试
+
+写一份独立 CPU float reference,不调用 GPU:
+
+- 纯黑、纯白、18% gray;
+- 0.75 阈值左右 `0.7499/0.75/0.7501`;
+- 高光 `1/2/4/8`;
+- RGB primary、肤色近似值;
+- 负分量和 alpha;
+- 64×64 gradient/checker/edge pattern。
+
+测试:
+
+~~~text
+CPU encode → quantize RGBA8 → CPU decode
+GPU encode → readback RGBA8
+GPU decode → readback FP16
+~~~
+
+容差:
+
+~~~text
+Proxy RGBA8: 每通道最多 1 code value
+Final FP16: abs error <= 0.002,且无 NaN/Inf
+~~~
+
+只有 diagnostic capture 工具允许同步 GPU readback。正常播放器路径不允许。
+
+---
+
+# 10. Frame Guidance
+
+统一数据合同:
+
+~~~cpp
+struct GuidanceFrame {
+ uint64_t frameId;
+ uint32_t width;
+ uint32_t height;
+ ID3D12Resource* motion; // R16G16_FLOAT
+ ID3D12Resource* depth; // R32_FLOAT
+ ID3D12Resource* confidence; // R8_UNORM
+ bool motionIsZero;
+ bool depthIsZero;
+ bool requiresHistoryReset;
+};
+~~~
+
+固定语义:
+
+~~~text
+Motion direction: Current → Previous
+Motion unit: source pixels
+Motion scale: 1.0, 1.0 after conversion
+Depth: relative inverse if real
+Depth inverted: true
+~~~
+
+## 10.1 Zero Guidance
+
+Phase 1 就实现。每个 frameId 发布尺寸正确的全零 motion/depth/confidence;metadata 不能复用旧 frameId。第一帧、seek、resize、scene cut、device recreate 设置 reset。
+
+Zero Guidance 是诚实的 fallback,不得在日志/UI 显示为 NVOF。
+
+## 10.2 NVOF D3D12
+
+Phase 5 再做。调用路径:
+
+~~~text
+Load System32 nvofapi64.dll
+→ NvOFGetMaxSupportedApiVersion
+→ NvOFAPICreateInstanceD3D12
+→ nvCreateOpticalFlowD3D12(device)
+→ nvOFGetCaps
+→ nvOFInit
+→ register current/reference/output/cost resources
+→ queue waits on producer fence
+→ nvOFExecuteD3D12
+→ graphics queue waits on NVOF output fence
+→ NvofVectorConvert compute
+~~~
+
+初始配置:
+
+~~~text
+mode: NV_OF_MODE_OPTICALFLOW
+perfLevel: NV_OF_PERF_LEVEL_MEDIUM
+external hints: false
+output cost: true, UINT8
+prediction: forward
+grid: 首选 1x1;不支持则 2x2/4x4 后 densify
+input/reference: current frame → previous frame
+~~~
+
+NVOF 不直接接受 Veyra 的 `Original/Final R16G16B16A16_FLOAT`。Phase 5 baseline 在 optional SR 之后、NR 之前,从同一 pre-NR linear frame 用 compute shader 生成专用 8-bit `NvofInput`,通过 SDK D3D12 buffer/register 路径声明为 `NV_OF_BUFFER_FORMAT_ABGR8`;全程 GPU-resident,不做 CPU 像素回读。实际 DXGI resource format、row pitch 和 RGBA/ABGR 通道映射必须以 SDK 5.0 D3D12 sample/返回的 resource desc 为准,并用 RGB bars 验证,禁止凭枚举名字猜 swizzle。
+
+至少保留 current/previous 两组独立注册 buffer 并用 fence 轮转;第一帧没有 previous 时发布 Zero Guidance,不调用 NVOF。seek/resize/scene-cut/device recreate 后,下一次 execute 设置 `disableTemporalHints = 1`,不得让 NVOF 内部 temporal hint 跨历史边界。
+
+NVOF raw vector 是 signed 10.5 fixed point,X/Y 各 16 bit。转 source-pixel float 时除以 32。若 grid 大于 1,按 SDK sample 的坐标定义 densify 到完整尺寸,不能简单把 raw texture 当 `R16G16_FLOAT`。
+
+NVOF 的 UINT8 cost 越高表示越不可信;内部字段既然命名为 confidence,就统一转换为 `1.0 - cost / 255.0` 后写 `R8_UNORM`。禁止把 raw cost 原样写入却标成 confidence。
+
+NVOF API context 非线程安全。一个 context 只在 guidance worker/受 mutex 保护的单一调用点使用。
+
+选择 current 为 input、previous 为 reference,是为了得到 Current→Previous。用一个平移测试片验证符号:画面向右平移时,当前像素回查 previous 的方向必须与 contract 一致;符号错误就修 producer,禁止在 NR 和 FG 两边各自乘一次 -1。
+
+## 10.3 Guidance 尺寸
+
+V1 让 NVOF 在 DLSSNR 的 working extent 上工作:
+
+- 无 SR:video output extent;
+- 有 SR:SR 输出/NR 输入 extent。
+
+这样 NR/FG 都消费同一份 full-resolution motion,`MVecScaleX/Y=1`。不要在一个 backend 用 render resolution、另一个用 output resolution。
+
+---
+
+# 11. DLSS Super Resolution
+
+Phase 4 实现,独立 backend:
+
+~~~text
+src/ngx/DlssSrBackend.*
+~~~
+
+使用官方 `nvsdk_ngx_helpers.h`:
+
+~~~text
+NGX_D3D12_CREATE_DLSS_EXT
+NGX_D3D12_EVALUATE_DLSS_EXT
+~~~
+
+资源和参数以 310.7.0 header 为真源,不手写一套私有字符串。
+
+策略:
+
+- input extent == output extent:整个 SR backend bypass;
+- input extent < output extent:SR 先执行,NR 后执行;
+- 第一轮用 Zero Guidance、jitter 0、preExposure 1 跑通;`reset=1` 只用于首帧和真实 history invalidation,正常后续帧必须为 0;
+- V1 的 SR 始终使用 Zero Guidance;full-resolution NVOF 在 SR 输出后生成,只供 NR/FG,禁止让 SR 反向依赖自己的输出;
+- SDR V1 不设置 HDR feature flag;
+- seek/resize/quality mode change 时 Release/Create 并 reset;
+- 不允许让 DLSSNR 自己兼任放大。
+
+Phase 4 必须单独抓:
+
+~~~text
+decoded_linear
+sr_output
+nr_proxy
+nr_raw
+final
+~~~
+
+如果 SR output gamma 错,先查输入是不是 linear、pre-exposure、format 和 range,不调 NR 参数掩盖。
+
+---
+
+# 12. DLSS Frame Generation 2X
+
+Phase 6 实现:
+
+~~~text
+src/ngx/DlssFgBackend.*
+src/player/GeneratedFrameScheduler.*
+~~~
+
+使用官方:
+
+~~~text
+nvsdk_ngx_helpers_dlssg.h
+NGX_D3D12_CREATE_DLSSG_EXT
+NGX_D3D12_EVALUATE_DLSSG_EXT
+~~~
+
+先从 capability parameters 读取:
+
+~~~text
+NVSDK_NGX_Parameter_FrameGeneration_Available
+NVSDK_NGX_Parameter_FrameGeneration_FeatureInitResult
+NVSDK_NGX_DLSSG_Parameter_MultiFrameCountMax
+~~~
+
+V1 固定 2X,即每相邻 real frame 只生成 1 帧:
+
+~~~text
+multiFrameCount = 1
+multiFrameIndex = 1
+~~~
+
+Create:
+
+~~~text
+Width/Height: 最终 backbuffer extent
+RenderWidth/RenderHeight: guidance extent
+NativeBackbufferFormat: Final NR color format
+~~~
+
+如果永远不提供以下资源,按官方 header/Magpie 已验证路径设置 `ResourceNeverProvided_Flags`:
+
+~~~text
+HUDLess
+UI
+UIAlpha
+BidirectionalDistortionField
+OutputReal
+~~~
+
+Evaluate 基线:
+
+~~~text
+pBackbuffer = 当前 Final NR real frame
+pMVecs = NVOF motion 或 ZeroMotion
+pDepth = ZeroDepth(V1 不估深度)
+pOutputInterpFrame = generated output
+pOutputDisableInterpolation = 4-byte/required output buffer
+BackbufferFrameID = 单调 frameId
+mvecScale = 1/width,1/height(GuidanceFrame 是 source-pixel 单位)
+reset = history reset flag
+cameraMotionIncluded = NVOF dense motion 时 true,Zero Motion 时 false
+depthInverted = false when using zero depth
+camera matrices = identity baseline
+~~~
+
+`mvecScale` 是 DLSSG 的归一化倍率,不是 Feature 18 的 `DLSSNR.MVecScaleX/Y`。
+官方 310.7 helper 要求 scale 后的 motion 落入 `[-1,1]`;因此 full-resolution
+source-pixel motion 使用 `{1/width, 1/height}`,平移测试同时验证方向和幅值。
+所有 backbuffer/motion/depth/output subrect 都显式填满各自 extent,不能依赖
+结构体的零尺寸默认值。
+
+已锁定的 Magpie experimental commit 在这一字段使用 `{1,1}`,与官方 header
+注释矛盾。实现 `DlssgMvecScaleMode::{OfficialNormalized, MagpieUnitDiagnostic}`:
+V1 默认且可发布路径只能是 `OfficialNormalized`;后者只允许 harness 显式选择,
+用于复现上游行为和定位 runtime 差异。Phase 6 的固定平移片必须把 mode、scale、
+输入 motion 的 min/max、generated hash/counter 和几何方向/幅值一起写入日志;
+不能因为两个模式都返回 success 就声称二者等价,也不能自动把诊断模式保存成默认。
+
+UI 必须在 FG 之后叠加。若把 UI 放进 `pBackbuffer`,FG 会把字幕、按钮和鼠标一起插值,结果不等价于 RenoDX 的“UI downstream”。
+
+## 12.1 时序
+
+要生成 F0 与 F1 中间的 G0.5,必须先拿到 F1。因此 2X FG 有至少一个 source-frame 的时间依赖:
+
+~~~text
+decode/process F0, hold
+decode/process F1
+evaluate FG using history/current
+present F0
+present G0.5
+present F1
+~~~
+
+实际 NVIDIA helper 的发布顺序以 runtime contract 为准,但 scheduler 必须明确 real/generated PTS,不能重复帧冒充。
+
+对源帧间隔 Δ:
+
+~~~text
+PTS(G between A,B) = (PTS(A) + PTS(B)) / 2
+~~~
+
+变帧率视频按相邻真实 PTS 插值,不按 nominal FPS 猜。
+
+## 12.2 证明真的插帧
+
+同时满足:
+
+- capability available;
+- Create/Evaluate success;
+- `pOutputDisableInterpolation` 表明 interpolation 没被 runtime 禁用;
+- generated frame hash 不等于前后 real frame;
+- 实际 Present 计数接近 real×2;
+- debug overlay 分开显示 real/generated;
+- seek/pause/resize 后旧 generated frame 不再 present。
+
+理论设置 2X 或把上一帧重复 present 两次都不算成功。
+
+---
+
+# 13. FFmpeg 媒体管线
+
+Phase 3 先 video-only。分两小步:
+
+## 13.1 Phase 3A:功能基线
+
+先用软件 decode + upload 验证 demux、PTS、seek/reset 和连续 NR。这个路径只用于 bring-up,不是最终性能路径。
+
+~~~text
+avformat_open_input
+→ avformat_find_stream_info
+→ av_find_best_stream(video)
+→ avcodec_alloc_context3 / parameters_to_context
+→ avcodec_open2
+→ packet send / frame receive
+→ swscale to BGRA/NV12 if needed
+→ upload to D3D12
+~~~
+
+完成后立刻进入 3B,不要把 CPU upload 当最终“零拷贝播放器”。
+
+## 13.2 Phase 3B:D3D12VA,共用 Veyra device
+
+使用 FFmpeg `AV_HWDEVICE_TYPE_D3D12VA`,不要让 FFmpeg 另建 adapter/device:
+
+~~~cpp
+AVBufferRef* ref = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D12VA);
+auto* hw = reinterpret_cast<AVHWDeviceContext*>(ref->data);
+auto* d3d = reinterpret_cast<AVD3D12VADeviceContext*>(hw->hwctx);
+
+d3d->device = veyraDevice;
+veyraDevice->AddRef(); // FFmpeg context owns/release this interface
+
+av_hwdevice_ctx_init(ref);
+codec->hw_device_ctx = av_buffer_ref(ref);
+~~~
+
+`get_format` 只在 decoder 提供时选择 `AV_PIX_FMT_D3D12`;否则记录 codec/profile 并 fallback software,不要声称硬解。
+
+每个硬解 AVFrame:
+
+~~~cpp
+auto* d3dFrame =
+ reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);
+
+ID3D12Resource* texture = d3dFrame->texture;
+int subresource = d3dFrame->subresource_index;
+auto& sync = d3dFrame->sync_ctx;
+~~~
+
+不要把 `frame->data[0]` 直接 cast 为 `ID3D12Resource*`。
+
+固定 FFmpeg 9.0.1 的 `AVD3D12VAFrame::subresource_index` 在 texture-array 模式表示 array slice。创建 NV12/P010 plane SRV 时:
+
+- 非 array texture 使用 `Texture2D.PlaneSlice = 0/1`;
+- array texture 使用 `Texture2DArray.FirstArraySlice = subresource_index`、`ArraySize = 1`、`PlaneSlice = 0/1`;
+- 不得把 `subresource_index` 当 plane index,也不得永远读取 array slice 0;
+- 日志记录 `d3dFrame->flags`、resource desc、array slice 和两个 plane SRV 描述。
+
+等待 `sync_ctx.fence/value` 后,再对实际 slice/plane 做正确的 state transition;对应 `AVFrame` 必须继续存活到 Veyra graphics fence 完成。
+
+GPU 同步:
+
+~~~text
+graphicsQueue->Wait(sync.fence, sync.fence_value)
+~~~
+
+这是 GPU queue wait,不是 CPU `WaitForSingleObject`。必须保持对应 `AVFrame`/`AVBufferRef` 存活,直到消费该 surface 的 graphics fence 完成。
+
+## 13.3 YUV → linear RGB
+
+`YuvToLinearRgb.hlsl` 读取:
+
+- NV12:plane 0 `R8_UNORM`,plane 1 `R8G8_UNORM`;
+- P010:plane 0 `R16_UNORM`,plane 1 `R16G16_UNORM`。
+
+每帧根据 FFmpeg metadata 选择:
+
+~~~text
+color_range
+colorspace
+color_primaries
+color_trc
+chroma_location
+~~~
+
+V1 至少正确支持:
+
+~~~text
+BT.709 limited/full SDR
+BT.601 limited/full SDR
+NV12 8-bit
+P010 SDR fallback
+~~~
+
+HDR/PQ/HLG 在 V1 中明确报 unsupported/bypass NR,不可把 PQ 数值当线性 RGB。
+
+优化顺序:
+
+1. 先独立 YUV→Original shader,保证颜色正确;
+2. 再把 Proxy Encode 融合进同一 dispatch,同时写 Original FP16 和 Proxy RGBA8;
+3. 融合前后用固定帧测试保证 1 code value 内一致。
+
+## 13.4 Seek/reset
+
+seek 流程必须完整:
+
+~~~text
+pause scheduler
+→ stop accepting decoded frames
+→ drain/retire GPU slots
+→ avcodec_flush_buffers
+→ av_seek_frame / avformat_seek_file
+→ clear packet/frame queues
+→ reset playback clock
+→ reset SR/NR/FG/NVOF history
+→ first new frame carries Reset=1
+→ resume
+~~~
+
+只调 `av_seek_frame` 而不清历史会把 seek 前内容混进 Neural/FG 输出。
+
+---
+
+# 14. 音频、UI 和播放时钟
+
+Phase 7:
+
+~~~text
+FFmpeg audio decode
+→ swresample to 48 kHz float stereo
+→ event-driven WASAPI shared mode
+→ audio clock is master
+~~~
+
+视频 scheduler 按 PTS 对齐音频:
+
+- 视频早:等待;
+- 视频轻微晚:尽快 present;
+- 严重晚:只丢尚未进入 temporal chain 的 real frame,并立即 history reset;
+- FG 不改变音频时长;
+- pause 时音频和视频同时冻结;
+- seek 后清 WASAPI padding/重新基准。
+
+UI:
+
+- 正常底栏只显示播放/暂停、seek、音量、SR/NR/FG 开关;
+- 调试面板显示 runtime/hash、参数、result、GPU ms、queue depth、real/generated present counts、guidance type、reset reason;
+- ImGui 在 Final/Generated frame 之后绘制;
+- UI 开关改变 NR 配置时,标记下一 real frame reset,不能在一对 FG 中间切参数。
+
+---
+
+# 15. 延迟预算和不能犯的错误
+
+Parity Encode/Decode 是 compute shader,本身不需要帧缓存,只增加 GPU 执行时间。DLSSNR/NVOF 也主要增加 GPU time。真正不可避免的整帧等待主要来自 2X FG:生成中间帧前需要下一张 real frame。
+
+理论额外等待:
+
+~~~text
+24 fps source: one frame ≈ 41.7 ms
+30 fps source: one frame ≈ 33.3 ms
+60 fps source: one frame ≈ 16.7 ms
+~~~
+
+这是 temporal availability,不包括 decode、NR、FG GPU time 和显示扫描。最终必须实测,不得承诺固定值。
+
+低延迟规则:
+
+- decoded-ready queue 上限 1;
+- GPU in-flight slots 3–4,但不做多帧 lookahead;
+- 单 direct queue 串起 color/SR/NR/parity;
+- normal path 无 GPU→CPU pixel readback;
+- 不在每个 pass/每帧 CPU wait;
+- D3D12VA fence 用 queue wait;
+- Present 用 flip model,支持时用 waitable swapchain;
+- capture 模式和正常模式完全分开;
+- 关闭 FG 时不保留下一 real frame,立即 present;
+- 统计 `decode→present`、`NR GPU`、`FG GPU`、`queue depth` 和 `present cadence`。
+
+禁止:
+
+~~~text
+decode 4–8 帧排队再处理
+每帧 WaitForSingleObject
+每 pass ExecuteCommandLists
+用 CPU memcpy 在 FP16/RGBA8 间来回
+为了 debug 一直开启同步 readback
+FG 开启后仍按源 FPS sleep
+~~~
+
+---
+
+# 16. 分阶段施工与硬门槛
+
+## Phase 0 — Runtime probe + D3D12 skeleton
+
+实现:
+
+~~~text
+veyra_runtime_probe
+D3D12DeviceContext
+CommandSlotRing
+ResourceStateTracker
+GpuProfiler
+RuntimeManifest
+Win32 test window
+~~~
+
+`veyra_runtime_probe --runtime-dir <absolute>` 输出:
+
+~~~text
+OS build
+adapter name/vendor/LUID/VRAM
+driver version
+D3D12 feature level
+DLL path/size/SHA256/file version/signature
+required export present/missing
+nvofapi64 path/version
+experimental flag
+~~~
+
+完成门槛:
+
+- Debug/Release 均可构建;
+- D3D12 窗口循环 5 分钟无 device removed;
+- runtime hash/signature 与 manifest 一致;
+- proprietary files 都是 ignored;
+- WORKLOG 记录真实命令和输出。
+
+## Phase 1 — Feature 18 Native Harness
+
+CLI 必须支持:
+
+~~~text
+veyra_nr_harness
+ --runtime-dir <absolute>
+ --width 1920
+ --height 1080
+ --frames 300
+ --guidance zero
+ --profile config/nr-default.json
+ --capture-frame 0
+ --capture-dir captures/phase1
+~~~
+
+输入由 `GenerateTestPattern.hlsl` 直接生成 RGBA8 Proxy,包含 gradient、checker、硬边和 RGB bars。Phase 1 先不依赖 Original、Parity Shader 或外部图片。
+
+完成门槛:
+
+- signed snippet Init_Ext success;
+- Feature 18 handle 非空;
+- 300/300 Evaluate success;
+- raw output 非黑、无 NaN;
+- 至少两组 Style/Intensity 产生不同 output hash;
+- Release/Shutdown 后无 crash/device removed;
+- D3D12 debug layer 无 state/descriptor lifetime error;
+- 保存 `logs/phase1.log` 与 capture manifest。
+
+任何一项不满足,不进入 Phase 2/3。
+
+## Phase 2 — Parity Codec
+
+实现 CPU reference、两个 shader、四阶段 capture、profile。
+
+完成门槛:
+
+- `ParityCpuReference` 全过;
+- GPU/CPU encode 误差 ≤1 code;
+- GPU/CPU decode FP16 误差 ≤0.002;
+- Original/Proxy/Raw/Final 四份真实抓帧存在;
+- 没有系统性洗白、压黑、截高光、整体偏色;
+- V1 中性 baseline 的三个 codec 参数、来源说明和 capture hash 已记录;
+- Raw/Final 可即时切换,证明 parity 确实执行。
+
+## Phase 3 — Minimal Video Pipeline
+
+3A 软件 decode,3B D3D12VA。
+
+完成门槛:
+
+- H.264/HEVC 的合法测试片可播放;
+- PTS 单调处理正确,VFR 不按固定 FPS 猜;
+- 10 次 seek 后无旧历史影像;
+- NR 每个 real frame 执行;
+- D3D12VA 模式日志显示共享 device 和 `AV_PIX_FMT_D3D12`;
+- normal path 无 pixel readback;
+- 30 分钟 video-only 无内存持续增长。
+
+## Phase 4 — DLSS SR
+
+完成门槛:
+
+- 1:1 自动 bypass;
+- 1080p→4K 走 SR→NR;
+- SR/NR resource extent/subrect 对齐;
+- resize/quality change 正确重建;
+- SR runtime 来自官方 310.7 manifest;
+- Phase 4 以 Zero Guidance 完成 SR 门禁,日志明确标为 Zero;NVOF 属于 Phase 5,尚未实现时必须报告 not enabled,不能用零运动冒充 NVOF。
+
+## Phase 5 — NVOF Guidance
+
+完成门槛:
+
+- System32 runtime/version/capability query 成功;
+- current→previous 方向由平移片验证;
+- fixed 10.5 除以 32 的转换测试通过;
+- 1x1 或 densified full-res motion;
+- NR/FG 消费同一个 GuidanceFrame;
+- NVOF 不可用时明确 fallback Zero;
+- API context 无多线程并发调用。
+
+## Phase 6 — DLSSG 2X
+
+完成门槛:
+
+- capability available、Create/Evaluate success;
+- 插值未被 disable;
+- 每对 real frame 产生一帧不同内容;
+- present counter 实际接近 2X;
+- generated PTS 位于相邻 real PTS 中点;
+- UI 在 FG 后;
+- seek/pause/resize 无 stale generated frame;
+- 报告新增 latency。
+
+## Phase 7 — Audio + minimum UI
+
+完成门槛:
+
+- WASAPI event-driven playback;
+- audio master clock;
+- 60 分钟 A/V drift 无持续增长;
+- FG on/off 不改变音频时长;
+- UI 改参数在 real-frame 边界 reset;
+- debug panel 数据来自真实 counter/timestamp。
+
+---
+
+# 17. 日志、抓帧和验收证据
+
+## 17.1 日志格式
+
+每行至少:
+
+~~~text
+timestamp
+thread
+frameId
+component
+operation
+resultHex/HRESULT
+SEH code if any
+width/height/format
+reset flag/reason
+GPU ms if available
+~~~
+
+必须出现的计数:
+
+~~~text
+nrCreateCount
+nrEvaluateAttempt/Success/Failure
+nrResetCount
+nvofSuccess/Fallback
+srEvaluateSuccess
+fgRealFrameCount
+fgGeneratedFrameCount
+presentReal/Generated/Dropped
+decodeQueueDepth
+gpuSlotWaitMs
+~~~
+
+## 17.2 Capture 格式
+
+RGBA8 阶段可保存无损 PNG。FP16 阶段不要强行转 8 bit 后声称是原始数据:
+
+~~~text
+00_original.rgba16f.bin
+00_original.json
+01_proxy.png
+02_raw_dlssnr.png
+03_final.rgba16f.bin
+03_final-preview.png
+03_final.json
+~~~
+
+JSON 写 width、height、DXGI format、row pitch、color space、profile、runtime hash、frameId、PTS。
+
+## 17.3 WORKLOG 模板
+
+每阶段追加:
+
+~~~markdown
+## YYYY-MM-DD Phase N
+
+Goal:
+
+Changed:
+
+Commands actually run:
+
+Results:
+
+Artifacts/logs:
+
+Failures and exact codes:
+
+Decision:
+
+Next single task:
+~~~
+
+不准写“测试应该能过”。没在 RTX 5070 上跑就写“未执行”。
+
+---
+
+# 18. 常见失败定位表
+
+## DLL hash 不一致
+
+动作:停工。记录实际 path/size/hash/signature,询问用户。不要自动下载替换。
+
+## `LoadLibraryExW` 失败
+
+检查:
+
+1. 是否绝对路径;
+2. runtime 是否 staged;
+3. Win32 `GetLastError`;
+4. 进程是否 x64;
+5. DLL signature/hash;
+6. 依赖搜索 flags。
+
+不要把 search path 扩到整个磁盘。
+
+## 导出缺失
+
+动作:报告缺失导出和 file version,停。不要尝试 ordinal 猜函数。
+
+## signed snippet Init_Ext 失败
+
+按顺序查:
+
+1. NGX core 是否先成功;
+2. adapter/device 是否同一个;
+3. runtimeDir 是否正确;
+4. caller compatibility 是否只对正确 module handle 生效;
+5. driver ≥615;
+6. GPU 是否当前支持;
+7. result hex/SEH。
+
+不要先改 App ID 或复用 Magpie Project ID。
+
+## CreateFeature 返回 `0xBAD00005` / InvalidParameter
+
+逐项 dump 参数“名字、类型、值”,重点:
+
+- 重复的 input/output/standard width/height 是否全设;
+- Upscaling=0、Scale=1、ScalingRatio=1;
+- callback 是否有效;
+- Preset 是 int;
+- node mask 是 uint32;
+- command list/device 是否同源;
+- feature ID 精确为 18;
+- create resources extent 是否稳定。
+
+不要通过删参数随机试。
+
+## Evaluate InvalidParameter
+
+重点:
+
+- 四个 resource 都非 null;
+- resource 属于同一个 D3D12 device;
+- Proxy/Neural/Motion/Depth format;
+- subrect 全部在资源内部且非 0;
+- parameter type;
+- motion/depth extent 与 output 相同;
+- output 有 UAV flag/state;
+- first frame Reset=1。
+
+## 返回 success 但黑图
+
+检查:
+
+1. Proxy 是否非黑;
+2. Neural UAV barrier;
+3. capture 是否读对 subresource/row pitch;
+4. output 是否被下一 pass 清零;
+5. sRGB encode 是否写到 UNORM;
+6. resource state tracker;
+7. parameter block 是否在 GPU 完成前被复用/销毁。
+
+success 不是画面正确的证据。
+
+## 画面洗白/压黑/高光断层
+
+按顺序查:
+
+1. YUV range;
+2. BT.601/709 matrix;
+3. transfer 是否 decode 到 linear;
+4. PaperWhiteScale;
+5. Proxy 是否 sRGB encode;
+6. Neural/Proxy 是否 sRGB decode;
+7. FP16/UNORM format;
+8. shoulder 常数/阈值;
+9. matrix 是否转置。
+
+不要先调 Intensity。
+
+## 时间越播越慢/延迟越来越高
+
+检查:
+
+- packet/frame queue 是否有上限;
+- slot 是否每帧同步等待;
+- capture readback 是否误开;
+- scheduler 是否按 nominal FPS 而非 PTS;
+- FG 是否缓存超过下一 real frame;
+- audio clock/present clock 是否双重 sleep;
+- NVOF/NGX 是否每帧重建 feature。
+
+## device removed
+
+记录:
+
+~~~text
+GetDeviceRemovedReason
+DRED breadcrumbs
+DRED page-fault data
+last frameId
+last resource states
+last NGX operation
+~~~
+
+不要立刻自动循环重建导致日志被冲掉。先写 crash report,再做一次受控 device recreation。
+
+## FG “成功”但画面重复
+
+检查 interpolation-disable output、generated hash、multiFrameCount/index、BackbufferFrameID、history reset、真实 motion。重复 present 不是 DLSSG。
+
+---
+
+# 19. 对抗式审查:最可能把项目做废的十件事
+
+1. 一上来搭完整播放器,Feature 18 错误被 FFmpeg/UI/时钟问题淹没。
+2. 把 addon 当配置或 DLL 加载,最终仍依赖 ReShade。
+3. Raw Neural 直接 present,误判为 DLSS 画质差,实际是缺 parity。
+4. 把 sRGB Proxy 当 linear 或把 FP16 当 UNORM。
+5. 参数名正确但类型错误,得到 InvalidParameter。
+6. 每帧 CPU wait,功能能跑但延迟和吞吐彻底坏掉。
+7. 用理论倍率冒充真实 DLSSG 帧。
+8. NVOF 符号、单位或 grid 转换错误,却在 consumer 端乱乘 scale。
+9. 复制 GPL Magpie 源码后还想闭源发布。
+10. 把 leaked/local runtime 放进 Git、安装包或云端 artifact。
+
+每个 PR/阶段完成前,对照这十条逐项打勾。
+
+---
+
+# 20. 唯一执行入口
+
+无人值守施工只使用根目录 `loop/GOAL_PROMPT.md`,并严格执行
+`loop/LOOP_ENGINE.md`。不要从本手册摘一段另写启动 Prompt;那会丢失循环上限、Reviewer、STOP、控制面 hash 和恢复规则。
+
+机器可读进度在 `loop/STATE.json`,唯一任务顺序在 `loop/BACKLOG.md`,
+实际门禁证据在 `loop/EVIDENCE.md`。每个 Phase 的 gate 和只读 Reviewer
+都通过后才自动进入下一 Phase。
+
+若不是 Goal 模式,只执行 STATE 指向的当前 Phase,完成或阻塞后停下报告,
+不得自行跨 Phase。任何状态文字都不能覆盖真实编译、运行、日志、counter、
+capture 和 present 结果。
+
+---
+
+# 21. 最终 V1 完成定义
+
+只有下面全部真实成立,才能说 V1 完成:
+
+~~~text
+Windows x64 player
++ FFmpeg D3D12VA decode on shared device
++ correct SDR YUV/range/transfer handling
++ optional DLSS SR
++ native signed-snippet DLSSNR Feature 18
++ RenoDX-equivalent proxy encode/decode
++ Zero/NVOF guidance with explicit identity
++ native DLSSG 2X with real generated frames
++ audio-master A/V sync
++ UI after FG
++ bounded low-latency queues
++ runtime/hash/result/GPU timing diagnostics
++ no ReShade/addon dependency in final executable
+~~~
+
+并且:
+
+- Feature 18 连续执行、重建、seek/reset 稳定;
+- CPU/GPU parity 数值测试与固定灰阶/色卡/高光门禁通过;若用户提供合格 RenoDX reference capture,再追加同输入/参数的管线级偏差对照;
+- runtime/local SDK 未进入 Git 或发行包;
+- 没有用 Magpie GPL 源码污染预定的闭源边界;
+- 所有“成功”都有日志、counter、capture 或实际 present 证据。
+
+这份手册不评价 DLSS5 对日常视频是否好看。我们的职责是正确调用、正确复现 parity、正确控制时序;模型本身的审美效果不在工程优化范围内。
diff --git a/VEYRA_PRODUCT_SPEC_V1.md b/VEYRA_PRODUCT_SPEC_V1.md
new file mode 100644
index 00000000..2dc90e95
--- /dev/null
+++ b/VEYRA_PRODUCT_SPEC_V1.md
@@ -0,0 +1,859 @@
+# Veyra DLSS 视频播放器
+## Product Spec V1(调用复现优先)
+
+> 文档状态:Locked V1 Product Boundary
+> 日期:2026-09-01
+> 当前验证环境:Windows 11 x64 / GeForce RTX 5070 / Driver 616.56
+> 核心目标:不研究 DLSS 5 是否适合普通视频,不自研模型画质;只完成稳定调用,并尽量复现 RenoDX/ReShade 的处理结果。
+
+---
+
+# 0. 前提与边界
+
+本方案接受以下已经被 Magpie Experimental 证明的事实,不再重复做可行性研究:
+
+1. 普通软件窗口、游戏捕获画面和视频帧可以作为 DLSS 输入。
+2. 独立应用可以调用 DLSS Neural Rendering、DLSS Super Resolution 和 DLSS Frame Generation。
+3. 视频没有游戏原生 Motion、Depth、Camera、HUD-less Buffer 时,仍可通过 Zero Guidance 或估算 Guidance 驱动相关功能。
+4. 第一阶段不评价 DLSS 5 对不同视频类型“好不好看”,不训练模型,也不承担 NVIDIA 模型本身的画质优化。
+
+本规格只解决四件事:
+
+```text
+1. 播放器稳定取得 GPU 视频帧
+2. 原生创建并执行 DLSSNR Feature 18
+3. 复现 RenoDX/ReShade 的颜色代理、参数与输出处理
+4. 原生执行 DLSS Frame Generation,并正确显示生成帧
+```
+
+“不再做可行性测试”不等于“不做工程验收”。仍必须记录 Create/Evaluate 是否成功、是否真的生成新帧、输出时序是否正确,以及与 ReShade 是否存在明显的颜色管线偏差;这些是完成定义,不是重新研究 DLSS 是否可用于视频。
+
+---
+
+# 1. 产品定义
+
+做一个面向 NVIDIA RTX 的极简 Windows 视频播放器与后续采集卡 Viewer:
+
+- FFmpeg 负责文件解封装、视频解码和音频解码;
+- D3D12 负责核心 GPU 管线;
+- DLSS Super Resolution 负责需要的分辨率放大;
+- `nvngx_dlssnr.dll` Feature 18 负责 DLSS 5 Neural Rendering;
+- RenoDX Parity Layer 负责复现 ReShade 插件前后的颜色转换和输出处理;
+- NVIDIA NGX DLSS Frame Generation 负责 2X,后续再开放 3X/4X;
+- ReShade 只作为开发期参考实现和对照输出,不进入最终产品运行链;
+- 播放器 UI、字幕和 OSD 在 Frame Generation 之后绘制。
+
+产品第一优先级不是媒体库和播放器功能,而是:
+
+> 同一输入、同一 DLSSNR DLL、同一参数下,Veyra 能稳定执行 Feature 18,并获得与 RenoDX/ReShade 同类的画面处理结果。
+
+---
+
+# 2. 已确认的本地运行时事实
+
+当前目录中的 `nvngx_dlssnr.dll`:
+
+```text
+Version: 310.8.0.0
+SHA-256: E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E
+Authenticode: Valid / NVIDIA Corporation
+Minimum Driver: 615.00
+GPU Architecture: NVSDK_NGX_GPU_Arch_Blackwell2
+Feature Runtime: NVIDIA DLSSNR - DVS PRODUCTION
+```
+
+当前目录中的 `renodx-dlss5-1.addon64`:
+
+```text
+Internal Name: renodx-dlss5.addon64
+Version: 0.2026.0827.2036
+SHA-256: 837B6A34D41C0EB75CB105AFEB5B985CFC72CB7F3A786C5DBB3F5415C45C978F
+Authenticode: Not signed
+Type: ReShade binary add-on, not a configuration file
+```
+
+插件暴露出的行为包括:
+
+- 拦截 D3D12 NGX Create/Evaluate;
+- 在已有 DLSS 输出之后执行 Feature 18;
+- 使用 Color、MotionVectors、Depth 和 Output 合同;
+- 建立 Control-compatible color transfer;
+- 使用 soft-clip、sRGB proxy、UpgradeToneMap、HDR/chroma transfer;
+- 提供 Preset、Style、Intensity、Local Tone、Local Structure、Skin Structure、Auto Mask、UI Correction、Depth Convention 和 Motion Scale 参数。
+
+因此,“接近 ReShade”的主要任务不是重新训练或优化 DLSS 5,而是复现它在 Feature 18 前后的数据合同。
+
+当前原始签名 DLL 的首个明确目标平台是本机 RTX 5070。不要在 V1 文案中宣称支持所有 RTX;其他显卡必须等实际 runtime capability 返回后再加入支持列表。
+
+---
+
+# 3. 最终处理管线
+
+```text
+FFmpeg Demux / Decode
+ ↓
+D3D12 Video Frame
+ ↓
+YUV → Working RGB
+range / matrix / transfer / chroma
+ ↓
+Optional DLSS Super Resolution
+只在输入分辨率低于输出分辨率时启用
+ ↓
+RenoDX Parity Encode
+Control-compatible proxy / soft clip / transfer
+ ↓
+DLSSNR Feature 18
+Color + Motion/Zero Motion + Depth/Zero Depth
+ ↓
+RenoDX Parity Decode
+UpgradeToneMap / color strength / luminance protection
+ ↓
+DLSS Frame Generation
+2X first
+ ↓
+Subtitle / OSD / Player UI
+ ↓
+DXGI Present
+```
+
+两条分辨率路径必须分开:
+
+```text
+同分辨率:Decode → Parity Encode → DLSSNR → Parity Decode
+
+放大播放:Decode → DLSS SR → Parity Encode → DLSSNR → Parity Decode
+```
+
+DLSSNR 不承担播放器的分辨率放大。需要 1080p→4K 时,由 DLSS SR 独立完成。
+
+---
+
+# 4. 技术架构
+
+## 4.1 基础技术栈
+
+- C++20
+- CMake
+- Win32 Window
+- D3D12
+- DXGI Flip Model Swap Chain
+- FFmpeg shared libraries
+- WASAPI
+- NVIDIA NGX / DLSS SDK headers
+- NVIDIA NGX DLSSG helper contract;Streamline 只保留为 V1 之后的替换研究
+- NVIDIA Optical Flow API
+- Dear ImGui 仅用于开发面板;正式 UI 可继续使用或改为轻量自绘
+
+禁止在 V1 引入:
+
+- Qt
+- Electron / Chromium
+- MFC 大型 UI 架构
+- OpenCV
+- 插件系统
+- 媒体库和网络视频平台
+- Depth Anything / ONNX Runtime
+- 自研 Motion Cleaner
+- FRUC、XeSS FG 等第二帧生成后端
+
+## 4.2 共享 D3D12 设备
+
+播放器、DLSS SR、DLSSNR、DLSSG 和 Guidance 应尽量共享同一物理 Adapter 和 D3D12 Device。
+
+```text
+D3D12DeviceContext
+├─ Graphics/Compute Queue
+├─ Video Decode Queue
+├─ NGX Core Session
+├─ Descriptor Allocator
+├─ Texture Pool
+├─ Fence Timeline
+└─ GPU Timestamp Queries
+```
+
+正常播放路径禁止 CPU readback。只有开发期截图、诊断和极小状态值允许 readback。
+
+## 4.3 NGX Core Host
+
+建立进程级唯一的 `NgxCoreHost`:
+
+- 使用本项目自己的 Project ID 和 `NVSDK_NGX_ENGINE_TYPE_CUSTOM`;
+- 负责 NGX Init、Capability Parameters、Parameter Allocation 和最终 Shutdown;
+- DLSS SR、DLSSNR、DLSSG 作为独立 consumer 共用生命周期;
+- 所有 proprietary API 调用外层增加 SEH 防护和结构化错误日志;
+- 禁止多个模块各自随意 Init/Shutdown NGX;
+- Device Lost 或 Adapter Change 时整体销毁并重建。
+
+## 4.4 DLSSNR Runtime Adapter
+
+`DlssNrBackend` 只暴露稳定的内部接口:
+
+```cpp
+struct DlssNrCreateDesc {
+ uint32_t width;
+ uint32_t height;
+ uint32_t preset;
+ DXGI_FORMAT inputFormat;
+ DXGI_FORMAT outputFormat;
+};
+
+struct DlssNrEvalDesc {
+ GpuTexture color;
+ GpuTexture motion;
+ GpuTexture depth;
+ GpuTexture output;
+ DlssNrControls controls;
+ bool reset;
+ uint64_t frameId;
+};
+```
+
+实现要求:
+
+- 动态加载 `nvngx_dlssnr.dll`;
+- 获取 D3D12 Init/Create/Evaluate/Release/Shutdown exports;
+- 当前 pre-release signed-snippet 兼容行为隔离在单独 adapter 中;
+- Feature ID、私有参数名和 runtime workaround 不得泄漏到播放器业务层;
+- 将来 NVIDIA 发布正式 Streamline DLSS 5 后,只替换 backend,不重写播放器;
+- runtime 加载前核对文件名、版本、SHA-256、NVIDIA 签名、最低驱动和 GPU capability;
+- 不自动下载、不写入 Git、不进入公开安装包。
+
+## 4.5 参数层
+
+NGX Parameter 必须强类型封装:
+
+```cpp
+SetU32(name, value)
+SetI32(name, value)
+SetF32(name, value)
+SetD3D12Resource(name, resource)
+```
+
+V1 支持参数:
+
+- Width / Height
+- Render Preset
+- Style
+- Intensity
+- Local Tone Strength
+- Local Structure Strength
+- Skin Structure Strength
+- Automatic Mask
+- UI Correction
+- Motion Vector Scale X/Y
+- Depth Inverted
+- Enabled
+- Reset
+- Color / Motion / Depth / Output subrect
+
+DLSSNR 参数默认值以 Playbook 已锁定的当前 runtime 调用合同为准。项目中没有 ReShade preset 配置文件;`renodx-dlss5-1.addon64` 是二进制 add-on,不能把它冒充 preset。Parity codec 的三个可调值在 V1 固定使用中性工程基线 1.0;若以后用户提供真实 preset,只新增可选对照 profile,不改变 V1 门禁。
+
+---
+
+# 5. RenoDX Parity Layer
+
+## 5.1 定位
+
+ReShade/RenoDX 只承担两个角色:
+
+1. 当前 add-on 中可观察到的行为和 shader 数学参考;
+2. 用户以后提供同版本 preset/capture 时的可选固定输入对照。
+
+最终程序不加载 ReShade,也不加载 `.addon64`。
+
+## 5.2 必须复现的阶段
+
+```text
+Original Working RGB
+ ↓
+Control-compatible proxy encode
+ ↓
+Feature 18 raw neural output
+ ↓
+Proxy decode / UpgradeToneMap
+ ↓
+Color-strength and luminance reconstruction
+ ↓
+Final RGB
+```
+
+根据当前 `renodx-dlss5-1.addon64` 内嵌 shader,Parity Codec 按下面的确定行为实现,不从零猜算法。
+
+### A. Proxy Encode
+
+输入为播放器正确解码后的线性 RGB:
+
+1. 保留一份高精度 `Original`;
+2. `Original.rgb` 除以 `PaperWhiteScale`,负值截为 0;
+3. 对 0.75 以上的高光使用指数 shoulder soft-clip,压到可供当前模型使用的范围;
+4. 执行标准 sRGB Encode;
+5. 写入 RGBA8 `Proxy`,作为 `DLSSNR.Color`。
+
+V1 资源建议:
+
+```text
+Original: R16G16B16A16_FLOAT
+Proxy: R8G8B8A8_UNORM
+Neural: R8G8B8A8_UNORM
+Final: R16G16B16A16_FLOAT
+```
+
+### B. Feature 18
+
+```text
+DLSSNR.Color = Proxy
+DLSSNR.Output = Neural
+DLSSNR.MVec = Motion or Zero Motion
+DLSSNR.Depth = Depth or Zero Depth
+```
+
+Feature 18 处理的是经过 Control-compatible transfer 的 `Proxy`,不是直接处理播放器最终显示用的线性 FP16 画面。
+
+### C. Parity Decode
+
+输出阶段同时读取 `Original`、`Proxy` 和 `Neural`:
+
+1. 对 `Proxy` 和 `Neural` 做 sRGB Decode;
+2. 使用 BT.709 luminance 系数计算三者亮度;
+3. 根据 `Original` 与 `Proxy` 的亮度差,对 Neural 恢复被 soft-clip 压掉的亮度范围;
+4. 在 OkLab 中恢复色相/色度关系;
+5. 转入 AP1 约束负色域,再转回 BT.709;
+6. 使用 `TransferStrength` 在 Original 与升级结果之间混合;
+7. 单独构造 luminance-only 结果,再用 `ColorStrength` 决定保留多少 Neural 色彩变化;
+8. 乘回 `PaperWhiteScale`,保留 Original alpha,写入 Final FP16。
+
+这三个常量必须进入配置和抓帧清单:
+
+```text
+PaperWhiteScale
+TransferStrength
+ColorStrength
+```
+
+它们属于 RenoDX Parity Codec,不等同于 Feature 18 自身的 `Intensity`、`LocalToneStrength` 或 `LocalStructureStrength`。
+
+内部保留四个可抓取观察点:
+
+```text
+00_original
+01_proxy_input
+02_raw_dlssnr
+03_final_parity_output
+```
+
+## 5.3 实现原则
+
+- 将 Parity Codec 写成独立 D3D12 compute pass;
+- 编码和解码都可单独 bypass;
+- 第一版先对齐 SDR;
+- HDR Transfer 参数和 HDR typed UAV 进入 V1.1;
+- 不加入主观锐化、降噪、肤质保护等额外滤镜;
+- 若结果与 ReShade 不同,优先检查格式、transfer、range、参数类型、subrect 和资源状态,不先怀疑模型。
+
+## 5.4 “类似 ReShade”的完成定义
+
+没有外部 RenoDX capture 时,完成条件由 CPU reference、GPU shader 对照和四阶段 capture 确定;不得编造一份“参考图”。用户以后提供同 addon hash、preset、输入和分辨率的 capture 时,再追加对照,不替换基础门禁。完成条件是:
+
+- CPU/GPU encode/decode 达到 Playbook 数值容差,四阶段资源真实存在;
+- 固定灰阶、色卡和高光输入不出现系统性洗白、压黑、截高光或整体色相漂移;
+- Style、Intensity、Structure、Auto Mask 以 Playbook 的精确名称/类型传入,开关或数值变化产生可观测且非恒定的输出;只有存在合格 reference 时才宣称调节方向与 RenoDX 一致;
+- Raw DLSSNR 与 Final Parity Output 可以分别抓取,确认差异来自 parity layer;
+- 若存在合格外部 reference capture,同一输入/参数下再检查整体亮度、gamma、饱和度与局部对比不存在明显系统性偏差。
+
+这是接口复现验收,不是评价 DLSS 5 本身的审美效果。
+
+---
+
+# 6. Frame Guidance
+
+V1 不自研 Guidance 算法,只实现 Magpie 已证明可工作的最小合同。
+
+统一内部规范:
+
+```text
+Motion Direction: Current → Previous
+Motion Unit: Source Pixels
+Motion Format: R16G16_FLOAT
+Depth Format: R32_FLOAT
+Frame Identity: uint64 frameId
+```
+
+Provider:
+
+```text
+ZeroGuidanceProvider
+├─ Zero Motion
+└─ Zero Depth
+
+NvofGuidanceProvider
+├─ NVIDIA Optical Flow
+├─ Dense Motion output
+└─ Zero Depth by default
+```
+
+V1 默认:
+
+- DLSSNR:NVOF Motion,可回退 Zero Motion;
+- DLSSG:NVOF Motion + Zero Depth;
+- Estimated Depth:不实现;
+- Motion Cleanup / Occlusion:不实现;
+- NVOF cost 只归一化成 diagnostic confidence,供可视化、日志和 scene-cut 诊断;V1 不把 confidence 冒充 NR/FG 的正式输入;
+- 文件和采集模式使用同一 provider contract。
+
+必须 Reset 的事件:
+
+- Seek
+- Resize
+- Source Change
+- Device Lost
+- Long Pause Resume
+- 硬切检测命中
+- Guidance frameId 不连续
+
+Scene Cut V1 只需要一个轻量直方图/帧差检测器,用于触发 Reset,不承担画质优化。
+
+---
+
+# 7. DLSS Super Resolution
+
+DLSS SR 与 DLSSNR 是两个独立阶段:
+
+- 输出尺寸等于输入尺寸:跳过 DLSS SR;
+- 输出尺寸大于输入尺寸:先 DLSS SR,再 DLSSNR;
+- DLSSNR 的输入/output 尺寸在 V1 保持一致;
+- UI 中将“分辨率增强”和“DLSS 5 Neural Rendering”分成两个开关,避免概念混淆。
+
+用户 UI:
+
+```text
+Upscale: OFF / Quality / Balanced / Performance
+DLSS 5: OFF / ON
+```
+
+V1 的 DLSS SR 固定使用 Zero Guidance;共享 NVOF 在 SR 输出之后生成,只供下游
+DLSSNR/DLSSG 使用,不能形成“先有 SR 输出才能算 NVOF、SR 又等待该 NVOF”的
+循环依赖。未来若要给 SR 实际 motion,必须另设 render-resolution provider,
+不复用本 V1 的 full-resolution `GuidanceFrame`。
+
+---
+
+# 8. DLSS Frame Generation
+
+## 8.1 V1 范围
+
+- Native NGX DLSSG;
+- 只发布 2X;
+- 3X/4X 代码结构预留但 UI 隐藏;
+- 使用 capability parameters 查询可用性和最大倍率;
+- 不加入 FRUC 或其他后端。
+
+## 8.2 输入合同
+
+```text
+Final DLSSNR Color
++ NVOF Motion / Zero Motion fallback
++ Zero Depth
++ Reset State
+→ DLSSG
+```
+
+内部 `GuidanceFrame` 的 motion 单位固定为 source pixels;DLSSG adapter 必须按
+官方 310.7 header 的语义把它归一化到 `[-1,1]`,即 full-resolution motion
+使用 `mvecScale = {1.0 / width, 1.0 / height}`。NR 的私有 Feature 18 合同仍按
+其已验证参数使用 `MVecScaleX/Y = 1`,两个 backend 不得误共用同一 scale 值。
+固定 Magpie experimental 提交虽然在 DLSSG 写了 `{1,1}`,但这与官方 header
+注释冲突;该值只保留为显式 `magpie-unit` 诊断模式,不能静默成为 Veyra 默认。
+Phase 6 用已知像素平移片记录两种 mode、实际 scale、输出 hash/counter 和方向/
+幅值结论,不以主观观感选择。
+
+V1 明确标记未提供:
+
+- HUD-less
+- UI Color
+- UI Alpha
+- Bidirectional Distortion Field
+- Output Real
+
+播放器自己的 UI 和字幕放在 FG 后绘制,因此不会进入 DLSSG。
+
+## 8.3 时序
+
+30→60 示例:
+
+```text
+Real A 0.00 ms
+Generated 16.67 ms
+Real B 33.33 ms
+Generated 50.00 ms
+Real C 66.67 ms
+```
+
+要求:
+
+- 音频仍是 master clock;
+- 生成帧具有独立 presentation timestamp;
+- 不通过重复 Present 假造输出 FPS;
+- Seek、暂停恢复和源切换后先 Reset,再接受新生成帧;
+- 记录每次 Evaluate、Interpolation Enabled/Disabled 和发布成功数。
+
+---
+
+# 9. 播放器
+
+## 9.1 V1 用户功能
+
+- 打开本地视频;
+- 播放、暂停、Seek;
+- 音量和静音;
+- 窗口/全屏;
+- Upscale OFF/模式;
+- DLSS 5 OFF/ON;
+- Frame Generation OFF/2X;
+- 显示输入分辨率、输入 FPS、输出 FPS 和 backend 状态。
+
+## 9.2 媒体管线
+
+V1 的解码路径:
+
+```text
+FFmpeg D3D12VA
+→ D3D12 texture
+
+Fallback:
+software decode
+→ GPU upload
+```
+
+D3D11VA/D3D11On12 不在 V1;它会额外引入 device/queue/handle 同步和资源状态
+边界,不能作为弱模型“顺手加”的第三条路径。
+
+V1 gate 的最低格式矩阵:
+
+- H.264 / HEVC video;
+- AAC / PCM audio;
+- MP4 / MKV container。
+
+AV1、VP9、Opus、FLAC、MOV、WebM 可以在 FFmpeg 已提供 decoder/demuxer 时作为
+best-effort 路径,但不允许拖延 Phase 3/7,也不能在没有固定测试片证据时写成
+已支持。
+
+## 9.3 UI
+
+底栏只保留:
+
+```text
+Play | Volume | Upscale | DLSS 5 | FG 2X | Fullscreen
+```
+
+开发面板显示:
+
+- NGX Core status
+- DLSSNR Create/Evaluate result
+- DLSSNR active parameters
+- SR/NR/FG GPU time
+- Feature 18 successful frame count
+- FG real/generated frame count
+- Guidance type
+- Reset count and reason
+- Queue depth / dropped frames
+
+---
+
+# 10. 工程目录
+
+```text
+Veyra/
+├─ CMakeLists.txt
+├─ cmake/
+├─ third_party/
+│ └─ README.md
+├─ runtime_local/ # gitignored,不进入发行包
+├─ src/
+│ ├─ app/
+│ │ ├─ App.cpp
+│ │ ├─ MainWindow.cpp
+│ │ └─ Settings.cpp
+│ ├─ gfx/
+│ │ ├─ D3D12DeviceContext.cpp
+│ │ ├─ SwapChain.cpp
+│ │ ├─ TexturePool.cpp
+│ │ ├─ ColorConverter.cpp
+│ │ └─ GpuProfiler.cpp
+│ ├─ media/
+│ │ ├─ FFmpegDemuxer.cpp
+│ │ ├─ FFmpegVideoDecoder.cpp
+│ │ ├─ FFmpegAudioDecoder.cpp
+│ │ ├─ PlaybackClock.cpp
+│ │ └─ AudioWASAPI.cpp
+│ ├─ ngx/
+│ │ ├─ NgxCoreHost.cpp
+│ │ ├─ NgxParameters.cpp
+│ │ ├─ DlssSrBackend.cpp
+│ │ ├─ DlssNrBackend.cpp
+│ │ ├─ DlssNrRuntimeAdapter.cpp
+│ │ └─ DlssFgBackend.cpp
+│ ├─ parity/
+│ │ ├─ RenoDxParityCodec.cpp
+│ │ ├─ RenoDxParityProfile.cpp
+│ │ └─ ParityCapture.cpp
+│ ├─ guidance/
+│ │ ├─ FrameGuidance.h
+│ │ ├─ ZeroGuidanceProvider.cpp
+│ │ ├─ NvofGuidanceProvider.cpp
+│ │ └─ SceneCutReset.cpp
+│ ├─ player/
+│ │ ├─ VideoPipeline.cpp
+│ │ ├─ FrameScheduler.cpp
+│ │ └─ Presenter.cpp
+│ └─ ui/
+│ ├─ PlayerControls.cpp
+│ └─ DebugPanel.cpp
+├─ tools/
+│ ├─ nr_harness/
+│ └─ parity_capture/
+└─ validation/
+ ├─ fixed_frames/
+ ├─ fixed_clips/
+ └─ expected_manifest.json
+```
+
+`validation/` 不是用于研究模型好坏,而是防止接口、色彩和时序在代码修改后回归。
+
+---
+
+# 11. 开发阶段
+
+## Phase 0 — Runtime Manifest 与 D3D12 Skeleton
+
+- C++20 / CMake;
+- Win32 Window;
+- D3D12 Device、Queue、SwapChain;
+- runtime manifest;
+- DLL hash/signature/version/capability 检查;
+- logging、SEH guard、GPU timestamp。
+
+完成条件:
+
+- 当前 RTX 5070 / 616.56 环境识别正确;
+- D3D12 窗口稳定;
+- proprietary runtime 不进入 Git。
+
+## Phase 1 — Feature 18 Native Harness
+
+先实现独立序列执行器,不先造完整播放器:
+
+```text
+fixed frame sequence
+→ D3D12 texture
+→ NGX Core
+→ signed DLSSNR runtime adapter
+→ Feature 18 Create/Evaluate
+→ output capture
+```
+
+完成条件:
+
+- Feature 18 Create 成功;
+- 连续 300 帧 Evaluate 成功;
+- Preset、Style、Intensity 等参数可改变;
+- Release/Shutdown 无泄漏或崩溃;
+- Raw output 可抓取。
+
+## Phase 2 — RenoDX Parity Codec
+
+- Proxy encode;
+- Feature 18;
+- Proxy decode / tone mapping;
+- 参数映射;
+- Original/Proxy/Raw/Final 四阶段确定性抓帧。
+
+完成条件:
+
+- CPU/GPU reference 数值门禁通过,固定灰阶/色卡/高光没有系统性 gamma、亮度、饱和度或高光偏差;
+- 参数变化产生可观测、非恒定输出;只有存在同 addon hash、preset、输入和分辨率的合格外部 reference 时,才追加“与 RenoDX 同方向”的结论;
+- 可切换 Raw / Parity Final。
+
+## Phase 3 — Minimal Video Pipeline
+
+- FFmpeg demux/decode;
+- 先做 video-only;
+- 连续 PTS;
+- DLSSNR history;
+- Seek/reset;
+- D3D12 present。
+
+完成条件:常见 1080p/4K 文件可连续播放,Feature 18 每个 real frame 稳定执行。
+
+## Phase 4 — DLSS Super Resolution
+
+- 输入/输出分辨率策略;
+- DLSS SR Create/Evaluate;
+- SR → NR 顺序;
+- resize/reset。
+
+完成条件:同分辨率自动跳过 SR,放大模式先 SR 后 NR,不发生错误 subrect 或资源错配。
+
+## Phase 5 — NVOF Guidance
+
+- Zero Guidance baseline;
+- NVIDIA Optical Flow;
+- Current→Previous / source-pixel contract;
+- frameId 和 reset。
+
+完成条件:DLSSNR 和 DLSSG 均消费同一个 source-pixel `GuidanceFrame`,各自 adapter
+执行自己的 scale 转换;当前机器 capability 可用时必须验证真实 NVOF,真实查询为
+unsupported 时才自动回退 Zero,不能主动跳过后把 Zero 标成 NVOF。
+
+## Phase 6 — DLSS Frame Generation 2X
+
+- capability query;
+- NGX DLSSG Create/Evaluate;
+- 生成帧发布;
+- PTS/cadence;
+- FG 后 UI。
+
+完成条件:
+
+- 确认 interpolation enabled;
+- 每两个 real frame 之间发布一个 generated frame;
+- 输出 FPS 统计来自实际 present,不是理论倍率;
+- Seek/pause/resize 后无旧历史生成帧。
+
+## Phase 7 — Audio 与最小 UI
+
+- FFmpeg audio decode;
+- WASAPI;
+- audio master clock;
+- 播放控制;
+- 正式底栏与隐藏调试面板。
+
+完成条件:长时间播放不发生持续 A/V drift,FG 不改变音频时长。
+
+# 12. 验收标准
+
+## 12.1 DLSSNR 调用
+
+- 日志明确记录 runtime hash、版本、Feature ID 和 Create result;
+- 每帧记录 Evaluate result;
+- 输出不是未处理输入的别名或错误 Copy;
+- 参数类型固定且可追踪;
+- reset 后首帧行为稳定;
+- 不因连续 Seek、Resize、暂停恢复崩溃。
+
+## 12.2 RenoDX/ReShade 相似性
+
+- 固定输入和固定参数;
+- 保存 Original、Proxy、Raw NR、Final 四阶段;
+- CPU/GPU parity 数值测试达到 Playbook 容差;
+- 检查全局亮度、gamma、饱和度、局部对比和高光范围;
+- 不做“哪个更好看”的主观评分;
+- 无外部 reference 时按已记录 shader 数学验收;有合格 reference 时才追加同条件对照。
+
+## 12.3 Frame Generation
+
+- capability 查询成功;
+- Create/Evaluate 成功;
+- generated frame count 与 real frame count 对应;
+- 生成帧拥有正确 PTS;
+- present cadence 连续;
+- reset 后不混入旧 source frame;
+- UI/字幕不进入生成输入。
+
+## 12.4 性能与稳定性
+
+- 正常路径无 CPU frame readback;
+- 每个 GPU stage 有 timestamp;
+- texture/fence/parameter/feature 生命周期无泄漏;
+- 记录 1080p 和 4K 的实测 GPU 时间,不在开发前虚构固定毫秒目标;
+- Device Lost 能显式失败或重建,不能静默黑屏。
+
+---
+
+# 13. 依赖与代码边界
+
+## 13.1 Magpie
+
+Magpie 已经完成可行性证明,并可作为:
+
+- API 调用顺序参考;
+- 参数合同参考;
+- Guidance 数据格式参考;
+- DLSSG 状态和计数参考。
+
+如果 Veyra 计划闭源,不复制 Magpie GPLv3 源码;根据公开 SDK 接口和可观察行为独立实现。若决定接受 GPLv3 并公开对应源码,则可以重新评估直接复用的成本。
+
+## 13.2 RenoDX Add-on
+
+- 开发期本地参考;
+- 不链接进产品;
+- 不随安装包分发;
+- 不把 `.addon64` 当配置文件;
+- V1 codec 配置使用三个 1.0 中性工程 baseline 并记录到 validation manifest;
+- 只有用户另行提供真实 `ReShade.ini`/preset 和配套 capture 时,才建立可选 reference profile。
+
+## 13.3 NVIDIA Runtime
+
+- `nvngx_dlssnr.dll` 只放 `runtime_local/`;
+- runtime 目录加入 `.gitignore`;
+- 不自动下载;
+- 不修改签名 DLL;
+- 发行方式与正式 SDK 出现后单独决定;
+- backend 必须可被将来的官方 Streamline DLSS 5 实现替换。
+
+---
+
+# 14. V1 明确不做什么
+
+- 不研究 DLSS 5 是否适合普通视频;
+- 不评价不同内容类型的模型审美;
+- 不训练或微调 AI 模型;
+- 不自研 Motion Cleaner;
+- 不接入 Depth Anything;
+- 不开发 FRUC fallback;
+- 不追求所有 RTX 显卡兼容;
+- 不做 HDR;
+- 不做 3X/4X;
+- 不做复杂字幕和媒体库;
+- 不把 ReShade 放入最终依赖;
+- 不先做采集卡而延误文件播放器主链。
+
+---
+
+# 15. 最终 V1 定义
+
+```text
+V1.0 =
+Minimal FFmpeg Player
++ D3D12 GPU-resident pipeline
++ Optional DLSS Super Resolution
++ Native DLSSNR Feature 18
++ RenoDX-equivalent parity layer
++ NVOF / Zero Guidance
++ Native DLSS Frame Generation 2X
++ WASAPI sync
++ Minimal UI
+```
+
+V1 的发布门槛不是“我们优化了 NVIDIA 的模型”,而是:
+
+> Veyra 能在不依赖 ReShade 的情况下稳定调用 DLSSNR 与 DLSSG,按已记录的 RenoDX parity 数学正确处理颜色、参数和输出;若存在合格外部 reference,再证明不存在明显的管线级偏差。
+
+---
+
+# 16. 开工顺序
+
+Agent 或开发者必须严格按以下顺序工作:
+
+```text
+1. Phase 0:D3D12 + runtime manifest
+2. Phase 1:Feature 18 native harness
+3. Phase 2:RenoDX parity codec
+4. Phase 3:video-only FFmpeg pipeline
+5. Phase 4:DLSS SR
+6. Phase 5:NVOF guidance
+7. Phase 6:DLSSG 2X
+8. Phase 7:audio/UI
+```
+
+禁止越过 Phase 1/2 直接堆播放器功能。调用链和 parity layer 是项目主体,播放器只是宿主。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
new file mode 100644
index 00000000..994bce23
--- /dev/null
+++ b/docs/WORKLOG.md
@@ -0,0 +1,122 @@
+# Veyra Worklog
+
+## 2026-09-01 Handoff baseline
+
+Goal:
+
+Prepare an implementation contract for the next Agent. No player source has been implemented yet.
+
+Changed:
+
+- Added `AGENTS.md` with project guardrails and phase gates.
+- Added `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md` with dependency acquisition, runtime layout, exact Feature 18 parameter contract, parity math, media pipeline, latency rules and phase acceptance criteria.
+- Added `.gitignore` before repository initialization so local NVIDIA/RenoDX binaries cannot be added accidentally.
+
+Commands actually run:
+
+- Inspected the project file list and product-spec headings.
+- Calculated/verified both local binary identities and Authenticode status.
+- Inspected exported/runtime strings and the embedded RenoDX parity shader behavior.
+- Verified the installed Windows, RTX 5070/616.56 environment and local Visual Studio/CMake/Ninja/DXC tool paths.
+- Checked pinned upstream DLSS, Magpie, FFmpeg/vcpkg and NVOF references.
+
+Results:
+
+- Current repository state before handoff: no `.git` directory and no application source.
+- Next allowed implementation phase: Phase 0 only.
+- No DLSS Feature was invoked and no runtime test was claimed in this handoff task.
+
+Artifacts/logs:
+
+- `AGENTS.md`
+- `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md`
+- `VEYRA_PRODUCT_SPEC_V1.md`
+
+Failures and exact codes:
+
+- None. One documentation patch wrapper parse error occurred before any write; it was corrected and had no workspace effect.
+
+Decision:
+
+Use direct NGX/D3D12 for V1; signed DLSSNR adapter is local-only; RenoDX add-on is reference-only; start with a native fixed-frame harness before the media player.
+
+Next single task:
+
+Execute Phase 0 from the playbook and stop at its acceptance gate.
+
+## 2026-09-01 Unattended Goal Loop handoff
+
+Goal:
+
+Turn the implementation plan into a recoverable Goal-based loop that another Agent can run without phase-by-phase supervision.
+
+Changed:
+
+- Added loop/LOOP_ENGINE.md with single-writer state machine, evidence rules, retry bounds, independent review and stop/complete conditions.
+- Added loop/GOAL_PROMPT.md as the copy-paste Goal task and loop/REVIEW_PROMPT.md as the read-only phase review task.
+- Added persistent STATE/BACKLOG/JOURNAL/EVIDENCE/INBOX files.
+- Added scripts/loop-gate.ps1 and scripts/gates/README.md.
+- Updated AGENTS.md, the Playbook and .gitignore for unattended execution.
+
+Commands actually run:
+
+- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
+- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate phase0
+- PowerShell AST parse of scripts/loop-gate.ps1 and ConvertFrom-Json validation of loop/STATE.json.
+
+Results:
+
+- Initial preflight found a Windows PowerShell 5.1 source-encoding bug in a non-ASCII product-plan filename check (exit 1); the bootstrap check was made encoding-safe. The later audit renamed the canonical product spec to an ASCII path.
+- Final re-run at 2026-09-01T17:16:32+08:00 passed 45/45 baseline checks (exit 0), including both local binary identities, STATE ledger/limits, ignore rules and eight protected control-file hashes.
+- Negative phase0 test failed closed as intended (underlying gate exit 1): Git is not initialized and scripts/gates/phase0.ps1 does not yet exist.
+- No application code, NGX Feature, video pipeline or Phase gate was claimed complete.
+
+Next single task:
+
+Start the Goal with loop/GOAL_PROMPT.md. The Agent must rerun preflight, finish P0.1 toolchain/GPU evidence, then execute Phase 0 in backlog order.
+
+## 2026-09-01 Full project audit and cleanup
+
+Goal:
+
+Re-audit the whole handoff package adversarially, remove superseded documentation, repair contradictory implementation instructions, and leave the unattended loop fail-closed for a weaker Agent.
+
+Changed:
+
+- Added `README.md` as the canonical entry point and renamed the retained product boundary to `VEYRA_PRODUCT_SPEC_V1.md`.
+- Deleted the obsolete V3 plan. It prescribed the superseded quality-first/capture/depth route and had no remaining active references.
+- Removed stale Phase 8 and old-plan routing. V1 is strictly Phase 0 through Phase 7.
+- Corrected the false premise that the RenoDX `.addon64` is a ReShade configuration. No preset exists in this workspace; Phase 2 uses a declared neutral codec baseline and only performs external-reference comparison if a matching preset/capture is later supplied.
+- Removed the D3D11VA/D3D11On12 side route and aligned the minimum codec/container matrix with Phase 3/7 gates.
+- Fixed the SR/NVOF circular dependency: V1 SR uses Zero Guidance; full-resolution NVOF is generated after SR and is shared only by NR/FG.
+- Added the D3D12VA texture-array slice/plane/lifetime contract, the NVOF ABGR8 input/ring/reset contract, and exact `GetModuleFileNameW` shim edge semantics.
+- Recorded the official DLSSG motion-normalization rule and isolated Magpie's conflicting `{1,1}` behavior as a diagnostic-only mode with a deterministic Phase 6 translation gate.
+- Hardened `scripts/loop-gate.ps1`: exact nine-file control set, stronger STATE phase/evidence/bound checks, Git commit-pointer checks, representative ignore probes, current-phase enforcement, and before/after hashes that prevent a phase gate from mutating non-ignored project files.
+- Rebuilt `loop/CONTROL_HASHES.json` for the canonical control plane.
+
+Commands actually run:
+
+- Official-source checks against NVIDIA DLSS SDK 310.7 headers, NVIDIA Optical Flow documentation/sample behavior, FFmpeg D3D12VA headers, the pinned vcpkg ports and Microsoft `GetModuleFileNameW` documentation.
+- PowerShell AST parse, JSON parse for every JSON file, Markdown fence-balance scan, stale-reference/TODO scans, and file inventory checks.
+- In-memory unit exercise of `Get-ProjectSourceSnapshot` / `Compare-ProjectSourceSnapshot` without changing disk files.
+- `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`
+- Negative gates for `phase0` and out-of-order `phase1`.
+- Reversible negative STATE tests for `cycle.completed=80` with active status and for prematurely unlocking Phase 1; the original state was restored after each test.
+
+Results:
+
+- Audited preflight passed 54/54 checks, including nine protected control hashes and both local binary identities.
+- `phase0` failed closed because Git is not initialized and `scripts/gates/phase0.ps1` does not exist; no Phase completion was claimed.
+- `phase1` additionally failed the current-phase check.
+- The loop-bound and phase-sequence mutations each made preflight exit 1 on the intended check, then the valid STATE was restored.
+- Mutation-snapshot unit exercise saw 17 control/state files, reported zero changes for identical snapshots, and detected an in-memory README hash change.
+- Current project truth remains: no Git repository, no application source, Phase 0 not started.
+
+Deleted/renamed:
+
+- Deleted the obsolete V3 plan. This workspace has no Git history yet, so that deletion is not recoverable from this directory's repository history.
+- Renamed the retained product plan to `VEYRA_PRODUCT_SPEC_V1.md`; its useful content was audited rather than discarded.
+
+Next single task:
+
+Start the Goal using `loop/GOAL_PROMPT.md`. The first Agent action is the 54-check preflight; then it completes P0.1 and proceeds through Phase 0 backlog order without crossing the gate.
diff --git a/loop/BACKLOG.md b/loop/BACKLOG.md
new file mode 100644
index 00000000..da52d608
--- /dev/null
+++ b/loop/BACKLOG.md
@@ -0,0 +1,84 @@
+# Veyra Loop Backlog
+
+状态标记:TODO、DOING、BLOCKED、GATE_PASS、REVIEW_PASS、DONE。主 Agent 只能选择当前 Phase 的第一个 TODO;前置 Phase 未完成时,后续项保持锁定。
+
+## Phase 0 — Runtime probe + D3D12 skeleton(当前)
+
+- [x] P0.1 运行 preflight,核对真实工作区、二进制身份、工具链和 GPU/driver;把结果写入 JOURNAL/STATE。(2026-09-02 Goal Cycle 001:preflight 54/54 exit 0;RTX 5070/616.56/12227 MiB/compute 12.0;nvofapi64 32.0.16.1656;MSVC 14.44.35207;CMake 3.31.6;Ninja 1.12.1;DXC 1.8;Git 2.53。证据:loop/JOURNAL.md Cycle 001。)
+- [ ] P0.2 确认 .gitignore 后按 LOOP_ENGINE 固定顺序初始化本地 Git;显式 staged allowlist、建立 baseline commit、切到 agent/veyra-v1-loop、写 baselineCommit 状态指针;验证两个二进制、runtime_local、third_party_local、reference_local、captures、logs 均未被跟踪。
+- [ ] P0.3 先创建 fail-closed 的 scripts/gates/phase0.ps1,编码 Playbook 的 Phase 0 门槛;此时因为工程/输出不存在必须失败。
+- [ ] P0.4 建立最小 CMake/C++20 Win32 x64 工程与 Debug/Release presets,不引入 FFmpeg/UI。
+- [ ] P0.5 实现结构化 logger、HRESULT/NGX result 字符串、文件 size/hash/signature 检查。
+- [ ] P0.6 实现 D3D12DeviceContext:RTX adapter、device、direct queue、debug layer、4-slot command allocator/list/fence/event ring。
+- [ ] P0.7 实现 veyra_runtime_probe:受限绝对路径加载本地复制的 nvngx_dlssnr.dll,验证 required exports;不得加载 addon。
+- [ ] P0.8 Debug/Release 构建并实际运行 probe;D3D12 窗口循环 5 分钟无 device removed;记录命令、exit code、GPU/driver、hash/signature/exports、日志路径。
+- [ ] P0.9 当前 gate 通过、只读 Reviewer 通过、修完 P0/P1、写 checkpoint。
+
+Phase 0 gate:以 Playbook 第 16 节 Phase 0 为准。未完成 P0.9 禁止开始 Phase 1。
+
+## Phase 1 — Feature 18 native harness(锁定)
+
+- [ ] P1.1 先建立 phase1 gate 和确定性 RGBA8 测试帧/输出统计。
+- [ ] P1.2 封装 NGX Core、parameter block、DLSSNR runtime 和严格逆序 RAII。
+- [ ] P1.3 实现受隔离、可关闭的 caller-name 兼容层;禁止 patch DLL。
+- [ ] P1.4 严格按 Playbook 参数名与类型 Create Feature 18。
+- [ ] P1.5 实现 Proxy→Feature18→Raw 的 D3D12 资源、barrier、subrect 与异步 4-slot 执行。
+- [ ] P1.6 连续 300/300 Evaluate;验证输出非黑、非恒定、随输入/参数变化;记录 GPU timings/result/capture。
+- [ ] P1.7 重建/reset/释放测试。
+- [ ] P1.8 gate、只读 Reviewer、P0/P1 修复、checkpoint。
+
+## Phase 2 — RenoDX-equivalent parity codec(锁定)
+
+- [ ] P2.1 为 transfer/range/matrix/proxy encode/decode 建 CPU golden tests 和 phase2 gate。
+- [ ] P2.2 实现 Original→Parity Encode shader,显式定义输入/输出色域、transfer、range 和资源格式。
+- [ ] P2.3 实现 Parity Decode 与 Raw/bypass 对照;记录三个 1.0 中性 codec baseline、来源说明、addon hash 和 capture hash。当前没有 preset;不得加载 addon 取值。
+- [ ] P2.4 CPU/GPU golden、identity/bypass、灰阶/色卡/高光测试达到 Playbook 容差。
+- [ ] P2.5 完整 Original→Encode→Feature18→Decode capture;不得以主观好看作为 gate。
+- [ ] P2.6 gate、只读 Reviewer、P0/P1 修复、checkpoint。
+
+## Phase 3 — Minimal video pipeline(锁定)
+
+- [ ] P3.1 引入固定版本 FFmpeg 依赖和 phase3 gate,不改变 NGX harness。
+- [ ] P3.2 先完成 H.264/HEVC 软件 decode 最小基线,正确按 PTS/VFR 驱动,不猜固定 FPS。
+- [ ] P3.3 共享 Veyra D3D12 device 的 D3D12VA decode,记录实际 AV_PIX_FMT_D3D12、hw device 和 shared device identity。
+- [ ] P3.4 完成 YUV range/matrix/transfer→linear RGB,禁止正常路径 GPU→CPU 像素回读。
+- [ ] P3.5 建有界 decode/process/present 队列和 backpressure。
+- [ ] P3.6 实现 open/seek/resize/pause-resume/device-lost 的历史 reset;10 次 seek 无旧历史影像。
+- [ ] P3.7 真实视频 30 分钟、seek 压测、内存/队列/延迟证据。
+- [ ] P3.8 gate、只读 Reviewer、P0/P1 修复、checkpoint。
+
+## Phase 4 — DLSS SR(锁定)
+
+- [ ] P4.1 建 phase4 gate 和明确的 SR off/on 可观测计数。
+- [ ] P4.2 从 Playbook 固定的官方 310.7 manifest 接入 DLSS SR,严格处理 render/output subrect、资源状态和 reset。
+- [ ] P4.3 验证 bypass、resize/seek、输入输出尺寸与 SR feature identity;不得把 NR 冒充 SR。
+- [ ] P4.4 gate、只读 Reviewer、P0/P1 修复、checkpoint。
+
+## Phase 5 — Zero/NVOF guidance(锁定)
+
+- [ ] P5.1 保留并验证明示的 Zero Guidance 路径。
+- [ ] P5.2 查询 System32 NVOF runtime/version/capability;建立 phase5 gate、flow/confidence 可视化与合成平移片。
+- [ ] P5.3 接入 NVOF,验证 current→previous 符号、fixed 10.5 / 32 转换、grid/scale/densify、scene cut、seek/reset;绝不以零向量冒充 NVOF。
+- [ ] P5.4 让 NR/FG 消费同一个 GuidanceFrame;验证 API context 无多线程并发调用;比较 Zero/NVOF 日志和 reset。
+- [ ] P5.5 gate、只读 Reviewer、P0/P1 修复、checkpoint。若 SDK 获取需要用户接受条款,先完成 Phase 5 内 capability/Zero fallback/接口测试,写 INBOX;gate 保持未通过且 Phase 6 继续锁定。
+
+## Phase 6 — DLSSG 2X(锁定)
+
+- [ ] P6.1 建 phase6 gate:generated count、内容 hash、timestamp/cadence、disable flag。
+- [ ] P6.2 接入真实 DLSSG 2X 输入、history 和 reset;默认按官方 header 将 source-pixel motion 用 `1/width,1/height` 归一化,Magpie `{1,1}` 仅保留显式 diagnostic mode。
+- [ ] P6.3 用已知像素平移片验证 DLSSG motion 方向/幅值和 scale mode,证明 generated frame 不是重复 present;验证 seek/pause/resume/scene-cut。
+- [ ] P6.4 确保 UI/OSD 在 FG 后合成,队列和 present cadence 有界。
+- [ ] P6.5 gate、只读 Reviewer、P0/P1 修复、checkpoint。
+
+## Phase 7 — Audio + minimum UI(锁定)
+
+- [ ] P7.1 建 phase7 端到端 gate 和 A/V sync/latency 采样。
+- [ ] P7.2 实现 audio-master 时钟、音频输出、drop/repeat 策略。
+- [ ] P7.3 实现最小 open/play/pause/seek、功能开关、诊断 OSD;UI 位于 FG 后。
+- [ ] P7.4 执行 60 分钟 A/V drift、seek storm、pause/resume、resize、device recovery、FG on/off 音频时长和功能组合矩阵。
+- [ ] P7.5 Debug/Release 最终构建、端到端证据、许可证/跟踪文件审计。
+- [ ] P7.6 gate、只读 Reviewer、修完全部 P0/P1、最终 checkpoint,按 Loop COMPLETE 条件收口。
+
+## 不属于本 Goal
+
+HDR、3X/4X、采集卡、Depth Anything、FRUC、主观画质调优、公开发布和安装包全部留在 V1 Goal 之外。
diff --git a/loop/CONTROL_HASHES.json b/loop/CONTROL_HASHES.json
new file mode 100644
index 00000000..730fbaa6
--- /dev/null
+++ b/loop/CONTROL_HASHES.json
@@ -0,0 +1,42 @@
+{
+ "schemaVersion": 1,
+ "purpose": "Fail-closed hash manifest for the unattended Goal control plane.",
+ "files": [
+ {
+ "path": ".gitignore",
+ "sha256": "A1DA73CCB34F7F46E08A19BB612037FE846F62C1B46253B457FF4F018A0CD56E"
+ },
+ {
+ "path": "AGENTS.md",
+ "sha256": "30EEA09A87FE6D719BEC9E474795D23CF968E58D1E31DC3C3A3AF7754B643F2A"
+ },
+ {
+ "path": "README.md",
+ "sha256": "DBEC0EE8228DD45C53A72B02FFE00EC6BCFE9CA8C83D80194670F381190C420D"
+ },
+ {
+ "path": "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
+ "sha256": "E91585886AE34176EADFA22A3D7BD1CD7519683B95CF7DE8320A79BD4B233BCD"
+ },
+ {
+ "path": "VEYRA_PRODUCT_SPEC_V1.md",
+ "sha256": "675B29931F16399F8B348F517FFE9745B0D713EA0A9531603C2938F363BE1294"
+ },
+ {
+ "path": "loop/GOAL_PROMPT.md",
+ "sha256": "1C76B4CE0D18650E6EBDE0A1AFFA992212E1C3626641498566B7ABFD936C8904"
+ },
+ {
+ "path": "loop/LOOP_ENGINE.md",
+ "sha256": "774077F6651EA8C400E9E16AB4665FA5D6468E91EF7DC2532548D08AB122D1A0"
+ },
+ {
+ "path": "loop/REVIEW_PROMPT.md",
+ "sha256": "A6C2F83247CF8420DD4616868FF6841CC1E6AD26BA4C74BD3E98497E647A08CD"
+ },
+ {
+ "path": "scripts/gates/README.md",
+ "sha256": "D5147CCC7A5718DF1CB41BE294B60EBEFF710EA4815C55181582E59BDB318F68"
+ }
+ ]
+}
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
new file mode 100644
index 00000000..be64fb16
--- /dev/null
+++ b/loop/EVIDENCE.md
@@ -0,0 +1,61 @@
+# Veyra Gate Evidence
+
+这里只登记真实存在的门禁证据。格式固定:
+
+## Phase N / Gate name / timestamp
+
+- Commit:
+- Command:
+- Exit code:
+- Build configuration:
+- Hardware/runtime identity:
+- Logs/captures:
+- Quantitative result:
+- Reviewer:
+- Open P0/P1:
+- Conclusion:
+
+在命令未执行、artifact 不存在或 Reviewer 未运行时,字段必须明确写 not run / not available,禁止使用 assumed、should pass 或理论结果代替。
+
+## Bootstrap / preflight / 2026-09-01T17:16:32+08:00
+
+- Commit: not available(本地 Git 尚未初始化)
+- Command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
+- Exit code: 0
+- Build configuration: not applicable;应用工程尚未建立
+- Hardware/runtime identity: nvngx_dlssnr.dll size/hash/signature/signer 通过;renodx add-on size/hash/NotSigned 身份通过
+- Logs/captures: 命令标准输出;无 Phase capture
+- Quantitative result: 45/45 baseline checks 通过,0 个失败;包含 8 个受保护控制面文件 SHA-256
+- Reviewer: not run;bootstrap 不是 Phase gate
+- Open P0/P1: none for Loop bootstrap
+- Conclusion: Loop preflight 可用;Phase 0 仍未通过
+
+反向检查:同一入口以 -Gate phase0 运行,exit 1,准确报告 Git 未初始化和 scripts/gates/phase0.ps1 缺失。
+
+## Audit / preflight / 2026-09-01T21:48:25+08:00
+
+- Commit: not available(本地 Git 尚未初始化)
+- Command: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`
+- Exit code: 0
+- Build configuration: not applicable;应用工程尚未建立
+- Hardware/runtime identity: 两个本地文件的 size/SHA-256/signature 校验通过;本次文档审查未冒充 P0.1 的 GPU/driver probe
+- Logs/captures: 命令标准输出;无 Phase capture
+- Quantitative result: 54/54 baseline checks;九个受保护控制文件 hash、STATE sequence/evidence/bounds、ignore rules 和 binary identity 全部通过;source-snapshot 内存单测为 17 files / 0 false changes / README mutation detected
+- Reviewer: not run;这是交接控制面审查,不是 Phase gate
+- Open P0/P1: none for the control-plane audit;应用 Phase 0 尚未开始
+- Conclusion: 经过清理后的 Loop preflight 可用,仍没有任何 Phase 被标为完成
+
+反向证据:`phase0` exit 1(Git 与 phase0 gate 缺失);`phase1` exit 1(并命中 requested=1/current=0);`cycle.completed=80,status=ready` exit 1(state-loop-bounds);提前解锁 Phase 1 exit 1(state-phase-sequence)。两次临时 STATE 修改均已恢复,随后再次执行正向 preflight。
+
+## Goal Cycle 001 / preflight / 2026-09-02T20:23:27+08:00
+
+- Commit: not available(本地 Git 尚未初始化,属 P0.2 范围)
+- Command: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`
+- Exit code: 0
+- Build configuration: not applicable;应用工程尚未建立(P0.4 范围)
+- Hardware/runtime identity: nvngx_dlssnr.dll size/SHA256/Valid NVIDIA 签名通过;renodx add-on size/SHA256/NotSigned 通过;`nvidia-smi` 实测 NVIDIA GeForce RTX 5070 / 616.56 / 12227 MiB / compute 12.0;System32 nvofapi64.dll 32.0.16.1656;Windows 10.0.26200.9168
+- Logs/captures: 命令标准输出(记录于 loop/JOURNAL.md Cycle 001);无 Phase capture
+- Quantitative result: 54/54 checks 通过,0 失败;工具链实测 MSVC 14.44.35207(cl 19.44.35226)、CMake 3.31.6-msvc6、Ninja 1.12.1、DXC 1.8-1.8.2502.11、Git 2.53.0.windows.2,全部与 Playbook §1.4 记录一致
+- Reviewer: not run;preflight 不是 Phase gate
+- Open P0/P1: none
+- Conclusion: P0.1 验收成立——Goal Agent 亲自采集的 preflight + 工具链/GPU/driver 证据取代交接基线;Phase 0 仍未通过(P0.2–P0.9 未完成)
diff --git a/loop/GOAL_PROMPT.md b/loop/GOAL_PROMPT.md
new file mode 100644
index 00000000..c716a3a0
--- /dev/null
+++ b/loop/GOAL_PROMPT.md
@@ -0,0 +1,59 @@
+# 可直接交给 Goal 模式的任务
+
+将下面整段作为另一个 Agent 的目标。推荐把 Goal 最大循环数设为 80;如果产品另有硬上限,以更小的硬上限为准,达到上限时必须留档,不能伪报完成。
+
+~~~text
+目标:在当前 Veyra DLSS Video Player 工作区内,严格按
+AGENTS.md、loop/LOOP_ENGINE.md、
+VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md 和
+VEYRA_PRODUCT_SPEC_V1.md,
+从当前真实状态继续施工,完成 Phase 0 到 Phase 7 的 V1。
+
+你是唯一有写权限的 Maker。每个回合先恢复 loop/STATE.json,
+核对磁盘/Git/日志,再只做 loop/BACKLOG.md 中当前 Phase 的第一个
+未完成原子任务。改动前写 loop/JOURNAL.md;改动后先跑窄测试,
+再运行 scripts/loop-gate.ps1 的当前 phase gate。任何“通过”都必须
+来自实际命令、exit code、日志、counter 或 capture,禁止把 stub、
+仅编译、理论结果、黑图或重复帧写成成功。
+
+不要重做“Magpie 是否证明 DLSS 可用于普通软件/视频”的可行性研究,
+也不要做主观画质优化;这里的测试只验证工程调用、数据契约、颜色
+parity、时序、延迟和稳定性。
+
+同一 failure fingerprint 最多做 3 个有新证据的不同尝试;连续 5 个
+cycle 没有新增可验证证据就停止重复并持久化阻塞;总计最多 80 个
+完整 cycle。可绕开的外部阻塞先记录,再继续当前 Phase 内不依赖它的
+工作;当前 gate 未通过时禁止启动后续 Phase。
+
+每个 Phase 的 gate 首次通过后,严格使用 loop/REVIEW_PROMPT.md,把
+其中的占位值替换后交给一个新上下文子 Agent 做只读 Reviewer:它不得
+编辑文件,必须独立重跑 gate 并按 Playbook 第 19 节检查。修完全部
+P0/P1、gate 再次通过、Reviewer 通过后,更新
+STATE/BACKLOG/EVIDENCE/JOURNAL/WORKLOG,做本地 checkpoint commit,
+然后自动进入下一 Phase,不等待用户确认。禁止并行写入 Agent。
+
+你被授权在项目目录内编辑、构建、运行测试、初始化本地 Git、创建
+本地 commit,并从 Playbook 指定的官方/上游来源获取开发依赖到
+gitignore 的 local 目录。你没有权限 push、发 PR、上传/发布/打包
+artifact、安装或降级驱动、修改系统安全设置、接受许可证条款、
+寻找其他 DLSSNR 泄露文件、修改签名 DLL、加载 RenoDX add-on、
+复制 Magpie GPL 源码或破坏用户改动。
+
+Goal 启动后,README、.gitignore、AGENTS、LOOP_ENGINE、GOAL_PROMPT、
+REVIEW_PROMPT、CONTROL_HASHES、基础 loop-gate、gate contract、
+Playbook 和 Product Spec 是只读控制面,禁止通过改规则或重写 hash manifest
+来过关。你只能新增/修改当前 Phase 的 phaseN gate;BACKLOG 只能更新
+状态或增加不降低门槛的子任务。
+
+若 loop/STOP 存在,保存状态并立即停止,不得删除它。只有 Phase 0
+到 7 的 gate 与独立 Reviewer 全部真实通过、Playbook 第 21 节全部
+有证据、无 P0/P1、专有文件未入 Git,才可把目标标为 complete。
+无法独立复核时状态必须是 needs_review;达到循环上限时状态必须是
+needs_handoff;同一真实阻塞连续三个 Goal 回合且无其他安全工作时
+才可标 blocked。不要因为预算或时间将近就声称完成。
+
+立即从 BOOT/RECONCILE 开始,不要先重写方案,不要询问用户已经由
+文档明确回答的问题。首条命令应运行 preflight gate。
+~~~
+
+说明:这是本项目唯一的无人值守执行入口。非 Goal 模式只能完成当前 Phase 后停下报告。
diff --git a/loop/INBOX.md b/loop/INBOX.md
new file mode 100644
index 00000000..bb44003e
--- /dev/null
+++ b/loop/INBOX.md
@@ -0,0 +1,14 @@
+# Veyra Human Inbox
+
+本文件只放需要用户新授权、凭据、许可接受、外部硬件或公开发布决定的阻塞,不放普通 bug 和待办。
+
+当前没有需要用户处理的阻塞。
+
+新增条目必须包含:
+
+- 发现时间与 Phase;
+- 精确阻塞和真实错误;
+- 已做的 3 个不同验证/尝试(如果适用);
+- 为什么不能安全自动决定;
+- 不受它影响、已经继续执行的工作;
+- 用户只需回答的最小问题。
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
new file mode 100644
index 00000000..6ad1cb7a
--- /dev/null
+++ b/loop/JOURNAL.md
@@ -0,0 +1,86 @@
+# Veyra Loop Journal
+
+本文件记录推理的可审计摘要和实际命令,不记录虚构结果。大日志放 logs/,这里只写路径与摘要。
+
+## Cycle 000 — Loop bootstrap
+
+Phase: 0
+
+Task: 安装无人值守 Loop Engine 的持久协议、目标 Prompt 和预检入口。
+
+Expected evidence: loop 文件存在;preflight 可运行;项目既有实现边界不被改写。
+
+Result:
+
+- 首次 preflight exit 1:Windows PowerShell 5.1 将无 BOM 脚本中的非 ASCII 产品方案路径按本地代码页解码,误报文件缺失;其余 hash/signature/ignore checks 通过。
+- 修复:bootstrap 检查改为不依赖源码中的非 ASCII literal;后续完整审查又把产品规格迁移到稳定的 ASCII 路径。
+- 2026-09-01T17:07:22+08:00 再次运行 preflight,exit 0。
+- 反向运行 phase0,按预期 exit 1:本地 Git 尚未初始化且 scripts/gates/phase0.ps1 尚不存在。证明当前状态不能越过 Phase 0。
+- 加入控制面 hash manifest 和完整 STATE ledger 校验后,于 2026-09-01T17:16:32+08:00 再跑 45 项 preflight,exit 0。
+- 有进展:预检由真实失败变为通过,未伪造 Phase 0 完成。
+
+## Control-plane audit — 2026-09-01T21:48:25+08:00(不计入 Goal cycle)
+
+- 全量复核产品规格、施工手册、Loop、STATE 和 gate;删除已被否决且无引用的旧方案,保留内容迁移为 `VEYRA_PRODUCT_SPEC_V1.md`。
+- 修复 ReShade preset 误判、SR/NVOF 循环依赖、D3D12VA surface 合同、NVOF 输入/重置、DLSSG motion scale 冲突和 caller shim 边界语义。
+- 重建九文件控制面 manifest;preflight 54/54,exit 0。
+- 反向 `phase0` exit 1:Git/phase0 gate 均不存在;反向 `phase1` exit 1:额外命中 current-phase 约束。
+- 临时将 cycle.completed 设为 80 且保持 ready,preflight 命中 state-loop-bounds 并 exit 1;已恢复为 0。
+- 临时提前解锁 Phase 1,preflight 命中 state-phase-sequence 并 exit 1;已恢复为 locked。
+- 内存单测执行 source snapshot/compare:17 个文件、相同快照变化数 0、模拟 README hash 变化被准确检出;磁盘文件未被该测试修改。
+- 未实现应用、未初始化 Git、未调用任何 NGX Feature;Phase 0 仍是唯一可施工阶段。
+
+---
+
+## Cycle 001 — P0.1 preflight 重跑与工具链/GPU probe
+
+### Before
+
+- Phase: 0
+- 唯一任务: 重跑 54 项 preflight,实测工具链与 GPU/driver,把证据写入 JOURNAL/STATE,标记 P0.1 完成。
+- 可证伪假设: 若任一控制面 hash 漂移、二进制身份不符、GPU/driver 或工具链与 Playbook §1.3/§1.4 不符,preflight/probe 将失败并停工。
+- 预计修改文件: loop/JOURNAL.md、loop/STATE.json、loop/BACKLOG.md(仅状态)。
+- 快速检查命令: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`;`nvidia-smi --query-gpu=name,driver_version,memory.total,compute_cap --format=csv,noheader`;各工具 `--version`。
+- 预期新增证据: preflight exit 0(54/54);真实 GPU/driver/OS/工具版本记录。
+
+### After
+
+- 实际修改: 仅本 Journal 条目、STATE.json(cycle/currentTask/nextAction/phase state=in_progress)、BACKLOG.md(P0.1 → DONE)。未触碰任何控制面文件。
+- 实际命令与 exit code:
+ - `scripts/loop-gate.ps1 -Gate preflight` → exit 0,54/54 checks(含 9 控制面 hash、两二进制 size/SHA256/签名、STATE ledger/limits/sequence、gitignore 8 项)。
+ - `cmd /c ver` → Windows 10.0.26200.9168。
+ - `nvidia-smi --query-gpu=...` → NVIDIA GeForce RTX 5070, 616.56, 12227 MiB, 12.0。
+ - System32 `nvofapi64.dll` FileVersion → 32.0.16.1656。
+ - `git --version` → 2.53.0.windows.2;`cmake --version` → 3.31.6-msvc6;`ninja --version` → 1.12.1;`dxc --version` → dxcompiler 1.8-1.8.2502.11 / dxil 1.8;MSVC 14.44.35207(cl 19.44.35226)。
+- 新证据/日志路径: 本条目即证据;无 GPU capture(Phase 0 probe 程序尚未建立)。
+- 失败 fingerprint: 无(全部命令 exit 0)。
+- 本 fingerprint 第几次不同尝试: 不适用。
+- 是否有进展,依据: 是——P0.1 的验收证据(preflight 0 + 实测工具链/GPU/driver 与 Playbook 一致)由本 Goal Agent 亲自采集,取代交接文档中的基线记录。
+- STATE/BACKLOG 更新: STATE.cycle.completed=1,phase 0 → in_progress,currentTask/nextAction 指向 P0.2;BACKLOG P0.1 → DONE。
+- 下一唯一动作: P0.2 按 LOOP_ENGINE §6 固定顺序初始化本地 Git(先验证 ignore,再显式 allowlist staging、baseline commit、切 agent/veyra-v1-loop)。
+
+---
+
+复制下面模板开始每个新 cycle。必须先填 Before,再改代码;完成后填 After。
+
+## Cycle NNN — 简短任务名
+
+### Before
+
+- Phase:
+- 唯一任务:
+- 可证伪假设:
+- 预计修改文件:
+- 快速检查命令:
+- 预期新增证据:
+
+### After
+
+- 实际修改:
+- 实际命令与 exit code:
+- 新证据/日志路径:
+- 失败 fingerprint:
+- 本 fingerprint 第几次不同尝试:
+- 是否有进展,依据:
+- STATE/BACKLOG 更新:
+- 下一唯一动作:
diff --git a/loop/LOOP_ENGINE.md b/loop/LOOP_ENGINE.md
new file mode 100644
index 00000000..5e26b4b2
--- /dev/null
+++ b/loop/LOOP_ENGINE.md
@@ -0,0 +1,317 @@
+# Veyra Loop Engine v1
+
+本文件把 Goal-based loop 落成 Veyra 项目的无人值守执行协议。它不是一句“持续工作直到完成”的提示词,而是一套可恢复、可验收、会停机的状态机。
+
+设计依据是 Claude Code 团队所述的 Goal-based loop:人工触发,以“目标完成或最大回合数”为停止条件,用确定性完成标准和第二 Agent 审查减少自我放行。Veyra 在此基础上增加 GPU/专有文件安全门禁和磁盘恢复状态。
+
+## 1. 目标与真源
+
+目标是完成 Playbook 定义的 V1(Phase 0 到 Phase 7),也不评价 DLSS 对日常视频是否“好看”。
+
+信息优先级:
+
+1. 实际文件、编译器、测试结果和运行日志;
+2. 根目录 AGENTS.md 的安全与许可证规则;
+3. 本文件的循环与停机规则;
+4. VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md 的施工细节;
+5. VEYRA_PRODUCT_SPEC_V1.md 的产品边界;
+6. loop/STATE.json、loop/EVIDENCE.md、docs/WORKLOG.md 中已经由证据确认的状态。
+
+文档与实际结果冲突时,以实际结果为准,但必须记录冲突;不允许偷偷改掉验收标准来让结果“通过”。
+
+## 2. 为什么采用单写者
+
+Veyra 的 D3D12 device、资源状态、NGX 参数、history/reset、颜色传递和播放时钟高度耦合。多个 Agent 同时写同一个 checkout,合并成功也可能留下时序错误。因此:
+
+- 主 Agent 是唯一 Maker,负责修改工作区。
+- Reviewer 只读检查 diff、代码、日志和门禁结果,不改文件。
+- 每个 Phase 只在本阶段门禁通过后启动一次新上下文 Reviewer。
+- 不创建并行写入 Agent。未来真要并行,必须使用独立 Git worktree 且任务文件完全不重叠;V1 Loop 默认禁止。
+
+## 3. 持久文件
+
+每次 Goal 回合开始都必须先读:
+
+- AGENTS.md
+- loop/LOOP_ENGINE.md
+- loop/STATE.json
+- loop/BACKLOG.md
+- loop/INBOX.md
+- docs/WORKLOG.md 的最后一个条目
+- git status --short、git diff --stat、git log -5 --oneline(Git 初始化后)
+
+职责:
+
+- loop/STATE.json:机器可读的当前位置、失败计数和下一动作。
+- loop/BACKLOG.md:按依赖排序的原子任务,不是随手愿望清单。
+- loop/JOURNAL.md:每轮先写假设,轮后写实际结果。
+- loop/EVIDENCE.md:通过门禁的证据索引;不复制大日志。
+- loop/INBOX.md:只有需要用户新授权或外部条件的真实阻塞。
+- docs/WORKLOG.md:面向交接的阶段记录。
+- loop/STOP:用户紧急停机开关。存在时保存状态并立即退出;Agent 不得自行删除。
+
+STATE.json 不是事实的替代品。若它与 Git、文件或日志冲突,先执行 RECONCILE,修正状态后再工作。
+STATE.phases 必须始终保留 0 到 7 的完整 ledger。进入下一 Phase 时只解锁相邻项;gateEvidence、reviewEvidence 和 commit 不得填入推测值。
+
+## 4. 允许与禁止
+
+无人值守时允许:
+
+- 读取、编辑、构建和运行本项目;
+- 初始化本地 Git 仓库并创建小型本地 checkpoint commit;
+- 从 Playbook 指定的官方或上游项目获取依赖,放入已忽略的 local 目录;
+- 在本机 RTX/NVIDIA 环境运行测试、GPU capture 和诊断;
+- 启动一个只读 Reviewer;
+- 在已有接口和验收定义内选择最小实现方案。
+
+无人值守时禁止:
+
+- push、创建远程仓库/PR、发布、上传 artifact、签名或制作含专有文件的安装包;
+- 安装/降级显卡驱动、关闭安全机制、修改系统级 DLL 搜索路径;
+- 搜索或下载其他“偷跑版”运行时,修改/重签 nvngx_dlssnr.dll;
+- 加载、注入、链接、改名或分发 renodx-dlss5-1.addon64;
+- 复制 Magpie GPL 源码进入闭源主线;
+- git reset --hard、强制 checkout、清理用户改动或其他破坏性 Git 操作;
+- 为通过门禁而降低阈值、删除失败测试、伪造日志或把 stub 当实现;
+- 对许可证、缺失 SDK、需要账号接受条款等事项自行替用户作决定。
+
+Goal 启动后,下列是只读控制面,Maker 和 Reviewer 都不得修改:
+
+- AGENTS.md
+- README.md
+- .gitignore
+- loop/LOOP_ENGINE.md
+- loop/GOAL_PROMPT.md
+- loop/REVIEW_PROMPT.md
+- loop/CONTROL_HASHES.json
+- scripts/loop-gate.ps1
+- scripts/gates/README.md
+- VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
+- VEYRA_PRODUCT_SPEC_V1.md
+
+发现控制面缺陷时写 INBOX 并继续其他安全任务,不能自行“修正规则”。允许创建和修改 scripts/gates/phase0.ps1 到 phase7.ps1;它们属于被审查的产品验证代码,不属于控制面。
+
+preflight 会按 loop/CONTROL_HASHES.json 校验控制面内容。任何 hash 漂移都 fail closed;不得通过重写 manifest 或基础 gate 消除告警。
+
+BACKLOG 只允许更新状态、补充不降低原门槛的原子子任务;禁止删除或改写验收项。STATE、JOURNAL、EVIDENCE、INBOX、WORKLOG 是运行状态,可以按协议更新。
+
+## 5. 状态机
+
+ BOOT
+ |
+ v
+ RECONCILE -> SELECT -> SPECIFY -> IMPLEMENT -> FAST_VERIFY
+ ^ | |
+ | | v
+ | +------ REPAIR
+ | |
+ | v
+ +---- CHECKPOINT <- REVIEW <- PHASE_GATE
+ |
+ +---- next microtask / next phase
+
+异常分支:
+
+- STOP 文件存在:PAUSED。
+- 同一 failure fingerprint 的 3 个不同方案都失败:ESCALATE。
+- 连续 5 轮没有新增可验证证据:ESCALATE。
+- 用户授权/许可证/硬件是唯一剩余阻塞:BLOCKED。
+- 80 个完整 cycle 后仍未完成:NEEDS_HANDOFF,留下可直接续跑的状态。
+- Phase 0 到 7 的全部完成定义真实成立:COMPLETE。
+
+## 6. 每一轮的固定协议
+
+### BOOT / RECONCILE
+
+1. 若 loop/STOP 存在,更新 STATE.status 为 paused,记录原因并退出。
+2. 读取第 3 节所列文件。
+3. 运行:
+
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
+
+4. 对照磁盘、Git 和最后一次日志修正 STATE。崩溃后不从头重做;先确认上次 patch 是否已存在、命令是否实际完成。
+5. 如果 preflight 因二进制身份、跟踪专有文件或 STOP 失败,不进入 IMPLEMENT。
+
+首次初始化 Git 时按固定顺序:
+
+1. 先确认 preflight 为 0;
+2. git init -b main;
+3. 若本仓库没有 user.name/email,只设置 repository-local 身份 Veyra Goal Agent / [email protected],不改 global config;
+4. 用 git check-ignore -v 分别确认两个根目录二进制、runtime_local、third_party_local、reference_local、captures、logs;
+5. 只显式 add 控制面、状态文档和现有方案,检查 git diff --cached --name-only 中没有专有文件;
+6. 创建 chore: establish Veyra baseline,记录该真实 hash 为 STATE.baselineCommit;
+7. 创建并切换到 agent/veyra-v1-loop,再用单独的 loop: record baseline commit 提交 STATE 指针。
+
+如果 Git 已存在,不重新 init、不改分支历史,先识别当前分支和用户未提交改动。
+
+### SELECT
+
+只选择 loop/BACKLOG.md 中当前 Phase 的第一个未完成且未阻塞原子任务。一个 cycle 只能有一个主任务,预计应能在一次小 patch 和一次验证中闭环。
+
+选择顺序:
+
+1. 修复当前 gate 的确定性失败;
+2. 补齐能暴露当前风险的测试/诊断;
+3. 实现当前 Phase 的下一个依赖;
+4. 清理由本轮产生且会阻塞 gate 的问题。
+
+禁止“顺便做 UI”“顺便重构”“先把后面接口都搭好”。
+
+### SPECIFY
+
+改代码前,先在 loop/JOURNAL.md 新增本轮开头,至少写:
+
+- cycle 编号与当前 Phase;
+- 唯一任务;
+- 可证伪的假设;
+- 预计修改文件;
+- 快速检查命令;
+- 通过后会新增什么证据。
+
+若无法写出确定的验证方式,这个任务还不够小,继续拆分。
+
+### IMPLEMENT
+
+- 修改最小范围。
+- 新行为优先先添加会失败的自动检查或可测 probe。
+- 保持错误码、HRESULT、NGX result、资源格式/尺寸、GPU timing 可记录。
+- 不覆盖用户或上一轮未确认的修改。
+
+### FAST_VERIFY
+
+先跑最窄检查,再跑当前 Phase gate。所有命令和 exit code 写入 JOURNAL。只编译不等于运行通过。
+
+当前阶段统一入口:
+
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate phaseN
+
+phaseN 必须替换为 phase0 到 phase7。scripts/gates/phaseN.ps1 必须由对应 Phase 建立,并检查 Playbook 中该 Phase 的真实验收结果。缺少 gate 脚本本身就是失败,不能手工口头放行。
+
+所有 phase gate 都必须遵守 scripts/gates/README.md:不修改源代码、控制面或 STATE,fail closed,实际运行测试并解析量化结果。Gate 可以触发被测程序在 ignored 的 logs/captures 下生成带 run-id 的新证据,但不能自行伪造、补写或修改结果,也不得只 grep 旧日志中的 PASS。
+
+窄测试通过且本轮产生了真实前进证据时,可以创建本地小提交,消息格式 phase-N work: <atomic outcome>。只显式 stage 本轮文件,提交前再次列出 staged names;失败状态、编译产物、runtime 和 captures 不提交。这个提交不是 Phase 通过,不能写入 lastGoodCommit。
+
+### REPAIR
+
+失败时生成稳定 fingerprint:
+
+ phase | command | exit/result code | first actionable error
+
+对同一 fingerprint:
+
+1. 第一次:定位最可能的本地原因,做最小修复;
+2. 第二次:收集额外诊断,验证另一个假设;
+3. 第三次:更换实现路径或缩小复现;
+4. 仍失败:停止重复,写入 INBOX/STATE,只转做当前 Phase 内不依赖该阻塞的任务;若没有独立任务则 BLOCKED。
+
+“重跑同一命令且没有新信息”不算不同尝试,并增加 noProgressCycles。
+failureLedger 必须按 fingerprint 累积 attempt、假设、命令和结果;切换到别的错误后再回来,次数不能清零。lastFailureFingerprint 只是快速恢复指针。
+
+### PHASE_GATE
+
+只有以下全部成立,当前 Phase 才能标记 passed:
+
+- 当前 phaseN gate exit code 为 0;
+- gate 输出和关键日志已登记到 EVIDENCE;
+- Debug/Release 或 Playbook 要求的运行矩阵真实执行;
+- Git 未跟踪专有 runtime、local SDK、capture 或大日志;
+- 无已知 P0/P1 缺陷;
+- WORKLOG 已写实际命令、结果、失败和下一步。
+
+### REVIEW
+
+阶段 gate 首次通过后,启动一个新上下文 Reviewer,任务必须明确“只读,不修改工作区”。Reviewer 要:
+
+1. 完整读 AGENTS、本循环、当前 Phase 定义和 git diff;
+2. 独立重跑 phaseN gate;
+3. 对照 Playbook 第 19 节逐项审查;
+4. 查找伪完成、错误类型、资源状态、历史 reset、许可证和证据缺口;
+5. 仅输出 P0/P1/P2 findings、证据和结论。
+
+Maker 必须修复 P0/P1 并重新跑 gate 与 Reviewer。P2 只有在不影响当前 gate/后续正确性时才能进入 BACKLOG。若平台没有可用的子 Agent 能力,不得声称“独立复核通过”;状态改为 needs_review,而不是自动进下一 Phase。
+
+### CHECKPOINT
+
+Reviewer 通过后:
+
+1. 更新 BACKLOG、EVIDENCE、JOURNAL 和 WORKLOG,并把 STATE 中本阶段状态置为 review_passed,commit 字段暂为 null;
+2. 检查 git diff --check、staged names 和 git status;
+3. 创建已验证内容的本地 checkpoint commit,消息格式:
+
+ phase-N: <verified outcome>
+
+4. 立刻读取 git rev-parse HEAD;把这个真实 hash 写入 STATE.lastGoodCommit 和 STATE.phases[N].commit,并把本阶段状态置为 passed、相邻下一 Phase 解锁;
+5. 以 loop: record phase N checkpoint 创建第二个纯状态提交。lastGoodCommit 指向前一个“已验证内容提交”,因此不会出现让文件引用其自身提交 hash 的不可能自引用;
+6. 自动进入下一 Phase,不等待用户逐阶段确认。
+
+不 push、不 merge 到任何远端。
+
+每个 cycle 收尾时(无论成功或失败)只把 cycle.completed 增加 1 次,更新 currentTask、nextAction、updatedAt;有新证据则 noProgressCycles 清零,否则加 1。先验证 STATE 能被 ConvertFrom-Json 读取,再结束本回合。
+
+## 7. 阶段门禁摘要
+
+具体参数、命令和阈值以 Playbook 第 16、17、21 节为准,下面只定义不可省略的出门条件。
+
+| Phase | 必须证明的结果 |
+|---|---|
+| 0 | 正确工具链与 D3D12 device;4-slot fence ring;本机 GPU/driver;两个文件身份;DLSSNR required exports;Debug/Release probe 实跑 |
+| 1 | RGBA8 Proxy 直接进入 Feature 18;Create 成功;连续 300/300 Evaluate 成功;Raw 输出非黑、非恒定、随参数/输入变化;资源与计时日志完整 |
+| 2 | Original→Parity Encode→Feature18→Parity Decode;CPU/GPU shader 对照在 Playbook 容差内;identity/bypass、色阶/transfer/range 正确 |
+| 3 | FFmpeg 共享 D3D12 device 的 D3D12VA 解码;无正常路径 CPU 像素回读;seek/reset;30 分钟播放和有界队列 |
+| 4 | DLSS SR 接入;正确 render/output subrect 与 reset;关闭 SR 时可旁路;没有把 NR 冒充 SR |
+| 5 | 查询 NVOF runtime/capability;可用时验证真实 flow/cost→confidence、grid/scale/sign 与 scene-cut reset;不可用时以真实 capability 结果触发 Zero fallback;不得主动跳过或用零运动冒充 NVOF |
+| 6 | DLSSG 2X 真实生成帧;按官方 header 验证 source-pixel motion 的归一化 scale/方向;generated-frame counter/hash/timestamp 证明不是重复 present;cadence、reset 与 UI 合成顺序正确 |
+| 7 | audio-master 时钟、A/V sync、seek/pause/resume;有界低延迟队列;最小 UI 位于 FG 后;端到端稳定性 |
+
+不得用 HDR、3X/4X、采集、Depth Anything 等未来扩展拖延 V1。
+
+## 8. 前进证据与防骗规则
+
+下列之一才算“本轮有进展”:
+
+- 新增自动检查从 fail 变 pass;
+- 当前 gate 的失败项减少;
+- 获得新的可操作错误码/日志,排除了一个明确假设;
+- 完成一个可构建、可运行、被测试覆盖的原子任务;
+- 阶段 Reviewer 关闭一个 P0/P1。
+
+代码行数、接口桩、TODO、只编译、理论 FPS、返回 0 但黑图都不算进展。
+
+日志和 capture 保存在已忽略目录;EVIDENCE 只写相对路径、命令、hash/摘要、exit code 和结论。不存在的 artifact 不得登记。
+
+## 9. 阻塞与严格顺序
+
+遇到阻塞先判断是否影响所有后续工作。
+
+- NVOF SDK/账号条款不可用:完成当前 Phase 内不依赖 SDK 的 capability、Zero fallback、接口和测试工作,再记录 Phase 5 阻塞。Phase 5 gate 未通过时不得把 Phase 6/7 标为开始;严格顺序优先于“多做一点”。
+- DLSSNR hash 不符、签名无效、required export 缺失:安全停机,不换 DLL。
+- 当前 GPU/driver 不满足实际运行:只继续当前 Phase 内的纯 CPU/配置/诊断工作,GPU gate 保持未通过;不得提前把后续 Phase 标为开始。
+- 需要用户接受许可证、提供凭据、公开发布或执行系统级变更:写入 INBOX,不擅自同意。
+
+只有在同一阻塞连续三个 Goal 回合都存在、并且没有任何安全的独立工作可做时,才把 Goal 标记 blocked。
+
+## 10. COMPLETE 的唯一条件
+
+只有同时满足以下条件才能结束 Goal:
+
+1. Phase 0 到 7 在 BACKLOG 和 STATE 中均为 passed;
+2. 每一阶段都有 phase gate 的 exit 0 证据和 Reviewer 通过结论;
+3. Playbook 第 21 节的每一项都有真实日志/counter/capture/present 证据;
+4. 没有未解决 P0/P1;
+5. 专有文件与 local SDK 未被 Git 跟踪或打包;
+6. 最终 Debug/Release 构建和端到端运行真实执行;
+7. STATE、EVIDENCE、WORKLOG 与 Git 一致;baselineCommit/lastGoodCommit/各 Phase commit 都真实存在且是当前 HEAD 的祖先;
+8. 仅允许列出不影响 V1 定义的 P2/未来扩展项。
+
+达到 cycle 上限、预算接近耗尽、文档写完或“理论上可行”都不是 COMPLETE。
+
+## 11. 人工接管
+
+用户回来后只需看:
+
+1. loop/STATE.json 的 status、phase、nextAction;
+2. loop/INBOX.md 是否有授权问题;
+3. loop/EVIDENCE.md 的最后一个 gate;
+4. docs/WORKLOG.md 的最后一个阶段记录。
+
+若要立即停机,在项目根目录创建 loop/STOP。续跑前由用户删除;Agent 没有删除权限。
diff --git a/loop/REVIEW_PROMPT.md b/loop/REVIEW_PROMPT.md
new file mode 100644
index 00000000..0d9a0901
--- /dev/null
+++ b/loop/REVIEW_PROMPT.md
@@ -0,0 +1,56 @@
+# 阶段 Reviewer 固定任务
+
+Maker 在每个 Phase gate 首次通过后,把下面任务交给一个新上下文子 Agent,并替换 N、BASE_COMMIT 和 GATE_EVIDENCE。Reviewer 只读;不要把 Maker 的解释当证据。
+
+~~~text
+你是 Veyra Phase N 的独立 Reviewer,不是 Maker。你没有修改受版本
+控制内容的权限:禁止 apply_patch、格式化、git add/commit/checkout,
+也禁止启动其他写入 Agent。运行 gate 时允许被测程序只在 gitignored
+的 logs/captures 下生成带 run-id 的新诊断证据。
+
+先完整阅读 AGENTS.md、loop/LOOP_ENGINE.md、
+VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md 中 Phase N、日志/证据、常见失败和
+对抗式审查章节,再读 loop/EVIDENCE.md、docs/WORKLOG.md、从
+BASE_COMMIT 到当前工作区的完整 diff。不要信任 Maker 的成功摘要。
+BASE_COMMIT 必须是 STATE.baselineCommit(Phase 0)或
+STATE.phases[N-1].commit(后续 Phase);先用 git cat-file -e 验证它
+真实存在。
+
+独立执行:
+1. scripts/loop-gate.ps1 -Gate preflight;
+2. scripts/loop-gate.ps1 -Gate phaseN;
+3. 对当前 Phase 最关键的一个窄测试或日志/capture 交叉检查;
+4. git status --short,确认专有 runtime、SDK、captures、logs 未被跟踪。
+
+重点查:
+- stub/仅编译/理论数值冒充运行通过;
+- 返回 success 但黑图、恒定图或重复帧;
+- NGX 参数名正确但类型错误;
+- D3D12 resource state/subrect/format/lifetime/fence 错误;
+- open/seek/resize/pause/scene-cut/device-lost 缺 history reset;
+- 正常路径 GPU→CPU 回读、每帧 fence wait、无界队列;
+- Raw NR 冒充 parity、Zero Motion 冒充 NVOF、重复 present 冒充 FG;
+- ReShade addon、泄露 runtime、GPL Magpie 或 local SDK 污染主线;
+- Maker 修改验收标准、测试或日志来制造通过。
+- Goal 开始后控制面文件被修改,或 phase gate 降低 Playbook 门槛。
+- CONTROL_HASHES 被改写,或 preflight 的控制面 hash 校验被绕过。
+
+输出固定格式:
+GATE_EXIT: <preflight>/<phaseN>
+WORKTREE_MUTATED_BY_REVIEWER: no
+FINDINGS:
+- [P0|P1|P2] 文件:行或 artifact — 事实、影响、最小修复条件
+EVIDENCE_GAPS:
+- ...
+VERDICT: PASS 或 FAIL
+
+只有两个 gate 都是 0、实际证据支持 Phase N 全部门槛、无 P0/P1,才能
+PASS。缺少运行环境或证据就是 FAIL/needs_review,不要用“看起来正确”
+放行。即使发现问题也只报告,不要修改。
+~~~
+
+Maker 在 Reviewer 前后都要记录 git status --porcelain=v1 和:
+
+ git diff --no-ext-diff --binary | git hash-object --stdin
+
+若指纹变化,Reviewer 违反只读契约。不要直接 reset;先区分 Reviewer 改动和用户并发改动,再按 AGENTS.md 处理。
diff --git a/loop/STATE.json b/loop/STATE.json
new file mode 100644
index 00000000..2e630890
--- /dev/null
+++ b/loop/STATE.json
@@ -0,0 +1,101 @@
+{
+ "schemaVersion": 1,
+ "engineVersion": "veyra-loop-v1",
+ "objective": "Complete the Veyra V1 definition for Phase 0 through Phase 7 with deterministic gates and independent phase review.",
+ "status": "ready",
+ "phase": {
+ "id": 0,
+ "name": "Runtime probe and D3D12 skeleton",
+ "state": "in_progress",
+ "gate": "phase0"
+ },
+ "phases": [
+ {
+ "id": 0,
+ "name": "Runtime probe and D3D12 skeleton",
+ "status": "in_progress",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 1,
+ "name": "Feature 18 native harness",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 2,
+ "name": "RenoDX-equivalent parity codec",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 3,
+ "name": "Minimal video pipeline",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 4,
+ "name": "DLSS SR",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 5,
+ "name": "NVOF guidance",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 6,
+ "name": "DLSSG 2X",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ },
+ {
+ "id": 7,
+ "name": "Audio and minimum UI",
+ "status": "locked",
+ "gateEvidence": null,
+ "reviewEvidence": null,
+ "commit": null
+ }
+ ],
+ "cycle": {
+ "completed": 1,
+ "maximum": 80,
+ "sameFailureAttempts": 0,
+ "maximumSameFailureAttempts": 3,
+ "noProgressCycles": 0,
+ "maximumNoProgressCycles": 5
+ },
+ "currentTask": "P0.2: initialize local Git per LOOP_ENGINE fixed order (ignore probes, explicit allowlist staging, baseline commit, agent/veyra-v1-loop branch, baselineCommit pointer).",
+ "lastGate": {
+ "name": "preflight",
+ "status": "passed",
+ "exitCode": 0,
+ "evidence": "loop/EVIDENCE.md#goal-cycle-001--preflight--2026-09-02"
+ },
+ "lastFailureFingerprint": null,
+ "failureLedger": [],
+ "baselineCommit": null,
+ "lastGoodCommit": null,
+ "openP0P1Findings": [],
+ "blockers": [],
+ "nextAction": "Execute P0.2 Git initialization in the LOOP_ENGINE fixed order, then continue P0.3 phase0 gate creation.",
+ "updatedAt": "2026-09-02T20:23:27+08:00"
+}
diff --git a/scripts/gates/README.md b/scripts/gates/README.md
new file mode 100644
index 00000000..699988be
--- /dev/null
+++ b/scripts/gates/README.md
@@ -0,0 +1,45 @@
+# Phase gate contract
+
+每个 scripts/gates/phaseN.ps1 都必须:
+
+1. 接受必填参数 param([string]$Root);
+2. Set-StrictMode -Version Latest,失败时非零退出;
+3. 不修改源代码、控制面、STATE/BACKLOG/EVIDENCE/WORKLOG;可以运行被测程序,让它在 gitignored 的 logs/captures 下生成本次 run-id 对应的新日志、counter 和 capture;
+4. fail closed:命令、日志、capture、counter、硬件能力或解析字段缺失都失败;
+5. 实际运行当前阶段的程序/测试,不能只搜索旧日志中的“PASS”;
+6. 检查 Debug/Release 和 Playbook 要求的运行矩阵;
+7. 打印每项 check、实际值、阈值、artifact 路径和最终 exit code;
+8. 不访问 renodx add-on,不联网换 DLSSNR 文件,不上传 artifact;
+9. 可重复运行;每次生成唯一 run-id,验证证据的 run-id、时间、输入 hash 和当前可执行文件 hash,不能把旧残留误认成本次结果;
+10. exit 0 只表示本阶段机器可验证条件通过,不代替独立 Reviewer。
+
+基础 `scripts/loop-gate.ps1` 会在 phase gate 前后 hash 所有 Git 已跟踪和未忽略的
+项目文件;phase gate 只能让被测程序写入已忽略的 `logs/`、`captures/` 或 build
+目录。任何源码、gate、STATE/记录或控制面变化都会让外层 gate 失败。
+
+建议骨架:
+
+~~~powershell
+[CmdletBinding()]
+param([Parameter(Mandatory = $true)][string]$Root)
+Set-StrictMode -Version Latest
+$ErrorActionPreference = "Stop"
+
+# Resolve known executables and inputs from $Root.
+# Run the actual test/probe and capture its exit code.
+# Parse quantitative output and fail if any required field/artifact is absent.
+
+if (-not $allChecksPassed) {
+ exit 1
+}
+exit 0
+~~~
+
+禁止的假 gate:
+
+- 只检查 exe 或日志“存在”;
+- 输出 PASS 后无条件 exit 0;
+- gate 自己伪造/补写结果文件,或用 placeholder 代替被测程序的真实输出;
+- 不核对 run-id、输入/exe hash,直接复用任意旧日志或 capture;
+- 用当前日期、代码行数、编译成功代替 Create/Evaluate/present 证据;
+- 捕获到黑图、恒定图、重复帧仍因 API 返回 0 而通过。
diff --git a/scripts/loop-gate.ps1 b/scripts/loop-gate.ps1
new file mode 100644
index 00000000..91e3c5fa
--- /dev/null
+++ b/scripts/loop-gate.ps1
@@ -0,0 +1,480 @@
+[CmdletBinding()]
+param(
+ [ValidateSet("preflight", "phase0", "phase1", "phase2", "phase3", "phase4", "phase5", "phase6", "phase7")]
+ [string]$Gate = "preflight"
+)
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = "Stop"
+
+$root = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "..")).Path
+$checks = New-Object System.Collections.Generic.List[object]
+$state = $null
+
+function Add-Check {
+ param(
+ [string]$Name,
+ [bool]$Passed,
+ [string]$Detail
+ )
+
+ $checks.Add([pscustomobject]@{
+ Check = $Name
+ Passed = $Passed
+ Detail = $Detail
+ })
+}
+
+function Get-ProjectSourceSnapshot {
+ $paths = @()
+ $gitMarker = Join-Path $root ".git"
+
+ if (Test-Path -LiteralPath $gitMarker) {
+ $paths = @(& git -C $root ls-files --cached --others --exclude-standard)
+ if ($LASTEXITCODE -ne 0) {
+ throw "git ls-files failed while creating the gate mutation snapshot"
+ }
+ }
+ else {
+ $paths = @(
+ "README.md",
+ ".gitignore",
+ "AGENTS.md",
+ "VEYRA_PRODUCT_SPEC_V1.md",
+ "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
+ "loop/LOOP_ENGINE.md",
+ "loop/GOAL_PROMPT.md",
+ "loop/REVIEW_PROMPT.md",
+ "loop/CONTROL_HASHES.json",
+ "loop/STATE.json",
+ "loop/BACKLOG.md",
+ "loop/JOURNAL.md",
+ "loop/EVIDENCE.md",
+ "loop/INBOX.md",
+ "docs/WORKLOG.md",
+ "scripts/loop-gate.ps1",
+ "scripts/gates/README.md"
+ )
+ }
+
+ $snapshot = @{}
+ foreach ($relativePath in @($paths | Sort-Object -Unique)) {
+ $fullPath = Join-Path $root $relativePath
+ $snapshot[[string]$relativePath] = if (Test-Path -LiteralPath $fullPath -PathType Leaf) {
+ (Get-FileHash -LiteralPath $fullPath -Algorithm SHA256).Hash.ToUpperInvariant()
+ }
+ else {
+ "<missing>"
+ }
+ }
+ return $snapshot
+}
+
+function Compare-ProjectSourceSnapshot {
+ param(
+ [hashtable]$Before,
+ [hashtable]$After
+ )
+
+ $allPaths = @(@($Before.Keys) + @($After.Keys) | Sort-Object -Unique)
+ foreach ($relativePath in $allPaths) {
+ $beforeHash = if ($Before.ContainsKey($relativePath)) { [string]$Before[$relativePath] } else { "<absent>" }
+ $afterHash = if ($After.ContainsKey($relativePath)) { [string]$After[$relativePath] } else { "<absent>" }
+ if ($beforeHash -ne $afterHash) {
+ [string]$relativePath
+ }
+ }
+}
+
+function Require-File {
+ param([string]$RelativePath)
+
+ $path = Join-Path $root $RelativePath
+ $exists = Test-Path -LiteralPath $path -PathType Leaf
+ Add-Check "file:$RelativePath" $exists $(if ($exists) { "present" } else { "missing" })
+ return $exists
+}
+
+function Check-Binary {
+ param(
+ [string]$RelativePath,
+ [long]$ExpectedSize,
+ [string]$ExpectedSha256,
+ [string]$ExpectedSignature,
+ [string]$ExpectedSignerFragment = ""
+ )
+
+ $path = Join-Path $root $RelativePath
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
+ Add-Check "binary:$RelativePath" $false "missing"
+ return
+ }
+
+ $item = Get-Item -LiteralPath $path
+ Add-Check "size:$RelativePath" ($item.Length -eq $ExpectedSize) "actual=$($item.Length) expected=$ExpectedSize"
+
+ $actualHash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToUpperInvariant()
+ Add-Check "sha256:$RelativePath" ($actualHash -eq $ExpectedSha256) "actual=$actualHash"
+
+ $signature = Get-AuthenticodeSignature -LiteralPath $path
+ $signatureText = [string]$signature.Status
+ Add-Check "signature:$RelativePath" ($signatureText -eq $ExpectedSignature) "actual=$signatureText expected=$ExpectedSignature"
+
+ if ($ExpectedSignerFragment.Length -gt 0) {
+ $subject = if ($null -ne $signature.SignerCertificate) { [string]$signature.SignerCertificate.Subject } else { "" }
+ Add-Check "signer:$RelativePath" ($subject -like "*$ExpectedSignerFragment*") "subject=$subject"
+ }
+}
+
+$stopPath = Join-Path $root "loop\STOP"
+if (Test-Path -LiteralPath $stopPath) {
+ Write-Host "VEYRA LOOP PAUSED: loop\STOP exists. Persist state and exit; do not delete it."
+ exit 20
+}
+
+$requiredFiles = @(
+ "README.md",
+ "AGENTS.md",
+ "VEYRA_PRODUCT_SPEC_V1.md",
+ "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
+ ".gitignore",
+ "loop\LOOP_ENGINE.md",
+ "loop\GOAL_PROMPT.md",
+ "loop\REVIEW_PROMPT.md",
+ "loop\CONTROL_HASHES.json",
+ "loop\STATE.json",
+ "loop\BACKLOG.md",
+ "loop\JOURNAL.md",
+ "loop\EVIDENCE.md",
+ "loop\INBOX.md",
+ "scripts\gates\README.md"
+)
+
+foreach ($requiredFile in $requiredFiles) {
+ [void](Require-File $requiredFile)
+}
+
+$controlManifestPath = Join-Path $root "loop\CONTROL_HASHES.json"
+$expectedControlManifestHash = "BAD07CB327A0B2171B738C7AEA42F20F54585A332A378A5523BD09453C3BE0D3"
+if (Test-Path -LiteralPath $controlManifestPath -PathType Leaf) {
+ $actualControlManifestHash = (Get-FileHash -LiteralPath $controlManifestPath -Algorithm SHA256).Hash.ToUpperInvariant()
+ $manifestHashValid = $actualControlManifestHash -eq $expectedControlManifestHash
+ Add-Check "control-manifest-hash" $manifestHashValid "actual=$actualControlManifestHash"
+
+ if ($manifestHashValid) {
+ try {
+ $controlManifest = Get-Content -Raw -Encoding UTF8 -LiteralPath $controlManifestPath | ConvertFrom-Json
+ $manifestEntries = @($controlManifest.files)
+ $expectedControlPaths = @(
+ ".gitignore",
+ "AGENTS.md",
+ "README.md",
+ "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
+ "VEYRA_PRODUCT_SPEC_V1.md",
+ "loop/GOAL_PROMPT.md",
+ "loop/LOOP_ENGINE.md",
+ "loop/REVIEW_PROMPT.md",
+ "scripts/gates/README.md"
+ ) | Sort-Object
+ $actualControlPaths = @($manifestEntries | ForEach-Object { [string]$_.path } | Sort-Object)
+ $validManifestEntries = @($manifestEntries | Where-Object {
+ $entryPath = [string]$_.path
+ (-not [string]::IsNullOrWhiteSpace($entryPath)) -and
+ (-not [IO.Path]::IsPathRooted($entryPath)) -and
+ ($entryPath -notmatch '(^|[\\/])\.\.([\\/]|$)') -and
+ ([string]$_.sha256 -match '^[0-9A-Fa-f]{64}$')
+ }).Count -eq $manifestEntries.Count
+ $manifestSchemaValid = ($controlManifest.schemaVersion -eq 1) -and
+ ($manifestEntries.Count -eq 9) -and
+ $validManifestEntries -and
+ (($actualControlPaths -join "|") -ceq ($expectedControlPaths -join "|"))
+ Add-Check "control-manifest-schema" $manifestSchemaValid "schemaVersion=$($controlManifest.schemaVersion) files=$($manifestEntries.Count) exactProtectedSet=$((($actualControlPaths -join '|') -ceq ($expectedControlPaths -join '|')))"
+
+ foreach ($entry in $manifestEntries) {
+ $relativeControlPath = [string]$entry.path
+ if ([string]::IsNullOrWhiteSpace($relativeControlPath) -or
+ [IO.Path]::IsPathRooted($relativeControlPath) -or
+ $relativeControlPath -match '(^|[\\/])\.\.([\\/]|$)') {
+ Add-Check "control:$relativeControlPath" $false "invalid relative path"
+ continue
+ }
+
+ $controlPath = Join-Path $root $relativeControlPath
+ if (-not (Test-Path -LiteralPath $controlPath -PathType Leaf)) {
+ Add-Check "control:$($entry.path)" $false "missing"
+ continue
+ }
+
+ $controlHash = (Get-FileHash -LiteralPath $controlPath -Algorithm SHA256).Hash.ToUpperInvariant()
+ $expectedControlHash = ([string]$entry.sha256).ToUpperInvariant()
+ Add-Check "control:$($entry.path)" ($controlHash -eq $expectedControlHash) "actual=$controlHash"
+ }
+ }
+ catch {
+ Add-Check "control-manifest-schema" $false $_.Exception.Message
+ }
+ }
+}
+
+$statePath = Join-Path $root "loop\STATE.json"
+if (Test-Path -LiteralPath $statePath -PathType Leaf) {
+ try {
+ $state = Get-Content -Raw -Encoding UTF8 -LiteralPath $statePath | ConvertFrom-Json
+ $validSchema = ($state.schemaVersion -eq 1) -and ($state.engineVersion -eq "veyra-loop-v1")
+ Add-Check "state-json" $validSchema "schemaVersion=$($state.schemaVersion) engineVersion=$($state.engineVersion)"
+
+ $allowedStatuses = @("ready", "running", "repairing", "needs_review", "paused", "blocked", "needs_handoff", "complete")
+ $validStatus = $allowedStatuses -contains [string]$state.status
+ Add-Check "state-status" $validStatus "status=$($state.status)"
+
+ $phaseId = [int]$state.phase.id
+ $allowedPhaseStates = @("not_started", "in_progress", "gate_passed", "review_passed", "passed", "blocked")
+ $validCurrentPhase = ($phaseId -ge 0) -and ($phaseId -le 7) -and ($allowedPhaseStates -contains [string]$state.phase.state)
+ Add-Check "state-current-phase" $validCurrentPhase "id=$phaseId state=$($state.phase.state)"
+
+ $phaseRecords = @($state.phases)
+ $phaseIds = @($phaseRecords | ForEach-Object { [int]$_.id } | Sort-Object -Unique)
+ $allowedLedgerStates = @("not_started", "locked", "in_progress", "gate_passed", "review_passed", "passed", "blocked")
+ $invalidLedgerStates = @($phaseRecords | Where-Object { $allowedLedgerStates -notcontains [string]$_.status })
+ $validLedger = ($phaseRecords.Count -eq 8) -and (($phaseIds -join ",") -eq "0,1,2,3,4,5,6,7") -and ($invalidLedgerStates.Count -eq 0)
+ Add-Check "state-phase-ledger" $validLedger "records=$($phaseRecords.Count) ids=$($phaseIds -join ',')"
+
+ $currentLedgerRecords = @($phaseRecords | Where-Object { [int]$_.id -eq $phaseId })
+ $phaseIdentityValid = ($currentLedgerRecords.Count -eq 1) -and
+ ([string]$state.phase.gate -ceq "phase$phaseId") -and
+ ([string]$state.phase.name -ceq [string]$currentLedgerRecords[0].name)
+ Add-Check "state-phase-identity" $phaseIdentityValid "id=$phaseId gate=$($state.phase.gate) name=$($state.phase.name)"
+
+ $phaseEvidenceValid = $true
+ foreach ($record in $phaseRecords) {
+ $recordStatus = [string]$record.status
+ $hasGateEvidence = -not [string]::IsNullOrWhiteSpace([string]$record.gateEvidence)
+ $hasReviewEvidence = -not [string]::IsNullOrWhiteSpace([string]$record.reviewEvidence)
+ $hasCommit = -not [string]::IsNullOrWhiteSpace([string]$record.commit)
+
+ if ((@("gate_passed", "review_passed", "passed") -contains $recordStatus) -and -not $hasGateEvidence) {
+ $phaseEvidenceValid = $false
+ }
+ if ((@("review_passed", "passed") -contains $recordStatus) -and -not $hasReviewEvidence) {
+ $phaseEvidenceValid = $false
+ }
+ if (($recordStatus -eq "passed") -and -not $hasCommit) {
+ $phaseEvidenceValid = $false
+ }
+ if (($recordStatus -eq "locked") -and ($hasGateEvidence -or $hasReviewEvidence -or $hasCommit)) {
+ $phaseEvidenceValid = $false
+ }
+ }
+ Add-Check "state-phase-evidence" $phaseEvidenceValid "gate/review/commit fields must match ledger status"
+
+ $completedCycles = [int]$state.cycle.completed
+ $maximumCycles = [int]$state.cycle.maximum
+ $sameFailureAttempts = [int]$state.cycle.sameFailureAttempts
+ $maximumSameFailureAttempts = [int]$state.cycle.maximumSameFailureAttempts
+ $noProgressCycles = [int]$state.cycle.noProgressCycles
+ $maximumNoProgressCycles = [int]$state.cycle.maximumNoProgressCycles
+
+ $validLimits = ($completedCycles -ge 0) -and
+ ($completedCycles -le $maximumCycles) -and
+ ($sameFailureAttempts -ge 0) -and
+ ($sameFailureAttempts -le $maximumSameFailureAttempts) -and
+ ($noProgressCycles -ge 0) -and
+ ($noProgressCycles -le $maximumNoProgressCycles) -and
+ ([int]$state.cycle.maximum -eq 80) -and
+ ([int]$state.cycle.maximumSameFailureAttempts -eq 3) -and
+ ([int]$state.cycle.maximumNoProgressCycles -eq 5)
+ Add-Check "state-loop-limits" $validLimits "completed=$completedCycles/$maximumCycles sameFailure=$sameFailureAttempts/$maximumSameFailureAttempts noProgress=$noProgressCycles/$maximumNoProgressCycles"
+
+ $validPhaseSequence = $true
+ foreach ($record in $phaseRecords) {
+ $recordId = [int]$record.id
+ if ($recordId -lt $phaseId -and [string]$record.status -ne "passed") {
+ $validPhaseSequence = $false
+ }
+ elseif ($recordId -eq $phaseId -and [string]$record.status -ne [string]$state.phase.state) {
+ $validPhaseSequence = $false
+ }
+ elseif ($recordId -gt $phaseId -and [string]$record.status -ne "locked") {
+ $validPhaseSequence = $false
+ }
+ }
+ Add-Check "state-phase-sequence" $validPhaseSequence "current=$phaseId; earlier must be passed, later must be locked"
+
+ $stateStatus = [string]$state.status
+ $cycleBoundValid = ($completedCycles -lt $maximumCycles) -or
+ (@("needs_handoff", "paused", "complete") -contains $stateStatus)
+ $failureBoundValid = ($sameFailureAttempts -lt $maximumSameFailureAttempts) -or
+ (@("blocked", "needs_handoff", "paused", "complete") -contains $stateStatus)
+ $noProgressBoundValid = ($noProgressCycles -lt $maximumNoProgressCycles) -or
+ (@("blocked", "needs_handoff", "paused", "complete") -contains $stateStatus)
+ $loopBoundsValid = $cycleBoundValid -and $failureBoundValid -and $noProgressBoundValid
+ Add-Check "state-loop-bounds" $loopBoundsValid "status=$stateStatus cycle=$cycleBoundValid failure=$failureBoundValid noProgress=$noProgressBoundValid"
+
+ $allPhasesPassed = @($phaseRecords | Where-Object { [string]$_.status -eq "passed" }).Count -eq 8
+ $completionHasGitPointers = (Test-Path -LiteralPath (Join-Path $root ".git")) -and
+ (-not [string]::IsNullOrWhiteSpace([string]$state.baselineCommit)) -and
+ (-not [string]::IsNullOrWhiteSpace([string]$state.lastGoodCommit))
+ $completionConsistent = ([string]$state.status -ne "complete") -or
+ ($allPhasesPassed -and
+ (@($state.openP0P1Findings).Count -eq 0) -and
+ (@($state.blockers).Count -eq 0) -and
+ $completionHasGitPointers)
+ Add-Check "state-completion" $completionConsistent "status=$($state.status) allPhasesPassed=$allPhasesPassed openP0P1=$(@($state.openP0P1Findings).Count) blockers=$(@($state.blockers).Count) gitPointers=$completionHasGitPointers"
+
+ $blockedStateConsistent = ([string]$state.status -ne "blocked") -or
+ (([string]$state.phase.state -eq "blocked") -and (@($state.blockers).Count -gt 0))
+ Add-Check "state-blocked-consistency" $blockedStateConsistent "status=$($state.status) phaseState=$($state.phase.state) blockers=$(@($state.blockers).Count)"
+
+ $hasNextAction = -not [string]::IsNullOrWhiteSpace([string]$state.nextAction)
+ Add-Check "state-next-action" $hasNextAction $([string]$state.nextAction)
+ }
+ catch {
+ Add-Check "state-json" $false $_.Exception.Message
+ }
+}
+
+Check-Binary "nvngx_dlssnr.dll" 165840496 "E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E" "Valid" "NVIDIA"
+Check-Binary "renodx-dlss5-1.addon64" 359424 "837B6A34D41C0EB75CB105AFEB5B985CFC72CB7F3A786C5DBB3F5415C45C978F" "NotSigned"
+
+$ignorePath = Join-Path $root ".gitignore"
+if (Test-Path -LiteralPath $ignorePath -PathType Leaf) {
+ $ignoreText = Get-Content -Raw -LiteralPath $ignorePath
+ $requiredIgnoreEntries = @(
+ "/nvngx_dlssnr.dll",
+ "/renodx-dlss5-1.addon64",
+ "/runtime_local/",
+ "/third_party_local/",
+ "/reference_local/",
+ "/captures/",
+ "/logs/",
+ "/loop/STOP"
+ )
+
+ foreach ($entry in $requiredIgnoreEntries) {
+ Add-Check "gitignore:$entry" ($ignoreText.Contains($entry)) $(if ($ignoreText.Contains($entry)) { "present" } else { "missing" })
+ }
+}
+
+$gitDirectory = Join-Path $root ".git"
+if (Test-Path -LiteralPath $gitDirectory) {
+ $insideWorktreeOutput = @(& git -C $root rev-parse --is-inside-work-tree 2>$null)
+ $insideWorktreeExit = $LASTEXITCODE
+ $validGitRepository = ($insideWorktreeExit -eq 0) -and ($insideWorktreeOutput.Count -gt 0) -and ([string]$insideWorktreeOutput[-1] -eq "true")
+ Add-Check "git-repository" $validGitRepository "rev-parse exitCode=$insideWorktreeExit inside=$($insideWorktreeOutput -join ',')"
+
+ $gitStateLinksValid = $null -ne $state
+ $gitStateLinkProblems = New-Object System.Collections.Generic.List[string]
+ if ($null -eq $state) {
+ $gitStateLinkProblems.Add("STATE unavailable")
+ }
+ else {
+ $commitsToVerify = New-Object System.Collections.Generic.List[object]
+ $baselineCommit = [string]$state.baselineCommit
+ if ([string]::IsNullOrWhiteSpace($baselineCommit)) {
+ $gitStateLinksValid = $false
+ $gitStateLinkProblems.Add("baselineCommit missing")
+ }
+ else {
+ $commitsToVerify.Add([pscustomobject]@{ Label = "baselineCommit"; Commit = $baselineCommit })
+ }
+
+ $lastGoodCommit = [string]$state.lastGoodCommit
+ if (-not [string]::IsNullOrWhiteSpace($lastGoodCommit)) {
+ $commitsToVerify.Add([pscustomobject]@{ Label = "lastGoodCommit"; Commit = $lastGoodCommit })
+ }
+
+ foreach ($record in @($state.phases | Where-Object { [string]$_.status -eq "passed" })) {
+ $recordCommit = [string]$record.commit
+ if (-not [string]::IsNullOrWhiteSpace($recordCommit)) {
+ $commitsToVerify.Add([pscustomobject]@{ Label = "phase$($record.id).commit"; Commit = $recordCommit })
+ }
+ }
+
+ foreach ($commitLink in $commitsToVerify) {
+ & git -C $root cat-file -e "$($commitLink.Commit)^{commit}" 2>$null
+ $commitExists = $LASTEXITCODE -eq 0
+ if (-not $commitExists) {
+ $gitStateLinksValid = $false
+ $gitStateLinkProblems.Add("$($commitLink.Label) missing:$($commitLink.Commit)")
+ continue
+ }
+
+ & git -C $root merge-base --is-ancestor $commitLink.Commit HEAD 2>$null
+ if ($LASTEXITCODE -ne 0) {
+ $gitStateLinksValid = $false
+ $gitStateLinkProblems.Add("$($commitLink.Label) not ancestor of HEAD:$($commitLink.Commit)")
+ }
+ }
+ }
+ Add-Check "state-git-links" ([bool]$gitStateLinksValid) $(if ($gitStateLinkProblems.Count -eq 0) { "all referenced commits exist and are HEAD ancestors" } else { $gitStateLinkProblems -join "; " })
+
+ $trackedSensitive = @(& git -C $root ls-files -- "nvngx_dlssnr.dll" "renodx-dlss5-1.addon64" "runtime_local" "third_party_local" "reference_local" "captures" "logs")
+ Add-Check "git-sensitive-files" ($trackedSensitive.Count -eq 0) $(if ($trackedSensitive.Count -eq 0) { "none tracked" } else { $trackedSensitive -join ", " })
+
+ $effectiveIgnoreTargets = @(
+ "nvngx_dlssnr.dll",
+ "renodx-dlss5-1.addon64",
+ "runtime_local/.veyra-ignore-probe",
+ "third_party_local/.veyra-ignore-probe",
+ "reference_local/.veyra-ignore-probe",
+ "captures/.veyra-ignore-probe",
+ "logs/.veyra-ignore-probe",
+ "loop/STOP"
+ )
+ foreach ($target in $effectiveIgnoreTargets) {
+ & git -C $root check-ignore -q --no-index -- $target
+ $ignoreExit = $LASTEXITCODE
+ Add-Check "git-effective-ignore:$target" ($ignoreExit -eq 0) "git check-ignore exitCode=$ignoreExit"
+ }
+
+ & git -C $root diff --check
+ $worktreeDiffExit = $LASTEXITCODE
+ Add-Check "git-diff-check" ($worktreeDiffExit -eq 0) "exitCode=$worktreeDiffExit"
+
+ & git -C $root diff --cached --check
+ $stagedDiffExit = $LASTEXITCODE
+ Add-Check "git-cached-diff-check" ($stagedDiffExit -eq 0) "exitCode=$stagedDiffExit"
+}
+else {
+ Add-Check "git-repository" ($Gate -eq "preflight") "not initialized; allowed only for preflight/P0.2"
+}
+
+if ($Gate -ne "preflight") {
+ if ($null -eq $state) {
+ Add-Check "phase-gate-current-state" $false "STATE could not be loaded"
+ }
+ else {
+ $requestedPhase = [int]$Gate.Substring(5)
+ Add-Check "phase-gate-current-state" ($requestedPhase -eq [int]$state.phase.id) "requested=$requestedPhase current=$($state.phase.id)"
+ }
+
+ $gateScript = Join-Path $root ("scripts\gates\" + $Gate + ".ps1")
+ if (-not (Test-Path -LiteralPath $gateScript -PathType Leaf)) {
+ Add-Check "phase-gate:$Gate" $false "missing $gateScript; create a deterministic gate from the Playbook before claiming this phase"
+ }
+ else {
+ $sourceSnapshotBefore = Get-ProjectSourceSnapshot
+ $shell = (Get-Process -Id $PID).Path
+ & $shell -NoProfile -ExecutionPolicy Bypass -File $gateScript -Root $root
+ $gateExit = $LASTEXITCODE
+ Add-Check "phase-gate:$Gate" ($gateExit -eq 0) "exitCode=$gateExit script=$gateScript"
+
+ $sourceSnapshotAfter = Get-ProjectSourceSnapshot
+ $mutatedProjectFiles = @(Compare-ProjectSourceSnapshot -Before $sourceSnapshotBefore -After $sourceSnapshotAfter)
+ Add-Check "phase-gate-no-project-mutation" ($mutatedProjectFiles.Count -eq 0) $(if ($mutatedProjectFiles.Count -eq 0) { "non-ignored project files unchanged" } else { "changed=" + ($mutatedProjectFiles -join ",") })
+
+ $stopCreatedByGate = Test-Path -LiteralPath $stopPath
+ Add-Check "phase-gate-no-stop-creation" (-not $stopCreatedByGate) $(if ($stopCreatedByGate) { "loop/STOP appeared while gate ran" } else { "not created" })
+ }
+}
+
+$checks | Format-Table -AutoSize -Wrap
+$failed = @($checks | Where-Object { -not $_.Passed })
+
+if ($failed.Count -gt 0) {
+ Write-Host "VEYRA GATE FAILED: $($failed.Count) check(s) failed."
+ exit 1
+}
+
+Write-Host "VEYRA GATE PASSED: $Gate ($($checks.Count) checks)"
+exit 0