Wire resident Unity probe operations

This commit is contained in:
Meta Vens 2026-04-30 15:03:39 +01:00
commit a0d798c5f8
5 changed files with 521 additions and 26 deletions

View file

@ -15,7 +15,39 @@ ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-gui" / "runtime"
PROJECT_VERSION_RELATIVE = Path("ProjectSettings") / "ProjectVersion.txt"
UNITY_EDITOR_RELATIVE = Path("Editor") / "Unity.exe"
FORBIDDEN_EXTRA_ARGS = {"-batchmode", "-quit", "-projectpath"}
FORBIDDEN_EXTRA_ARGS = {"-batchmode", "-quit", "-projectpath", "-logfile"}
EDITOR_BRIDGE_RELATIVE = Path("Assets") / "Editor" / "Epiphany" / "EpiphanyEditorBridge.cs"
EDITOR_BRIDGE_EXECUTE_METHOD = "GameCult.Epiphany.Unity.EpiphanyEditorBridge.RunProbe"
NAMED_PROBE_OPERATIONS = {
"inspect-project": {
"description": "Capture Unity project/editor/build/render-pipeline facts.",
"expectedArtifacts": ["project-facts.json", "unity-probe-result.json", "unity-probe-result.md"],
},
"check-compilation": {
"description": "Check whether the editor bridge can run after Unity script compilation.",
"expectedArtifacts": ["compilation.json", "unity-probe-result.json", "unity-probe-result.md"],
},
"scene-facts": {
"description": "Capture scene hierarchy, components, prefab links, and serialized fields.",
"expectedArtifacts": ["scene-facts.json", "unity-probe-result.json", "unity-probe-result.md"],
},
"prefab-facts": {
"description": "Capture prefab hierarchy, nested instances, overrides, and serialized fields.",
"expectedArtifacts": ["prefab-facts.json", "unity-probe-result.json", "unity-probe-result.md"],
},
"serialized-object": {
"description": "Capture SerializedObject properties for one asset.",
"expectedArtifacts": [
"serialized-object-facts.json",
"unity-probe-result.json",
"unity-probe-result.md",
],
},
"reference-search": {
"description": "Search Unity asset dependencies for references to a GUID or asset.",
"expectedArtifacts": ["reference-search.json", "unity-probe-result.json", "unity-probe-result.md"],
},
}
def now_iso() -> str:
@ -140,6 +172,7 @@ def resolve_unity_editor(project_path: Path) -> dict[str, Any]:
"status": "missingProjectVersion",
"note": "ProjectSettings/ProjectVersion.txt was not found or did not pin a Unity editor.",
}
result["editorBridge"] = detect_editor_bridge(project_path)
project_version = version.get("editorVersion")
if not isinstance(project_version, str) or not project_version:
return result
@ -165,6 +198,17 @@ def resolve_unity_editor(project_path: Path) -> dict[str, Any]:
return result
def detect_editor_bridge(project_path: Path) -> dict[str, Any]:
package_path = project_path.resolve() / EDITOR_BRIDGE_RELATIVE
return {
"kind": "epiphanyUnityEditorBridge",
"path": str(package_path),
"relativePath": str(EDITOR_BRIDGE_RELATIVE).replace("\\", "/"),
"exists": package_path.exists(),
"executeMethod": EDITOR_BRIDGE_EXECUTE_METHOD,
}
def render_inspection(summary: dict[str, Any]) -> str:
installed = summary.get("installedEditors")
if not isinstance(installed, list) or not installed:
@ -221,12 +265,17 @@ def validate_unity_args(values: list[str]) -> None:
forbidden = sorted(lowered & FORBIDDEN_EXTRA_ARGS)
if forbidden:
raise ValueError(
"Unity bridge owns batchmode, quit, and projectPath; remove extra args: "
"Unity bridge owns batchmode, quit, projectPath, and logFile; remove extra args: "
+ ", ".join(forbidden)
)
def build_unity_command(summary: dict[str, Any], extra_args: list[str]) -> list[str]:
def build_unity_command(
summary: dict[str, Any],
extra_args: list[str],
*,
log_path: Path | None = None,
) -> list[str]:
editor_path = summary.get("editorPath")
if not isinstance(editor_path, str) or not editor_path:
raise ValueError("Unity editor path is unavailable.")
@ -234,14 +283,66 @@ def build_unity_command(summary: dict[str, Any], extra_args: list[str]) -> list[
if not isinstance(project_path, str) or not project_path:
raise ValueError("Unity project path is unavailable.")
validate_unity_args(extra_args)
return [
command = [
editor_path,
"-batchmode",
"-quit",
"-projectPath",
project_path,
*extra_args,
]
if log_path is not None:
command.extend(["-logFile", str(log_path)])
command.extend(extra_args)
return command
def editor_bridge_ready(summary: dict[str, Any]) -> bool:
bridge = summary.get("editorBridge")
return isinstance(bridge, dict) and bridge.get("exists") is True
def named_probe_extra_args(args: argparse.Namespace, operation: str, directory: Path) -> list[str]:
extra_args = [
"-executeMethod",
EDITOR_BRIDGE_EXECUTE_METHOD,
"-epiphanyArtifactDir",
str(directory),
"-epiphanyOperation",
operation,
]
optional_values = [
("scene", "-epiphanyScene"),
("asset", "-epiphanyAsset"),
("guid", "-epiphanyGuid"),
("max_objects", "-epiphanyMaxObjects"),
("max_properties", "-epiphanyMaxProperties"),
("max_dependencies", "-epiphanyMaxDependencies"),
]
for attribute, flag in optional_values:
value = getattr(args, attribute, None)
if value is None:
continue
extra_args.extend([flag, str(value)])
return extra_args
def write_command_artifact(
directory: Path,
*,
command: list[str],
dry_run: bool,
operation: str,
expected_artifacts: list[str] | None = None,
) -> None:
write_json(
directory / "unity-command.json",
{
"command": command,
"dryRun": dry_run,
"operation": operation,
"expectedArtifacts": expected_artifacts or [],
},
)
def run_unity(args: argparse.Namespace) -> dict[str, Any]:
@ -263,13 +364,15 @@ def run_unity(args: argparse.Namespace) -> dict[str, Any]:
write_inspection_artifacts(directory, summary)
return summary
command = build_unity_command(summary, extra_args)
log_path = directory / "unity.log"
command = build_unity_command(summary, extra_args, log_path=log_path)
summary["command"] = command
summary["logPath"] = str(log_path)
if args.dry_run:
summary["runStatus"] = "planned"
summary["returncode"] = None
write_inspection_artifacts(directory, summary)
write_json(directory / "unity-command.json", {"command": command, "dryRun": True})
write_command_artifact(directory, command=command, dry_run=True, operation="run")
return summary
stdout_path = directory / "unity-stdout.log"
@ -315,7 +418,221 @@ def run_unity(args: argparse.Namespace) -> dict[str, Any]:
)
write_inspection_artifacts(directory, summary)
write_json(directory / "unity-command.json", {"command": command, "dryRun": False})
write_command_artifact(directory, command=command, dry_run=False, operation="run")
return summary
def run_named_probe(args: argparse.Namespace, operation: str) -> dict[str, Any]:
directory = (
args.artifact_dir.resolve()
if args.artifact_dir
else artifact_dir(args.artifact_root, operation.replace("-", "_"))
)
project_path = args.project_path.resolve()
summary = resolve_unity_editor(project_path)
summary["artifactPath"] = str(directory)
summary["operation"] = operation
summary["probe"] = NAMED_PROBE_OPERATIONS[operation]
if summary.get("status") != "ready":
summary["runStatus"] = "blocked"
summary["note"] = (
f"{summary.get('note')} Runtime/editor probe refused; install the exact pinned editor "
"or use inspect artifacts as evidence of the missing runtime."
)
write_inspection_artifacts(directory, summary)
return summary
if not editor_bridge_ready(summary):
bridge = summary.get("editorBridge")
bridge_path = bridge.get("path") if isinstance(bridge, dict) else str(project_path / EDITOR_BRIDGE_RELATIVE)
summary["status"] = "missingEditorBridgePackage"
summary["runStatus"] = "blocked"
summary["note"] = (
"The Epiphany Unity editor package is missing. Add "
f"{bridge_path} before running editor-resident probes."
)
write_inspection_artifacts(directory, summary)
return summary
extra_args = named_probe_extra_args(args, operation, directory)
log_path = directory / "unity.log"
command = build_unity_command(summary, extra_args, log_path=log_path)
summary["command"] = command
summary["logPath"] = str(log_path)
expected_artifacts = NAMED_PROBE_OPERATIONS[operation]["expectedArtifacts"]
if args.dry_run:
summary["runStatus"] = "planned"
summary["returncode"] = None
write_inspection_artifacts(directory, summary)
write_command_artifact(
directory,
command=command,
dry_run=True,
operation=operation,
expected_artifacts=expected_artifacts,
)
return summary
stdout_path = directory / "unity-stdout.log"
stderr_path = directory / "unity-stderr.log"
started = time.time()
try:
completed = subprocess.run(
command,
cwd=project_path,
capture_output=True,
check=False,
timeout=args.timeout_seconds,
)
duration_seconds = time.time() - started
stdout_path.parent.mkdir(parents=True, exist_ok=True)
stdout_path.write_bytes(completed.stdout)
stderr_path.write_bytes(completed.stderr)
summary.update(
{
"runStatus": "passed" if completed.returncode == 0 else "failed",
"returncode": completed.returncode,
"durationSeconds": round(duration_seconds, 3),
"stdoutPath": str(stdout_path),
"stderrPath": str(stderr_path),
}
)
except subprocess.TimeoutExpired as error:
duration_seconds = time.time() - started
stdout_path.parent.mkdir(parents=True, exist_ok=True)
if error.stdout:
stdout_path.write_bytes(error.stdout)
summary["stdoutPath"] = str(stdout_path)
if error.stderr:
stderr_path.write_bytes(error.stderr)
summary["stderrPath"] = str(stderr_path)
summary.update(
{
"runStatus": "timedOut",
"returncode": None,
"durationSeconds": round(duration_seconds, 3),
"note": f"Unity command timed out after {args.timeout_seconds} seconds.",
}
)
write_inspection_artifacts(directory, summary)
write_command_artifact(
directory,
command=command,
dry_run=False,
operation=operation,
expected_artifacts=expected_artifacts,
)
return summary
def check_compilation(args: argparse.Namespace) -> dict[str, Any]:
return run_named_probe(args, "check-compilation")
def probe_unity(args: argparse.Namespace) -> dict[str, Any]:
return run_named_probe(args, args.operation)
def test_unity(args: argparse.Namespace) -> dict[str, Any]:
directory = args.artifact_dir.resolve() if args.artifact_dir else artifact_dir(args.artifact_root, "run_tests")
project_path = args.project_path.resolve()
summary = resolve_unity_editor(project_path)
summary["artifactPath"] = str(directory)
summary["operation"] = "run-tests"
summary["testPlatform"] = args.platform
summary["testFilter"] = args.filter
if summary.get("status") != "ready":
summary["runStatus"] = "blocked"
summary["note"] = (
f"{summary.get('note')} Unity tests refused; install the exact pinned editor "
"or use inspect artifacts as evidence of the missing runtime."
)
write_inspection_artifacts(directory, summary)
return summary
log_path = directory / "unity.log"
test_results = directory / "test-results.xml"
extra_args = [
"-runTests",
"-testPlatform",
args.platform,
"-testResults",
str(test_results),
]
if args.filter:
extra_args.extend(["-testFilter", args.filter])
command = build_unity_command(summary, extra_args, log_path=log_path)
summary["command"] = command
summary["logPath"] = str(log_path)
summary["testResultsPath"] = str(test_results)
if args.dry_run:
summary["runStatus"] = "planned"
summary["returncode"] = None
write_inspection_artifacts(directory, summary)
write_command_artifact(
directory,
command=command,
dry_run=True,
operation="run-tests",
expected_artifacts=["test-results.xml", "unity.log"],
)
return summary
stdout_path = directory / "unity-stdout.log"
stderr_path = directory / "unity-stderr.log"
started = time.time()
try:
completed = subprocess.run(
command,
cwd=project_path,
capture_output=True,
check=False,
timeout=args.timeout_seconds,
)
duration_seconds = time.time() - started
stdout_path.parent.mkdir(parents=True, exist_ok=True)
stdout_path.write_bytes(completed.stdout)
stderr_path.write_bytes(completed.stderr)
summary.update(
{
"runStatus": "passed" if completed.returncode == 0 else "failed",
"returncode": completed.returncode,
"durationSeconds": round(duration_seconds, 3),
"stdoutPath": str(stdout_path),
"stderrPath": str(stderr_path),
}
)
except subprocess.TimeoutExpired as error:
duration_seconds = time.time() - started
stdout_path.parent.mkdir(parents=True, exist_ok=True)
if error.stdout:
stdout_path.write_bytes(error.stdout)
summary["stdoutPath"] = str(stdout_path)
if error.stderr:
stderr_path.write_bytes(error.stderr)
summary["stderrPath"] = str(stderr_path)
summary.update(
{
"runStatus": "timedOut",
"returncode": None,
"durationSeconds": round(duration_seconds, 3),
"note": f"Unity test command timed out after {args.timeout_seconds} seconds.",
}
)
write_inspection_artifacts(directory, summary)
write_command_artifact(
directory,
command=command,
dry_run=False,
operation="run-tests",
expected_artifacts=["test-results.xml", "unity.log"],
)
return summary
@ -338,12 +655,24 @@ def bridge_guidance(project_path: Path, repo_root: Path | None = None) -> str:
f"`python {script_path} inspect --project-path {project_path}`"
)
if summary.get("status") == "ready":
if editor_bridge_ready(summary):
return (
f"- Unity bridge: project pins {summary.get('projectVersion')} and the exact editor "
f"resolved to `{summary.get('editorPath')}`. If Unity execution is needed, use named "
f"bridge operations such as `python {script_path} probe --project-path {project_path} "
"--operation scene-facts --scene <Assets/...unity>` or "
f"`python {script_path} check-compilation --project-path {project_path}`. The bridge "
"owns -batchmode, -quit, -projectPath, -logFile, -executeMethod, and artifacts. Do not "
"invoke `Unity`, `Unity.exe`, default installs, or PATH-resolved editors directly, and "
"do not refactor Unity-owned scene/prefab state as raw text when the editor bridge can "
"inspect it."
)
return (
f"- Unity bridge: project pins {summary.get('projectVersion')} and the exact editor "
f"resolved to `{summary.get('editorPath')}`. If Unity execution is needed, use "
f"`python {script_path} run --project-path {project_path} -- -executeMethod <method>`; "
"the bridge owns -batchmode, -quit, -projectPath, logs, and artifacts. Do not invoke "
"`Unity`, `Unity.exe`, default installs, or PATH-resolved editors directly."
f"resolved to `{summary.get('editorPath')}`, but the resident editor package is missing. "
f"Add `{EDITOR_BRIDGE_RELATIVE.as_posix()}` before claiming scene, prefab, or runtime "
"facts. Do not invoke `Unity`, `Unity.exe`, default installs, or PATH-resolved editors "
"directly."
)
return (
f"- Unity bridge: {summary.get('note')} Run {inspect_command} to write an auditable "
@ -371,12 +700,59 @@ def main() -> int:
run_parser.add_argument("--dry-run", action="store_true")
run_parser.add_argument("unity_args", nargs=argparse.REMAINDER)
check_parser = subparsers.add_parser(
"check-compilation",
help="Run the resident editor bridge compilation probe.",
)
check_parser.add_argument("--project-path", type=Path, default=Path.cwd())
check_parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT)
check_parser.add_argument("--artifact-dir", type=Path)
check_parser.add_argument("--timeout-seconds", type=int, default=600)
check_parser.add_argument("--dry-run", action="store_true")
probe_parser = subparsers.add_parser(
"probe",
help="Run a named resident-editor probe through the pinned editor.",
)
probe_parser.add_argument("--project-path", type=Path, default=Path.cwd())
probe_parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT)
probe_parser.add_argument("--artifact-dir", type=Path)
probe_parser.add_argument("--timeout-seconds", type=int, default=600)
probe_parser.add_argument("--dry-run", action="store_true")
probe_parser.add_argument("--operation", choices=sorted(NAMED_PROBE_OPERATIONS), required=True)
probe_parser.add_argument("--scene")
probe_parser.add_argument("--asset")
probe_parser.add_argument("--guid")
probe_parser.add_argument("--max-objects", type=int)
probe_parser.add_argument("--max-properties", type=int)
probe_parser.add_argument("--max-dependencies", type=int)
test_parser = subparsers.add_parser(
"run-tests",
help="Run Unity editmode/playmode tests through the pinned editor.",
)
test_parser.add_argument("--project-path", type=Path, default=Path.cwd())
test_parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT)
test_parser.add_argument("--artifact-dir", type=Path)
test_parser.add_argument("--timeout-seconds", type=int, default=900)
test_parser.add_argument("--dry-run", action="store_true")
test_parser.add_argument("--platform", choices=["editmode", "playmode"], default="editmode")
test_parser.add_argument("--filter")
args = parser.parse_args()
try:
if args.command == "inspect":
result = inspect_unity(args)
else:
elif args.command == "run":
result = run_unity(args)
elif args.command == "check-compilation":
result = check_compilation(args)
elif args.command == "probe":
result = probe_unity(args)
elif args.command == "run-tests":
result = test_unity(args)
else:
raise ValueError(f"Unsupported command: {args.command}")
except Exception as error:
print(json.dumps({"status": "error", "error": str(error)}, indent=2), flush=True)
return 1