agent-build-coordinator 0.3.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.
Files changed (63) hide show
  1. adapters/__init__.py +1 -0
  2. adapters/python_pytest/__init__.py +1 -0
  3. adapters/python_pytest/build_adapter.py +171 -0
  4. adapters/unreal_cpp/__init__.py +1 -0
  5. adapters/unreal_cpp/build_adapter.py +403 -0
  6. adapters/unreal_cpp/start_gate.py +66 -0
  7. agent_build_coordinator-0.3.0.dist-info/METADATA +117 -0
  8. agent_build_coordinator-0.3.0.dist-info/RECORD +63 -0
  9. agent_build_coordinator-0.3.0.dist-info/WHEEL +5 -0
  10. agent_build_coordinator-0.3.0.dist-info/entry_points.txt +2 -0
  11. agent_build_coordinator-0.3.0.dist-info/licenses/LICENSE +21 -0
  12. agent_build_coordinator-0.3.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +1 -0
  14. core/cli.py +3743 -0
  15. core/coordinator/__init__.py +1 -0
  16. core/coordinator/activity.py +720 -0
  17. core/coordinator/adapter_protocol.py +53 -0
  18. core/coordinator/cpu_reserve.py +46 -0
  19. core/coordinator/dispatcher.py +1429 -0
  20. core/coordinator/git_flow.py +1047 -0
  21. core/coordinator/handover.py +423 -0
  22. core/coordinator/host_guard.py +504 -0
  23. core/coordinator/job_queue.py +398 -0
  24. core/coordinator/lease.py +168 -0
  25. core/coordinator/protected_paths.py +68 -0
  26. core/coordinator/quotas.py +902 -0
  27. core/coordinator/ready_queue.py +90 -0
  28. core/coordinator/release_pipeline.py +327 -0
  29. core/coordinator/remote_worker.py +470 -0
  30. core/coordinator/review_gate.py +200 -0
  31. core/coordinator/round_runner.py +241 -0
  32. core/coordinator/round_state.py +449 -0
  33. core/coordinator/router.py +556 -0
  34. core/coordinator/runner.py +428 -0
  35. core/coordinator/status_doc.py +434 -0
  36. core/coordinator/test_planner.py +346 -0
  37. core/coordinator/workspaces.py +407 -0
  38. core/git_hooks/__init__.py +1 -0
  39. core/git_hooks/check_commit_msg.py +155 -0
  40. core/git_hooks/check_pre_push.py +175 -0
  41. core/git_hooks/install_hooks.py +48 -0
  42. core/github/__init__.py +21 -0
  43. core/github/client.py +577 -0
  44. core/scripts/__init__.py +1 -0
  45. core/scripts/board.py +2687 -0
  46. core/scripts/board_ui.py +5147 -0
  47. core/scripts/budget_analyze.py +195 -0
  48. core/scripts/decisions.py +537 -0
  49. core/scripts/demo.py +640 -0
  50. core/scripts/doctor.py +284 -0
  51. core/scripts/feedback.py +130 -0
  52. core/scripts/flaky_stats.py +102 -0
  53. core/scripts/harness_lint.py +387 -0
  54. core/scripts/init_repo.py +446 -0
  55. core/scripts/inputs_check.py +46 -0
  56. core/scripts/install_skills.py +151 -0
  57. core/scripts/layer_check.py +295 -0
  58. core/scripts/md_section.py +126 -0
  59. core/scripts/metrics.py +133 -0
  60. core/scripts/metrics_report.py +126 -0
  61. core/scripts/project_brief.py +273 -0
  62. core/scripts/prune_state.py +253 -0
  63. core/scripts/review_receipts.py +143 -0
