"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: improve unreal insights live analysis
aimidi9184c00e31ee
diff --git a/skills/cli-anything-unrealinsights/SKILL.md b/skills/cli-anything-unrealinsights/SKILL.mdindex 5986f7444..8f06b682e 100644--- a/skills/cli-anything-unrealinsights/SKILL.md+++ b/skills/cli-anything-unrealinsights/SKILL.md@@ -1,6 +1,6 @@---name: "cli-anything-unrealinsights"-description: "Capture Unreal Engine traces to .utrace files and export Unreal Insights timing/counter data in headless mode."+description: "Capture Unreal Engine traces, inspect Trace Store files, keep Unreal Insights GUI open, and export/summarize timing/counter data."---# cli-anything-unrealinsights@@ -10,8 +10,10 @@ and exporter workflows on Windows.## Prerequisites-- Unreal Engine 5.5+ installed with `UnrealInsights.exe`- Windows+- Unreal Engine tools installed with `UnrealInsights.exe`+- Verified with UE 5.5; headless timing exporters include compatibility handling+ for UE 5.3-style command parsing where possible- Optional explicit env vars:- `UNREALINSIGHTS_EXE`- `UNREAL_TRACE_SERVER_EXE`@@ -42,6 +44,14 @@ cli-anything-unrealinsights trace set D:\captures\session.utracecli-anything-unrealinsights --json trace info```+### Trace Store discovery++```powershell+cli-anything-unrealinsights --json store info+cli-anything-unrealinsights --json store list --live-only+cli-anything-unrealinsights --json store latest --set-current+```+### Capture orchestration```powershell@@ -81,20 +91,64 @@ or snapshot later in a follow-up turn.If a tracked capture session is still running, `capture start` now requires`--replace` so the previous process is stopped before a new one is launched.+### Live trace control backend++```powershell+$env:UNREALINSIGHTS_LIVE_EXEC='ushell-wrapper --pid {pid} --cmd "{cmd}"'+cli-anything-unrealinsights --json live processes+cli-anything-unrealinsights --json live trace-status --pid 1234+cli-anything-unrealinsights --json live bookmark --pid 1234 "BeforeExport"+cli-anything-unrealinsights --json live stop-trace --pid 1234+```++Live command delivery requires `UNREALINSIGHTS_LIVE_EXEC` or `--backend-command`.+If no backend is configured, live commands return a JSON error and do not claim+success. `live stop-trace` stops trace collection without killing the UE process;+`capture stop` still terminates the harness-launched process tree.++### GUI co-pilot++```powershell+cli-anything-unrealinsights --json gui status+cli-anything-unrealinsights --json gui open --trace D:\captures\session.utrace+cli-anything-unrealinsights --json gui open-latest+```++GUI commands omit `-NoUI` and `-AutoQuit` so Unreal Insights remains open.+### Offline exporters```powershellcli-anything-unrealinsights --json -t D:\captures\session.utrace export threads D:\out\threads.csv-cli-anything-unrealinsights --json -t D:\captures\session.utrace export timer-stats D:\out\stats.csv --region "EXPORT_CAPTURE"-cli-anything-unrealinsights --json -t D:\captures\session.utrace export counter-values D:\out\counter_values.csv --counter "*"+cli-anything-unrealinsights --json -t D:\captures\session.utrace export timer-stats D:\out\stats.csv --region=EXPORT_CAPTURE+cli-anything-unrealinsights --json -t D:\captures\session.utrace export counter-values D:\out\counter_values.csv --counter=*```+Prefer equals-form wildcard filters such as `--timers=*` and `--counter=*`.+The harness passes simple values to UnrealInsights without inner quotes so+wildcards remain usable inside `-ExecOnAnalysisCompleteCmd`.+### Batch response files```powershellcli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D:\out\exports.rsp```+### Analyze summaries++```powershell+cli-anything-unrealinsights --json -t D:\captures\session.utrace analyze summary --out D:\out\summary+cli-anything-unrealinsights --json analyze summary --skip-export --out D:\out\summary+```++The summary reports top timers, focused GameThread/RenderThread/RHIThread+hotspots, wait/task-related timers, counter peaks, and uncovered domains for+future Memory/Network/Slate/Asset/Cooking analysis.++`analyze summary` also returns `export_status` and+`summary.diagnostics.export_status_counts` so agents can distinguish successful+exports from trace/filter combinations that completed but produced no rows.+## JSON Output Guidance- Prefer `--json` for agent workflows.@@ -102,6 +156,8 @@ cli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D- `trace_path`- `exec_command`- `output_files`+ - `output_status`+ - `status_message`- `log_path`- `exit_code`- `warnings`@@ -121,11 +177,38 @@ cli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D- `trace_path`- `trace_size`- `started_at`+- Trace Store commands return:+ - `store_dir`+ - `trace_count`+ - `traces`+ - `latest`+- Live commands return:+ - `pid`+ - `live_command`+ - `backend`+ - `exit_code`+ - `succeeded`+- Analyze summary returns:+ - `exports`+ - `export_status`+ - `summary.top_timers`+ - `summary.focus_threads`+ - `summary.wait_timers`+ - `summary.counter_peaks`+ - `summary.diagnostics`+ - `summary.uncovered_domains`++Treat `output_status == "ok"` as a materialized export. Treat+`output_status == "no_output"` as an empty trace/filter result, not a backend+crash. Use `exporter_error`, `process_failed`, and `timed_out` for retry or+debugging decisions.## Notes- v1 is Windows-first.-- v1 supports file-mode capture orchestration only.-- v1 does not control already-running UE instances or browse trace stores.+- v1 includes Trace Store browsing, GUI open/status, pluggable live command delivery,+ and timing/counter summaries.- `capture stop` is a best-effort stop of the harness-launched process tree.- `capture snapshot` is a best-effort filesystem snapshot of the active trace.+- Regression tests auto-discover the UE `example_trace.decomp.utrace` sample+ when present; the binary trace is not vendored.diff --git a/unrealinsights/agent-harness/UNREALINSIGHTS.md b/unrealinsights/agent-harness/UNREALINSIGHTS.mdindex d549b74ae..26781e37c 100644--- a/unrealinsights/agent-harness/UNREALINSIGHTS.md+++ b/unrealinsights/agent-harness/UNREALINSIGHTS.md@@ -27,6 +27,11 @@ The command may be:- a direct exporter command such as `TimingInsights.ExportThreads`- `@=<response-file>` for batch execution+Simple exporter filters are emitted without inner quotes, for example+`-threads=GameThread`, `-timers=*`, and `-counter=*`. This keeps Unreal's+`FParse::Token` from treating backslash-escaped quotes as literal filter text+inside `-ExecOnAnalysisCompleteCmd`.+This harness can also ensure an engine-matched analysis backend for customsource engines by locating or building `Engine/Binaries/Win64/UnrealInsights.exe`.@@ -43,7 +48,9 @@ This harness supports two v1 launch shapes:- explicit target executable path- `--project + --engine-root` convenience mode, which resolves `UnrealEditor.exe`-This harness only supports file-mode capture orchestration in v1.+This harness supports file-mode capture orchestration plus v1 helper surfaces+for Trace Store discovery, GUI co-pilot launch, pluggable live command delivery,+and basic timing/counter summaries.## CLI Coverage Map@@ -61,12 +68,23 @@ This harness only supports file-mode capture orchestration in v1.| Export counter list | `export counters` | v1 || Export counter values | `export counter-values` | v1 || Batch response file | `batch run-rsp` | v1 |-| Control live instances | — | future |-| Trace store browsing | — | future |+| Trace Store browsing | `store info/list/latest` | v1 |+| List live UE processes | `live processes` | v1 |+| Send live console command | `live exec` | v1 backend boundary |+| Common trace control commands | `live trace-status/bookmark/screenshot/snapshot/stop-trace` | v1 backend boundary |+| Keep Unreal Insights GUI running | `gui status/open/open-latest` | v1 |+| Timing/counter summary | `analyze summary` | v1 |+| Export result classification | `output_status` / `export_status` JSON fields | v1 |## Current Limitations- Windows-first discovery only-- No SessionServices control of already-running UE instances-- No trace store session enumeration+- Live command delivery requires an external SessionServices/ushell-style backend+ configured through `UNREALINSIGHTS_LIVE_EXEC` or `--backend-command`- Capture orchestration assumes the target executable accepts standard UE trace flags+- `capture stop` still stops the harness-launched process tree; use+ `live stop-trace` when the intent is to stop trace collection without killing UE+- Empty exporter output is classified as `no_output`; agents should treat that+ as a trace/filter data boundary unless UnrealInsights logs explicit errors+- Deep Memory, Networking, Slate, Asset Loading, and Cooking analysis are reported+ as uncovered domains by `analyze summary`diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/README.md b/unrealinsights/agent-harness/cli_anything/unrealinsights/README.mdindex 1539ba0e9..94b0ab272 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/README.md+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/README.md@@ -16,8 +16,9 @@ pip install -e .## Prerequisites-- Windows-- Unreal Engine 5.5+ installed with `UnrealInsights.exe`+- Windows with Unreal Engine tools installed+- verified with UE 5.5; the headless timing exporters include legacy handling for+ UE 5.3-style command parsing where possible- optional `UnrealTraceServer.exe` for backend reportingYou can point the harness at explicit binaries:@@ -36,6 +37,10 @@ If those are not set, the harness auto-discovers common UE installs under# Inspect resolved backend binariescli-anything-unrealinsights --json backend info+# Inspect the local Trace Store and select the latest trace+cli-anything-unrealinsights --json store info+cli-anything-unrealinsights --json store latest --set-current+# Find or build UnrealInsights.exe for a custom engine rootcli-anything-unrealinsights --json backend ensure-insights `--engine-root 'D:\code\D5\d5render-ue5_3'@@ -64,16 +69,27 @@ cli-anything-unrealinsights --json capture snapshot D:\captures\live_snapshot.ut# Stop the tracked capture sessioncli-anything-unrealinsights --json capture stop+# List live UE processes and query live trace status through a configured backend+$env:UNREALINSIGHTS_LIVE_EXEC='ushell-wrapper --pid {pid} --cmd "{cmd}"'+cli-anything-unrealinsights --json live processes+cli-anything-unrealinsights --json live trace-status --pid 1234++# Open Unreal Insights GUI and keep it running+cli-anything-unrealinsights --json gui open-latest+# Export threadscli-anything-unrealinsights --json -t D:\captures\session.utrace export threads D:\out\threads.csv# Export timer statistics for a regioncli-anything-unrealinsights --json -t D:\captures\session.utrace export timer-stats `- D:\out\timer_stats.csv --threads "GameThread" --timers "*" --region "EXPORT_CAPTURE"+ D:\out\timer_stats.csv --threads=GameThread --timers=* --region=EXPORT_CAPTURE# Execute a response filecli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D:\out\export.rsp+# Export and summarize timing/counter hotspots+cli-anything-unrealinsights --json -t D:\captures\session.utrace analyze summary --out D:\out\summary+# Launch a traced UE target and wait for completioncli-anything-unrealinsights --json capture run `--project 'D:\Projects\MyGame\MyGame.uproject' `@@ -95,12 +111,28 @@ cli-anything-unrealinsights- `trace`- `set`- `info`+- `store`+ - `info`+ - `list`+ - `latest`- `capture`- `run`- `start`- `status`- `stop`- `snapshot`+- `live`+ - `processes`+ - `exec`+ - `trace-status`+ - `bookmark`+ - `screenshot`+ - `snapshot`+ - `stop-trace`+- `gui`+ - `status`+ - `open`+ - `open-latest`- `export`- `threads`- `timers`@@ -111,6 +143,8 @@ cli-anything-unrealinsights- `counter-values`- `batch`- `run-rsp`+- `analyze`+ - `summary`- `repl`## Global Options@@ -177,6 +211,67 @@ Behavior:- `capture status` reads the persisted session state and reports whether the process is still running and how large the trace has grown- `capture snapshot` creates a best-effort copy of the current `.utrace` without requiring you to end the session first- `capture stop` performs a best-effort stop of the tracked process tree launched by the harness+- `live stop-trace` is the non-killing trace-control path for already-running UE processes when a live backend is configured++## Trace Store, Live, and GUI Workflows++Trace Store helpers:++```powershell+cli-anything-unrealinsights --json store info+cli-anything-unrealinsights --json store list --live-only+cli-anything-unrealinsights --json store latest --set-current+```++Live process helpers:++```powershell+$env:UNREALINSIGHTS_LIVE_EXEC='ushell-wrapper --pid {pid} --cmd "{cmd}"'+cli-anything-unrealinsights --json live processes+cli-anything-unrealinsights --json live bookmark --pid 1234 "BeforeExport"+cli-anything-unrealinsights --json live snapshot --pid 1234 D:\captures\snapshot.utrace+cli-anything-unrealinsights --json live stop-trace --pid 1234+```++`UNREALINSIGHTS_LIVE_EXEC` is a pluggable command template. It must accept+`{pid}` and `{cmd}` placeholders and should route the command to UE through a+SessionServices/ushell-style backend. If it is not configured, live command+commands fail loudly with a JSON error instead of pretending to control UE.++GUI helpers:++```powershell+cli-anything-unrealinsights --json gui status+cli-anything-unrealinsights --json gui open --trace D:\captures\session.utrace+cli-anything-unrealinsights --json gui open-latest+```++These commands intentionally omit `-NoUI` and `-AutoQuit`, so the Unreal Insights+GUI remains available for human + AI co-analysis.++## Analyze Summary++```powershell+cli-anything-unrealinsights --json -t D:\captures\session.utrace analyze summary --out D:\out\summary+```++`analyze summary` runs the standard timing/counter exporter bundle, then parses+the generated CSV files for top timers, GameThread/RenderThread/RHIThread+hotspots, wait/task-related timers, and counter peaks. For offline parsing of+existing CSV files:++```powershell+cli-anything-unrealinsights --json analyze summary --skip-export --out D:\out\summary+```++Deep Memory, Networking, Slate, Asset Loading, and Cooking analysis are reported+as uncovered domains in the summary until dedicated parsers are added.++The JSON response includes `export_status` and+`summary.diagnostics.export_status_counts`. This makes exporter behavior+machine-readable: `ok` means files were produced, while `no_output` means+Unreal Insights completed successfully but the trace/filter combination did not+materialize data for that exporter.## Human + AI Workflow@@ -242,6 +337,28 @@ Useful phrases in prompts:- `--end-time`- `--region`+For wildcard filters in scripts and tests, prefer the equals form+`--threads=GameThread --timers=* --counter=*`. The harness emits simple+UnrealInsights filter values without inner quotes so `FParse::Token` receives+the wildcard instead of a literal escape character.++## Export Status++Exporter and batch JSON responses include:++- `output_status`+- `status_message`+- `output_files`+- `warnings`+- `errors`+- `succeeded`++`succeeded` is true only when `output_status` is `ok` and at least one expected+file was materialized. `no_output` is a data boundary, not a process crash; it+usually means the trace lacks that event/counter stream or the selected filters+matched nothing. `exporter_error`, `process_failed`, and `timed_out` classify+hard failures for agent retry/debug decisions.+## Testing```bash@@ -254,3 +371,12 @@ Optional environment variables for E2E coverage:- `UNREALINSIGHTS_TEST_TRACE`- `UNREALINSIGHTS_TEST_TARGET_EXE`++If `UNREALINSIGHTS_TEST_TRACE` is not set, the E2E suite tries to discover the+UE sample trace at:++```text+<drive>:\Program Files\Epic Games\UE_*\Engine\Source\Programs\Shared\EpicGames.Tracing.Tests\UnrealInsights\example_trace.decomp.utrace+```++That sample trace is not vendored into this repository.diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/analyze.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/analyze.pynew file mode 100644index 000000000..39f6bca99--- /dev/null+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/analyze.py@@ -0,0 +1,299 @@+"""+Analysis helpers for exported Unreal Insights CSV files.+"""++from __future__ import annotations++import csv+import re+from collections import defaultdict+from pathlib import Path+from typing import Iterable++from cli_anything.unrealinsights.core.export import execute_export++SUMMARY_EXPORTS = [+ ("threads", "threads.csv", {}),+ ("timers", "timers.csv", {}),+ ("timer-stats", "timer_stats.csv", {"threads": "*", "timers": "*"}),+ ("counters", "counters.csv", {}),+ ("counter-values", "counter_values.csv", {"counter": "*"}),+]++DEFAULT_FOCUS_THREADS = ("GameThread", "RenderThread", "RHIThread")+WAIT_TOKENS = ("wait", "stall", "sleep", "task", "fence", "block")+UNCOVERED_DOMAINS = [+ "Memory Insights allocation queries",+ "Networking packet/RPC breakdown",+ "Slate widget tree analysis",+ "Asset Loading deep analysis",+ "Cooking Insights analysis",+]+++def _normalize_header(value: str) -> str:+ return re.sub(r"[^a-z0-9]", "", value.lower())+++def _read_csv_rows(path: Path) -> list[dict[str, str]]:+ if not path.is_file():+ return []+ with path.open("r", encoding="utf-8-sig", errors="replace", newline="") as handle:+ reader = csv.DictReader(handle)+ return [dict(row) for row in reader]+++def _field(row: dict[str, str], candidates: Iterable[str]) -> str | None:+ normalized = {_normalize_header(key): key for key in row.keys()}+ for candidate in candidates:+ key = normalized.get(_normalize_header(candidate))+ if key is not None:+ return row.get(key)+ for norm_key, original in normalized.items():+ if any(_normalize_header(candidate) in norm_key for candidate in candidates):+ return row.get(original)+ return None+++def _number(value: str | None) -> float | None:+ if value is None:+ return None+ text = value.strip().replace(",", "")+ if not text:+ return None+ match = re.search(r"-?\d+(?:\.\d+)?", text)+ if not match:+ return None+ try:+ return float(match.group(0))+ except ValueError:+ return None+++def _timer_entry(row: dict[str, str]) -> dict[str, object]:+ name = _field(row, ("Timer Name", "TimerName", "Name", "Timer", "EventName")) or "unknown"+ thread = _field(row, ("Thread", "Thread Name", "ThreadName", "ThreadId"))+ count = _number(_field(row, ("Count", "Num Calls", "Calls", "Instance Count")))+ inclusive = _number(_field(row, ("Inclusive Time", "InclusiveTime", "Incl Time", "Total Incl Time")))+ exclusive = _number(_field(row, ("Exclusive Time", "ExclusiveTime", "Excl Time", "Total Excl Time")))+ total = _number(_field(row, ("Total Time", "TotalTime", "Duration", "Time", "Sum")))+ score = total if total is not None else inclusive if inclusive is not None else exclusive if exclusive is not None else count or 0.0+ return {+ "name": name,+ "thread": thread,+ "count": count,+ "total_time": total,+ "inclusive_time": inclusive,+ "exclusive_time": exclusive,+ "score": score,+ }+++def _top_entries(entries: list[dict[str, object]], limit: int) -> list[dict[str, object]]:+ return sorted(entries, key=lambda item: float(item.get("score") or 0.0), reverse=True)[:limit]+++def _counter_summaries(rows: list[dict[str, str]], limit: int) -> list[dict[str, object]]:+ grouped: dict[str, list[float]] = defaultdict(list)+ for row in rows:+ name = _field(row, ("Counter", "Counter Name", "CounterName", "Name")) or "unknown"+ value = _number(_field(row, ("Value", "Counter Value", "CounterValue")))+ if value is not None:+ grouped[name].append(value)++ summaries = []+ for name, values in grouped.items():+ summaries.append(+ {+ "name": name,+ "samples": len(values),+ "min": min(values),+ "max": max(values),+ "last": values[-1],+ "score": max(values),+ }+ )+ return _top_entries(summaries, limit)+++def _diagnostics(+ top_timers: list[dict[str, object]],+ focus: dict[str, list[dict[str, object]]],+ wait_timers: list[dict[str, object]],+ counter_peaks: list[dict[str, object]],+ export_status: list[dict[str, object]],+) -> dict[str, object]:+ active_threads = [thread for thread, entries in focus.items() if entries]+ counter_anomalies = [+ counter+ for counter in counter_peaks+ if counter.get("samples", 0) > 1 and counter.get("min") != counter.get("max")+ ]+ next_steps = []+ if top_timers:+ next_steps.append(f"Inspect the top timer `{top_timers[0]['name']}` first.")+ if wait_timers:+ next_steps.append("Review wait/task timers for synchronization or scheduling stalls.")+ if counter_anomalies:+ next_steps.append("Check counter peaks for transient spikes during the selected interval.")+ if not top_timers:+ next_steps.append("Run exporter validation or provide a trace with timing data.")+ blocked_exports = [+ item+ for item in export_status+ if item.get("status") not in (None, "ok")+ ]+ if blocked_exports:+ next_steps.append("Inspect export_status for exporters that produced no output or errors.")++ return {+ "primary_hotspot": top_timers[0] if top_timers else None,+ "active_focus_threads": active_threads,+ "wait_pressure": "present" if wait_timers else "none",+ "counter_anomaly_count": len(counter_anomalies),+ "counter_anomalies": counter_anomalies,+ "export_status_counts": _status_counts(export_status),+ "next_steps": next_steps,+ }+++def _status_counts(export_status: list[dict[str, object]]) -> dict[str, int]:+ counts: dict[str, int] = defaultdict(int)+ for item in export_status:+ counts[str(item.get("status") or "unknown")] += 1+ return dict(counts)+++def _export_statuses(export_results: list[dict[str, object]] | None) -> list[dict[str, object]]:+ statuses = []+ for result in export_results or []:+ statuses.append(+ {+ "exporter": result.get("exporter") or "unknown",+ "status": result.get("output_status") or ("ok" if result.get("succeeded") else "unknown"),+ "succeeded": bool(result.get("succeeded")),+ "output_files": list(result.get("output_files") or []),+ "status_message": result.get("status_message"),+ "log_path": result.get("log_path"),+ }+ )+ return statuses+++def summarize_exports(+ out_dir: str,+ *,+ trace_path: str | None = None,+ export_results: list[dict[str, object]] | None = None,+ limit: int = 20,+ focus_threads: Iterable[str] = DEFAULT_FOCUS_THREADS,+) -> dict[str, object]:+ """Summarize exported Unreal Insights CSV files."""+ root = Path(out_dir).expanduser().resolve()+ timer_rows = _read_csv_rows(root / "timer_stats.csv") or _read_csv_rows(root / "timers.csv")+ counter_rows = _read_csv_rows(root / "counter_values.csv")+ timer_entries = [_timer_entry(row) for row in timer_rows]++ focus = {}+ for thread in focus_threads:+ token = thread.lower()+ focus[thread] = _top_entries(+ [+ entry+ for entry in timer_entries+ if token in str(entry.get("thread") or "").lower() or token in str(entry.get("name") or "").lower()+ ],+ limit,+ )++ wait_entries = [+ entry+ for entry in timer_entries+ if any(token in str(entry.get("name") or "").lower() for token in WAIT_TOKENS)+ ]++ warnings = []+ if not timer_entries:+ warnings.append("No timer statistics CSV was found or parsed.")+ if not counter_rows:+ warnings.append("No counter values CSV was found or parsed.")++ top_timers = _top_entries(timer_entries, limit)+ wait_timers = _top_entries(wait_entries, limit)+ counter_peaks = _counter_summaries(counter_rows, limit)+ export_status = _export_statuses(export_results)++ return {+ "trace_path": str(Path(trace_path).expanduser().resolve()) if trace_path else None,+ "out_dir": str(root),+ "exports": export_results or [],+ "export_status": export_status,+ "summary": {+ "top_timers": top_timers,+ "focus_threads": focus,+ "wait_timers": wait_timers,+ "counter_peaks": counter_peaks,+ "diagnostics": _diagnostics(top_timers, focus, wait_timers, counter_peaks, export_status),+ "uncovered_domains": UNCOVERED_DOMAINS,+ },+ "warnings": warnings,+ "succeeded": bool(timer_entries or counter_rows),+ }+++def run_summary_exports(+ insights_exe: str,+ trace_path: str,+ out_dir: str,+ *,+ insights_version: str | None = None,+) -> list[dict[str, object]]:+ """Run the standard exporter bundle used by analyze summary."""+ root = Path(out_dir).expanduser().resolve()+ root.mkdir(parents=True, exist_ok=True)+ results = []+ for exporter, filename, options in SUMMARY_EXPORTS:+ result = execute_export(+ insights_exe,+ trace_path,+ exporter,+ str(root / filename),+ insights_version=insights_version,+ **options,+ )+ results.append(result)+ return results+++def analyze_summary(+ insights_exe: str | None,+ trace_path: str | None,+ out_dir: str,+ *,+ insights_version: str | None = None,+ skip_export: bool = False,+ limit: int = 20,+) -> dict[str, object]:+ """Run exports when requested, then summarize the export directory."""+ export_results: list[dict[str, object]] = []+ if not skip_export:+ if not insights_exe:+ raise RuntimeError("UnrealInsights.exe is required unless --skip-export is used.")+ if not trace_path:+ raise RuntimeError("A trace path is required unless --skip-export is used.")+ export_results = run_summary_exports(+ insights_exe,+ trace_path,+ out_dir,+ insights_version=insights_version,+ )++ summary = summarize_exports(+ out_dir,+ trace_path=trace_path,+ export_results=export_results,+ limit=limit,+ )+ if export_results:+ summary["succeeded"] = any(result.get("succeeded") for result in export_results) and summary["succeeded"]+ return summarydiff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/export.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/export.pyindex 92fd5979a..13431c51f 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/export.py+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/export.py@@ -87,6 +87,12 @@ def _filename_arg(output_path: str, insights_version: str | None = None) -> str:return _modern_filename_arg(output_abs)+def _option_value_arg(name: str, value: str) -> str:+ if not any(ch.isspace() for ch in value):+ return f"-{name}={value}"+ return f"-{name}={_quote(value)}"++def build_export_exec_command(exporter: str,output_path: str,@@ -110,19 +116,19 @@ def build_export_exec_command(parts = [EXPORTER_COMMANDS[exporter], filename_token]if counter:- parts.append(f"-counter={_quote(counter)}")+ parts.append(_option_value_arg("counter", counter))if columns:- parts.append(f"-columns={_quote(columns)}")+ parts.append(_option_value_arg("columns", columns))if threads:- parts.append(f"-threads={_quote(threads)}")+ parts.append(_option_value_arg("threads", threads))if timers:- parts.append(f"-timers={_quote(timers)}")+ parts.append(_option_value_arg("timers", timers))if start_time is not None:parts.append(f"-startTime={start_time}")if end_time is not None:parts.append(f"-endTime={end_time}")if region:- parts.append(f"-region={_quote(region)}")+ parts.append(_option_value_arg("region", region))return " ".join(parts)@@ -193,6 +199,52 @@ def expected_outputs_from_rsp(rsp_path: str) -> list[str]:return outputs+def normalize_response_file_lines(lines: list[str], *, insights_version: str | None = None) -> list[str]:+ """Normalize response-file output filename tokens for UnrealInsights parsing."""+ normalized_lines = []+ for line in lines:+ stripped = line.strip()+ if not stripped or stripped.startswith("#"):+ normalized_lines.append(line)+ continue+ try:+ tokens = shlex.split(stripped, posix=False)+ except ValueError:+ normalized_lines.append(line)+ continue+ if len(tokens) < 2:+ normalized_lines.append(line)+ continue+ output_path = tokens[1].strip('"')+ filename_token = _filename_arg(output_path, insights_version=insights_version)+ normalized_lines.append(" ".join([tokens[0], filename_token, *tokens[2:]]))+ return normalized_lines+++def normalized_response_file_path(rsp_path: str, *, insights_version: str | None = None) -> str:+ """Return a normalized temporary response file path when normalization changes content."""+ path = Path(rsp_path).expanduser().resolve()+ if not path.is_file():+ return str(path)+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()+ normalized_lines = normalize_response_file_lines(lines, insights_version=insights_version)+ if normalized_lines == lines:+ return str(path)++ handle = tempfile.NamedTemporaryFile(+ "w",+ encoding="utf-8",+ errors="replace",+ suffix=".rsp",+ prefix=f"{path.stem}-normalized-",+ delete=False,+ )+ with handle:+ handle.write("\n".join(normalized_lines))+ handle.write("\n")+ return str(Path(handle.name).resolve())++def default_log_path(reference_path: str, suffix: str = ".insights.log") -> str:path = Path(reference_path).expanduser().resolve()return str(path.with_name(f"{path.stem}{suffix}"))@@ -225,6 +277,8 @@ def _execute_insights(actual_outputs.append(match)seen.add(match)+ output_status, status_message = classify_export_result(run_result, log_info, actual_outputs, expected_outputs)+run_result.update({"trace_path": str(Path(trace_path).expanduser().resolve()),@@ -234,16 +288,39 @@ def _execute_insights("log_path": log_info["path"],"warnings": log_info["warnings"],"errors": log_info["errors"],- "succeeded": (- not run_result["timed_out"]- and run_result["exit_code"] == 0- and len(actual_outputs) > 0- ),+ "output_status": output_status,+ "status_message": status_message,+ "succeeded": output_status == "ok",})return run_result+def classify_export_result(+ run_result: dict[str, object],+ log_info: dict[str, object],+ actual_outputs: list[str],+ expected_outputs: list[str],+) -> tuple[str, str]:+ """Classify an Unreal Insights exporter result for agent diagnostics."""+ if run_result.get("timed_out"):+ return "timed_out", "UnrealInsights.exe timed out before export completion."+ if run_result.get("exit_code") != 0:+ return "process_failed", f"UnrealInsights.exe exited with code {run_result.get('exit_code')}."+ if actual_outputs:+ return "ok", f"Materialized {len(actual_outputs)} output file(s)."++ errors = list(log_info.get("errors") or [])+ if errors:+ return "exporter_error", errors[-1]+ if expected_outputs:+ return (+ "no_output",+ "Exporter completed without materializing expected outputs; the trace may not contain matching data.",+ )+ return "no_expected_outputs", "No output paths were inferred for this export command."++def execute_export(insights_exe: str,trace_path: str,@@ -275,13 +352,15 @@ def execute_export(region=region,counter=counter,)- return _execute_insights(+ result = _execute_insights(insights_exe,trace_path,exec_command=exec_command,expected_outputs=[output_abs],log_path=resolved_log_path,)+ result["exporter"] = exporter+ return resultdef execute_response_file(@@ -313,7 +392,7 @@ def execute_response_file(with tempfile.NamedTemporaryFile("w", suffix=".rsp", delete=False, encoding="utf-8", newline="\n") as handle:temp_rsp_path = handle.namehandle.write("\n".join(normalized_lines))- return _execute_insights(+ result = _execute_insights(insights_exe,trace_path,exec_command=build_rsp_exec_command(temp_rsp_path),@@ -326,3 +405,7 @@ def execute_response_file(Path(temp_rsp_path).unlink()except OSError:pass+ result["response_file"] = rsp_abs+ result["executed_response_file"] = str(Path(temp_rsp_path).resolve()) if temp_rsp_path else rsp_abs+ result["exporter"] = "response-file"+ return resultdiff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/gui.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/gui.pynew file mode 100644index 000000000..59981cc32--- /dev/null+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/gui.py@@ -0,0 +1,49 @@+"""+Unreal Insights GUI process helpers.+"""++from __future__ import annotations++from pathlib import Path++from cli_anything.unrealinsights.core.live import list_unreal_processes+from cli_anything.unrealinsights.utils import unrealinsights_backend as backend+++def build_gui_command(insights_exe: str, trace_path: str | None = None, *, log: bool = True) -> list[str]:+ """Build a GUI UnrealInsights command line without headless flags."""+ command = [str(Path(insights_exe).expanduser().resolve())]+ if trace_path:+ command.append(f"-OpenTraceFile={Path(trace_path).expanduser().resolve()}")+ if log:+ command.append("-log")+ return command+++def open_gui(insights_exe: str, trace_path: str | None = None) -> dict[str, object]:+ """Open Unreal Insights GUI and keep it running."""+ command = build_gui_command(insights_exe, trace_path)+ result = backend.run_process(command, wait=False)+ result.update(+ {+ "insights_exe": str(Path(insights_exe).expanduser().resolve()),+ "trace_path": str(Path(trace_path).expanduser().resolve()) if trace_path else None,+ "mode": "gui",+ "kept_running": True,+ }+ )+ return result+++def gui_status() -> dict[str, object]:+ """Return currently running Unreal Insights GUI processes."""+ processes = [+ process+ for process in list_unreal_processes(include_tools=True)["processes"]+ if process.get("role") == "insights"+ ]+ return {+ "running": bool(processes),+ "process_count": len(processes),+ "processes": processes,+ }diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/live.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/live.pynew file mode 100644index 000000000..3f97d4964--- /dev/null+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/live.py@@ -0,0 +1,194 @@+"""+Live Unreal process discovery and trace-control command helpers.+"""++from __future__ import annotations++import json+import os+import shlex+import subprocess+from pathlib import Path++from cli_anything.unrealinsights.utils import unrealinsights_backend as backend++LIVE_BACKEND_ENV = "UNREALINSIGHTS_LIVE_EXEC"+++def _process_role(name: str, path: str | None, command_line: str | None) -> str:+ lower_name = name.lower()+ lower_text = " ".join(part for part in (path or "", command_line or "") if part).lower()+ if lower_name in {"powershell.exe", "pwsh.exe", "cmd.exe", "dotnet.exe", "python.exe"}:+ return "helper"+ if lower_name == "unrealinsights.exe":+ return "insights"+ if lower_name == "unrealtraceserver.exe":+ return "trace-server"+ if "unrealeditor" in lower_name or "unrealeditor" in lower_text:+ return "editor"+ if "unrealgame" in lower_name or "-win64-" in lower_name or ".uproject" in lower_text:+ return "game"+ return "unknown"+++def _normalize_process(item: dict[str, object]) -> dict[str, object]:+ name = str(item.get("Name") or item.get("name") or "")+ pid = item.get("ProcessId") or item.get("pid")+ path = item.get("ExecutablePath") or item.get("path")+ command_line = item.get("CommandLine") or item.get("command_line")+ return {+ "pid": int(pid) if pid is not None else None,+ "name": name,+ "path": str(path) if path else None,+ "command_line": str(command_line) if command_line else None,+ "started_at": item.get("CreationDate") or item.get("started_at"),+ "role": _process_role(name, str(path) if path else None, str(command_line) if command_line else None),+ }+++def _list_windows_unreal_processes() -> list[dict[str, object]]:+ script = (+ "Get-CimInstance Win32_Process | "+ "Where-Object { $_.Name -like '*Unreal*' -or $_.CommandLine -like '*.uproject*' } | "+ "Select-Object Name,ProcessId,ExecutablePath,CommandLine,CreationDate | "+ "ConvertTo-Json -Compress"+ )+ result = subprocess.run(+ ["powershell", "-NoProfile", "-Command", script],+ capture_output=True,+ text=True,+ timeout=15,+ check=False,+ )+ text = result.stdout.strip()+ if result.returncode != 0 or not text:+ return []+ data = json.loads(text)+ if isinstance(data, dict):+ data = [data]+ return [_normalize_process(item) for item in data]+++def _list_posix_unreal_processes() -> list[dict[str, object]]:+ result = subprocess.run(+ ["ps", "-eo", "pid=,comm=,args="],+ capture_output=True,+ text=True,+ timeout=15,+ check=False,+ )+ processes = []+ for line in result.stdout.splitlines():+ stripped = line.strip()+ if not stripped:+ continue+ parts = stripped.split(None, 2)+ if len(parts) < 2:+ continue+ pid, name = parts[0], parts[1]+ command_line = parts[2] if len(parts) > 2 else ""+ if "Unreal" not in name and "Unreal" not in command_line and ".uproject" not in command_line:+ continue+ processes.append(+ _normalize_process(+ {+ "pid": pid,+ "name": Path(name).name,+ "path": name,+ "command_line": command_line,+ }+ )+ )+ return processes+++def list_unreal_processes(*, include_tools: bool = True) -> dict[str, object]:+ """List local Unreal-related processes."""+ processes = _list_windows_unreal_processes() if os.name == "nt" else _list_posix_unreal_processes()+ processes = [process for process in processes if process["role"] not in ("helper", "unknown")]+ if not include_tools:+ processes = [process for process in processes if process["role"] not in ("insights", "trace-server")]+ processes.sort(key=lambda process: (str(process.get("role")), int(process.get("pid") or 0)))+ return {+ "process_count": len(processes),+ "include_tools": include_tools,+ "processes": processes,+ }+++def _render_backend_command(template: str, pid: int, command: str) -> list[str]:+ rendered = template.format(pid=pid, cmd=command, command=command)+ return shlex.split(rendered, posix=os.name != "nt")+++def execute_live_command(+ pid: int,+ command: str,+ *,+ backend_command: str | None = None,+ timeout: float | None = None,+) -> dict[str, object]:+ """Send a console command to a live UE process through a configured backend."""+ template = backend_command or os.environ.get(LIVE_BACKEND_ENV, "").strip()+ if not template:+ raise RuntimeError(+ "Live control backend unavailable. Configure UNREALINSIGHTS_LIVE_EXEC "+ "with a command template that accepts {pid} and {cmd}, for example a "+ "SessionServices/ushell wrapper."+ )++ argv = _render_backend_command(template, pid, command)+ result = backend.run_process(argv, timeout=timeout, wait=True)+ result.update(+ {+ "pid": pid,+ "live_command": command,+ "backend": "external-template",+ "backend_template": template,+ "succeeded": (not result["timed_out"] and result["exit_code"] == 0),+ }+ )+ return result+++def trace_status(pid: int, *, backend_command: str | None = None, timeout: float | None = None) -> dict[str, object]:+ return execute_live_command(pid, "Trace.Status", backend_command=backend_command, timeout=timeout)+++def trace_bookmark(+ pid: int,+ name: str,+ *,+ backend_command: str | None = None,+ timeout: float | None = None,+) -> dict[str, object]:+ return execute_live_command(pid, f"Trace.Bookmark {name}", backend_command=backend_command, timeout=timeout)+++def trace_screenshot(+ pid: int,+ name: str,+ *,+ backend_command: str | None = None,+ timeout: float | None = None,+) -> dict[str, object]:+ return execute_live_command(pid, f"Trace.Screenshot {name}", backend_command=backend_command, timeout=timeout)+++def trace_snapshot(+ pid: int,+ output_path: str,+ *,+ backend_command: str | None = None,+ timeout: float | None = None,+) -> dict[str, object]:+ return execute_live_command(+ pid,+ f"Trace.SnapshotFile {Path(output_path).expanduser().resolve()}",+ backend_command=backend_command,+ timeout=timeout,+ )+++def trace_stop(pid: int, *, backend_command: str | None = None, timeout: float | None = None) -> dict[str, object]:+ return execute_live_command(pid, "Trace.Stop", backend_command=backend_command, timeout=timeout)diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/core/store.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/store.pynew file mode 100644index 000000000..a4d0c7772--- /dev/null+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/core/store.py@@ -0,0 +1,144 @@+"""+Trace Store discovery helpers.+"""++from __future__ import annotations++import os+from datetime import datetime, timezone+from pathlib import Path++from cli_anything.unrealinsights.utils import unrealinsights_backend as backend++TRACE_FILE_SUFFIXES = (".utrace", ".ucache")+DEFAULT_LIVE_WINDOW_SECONDS = 60.0+++def default_trace_root() -> Path:+ """Return the default Unreal Trace root for the current user."""+ override = os.environ.get("UNREAL_TRACE_ROOT", "").strip()+ if override:+ return Path(override).expanduser().resolve()++ local_app_data = os.environ.get("LOCALAPPDATA", "").strip()+ if local_app_data:+ return Path(local_app_data).expanduser().resolve() / "UnrealEngine" / "Common" / "UnrealTrace"++ return Path.home() / "AppData" / "Local" / "UnrealEngine" / "Common" / "UnrealTrace"+++def resolve_store_dir(store_dir: str | None = None) -> Path:+ """Resolve the Unreal Trace Store directory."""+ env_store = (+ os.environ.get("UNREALINSIGHTS_TRACE_STORE_DIR", "").strip()+ or os.environ.get("UNREAL_TRACE_STORE_DIR", "").strip()+ )+ if store_dir:+ return Path(store_dir).expanduser().resolve()+ if env_store:+ return Path(env_store).expanduser().resolve()+ return default_trace_root() / "Store"+++def _iso_from_mtime(mtime: float) -> str:+ return datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat()+++def _trace_file_info(path: Path, now: float, live_window_seconds: float) -> dict[str, object]:+ stat = path.stat()+ age = max(0.0, now - stat.st_mtime)+ return {+ "path": str(path.resolve()),+ "name": path.name,+ "extension": path.suffix.lower(),+ "file_size": stat.st_size,+ "modified_at": _iso_from_mtime(stat.st_mtime),+ "age_seconds": age,+ "is_live_candidate": age <= live_window_seconds,+ }+++def list_trace_files(+ store_dir: str | None = None,+ *,+ live_only: bool = False,+ include_cache: bool = True,+ live_window_seconds: float = DEFAULT_LIVE_WINDOW_SECONDS,+) -> dict[str, object]:+ """List trace files from the local Trace Store."""+ root = resolve_store_dir(store_dir)+ suffixes = set(TRACE_FILE_SUFFIXES if include_cache else (".utrace",))+ traces: list[dict[str, object]] = []+ now = datetime.now(timezone.utc).timestamp()++ if root.is_dir():+ for path in root.rglob("*"):+ if not path.is_file() or path.suffix.lower() not in suffixes:+ continue+ info = _trace_file_info(path, now=now, live_window_seconds=live_window_seconds)+ if live_only and not info["is_live_candidate"]:+ continue+ traces.append(info)++ traces.sort(key=lambda item: (item.get("modified_at") or "", item.get("path") or ""), reverse=True)+ return {+ "store_dir": str(root),+ "exists": root.is_dir(),+ "include_cache": include_cache,+ "live_only": live_only,+ "live_window_seconds": live_window_seconds,+ "trace_count": len(traces),+ "traces": traces,+ }+++def latest_trace_file(+ store_dir: str | None = None,+ *,+ live_only: bool = False,+ include_cache: bool = True,+ live_window_seconds: float = DEFAULT_LIVE_WINDOW_SECONDS,+) -> dict[str, object]:+ """Return the newest trace file from the Trace Store."""+ listing = list_trace_files(+ store_dir,+ live_only=live_only,+ include_cache=include_cache,+ live_window_seconds=live_window_seconds,+ )+ latest = listing["traces"][0] if listing["traces"] else None+ return {+ **listing,+ "latest": latest,+ }+++def trace_store_info(store_dir: str | None = None, trace_server_exe: str | None = None) -> dict[str, object]:+ """Return local Trace Store and Trace Server status."""+ root = default_trace_root()+ resolved_store = resolve_store_dir(store_dir)+ trace_server = backend.resolve_trace_server_exe(trace_server_exe, required=False)+ listing = list_trace_files(str(resolved_store))++ logs = []+ if root.is_dir():+ for log_path in sorted(root.glob("Server_*.log"), key=lambda path: path.stat().st_mtime, reverse=True):+ stat = log_path.stat()+ logs.append(+ {+ "path": str(log_path.resolve()),+ "file_size": stat.st_size,+ "modified_at": _iso_from_mtime(stat.st_mtime),+ }+ )++ return {+ "trace_root": str(root),+ "trace_root_exists": root.is_dir(),+ "store_dir": str(resolved_store),+ "store_exists": resolved_store.is_dir(),+ "trace_file_count": listing["trace_count"],+ "trace_server": trace_server,+ "watch_folders": [str(resolved_store)],+ "server_logs": logs[:10],+ }diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/skills/SKILL.md b/unrealinsights/agent-harness/cli_anything/unrealinsights/skills/SKILL.mdindex 5986f7444..8f06b682e 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/skills/SKILL.md+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/skills/SKILL.md@@ -1,6 +1,6 @@---name: "cli-anything-unrealinsights"-description: "Capture Unreal Engine traces to .utrace files and export Unreal Insights timing/counter data in headless mode."+description: "Capture Unreal Engine traces, inspect Trace Store files, keep Unreal Insights GUI open, and export/summarize timing/counter data."---# cli-anything-unrealinsights@@ -10,8 +10,10 @@ and exporter workflows on Windows.## Prerequisites-- Unreal Engine 5.5+ installed with `UnrealInsights.exe`- Windows+- Unreal Engine tools installed with `UnrealInsights.exe`+- Verified with UE 5.5; headless timing exporters include compatibility handling+ for UE 5.3-style command parsing where possible- Optional explicit env vars:- `UNREALINSIGHTS_EXE`- `UNREAL_TRACE_SERVER_EXE`@@ -42,6 +44,14 @@ cli-anything-unrealinsights trace set D:\captures\session.utracecli-anything-unrealinsights --json trace info```+### Trace Store discovery++```powershell+cli-anything-unrealinsights --json store info+cli-anything-unrealinsights --json store list --live-only+cli-anything-unrealinsights --json store latest --set-current+```+### Capture orchestration```powershell@@ -81,20 +91,64 @@ or snapshot later in a follow-up turn.If a tracked capture session is still running, `capture start` now requires`--replace` so the previous process is stopped before a new one is launched.+### Live trace control backend++```powershell+$env:UNREALINSIGHTS_LIVE_EXEC='ushell-wrapper --pid {pid} --cmd "{cmd}"'+cli-anything-unrealinsights --json live processes+cli-anything-unrealinsights --json live trace-status --pid 1234+cli-anything-unrealinsights --json live bookmark --pid 1234 "BeforeExport"+cli-anything-unrealinsights --json live stop-trace --pid 1234+```++Live command delivery requires `UNREALINSIGHTS_LIVE_EXEC` or `--backend-command`.+If no backend is configured, live commands return a JSON error and do not claim+success. `live stop-trace` stops trace collection without killing the UE process;+`capture stop` still terminates the harness-launched process tree.++### GUI co-pilot++```powershell+cli-anything-unrealinsights --json gui status+cli-anything-unrealinsights --json gui open --trace D:\captures\session.utrace+cli-anything-unrealinsights --json gui open-latest+```++GUI commands omit `-NoUI` and `-AutoQuit` so Unreal Insights remains open.+### Offline exporters```powershellcli-anything-unrealinsights --json -t D:\captures\session.utrace export threads D:\out\threads.csv-cli-anything-unrealinsights --json -t D:\captures\session.utrace export timer-stats D:\out\stats.csv --region "EXPORT_CAPTURE"-cli-anything-unrealinsights --json -t D:\captures\session.utrace export counter-values D:\out\counter_values.csv --counter "*"+cli-anything-unrealinsights --json -t D:\captures\session.utrace export timer-stats D:\out\stats.csv --region=EXPORT_CAPTURE+cli-anything-unrealinsights --json -t D:\captures\session.utrace export counter-values D:\out\counter_values.csv --counter=*```+Prefer equals-form wildcard filters such as `--timers=*` and `--counter=*`.+The harness passes simple values to UnrealInsights without inner quotes so+wildcards remain usable inside `-ExecOnAnalysisCompleteCmd`.+### Batch response files```powershellcli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D:\out\exports.rsp```+### Analyze summaries++```powershell+cli-anything-unrealinsights --json -t D:\captures\session.utrace analyze summary --out D:\out\summary+cli-anything-unrealinsights --json analyze summary --skip-export --out D:\out\summary+```++The summary reports top timers, focused GameThread/RenderThread/RHIThread+hotspots, wait/task-related timers, counter peaks, and uncovered domains for+future Memory/Network/Slate/Asset/Cooking analysis.++`analyze summary` also returns `export_status` and+`summary.diagnostics.export_status_counts` so agents can distinguish successful+exports from trace/filter combinations that completed but produced no rows.+## JSON Output Guidance- Prefer `--json` for agent workflows.@@ -102,6 +156,8 @@ cli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D- `trace_path`- `exec_command`- `output_files`+ - `output_status`+ - `status_message`- `log_path`- `exit_code`- `warnings`@@ -121,11 +177,38 @@ cli-anything-unrealinsights --json -t D:\captures\session.utrace batch run-rsp D- `trace_path`- `trace_size`- `started_at`+- Trace Store commands return:+ - `store_dir`+ - `trace_count`+ - `traces`+ - `latest`+- Live commands return:+ - `pid`+ - `live_command`+ - `backend`+ - `exit_code`+ - `succeeded`+- Analyze summary returns:+ - `exports`+ - `export_status`+ - `summary.top_timers`+ - `summary.focus_threads`+ - `summary.wait_timers`+ - `summary.counter_peaks`+ - `summary.diagnostics`+ - `summary.uncovered_domains`++Treat `output_status == "ok"` as a materialized export. Treat+`output_status == "no_output"` as an empty trace/filter result, not a backend+crash. Use `exporter_error`, `process_failed`, and `timed_out` for retry or+debugging decisions.## Notes- v1 is Windows-first.-- v1 supports file-mode capture orchestration only.-- v1 does not control already-running UE instances or browse trace stores.+- v1 includes Trace Store browsing, GUI open/status, pluggable live command delivery,+ and timing/counter summaries.- `capture stop` is a best-effort stop of the harness-launched process tree.- `capture snapshot` is a best-effort filesystem snapshot of the active trace.+- Regression tests auto-discover the UE `example_trace.decomp.utrace` sample+ when present; the binary trace is not vendored.diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/TEST.md b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/TEST.mdindex 6176cb854..e4e73c0cd 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/TEST.md+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/TEST.md@@ -2,173 +2,124 @@## Test Inventory Plan-- `test_core.py`: 49 unit tests planned-- `test_full_e2e.py`: 10 E2E tests planned+- `test_core.py`: 70 unit tests planned+- `test_full_e2e.py`: 15 E2E/smoke tests planned## Unit Test Plan### `utils/unrealinsights_backend.py`+- Validate binary discovery precedence: explicit path, env var, then Windows auto-discovery- Validate missing explicit and env paths fail loudly-- Validate Unreal Insights command construction+- Validate Unreal Insights headless command construction- Validate engine-root binary resolution and build orchestration-- Planned tests: 13### `core/capture.py`+- Validate output trace path normalization- Validate traced target command construction- Validate `-ExecCmds=` joining semantics- Validate `--project + --engine-root` convenience resolution- Validate tracked capture status, snapshot, and stop flows-- Planned tests: 12### `core/export.py`-- Validate exporter command strings for all supported exporters++- Validate exporter command strings for all supported Timing Insights exporters- Validate response-file parsing and output inference+- Validate UnrealInsights-safe filename normalization for direct and response-file exports- Validate placeholder-aware output collection- Validate legacy UnrealInsights 5.3 export command compatibility-- Planned tests: 9+- Validate exporter output classification for `ok`, `no_output`, and hard-error cases++### `core/store.py`++- Validate Trace Store directory resolution+- Validate `.utrace` and `.ucache` enumeration+- Validate latest-trace selection and live-candidate metadata+- Validate Trace Server/store info payloads++### `core/live.py`++- Validate Unreal-related process discovery and role classification+- Validate explicit failure when no live command backend is configured+- Validate configured backend command-template execution++### `core/gui.py`++- Validate GUI command lines omit `-NoUI` and `-AutoQuit`+- Validate GUI launch keeps Unreal Insights running+- Validate GUI status process reporting++### `core/analyze.py`++- Validate synthetic CSV parsing for top timers, focused threads, wait timers, and counter peaks+- Validate standard exporter bundle orchestration+- Validate `--skip-export` summary mode for existing CSV outputs+- Validate `export_status` propagation and diagnostics status counts### `unrealinsights_cli.py`-- Validate root and group help++- Validate root and group help, including `store`, `live`, `gui`, and `analyze`- Validate JSON error payloads when trace/backend requirements are missing- Validate REPL session trace state- Validate capture convenience-layer argument handling-- Validate `capture status`, `capture stop`, and `capture snapshot` JSON flows-- Planned tests: 12+- Validate JSON command surfaces for the added command groups## E2E Test Plan### Prerequisites-- Unreal Engine 5.5+ installed with `UnrealInsights.exe`++- Windows with Unreal Engine tools installed- Optional trace file via `UNREALINSIGHTS_TEST_TRACE`+- If not set, tests auto-discover the UE sample `example_trace.decomp.utrace` when installed locally- Optional UE/Game executable via `UNREALINSIGHTS_TEST_TARGET_EXE`### Workflows to validate+- `backend info` against the local UE install+- `store list/latest` against a synthetic Trace Store+- `gui status` without requiring a running GUI+- `live exec` backend-unavailable JSON boundary+- `analyze summary --skip-export` against synthetic CSV exports- Export threads/timers/timing-events/timer-stats/timer-callees/counters/counter-values from a real `.utrace`- Execute a generated response file containing multiple exporter commands- Launch a traced target executable in file mode and verify `.utrace` creation--### Output validation-- All `--json` responses parse correctly-- Export commands create non-empty output files and surface log paths-- `batch run-rsp` returns the materialized output list-- `capture run --wait` returns exit status plus `.utrace` file metadata--## Realistic Workflow Scenarios--### Workflow name: `trace_export_bundle`-- Simulates: post-capture analysis of a performance trace-- Operations chained:- 1. `trace set`- 2. `export threads`- 3. `export timer-stats`- 4. `export counter-values`- 5. `batch run-rsp`-- Verified:- - exporter outputs exist- - response-file execution triggers multiple materialized files- - JSON payloads include log path and exit code--### Workflow name: `editor_boot_capture`-- Simulates: launching a traced UE executable and recording startup behavior-- Operations chained:- 1. `capture run`- 2. `trace info`- 3. optional exporter pass on the produced trace-- Verified:- - traced command line contains `-trace=` and `-tracefile=`- - `.utrace` file is created and has size > 0+- Run `analyze summary` against a real `.utrace` when supplied## Test Results### Commands run```bash-python -m pytest cli_anything/unrealinsights/tests/test_core.py -v --tb=no-python -m pytest cli_anything/unrealinsights/tests/test_full_e2e.py -v -s --tb=nopython -m pip install -e .-cli-anything-unrealinsights --json backend info+python -m pytest cli_anything/unrealinsights/tests/test_core.py -q+python -m pytest cli_anything/unrealinsights/tests/test_full_e2e.py -q -s --tb=short```### Result summary-- `test_core.py`: 49 passed-- `test_full_e2e.py`: 1 passed, 9 skipped-- Manual smoke: installed entrypoint resolved local UE 5.5 binaries successfully--### Coverage notes+- `test_core.py`: 70 passed+- `test_full_e2e.py`: 14 passed, 1 skipped+- Remaining skipped E2E coverage requires `UNREALINSIGHTS_TEST_TARGET_EXE`-- Real export and capture E2E scenarios are env-gated and were skipped because- `UNREALINSIGHTS_TEST_TRACE` and `UNREALINSIGHTS_TEST_TARGET_EXE` were not set.-- The local Windows auto-discovery path was validated against:- - `D:\Program Files\Epic Games\UE_5.5\Engine\Binaries\Win64\UnrealInsights.exe`- - `D:\Program Files\Epic Games\UE_5.5\Engine\Binaries\Win64\UnrealTraceServer.exe`--### Full pytest output+### Latest pytest output```text-============================= test session starts =============================-platform win32 -- Python 3.11.9, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\aimidi\AppData\Local\Programs\Python\Python311\python.exe-cachedir: .pytest_cache-rootdir: D:\code\D5\CLI-Anything-unrealinsights\unrealinsights\agent-harness-collecting ... collected 46 items--cli_anything/unrealinsights/tests/test_core.py::TestOutputUtils::test_output_json PASSED [ 3%]-cli_anything/unrealinsights/tests/test_core.py::TestOutputUtils::test_output_table_empty PASSED [ 7%]-cli_anything/unrealinsights/tests/test_core.py::TestOutputUtils::test_format_size PASSED [ 11%]-cli_anything/unrealinsights/tests/test_core.py::TestErrorUtils::test_handle_error PASSED [ 14%]-cli_anything/unrealinsights/tests/test_core.py::TestBackendDiscovery::test_explicit_path_precedence PASSED [ 18%]-cli_anything/unrealinsights/tests/test_core.py::TestBackendDiscovery::test_env_path_precedence PASSED [ 22%]-cli_anything/unrealinsights/tests/test_core.py::TestBackendDiscovery::test_auto_discovery PASSED [ 25%]-cli_anything/unrealinsights/tests/test_core.py::TestBackendDiscovery::test_missing_explicit_path_fails PASSED [ 29%]-cli_anything/unrealinsights/tests/test_core.py::TestBackendDiscovery::test_build_insights_command PASSED [ 33%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_normalize_trace_output_path_prefers_explicit PASSED [ 37%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_build_exec_cmds_arg PASSED [ 40%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_resolve_engine_root_from_engine_subdir PASSED [ 43%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_resolve_editor_target PASSED [ 46%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_resolve_capture_target_from_project_and_engine PASSED [ 50%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCore::test_build_capture_command PASSED [ 53%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[threads-TimingInsights.ExportThreads] PASSED [ 56%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[timers-TimingInsights.ExportTimers] PASSED [ 59%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[timing-events-TimingInsights.ExportTimingEvents] PASSED [ 62%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[timer-stats-TimingInsights.ExportTimerStatistics] PASSED [ 65%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[timer-callees-TimingInsights.ExportTimerCallees] PASSED [ 68%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[counters-TimingInsights.ExportCounters] PASSED [ 71%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_export_exec_command[counter-values-TimingInsights.ExportCounterValues] PASSED [ 75%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_build_rsp_exec_command PASSED [ 78%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_expected_outputs_from_rsp PASSED [ 81%]-cli_anything/unrealinsights/tests/test_core.py::TestExportCore::test_collect_materialized_outputs_placeholder PASSED [ 84%]-cli_anything/unrealinsights/tests/test_core.py::TestCLIHelp::test_main_help PASSED [ 87%]-cli_anything/unrealinsights/tests/test_core.py::TestCLIHelp::test_group_help PASSED [ 90%]-cli_anything/unrealinsights/tests/test_core.py::TestCLIJsonErrors::test_export_threads_requires_trace PASSED [ 93%]-cli_anything/unrealinsights/tests/test_core.py::TestCLIJsonErrors::test_backend_info_json PASSED [ 96%]-cli_anything/unrealinsights/tests/test_core.py::TestCLIJsonErrors::test_capture_project_requires_engine_root PASSED [ 96%]-cli_anything/unrealinsights/tests/test_core.py::TestREPLSessionState::test_trace_set_then_info_in_repl PASSED [ 99%]-cli_anything/unrealinsights/tests/test_core.py::TestCaptureCLIConvenience::test_capture_run_with_project_and_engine_root PASSED [100%]--============================= 46 passed in 0.28s ==============================--============================= test session starts =============================-platform win32 -- Python 3.11.9, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\aimidi\AppData\Local\Programs\Python\Python311\python.exe-cachedir: .pytest_cache-rootdir: D:\code\D5\CLI-Anything-unrealinsights\unrealinsights\agent-harness-collecting ... [_resolve_cli] Using installed command: C:\Users\aimidi\AppData\Local\Programs\Python\Python311\Scripts\cli-anything-unrealinsights.EXE+...................................................................... [100%]+70 passed in 0.58s++[_resolve_cli] Using installed command: C:\Users\aimidi\AppData\Local\Programs\Python\Python311\Scripts\cli-anything-unrealinsights.EXE[_resolve_cli] Using installed command: C:\Users\aimidi\AppData\Local\Programs\Python\Python311\Scripts\cli-anything-unrealinsights.EXE[_resolve_cli] Using installed command: C:\Users\aimidi\AppData\Local\Programs\Python\Python311\Scripts\cli-anything-unrealinsights.EXE-collected 10 items--cli_anything/unrealinsights/tests/test_full_e2e.py::TestCLISmoke::test_backend_info PASSED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[threads-extra_args0] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[timers-extra_args1] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[timing-events-extra_args2] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[timer-stats-extra_args3] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[timer-callees-extra_args4] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[counters-extra_args5] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_exporter_creates_output[counter-values-extra_args6] SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestExportE2E::test_batch_run_rsp SKIPPED-cli_anything/unrealinsights/tests/test_full_e2e.py::TestCaptureE2E::test_capture_run_wait SKIPPED--======================== 1 passed, 9 skipped in 0.85s =========================+..............s+14 passed, 1 skipped in 80.60s```++## Coverage Notes++- Real export E2E scenarios run automatically when the UE sample trace is present, or when `UNREALINSIGHTS_TEST_TRACE` is set.+- The local UE sample trace passed threads, timers, timing-events, timer-stats, timer-callees, counters, counter-values, batch, and analyze flows.+- `counter-values` required unquoted simple filter tokens such as `-counter=*`; quoted wildcards were parsed by UnrealInsights as a literal backslash escape and matched zero counters.+- Real capture E2E scenarios remain env-gated because they require a user-supplied target executable.+- Live command delivery is intentionally tested through an external command-template boundary; without `UNREALINSIGHTS_LIVE_EXEC`, live commands fail loudly.+- `analyze summary` currently covers timing/counter CSVs. Memory, Networking, Slate, Asset Loading, and Cooking analysis are documented as uncovered domains.diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_core.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_core.pyindex 7501854c2..4f846a93f 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_core.py+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_core.py@@ -367,6 +367,12 @@ class TestExportCore:counter="*" if exporter == "counter-values" else None,)assert command.startswith(expected)+ if exporter == "counter-values":+ assert "-counter=*" in command+ assert '-counter="' not in command+ if exporter in ("timing-events", "timer-stats", "timer-callees"):+ assert "-threads=GameThread" in command+ assert "-timers=*" in commanddef test_build_rsp_exec_command(self, tmp_path):from cli_anything.unrealinsights.core.export import build_rsp_exec_command@@ -411,6 +417,69 @@ class TestExportCore:assert f'"{resolved}"' not in commandassert resolved in command+ @patch("cli_anything.unrealinsights.core.export.backend.parse_unreal_log")+ @patch("cli_anything.unrealinsights.core.export.backend.run_process")+ def test_execute_export_classifies_no_output(self, mock_run, mock_log, tmp_path):+ from cli_anything.unrealinsights.core.export import execute_export++ mock_run.return_value = {+ "command": "UnrealInsights.exe",+ "waited": True,+ "timed_out": False,+ "exit_code": 0,+ "stdout": "",+ "stderr": "",+ "pid": None,+ }+ mock_log.return_value = {+ "path": str(tmp_path / "export.log"),+ "exists": True,+ "warnings": [],+ "errors": [],+ "tail": [],+ }++ result = execute_export(+ "C:/UE/UnrealInsights.exe",+ "C:/trace.utrace",+ "counter-values",+ str(tmp_path / "counter_values.csv"),+ )+ assert result["output_status"] == "no_output"+ assert result["succeeded"] is False+ assert "without materializing" in result["status_message"]++ @patch("cli_anything.unrealinsights.core.export.backend.parse_unreal_log")+ @patch("cli_anything.unrealinsights.core.export.backend.run_process")+ def test_execute_export_classifies_exporter_error(self, mock_run, mock_log, tmp_path):+ from cli_anything.unrealinsights.core.export import execute_export++ mock_run.return_value = {+ "command": "UnrealInsights.exe",+ "waited": True,+ "timed_out": False,+ "exit_code": 0,+ "stdout": "",+ "stderr": "",+ "pid": None,+ }+ mock_log.return_value = {+ "path": str(tmp_path / "export.log"),+ "exists": True,+ "warnings": [],+ "errors": ["TimingInsights: Error: Export failed."],+ "tail": [],+ }++ result = execute_export(+ "C:/UE/UnrealInsights.exe",+ "C:/trace.utrace",+ "threads",+ str(tmp_path / "threads.csv"),+ )+ assert result["output_status"] == "exporter_error"+ assert result["status_message"] == "TimingInsights: Error: Export failed."+def test_expected_outputs_from_rsp(self, tmp_path):from cli_anything.unrealinsights.core.export import expected_outputs_from_rsp@@ -429,6 +498,25 @@ class TestExportCore:assert str((tmp_path / "threads.csv").resolve()) in outputsassert str((tmp_path / "timers.csv").resolve()) in outputs+ def test_normalize_response_file_lines_unquotes_filename_without_spaces(self, tmp_path):+ from cli_anything.unrealinsights.core.export import normalize_response_file_lines++ output = tmp_path / "threads.csv"+ lines = [f'TimingInsights.ExportThreads "{output}"']+ normalized = normalize_response_file_lines(lines, insights_version="5.5.4")+ assert normalized[0] == f"TimingInsights.ExportThreads {output.resolve()}"++ def test_normalized_response_file_path_writes_temp_file(self, tmp_path):+ from cli_anything.unrealinsights.core.export import normalized_response_file_path++ output = tmp_path / "threads.csv"+ rsp = tmp_path / "exports.rsp"+ rsp.write_text(f'TimingInsights.ExportThreads "{output}"\n', encoding="utf-8")+ normalized_path = normalized_response_file_path(str(rsp), insights_version="5.5.4")+ assert normalized_path != str(rsp.resolve())+ assert f"TimingInsights.ExportThreads {output.resolve()}" in Path(normalized_path).read_text(encoding="utf-8")+ Path(normalized_path).unlink()+def test_collect_materialized_outputs_placeholder(self, tmp_path):from cli_anything.unrealinsights.core.export import collect_materialized_outputs@@ -437,6 +525,228 @@ class TestExportCore:assert str((tmp_path / "stats_GameThread.csv").resolve()) in outputs+class TestStoreCore:+ def test_list_trace_files_includes_ucache_and_live_flag(self, tmp_path):+ from cli_anything.unrealinsights.core.store import list_trace_files++ trace_dir = tmp_path / "Store" / "001"+ trace_dir.mkdir(parents=True)+ trace = trace_dir / "session.ucache"+ trace.write_text("trace", encoding="utf-8")++ result = list_trace_files(str(tmp_path / "Store"), live_window_seconds=3600)+ assert result["trace_count"] == 1+ assert result["traces"][0]["extension"] == ".ucache"+ assert result["traces"][0]["is_live_candidate"] is True++ def test_latest_trace_file(self, tmp_path):+ from cli_anything.unrealinsights.core.store import latest_trace_file++ store = tmp_path / "Store"+ store.mkdir()+ old_trace = store / "old.utrace"+ new_trace = store / "new.utrace"+ old_trace.write_text("old", encoding="utf-8")+ new_trace.write_text("new", encoding="utf-8")+ os.utime(old_trace, (1, 1))++ result = latest_trace_file(str(store))+ assert result["latest"]["path"] == str(new_trace.resolve())++ @patch("cli_anything.unrealinsights.core.store.backend.resolve_trace_server_exe")+ def test_trace_store_info(self, mock_resolve, tmp_path, monkeypatch):+ from cli_anything.unrealinsights.core.store import trace_store_info++ trace_root = tmp_path / "Trace"+ store = trace_root / "Store"+ store.mkdir(parents=True)+ monkeypatch.setenv("UNREAL_TRACE_ROOT", str(trace_root))+ mock_resolve.return_value = {"available": False, "path": None, "error": "missing"}++ result = trace_store_info()+ assert result["store_dir"] == str(store)+ assert result["store_exists"] is True+++class TestLiveCore:+ @patch("cli_anything.unrealinsights.core.live.subprocess.run")+ def test_list_unreal_processes_windows_json(self, mock_run):+ from cli_anything.unrealinsights.core.live import list_unreal_processes++ mock_run.return_value = type(+ "Result",+ (),+ {+ "returncode": 0,+ "stdout": json.dumps(+ [+ {+ "Name": "UnrealEditor.exe",+ "ProcessId": 100,+ "ExecutablePath": "C:/UE/UnrealEditor.exe",+ "CommandLine": "UnrealEditor.exe C:/Game.uproject",+ "CreationDate": "now",+ },+ {+ "Name": "UnrealInsights.exe",+ "ProcessId": 200,+ "ExecutablePath": "C:/UE/UnrealInsights.exe",+ "CommandLine": "UnrealInsights.exe",+ "CreationDate": "now",+ },+ ]+ ),+ },+ )()++ with patch("cli_anything.unrealinsights.core.live.os.name", "nt"):+ result = list_unreal_processes()+ assert result["process_count"] == 2+ assert {process["role"] for process in result["processes"]} == {"editor", "insights"}++ def test_live_exec_requires_backend(self, monkeypatch):+ from cli_anything.unrealinsights.core.live import execute_live_command++ monkeypatch.delenv("UNREALINSIGHTS_LIVE_EXEC", raising=False)+ with pytest.raises(RuntimeError, match="Live control backend unavailable"):+ execute_live_command(100, "Trace.Status", backend_command=None)++ @patch("cli_anything.unrealinsights.core.live.backend.run_process")+ def test_live_exec_uses_template(self, mock_run, monkeypatch):+ from cli_anything.unrealinsights.core.live import execute_live_command++ monkeypatch.delenv("UNREALINSIGHTS_LIVE_EXEC", raising=False)+ mock_run.return_value = {+ "command": ["sender"],+ "waited": True,+ "timed_out": False,+ "exit_code": 0,+ "stdout": "ok",+ "stderr": "",+ "pid": None,+ }++ result = execute_live_command(100, "Trace.Status", backend_command='sender --pid {pid} --cmd "{cmd}"')+ assert result["succeeded"] is True+ assert result["live_command"] == "Trace.Status"+++class TestGuiCore:+ def test_build_gui_command_has_no_headless_flags(self, tmp_path):+ from cli_anything.unrealinsights.core.gui import build_gui_command++ exe = tmp_path / "UnrealInsights.exe"+ trace = tmp_path / "session.utrace"+ exe.write_text("x", encoding="utf-8")+ trace.write_text("x", encoding="utf-8")+ command = build_gui_command(str(exe), str(trace))+ assert "-NoUI" not in command+ assert "-AutoQuit" not in command+ assert any(arg.startswith("-OpenTraceFile=") for arg in command)++ @patch("cli_anything.unrealinsights.core.gui.backend.run_process")+ def test_open_gui_keeps_running(self, mock_run, tmp_path):+ from cli_anything.unrealinsights.core.gui import open_gui++ exe = tmp_path / "UnrealInsights.exe"+ exe.write_text("x", encoding="utf-8")+ mock_run.return_value = {+ "command": [str(exe)],+ "waited": False,+ "timed_out": False,+ "exit_code": None,+ "stdout": None,+ "stderr": None,+ "pid": 321,+ }+ result = open_gui(str(exe))+ assert result["pid"] == 321+ assert result["kept_running"] is True+++class TestAnalyzeCore:+ def test_summarize_exports_from_synthetic_csv(self, tmp_path):+ from cli_anything.unrealinsights.core.analyze import summarize_exports++ (tmp_path / "timer_stats.csv").write_text(+ "\n".join(+ [+ "Timer Name,Thread,Total Time,Count",+ "Tick,GameThread,12.5,3",+ "WaitForTasks,RenderThread,20.0,2",+ ]+ ),+ encoding="utf-8",+ )+ (tmp_path / "counter_values.csv").write_text(+ "\n".join(+ [+ "Counter,Value",+ "FrameTime,33.3",+ "FrameTime,16.6",+ ]+ ),+ encoding="utf-8",+ )++ result = summarize_exports(str(tmp_path), limit=2)+ assert result["succeeded"] is True+ assert result["summary"]["top_timers"][0]["name"] == "WaitForTasks"+ assert result["summary"]["focus_threads"]["GameThread"][0]["name"] == "Tick"+ assert result["summary"]["counter_peaks"][0]["name"] == "FrameTime"+ diagnostics = result["summary"]["diagnostics"]+ assert diagnostics["primary_hotspot"]["name"] == "WaitForTasks"+ assert diagnostics["wait_pressure"] == "present"+ assert diagnostics["counter_anomaly_count"] == 1++ def test_summarize_exports_reports_export_status(self, tmp_path):+ from cli_anything.unrealinsights.core.analyze import summarize_exports++ (tmp_path / "timer_stats.csv").write_text("Timer Name,Total Time\nTick,1.0\n", encoding="utf-8")+ result = summarize_exports(+ str(tmp_path),+ export_results=[+ {+ "exporter": "timer-stats",+ "output_status": "ok",+ "succeeded": True,+ "output_files": [str(tmp_path / "timer_stats.csv")],+ "status_message": "ok",+ "log_path": "timer_stats.log",+ },+ {+ "exporter": "counter-values",+ "output_status": "no_output",+ "succeeded": False,+ "output_files": [],+ "status_message": "no data",+ "log_path": "counter_values.log",+ },+ ],+ )+ assert result["export_status"][1]["status"] == "no_output"+ assert result["summary"]["diagnostics"]["export_status_counts"]["ok"] == 1+ assert result["summary"]["diagnostics"]["export_status_counts"]["no_output"] == 1++ @patch("cli_anything.unrealinsights.core.analyze.execute_export")+ def test_analyze_summary_runs_export_bundle(self, mock_export, tmp_path):+ from cli_anything.unrealinsights.core.analyze import analyze_summary++ def _fake_export(_exe, _trace, exporter, output_path, **_kwargs):+ if exporter == "timer-stats":+ Path(output_path).write_text("Timer Name,Total Time\nTick,1.0\n", encoding="utf-8")+ elif exporter == "counter-values":+ Path(output_path).write_text("Counter,Value\nFrameTime,16.0\n", encoding="utf-8")+ else:+ Path(output_path).write_text("Name\nx\n", encoding="utf-8")+ return {"exporter": exporter, "output_files": [output_path], "succeeded": True}++ mock_export.side_effect = _fake_export+ result = analyze_summary("C:/UE/UnrealInsights.exe", "C:/trace.utrace", str(tmp_path))+ assert result["succeeded"] is True+ assert mock_export.call_count == 5++class TestCLIHelp:def test_main_help(self):from cli_anything.unrealinsights.unrealinsights_cli import cli@@ -450,7 +760,7 @@ class TestCLIHelp:from cli_anything.unrealinsights.unrealinsights_cli import clirunner = CliRunner()- for group in ("backend", "trace", "capture", "export", "batch"):+ for group in ("backend", "trace", "store", "capture", "live", "gui", "export", "batch", "analyze"):result = runner.invoke(cli, [group, "--help"])assert result.exit_code == 0, f"{group} help failed"@@ -594,6 +904,57 @@ class TestCLIJsonErrors:data = json.loads(result.output)assert data["snapshot_exists"] is True+ @patch("cli_anything.unrealinsights.unrealinsights_cli.trace_store_info")+ def test_store_info_json(self, mock_store_info):+ from cli_anything.unrealinsights.unrealinsights_cli import cli++ mock_store_info.return_value = {+ "trace_root": "C:/Trace",+ "trace_root_exists": True,+ "store_dir": "C:/Trace/Store",+ "store_exists": True,+ "trace_file_count": 0,+ "trace_server": {"available": False, "error": "missing"},+ "watch_folders": ["C:/Trace/Store"],+ "server_logs": [],+ }+ runner = CliRunner()+ result = runner.invoke(cli, ["--json", "store", "info"])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["store_exists"] is True++ def test_live_exec_json_backend_unavailable(self, monkeypatch):+ from cli_anything.unrealinsights.unrealinsights_cli import cli++ monkeypatch.delenv("UNREALINSIGHTS_LIVE_EXEC", raising=False)+ runner = CliRunner()+ result = runner.invoke(cli, ["--json", "live", "exec", "--pid", "1234", "Trace.Status"])+ assert result.exit_code == 1+ data = json.loads(result.output)+ assert "Live control backend unavailable" in data["error"]++ @patch("cli_anything.unrealinsights.unrealinsights_cli.gui_status")+ def test_gui_status_json(self, mock_gui_status):+ from cli_anything.unrealinsights.unrealinsights_cli import cli++ mock_gui_status.return_value = {"running": False, "process_count": 0, "processes": []}+ runner = CliRunner()+ result = runner.invoke(cli, ["--json", "gui", "status"])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["running"] is False++ def test_analyze_summary_skip_export_json(self, tmp_path):+ from cli_anything.unrealinsights.unrealinsights_cli import cli++ (tmp_path / "timer_stats.csv").write_text("Timer Name,Total Time\nTick,1.0\n", encoding="utf-8")+ runner = CliRunner()+ result = runner.invoke(cli, ["--json", "analyze", "summary", "--skip-export", "--out", str(tmp_path)])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["summary"]["top_timers"][0]["name"] == "Tick"+class TestREPLSessionState:def test_trace_set_then_info_in_repl(self):diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_full_e2e.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_full_e2e.pyindex a852a64d6..9d1691218 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_full_e2e.py+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/tests/test_full_e2e.py@@ -16,7 +16,24 @@ import pytestfrom cli_anything.unrealinsights.utils.unrealinsights_backend import resolve_unrealinsights_exeHARNESS_ROOT = str(Path(__file__).resolve().parents[3])-TEST_TRACE = os.environ.get("UNREALINSIGHTS_TEST_TRACE", "")+++def _discover_sample_trace() -> str:+ env_trace = os.environ.get("UNREALINSIGHTS_TEST_TRACE", "").strip()+ if env_trace:+ return env_trace+ for drive in "CDEFGHIJKLMNOPQRSTUVWXYZ":+ root = Path(f"{drive}:/Program Files/Epic Games")+ if not root.is_dir():+ continue+ for install in sorted(root.glob("UE_*"), reverse=True):+ candidate = install / "Engine" / "Source" / "Programs" / "Shared" / "EpicGames.Tracing.Tests" / "UnrealInsights" / "example_trace.decomp.utrace"+ if candidate.is_file():+ return str(candidate)+ return ""+++TEST_TRACE = _discover_sample_trace()TEST_TARGET_EXE = os.environ.get("UNREALINSIGHTS_TEST_TARGET_EXE", "")@@ -80,6 +97,46 @@ class TestCLISmoke:assert data["insights"]["available"] is Trueassert data["insights"]["path"].lower().endswith("unrealinsights.exe")+ def test_store_list_latest_smoke(self, tmp_path, monkeypatch):+ store = tmp_path / "Store" / "001"+ store.mkdir(parents=True)+ trace = store / "session.utrace"+ trace.write_text("trace", encoding="utf-8")+ monkeypatch.setenv("UNREAL_TRACE_STORE_DIR", str(tmp_path / "Store"))++ result = self._run(["--json", "store", "list"])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert data["trace_count"] == 1++ latest = self._run(["--json", "store", "latest", "--set-current"])+ latest_data = json.loads(latest.stdout)+ assert latest_data["latest"]["path"] == str(trace.resolve())++ def test_gui_status_smoke(self):+ result = self._run(["--json", "gui", "status"])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "running" in data+ assert "processes" in data++ def test_live_backend_unavailable_smoke(self, monkeypatch):+ monkeypatch.delenv("UNREALINSIGHTS_LIVE_EXEC", raising=False)+ result = self._run(["--json", "live", "exec", "--pid", "1234", "Trace.Status"], check=False)+ assert result.returncode == 1+ data = json.loads(result.stdout)+ assert "Live control backend unavailable" in data["error"]++ def test_analyze_summary_skip_export_smoke(self, tmp_path):+ (tmp_path / "timer_stats.csv").write_text(+ "Timer Name,Thread,Total Time\nTick,GameThread,1.0\n",+ encoding="utf-8",+ )+ result = self._run(["--json", "analyze", "summary", "--skip-export", "--out", str(tmp_path)])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert data["summary"]["top_timers"][0]["name"] == "Tick"+@skip_no_traceclass TestExportE2E:@@ -100,11 +157,11 @@ class TestExportE2E:[("threads", []),("timers", []),- ("timing-events", ["--threads", "GameThread", "--timers", "*"]),- ("timer-stats", ["--threads", "GameThread", "--timers", "*"]),- ("timer-callees", ["--threads", "GameThread", "--timers", "*"]),+ ("timing-events", ["--threads=GameThread", "--timers=*"]),+ ("timer-stats", ["--threads=GameThread", "--timers=*"]),+ ("timer-callees", ["--threads=GameThread", "--timers=*"]),("counters", []),- ("counter-values", ["--counter", "*"]),+ ("counter-values", ["--counter=*"]),],)def test_exporter_creates_output(self, subcommand, extra_args):@@ -117,6 +174,9 @@ class TestExportE2E:if result.returncode != 0:pytest.skip(f"{subcommand} exporter failed for supplied trace")data = json.loads(result.stdout)+ if data.get("output_status") == "no_output":+ pytest.skip(f"{subcommand} exporter produced no output for supplied trace")+ assert data["output_status"] == "ok"assert data["output_files"]for path in data["output_files"]:assert os.path.isfile(path)@@ -145,6 +205,19 @@ class TestExportE2E:assert os.path.isfile(path)assert os.path.getsize(path) > 0+ def test_analyze_summary_real_trace(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ result = self._run(+ ["--json", "-t", TEST_TRACE, "analyze", "summary", "--out", tmpdir],+ check=False,+ timeout=360,+ )+ if result.returncode != 0:+ pytest.skip("analyze summary failed for supplied trace")+ data = json.loads(result.stdout)+ assert data["exports"]+ assert data["out_dir"] == str(Path(tmpdir).resolve())+@skip_no_targetclass TestCaptureE2E:diff --git a/unrealinsights/agent-harness/cli_anything/unrealinsights/unrealinsights_cli.py b/unrealinsights/agent-harness/cli_anything/unrealinsights/unrealinsights_cli.pyindex 8c1852dbe..aab99f49b 100644--- a/unrealinsights/agent-harness/cli_anything/unrealinsights/unrealinsights_cli.py+++ b/unrealinsights/agent-harness/cli_anything/unrealinsights/unrealinsights_cli.py@@ -12,6 +12,7 @@ from pathlib import Pathimport clickfrom cli_anything.unrealinsights import __version__+from cli_anything.unrealinsights.core.analyze import analyze_summaryfrom cli_anything.unrealinsights.core.capture import (DEFAULT_CHANNELS,capture_status,@@ -22,7 +23,18 @@ from cli_anything.unrealinsights.core.capture import (stop_capture,)from cli_anything.unrealinsights.core.export import execute_export, execute_response_file+from cli_anything.unrealinsights.core.gui import gui_status, open_gui+from cli_anything.unrealinsights.core.live import (+ execute_live_command,+ list_unreal_processes,+ trace_bookmark,+ trace_screenshot,+ trace_snapshot,+ trace_status as live_trace_status,+ trace_stop,+)from cli_anything.unrealinsights.core.session import UnrealInsightsSession, state_dir+from cli_anything.unrealinsights.core.store import latest_trace_file, list_trace_files, trace_store_infofrom cli_anything.unrealinsights.utils.errors import handle_errorfrom cli_anything.unrealinsights.utils.output import format_size, output_jsonfrom cli_anything.unrealinsights.utils.unrealinsights_backend import (@@ -128,7 +140,10 @@ def _human_export_result(data: dict[str, object]):click.echo(f"Command: {data['exec_command']}")click.echo(f"Log: {data['log_path']}")click.echo(f"Exit code: {data['exit_code']}")+ click.echo(f"Status: {data.get('output_status', 'unknown')}")click.echo(f"Success: {'yes' if data['succeeded'] else 'no'}")+ if data.get("status_message"):+ click.echo(f"Message: {data['status_message']}")if data["output_files"]:click.echo("Outputs:")for output_path in data["output_files"]:@@ -192,6 +207,85 @@ def _human_stop_result(data: dict[str, object]):click.echo(f"Exit code: {termination.get('exit_code')}")+def _human_store_info(data: dict[str, object]):+ click.echo(f"Trace root: {data['trace_root']}")+ click.echo(f"Store: {data['store_dir']}")+ click.echo(f"Store exists: {'yes' if data['store_exists'] else 'no'}")+ click.echo(f"Trace files: {data['trace_file_count']}")+ trace_server = data["trace_server"]+ if trace_server.get("available"):+ click.echo(f"TraceServer: {trace_server['path']}")+ else:+ click.echo(f"TraceServer: unavailable ({trace_server.get('error', 'not found')})")+++def _human_store_list(data: dict[str, object]):+ click.echo(f"Store: {data['store_dir']}")+ click.echo(f"Trace count: {data['trace_count']}")+ for trace in data["traces"][:20]:+ live = " live?" if trace.get("is_live_candidate") else ""+ click.echo(f" {trace['path']} ({format_size(trace.get('file_size'))}){live}")+++def _human_store_latest(data: dict[str, object]):+ latest = data.get("latest")+ if not latest:+ click.echo("No trace file found.")+ return+ click.echo(f"Latest trace: {latest['path']}")+ click.echo(f"Size: {format_size(latest.get('file_size'))}")+ click.echo(f"Live guess: {'yes' if latest.get('is_live_candidate') else 'no'}")+ if data.get("set_current"):+ click.echo("Current session trace updated.")+++def _human_processes(data: dict[str, object]):+ click.echo(f"Processes: {data['process_count']}")+ for process in data["processes"]:+ click.echo(f" {process['pid']} {process['role']} {process['name']} {process.get('path') or ''}")+++def _human_live_result(data: dict[str, object]):+ click.echo(f"PID: {data['pid']}")+ click.echo(f"Command: {data['live_command']}")+ click.echo(f"Backend: {data['backend']}")+ click.echo(f"Exit: {data['exit_code']}")+ click.echo(f"Success: {'yes' if data['succeeded'] else 'no'}")+ if data.get("stdout"):+ click.echo(data["stdout"])+ if data.get("stderr"):+ click.echo(data["stderr"])+++def _human_gui_status(data: dict[str, object]):+ click.echo(f"Unreal Insights GUI running: {'yes' if data['running'] else 'no'}")+ for process in data["processes"]:+ click.echo(f" {process['pid']} {process.get('path') or process['name']}")+++def _human_gui_open(data: dict[str, object]):+ click.echo(f"UnrealInsights.exe: {data['insights_exe']}")+ if data.get("trace_path"):+ click.echo(f"Trace: {data['trace_path']}")+ click.echo(f"PID: {data['pid']}")+ click.echo("Mode: GUI kept running")+++def _human_analyze_summary(data: dict[str, object]):+ click.echo(f"Trace: {data.get('trace_path') or 'not supplied'}")+ click.echo(f"Out dir: {data['out_dir']}")+ click.echo(f"Success: {'yes' if data['succeeded'] else 'no'}")+ top_timers = data["summary"].get("top_timers", [])+ if top_timers:+ click.echo("Top timers:")+ for entry in top_timers[:10]:+ click.echo(f" {entry['name']} score={entry.get('score')}")+ if data.get("warnings"):+ click.echo("Warnings:")+ for warning in data["warnings"]:+ click.echo(f" {warning}")++@click.group(invoke_without_command=True)@click.option("--json", "json_mode", is_flag=True, help="Output in JSON format.")@click.option("--debug", is_flag=True, help="Show debug tracebacks on errors.")@@ -306,6 +400,71 @@ def trace_info(ctx):_output(ctx, session.trace_info(), _human_trace_info)[email protected]("store")+def store_group():+ """Trace Store discovery and session selection."""+++@store_group.command("info")[email protected]("--store-dir", type=click.Path(exists=False), default=None, help="Explicit Trace Store directory.")[email protected]_context+def store_info(ctx, store_dir):+ """Inspect the local Unreal Trace Store."""+ try:+ session = _get_session(ctx)+ data = trace_store_info(store_dir=store_dir, trace_server_exe=session.trace_server_exe)+ _output(ctx, data, _human_store_info)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@store_group.command("list")[email protected]("--store-dir", type=click.Path(exists=False), default=None, help="Explicit Trace Store directory.")[email protected]("--live-only", is_flag=True, help="Only show recently modified trace files.")[email protected]("--include-cache/--no-include-cache", default=True, show_default=True, help="Include Trace Store .ucache files.")[email protected]("--live-window", type=float, default=60.0, show_default=True, help="Seconds used for live-candidate detection.")[email protected]_context+def store_list(ctx, store_dir, live_only, include_cache, live_window):+ """List trace files in the Trace Store."""+ try:+ data = list_trace_files(+ store_dir=store_dir,+ live_only=live_only,+ include_cache=include_cache,+ live_window_seconds=live_window,+ )+ _output(ctx, data, _human_store_list)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@store_group.command("latest")[email protected]("--store-dir", type=click.Path(exists=False), default=None, help="Explicit Trace Store directory.")[email protected]("--live-only", is_flag=True, help="Only consider recently modified trace files.")[email protected]("--include-cache/--no-include-cache", default=True, show_default=True, help="Include Trace Store .ucache files.")[email protected]("--live-window", type=float, default=60.0, show_default=True, help="Seconds used for live-candidate detection.")[email protected]("--set-current", is_flag=True, help="Set the selected trace as the current session trace.")[email protected]_context+def store_latest(ctx, store_dir, live_only, include_cache, live_window, set_current):+ """Select the newest trace file in the Trace Store."""+ try:+ data = latest_trace_file(+ store_dir=store_dir,+ live_only=live_only,+ include_cache=include_cache,+ live_window_seconds=live_window,+ )+ latest = data.get("latest")+ if latest and set_current:+ _get_session(ctx).set_trace(latest["path"])+ data["set_current"] = True+ else:+ data["set_current"] = False+ _output(ctx, data, _human_store_latest)+ except Exception as exc:+ _handle_exc(ctx, exc)++@cli.group("capture")def capture_group():"""Trace capture orchestration."""@@ -458,6 +617,166 @@ def capture_snapshot_cmd(ctx, output_trace):_handle_exc(ctx, exc)[email protected]("live")+def live_group():+ """Live UE process discovery and trace-control command delivery."""+++@live_group.command("processes")[email protected]("--include-tools/--no-include-tools", default=True, show_default=True, help="Include UnrealInsights and TraceServer.")[email protected]_context+def live_processes(ctx, include_tools):+ """List local Unreal-related processes."""+ try:+ data = list_unreal_processes(include_tools=include_tools)+ _output(ctx, data, _human_processes)+ except Exception as exc:+ _handle_exc(ctx, exc)+++def _run_live_command(ctx: click.Context, fn, *args, backend_command=None, timeout=None):+ data = fn(*args, backend_command=backend_command, timeout=timeout)+ _output(ctx, data, _human_live_result)+++@live_group.command("exec")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]("command", nargs=-1, required=True)[email protected]_context+def live_exec(ctx, pid, backend_command, timeout, command):+ """Send a raw console command to a live UE process."""+ try:+ data = execute_live_command(+ pid,+ " ".join(command),+ backend_command=backend_command,+ timeout=timeout,+ )+ _output(ctx, data, _human_live_result)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@live_group.command("trace-status")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]_context+def live_trace_status_cmd(ctx, pid, backend_command, timeout):+ """Run Trace.Status on a live UE process."""+ try:+ _run_live_command(ctx, live_trace_status, pid, backend_command=backend_command, timeout=timeout)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@live_group.command("bookmark")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]("name")[email protected]_context+def live_bookmark(ctx, pid, backend_command, timeout, name):+ """Insert a Trace.Bookmark marker in a live UE process."""+ try:+ _run_live_command(ctx, trace_bookmark, pid, name, backend_command=backend_command, timeout=timeout)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@live_group.command("screenshot")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]("name")[email protected]_context+def live_screenshot(ctx, pid, backend_command, timeout, name):+ """Insert a Trace.Screenshot marker in a live UE process."""+ try:+ _run_live_command(ctx, trace_screenshot, pid, name, backend_command=backend_command, timeout=timeout)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@live_group.command("snapshot")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]("output_trace", type=click.Path(exists=False))[email protected]_context+def live_snapshot(ctx, pid, backend_command, timeout, output_trace):+ """Request a Trace.SnapshotFile from a live UE process."""+ try:+ _run_live_command(ctx, trace_snapshot, pid, output_trace, backend_command=backend_command, timeout=timeout)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@live_group.command("stop-trace")[email protected]("--pid", required=True, type=int, help="Target UE process id.")[email protected]("--backend-command", default=None, help="External command template accepting {pid} and {cmd}.")[email protected]("--timeout", type=float, default=None, help="Optional backend timeout in seconds.")[email protected]_context+def live_stop_trace(ctx, pid, backend_command, timeout):+ """Stop tracing in a live UE process without killing the process."""+ try:+ _run_live_command(ctx, trace_stop, pid, backend_command=backend_command, timeout=timeout)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]("gui")+def gui_group():+ """Unreal Insights GUI co-pilot helpers."""+++@gui_group.command("status")[email protected]_context+def gui_status_cmd(ctx):+ """Show running Unreal Insights GUI processes."""+ try:+ data = gui_status()+ _output(ctx, data, _human_gui_status)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@gui_group.command("open")[email protected]("--trace", "trace_override", type=click.Path(exists=False), default=None, help="Trace file to open in the GUI.")[email protected]_context+def gui_open_cmd(ctx, trace_override):+ """Open Unreal Insights GUI and keep it running."""+ try:+ trace_path = trace_override or _get_session(ctx).trace_path+ insights = _resolve_insights(ctx)+ data = open_gui(insights["path"], trace_path=trace_path)+ _output(ctx, data, _human_gui_open)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@gui_group.command("open-latest")[email protected]("--store-dir", type=click.Path(exists=False), default=None, help="Explicit Trace Store directory.")[email protected]("--live-only", is_flag=True, help="Only consider recently modified trace files.")[email protected]("--include-cache/--no-include-cache", default=True, show_default=True, help="Include Trace Store .ucache files.")[email protected]_context+def gui_open_latest(ctx, store_dir, live_only, include_cache):+ """Open the newest Trace Store trace in Unreal Insights GUI."""+ try:+ latest = latest_trace_file(store_dir=store_dir, live_only=live_only, include_cache=include_cache).get("latest")+ if not latest:+ raise RuntimeError("No trace file found in the Trace Store.")+ _get_session(ctx).set_trace(latest["path"])+ insights = _resolve_insights(ctx)+ data = open_gui(insights["path"], trace_path=latest["path"])+ data["latest"] = latest+ _output(ctx, data, _human_gui_open)+ except Exception as exc:+ _handle_exc(ctx, exc)++@cli.group("export")def export_group():"""Offline Unreal Insights exporters."""@@ -656,6 +975,46 @@ def batch_run_rsp(ctx, rsp_path):_handle_exc(ctx, exc)[email protected]("analyze")+def analyze_group():+ """Export and summarize Unreal Insights timing/counter data."""+++@analyze_group.command("summary")[email protected]("--trace", "trace_override", type=click.Path(exists=False), default=None, help="Trace file to analyze.")[email protected]("--out", "out_dir", required=True, type=click.Path(exists=False), help="Directory for exports and summary inputs.")[email protected]("--skip-export", is_flag=True, help="Summarize existing CSV exports without launching UnrealInsights.exe.")[email protected]("--limit", type=int, default=20, show_default=True, help="Maximum entries per summary list.")[email protected]_context+def analyze_summary_cmd(ctx, trace_override, out_dir, skip_export, limit):+ """Run the standard exporter bundle and summarize hot spots."""+ try:+ trace_path = None+ insights = None+ if trace_override:+ trace_path = str(Path(trace_override).expanduser().resolve())+ _get_session(ctx).set_trace(trace_path)+ elif not skip_export:+ trace_path = _require_trace(ctx)+ elif _get_session(ctx).trace_path:+ trace_path = _get_session(ctx).trace_path++ if not skip_export:+ insights = _resolve_insights(ctx)++ data = analyze_summary(+ insights["path"] if insights else None,+ trace_path,+ out_dir,+ insights_version=insights.get("version") if insights else None,+ skip_export=skip_export,+ limit=limit,+ )+ _output(ctx, data, _human_analyze_summary)+ except Exception as exc:+ _handle_exc(ctx, exc)++@cli.command()@click.pass_contextdef repl(ctx):@@ -673,9 +1032,13 @@ def repl(ctx):repl_commands = {"backend": "info|ensure-insights","trace": "set|info",+ "store": "info|list|latest","capture": "run|start|status|stop|snapshot",+ "live": "processes|exec|trace-status|bookmark|screenshot|snapshot|stop-trace",+ "gui": "status|open|open-latest","export": "threads|timers|timing-events|timer-stats|timer-callees|counters|counter-values","batch": "run-rsp",+ "analyze": "summary","help": "Show this help","quit": "Exit REPL",}