ueagentdevkit 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ueagent.py ADDED
@@ -0,0 +1,240 @@
1
+ """Win64 UE project inspection, isolated Automation, and offline report validation."""
2
+ import argparse
3
+ from datetime import datetime, timezone
4
+ import json
5
+ import os
6
+ import shutil
7
+ from pathlib import Path
8
+ import re
9
+ import socket
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import uuid
14
+
15
+ from Tools.environment import inspect, read_json
16
+ from Tools.report import verdict
17
+
18
+ ROOT = Path(__file__).resolve().parent
19
+ HOST = ROOT / "TestHost/AgentDevTestHost.uproject"
20
+
21
+
22
+ def write(path, data):
23
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
24
+
25
+
26
+ def execute(args):
27
+ project = args.project.resolve()
28
+ from Tools.Hygiene.recovery import ART
29
+ folder = ART / "Runs" / (datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ-") + uuid.uuid4().hex[:8])
30
+ folder.mkdir(parents=True)
31
+ from Tools.Hygiene.lifecycle import begin, finish, budget
32
+ begin(folder, project, "automation", {"argv":sys.argv[1:],"engine":str(args.engine) if args.engine else None})
33
+ print(folder, flush=True)
34
+ test = args.test
35
+ result = dict(status="ERROR", test=test, scope="Editor Automation / NullRHI")
36
+ write(folder / "manifest.json", dict(project=str(project), expected=test, seed=None,
37
+ utc=datetime.now(timezone.utc).isoformat(), invocation=sys.argv[1:]))
38
+ commands = folder / "commands.jsonl"
39
+
40
+ def start(argv, output):
41
+ with commands.open("a", encoding="utf-8") as log:
42
+ log.write(json.dumps(argv) + "\n")
43
+ return subprocess.Popen(argv, stdout=output, stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW)
44
+
45
+ try:
46
+ budget(folder, 2 * 1024**3)
47
+ env = inspect(project, args.engine)
48
+ write(folder / "environment.json", env)
49
+ build_required = not args.native or bool(env["modules"] or args.target)
50
+ required = ("editor", "build", "ubt") if build_required else ("editor",)
51
+ missing = [env["paths"][key] for key in required if env["paths"][key] in env["missing"]]
52
+ if missing:
53
+ raise ValueError(f"Missing engine tools: {missing}")
54
+ if any(not Path(p["project"]).is_absolute() or Path(p["project"]).resolve() == project for p in env["editors"]):
55
+ raise ValueError("An editor has this project name or its project identity is unknown")
56
+ target = args.target or project.stem + "Editor"
57
+ if not re.fullmatch(r"[A-Za-z0-9_]+", target) or not re.fullmatch(r"[A-Za-z0-9_.]+", test):
58
+ raise ValueError("Supply an Editor target and one exact dotted Automation test path")
59
+ if any(c in str(project) + env["paths"]["build"] for c in '&|<>^%!"\r\n'):
60
+ raise ValueError("Unsupported Windows batch path character")
61
+ result["build"] = "required" if build_required else "not needed for a project without native modules"
62
+ if build_required:
63
+ build = [env["paths"]["build"], target, "Win64", "Development", f"-Project={project}", "-WaitMutex"]
64
+ if args.native or (project == HOST and (Path(env["engine"]) / "Engine/Build/InstalledBuild.txt").exists()):
65
+ build.append("-NoHotReloadFromIDE")
66
+ with (folder / "build.log").open("wb") as log:
67
+ build_proc = start(build, log)
68
+ try:
69
+ result["build_exit"] = build_proc.wait(args.timeout)
70
+ except subprocess.TimeoutExpired:
71
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(build_proc.pid)], capture_output=True)
72
+ raise
73
+ if result["build_exit"]:
74
+ raise ValueError("Build failed; inspect build.log")
75
+ engine_log = folder / "editor.log"
76
+ report_dir = folder / "Automation"
77
+ argv = [env["paths"]["editor"], str(project), "/Engine/Maps/Entry", "-unattended", "-NullRHI",
78
+ "-nosound", "-nosplash", "-NoMessaging", "-FORCELOGFLUSH",
79
+ f"-ExecCmds=Automation RunTests {test};Quit", f"-ReportExportPath={report_dir}", f"-AbsLog={engine_log}"]
80
+ if not args.native:
81
+ if not (ROOT / "External/unreal-editor-mcp/scripts/connect.py").is_file():
82
+ raise ValueError("Initialize the optional MCP integration with Setup.ps1, or use run --native")
83
+ with socket.socket() as sock:
84
+ sock.bind(("127.0.0.1", 0))
85
+ port = sock.getsockname()[1]
86
+ argv.extend(["-EnablePlugins=ModelContextProtocol", "-ModelContextProtocolStartServer", f"-ModelContextProtocolPort={port}"])
87
+ with (folder / "console.log").open("wb") as output:
88
+ proc = start(argv, output)
89
+ deadline = time.monotonic() + args.timeout
90
+ try:
91
+ while not args.native and proc.poll() is None and time.monotonic() < deadline:
92
+ if engine_log.exists() and f"Starting MCP server on port {port}" in engine_log.read_text(errors="replace"):
93
+ listeners = subprocess.check_output(["netstat", "-ano", "-p", "tcp"], text=True)
94
+ if re.search(rf"127\.0\.0\.1:{port}\s+\S+\s+\S+\s+{proc.pid}\s*$", listeners, re.M):
95
+ scripts = ROOT / "External/unreal-editor-mcp/scripts"
96
+ if not (scripts / "connect.py").is_file():
97
+ raise ValueError("Initialize the pinned MCP dependency with Setup.ps1")
98
+ sys.path.insert(0, str(scripts))
99
+ from connect import ConnectError, handshake
100
+ try:
101
+ discovery = handshake({"url": f"http://127.0.0.1:{port}/mcp"}, scripts,
102
+ timeout=max(1, deadline - time.monotonic()))
103
+ except ConnectError as exc:
104
+ write(folder / "mcp-error.json", dict(port=port,pid=proc.pid,error=str(exc),
105
+ details=getattr(exc,"details",{})))
106
+ time.sleep(.25)
107
+ continue
108
+ if not discovery["tool_count"]:
109
+ raise ValueError("MCP discovery returned zero tools")
110
+ write(folder / "mcp.json", dict(port=port, pid=proc.pid, **discovery))
111
+ break
112
+ time.sleep(.25)
113
+ result["editor_exit"] = proc.wait(max(.01, deadline - time.monotonic()))
114
+ finally:
115
+ if proc.poll() is None:
116
+ proc.kill()
117
+ proc.wait()
118
+ index = report_dir / "index.json"
119
+ if index.is_file():
120
+ result["status"] = verdict(read_json(index), test)
121
+ elif engine_log.exists() and "No automation tests matched" in engine_log.read_text(errors="replace"):
122
+ result["status"] = "NOT_RUN"
123
+ if result["status"] == "PASS" and (result["editor_exit"] or (not args.native and not (folder / "mcp.json").exists())):
124
+ result.update(status="ERROR", error="Editor exit or MCP discovery failed")
125
+ if not index.exists():
126
+ result["detail"] = "No Automation/index.json; inspect editor.log"
127
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error:
128
+ result.update(status="ERROR", error=str(error))
129
+ write(folder / "result.json", result)
130
+ (folder / "report.md").write_text(f"# {test}\n\n{result['status']} · {result['scope']}\n\n"
131
+ + json.dumps(result, ensure_ascii=False, indent=2) + "\n\nSee commands.jsonl, environment.json, build.log, editor.log, mcp.json and Automation/index.json for completed stages.\n", encoding="utf-8")
132
+ print(json.dumps(result))
133
+ finish(folder, result["status"], environment="environment.json", report="report.md")
134
+ return 0 if result["status"] == "PASS" else 1
135
+
136
+
137
+ def main():
138
+ action = sys.argv[1:2]
139
+ if action == ["hygiene"]:
140
+ from Tools.Hygiene.cli import main as hygiene
141
+ return hygiene(sys.argv[2:])
142
+ if action in (["inspector"], ["windows"], ["media"]):
143
+ del sys.argv[1]
144
+ try:
145
+ if action == ["media"]:
146
+ from Tools.media import main as media
147
+ return media()
148
+ from Tools.optional_diagnostics import main as diagnostics
149
+ return diagnostics(action[0])
150
+ except (ImportError, OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
151
+ print(json.dumps({"status": "ERROR", "error": str(exc)}))
152
+ return 1
153
+ if sys.argv[1:2] == ["uap-lab"]:
154
+ from Tools.uap_lab import main as uap_lab
155
+ del sys.argv[1]
156
+ return uap_lab()
157
+ if sys.argv[1:2] == ["pie"]:
158
+ scripts = ROOT / "External/unreal-editor-mcp/scripts"
159
+ if not (scripts / "connect.py").is_file():
160
+ print("Run Setup.ps1 to initialize the MCP dependency", file=sys.stderr)
161
+ return 1
162
+ sys.path.insert(0, str(scripts))
163
+ from connect import probe_command
164
+ return subprocess.call([*probe_command(), str(ROOT / "Tools/pie_behavior.py"), *sys.argv[2:]])
165
+ parser = argparse.ArgumentParser(description=__doc__)
166
+ subs = parser.add_subparsers(dest="action", required=True)
167
+ association = subs.add_parser("association", help="Inspect the Windows .uproject file association as JSON")
168
+ modes = association.add_mutually_exclusive_group()
169
+ modes.add_argument("--wizard", action="store_true", help="Open the interactive diagnosis and repair wizard")
170
+ modes.add_argument("--launcher-reports-error", action="store_true",
171
+ help="Record that Epic still shows the file association warning")
172
+ subs.add_parser("uap-lab", help="Build the pinned UnrealAgentPlayer and exercise a disposable rendered host")
173
+ for action in ("inspector", "windows", "media", "hygiene"):
174
+ subs.add_parser(action)
175
+ subs.add_parser("pie", help="Run rendered PIE movement and evidence capture in a dedicated test host")
176
+ for name in ("doctor", "run"):
177
+ sub = subs.add_parser(name)
178
+ sub.add_argument("--project", type=Path)
179
+ sub.add_argument("--profile", type=Path, help="Read project, engine and Automation defaults from JSON")
180
+ sub.add_argument("--engine", type=Path)
181
+ if name == "doctor":
182
+ discovery = sub.add_mutually_exclusive_group()
183
+ discovery.add_argument("--mcp", action="store_true", help="Include read-only upstream plugin and listener inventory")
184
+ discovery.add_argument("--mcp-url", help="List tools at an explicit loopback endpoint")
185
+ if name == "run":
186
+ sub.add_argument("--test")
187
+ sub.add_argument("--target")
188
+ sub.add_argument("--native", action="store_true", help="Use UE Automation without the optional MCP provider")
189
+ sub.add_argument("--timeout", type=int, default=300, help="Seconds per stage")
190
+ check = subs.add_parser("check-report")
191
+ check.add_argument("index", type=Path)
192
+ check.add_argument("--test", required=True)
193
+ args = parser.parse_args()
194
+ try:
195
+ if args.action == "association":
196
+ windows = Path(os.environ["SystemRoot"])
197
+ system = windows / ("Sysnative" if (windows / "Sysnative").is_dir() else "System32")
198
+ shell = shutil.which("pwsh.exe") or system / "WindowsPowerShell/v1.0/powershell.exe"
199
+ folder = ROOT / "External/unreal-association-doctor"
200
+ if not (folder / "Repair-UnrealAssociation.ps1").is_file():
201
+ folder = Path(sys.prefix) / "share/ueagentdevkit/association"
202
+ host = [str(shell), "-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned"]
203
+ if args.wizard:
204
+ return subprocess.call([*host, "-File", str(folder / "Start-Doctor.ps1")])
205
+ script = folder / "Repair-UnrealAssociation.ps1"
206
+ command = ("[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); "
207
+ "& $env:UEAGENT_ASSOCIATION_SCRIPT -Mode Diagnose")
208
+ if args.launcher_reports_error:
209
+ command += " -LauncherReportsError"
210
+ return subprocess.call([*host, "-NonInteractive", "-Command", command],
211
+ env=dict(os.environ, UEAGENT_ASSOCIATION_SCRIPT=str(script)))
212
+ if args.action in ("doctor", "run"):
213
+ from Tools.project_profile import apply_project_defaults
214
+ apply_project_defaults(args, HOST)
215
+ if args.action == "run":
216
+ return execute(args)
217
+ if args.action == "check-report":
218
+ state = verdict(read_json(args.index), args.test)
219
+ print(json.dumps({"status":state,"test":args.test}))
220
+ return int(state != "PASS")
221
+ env = inspect(args.project.resolve(), args.engine)
222
+ if args.mcp:
223
+ script = ROOT / "External/unreal-editor-mcp/scripts/discover.py"
224
+ if not script.is_file():
225
+ raise ValueError("Run Setup.ps1 to initialize the MCP dependency")
226
+ inventory = subprocess.check_output([sys.executable, "-X", "utf8", str(script),
227
+ "--project", env["project"], "--engine", env["engine"]], timeout=90)
228
+ env["mcp_inventory"] = json.loads(inventory)
229
+ if args.mcp_url:
230
+ from Tools.mcp_endpoint import probe
231
+ env["mcp_endpoint"] = probe(args.mcp_url)
232
+ print(json.dumps(env, ensure_ascii=False, indent=2))
233
+ return int(bool(env["missing"] or env.get("mcp_inventory", {}).get("errors")))
234
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error:
235
+ print(json.dumps({"status":"ERROR","error":str(error)}))
236
+ return 1
237
+
238
+
239
+ if __name__ == "__main__":
240
+ sys.exit(main())
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 redtidev1918
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,226 @@
1
+ #requires -Version 5.1
2
+ [CmdletBinding()]
3
+ param(
4
+ [ValidateSet('Diagnose','Repair')][string]$Mode = 'Diagnose',
5
+ [string]$SelectorPath,
6
+ [string[]]$SearchRoot = @(),
7
+ [switch]$ForceRepair,
8
+ [switch]$LauncherReportsError,
9
+ [string]$OpenProject,
10
+ [ValidateRange(5,300)][int]$OpenTimeoutSeconds = 60,
11
+ [string]$BackupRoot = (Join-Path $env:LOCALAPPDATA 'UnrealAssociationDoctor\Backups')
12
+ )
13
+ $ErrorActionPreference = 'Stop'
14
+
15
+ function Get-RegistryDefault([string]$Path) {
16
+ if (Test-Path -LiteralPath $Path) { return (Get-Item -LiteralPath $Path).GetValue('') }
17
+ return $null
18
+ }
19
+
20
+ function Get-SelectorCandidates {
21
+ $roots = New-Object 'System.Collections.Generic.List[string]'
22
+ foreach ($root in $SearchRoot) { if ($root) { $roots.Add($root) } }
23
+ foreach ($process in @(Get-Process EpicGamesLauncher -ErrorAction SilentlyContinue)) {
24
+ if ($process.Path) { $roots.Add((Split-Path (Split-Path (Split-Path (Split-Path $process.Path))))) }
25
+ }
26
+ foreach ($view in @('Registry64','Registry32')) {
27
+ $base = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', [Microsoft.Win32.RegistryView]::$view)
28
+ try {
29
+ foreach ($name in @('SOFTWARE\EpicGames\Unreal Engine','SOFTWARE\EpicGames\EpicGamesLauncher')) {
30
+ $key = $base.OpenSubKey($name)
31
+ if ($key) {
32
+ try {
33
+ foreach ($valueName in @('INSTALLDIR','InstallLocation','AppDataPath')) {
34
+ $value = $key.GetValue($valueName)
35
+ if ($value -is [string] -and $value) { $roots.Add($value) }
36
+ }
37
+ } finally { $key.Dispose() }
38
+ }
39
+ }
40
+ } finally { $base.Dispose() }
41
+ }
42
+ $manifest = Join-Path $env:ProgramData 'Epic\UnrealEngineLauncher\LauncherInstalled.dat'
43
+ if (Test-Path -LiteralPath $manifest) {
44
+ try {
45
+ foreach ($install in (Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json).InstallationList) {
46
+ if ($install.InstallLocation) { $roots.Add($install.InstallLocation) }
47
+ }
48
+ } catch { Write-Warning "Could not parse Epic manifest: $($_.Exception.Message)" }
49
+ }
50
+ foreach ($pf in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
51
+ if ($pf) { $roots.Add((Join-Path $pf 'Epic Games')) }
52
+ }
53
+ $found = New-Object 'System.Collections.Generic.List[string]'
54
+ $command = Get-RegistryDefault 'Registry::HKEY_CLASSES_ROOT\Unreal.ProjectFile\shell\open\command'
55
+ if ($command -match '^"([^"]+\.exe)"' -and (Test-Path -LiteralPath $Matches[1])) { $found.Add($Matches[1]) }
56
+ foreach ($root in ($roots | Select-Object -Unique)) {
57
+ foreach ($relative in @('UnrealVersionSelector.exe','Engine\Binaries\Win64\UnrealVersionSelector.exe','Launcher\Engine\Binaries\Win64\UnrealVersionSelector.exe','Engine\Binaries\Win64\UnrealVersionSelector-Win64-Shipping.exe')) {
58
+ $candidate = Join-Path $root $relative
59
+ if (Test-Path -LiteralPath $candidate -PathType Leaf) { $found.Add((Get-Item -LiteralPath $candidate).FullName) }
60
+ }
61
+ }
62
+ return @($found | Sort-Object -Unique)
63
+ }
64
+
65
+ function Get-AssociationState {
66
+ $command = Get-RegistryDefault 'Registry::HKEY_CLASSES_ROOT\Unreal.ProjectFile\shell\open\command'
67
+ $target = $null
68
+ if ($command -match '^"([^"]+\.exe)"') { $target = $Matches[1] }
69
+ $overrides = @()
70
+ foreach ($name in @('.uproject','.uplugin','Unreal.ProjectFile')) {
71
+ $path = "HKCU:\Software\Classes\$name"
72
+ if (Test-Path -LiteralPath $path) {
73
+ $preview = Get-RegistryDefault ($path + '\shellex\{8895b1c6-b41f-4c1c-a562-0d564250836f}')
74
+ $overrides += [pscustomobject]@{ Name=$name; Default=(Get-RegistryDefault $path); HasChildren=(@(Get-ChildItem -LiteralPath $path).Count -gt 0); PreviewHandler=$preview; MonacoPreviewDetected=($preview -eq '{D8034CFA-F34B-41FE-AD45-62FCBB52A6DA}') }
75
+ }
76
+ }
77
+ [pscustomobject]@{
78
+ ExtensionClass = Get-RegistryDefault 'Registry::HKEY_CLASSES_ROOT\.uproject'
79
+ OpenCommand = $command
80
+ MachineOpenCommand = Get-RegistryDefault 'HKLM:\Software\Classes\Unreal.ProjectFile\shell\open\command'
81
+ TargetExists = [bool]($target -and (Test-Path -LiteralPath $target -PathType Leaf))
82
+ UserOverrides = $overrides
83
+ MonacoPreviewKeys = @($overrides | Where-Object MonacoPreviewDetected | ForEach-Object Name)
84
+ UserChoice = if (Test-Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.uproject\UserChoice') {
85
+ (Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.uproject\UserChoice').ProgId
86
+ } else { $null }
87
+ # .uplugin has no HKLM class by design: the selector only registers .uproject. Informational, never a fault.
88
+ MachinePluginClassPresent = (Test-Path 'HKLM:\Software\Classes\Unreal.PluginFile')
89
+ IsElevated = (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
90
+ PreservedKeyCount = @(Get-ChildItem -LiteralPath 'HKCU:\Software\Classes' -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -like '*.AssociationDoctor-*' }).Count
91
+ LauncherRunning = [bool](Get-Process EpicGamesLauncher -ErrorAction SilentlyContinue)
92
+ PowerToysRunning = [bool](Get-Process PowerToys -ErrorAction SilentlyContinue)
93
+ }
94
+ }
95
+
96
+ function Test-AssociationConfiguration($State, [string]$ExpectedSelector) {
97
+ if ($State.ExtensionClass -ne 'Unreal.ProjectFile' -or -not $State.TargetExists) { return $false }
98
+ if ($State.UserChoice -and $State.UserChoice -ne 'Unreal.ProjectFile') { return $false }
99
+ if ($State.OpenCommand -notmatch '^"([^\"]+UnrealVersionSelector(?:-Win64-Shipping)?\.exe)"\s+/editor\s+"%1"$') { return $false }
100
+ if ($ExpectedSelector -and $Matches[1] -ne $ExpectedSelector) { return $false }
101
+ return $State.OpenCommand -eq $State.MachineOpenCommand
102
+ }
103
+
104
+ # Decides whether the official tool should run. Returns a reason string, or $null to skip.
105
+ # A configured association with the launcher still erroring is repaired once when user-level
106
+ # overrides exist (the case that was fixed by moving them aside and rerunning the official tool).
107
+ # Once Doctor has preserved overrides before, recreated ones do not retrigger: it cannot change the outcome.
108
+ function Get-RepairReason($State, [bool]$Configured, [bool]$LauncherError, [bool]$Force) {
109
+ if (-not $Configured) { return 'AssociationNeedsRepair' }
110
+ if ($Force) { return 'Forced' }
111
+ $preserved = if ($State.PSObject.Properties['PreservedKeyCount']) { [int]$State.PreservedKeyCount } else { 0 }
112
+ if ($LauncherError -and @($State.UserOverrides).Count -gt 0 -and $preserved -eq 0) { return 'LauncherErrorWithUserOverrides' }
113
+ return $null
114
+ }
115
+
116
+ function Get-AssociationStatus([bool]$Configured, [bool]$LauncherError) {
117
+ if ($Configured -and $LauncherError) { return 'AssociationConfiguredLauncherErrorReported' }
118
+ if ($Configured) { return 'AssociationConfigured' }
119
+ return 'AssociationNeedsAttention'
120
+ }
121
+
122
+ # Opt-in end-to-end check: opens the project the way a double-click does, then looks for an editor
123
+ # process whose command line names that project. Never runs unless -OpenProject is given.
124
+ function Test-ProjectOpens([string]$Project, [int]$TimeoutSeconds) {
125
+ $full = (Resolve-Path -LiteralPath $Project).Path
126
+ if ([IO.Path]::GetExtension($full) -ne '.uproject') { throw '-OpenProject must point to a .uproject file.' }
127
+ Start-Process -FilePath $full | Out-Null
128
+ $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
129
+ while ((Get-Date) -lt $deadline) {
130
+ Start-Sleep -Seconds 2
131
+ $match = @(Get-CimInstance Win32_Process -Filter "Name LIKE 'UnrealEditor%'" -ErrorAction SilentlyContinue |
132
+ Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($full, [StringComparison]::OrdinalIgnoreCase) -ge 0 })
133
+ if ($match.Count) { return $true }
134
+ }
135
+ return $false
136
+ }
137
+
138
+ function Complete-Report($Report) {
139
+ if ($OpenProject) {
140
+ $Report.ProjectOpenVerified = [bool](Test-ProjectOpens $OpenProject $OpenTimeoutSeconds)
141
+ $Report.VerificationScope = 'Windows open command, plus project open via double-click path (-OpenProject)'
142
+ }
143
+ return [pscustomobject]$Report
144
+ }
145
+
146
+ function Invoke-AssociationDoctor {
147
+ if (-not [Environment]::Is64BitProcess -and [Environment]::Is64BitOperatingSystem) {
148
+ throw 'Use 64-bit PowerShell so registry inspection and repair use the same registry view.'
149
+ }
150
+ $before = Get-AssociationState
151
+ $candidates = @(Get-SelectorCandidates)
152
+ if ($SelectorPath) {
153
+ $selected = (Resolve-Path -LiteralPath $SelectorPath).Path
154
+ } elseif ($candidates.Count -eq 1) { $selected = $candidates[0] }
155
+ else { $selected = $null }
156
+ $configured = Test-AssociationConfiguration $before $selected
157
+ $report = [ordered]@{ Mode=$Mode; Candidates=$candidates; Selected=$selected; Before=$before; After=$null; Backup=$null; ToolExitCode=$null; RegistryVerified=$configured; LauncherVerified=$false; ProjectOpenVerified=$false; LauncherErrorReported=[bool]$LauncherReportsError; Status=(Get-AssociationStatus $configured ([bool]$LauncherReportsError)); Action='None'; RepairReason=$null; VerificationScope='Windows open command only; launcher and project loading are not tested' }
158
+ $reason = Get-RepairReason $before $configured ([bool]$LauncherReportsError) ([bool]$ForceRepair)
159
+ $report.RepairReason = $reason
160
+ if ($Mode -eq 'Diagnose') { return (Complete-Report $report) }
161
+ if (-not $reason) {
162
+ $report.Action = 'SkippedAlreadyConfigured'
163
+ Write-Warning 'Windows association already matches. No registry changes made and the official tool was not run. If Epic still reports an error, repair with -LauncherReportsError (runs once when user overrides exist); -ForceRepair only reruns the official tool.'
164
+ return (Complete-Report $report)
165
+ }
166
+ if (-not $selected) { throw 'No unique selector found. Use -SelectorPath with the intended launcher executable, or -SearchRoot with its installation directory.' }
167
+ if ([IO.Path]::GetFileName($selected) -notmatch '^UnrealVersionSelector(?:-Win64-Shipping)?\.exe$') { throw 'The selected executable is not named UnrealVersionSelector.' }
168
+ $signature = Get-AuthenticodeSignature -LiteralPath $selected
169
+ if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Epic Games') {
170
+ throw 'Automatic repair requires a valid Epic Games signed selector. Source builds can be inspected in Diagnose mode; run their trusted selector manually.'
171
+ }
172
+ $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
173
+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Repair requires an elevated PowerShell window. Diagnose does not require administrator rights.' }
174
+ if (@(Get-Process UnrealVersionSelector -ErrorAction SilentlyContinue).Count) { throw 'Close existing UnrealVersionSelector dialogs before repairing. An old error dialog must not be mistaken for a new result.' }
175
+ if ($before.UserChoice -and $before.UserChoice -ne 'Unreal.ProjectFile') { throw 'Windows UserChoice selects another app. Change the .uproject default app in Windows Settings first; this tool does not modify protected UserChoice hashes.' }
176
+ # Validate every override before making changes. Unknown registrations are preserved.
177
+ foreach ($entry in $before.UserOverrides) {
178
+ if ($entry.Name -in @('.uproject','.uplugin')) {
179
+ $expected = if ($entry.Name -eq '.uproject') { 'Unreal.ProjectFile' } else { 'Unreal.PluginFile' }
180
+ if ($entry.Default -and $entry.Default -ne $expected) { throw "Unknown association for $($entry.Name); leaving it unchanged." }
181
+ } else {
182
+ $userCommand = Get-RegistryDefault 'HKCU:\Software\Classes\Unreal.ProjectFile\shell\open\command'
183
+ if ($userCommand -notmatch 'UnrealVersionSelector[^"\\]*\.exe"?\s+/editor') { throw 'Unknown user-level project handler; leaving it unchanged.' }
184
+ }
185
+ }
186
+ $backup = Join-Path $BackupRoot ((Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,8))
187
+ New-Item -ItemType Directory -Path $backup -Force | Out-Null
188
+ $report.Backup = $backup
189
+ $before | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $backup 'before.json') -Encoding UTF8
190
+ foreach ($hive in @('HKCU','HKLM')) {
191
+ foreach ($name in @('.uproject','.uplugin','Unreal.ProjectFile','Unreal.PluginFile')) {
192
+ if (Test-Path -LiteralPath "${hive}:\Software\Classes\$name") {
193
+ & reg.exe export "$hive\Software\Classes\$name" (Join-Path $backup "$hive-$name.reg") /y | Out-Null
194
+ if ($LASTEXITCODE -ne 0) { throw "Backup failed for $hive/$name. No overrides have been moved." }
195
+ }
196
+ }
197
+ }
198
+ $moves = @()
199
+ try {
200
+ foreach ($entry in $before.UserOverrides) {
201
+ $oldPath = "HKCU:\Software\Classes\$($entry.Name)"
202
+ $newName = $entry.Name + '.AssociationDoctor-' + [guid]::NewGuid().ToString('N')
203
+ Rename-Item -LiteralPath $oldPath -NewName $newName
204
+ $moves += [pscustomobject]@{ Original=$entry.Name; Preserved=$newName }
205
+ $moves | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $backup 'preserved-keys.json') -Encoding UTF8
206
+ }
207
+ $p = Start-Process -FilePath $selected -ArgumentList '/fileassociations' -WorkingDirectory (Split-Path $selected) -PassThru
208
+ if (-not $p.WaitForExit(60000)) { throw 'Selector is still running. Inspect its dialog; do not launch another instance. Backups and preserved keys are retained.' }
209
+ $report.ToolExitCode = $p.ExitCode
210
+ $report.Action = 'OfficialToolExecuted'
211
+ $after = Get-AssociationState
212
+ $report.After = $after
213
+ $report.RegistryVerified = Test-AssociationConfiguration $after $selected
214
+ $report.Status = Get-AssociationStatus $report.RegistryVerified ([bool]$LauncherReportsError)
215
+ if ($p.ExitCode -ne 0 -or -not $report.RegistryVerified) { throw 'Official tool failed or registry verification failed; see report.json. Registry state and tool exit code are recorded separately.' }
216
+ } finally {
217
+ $report.After = Get-AssociationState
218
+ $report | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $backup 'report.json') -Encoding UTF8
219
+ }
220
+ Write-Warning 'Registry verified only. Fully exit and restart Epic, enter Unreal Engine > Library, and open a known project to verify the complete workflow. PowerToys preview may recreate user overrides.'
221
+ return (Complete-Report $report)
222
+ }
223
+
224
+ if ($MyInvocation.InvocationName -ne '.') {
225
+ Invoke-AssociationDoctor | ConvertTo-Json -Depth 10
226
+ }