adapters/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Engine and domain adapters implementing core.coordinator.adapter_protocol."""
@@ -0,0 +1 @@
1
+ """Python pytest BuildAdapter package demonstrating engine-agnostic coordination."""
@@ -0,0 +1,171 @@
1
+ """Python + pytest BuildAdapter implementation using Python stdlib only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+ import xml.etree.ElementTree as ET
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any, Callable, Sequence
11
+
12
+ from core.coordinator.adapter_protocol import BuildResult, TestResult
13
+ from core.coordinator.host_guard import suppress_error_dialogs
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class PythonAdapterConfig:
18
+ """Configuration for PythonPytestAdapter."""
19
+
20
+ python_executable: str = sys.executable
21
+ path_test_map: dict[str, tuple[str, ...]] | None = None
22
+ default_test_paths: tuple[str, ...] = ("tests",)
23
+
24
+
25
+ class PythonPytestAdapter:
26
+ """Implements BuildAdapter for Python repositories tested with pytest."""
27
+
28
+ def __init__(
29
+ self,
30
+ config: PythonAdapterConfig | None = None,
31
+ *,
32
+ runner: Callable[[Sequence[str], Path], subprocess.CompletedProcess[str]] | None = None,
33
+ ) -> None:
34
+ self.config = config or PythonAdapterConfig()
35
+ self._runner = runner or self._default_runner
36
+
37
+ @classmethod
38
+ def from_config(cls, config: dict[str, Any], workspace: Path) -> "PythonPytestAdapter":
39
+ """Construct a PythonPytestAdapter from coordinator.config.json."""
40
+ _ = workspace
41
+ raw_map = config.get("path_test_map")
42
+ path_test_map: dict[str, tuple[str, ...]] | None = None
43
+ if isinstance(raw_map, dict):
44
+ path_test_map = {str(k): tuple(str(v) for v in vals) for k, vals in raw_map.items()}
45
+
46
+ raw_defaults = config.get("default_test_paths")
47
+ default_paths = (
48
+ tuple(str(p) for p in raw_defaults)
49
+ if isinstance(raw_defaults, list) and raw_defaults
50
+ else ("tests",)
51
+ )
52
+ py_exe = str(config.get("python_executable") or sys.executable)
53
+ return cls(
54
+ PythonAdapterConfig(
55
+ python_executable=py_exe,
56
+ path_test_map=path_test_map,
57
+ default_test_paths=default_paths,
58
+ )
59
+ )
60
+
61
+ @staticmethod
62
+ def _default_runner(cmd: Sequence[str], cwd: Path) -> subprocess.CompletedProcess[str]:
63
+ with suppress_error_dialogs():
64
+ return subprocess.run(
65
+ list(cmd),
66
+ cwd=cwd,
67
+ capture_output=True,
68
+ text=True,
69
+ encoding="utf-8",
70
+ errors="replace",
71
+ check=False,
72
+ )
73
+
74
+ def select_tests(self, changed_files: Sequence[str]) -> list[str]:
75
+ """Map changed file paths to targeted pytest paths or fall back to defaults."""
76
+ if not changed_files:
77
+ return []
78
+ mapping = self.config.path_test_map or {}
79
+ selected: set[str] = set()
80
+ for raw_path in changed_files:
81
+ norm = raw_path.replace("\\", "/").strip()
82
+ for prefix, targets in mapping.items():
83
+ if norm.startswith(prefix) or prefix in norm:
84
+ selected.update(targets)
85
+ if selected:
86
+ return sorted(selected)
87
+ return sorted(set(self.config.default_test_paths))
88
+
89
+ def build_target(self, target: str, workspace: Path) -> BuildResult:
90
+ """Byte-compile the target module/directory using compileall (force recompile to avoid stale same-second pyc)."""
91
+ cmd = [self.config.python_executable, "-m", "compileall", "-f", "-q", target]
92
+ proc = self._runner(cmd, workspace)
93
+ return BuildResult(
94
+ success=(proc.returncode == 0),
95
+ exit_code=proc.returncode,
96
+ summary=(proc.stdout + "\n" + proc.stderr).strip()[:1000] or f"compileall exit={proc.returncode}",
97
+ )
98
+
99
+ @staticmethod
100
+ def parse_junit_report(xml_path: Path, *, exit_code: int) -> TestResult:
101
+ """Parse JUnit XML emitted by pytest and guard against zero-test runs."""
102
+ if exit_code == 5:
103
+ return TestResult(
104
+ verdict="NOT ASSESSED",
105
+ report_path=xml_path if xml_path.is_file() else None,
106
+ exit_code=exit_code,
107
+ )
108
+ if not xml_path.is_file():
109
+ return TestResult(
110
+ verdict="FAIL" if exit_code != 0 else "NOT ASSESSED",
111
+ report_path=None,
112
+ exit_code=exit_code,
113
+ )
114
+
115
+ try:
116
+ root = ET.parse(xml_path).getroot()
117
+ except (OSError, ET.ParseError):
118
+ return TestResult(verdict="NOT ASSESSED", report_path=xml_path, exit_code=exit_code)
119
+
120
+ passed = 0
121
+ failed_names: list[str] = []
122
+ for case in root.iter("testcase"):
123
+ if case.find("skipped") is not None:
124
+ continue
125
+ classname = case.attrib.get("classname", "").strip()
126
+ name = case.attrib.get("name", "unknown").strip()
127
+ full_name = f"{classname}::{name}" if classname else name
128
+ if case.find("failure") is not None or case.find("error") is not None:
129
+ failed_names.append(full_name)
130
+ else:
131
+ passed += 1
132
+
133
+ total = passed + len(failed_names)
134
+ if total == 0:
135
+ return TestResult(verdict="NOT ASSESSED", report_path=xml_path, exit_code=exit_code)
136
+
137
+ verdict = "PASS" if (not failed_names and exit_code == 0) else "FAIL"
138
+ return TestResult(
139
+ verdict=verdict,
140
+ total=total,
141
+ passed=passed,
142
+ failed=len(failed_names),
143
+ failed_names=tuple(failed_names),
144
+ report_path=xml_path,
145
+ exit_code=exit_code,
146
+ )
147
+
148
+ def run_tests(self, groups: Sequence[str], workspace: Path, output_dir: Path) -> TestResult:
149
+ """Run pytest on selected test groups with JUnit XML export."""
150
+ if not groups:
151
+ return TestResult(verdict="NOT ASSESSED")
152
+ output_dir.mkdir(parents=True, exist_ok=True)
153
+ xml_path = output_dir / "junit.xml"
154
+ cmd = [
155
+ self.config.python_executable,
156
+ "-m",
157
+ "pytest",
158
+ "-q",
159
+ f"--junitxml={xml_path}",
160
+ *groups,
161
+ ]
162
+ proc = self._runner(cmd, workspace)
163
+ return self.parse_junit_report(xml_path, exit_code=proc.returncode)
164
+
165
+ def check_start_gate(self, workspace: Path) -> tuple[bool, str]:
166
+ """Verify workspace is a valid Python/Git repository directory."""
167
+ if not workspace.is_dir():
168
+ return False, f"Workspace directory does not exist: {workspace}"
169
+ if (workspace / "pyproject.toml").is_file() or (workspace / ".git").exists():
170
+ return True, "Python workspace start gate clear."
171
+ return False, f"Workspace lacks pyproject.toml or .git marker: {workspace}"
@@ -0,0 +1 @@
1
+ """Unreal Engine 5 C++ adapter, rules, specialist roles, and templates."""
@@ -0,0 +1,403 @@
1
+ """Unreal Engine 5 C++ BuildAdapter implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any, Callable, Sequence
11
+
12
+ from adapters.unreal_cpp.start_gate import check_unreal_start_gate
13
+ from core.coordinator.adapter_protocol import BuildResult, TestResult
14
+ from core.coordinator.host_guard import suppress_error_dialogs
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class UnrealAdapterConfig:
19
+ uproject_path: Path
20
+ ue_root: Path
21
+ editor_target: str
22
+ game_target: str
23
+ platform: str = "Win64"
24
+ configuration: str = "Development"
25
+ plugin_test_map: dict[str, tuple[str, ...]] | None = None
26
+ extra_ubt_args: tuple[str, ...] = ()
27
+
28
+
29
+ class UnrealBuildAdapter:
30
+ """Implements core.coordinator.adapter_protocol.BuildAdapter for UE5 C++."""
31
+
32
+ def __init__(
33
+ self,
34
+ config: UnrealAdapterConfig,
35
+ *,
36
+ runner: Callable[[Sequence[str], Path], subprocess.CompletedProcess[str]] | None = None,
37
+ ) -> None:
38
+ self.config = config
39
+ self._runner = runner or self._default_runner
40
+
41
+ @classmethod
42
+ def from_config(cls, config: dict[str, Any], workspace: Path) -> "UnrealBuildAdapter":
43
+ """Construct an UnrealBuildAdapter from coordinator.config.json and UE_ROOT."""
44
+ project_name = str(config.get("project_name", "UnrealProject")).strip() or "UnrealProject"
45
+ game_target = str(config.get("game_target") or project_name)
46
+ editor_target = str(config.get("editor_target") or f"{game_target}Editor")
47
+ raw_uproject = str(config.get("uproject") or f"{game_target}.uproject").strip()
48
+ uproject_candidate = Path(raw_uproject)
49
+ uproject_path = uproject_candidate if uproject_candidate.is_absolute() else (workspace.resolve() / uproject_candidate)
50
+
51
+ raw_ue_root = str(config.get("ue_root") or os.environ.get("UE_ROOT", "")).strip()
52
+ if not raw_ue_root:
53
+ raise ValueError("Unreal Engine root path must be configured via 'ue_root' or UE_ROOT env var.")
54
+
55
+ raw_map = config.get("plugin_test_map")
56
+ plugin_test_map: dict[str, tuple[str, ...]] | None = None
57
+ if isinstance(raw_map, dict):
58
+ plugin_test_map = {str(k): tuple(str(v) for v in vals) for k, vals in raw_map.items()}
59
+
60
+ raw_extra = config.get("extra_ubt_args") or ()
61
+ extra_ubt_args = tuple(str(arg).strip() for arg in raw_extra if str(arg).strip())
62
+
63
+ return cls(
64
+ UnrealAdapterConfig(
65
+ uproject_path=uproject_path,
66
+ ue_root=Path(raw_ue_root),
67
+ editor_target=editor_target,
68
+ game_target=game_target,
69
+ platform=str(config.get("platform", "Win64")),
70
+ configuration=str(config.get("configuration", "Development")),
71
+ plugin_test_map=plugin_test_map,
72
+ extra_ubt_args=extra_ubt_args,
73
+ )
74
+ )
75
+
76
+ @staticmethod
77
+ def _headless_env() -> dict[str, str]:
78
+ env = os.environ.copy()
79
+ env["DOTNET_EnableCrashReport"] = "0"
80
+ env["COMPlus_EnableDiagnostics"] = "0"
81
+ return env
82
+
83
+ @staticmethod
84
+ def _default_runner(cmd: Sequence[str], cwd: Path) -> subprocess.CompletedProcess[str]:
85
+ env = UnrealBuildAdapter._headless_env()
86
+ with suppress_error_dialogs():
87
+ return subprocess.run(
88
+ list(cmd),
89
+ cwd=cwd,
90
+ env=env,
91
+ capture_output=True,
92
+ text=True,
93
+ encoding="utf-8",
94
+ errors="replace",
95
+ check=False,
96
+ )
97
+
98
+ def select_tests(self, changed_files: Sequence[str]) -> list[str]:
99
+ """Map changed file paths to targeted Unreal Automation test filter prefixes."""
100
+ mapping = self.config.plugin_test_map or {}
101
+ selected: set[str] = set()
102
+ for raw_path in changed_files:
103
+ norm = raw_path.replace("\\", "/")
104
+ for prefix, groups in mapping.items():
105
+ if prefix in norm:
106
+ selected.update(groups)
107
+ return sorted(selected)
108
+
109
+ def build_ubt_command(self, target: str) -> list[str]:
110
+ """Build an UnrealBuildTool command line, preferring BatchFiles wrapper when present."""
111
+ extra = list(self.config.extra_ubt_args)
112
+ if os.name == "nt":
113
+ build_bat = self.config.ue_root / "Engine" / "Build" / "BatchFiles" / "Build.bat"
114
+ if build_bat.is_file():
115
+ return [
116
+ str(build_bat),
117
+ target,
118
+ self.config.platform,
119
+ self.config.configuration,
120
+ f"-Project={self.config.uproject_path}",
121
+ "-WaitMutex",
122
+ "-FromMsBuild",
123
+ *extra,
124
+ ]
125
+ else:
126
+ build_sh = self.config.ue_root / "Engine" / "Build" / "BatchFiles" / "Linux" / "Build.sh"
127
+ if build_sh.is_file():
128
+ return [
129
+ str(build_sh),
130
+ target,
131
+ self.config.platform,
132
+ self.config.configuration,
133
+ f"-Project={self.config.uproject_path}",
134
+ "-WaitMutex",
135
+ *extra,
136
+ ]
137
+
138
+ ubt_dll = self.config.ue_root / "Engine" / "Binaries" / "DotNET" / "UnrealBuildTool" / "UnrealBuildTool.dll"
139
+ return [
140
+ "dotnet",
141
+ str(ubt_dll),
142
+ target,
143
+ self.config.platform,
144
+ self.config.configuration,
145
+ f"-Project={self.config.uproject_path}",
146
+ "-WaitMutex",
147
+ *extra,
148
+ ]
149
+
150
+ def build_automation_command(self, groups: Sequence[str], output_dir: Path) -> list[str]:
151
+ """Build a headless UnrealEditor-Cmd Automation RunTests command."""
152
+ editor_exe = self.config.ue_root / "Engine" / "Binaries" / self.config.platform / "UnrealEditor-Cmd.exe"
153
+ filter_expr = "+".join(groups)
154
+ return [
155
+ str(editor_exe),
156
+ str(self.config.uproject_path),
157
+ f"-ExecCmds=Automation RunTests {filter_expr}; Quit",
158
+ "-TestExit=Automation Test Queue Empty",
159
+ f"-abslog={output_dir / 'ue-automation.log'}",
160
+ "-unattended",
161
+ "-nop4",
162
+ "-nosplash",
163
+ "-NullRHI",
164
+ f"-ReportExportPath={output_dir}",
165
+ ]
166
+
167
+ def _run_logged_build(
168
+ self,
169
+ cmd: Sequence[str],
170
+ workspace: Path,
171
+ output_dir: Path | None,
172
+ log_filename: str,
173
+ ) -> BuildResult:
174
+ proc = self._runner(cmd, workspace)
175
+ combined = (proc.stdout + "\n" + proc.stderr).strip()
176
+ log_path: Path | None = None
177
+ if output_dir is not None:
178
+ output_dir.mkdir(parents=True, exist_ok=True)
179
+ log_path = output_dir / log_filename
180
+ log_path.write_text((combined + "\n") if combined else "", encoding="utf-8")
181
+ return BuildResult(
182
+ success=(proc.returncode == 0),
183
+ exit_code=proc.returncode,
184
+ summary=combined[:1000],
185
+ log_path=log_path,
186
+ )
187
+
188
+ def build_target(self, target: str, workspace: Path, *, output_dir: Path | None = None) -> BuildResult:
189
+ """Execute UBT for target inside workspace and optionally persist build.log."""
190
+ return self._run_logged_build(self.build_ubt_command(target), workspace, output_dir, "build.log")
191
+
192
+ def build_commandlet_command(
193
+ self,
194
+ commandlet_name: str,
195
+ output_dir: Path,
196
+ *,
197
+ render_offscreen: bool = False,
198
+ ) -> list[str]:
199
+ """Build a headless or GPU-offscreen UnrealEditor-Cmd commandlet invocation."""
200
+ editor_exe = self.config.ue_root / "Engine" / "Binaries" / self.config.platform / "UnrealEditor-Cmd.exe"
201
+ render_flags = ["-RenderOffScreen", "-AllowCommandletRendering"] if render_offscreen else ["-nullrhi"]
202
+ return [
203
+ str(editor_exe),
204
+ str(self.config.uproject_path),
205
+ f"-run={commandlet_name}",
206
+ *render_flags,
207
+ "-unattended",
208
+ "-nop4",
209
+ "-nosplash",
210
+ "-stdout",
211
+ "-NoLogTimes",
212
+ f"-abslog={output_dir / f'commandlet-{commandlet_name}.log'}",
213
+ ]
214
+
215
+ def run_commandlet(
216
+ self,
217
+ commandlet_name: str,
218
+ workspace: Path,
219
+ output_dir: Path,
220
+ *,
221
+ render_offscreen: bool = False,
222
+ ) -> BuildResult:
223
+ """Execute a named UE5 editor commandlet and persist commandlet.log."""
224
+ cmd = self.build_commandlet_command(
225
+ commandlet_name,
226
+ output_dir,
227
+ render_offscreen=render_offscreen,
228
+ )
229
+ return self._run_logged_build(cmd, workspace, output_dir, "commandlet.log")
230
+
231
+ @staticmethod
232
+ def parse_ue_test_report(report_file: Path, *, exit_code: int, stdout_text: str = "") -> TestResult:
233
+ """Parse Unreal's index.json / result.json and guard against Exit-255 zero-match runs."""
234
+ if not report_file.is_file():
235
+ # Unreal returns exit 255 both on failure and when zero tests match a filter.
236
+ return TestResult(
237
+ verdict="NOT ASSESSED" if exit_code == 255 else "FAIL",
238
+ report_path=None,
239
+ exit_code=exit_code,
240
+ )
241
+
242
+ try:
243
+ payload = json.loads(report_file.read_text(encoding="utf-8-sig", errors="replace"))
244
+ except (OSError, json.JSONDecodeError):
245
+ return TestResult(verdict="NOT ASSESSED", report_path=report_file, exit_code=exit_code)
246
+
247
+ tests = payload.get("tests") if isinstance(payload, dict) else None
248
+ if not isinstance(tests, list) or len(tests) == 0:
249
+ return TestResult(verdict="NOT ASSESSED", report_path=report_file, exit_code=exit_code)
250
+
251
+ passed = 0
252
+ failed_names: list[str] = []
253
+ for entry in tests:
254
+ if not isinstance(entry, dict):
255
+ continue
256
+ state = str(entry.get("state", "")).strip().lower()
257
+ if state == "skipped":
258
+ continue
259
+ name = str(entry.get("fullTestPath") or entry.get("testDisplayName") or "unknown")
260
+ if state == "success":
261
+ passed += 1
262
+ else:
263
+ failed_names.append(name)
264
+
265
+ total = passed + len(failed_names)
266
+ if total == 0 or ("0 tests" in stdout_text.lower() and exit_code == 255):
267
+ return TestResult(verdict="NOT ASSESSED", report_path=report_file, exit_code=exit_code)
268
+
269
+ verdict = "PASS" if (not failed_names and exit_code == 0) else "FAIL"
270
+ return TestResult(
271
+ verdict=verdict,
272
+ total=total,
273
+ passed=passed,
274
+ failed=len(failed_names),
275
+ failed_names=tuple(failed_names),
276
+ report_path=report_file,
277
+ exit_code=exit_code,
278
+ )
279
+
280
+ def run_tests(self, groups: Sequence[str], workspace: Path, output_dir: Path) -> TestResult:
281
+ """Run selected Unreal Automation test groups and parse the exported report."""
282
+ if not groups:
283
+ return TestResult(verdict="NOT ASSESSED")
284
+ output_dir.mkdir(parents=True, exist_ok=True)
285
+ cmd = self.build_automation_command(groups, output_dir)
286
+ proc = self._runner(cmd, workspace)
287
+ report_file = output_dir / "index.json"
288
+ return self.parse_ue_test_report(report_file, exit_code=proc.returncode, stdout_text=proc.stdout)
289
+
290
+ def check_start_gate(self, workspace: Path) -> tuple[bool, str]:
291
+ """Verify no conflicting UE editor/compiler processes are running."""
292
+ return check_unreal_start_gate(workspace)
293
+
294
+ def build_package_command(
295
+ self,
296
+ output_dir: Path,
297
+ *,
298
+ client: bool = True,
299
+ server: bool = False,
300
+ archive_dir: Path | None = None,
301
+ extra_uat_args: Sequence[str] = (),
302
+ ) -> list[str]:
303
+ """Build a RunUAT BuildCookRun command for client and/or dedicated server packaging."""
304
+ if os.name == "nt":
305
+ uat = self.config.ue_root / "Engine" / "Build" / "BatchFiles" / "RunUAT.bat"
306
+ else:
307
+ uat = self.config.ue_root / "Engine" / "Build" / "BatchFiles" / "RunUAT.sh"
308
+ resolved_archive = (archive_dir or (output_dir / "Archive")).resolve()
309
+ cmd = [
310
+ str(uat),
311
+ "BuildCookRun",
312
+ f"-project={self.config.uproject_path}",
313
+ "-noP4",
314
+ f"-platform={self.config.platform}",
315
+ f"-clientconfig={self.config.configuration}",
316
+ f"-serverconfig={self.config.configuration}",
317
+ "-cook",
318
+ "-allmaps",
319
+ "-stage",
320
+ "-package",
321
+ "-archive",
322
+ f"-archivedirectory={resolved_archive}",
323
+ "-unattended",
324
+ "-utf8output",
325
+ ]
326
+ if not client:
327
+ cmd.append("-noclient")
328
+ if server:
329
+ cmd.append("-server")
330
+ cmd.extend(str(arg) for arg in extra_uat_args if str(arg).strip())
331
+ return cmd
332
+
333
+ @staticmethod
334
+ def check_server_inventory(
335
+ archive_dir: Path,
336
+ *,
337
+ forbidden_patterns: Sequence[str] = ("UnrealEditor", ".pdb", "EditorData"),
338
+ ) -> dict[str, Any]:
339
+ """Verify packaged server output does not ship forbidden editor/debug artifacts."""
340
+ resolved = archive_dir.resolve()
341
+ if not resolved.is_dir():
342
+ return {
343
+ "ok": False,
344
+ "archive_dir": str(resolved),
345
+ "file_count": 0,
346
+ "total_bytes": 0,
347
+ "violations": [f"Archive directory missing: {resolved}"],
348
+ }
349
+ lowered = [str(p).lower() for p in forbidden_patterns if str(p).strip()]
350
+ file_count = 0
351
+ total_bytes = 0
352
+ violations: list[str] = []
353
+ for root_dir, _dirnames, filenames in os.walk(resolved, followlinks=False):
354
+ base = Path(root_dir)
355
+ for fname in filenames:
356
+ fpath = base / fname
357
+ rel = fpath.relative_to(resolved).as_posix()
358
+ file_count += 1
359
+ try:
360
+ total_bytes += fpath.stat().st_size
361
+ except OSError:
362
+ pass
363
+ rel_lower = rel.lower()
364
+ if any(pat in rel_lower for pat in lowered):
365
+ violations.append(rel)
366
+ return {
367
+ "ok": len(violations) == 0,
368
+ "archive_dir": str(resolved),
369
+ "file_count": file_count,
370
+ "total_bytes": total_bytes,
371
+ "violations": sorted(violations),
372
+ }
373
+
374
+ def package_project(
375
+ self,
376
+ workspace: Path,
377
+ output_dir: Path,
378
+ *,
379
+ client: bool = True,
380
+ server: bool = False,
381
+ verify_server_inventory: bool = True,
382
+ ) -> BuildResult:
383
+ """Package client/server builds via RunUAT and optionally audit server inventory."""
384
+ resolved_out = output_dir.resolve()
385
+ archive_dir = resolved_out / "Archive"
386
+ cmd = self.build_package_command(
387
+ resolved_out,
388
+ client=client,
389
+ server=server,
390
+ archive_dir=archive_dir,
391
+ )
392
+ res = self._run_logged_build(cmd, workspace, resolved_out, "package.log")
393
+ if res.success and server and verify_server_inventory:
394
+ inv = self.check_server_inventory(archive_dir)
395
+ if not inv["ok"]:
396
+ bad = ", ".join(inv["violations"][:5])
397
+ return BuildResult(
398
+ success=False,
399
+ exit_code=1,
400
+ summary=f"Server inventory check failed ({bad}).",
401
+ log_path=res.log_path,
402
+ )
403
+ return res
@@ -0,0 +1,66 @@
1
+ """Pre-launch guard checking for conflicting Unreal Editor or compiler processes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+ from typing import Callable, Sequence
9
+
10
+ CONFLICTING_PROCESS_NAMES: tuple[str, ...] = (
11
+ "unrealeditor",
12
+ "unrealeditor-cmd",
13
+ "unrealbuildtool",
14
+ "shadercompileworker",
15
+ "livecodingconsole",
16
+ )
17
+
18
+
19
+ def list_running_process_names() -> list[str]:
20
+ """Return lowercase process executable names currently running on this host."""
21
+ if os.name == "nt":
22
+ proc = subprocess.run(
23
+ ["tasklist", "/FO", "CSV", "/NH"],
24
+ capture_output=True,
25
+ text=True,
26
+ encoding="utf-8",
27
+ errors="replace",
28
+ check=False,
29
+ )
30
+ names: list[str] = []
31
+ for line in proc.stdout.splitlines():
32
+ if not line.strip():
33
+ continue
34
+ first_col = line.split(",", 1)[0].strip().strip('"').lower()
35
+ names.append(first_col.removesuffix(".exe"))
36
+ return names
37
+
38
+ proc = subprocess.run(
39
+ ["ps", "-eo", "comm="],
40
+ capture_output=True,
41
+ text=True,
42
+ encoding="utf-8",
43
+ errors="replace",
44
+ check=False,
45
+ )
46
+ return [Path(line.strip()).name.lower() for line in proc.stdout.splitlines() if line.strip()]
47
+
48
+
49
+ def check_unreal_start_gate(
50
+ workspace: Path,
51
+ *,
52
+ process_lister: Callable[[], Sequence[str]] = list_running_process_names,
53
+ allow_live_editor: bool = False,
54
+ ) -> tuple[bool, str]:
55
+ """Return (safe_to_start, reason) before launching UE editor or build steps."""
56
+ if not workspace.exists():
57
+ return False, f"Workspace does not exist: {workspace}"
58
+
59
+ if allow_live_editor:
60
+ return True, "Start gate bypassed via allow_live_editor."
61
+
62
+ running = {name.lower().removesuffix(".exe") for name in process_lister()}
63
+ conflicts = sorted(name for name in CONFLICTING_PROCESS_NAMES if name in running)
64
+ if conflicts:
65
+ return False, "Conflicting Unreal processes detected: " + ", ".join(conflicts)
66
+ return True, "No conflicting Unreal processes running."