"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: enhance nsight graphics analysis
aimidia30b9174d8f6
diff --git a/README.md b/README.mdindex 0bd2fed71..4a90ab5fa 100644--- a/README.md+++ b/README.md@@ -596,7 +596,7 @@ AI agents are great at reasoning but terrible at using real professional softwar| ๐ธ "UI automation breaks constantly" | No screenshots, no clicking, no RPA fragility. Pure command-line reliability with structured interfaces || ๐ "Agents need structured data" | Built-in JSON output for seamless agent consumption + human-readable formats for debugging || ๐ง "Custom integrations are expensive" | One Claude plugin auto-generates CLIs for ANY codebase through proven 7-phase pipeline |-| โก "Prototype vs Production gap" | 2,269+ tests with real software validation. Battle-tested across 18 major applications |+| โก "Prototype vs Production gap" | 2,280+ tests with real software validation. Battle-tested across 18 major applications |---@@ -978,8 +978,8 @@ Each application received complete, production-ready CLI interfaces โ not demo<td align="center"><strong>๐ฉ <a href="nsight-graphics/agent-harness/">Nsight Graphics CLI</a></strong></td><td>GPU Debugging & Profiling</td><td><code>cli-anything-nsight-graphics</code></td>-<td>Official ngfx / ngfx-capture orchestration + GPU Trace summary</td>-<td align="center">โ 40</td>+<td>Official ngfx / ngfx-capture orchestration + GPU Trace summary + replay analysis</td>+<td align="center">โ 51</td></tr><tr><td align="center"><strong>๐ <a href="exa/agent-harness/">Exa</a></strong></td>@@ -1011,11 +1011,11 @@ Each application received complete, production-ready CLI interfaces โ not demo</tr><tr><td align="center" colspan="4"><strong>Total</strong></td>-<td align="center"><strong>โ 2,269</strong></td>+<td align="center"><strong>โ 2,280</strong></td></tr></table>-> **100% pass rate** across all 2,269 tests โ 1,672 unit tests + 578 end-to-end tests + 19 Node.js tests.+> **100% pass rate** across all 2,280 tests โ 1,682 unit tests + 579 end-to-end tests + 19 Node.js tests.---@@ -1055,11 +1055,11 @@ renderdoc 59 passed โ (45 unit + 14 e2e)cloudcompare 88 passed โ (49 unit + 39 e2e)openscreen 101 passed โ (78 unit + 23 e2e)lldb 27 passed โ (23 unit + 4 e2e)-nsight-graphics 40 passed โ (36 unit + 4 e2e)+nsight-graphics 51 passed โ (46 unit/CLI + 5 local e2e)unrealinsights 50 passed โ (49 unit + 1 e2e, 9 backend-gated e2e skipped)cloudanalyzer 14 passed โ (7 unit + 7 e2e)โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-TOTAL 2,269 passed โ 100% pass rate+TOTAL 2,280 passed โ 100% pass rate```---@@ -1133,7 +1133,7 @@ cli-anything/โโโ ๐ฎ godot/agent-harness/ # Godot Engine CLI (24 tests)โโโ ๐จ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)โโโ ๐ฌ renderdoc/agent-harness/ # RenderDoc CLI (59 tests)-โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI (40 tests)+โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI (51 tests)โโโ ๐ lldb/agent-harness/ # LLDB CLI (27 tests)โโโ ๐ unrealinsights/agent-harness/ # Unreal Insights CLI (50 tests)โโโ ๐ฌ videocaptioner/agent-harness/ # VideoCaptioner CLI (26 tests)@@ -1366,7 +1366,7 @@ MIT License โ free to use, modify, and distribute.**CLI-Anything** โ *Make any software with a codebase Agent-native.*-<sub>A methodology for the age of AI agents | 18 professional software demos | 2,269 passing tests</sub>+<sub>A methodology for the age of AI agents | 18 professional software demos | 2,280 passing tests</sub><br>diff --git a/README_CN.md b/README_CN.mdindex f66cca05b..6cb5b091f 100644--- a/README_CN.md+++ b/README_CN.md@@ -374,7 +374,7 @@ AI Agent ๆจ็่ฝๅๅพๅผบ๏ผไฝๆๆง็ๅฎไธไธ่ฝฏไปถ็่ฝๅๅพๅผฑใ็ฐ| ๐ธ "GUI ่ชๅจๅไธๅคฉไธคๅคดๅดฉ" | ๅๅซๆชๅพใ็นๅปๅ RPA ็่ๅผฑๆง๏ผ็บฏๅฝไปค่กๆๆง๏ผ็ปๆๅๆฅๅฃ || ๐ "Agent ้่ฆ็ปๆๅๆฐๆฎ" | ๅ ็ฝฎ JSON ่พๅบไพ Agent ็ดๆฅๆถ่ดน๏ผๅๆถไฟ็ๅฏ่ฏปๆ ผๅผๆนไพฟ่ฐ่ฏ || ๐ง "ๅฎๅถ้ๆๅคช่ดตไบ" | ไธไธชๆไปถๅฐฑ่ฝไธบไปปๆไปฃ็ ๅบ่ชๅจ็ๆ CLI๏ผ็ป่ฟ้ช่ฏ็ 7 ้ถๆฎตๆตๆฐด็บฟ |-| โก "ๅๅๅ็ไบงไน้ดๅทฎๅไธๅ ซๅ้" | 1,741+ ๆต่ฏ็จไพ๏ผๅ จ้จๅจ็ๅฎ่ฝฏไปถไธ้ช่ฏ้่ฟ๏ผ่ฆ็ 13 ๆฌพไธปๆตๅบ็จ |+| โก "ๅๅๅ็ไบงไน้ดๅทฎๅไธๅ ซๅ้" | 1,752+ ๆต่ฏ็จไพ๏ผๅ จ้จๅจ็ๅฎ่ฝฏไปถไธ้ช่ฏ้่ฟ๏ผ่ฆ็ 13 ๆฌพไธปๆตๅบ็จ |---@@ -591,8 +591,8 @@ CLI-Anything ้็จไบไปปไฝๆไปฃ็ ๅบ็่ฝฏไปถ โโ ไธ้้ขๅ๏ผไธ้<td align="center"><strong>๐ฉ <a href="nsight-graphics/agent-harness/">Nsight Graphics CLI</a></strong></td><td>GPU ่ฐ่ฏไธๅๆ</td><td><code>cli-anything-nsight-graphics</code></td>-<td>ๅฎๆน ngfx / ngfx-capture ็ผๆ + GPU Trace ๆ่ฆ</td>-<td align="center">โ 40</td>+<td>ๅฎๆน ngfx / ngfx-capture ็ผๆ + GPU Trace ๆ่ฆ + replay ๅๆ</td>+<td align="center">โ 51</td></tr><tr><td align="center"><strong>๐ <a href="unrealinsights/agent-harness/">Unreal Insights</a></strong></td>@@ -610,11 +610,11 @@ CLI-Anything ้็จไบไปปไฝๆไปฃ็ ๅบ็่ฝฏไปถ โโ ไธ้้ขๅ๏ผไธ้</tr><tr><td align="center" colspan="4"><strong>ๅ่ฎก</strong></td>-<td align="center"><strong>โ 1,741</strong></td>+<td align="center"><strong>โ 1,752</strong></td></tr></table>-> ๅ จ้จ 1,741 ้กนๆต่ฏ **100% ้่ฟ** โโ 1,256 ้กนๅๅ ๆต่ฏ + 466 ้กน็ซฏๅฐ็ซฏๆต่ฏ + 19 ้กน Node.js ๆต่ฏใ+> ๅ จ้จ 1,752 ้กนๆต่ฏ **100% ้่ฟ** โโ 1,266 ้กนๅๅ ๆต่ฏ + 467 ้กน็ซฏๅฐ็ซฏๆต่ฏ + 19 ้กน Node.js ๆต่ฏใ---@@ -644,11 +644,11 @@ zoom 22 passed โ (22 unit + 0 e2e)drawio 138 passed โ (116 unit + 22 e2e)anygen 50 passed โ (40 unit + 10 e2e)lldb 27 passed โ (23 unit + 4 e2e)-nsight-graphics 40 passed โ (36 unit + 4 e2e)+nsight-graphics 51 passed โ (46 unit/CLI + 5 local e2e)unrealinsights 50 passed โ (49 unit + 1 e2e, 9 backend-gated e2e skipped)sketch 19 passed โ (19 jest, Node.js)โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-TOTAL 1,741 passed โ 100% pass rate+TOTAL 1,752 passed โ 100% pass rate```---@@ -715,7 +715,7 @@ cli-anything/โโโ ๐ zoom/agent-harness/ # Zoom CLI๏ผ22 ้กนๆต่ฏ๏ผโโโ ๐ drawio/agent-harness/ # Draw.io CLI๏ผ138 ้กนๆต่ฏ๏ผโโโ โจ anygen/agent-harness/ # AnyGen CLI๏ผ50 ้กนๆต่ฏ๏ผ-โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI๏ผ40 ้กนๆต่ฏ๏ผ+โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI๏ผ51 ้กนๆต่ฏ๏ผโโโ ๐ lldb/agent-harness/ # LLDB CLI๏ผ27 ้กนๆต่ฏ๏ผโโโ ๐ unrealinsights/agent-harness/ # Unreal Insights CLI๏ผ50 ้กนๆต่ฏ๏ผโโโ ๐จ sketch/agent-harness/ # Sketch CLI๏ผ19 ้กนๆต่ฏ๏ผNode.js๏ผ@@ -954,7 +954,7 @@ MIT License โ ๅฏ่ช็ฑไฝฟ็จใไฟฎๆนๅๅๅใ**CLI-Anything** โ *ไธ่กๅฝไปค๏ผ่ฎฉไปปไฝ่ฝฏไปถๆไธบ Agent ็ๅ็ๅทฅๅ ทใ*-<sub>ไธบ AI Agent ๆถไปฃ่็ | 13 ๆฌพไธไธ่ฝฏไปถๅฎๆต | 1,741 ้กนๆต่ฏๅ จ้จ้่ฟ</sub>+<sub>ไธบ AI Agent ๆถไปฃ่็ | 13 ๆฌพไธไธ่ฝฏไปถๅฎๆต | 1,752 ้กนๆต่ฏๅ จ้จ้่ฟ</sub><br>diff --git a/nsight-graphics/agent-harness/HARNESS.md b/nsight-graphics/agent-harness/HARNESS.mdindex c6482b997..aafd93425 100644--- a/nsight-graphics/agent-harness/HARNESS.md+++ b/nsight-graphics/agent-harness/HARNESS.md@@ -9,12 +9,14 @@ V1 is intentionally **orchestration-focused**:- installation and capability probing- detached launch and PID attach via `ngfx.exe`-- Frame Debugger capture+- Graphics Capture / OpenGL Frame Debugger capture- GPU Trace capture and auto-export+- replay metadata/log/screenshot/perf-report analysis for existing captures- Generate C++ Capture-It does **not** attempt RenderDoc-style offline object inspection of pipeline-state, shaders, textures, or resources.+Replay analysis uses official `ngfx-replay` outputs. It does **not** attempt+RenderDoc-style offline object inspection of pipeline state, shaders, textures,+or resources.## Architecture@@ -34,6 +36,7 @@ agent-harness/โ โโโ launch.pyโ โโโ frame.pyโ โโโ gpu_trace.py+ โ โโโ replay.pyโ โโโ cpp_capture.pyโโโ utils/โ โโโ nsight_graphics_backend.py@@ -56,6 +59,7 @@ agent-harness/| `launch` | `detached`, `attach` || `frame` | `capture` || `gpu-trace` | `capture`, `summarize` |+| `replay` | `analyze` || `cpp` | `capture` |## Backend Strategy@@ -65,20 +69,27 @@ agent-harness/2. Detect compatibility mode:- `unified`: legacy `ngfx.exe` activity-driven CLI- `split`: modern `ngfx-capture` / `ngfx-replay` present+ - `unified+split`: both tool families are present3. Prefer `ngfx.exe` when available, because it covers launch, attach,GPU Trace, and Generate C++ Capture.-4. Use version-tolerant artifact discovery by diffing the output directory- before and after a command instead of depending on one filename.+4. Create explicit output directories before invoking `ngfx.exe`, then use+ version-tolerant artifact discovery by diffing the output directory before+ and after a command instead of depending on one filename.+5. Use `ngfx-replay` for analysis of existing `.ngfx-capture` files. Accept+ `.ngfx-gputrace` inputs only to report clear compatibility diagnostics,+ because `ngfx-replay` documents its filename input as a Graphics Capture file+ and can reject standalone GPU Trace files with `Invalid file header`.## Testing Strategy- `test_core.py`: mock-based unit tests for discovery, parsing, command- construction, error handling, and CLI help.+ construction, output directory preparation, GPU Trace summary parsing, error+ handling, and CLI help.- `test_full_e2e.py`: conditional tests using a real Nsight installation and auser-supplied test executable via environment variables.## Notes- V1 is Windows-first and only claims verified support on Windows hosts.-- Split replay binaries are detected and reported by `doctor info`, but replay- helper commands are intentionally deferred.+- Replay helpers are metadata/log/perf oriented and do not claim deep+ shader/pipeline/texture/resource inspection.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.mdindex 81fce044a..3d995cf69 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.md+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.md@@ -7,12 +7,19 @@ terminal:- installation and capability probing- detached launch and PID attach-- Frame Debugger capture+- Graphics Capture / OpenGL Frame Debugger capture- GPU Trace capture, auto-export, and summary generation+- replay analysis for existing `.ngfx-capture` files, plus explicit+ `.ngfx-gputrace` compatibility diagnostics- Generate C++ Capture-It does not provide RenderDoc-style offline inspection of shaders, pipeline-state, textures, or resources.+Replay analysis is based on official `ngfx-replay` metadata, logs,+screenshot, and performance report outputs. `ngfx-replay` documents its input as+a Graphics Capture file; on Nsight Graphics 2026.1.0, standalone+`.ngfx-gputrace` files may report `Invalid file header` instead of metadata.+Use `gpu-trace summarize` for GPU Trace exported table analysis. This harness+does not provide RenderDoc-style offline inspection of shaders, pipeline state,+textures, or resources.## Installation@@ -21,6 +28,9 @@ cd nsight-graphics/agent-harnesspip install -e .```+Use that editable install command whenever this repo moved or a previous+`cli-anything-nsight-graphics` entry point points at an old worktree.+## Prerequisites- Windows host recommended and verified for v1@@ -78,6 +88,10 @@ cli-anything-nsight-graphics --output-dir D:\captures frame capture ^--wait-frames 10```+Use `--activity "OpenGL Frame Debugger"` for OpenGL-specific frame debugger+captures. On current Nsight Graphics builds, the default frame capture activity+is `Graphics Capture`.+### Collect a GPU trace```bash@@ -101,6 +115,22 @@ parent output root that contains multiple exports. When multiple complete GPUTrace exports are present, the CLI summarizes the newest complete exportdirectory so stale tables are not mixed into the result.+### Analyze an existing capture++```bash+cli-anything-nsight-graphics --json replay analyze ^+ --capture-file D:\captures\frame.ngfx-capture ^+ --output-dir D:\analysis+```++By default, `replay analyze` exports metadata, captured logs, captured error+logs, and a one-loop replay performance report. Add `--screenshot` to also+export the embedded metadata screenshot, or pass explicit switches such as+`--metadata --logs` to run only those analysis surfaces. The JSON response also+includes structured `metadata.summary`, `metadata.functions`, `metadata.objects`,+`logs.error_line_count`, and `analysis.highlights` / `analysis.warnings` fields+so callers can triage without parsing artifact files themselves.+### Generate a C++ capture```bash@@ -119,7 +149,7 @@ cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^| `--debug` | Include traceback details in errors || `--nsight-path` | Explicit install directory or executable to use when multiple Nsight versions are installed || `--project` | Nsight Graphics project file |-| `--output-dir` | Output directory for captures or exported artifacts |+| `--output-dir` | Output directory for captures or exported artifacts; explicit directories are created before invoking Nsight || `--hostname` | Remote host for Nsight launch/attach || `--platform` | Target platform string passed to Nsight |@@ -131,9 +161,10 @@ cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^| `doctor` | `versions` | List detected Nsight Graphics installs and show which one is selected || `launch` | `detached` | Launch a target under Nsight without blocking the CLI || `launch` | `attach` | Attach Nsight to a running PID |-| `frame` | `capture` | Trigger a Frame Debugger capture |+| `frame` | `capture` | Trigger a Graphics Capture or OpenGL Frame Debugger capture || `gpu-trace` | `capture` | Trigger a GPU Trace capture and optionally summarize the exported result || `gpu-trace` | `summarize` | Summarize an existing GPU Trace export directory |+| `replay` | `analyze` | Analyze an existing `.ngfx-capture` with `ngfx-replay`; report clear compatibility diagnostics for `.ngfx-gputrace` || `cpp` | `capture` | Trigger Generate C++ Capture |## JSON Output@@ -160,40 +191,60 @@ When `gpu-trace capture --summarize` is used, the result also includes:- `summary.frame_time_ms`- `summary.fps_estimate`- `summary.metrics`+- `summary.tables`+- `summary.metric_inventory`- `summary.top_events`+- `summary.top_level_events`+- `summary.analysis.frame_budget`+- `summary.analysis.workload`+- `summary.analysis.throughput`+- `summary.analysis.bottlenecks`+- `summary.analysis.recommendations`+- `summary.analysis.warnings`- `summary.highlights`+When `replay analyze` is used, the result includes:++- `capture_file`+- `capture_type`+- `replay_executable`+- `requested_outputs`+- `command_results`+- `metadata.present`+- `metadata.summary`+- `metadata.functions`+- `metadata.objects`+- `logs.status`+- `logs.error_line_count`+- `logs.error_summary`+- `perf_report.present`+- `screenshot.present`+- `analysis.summary`+- `analysis.highlights`+- `analysis.warnings`+## Environment Variables| Variable | Purpose ||----------|---------|| `NSIGHT_GRAPHICS_PATH` | Override executable discovery |-| `NSIGHT_GRAPHICS_TEST_EXE` | Shared fallback E2E target executable |-| `NSIGHT_GRAPHICS_TEST_ARGS` | Shared fallback E2E target arguments |-| `NSIGHT_GRAPHICS_TEST_WORKDIR` | Shared fallback E2E working directory |-| `NSIGHT_GRAPHICS_FRAME_TEST_EXE` | Optional frame-capture-specific executable override |-| `NSIGHT_GRAPHICS_FRAME_TEST_ARGS` | Optional frame-capture-specific args override |-| `NSIGHT_GRAPHICS_FRAME_TEST_WORKDIR` | Optional frame-capture-specific workdir override |-| `NSIGHT_GRAPHICS_GPU_TRACE_TEST_EXE` | Optional GPU Trace-specific executable override |-| `NSIGHT_GRAPHICS_GPU_TRACE_TEST_ARGS` | Optional GPU Trace-specific args override |-| `NSIGHT_GRAPHICS_GPU_TRACE_TEST_WORKDIR` | Optional GPU Trace-specific workdir override |-| `NSIGHT_GRAPHICS_CPP_TEST_EXE` | Optional C++ Capture-specific executable override |-| `NSIGHT_GRAPHICS_CPP_TEST_ARGS` | Optional C++ Capture-specific args override |-| `NSIGHT_GRAPHICS_CPP_TEST_WORKDIR` | Optional C++ Capture-specific workdir override |+| `NSIGHT_GRAPHICS_TEST_EXE` | E2E target executable |+| `NSIGHT_GRAPHICS_TEST_ARGS` | Optional E2E target arguments |+| `NSIGHT_GRAPHICS_TEST_WORKDIR` | Optional E2E working directory |+| `NSIGHT_GRAPHICS_TEST_CAPTURE_FILE` | Optional existing `.ngfx-capture` for replay E2E |## E2E Test PrerequisitesThe E2E suite assumes:- Nsight Graphics is installed and discoverable-- either `NSIGHT_GRAPHICS_TEST_EXE` or the activity-specific `NSIGHT_GRAPHICS_*_TEST_EXE`- overrides point to graphics workloads that Nsight can launch for that activity-- optional args/workdir are provided if the chosen test target requires them+- `NSIGHT_GRAPHICS_TEST_EXE` points to a graphics workload that Nsight can+ launch or capture+- `NSIGHT_GRAPHICS_TEST_CAPTURE_FILE` points to an existing capture when replay+ analysis E2E should run+- optional args/workdir are provided if the test target requires themTypical examples include `vkcube.exe`, game samples, or internal engine demos.-Different activities may require different targets on newer Nsight builds, so-the E2E suite accepts per-activity overrides instead of assuming one executable-works for frame capture, GPU Trace, and C++ Capture.## Multiple Installations@@ -230,8 +281,13 @@ That gives you:- the `.ngfx-gputrace` artifact- exported `FRAME.xls`, `GPUTRACE_FRAME.xls`, and `D3DPERF_EVENTS.xls`-- a parsed summary from the newest complete export directory, with frame time,- estimated FPS, selected counters, and top GPU events+- a parsed summary from the newly exported complete table set, with frame time,+ estimated FPS, selected counters, table inventory, metric inventory, top GPU+ events, workload classification, throughput ranking, and warning fields for+ empty event/regime tables++If the capture command fails or does not create a complete new export table set,+the CLI refuses to summarize old tables from the output root.## Human + AI Workflowdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.pyindex ec369d319..8dd32f5e4 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.py@@ -1,3 +1,3 @@"""Nsight Graphics CLI harness package."""-__version__ = "0.1.0"+__version__ = "0.2.0"diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.pyindex 6cc8b13d6..79ed93f8a 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.py@@ -22,6 +22,7 @@ def capture_cpp(wait_hotkey: bool,) -> dict:"""Run Generate C++ Capture."""+ output_dir = backend.prepare_output_dir(output_dir)report = backend.probe_installation(nsight_path=nsight_path)binaries = report["binaries"]backend.require_binary(binaries, "ngfx")diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.pyindex e3f1e5aa9..4cf8f30bc 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.py@@ -6,16 +6,55 @@ from typing import Sequencefrom cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+GRAPHICS_CAPTURE_ACTIVITY = "Graphics Capture"+LEGACY_FRAME_ACTIVITY = "Frame Debugger"+OPENGL_FRAME_ACTIVITY = "OpenGL Frame Debugger"-def _build_unified_frame_args(++def _select_frame_activity(report: dict, requested_activity: str | None) -> str:+ """Choose a frame capture activity that matches the installed Nsight version."""+ if requested_activity:+ return requested_activity++ supported = set(report.get("supported_activities") or [])+ for candidate in (GRAPHICS_CAPTURE_ACTIVITY, LEGACY_FRAME_ACTIVITY, OPENGL_FRAME_ACTIVITY):+ if candidate in supported:+ return candidate+ return GRAPHICS_CAPTURE_ACTIVITY+++def _activity_options(report: dict, activity: str) -> set[str]:+ """Return known options for a parsed ngfx activity."""+ return set((report.get("activity_options") or {}).get(activity, []))+++def _append_if_supported(+ extra_args: list[str],+ *,+ report: dict,activity: str,+ option: str,+ enabled: bool,+) -> None:+ """Append an option only when this Nsight activity advertises it."""+ if not enabled:+ return+ if option not in _activity_options(report, activity):+ raise RuntimeError(f"{option} is not supported by Nsight activity '{activity}'.")+ extra_args.append(option)+++def _build_unified_frame_args(*,+ report: dict,+ activity: str,wait_seconds: int | None,wait_frames: int | None,wait_hotkey: bool,export_frame_perf_metrics: bool,export_range_perf_metrics: bool,) -> list[str]:+ """Map the harness trigger vocabulary onto the selected ngfx activity."""backend.ensure_exactly_one("frame trigger",{@@ -25,34 +64,38 @@ def _build_unified_frame_args(},)- normalized = activity.lower()- if normalized == "graphics capture":- if export_frame_perf_metrics or export_range_perf_metrics:- raise RuntimeError(- "Frame performance export flags are not supported by Graphics Capture mode on modern ngfx.exe builds."- )-- extra_args = ["--frame-count", "1"]+ options = _activity_options(report, activity)+ extra_args: list[str] = []+ if activity == GRAPHICS_CAPTURE_ACTIVITY or "--frame-index" in options:+ extra_args.extend(["--frame-count", "1"])if wait_seconds is not None:extra_args.extend(["--elapsed-time", str(wait_seconds)])elif wait_frames is not None:extra_args.extend(["--frame-index", str(wait_frames)])else:extra_args.append("--hotkey-capture")- return extra_args-- extra_args: list[str] = []- if wait_seconds is not None:- extra_args.extend(["--wait-seconds", str(wait_seconds)])- elif wait_frames is not None:- extra_args.extend(["--wait-frames", str(wait_frames)])else:- extra_args.append("--wait-hotkey")+ if wait_seconds is not None:+ extra_args.extend(["--wait-seconds", str(wait_seconds)])+ elif wait_frames is not None:+ extra_args.extend(["--wait-frames", str(wait_frames)])+ else:+ extra_args.append("--wait-hotkey")- if export_frame_perf_metrics:- extra_args.append("--export-frame-perf-metrics")- if export_range_perf_metrics:- extra_args.append("--export-range-perf-metrics")+ _append_if_supported(+ extra_args,+ report=report,+ activity=activity,+ option="--export-frame-perf-metrics",+ enabled=export_frame_perf_metrics,+ )+ _append_if_supported(+ extra_args,+ report=report,+ activity=activity,+ option="--export-range-perf-metrics",+ enabled=export_range_perf_metrics,+ )return extra_args@@ -67,6 +110,7 @@ def capture_frame(working_dir: str | None,args: Sequence[str],envs: Sequence[str],+ activity: str | None,wait_seconds: int | None,wait_frames: int | None,wait_hotkey: bool,@@ -74,15 +118,20 @@ def capture_frame(export_range_perf_metrics: bool,) -> dict:"""Run a Frame Debugger capture."""+ output_dir = backend.prepare_output_dir(output_dir)report = backend.probe_installation(nsight_path=nsight_path)binaries = report["binaries"]- activity = backend.resolve_activity_name(report, "Frame Debugger")- artifact_roots = backend.activity_artifact_roots(activity, output_dir)+ selected_activity = _select_frame_activity(report, activity)+ artifact_roots = backend._dedupe(+ backend.activity_artifact_roots(selected_activity, output_dir)+ + backend.activity_artifact_roots(selected_activity, None)+ )if binaries.get("ngfx"):backend.require_launch_target(project=project, exe=exe)extra_args = _build_unified_frame_args(- activity,+ report=report,+ activity=selected_activity,wait_seconds=wait_seconds,wait_frames=wait_frames,wait_hotkey=wait_hotkey,@@ -92,7 +141,7 @@ def capture_frame(command = backend.build_unified_command(binaries,- activity=activity,+ activity=selected_activity,project=project,output_dir=output_dir,hostname=hostname,@@ -110,9 +159,14 @@ def capture_frame()result["tool_mode"] = "unified"elif binaries.get("ngfx_capture"):+ if selected_activity != GRAPHICS_CAPTURE_ACTIVITY:+ raise RuntimeError(+ f"Activity '{selected_activity}' requires ngfx.exe; split ngfx-capture "+ "mode supports Graphics Capture only."+ )if project:raise RuntimeError(- "Project-driven frame capture fallback requires ngfx.exe; "+ "Project-driven graphics capture fallback requires ngfx.exe; ""split ngfx-capture mode currently needs --exe.")if export_frame_perf_metrics or export_range_perf_metrics:@@ -142,6 +196,6 @@ def capture_frame(else:raise RuntimeError(backend.INSTALL_INSTRUCTIONS)- result["activity"] = activity+ result["activity"] = selected_activityresult["output_dir"] = output_dir or backend.default_output_dir()return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.pyindex ad26c8fe7..9ddddd8a5 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections import Counterimport csvfrom pathlib import Pathfrom typing import Any, Sequence@@ -28,9 +29,17 @@ REQUIRED_EXPORT_FILES = ()-def _find_export_dir(output_dir: str) -> tuple[str, dict[str, str]]:+def _find_export_dir(+ output_dir: str,+ *,+ artifact_paths: Sequence[str] | None = None,+) -> tuple[str, dict[str, str]]:"""Pick the newest export directory containing a complete GPU Trace export."""output_root = Path(output_dir).resolve()+ artifact_path_set = None+ if artifact_paths is not None:+ artifact_path_set = {str(Path(path).resolve()) for path in artifact_paths}+matches_by_name = {name: sorted(output_root.rglob(name))for name in (*REQUIRED_EXPORT_FILES, "GPUTRACE_REGIMES.xls")@@ -46,6 +55,8 @@ def _find_export_dir(output_dir: str) -> tuple[str, dict[str, str]]:required_paths = [directory / name for name in REQUIRED_EXPORT_FILES]if not all(path.is_file() for path in required_paths):continue+ if artifact_path_set is not None and not all(str(path.resolve()) in artifact_path_set for path in required_paths):+ continuenewest_required_mtime = max(path.stat().st_mtime_ns for path in required_paths)files = {"frame": str(directory / "FRAME.xls"),@@ -65,6 +76,13 @@ def _find_export_dir(output_dir: str) -> tuple[str, dict[str, str]]:)return str(export_dir), files+ if artifact_path_set is not None:+ raise RuntimeError(+ "GPU Trace capture finished without a complete newly exported table set "+ "(FRAME.xls, GPUTRACE_FRAME.xls, D3DPERF_EVENTS.xls). Refusing to "+ "summarize stale export data."+ )+missing = [namefor name in REQUIRED_EXPORT_FILES@@ -108,6 +126,19 @@ def _read_event_rows(path: str) -> list[dict[str, str]]:return rows+def _read_table_rows(path: str | None) -> tuple[list[str], list[dict[str, str]]]:+ """Read a generic tab-separated table."""+ if not path:+ return [], []+ with open(path, "r", encoding="utf-8-sig", errors="replace", newline="") as handle:+ reader = csv.DictReader(handle, delimiter="\t")+ rows = [+ {str(key): (value or "").strip() for key, value in row.items() if key is not None}+ for row in reader+ ]+ return list(reader.fieldnames or []), rows++def _safe_float(value: str | None) -> float | None:"""Convert a string to float when possible."""if value is None:@@ -125,6 +156,91 @@ def _safe_int(value: float | None) -> int | None:return int(round(value))+def _metric_unit(metric_name: str) -> str:+ """Classify a metric suffix into a compact unit family."""+ lowered = metric_name.lower()+ if lowered.endswith(".avg.pct_of_peak_sustained_elapsed"):+ return "pct_of_peak"+ if lowered.endswith(".pct"):+ return "percent"+ if lowered.endswith(".sum.per_second"):+ return "per_second"+ if lowered.endswith(".sum"):+ return "count"+ if lowered.endswith(".avg.per_cycle_elapsed"):+ return "per_cycle"+ if lowered.endswith(".avg.peak_sustained"):+ return "peak_sustained"+ if ".avg." in lowered:+ return "average"+ return "other"+++def _metric_category(metric_name: str) -> str:+ """Classify a metric by GPU subsystem using stable metric prefixes."""+ lowered = metric_name.lower()+ if "pcie__" in lowered:+ return "pcie"+ if "dramc__" in lowered:+ return "dram"+ if "lts__" in lowered:+ return "l2_cache"+ if "l1tex__" in lowered:+ return "l1_texture"+ if "sm__" in lowered or "smsp__" in lowered or "tpc__" in lowered:+ return "shader_core"+ if "crop__" in lowered or "zrop__" in lowered or "raster__" in lowered or "prop__" in lowered or "vaf__" in lowered:+ return "raster_rop"+ if "fe__" in lowered:+ return "frontend"+ if "gr__" in lowered or "gpu__" in lowered:+ return "graphics_engine"+ return "other"+++def _numeric_metrics(metrics: dict[str, str]) -> list[dict[str, Any]]:+ """Return metrics with parsed numeric values and basic classification."""+ parsed: list[dict[str, Any]] = []+ for key, value in metrics.items():+ numeric = _safe_float(value)+ if numeric is None:+ continue+ parsed.append(+ {+ "metric": key,+ "value": numeric,+ "unit": _metric_unit(key),+ "category": _metric_category(key),+ }+ )+ return parsed+++def _top_numeric_metrics(+ parsed_metrics: list[dict[str, Any]],+ *,+ unit: str,+ limit: int,+) -> list[dict[str, Any]]:+ """Return top numeric metrics for a unit family."""+ candidates = [item for item in parsed_metrics if item["unit"] == unit]+ candidates.sort(key=lambda item: abs(item["value"]), reverse=True)+ return candidates[:limit]+++def _metric_inventory(metrics: dict[str, str], top_n: int) -> dict[str, Any]:+ """Summarize the exported GPU Trace metric table."""+ parsed = _numeric_metrics(metrics)+ return {+ "metric_count": len(metrics),+ "numeric_metric_count": len(parsed),+ "unit_counts": dict(Counter(item["unit"] for item in parsed)),+ "category_counts": dict(Counter(item["category"] for item in parsed)),+ "top_pct_of_peak_metrics": _top_numeric_metrics(parsed, unit="pct_of_peak", limit=top_n),+ "top_count_metrics": _top_numeric_metrics(parsed, unit="count", limit=top_n),+ }++def _pick_metric(metrics: dict[str, str], needle: str) -> float | None:"""Find the first metric whose key ends with the requested suffix."""for key, value in metrics.items():@@ -138,6 +254,214 @@ def _event_depth(event_text: str) -> int:return len(event_text) - len(event_text.lstrip(" "))+def _table_file_info(path: str | None) -> dict[str, Any]:+ """Return compact file metadata for an optional table path."""+ if not path:+ return {"path": None, "present": False, "size": 0}+ table_path = Path(path)+ return {+ "path": str(table_path),+ "present": table_path.is_file(),+ "size": table_path.stat().st_size if table_path.is_file() else 0,+ }+++def _table_inventory(+ *,+ files: dict[str, str | None],+ frame_data: dict[str, str],+ trace_metrics: dict[str, str],+ event_rows: list[dict[str, str]],+ regime_columns: list[str],+ regime_rows: list[dict[str, str]],+) -> dict[str, Any]:+ """Describe exported tables and how much usable data they contain."""+ frame_info = _table_file_info(files["frame"])+ frame_info.update({"row_count": len(frame_data), "metric_count": len(frame_data)})++ trace_info = _table_file_info(files["trace_frame"])+ trace_info.update({"row_count": len(trace_metrics), "metric_count": len(trace_metrics)})++ events_info = _table_file_info(files["events"])+ events_info.update({"row_count": len(event_rows), "column_count": 2})++ regimes_info = _table_file_info(files.get("regimes"))+ regimes_info.update(+ {+ "row_count": len(regime_rows),+ "column_count": len(regime_columns),+ "metric_column_count": max(len(regime_columns) - 1, 0),+ }+ )++ return {+ "frame": frame_info,+ "trace_frame": trace_info,+ "events": events_info,+ "regimes": regimes_info,+ }+++def _frame_budget(frame_time_ms: float | None, fps_estimate: float | None) -> dict[str, Any]:+ """Classify frame time against common budgets."""+ if frame_time_ms is None:+ return {+ "frame_time_ms": None,+ "fps_estimate": fps_estimate,+ "bucket": "unknown",+ "over_60fps_budget_ms": None,+ "over_30fps_budget_ms": None,+ }+ return {+ "frame_time_ms": frame_time_ms,+ "fps_estimate": fps_estimate,+ "bucket": "over_30fps_budget" if frame_time_ms > 33.3 else "over_60fps_budget" if frame_time_ms > 16.7 else "within_60fps_budget",+ "over_60fps_budget_ms": max(frame_time_ms - 16.6667, 0.0),+ "over_30fps_budget_ms": max(frame_time_ms - 33.3333, 0.0),+ }+++def _workload_classification(metrics: dict[str, float | int | None]) -> dict[str, Any]:+ """Classify draw/dispatch balance."""+ draw_count = metrics.get("draw_count")+ dispatch_count = metrics.get("dispatch_count")+ draw_count = draw_count if isinstance(draw_count, int) else 0+ dispatch_count = dispatch_count if isinstance(dispatch_count, int) else 0++ if dispatch_count > max(draw_count * 2, 500):+ classification = "compute_heavy"+ elif draw_count > max(dispatch_count * 2, 100):+ classification = "graphics_heavy"+ elif draw_count or dispatch_count:+ classification = "mixed"+ else:+ classification = "unknown"++ return {+ "classification": classification,+ "draw_count": draw_count,+ "dispatch_count": dispatch_count,+ }+++def _throughput_units(metrics: dict[str, float | int | None]) -> list[dict[str, Any]]:+ """Rank selected throughput metrics by utilization."""+ units = [+ ("graphics_engine", "graphics_engine_active_pct"),+ ("shader_sm", "sm_throughput_pct"),+ ("l1_texture", "l1tex_throughput_pct"),+ ("l2_cache", "l2_throughput_pct"),+ ("dram", "dram_throughput_pct"),+ ("pcie", "pcie_throughput_pct"),+ ("sync_compute", "compute_queue_sync_active_pct"),+ ("async_compute", "compute_queue_async_active_pct"),+ ]+ ranked = [+ {"name": name, "metric": metric_name, "pct": value}+ for name, metric_name in units+ if isinstance((value := metrics.get(metric_name)), float)+ ]+ ranked.sort(key=lambda item: item["pct"], reverse=True)+ return ranked+++def _build_trace_analysis(+ *,+ frame_time_ms: float | None,+ fps_estimate: float | None,+ metrics: dict[str, float | int | None],+ ranked_events: list[dict[str, Any]],+ table_inventory: dict[str, Any],+) -> dict[str, Any]:+ """Build higher-level GPU Trace diagnostics from exported tables."""+ budget = _frame_budget(frame_time_ms, fps_estimate)+ workload = _workload_classification(metrics)+ throughput_units = _throughput_units(metrics)+ dominant_unit = throughput_units[0] if throughput_units else None+ event_depths = [item["depth"] for item in ranked_events]++ bottlenecks: list[dict[str, Any]] = []+ recommendations: list[str] = []+ warnings: list[str] = []+ highlights: list[str] = []++ if budget["bucket"] == "over_30fps_budget":+ bottlenecks.append(+ {+ "id": "frame_budget_30fps",+ "severity": "high",+ "value": frame_time_ms,+ "message": "GPU frame time exceeds a 30 FPS budget.",+ }+ )+ recommendations.append("Start from the longest GPU events and reduce work on the critical frame path.")+ elif budget["bucket"] == "over_60fps_budget":+ bottlenecks.append(+ {+ "id": "frame_budget_60fps",+ "severity": "medium",+ "value": frame_time_ms,+ "message": "GPU frame time exceeds a 60 FPS budget.",+ }+ )++ for item in throughput_units:+ pct = item["pct"]+ if pct >= 80.0:+ severity = "high"+ elif pct >= 60.0:+ severity = "medium"+ else:+ continue+ bottlenecks.append(+ {+ "id": f"high_{item['name']}_throughput",+ "severity": severity,+ "value": pct,+ "message": f"{item['name']} utilization is {pct:.1f}% of peak sustained elapsed.",+ }+ )++ if workload["classification"] == "compute_heavy":+ recommendations.append("Dispatch count dominates draw count; inspect compute workloads and synchronization.")+ if any(item["name"] == "dram" and item["pct"] >= 60.0 for item in throughput_units):+ recommendations.append("DRAM throughput is high; inspect bandwidth, render target size, and cache locality.")+ if any(item["name"] == "pcie" and item["pct"] >= 60.0 for item in throughput_units):+ recommendations.append("PCIe throughput is high; inspect uploads, readbacks, and host-visible buffer traffic.")+ if any(item["name"] == "shader_sm" and item["pct"] >= 60.0 for item in throughput_units):+ recommendations.append("SM throughput is high; inspect expensive shaders and dispatch/draw ranges.")+ if not ranked_events:+ warnings.append("D3DPERF_EVENTS.xls contains no timed GPU event rows; add markers/NVTX ranges for pass-level attribution.")+ if table_inventory["regimes"]["present"] and table_inventory["regimes"]["row_count"] == 0:+ warnings.append("GPUTRACE_REGIMES.xls contains headers but no per-regime rows.")++ if dominant_unit:+ highlights.append(f"Dominant throughput unit: {dominant_unit['name']} at {dominant_unit['pct']:.3f}%.")+ if workload["classification"] != "unknown":+ highlights.append(+ f"Workload classification: {workload['classification']} "+ f"({workload['draw_count']} draws, {workload['dispatch_count']} dispatches)."+ )++ return {+ "frame_budget": budget,+ "workload": workload,+ "throughput": {+ "dominant_unit": dominant_unit,+ "top_units": throughput_units,+ },+ "event_summary": {+ "event_count": len(ranked_events),+ "top_level_event_count": sum(1 for item in ranked_events if item["depth"] == 0),+ "max_depth": max(event_depths) if event_depths else 0,+ },+ "bottlenecks": bottlenecks,+ "recommendations": recommendations,+ "warnings": warnings,+ "highlights": highlights,+ }++def _make_highlights(frame_time_ms: float | None,metrics: dict[str, float | int | None],@@ -174,10 +498,15 @@ def _make_highlights(return highlights-def summarize_export_dir(output_dir: str, top_n: int = 10) -> dict[str, Any]:+def summarize_export_dir(+ output_dir: str,+ top_n: int = 10,+ *,+ artifact_paths: Sequence[str] | None = None,+) -> dict[str, Any]:"""Summarize exported GPU Trace tables from an output directory."""output_root = str(Path(output_dir).resolve())- export_dir, files = _find_export_dir(output_root)+ export_dir, files = _find_export_dir(output_root, artifact_paths=artifact_paths)frame_path = files["frame"]trace_frame_path = files["trace_frame"]events_path = files["events"]@@ -186,6 +515,7 @@ def summarize_export_dir(output_dir: str, top_n: int = 10) -> dict[str, Any]:frame_data = _read_kv_file(frame_path)trace_metrics = _read_kv_file(trace_frame_path)event_rows = _read_event_rows(events_path)+ regime_columns, regime_rows = _read_table_rows(regimes_path)frame_time_ms = _safe_float(frame_data.get("GPU frame time"))fps_estimate = (1000.0 / frame_time_ms) if frame_time_ms and frame_time_ms > 0 else None@@ -216,18 +546,37 @@ def summarize_export_dir(output_dir: str, top_n: int = 10) -> dict[str, Any]:ranked_events.sort(key=lambda item: item["time_ms"], reverse=True)top_events = ranked_events[:top_n]- top_level_events = [item for item in top_events if item["depth"] == 0]+ top_level_events = [item for item in ranked_events if item["depth"] == 0][:top_n]+ tables = _table_inventory(+ files=files,+ frame_data=frame_data,+ trace_metrics=trace_metrics,+ event_rows=event_rows,+ regime_columns=regime_columns,+ regime_rows=regime_rows,+ )+ analysis = _build_trace_analysis(+ frame_time_ms=frame_time_ms,+ fps_estimate=fps_estimate,+ metrics=summary_metrics,+ ranked_events=ranked_events,+ table_inventory=tables,+ )+ highlights = _make_highlights(frame_time_ms, summary_metrics, top_events) + analysis["highlights"]return {"output_dir": export_dir,"search_root": output_root,"files": files,+ "tables": tables,"frame_time_ms": frame_time_ms,"fps_estimate": fps_estimate,"metrics": summary_metrics,+ "metric_inventory": _metric_inventory(trace_metrics, top_n),"top_events": top_events,"top_level_events": top_level_events,- "highlights": _make_highlights(frame_time_ms, summary_metrics, top_events),+ "highlights": highlights,+ "analysis": analysis,}@@ -258,6 +607,7 @@ def capture_trace(summary_limit: int = 10,) -> dict:"""Run a GPU Trace capture."""+ output_dir = backend.prepare_output_dir(output_dir)report = backend.probe_installation(nsight_path=nsight_path)binaries = report["binaries"]backend.require_binary(binaries, "ngfx")@@ -337,5 +687,15 @@ def capture_trace(result["auto_export"] = auto_exportif summarize:- result["summary"] = summarize_export_dir(result["output_dir"], top_n=summary_limit)+ if not result.get("ok"):+ raise RuntimeError(+ "GPU Trace capture failed; refusing to summarize stale export tables. "+ f"stderr: {result.get('stderr') or '<empty>'}"+ )+ artifact_paths = [item["path"] for item in result.get("artifacts", [])]+ result["summary"] = summarize_export_dir(+ result["output_dir"],+ top_n=summary_limit,+ artifact_paths=artifact_paths,+ )return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/replay.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/replay.pynew file mode 100644index 000000000..c468da58a--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/replay.py@@ -0,0 +1,568 @@+"""Replay analysis for existing Nsight Graphics capture files."""++from __future__ import annotations++import json+from collections import Counter+from pathlib import Path+from typing import Any++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend++SUPPORTED_CAPTURE_SUFFIXES = {+ ".ngfx-capture": "graphics_capture",+ ".ngfx-gputrace": "gpu_trace",+}+++def _capture_type(path: Path) -> str:+ """Return the supported capture type for a file path."""+ suffix = path.suffix.lower()+ capture_type = SUPPORTED_CAPTURE_SUFFIXES.get(suffix)+ if capture_type is None:+ supported = ", ".join(sorted(SUPPORTED_CAPTURE_SUFFIXES))+ raise ValueError(f"Unsupported Nsight capture file extension '{suffix}'. Expected one of: {supported}.")+ return capture_type+++def _write_stdout(path: Path, text: str) -> bool:+ """Write stdout to an artifact file when there is output."""+ if not text:+ return False+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return True+++def _read_text(path: Path) -> str:+ """Read a generated replay artifact as text, tolerating missing files."""+ if not path.is_file():+ return ""+ return path.read_text(encoding="utf-8-sig", errors="replace")+++def _load_json_artifact(path: Path) -> tuple[Any | None, str | None]:+ """Load a JSON artifact, returning a parse error instead of raising."""+ text = _read_text(path).strip()+ if not text:+ return None, None+ try:+ return json.loads(text), None+ except json.JSONDecodeError as exc:+ return None, f"{exc.msg} at line {exc.lineno}, column {exc.colno}"+++def _top_counts(counter: Counter[str], limit: int = 10) -> list[dict[str, Any]]:+ """Return top counter entries in a stable JSON shape."""+ return [{"name": name, "count": count} for name, count in counter.most_common(limit)]+++def _first_value(item: dict[str, Any], keys: tuple[str, ...]) -> Any:+ """Return the first non-empty value from a dict."""+ for key in keys:+ value = item.get(key)+ if value not in (None, ""):+ return value+ return None+++def _records_from_json(data: Any, collection_keys: tuple[str, ...]) -> list[dict[str, Any]]:+ """Extract a list of dict records from common metadata JSON shapes."""+ if isinstance(data, list):+ return [item for item in data if isinstance(item, dict)]+ if isinstance(data, dict):+ for key in collection_keys:+ value = data.get(key)+ if isinstance(value, list):+ return [item for item in value if isinstance(item, dict)]+ return []+++def _summarize_metadata(path: Path | None) -> dict[str, Any]:+ """Summarize ngfx-replay --metadata without echoing large environment blocks."""+ if path is None:+ return {"parsed": False}+ data, error = _load_json_artifact(path)+ summary: dict[str, Any] = {"parsed": isinstance(data, dict)}+ if error:+ summary["parse_error"] = error+ if not isinstance(data, dict):+ return summary++ graphics_apis = data.get("graphics_apis")+ if isinstance(graphics_apis, dict):+ api_names = sorted(str(key) for key in graphics_apis)+ elif isinstance(graphics_apis, list):+ api_names = [str(item) for item in graphics_apis]+ else:+ api_names = []++ for key in [+ "nsight_version",+ "nsight_version_build_id",+ "captured_frame",+ "primary_api",+ "primary_gpu",+ "driver_vendor",+ "driver_version",+ "os_information",+ "has_unsupported_operation",+ "non_portable",+ ]:+ if key in data:+ summary[key] = data[key]+ summary["graphics_apis"] = api_names+ summary["process_command_line_present"] = bool(data.get("process_command_line"))+ return summary+++def _summarize_objects(path: Path | None) -> dict[str, Any]:+ """Summarize object metadata from ngfx-replay --metadata-objects."""+ if path is None:+ return {"parsed": False, "total": 0, "top_types": [], "top_apis": []}+ data, error = _load_json_artifact(path)+ records = _records_from_json(data, ("objects", "resources", "items"))+ type_counts: Counter[str] = Counter()+ api_counts: Counter[str] = Counter()+ named_count = 0+ uid_count = 0+ samples: list[dict[str, Any]] = []++ for item in records:+ type_value = _first_value(item, ("type_name", "type", "object_type", "objectType", "resource_type", "resourceType"))+ api_value = _first_value(item, ("api", "graphics_api", "graphicsApi"))+ name_value = _first_value(item, ("object_name", "name", "label"))+ uid_value = _first_value(item, ("uid", "id", "object_id", "objectId"))+ if type_value is not None:+ type_counts[str(type_value)] += 1+ if api_value is not None:+ api_counts[str(api_value)] += 1+ if name_value is not None:+ named_count += 1+ if uid_value is not None:+ uid_count += 1+ if len(samples) < 5:+ samples.append(+ {+ "uid": uid_value,+ "type": type_value,+ "name": name_value,+ "api": api_value,+ }+ )++ summary: dict[str, Any] = {+ "parsed": bool(records),+ "total": len(records),+ "named_count": named_count,+ "uid_count": uid_count,+ "top_types": _top_counts(type_counts),+ "top_apis": _top_counts(api_counts),+ "samples": samples,+ }+ if error:+ summary["parse_error"] = error+ return summary+++def _summarize_functions(path: Path | None) -> dict[str, Any]:+ """Summarize function-stream metadata from ngfx-replay --metadata-functions."""+ if path is None:+ return {"parsed": False, "total": 0, "unique_count": 0, "top_functions": []}++ data, error = _load_json_artifact(path)+ records = _records_from_json(data, ("functions", "events", "items"))+ names: list[str] = []+ thread_ids: set[str] = set()+ sequence_ids: list[int] = []++ for item in records:+ name = _first_value(item, ("function_name", "name", "function", "call"))+ if name is not None:+ names.append(str(name))+ thread_id = _first_value(item, ("thread_index", "thread_id", "threadId"))+ if thread_id is not None:+ thread_ids.add(str(thread_id))+ sequence_id = _first_value(item, ("sequence_id", "sequenceId", "event_index", "eventIndex"))+ if isinstance(sequence_id, int):+ sequence_ids.append(sequence_id)++ fallback_used = False+ if not records and not error:+ lines = [line.strip() for line in _read_text(path).splitlines() if line.strip()]+ if lines:+ fallback_used = True+ names = lines++ counts = Counter(names)+ summary: dict[str, Any] = {+ "parsed": bool(records) or fallback_used,+ "total": len(names),+ "unique_count": len(counts),+ "top_functions": _top_counts(counts),+ "thread_count": len(thread_ids),+ }+ if sequence_ids:+ summary["first_sequence_id"] = min(sequence_ids)+ summary["last_sequence_id"] = max(sequence_ids)+ if error:+ summary["parse_error"] = error+ if fallback_used:+ summary["parse_mode"] = "line_fallback"+ return summary+++def _compact_result(kind: str, result: dict[str, Any], *, stdout_file: Path | None = None, output_file: Path | None = None) -> dict[str, Any]:+ """Return a JSON-friendly command result without embedding large stdout blobs."""+ payload: dict[str, Any] = {+ "kind": kind,+ "ok": result.get("ok", False),+ "returncode": result.get("returncode"),+ "command": result.get("command"),+ "stdout_bytes": len((result.get("stdout") or "").encode("utf-8")),+ "stderr": result.get("stderr") or "",+ }+ if stdout_file is not None:+ payload["stdout_file"] = str(stdout_file)+ payload["stdout_file_present"] = stdout_file.is_file() and stdout_file.stat().st_size > 0+ if output_file is not None:+ payload["output_file"] = str(output_file)+ payload["output_file_present"] = output_file.is_file() and output_file.stat().st_size > 0+ return payload+++def _run_stdout_export(+ binaries: dict[str, str | None],+ *,+ capture_file: str,+ output_file: Path,+ kind: str,+ replay_flag: str,+ timeout: int = 300,+) -> dict[str, Any]:+ """Run a metadata-style replay command and save stdout."""+ command = backend.build_replay_command(+ binaries,+ capture_file=capture_file,+ extra_args=[replay_flag],+ )+ result = backend.run_command(command, timeout=timeout)+ _write_stdout(output_file, result.get("stdout") or "")+ return _compact_result(kind, result, stdout_file=output_file)+++def _read_error_summary(path: Path, limit: int = 10) -> list[str]:+ """Read a compact captured-log error summary."""+ if not path.is_file():+ return []+ lines = [line.strip() for line in path.read_text(encoding="utf-8", errors="replace").splitlines()]+ return [line for line in lines if line][:limit]+++def _is_no_error_line(line: str) -> bool:+ """Return whether ngfx-replay is explicitly reporting an empty error set."""+ return line.strip().lower().startswith("no log messages found")+++def _summarize_logs(log_file: Path | None, errors_file: Path | None, limit: int = 10) -> dict[str, Any]:+ """Summarize captured replay logs and separate no-error markers from errors."""+ log_lines = [line.strip() for line in _read_text(log_file).splitlines() if line.strip()] if log_file else []+ raw_error_lines = [line.strip() for line in _read_text(errors_file).splitlines() if line.strip()] if errors_file else []+ if raw_error_lines and all(_is_no_error_line(line) for line in raw_error_lines):+ error_lines: list[str] = []+ status = "no_errors"+ elif raw_error_lines:+ error_lines = raw_error_lines+ status = "errors_present"+ else:+ error_lines = []+ status = "no_error_artifact" if errors_file else "not_requested"++ return {+ "log_line_count": len(log_lines),+ "error_line_count": len(error_lines),+ "error_summary": error_lines[:limit],+ "raw_error_summary": raw_error_lines[:limit],+ "status": status,+ }+++def _has_files(path: Path) -> bool:+ """Return whether a directory contains at least one non-empty file."""+ if not path.is_dir():+ return False+ for child in path.rglob("*"):+ if child.is_file() and child.stat().st_size > 0:+ return True+ return False+++def _build_analysis(+ *,+ capture_kind: str,+ metadata_requested: bool,+ logs_requested: bool,+ screenshot_requested: bool,+ perf_requested: bool,+ metadata_present: dict[str, bool],+ metadata_summary: dict[str, Any],+ object_summary: dict[str, Any],+ function_summary: dict[str, Any],+ logs_summary: dict[str, Any],+ screenshot_payload: dict[str, Any],+ perf_payload: dict[str, Any],+ command_results: list[dict[str, Any]],+) -> dict[str, Any]:+ """Build a compact human-usable diagnosis layer over replay artifacts."""+ highlights: list[str] = []+ warnings: list[str] = []++ if capture_kind == "gpu_trace":+ warnings.append(+ "ngfx-replay metadata is documented for graphics capture files; "+ ".ngfx-gputrace inputs may not produce metadata on this Nsight version."+ )++ failed = [item["kind"] for item in command_results if not item.get("ok")]+ if failed:+ warnings.append(f"Replay command failures: {', '.join(failed)}.")++ if metadata_requested:+ if metadata_summary.get("primary_api"):+ highlights.append(f"Primary API: {metadata_summary['primary_api']}.")+ if metadata_summary.get("primary_gpu"):+ highlights.append(f"Primary GPU: {metadata_summary['primary_gpu']}.")+ if object_summary.get("total"):+ highlights.append(f"Metadata objects: {object_summary['total']}.")+ if function_summary.get("total"):+ highlights.append(f"Function events: {function_summary['total']}.")+ if not any(metadata_present.values()):+ warnings.append("No replay metadata artifacts were produced.")++ if logs_requested:+ if logs_summary.get("error_line_count"):+ warnings.append(f"Captured log errors: {logs_summary['error_line_count']}.")+ elif logs_summary.get("status") == "no_errors":+ highlights.append("Captured replay logs reported no severity >= 2 errors.")++ if screenshot_requested:+ if screenshot_payload.get("present"):+ highlights.append("Metadata screenshot exported.")+ else:+ warnings.append("Metadata screenshot was requested but no non-empty image was produced.")++ if perf_requested:+ if perf_payload.get("present"):+ highlights.append("Replay performance report exported.")+ else:+ warnings.append("Performance report was requested but no non-empty report files were produced.")++ return {+ "summary": {+ "metadata_artifacts_present": metadata_present,+ "primary_api": metadata_summary.get("primary_api"),+ "primary_gpu": metadata_summary.get("primary_gpu"),+ "object_count": object_summary.get("total", 0),+ "function_event_count": function_summary.get("total", 0),+ "log_error_count": logs_summary.get("error_line_count", 0),+ "screenshot_present": screenshot_payload.get("present", False),+ "perf_report_present": perf_payload.get("present", False),+ },+ "highlights": highlights,+ "warnings": warnings,+ }+++def analyze_capture(+ *,+ nsight_path: str | None,+ capture_file: str,+ output_dir: str,+ metadata: bool,+ logs: bool,+ screenshot: bool,+ perf_report: bool,+) -> dict[str, Any]:+ """Analyze an existing capture through ngfx-replay metadata and replay outputs."""+ capture_path = Path(capture_file).resolve()+ if not capture_path.is_file():+ raise FileNotFoundError(f"Capture file does not exist: {capture_file}")+ capture_kind = _capture_type(capture_path)++ if not any((metadata, logs, screenshot, perf_report)):+ metadata = True+ logs = True+ perf_report = True++ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ if not binaries.get("ngfx_replay"):+ raise RuntimeError(+ "ngfx-replay.exe is required for replay analyze. Install Nsight Graphics "+ "with replay tools or set NSIGHT_GRAPHICS_PATH to an install containing ngfx-replay.exe."+ )++ output_root = Path(output_dir).resolve()+ output_root.mkdir(parents=True, exist_ok=True)+ before = backend.snapshot_files([str(output_root)])++ command_results: list[dict[str, Any]] = []+ metadata_files: dict[str, str | None] = {+ "summary": None,+ "functions": None,+ "objects": None,+ }+ logs_payload: dict[str, Any] = {+ "log_file": None,+ "errors_file": None,+ "log_line_count": 0,+ "error_line_count": 0,+ "error_summary": [],+ "raw_error_summary": [],+ "status": "not_requested",+ }+ screenshot_payload: dict[str, Any] = {"path": None, "present": False}+ perf_payload: dict[str, Any] = {"dir": None, "present": False}++ if metadata:+ for kind, flag, filename in [+ ("metadata", "--metadata", "metadata.txt"),+ ("metadata_functions", "--metadata-functions", "metadata_functions.txt"),+ ("metadata_objects", "--metadata-objects", "metadata_objects.json"),+ ]:+ output_file = output_root / filename+ command_results.append(+ _run_stdout_export(+ binaries,+ capture_file=str(capture_path),+ output_file=output_file,+ kind=kind,+ replay_flag=flag,+ )+ )+ metadata_key = kind.replace("metadata_", "") if kind != "metadata" else "summary"+ metadata_files[metadata_key] = str(output_file) if output_file.is_file() else None++ if logs:+ log_file = output_root / "metadata_logs.txt"+ errors_file = output_root / "metadata_log_errors.txt"+ command_results.append(+ _run_stdout_export(+ binaries,+ capture_file=str(capture_path),+ output_file=log_file,+ kind="metadata_logs",+ replay_flag="--metadata-logs",+ )+ )+ command_results.append(+ _run_stdout_export(+ binaries,+ capture_file=str(capture_path),+ output_file=errors_file,+ kind="metadata_log_errors",+ replay_flag="--metadata-logs-errors",+ )+ )+ logs_payload["log_file"] = str(log_file) if log_file.is_file() else None+ logs_payload["errors_file"] = str(errors_file) if errors_file.is_file() else None+ logs_payload.update(_summarize_logs(log_file, errors_file))++ if screenshot:+ screenshot_file = output_root / "metadata_screenshot.png"+ command = backend.build_replay_command(+ binaries,+ capture_file=str(capture_path),+ extra_args=["--metadata-screenshot", str(screenshot_file)],+ )+ result = backend.run_command(command, timeout=300)+ command_results.append(_compact_result("metadata_screenshot", result, output_file=screenshot_file))+ screenshot_payload = {+ "path": str(screenshot_file),+ "present": screenshot_file.is_file() and screenshot_file.stat().st_size > 0,+ }++ if perf_report:+ perf_dir = output_root / "perf_report"+ perf_dir.mkdir(parents=True, exist_ok=True)+ command = backend.build_replay_command(+ binaries,+ capture_file=str(capture_path),+ extra_args=[+ "--loop-count",+ "1",+ "--present-hidden",+ "--no-block-on-incompatibility",+ "--perf-report-dir",+ str(perf_dir),+ ],+ )+ result = backend.run_command(command, timeout=600)+ command_results.append(_compact_result("perf_report", result, output_file=perf_dir))+ perf_payload = {+ "dir": str(perf_dir),+ "present": _has_files(perf_dir),+ }++ after = backend.snapshot_files([str(output_root)])+ artifacts = backend.diff_snapshots(before, after)+ metadata_present = {+ "summary": bool(metadata_files["summary"] and Path(metadata_files["summary"]).is_file()),+ "functions": bool(metadata_files["functions"] and Path(metadata_files["functions"]).is_file()),+ "objects": bool(metadata_files["objects"] and Path(metadata_files["objects"]).is_file()),+ }+ metadata_summary = _summarize_metadata(Path(metadata_files["summary"]) if metadata_files["summary"] else None)+ function_summary = _summarize_functions(Path(metadata_files["functions"]) if metadata_files["functions"] else None)+ object_summary = _summarize_objects(Path(metadata_files["objects"]) if metadata_files["objects"] else None)+ all_commands_ok = all(item["ok"] for item in command_results)+ ok = all_commands_ok+ if screenshot:+ ok = ok and screenshot_payload["present"]+ if perf_report:+ ok = ok and perf_payload["present"]+ analysis = _build_analysis(+ capture_kind=capture_kind,+ metadata_requested=metadata,+ logs_requested=logs,+ screenshot_requested=screenshot,+ perf_requested=perf_report,+ metadata_present=metadata_present,+ metadata_summary=metadata_summary,+ object_summary=object_summary,+ function_summary=function_summary,+ logs_summary=logs_payload,+ screenshot_payload=screenshot_payload,+ perf_payload=perf_payload,+ command_results=command_results,+ )++ return {+ "ok": ok,+ "capture_file": str(capture_path),+ "capture_type": capture_kind,+ "version": report.get("version"),+ "tool_mode": report.get("tool_mode"),+ "compatibility_mode": report.get("compatibility_mode"),+ "replay_executable": binaries.get("ngfx_replay"),+ "output_dir": str(output_root),+ "requested_outputs": {+ "metadata": metadata,+ "logs": logs,+ "screenshot": screenshot,+ "perf_report": perf_report,+ },+ "command_results": command_results,+ "artifacts": artifacts,+ "artifact_count": len(artifacts),+ "metadata": {+ "files": metadata_files,+ "present": metadata_present,+ "summary": metadata_summary,+ "functions": function_summary,+ "objects": object_summary,+ },+ "logs": logs_payload,+ "screenshot": screenshot_payload,+ "perf_report": perf_payload,+ "analysis": analysis,+ }diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.pyindex cb832e395..c2194c9ba 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.py@@ -9,7 +9,7 @@ import shleximport click-from cli_anything.nsight_graphics.core import cpp_capture, doctor, frame, gpu_trace, launch+from cli_anything.nsight_graphics.core import cpp_capture, doctor, frame, gpu_trace, launch, replay_repl_mode = False@@ -91,6 +91,25 @@ def _print_gpu_trace_summary(summary: dict) -> None:click.echo(f" - {line}")+def _print_replay_analysis(payload: dict) -> None:+ """Render a compact human-readable replay analysis summary."""+ click.echo(f"Capture: {payload.get('capture_file')}")+ click.echo(f"Type: {payload.get('capture_type')}")+ click.echo(f"Output: {payload.get('output_dir')}")+ click.echo(f"Artifacts: {payload.get('artifact_count', 0)}")+ metadata_present = (payload.get("metadata") or {}).get("present") or {}+ if metadata_present:+ click.echo(+ "Metadata: "+ + ", ".join(f"{key}={'yes' if value else 'no'}" for key, value in metadata_present.items())+ )+ errors = (payload.get("logs") or {}).get("error_summary") or []+ if errors:+ click.echo("Captured log errors:")+ for line in errors:+ click.echo(f" - {line}")++@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.")@@ -187,7 +206,7 @@ def launch_group():@launch_group.command("detached")[email protected]("--activity", default="Frame Debugger", show_default=True, help="Nsight activity name.")[email protected]("--activity", default="Graphics Capture", show_default=True, help="Nsight activity name.")@click.option("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")@click.option("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")@click.option("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")@@ -210,7 +229,7 @@ def launch_detached_cmd(ctx, activity, exe_path, working_dir, program_args, envs@launch_group.command("attach")[email protected]("--activity", default="Frame Debugger", show_default=True, help="Nsight activity name.")[email protected]("--activity", default="Graphics Capture", show_default=True, help="Nsight activity name.")@click.option("--pid", type=int, required=True, help="PID to attach.")@click.pass_contextdef launch_attach_cmd(ctx, activity, pid):@@ -228,10 +247,11 @@ def launch_attach_cmd(ctx, activity, pid):@cli.group("frame")def frame_group():- """Frame Debugger capture commands."""+ """Graphics capture commands."""@frame_group.command("capture")[email protected]("--activity", default=None, help="Nsight activity name. Defaults to Graphics Capture when available.")@click.option("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")@click.option("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")@click.option("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")@@ -244,6 +264,7 @@ def frame_group():@click.pass_contextdef frame_capture_cmd(ctx,+ activity,exe_path,working_dir,program_args,@@ -261,6 +282,7 @@ def frame_capture_cmd(working_dir=working_dir,args=program_args,envs=envs,+ activity=activity,wait_seconds=wait_seconds,wait_frames=wait_frames,wait_hotkey=wait_hotkey,@@ -368,6 +390,36 @@ def gpu_trace_summarize_cmd(ctx, input_dir, summary_limit):_handle_exc(ctx, exc)[email protected]("replay")+def replay_group():+ """Analyze existing Nsight capture files with ngfx-replay."""+++@replay_group.command("analyze")[email protected]("--capture-file", required=True, type=click.Path(exists=True, dir_okay=False), help="Existing .ngfx-capture or .ngfx-gputrace file.")[email protected]("--output-dir", required=True, type=click.Path(file_okay=False), help="Directory for replay analysis artifacts.")[email protected]("--metadata", is_flag=True, help="Export metadata, function stream, and object metadata.")[email protected]("--logs", is_flag=True, help="Export captured logs and captured error logs.")[email protected]("--screenshot", is_flag=True, help="Export the embedded metadata screenshot.")[email protected]("--perf-report", is_flag=True, help="Replay once and collect a performance report.")[email protected]_context+def replay_analyze_cmd(ctx, capture_file, output_dir, metadata, logs, screenshot, perf_report):+ """Analyze an existing capture through ngfx-replay."""+ try:+ data = replay.analyze_capture(+ nsight_path=ctx.obj.get("nsight_path"),+ capture_file=capture_file,+ output_dir=output_dir,+ metadata=metadata,+ logs=logs,+ screenshot=screenshot,+ perf_report=perf_report,+ )+ _output(ctx, data, _print_replay_analysis)+ except Exception as exc:+ _handle_exc(ctx, exc)++@cli.group("cpp")def cpp_group():"""Generate C++ Capture commands."""@@ -416,6 +468,7 @@ def repl(ctx):"launch": "detached|attach","frame": "capture","gpu-trace": "capture|summarize",+ "replay": "analyze","cpp": "capture","help": "Show this help","quit": "Exit REPL",diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.mdindex 2b52ceda0..e5c8deff6 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md@@ -1,7 +1,7 @@---name: cli-anything-nsight-graphics-description: Windows-first CLI harness for Nsight Graphics launch, frame capture, GPU Trace, and C++ Capture orchestration-version: 0.1.0+description: Windows-first CLI harness for Nsight Graphics capture, GPU Trace summary, and ngfx-replay analysis+version: 0.2.0command: cli-anything-nsight-graphicsinstall: pip install cli-anything-nsight-graphicsrequires:@@ -23,8 +23,10 @@ Command-line orchestration of official NVIDIA Nsight Graphics activities.- Probe installed Nsight binaries and compatibility mode- Launch an application detached under Nsight- Attach Nsight to a running PID-- Trigger Frame Debugger capture+- Trigger Graphics Capture or OpenGL Frame Debugger capture- Trigger GPU Trace capture, auto-export, and summarize+- Analyze existing `.ngfx-capture` files through `ngfx-replay`+- Report clear compatibility diagnostics for `.ngfx-gputrace` inputs- Trigger Generate C++ Capture## Commands@@ -40,8 +42,8 @@ cli-anything-nsight-graphics --nsight-path "C:\Path\To\Nsight Graphics 2024.2\ho### launch```bash-cli-anything-nsight-graphics launch detached --activity "Frame Debugger" --exe "C:\Path\To\App.exe"-cli-anything-nsight-graphics launch attach --activity "Frame Debugger" --pid 12345+cli-anything-nsight-graphics launch detached --activity "Graphics Capture" --exe "C:\Path\To\App.exe"+cli-anything-nsight-graphics launch attach --activity "Graphics Capture" --pid 12345```### frame capture@@ -66,6 +68,14 @@ cli-anything-nsight-graphics gpu-trace summarize ^--input-dir D:\traces```+### Replay analysis++```bash+cli-anything-nsight-graphics --json replay analyze ^+ --capture-file D:\captures\frame.ngfx-capture ^+ --output-dir D:\analysis+```+### Generate C++ Capture```bash@@ -80,8 +90,21 @@ cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^- Use `doctor versions` to list detected installs when multiple Nsight Graphics versions exist.- Use `--nsight-path` to force a specific install directory or `ngfx.exe`.- Use `--json` for programmatic workflows.-- Prefer `gpu-trace capture --auto-export --summarize` for one-step performance triage.+- Prefer `gpu-trace capture --auto-export --summarize` for one-step performance+ triage. The summary includes exported table inventory, metric inventory,+ frame-budget classification, workload classification, throughput ranking,+ bottleneck hints, and warnings for empty event/regime tables.+- Use `replay analyze` when the input is an existing `.ngfx-capture` file. With+ no analysis switches it exports metadata, logs, captured log errors, and a+ replay performance report, then adds structured `analysis.highlights` /+ `analysis.warnings`.+- `ngfx-replay` documents its input as a Graphics Capture file. `.ngfx-gputrace`+ inputs are accepted for clear diagnostics, but on Nsight Graphics 2026.1.0+ they may report `Invalid file header`; use `gpu-trace summarize` for exported+ GPU Trace table analysis.+- `replay analyze` uses official `ngfx-replay` metadata/log/screenshot/perf-report+ outputs; it is not a RenderDoc-style shader, pipeline, texture, or resource inspector.- Frame/GPU/C++ capture commands require a launch target through `--exe` or apreconfigured root-level `--project`.-- V1 is orchestration-focused; it does not expose shader, pipeline, or resource- inspection commands.+- If a global `cli-anything-nsight-graphics` command points at an old worktree,+ reinstall from `nsight-graphics/agent-harness` with `python -m pip install -e .`.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.mdindex be2d786c6..2365b0604 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.md+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.md@@ -1,38 +1,47 @@-# TEST.md โ Nsight Graphics CLI Test Plan & Results+# TEST.md - Nsight Graphics CLI Test Plan & Results## Test Inventory Plan-- `test_core.py`: 36 unit tests planned-- `test_full_e2e.py`: 4 E2E tests planned+- `test_core.py`: 46 unit and CLI tests planned+- `test_full_e2e.py`: 5 conditional E2E tests planned## Unit Test Plan### `utils/nsight_graphics_backend.py`- executable discovery from env override and install directories-- compatibility mode detection+- compatibility mode detection for `unified`, `split`, `unified+split`, and missing tools- CLI override precedence via `--nsight-path`-- `ngfx --help-all` parsing for activities and options+- `ngfx --help-all` parsing for current Graphics Capture and GPU Trace activities- installation listing and version reporting- Windows registry discovery for registered-only installs- fixed-drive discovery for non-`C:` installs-- unified and split command construction+- unified, split capture, and replay command construction+- explicit output directory creation before invoking Nsight- artifact diffing behavior- exported GPU Trace summary parsing+- exported GPU Trace table inventory, metric inventory, frame-budget/workload+ analysis, throughput ranking, bottleneck hints, and empty table warnings- newest-complete GPU Trace export selection when multiple exports share an output root### `core/*.py`-- frame capture command routing+- Graphics Capture default activity selection and explicit OpenGL Frame Debugger routing- split-mode fallback restrictions- GPU Trace validation for trigger/limit options-- GPU Trace one-step summary behavior+- GPU Trace one-step summary behavior, including refusal to summarize stale exports+- `ngfx-replay` metadata/log/screenshot/perf-report analysis command orchestration+- structured replay metadata summaries for capture metadata, function streams,+ object inventories, and no-error log markers+- `.ngfx-gputrace` replay compatibility diagnostics when `ngfx-replay` rejects+ the file header- launch attach/detached wrapping### `nsight_graphics_cli.py`- root help-- help for `doctor`, `launch`, `frame`, `gpu-trace`, and `cpp`+- help for `doctor`, `launch`, `frame`, `gpu-trace`, `replay`, and `cpp`+- JSON output for `replay analyze`- subprocess smoke test via `python -m`## E2E Test Plan@@ -40,19 +49,21 @@Environment prerequisites:- Nsight Graphics installed and discoverable-- one shared target via `NSIGHT_GRAPHICS_TEST_EXE` (plus optional args/workdir), or-- activity-specific targets via:- - `NSIGHT_GRAPHICS_FRAME_TEST_EXE`- - `NSIGHT_GRAPHICS_GPU_TRACE_TEST_EXE`- - `NSIGHT_GRAPHICS_CPP_TEST_EXE`-- optional args/workdirs for each activity via the matching `*_ARGS` / `*_WORKDIR` variables+- `NSIGHT_GRAPHICS_TEST_EXE`+- optional `NSIGHT_GRAPHICS_TEST_ARGS`+- optional `NSIGHT_GRAPHICS_TEST_WORKDIR`+- optional `NSIGHT_GRAPHICS_TEST_CAPTURE_FILE` pointing at `.ngfx-capture`Scenarios:1. `doctor info` returns installation metadata-2. `frame capture` produces one or more non-empty artifacts-3. `gpu-trace capture --auto-export` produces one or more non-empty artifacts+2. `frame capture` produces one or more non-empty artifacts, then feeds a+ discovered `.ngfx-capture` into `replay analyze`+3. `gpu-trace capture --auto-export --summarize` produces one or more+ non-empty artifacts and structured table/metric/analysis summary fields4. `cpp capture` produces one or more non-empty artifacts+5. `replay analyze` on an existing capture produces non-empty analysis artifacts+ and structured metadata/log summary fields## Running Tests@@ -62,41 +73,93 @@ python -m pip install -e .python -m pytest cli_anything/nsight_graphics/tests -v --tb=no```+For the full local E2E run on this workstation:++```powershell+$env:NSIGHT_GRAPHICS_TEST_EXE = "D:\Program Files\NVIDIA Corporation\Nsight Graphics 2026.1.0\samples\applications\vk_graphics_pipeline_library\vk_graphics_pipeline_library.exe"+$env:NSIGHT_GRAPHICS_TEST_WORKDIR = "D:\Program Files\NVIDIA Corporation\Nsight Graphics 2026.1.0\samples\applications\vk_graphics_pipeline_library"+$env:NSIGHT_GRAPHICS_TEST_CAPTURE_FILE = "C:\Users\aimidi\Documents\NVIDIA Nsight Graphics\GraphicsCaptures\vk_graphics_pipeline_library_2026_04_23_17_48_22.ngfx-capture"+python -m pytest cli_anything/nsight_graphics/tests -v --tb=no+```+## Test Results```text-python -m pytest cli_anything/nsight_graphics/tests/test_core.py -q-.................................... [100%]-36 passed in 0.27s--python -m pytest cli_anything/nsight_graphics/tests/test_full_e2e.py -v -rs============================= 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.execachedir: .pytest_cacherootdir: C:\Users\aimidi\.codex\worktrees\da29\CLI-Anything\nsight-graphics\agent-harness-collecting ... collected 4 items--cli_anything/nsight_graphics/tests/test_full_e2e.py::TestDoctorE2E::test_doctor_info PASSED [ 25%]-cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_frame_capture PASSED [ 50%]-cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_gpu_trace_capture PASSED [ 75%]-cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_cpp_capture PASSED [100%]--============================= 4 passed in 23.10s ==============================+collecting ... collected 51 items++cli_anything/nsight_graphics/tests/test_core.py::TestOutputAndErrors::test_output_json PASSED [ 2%]+cli_anything/nsight_graphics/tests/test_core.py::TestOutputAndErrors::test_handle_error_debug PASSED [ 4%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_default_windows_install_dirs_prefers_higher_version PASSED [ 6%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_discover_binaries_from_env_dir PASSED [ 8%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_discover_binaries_prefers_cli_override PASSED [ 10%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_detect_tool_mode PASSED [ 12%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_prepare_output_dir_creates_missing_directory PASSED [ 13%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_reports_versions PASSED [ 14%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_includes_registry_only_entries PASSED [ 16%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_merges_registry_metadata_into_filesystem_entry PASSED [ 18%]+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_promotes_newer_drive_install PASSED [ 20%]+cli_anything/nsight_graphics/tests/test_core.py::TestHelpParsing::test_parse_unified_help_extracts_activities_and_options PASSED [ 22%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_build_unified_command_formats_args_and_env PASSED [ 24%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_build_split_capture_command_maps_wait_seconds PASSED [ 26%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_build_replay_command_uses_capture_file_as_positional PASSED [ 28%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_diff_snapshots_reports_new_nonempty_files PASSED [ 30%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_gpu_trace_summary_from_export_dir PASSED [ 32%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_gpu_trace_summary_reports_empty_event_and_regime_tables PASSED [ 35%]+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_gpu_trace_summary_prefers_newest_complete_export_dir PASSED [ 34%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_frame_capture_uses_unified_ngfx PASSED [ 36%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_frame_capture_allows_explicit_opengl_frame_debugger PASSED [ 38%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_frame_capture_split_mode_rejects_perf_exports PASSED [ 40%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_gpu_trace_requires_arch_for_metric_set PASSED [ 42%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_launch_attach_returns_unified_result PASSED [ 44%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_cpp_capture_sets_activity PASSED [ 46%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_gpu_trace_capture_with_summary PASSED [ 48%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_gpu_trace_capture_summary_refuses_failed_capture PASSED [ 51%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_gpu_trace_capture_summary_requires_new_complete_export PASSED [ 53%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_exports_requested_metadata_logs_screenshot_and_perf PASSED [ 55%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_defaults_to_metadata_logs_and_perf PASSED [ 57%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_filters_no_error_log_marker PASSED [ 59%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_reports_gputrace_replay_incompatibility PASSED [ 61%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_requires_ngfx_replay PASSED [ 63%]+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_replay_analyze_rejects_unknown_capture_extension PASSED [ 65%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_root_help PASSED [ 67%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_nsight_path_is_forwarded_to_doctor PASSED [ 69%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args0-info] PASSED [ 71%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args1-versions] PASSED [ 73%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args2-detached] PASSED [ 75%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args3-capture] PASSED [ 77%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args4-capture] PASSED [ 79%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args5-summarize] PASSED [ 81%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args6-analyze] PASSED [ 83%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args7-capture] PASSED [ 85%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_replay_analyze_json_cli PASSED [ 87%]+cli_anything/nsight_graphics/tests/test_core.py::TestCLISubprocess::test_cli_help_subprocess PASSED [ 89%]+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestDoctorE2E::test_doctor_info PASSED [ 91%]+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_frame_capture PASSED [ 93%]+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_gpu_trace_capture PASSED [ 95%]+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_cpp_capture PASSED [ 97%]+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestReplayE2E::test_replay_analyze_existing_capture PASSED [100%]++============================= 51 passed in 36.51s =============================```## Summary Statistics-- Total tests collected: 40-- Passed: 40-- Skipped: 0 in the validated real-environment run+- Total tests collected: 51+- Passed: 51+- Skipped: 0- Pass rate: 100%## Coverage Notes- `doctor info` E2E passed against the local Nsight Graphics installation.-- Target-dependent E2E scenarios are env-gated by executable/workdir configuration.-- Verified all targeted E2E scenarios locally with the bundled Vulkan sample:- `D:\Program Files\NVIDIA Corporation\Nsight Graphics 2026.1.0\samples\applications\vk_graphics_pipeline_library\vk_graphics_pipeline_library.exe`-- GPU Trace summary coverage now includes the case where an output root contains- multiple export directories; the newest complete export is selected.-- Current builds map legacy `Frame Debugger` flows onto `Graphics Capture` where required by newer Nsight Graphics releases.+- Target-dependent capture E2E passed with the Nsight Graphics 2026.1.0 `vk_graphics_pipeline_library.exe` sample, including `gpu-trace capture --auto-export --summarize`.+- Replay E2E passed with an existing local `.ngfx-capture` generated from the same sample and now asserts structured metadata/log summary fields.+- Frame capture E2E now immediately replays the captured `.ngfx-capture` when one is discovered.+- A real local `.ngfx-gputrace` was checked manually against `ngfx-replay` and returned `ERROR: Invalid file header`; the CLI now reports this as a compatibility warning instead of implying metadata support.+- GPU Trace summary coverage now refuses stale exports for one-step capture summaries and reports table inventory, metric inventory, frame-budget/workload analysis, throughput ranking, bottleneck hints, and empty event/regime table warnings.+- Explicit `--output-dir` paths are now created before capture commands invoke Nsight.+- Without target/capture E2E environment variables, the suite reports `47 passed, 4 skipped`; the skips are the expected target-dependent capture and replay E2E gates.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.pyindex d616c10b1..63ed30ae0 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.py@@ -12,7 +12,7 @@ from unittest.mock import patchimport pytest-from cli_anything.nsight_graphics.core import cpp_capture, frame, gpu_trace, launch+from cli_anything.nsight_graphics.core import cpp_capture, frame, gpu_trace, launch, replayfrom cli_anything.nsight_graphics.utils import nsight_graphics_backend as backendfrom cli_anything.nsight_graphics.utils.errors import handle_errorfrom cli_anything.nsight_graphics.utils.output import output_json@@ -25,7 +25,8 @@ General Options:--project arg Nsight project file to load--output-dir arg Output folder to export/write data to--activity arg Target activity to use, should be one of:- Frame Debugger+ Graphics Capture+ OpenGL Frame DebuggerGenerate C++ CaptureGPU Trace Profiler--platform arg Target platform to use, should be one of:@@ -37,7 +38,13 @@ General Options:--args arg Command-line arguments of launched application--env arg Environment variables of launched application-Frame Debugger activity options:+Graphics Capture activity options:+ --frame-count arg Capture N frames+ --hotkey-capture Wait for hotkey+ --frame-index arg Capture frame index+ --elapsed-time arg Wait in time (seconds) before capturing++OpenGL Frame Debugger activity options:--wait-frames arg Wait in frames before capturing a frame--wait-seconds arg Wait in time (seconds) before capturing a frame--wait-hotkey Wait for hotkey@@ -78,7 +85,7 @@ class TestOutputAndErrors:class TestBackendDiscovery:def test_default_windows_install_dirs_prefers_higher_version(self):- with patch("cli_anything.nsight_graphics.utils.backend.discovery._fixed_windows_drive_roots", return_value=["C:", "D:"]):+ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._fixed_windows_drive_roots", return_value=["C:", "D:"]):result = backend._default_windows_install_dirs(lambda pattern: {"C:/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [@@ -123,9 +130,17 @@ class TestBackendDiscovery:def test_detect_tool_mode(self):assert backend.detect_tool_mode({"ngfx": "a", "ngfx_capture": None, "ngfx_replay": None}) == "unified"+ assert backend.detect_tool_mode({"ngfx": "a", "ngfx_capture": "b", "ngfx_replay": "c"}) == "unified+split"assert backend.detect_tool_mode({"ngfx": None, "ngfx_capture": "a", "ngfx_replay": None}) == "split"assert backend.detect_tool_mode({"ngfx": None, "ngfx_capture": None, "ngfx_replay": None}) == "missing"+ def test_prepare_output_dir_creates_missing_directory(self, tmp_path):+ output_dir = tmp_path / "new" / "capture-output"+ assert not output_dir.exists()+ resolved = backend.prepare_output_dir(str(output_dir))+ assert resolved == str(output_dir.resolve())+ assert output_dir.is_dir()+def test_list_installations_reports_versions(self, tmp_path):install_dir = tmp_path / "Nsight Graphics 2025.1" / "host" / "windows-desktop-nomad-x64"install_dir.mkdir(parents=True)@@ -211,8 +226,8 @@ class TestBackendDiscovery:(c_dir / "ngfx.exe").write_text("", encoding="utf-8")(d_dir / "ngfx.exe").write_text("", encoding="utf-8")- with patch("cli_anything.nsight_graphics.utils.backend.discovery._fixed_windows_drive_roots", return_value=["C:", "D:"]), \- patch("cli_anything.nsight_graphics.utils.backend.discovery._read_registry_installations", return_value=[]):+ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._fixed_windows_drive_roots", return_value=["C:", "D:"]), \+ patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._read_registry_installations", return_value=[]):result = backend.list_installations(env={},which=lambda _: None,@@ -232,26 +247,17 @@ class TestHelpParsing:def test_parse_unified_help_extracts_activities_and_options(self):result = backend.parse_unified_help(SAMPLE_HELP)assert result["activities"] == [- "Frame Debugger",+ "Graphics Capture",+ "OpenGL Frame Debugger","Generate C++ Capture","GPU Trace Profiler",]assert result["platforms"] == ["Windows"]assert "--project" in result["general_options"]- assert "--wait-frames" in result["activity_options"]["Frame Debugger"]+ assert "--frame-index" in result["activity_options"]["Graphics Capture"]+ assert "--wait-frames" in result["activity_options"]["OpenGL Frame Debugger"]assert "--metric-set-id" in result["activity_options"]["GPU Trace Profiler"]- def test_resolve_activity_name_maps_legacy_frame_debugger_to_graphics_capture(self):- report = {- "supported_activities": [- "Graphics Capture",- "Generate C++ Capture",- "GPU Trace Profiler",- ]- }- assert backend.resolve_activity_name(report, "Frame Debugger") == "Graphics Capture"- assert backend.resolve_activity_name(report, "Graphics Capture") == "Graphics Capture"-class TestCommandBuilders:def test_build_unified_command_formats_args_and_env(self):@@ -288,11 +294,17 @@ class TestCommandBuilders:assert "--capture-countdown-timer" in commandassert command[command.index("--capture-countdown-timer") + 1] == "3000"- @patch("cli_anything.nsight_graphics.utils.backend.execution.subprocess.run")- def test_run_command_suppresses_graphics_capture_suggestion_dialog(self, run_mock):- run_mock.return_value = type("Result", (), {"returncode": 0, "stdout": "", "stderr": ""})()- backend.run_command(["C:/Nsight/ngfx.exe", "--help"])- assert run_mock.call_args.kwargs["env"]["NSIGHT_SUGGEST_GRAPHICS_CAPTURE"] == "0"+ def test_build_replay_command_uses_capture_file_as_positional(self):+ command = backend.build_replay_command(+ {"ngfx_replay": "C:/Nsight/ngfx-replay.exe"},+ capture_file="D:/captures/frame.ngfx-capture",+ extra_args=["--metadata"],+ )+ assert command == [+ "C:/Nsight/ngfx-replay.exe",+ "--metadata",+ "D:/captures/frame.ngfx-capture",+ ]def test_diff_snapshots_reports_new_nonempty_files(self, tmp_path):before = backend.snapshot_files([str(tmp_path)])@@ -304,12 +316,6 @@ class TestCommandBuilders:assert diff[0]["path"].endswith("capture.ngfx-capture")assert diff[0]["size"] > 0- def test_activity_artifact_roots_keeps_default_graphics_capture_location(self):- roots = backend.activity_artifact_roots("Graphics Capture", "D:/captures")- assert str(Path("D:/captures").resolve()) in roots- assert any(root.endswith("Documents\\NVIDIA Nsight Graphics") for root in roots)- assert any(root.endswith("Documents\\NVIDIA Nsight Graphics\\GraphicsCaptures") for root in roots)-def test_gpu_trace_summary_from_export_dir(self, tmp_path):base = tmp_path / "BASE"base.mkdir()@@ -324,6 +330,8 @@ class TestCommandBuilders:"TriageAC.sm__throughput.avg.pct_of_peak_sustained_elapsed\t23.6331","LTS.TriageAC.lts__throughput.avg.pct_of_peak_sustained_elapsed\t32.0437","FBSP.TriageAC.dramc__throughput.avg.pct_of_peak_sustained_elapsed\t19.5897",+ "PCI.TriageAC.pcie__throughput.avg.pct_of_peak_sustained_elapsed\t12.0",+ "SM_A.TriageAC.sm__inst_executed_realtime.sum\t123456",]),encoding="utf-8",@@ -336,16 +344,65 @@ class TestCommandBuilders:" ReSTIRDI\t14.0627\n",encoding="utf-8",)+ (base / "GPUTRACE_REGIMES.xls").write_text(+ "flattened_event_name\tTriageAC.sm__throughput.avg.pct_of_peak_sustained_elapsed\n"+ "Scene\t23.6331\n",+ encoding="utf-8",+ )summary = gpu_trace.summarize_export_dir(str(tmp_path), top_n=3)assert summary["frame_time_ms"] == pytest.approx(31.0446)assert summary["fps_estimate"] == pytest.approx(1000.0 / 31.0446)assert summary["metrics"]["draw_count"] == 309assert summary["metrics"]["dispatch_count"] == 2561+ assert summary["tables"]["trace_frame"]["metric_count"] == 9+ assert summary["tables"]["events"]["row_count"] == 4+ assert summary["tables"]["regimes"]["row_count"] == 1+ assert summary["metric_inventory"]["metric_count"] == 9+ assert summary["metric_inventory"]["top_pct_of_peak_metrics"][0]["metric"].endswith(+ "gr__cycles_active.avg.pct_of_peak_sustained_elapsed"+ )assert summary["top_events"][0]["event"] == "Scene"assert summary["top_events"][1]["event"] == "DirectLighting"+ assert summary["analysis"]["workload"]["classification"] == "compute_heavy"+ assert summary["analysis"]["throughput"]["dominant_unit"]["name"] == "graphics_engine"+ assert summary["analysis"]["event_summary"]["event_count"] == 3+ assert any(item["id"] == "frame_budget_60fps" for item in summary["analysis"]["bottlenecks"])assert summary["highlights"]+ def test_gpu_trace_summary_reports_empty_event_and_regime_tables(self, tmp_path):+ base = tmp_path / "BASE"+ base.mkdir()+ (base / "FRAME.xls").write_text("GPU frame time\t1.5\n", encoding="utf-8")+ (base / "GPUTRACE_FRAME.xls").write_text(+ "\n".join(+ [+ "FE_B.TriageAC.fe__draw_count.sum\t38",+ "FE_A.TriageAC.gr__dispatch_count.sum\t0",+ "FE_B.TriageAC.gr__cycles_active.avg.pct_of_peak_sustained_elapsed\t12.0",+ "TriageAC.sm__throughput.avg.pct_of_peak_sustained_elapsed\t3.0",+ "SM_B.TriageAC.l1tex__t_sector_hit_rate.pct\t96.0",+ ]+ ),+ encoding="utf-8",+ )+ (base / "D3DPERF_EVENTS.xls").write_text("event_text\ttime_ms\n", encoding="utf-8")+ (base / "GPUTRACE_REGIMES.xls").write_text(+ "flattened_event_name\tFE_B.TriageAC.gr__cycles_active.avg.pct_of_peak_sustained_elapsed\n",+ encoding="utf-8",+ )++ summary = gpu_trace.summarize_export_dir(str(tmp_path), top_n=2)++ assert summary["tables"]["events"]["row_count"] == 0+ assert summary["tables"]["regimes"]["present"] is True+ assert summary["tables"]["regimes"]["row_count"] == 0+ assert summary["analysis"]["event_summary"]["event_count"] == 0+ assert summary["analysis"]["frame_budget"]["bucket"] == "within_60fps_budget"+ assert summary["analysis"]["workload"]["classification"] == "mixed"+ assert any("D3DPERF_EVENTS.xls contains no timed GPU event rows" in warning for warning in summary["analysis"]["warnings"])+ assert any("GPUTRACE_REGIMES.xls contains headers" in warning for warning in summary["analysis"]["warnings"])+def test_gpu_trace_summary_prefers_newest_complete_export_dir(self, tmp_path):old_export = tmp_path / "A_old_export"new_export = tmp_path / "B_new_export"@@ -403,11 +460,16 @@ class TestCoreModules:@patch("cli_anything.nsight_graphics.core.frame.backend.run_with_artifacts")@patch("cli_anything.nsight_graphics.core.frame.backend.build_unified_command")@patch("cli_anything.nsight_graphics.core.frame.backend.probe_installation")- def test_frame_capture_uses_unified_ngfx(self, probe_mock, build_mock, run_mock):+ def test_frame_capture_uses_unified_ngfx(self, probe_mock, build_mock, run_mock, tmp_path):probe_mock.return_value = {"binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ "supported_activities": ["Graphics Capture", "OpenGL Frame Debugger"],+ "activity_options": {+ "Graphics Capture": ["--frame-count", "--frame-index", "--elapsed-time", "--hotkey-capture"],+ "OpenGL Frame Debugger": ["--wait-frames", "--wait-seconds", "--wait-hotkey"],+ },}- build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "Frame Debugger"]+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "Graphics Capture"]run_mock.return_value = {"ok": True,"returncode": 0,@@ -420,13 +482,14 @@ class TestCoreModules:result = frame.capture_frame(nsight_path=None,project=None,- output_dir="D:/out",+ output_dir=str(tmp_path / "out"),hostname=None,platform_name=None,exe="C:/demo.exe",working_dir=None,args=(),envs=(),+ activity=None,wait_seconds=None,wait_frames=10,wait_hotkey=False,@@ -435,48 +498,55 @@ class TestCoreModules:)assert build_mock.called+ assert build_mock.call_args.kwargs["activity"] == "Graphics Capture"+ assert "--frame-index" in build_mock.call_args.kwargs["extra_args"]assert result["tool_mode"] == "unified"- assert result["activity"] == "Frame Debugger"+ assert result["activity"] == "Graphics Capture"assert result["artifacts"]@patch("cli_anything.nsight_graphics.core.frame.backend.run_with_artifacts")@patch("cli_anything.nsight_graphics.core.frame.backend.build_unified_command")@patch("cli_anything.nsight_graphics.core.frame.backend.probe_installation")- def test_frame_capture_maps_graphics_capture_options(self, probe_mock, build_mock, run_mock):+ def test_frame_capture_allows_explicit_opengl_frame_debugger(self, probe_mock, build_mock, run_mock, tmp_path):probe_mock.return_value = {"binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},- "supported_activities": ["Graphics Capture", "GPU Trace Profiler"],+ "supported_activities": ["Graphics Capture", "OpenGL Frame Debugger"],+ "activity_options": {+ "Graphics Capture": ["--frame-count", "--frame-index", "--elapsed-time", "--hotkey-capture"],+ "OpenGL Frame Debugger": ["--wait-frames", "--wait-seconds", "--wait-hotkey"],+ },}- build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "Graphics Capture"]+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "OpenGL Frame Debugger"]run_mock.return_value = {"ok": True,"returncode": 0,"stdout": "","stderr": "","command": "ngfx",- "artifacts": [{"path": "D:/out/capture.ngfx-capture", "size": 10, "mtime_ns": 1}],+ "artifacts": [],}result = frame.capture_frame(nsight_path=None,project=None,- output_dir="D:/out",+ output_dir=str(tmp_path / "out"),hostname=None,platform_name=None,exe="C:/demo.exe",working_dir=None,args=(),envs=(),- wait_seconds=1,- wait_frames=None,+ activity="OpenGL Frame Debugger",+ wait_seconds=None,+ wait_frames=10,wait_hotkey=False,export_frame_perf_metrics=False,export_range_perf_metrics=False,)- assert build_mock.call_args.kwargs["activity"] == "Graphics Capture"- assert build_mock.call_args.kwargs["extra_args"] == ["--frame-count", "1", "--elapsed-time", "1"]- assert result["activity"] == "Graphics Capture"+ assert build_mock.call_args.kwargs["activity"] == "OpenGL Frame Debugger"+ assert "--wait-frames" in build_mock.call_args.kwargs["extra_args"]+ assert result["activity"] == "OpenGL Frame Debugger"@patch("cli_anything.nsight_graphics.core.frame.backend.probe_installation")def test_frame_capture_split_mode_rejects_perf_exports(self, probe_mock):@@ -494,6 +564,7 @@ class TestCoreModules:working_dir=None,args=(),envs=(),+ activity=None,wait_seconds=None,wait_frames=1,wait_hotkey=False,@@ -562,7 +633,7 @@ class TestCoreModules:@patch("cli_anything.nsight_graphics.core.cpp_capture.backend.run_with_artifacts")@patch("cli_anything.nsight_graphics.core.cpp_capture.backend.build_unified_command")@patch("cli_anything.nsight_graphics.core.cpp_capture.backend.probe_installation")- def test_cpp_capture_sets_activity(self, probe_mock, build_mock, run_mock):+ def test_cpp_capture_sets_activity(self, probe_mock, build_mock, run_mock, tmp_path):probe_mock.return_value = {"binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},}@@ -578,7 +649,7 @@ class TestCoreModules:result = cpp_capture.capture_cpp(nsight_path=None,project=None,- output_dir="D:/out",+ output_dir=str(tmp_path / "out"),hostname=None,platform_name=None,exe="C:/demo.exe",@@ -617,8 +688,12 @@ class TestCoreModules:"stdout": "","stderr": "","command": "ngfx",- "artifacts": [],- "artifact_count": 0,+ "artifacts": [+ {"path": str(base / "FRAME.xls"), "size": 1, "mtime_ns": 1},+ {"path": str(base / "GPUTRACE_FRAME.xls"), "size": 1, "mtime_ns": 1},+ {"path": str(base / "D3DPERF_EVENTS.xls"), "size": 1, "mtime_ns": 1},+ ],+ "artifact_count": 3,}result = gpu_trace.capture_trace(@@ -651,6 +726,366 @@ class TestCoreModules:assert result["summary"]["frame_time_ms"] == pytest.approx(16.0)assert result["summary"]["top_events"][0]["event"] == "Scene"+ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.run_with_artifacts")+ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.build_unified_command")+ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.probe_installation")+ def test_gpu_trace_capture_summary_refuses_failed_capture(self, probe_mock, build_mock, run_mock, tmp_path):+ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "GPU Trace Profiler"]+ run_mock.return_value = {+ "ok": False,+ "returncode": 1,+ "stdout": "",+ "stderr": "capture failed",+ "command": "ngfx",+ "artifacts": [],+ "artifact_count": 0,+ }++ with pytest.raises(RuntimeError, match="refusing to summarize stale"):+ gpu_trace.capture_trace(+ nsight_path=None,+ project=None,+ output_dir=str(tmp_path),+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ start_after_frames=1,+ start_after_submits=None,+ start_after_ms=None,+ start_after_hotkey=False,+ max_duration_ms=None,+ limit_to_frames=1,+ limit_to_submits=None,+ auto_export=False,+ architecture=None,+ metric_set_id=None,+ multi_pass_metrics=False,+ real_time_shader_profiler=False,+ summarize=True,+ summary_limit=5,+ )++ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.run_with_artifacts")+ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.build_unified_command")+ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.probe_installation")+ def test_gpu_trace_capture_summary_requires_new_complete_export(self, probe_mock, build_mock, run_mock, tmp_path):+ old_export = tmp_path / "old"+ old_export.mkdir()+ (old_export / "FRAME.xls").write_text("GPU frame time\t16.0\n", encoding="utf-8")+ (old_export / "GPUTRACE_FRAME.xls").write_text("FE_B.TriageAC.fe__draw_count.sum\t1\n", encoding="utf-8")+ (old_export / "D3DPERF_EVENTS.xls").write_text("event_text\ttime_ms\nOldPass\t1.0\n", encoding="utf-8")++ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "GPU Trace Profiler"]+ run_mock.return_value = {+ "ok": True,+ "returncode": 0,+ "stdout": "",+ "stderr": "",+ "command": "ngfx",+ "artifacts": [{"path": str(tmp_path / "capture.ngfx-gputrace"), "size": 1, "mtime_ns": 1}],+ "artifact_count": 1,+ }++ with pytest.raises(RuntimeError, match="complete newly exported table set"):+ gpu_trace.capture_trace(+ nsight_path=None,+ project=None,+ output_dir=str(tmp_path),+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ start_after_frames=1,+ start_after_submits=None,+ start_after_ms=None,+ start_after_hotkey=False,+ max_duration_ms=None,+ limit_to_frames=1,+ limit_to_submits=None,+ auto_export=False,+ architecture=None,+ metric_set_id=None,+ multi_pass_metrics=False,+ real_time_shader_profiler=False,+ summarize=True,+ summary_limit=5,+ )++ @patch("cli_anything.nsight_graphics.core.replay.backend.run_command")+ @patch("cli_anything.nsight_graphics.core.replay.backend.probe_installation")+ def test_replay_analyze_exports_requested_metadata_logs_screenshot_and_perf(self, probe_mock, run_mock, tmp_path):+ capture_file = tmp_path / "frame.ngfx-capture"+ capture_file.write_text("capture", encoding="utf-8")++ probe_mock.return_value = {+ "version": "2026.1.0",+ "tool_mode": "unified+split",+ "compatibility_mode": "unified+split",+ "binaries": {"ngfx_replay": "C:/Nsight/ngfx-replay.exe"},+ }++ def fake_run(command, timeout=120, cwd=None):+ if "--metadata-screenshot" in command:+ screenshot_path = Path(command[command.index("--metadata-screenshot") + 1])+ screenshot_path.write_bytes(b"png")+ stdout = ""+ elif "--perf-report-dir" in command:+ perf_dir = Path(command[command.index("--perf-report-dir") + 1])+ perf_dir.mkdir(parents=True, exist_ok=True)+ (perf_dir / "report.txt").write_text("perf", encoding="utf-8")+ stdout = ""+ elif "--metadata-functions" in command:+ stdout = json.dumps(+ [+ {"function_name": "vkQueueSubmit", "sequence_id": 1, "thread_index": 0},+ {"function_name": "vkQueueSubmit", "sequence_id": 2, "thread_index": 0},+ {"function_name": "vkCreateImage", "sequence_id": 3, "thread_index": 1},+ ]+ )+ elif "--metadata-objects" in command:+ stdout = json.dumps(+ [+ {"api": "Vulkan", "object_name": "Device_1", "type_name": "Device", "uid": 1},+ {"api": "Vulkan", "object_name": "Image_2", "type_name": "Image", "uid": 2},+ {"api": "Vulkan", "object_name": "Image_3", "type_name": "Image", "uid": 3},+ ]+ )+ elif "--metadata-logs-errors" in command:+ stdout = "Captured error A\nCaptured error B\n"+ elif "--metadata-logs" in command:+ stdout = "Captured info A\n"+ elif "--metadata" in command:+ stdout = json.dumps(+ {+ "nsight_version": "2026.1.0",+ "captured_frame": "2",+ "primary_api": "Vulkan",+ "primary_gpu": "NVIDIA GeForce RTX 4070 Ti",+ "driver_vendor": "NVIDIA",+ "driver_version": "591.74",+ "graphics_apis": {"Vulkan": ["general"]},+ }+ )+ else:+ stdout = f"{command[1]} output"+ return {+ "ok": True,+ "returncode": 0,+ "stdout": stdout,+ "stderr": "",+ "command": " ".join(command),+ }++ run_mock.side_effect = fake_run++ result = replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=True,+ logs=True,+ screenshot=True,+ perf_report=True,+ )++ assert result["ok"] is True+ assert result["capture_type"] == "graphics_capture"+ assert result["metadata"]["present"]["functions"] is True+ assert result["metadata"]["present"]["objects"] is True+ assert result["metadata"]["summary"]["primary_api"] == "Vulkan"+ assert result["metadata"]["summary"]["primary_gpu"] == "NVIDIA GeForce RTX 4070 Ti"+ assert result["metadata"]["functions"]["total"] == 3+ assert result["metadata"]["functions"]["top_functions"][0] == {"name": "vkQueueSubmit", "count": 2}+ assert result["metadata"]["objects"]["total"] == 3+ assert result["metadata"]["objects"]["top_types"][0] == {"name": "Image", "count": 2}+ assert result["logs"]["error_line_count"] == 2+ assert result["logs"]["error_summary"] == ["Captured error A", "Captured error B"]+ assert result["screenshot"]["present"] is True+ assert result["perf_report"]["present"] is True+ assert result["analysis"]["summary"]["object_count"] == 3+ assert result["analysis"]["summary"]["function_event_count"] == 3+ assert result["analysis"]["summary"]["log_error_count"] == 2+ assert any("Captured log errors" in warning for warning in result["analysis"]["warnings"])+ commands = [item["command"] for item in result["command_results"]]+ assert any("--metadata-objects" in command for command in commands)+ assert any("--metadata-logs" in command for command in commands)+ assert any("--metadata-screenshot" in command for command in commands)+ assert any("--perf-report-dir" in command for command in commands)++ @patch("cli_anything.nsight_graphics.core.replay.backend.run_command")+ @patch("cli_anything.nsight_graphics.core.replay.backend.probe_installation")+ def test_replay_analyze_defaults_to_metadata_logs_and_perf(self, probe_mock, run_mock, tmp_path):+ capture_file = tmp_path / "trace.ngfx-gputrace"+ capture_file.write_text("trace", encoding="utf-8")+ probe_mock.return_value = {+ "version": "2026.1.0",+ "tool_mode": "unified+split",+ "compatibility_mode": "unified+split",+ "binaries": {"ngfx_replay": "C:/Nsight/ngfx-replay.exe"},+ }++ def fake_run(command, timeout=120, cwd=None):+ if "--perf-report-dir" in command:+ perf_dir = Path(command[command.index("--perf-report-dir") + 1])+ perf_dir.mkdir(parents=True, exist_ok=True)+ (perf_dir / "report.txt").write_text("perf", encoding="utf-8")+ stdout = ""+ else:+ stdout = "output"+ return {+ "ok": True,+ "returncode": 0,+ "stdout": stdout,+ "stderr": "",+ "command": " ".join(command),+ }++ run_mock.side_effect = fake_run++ result = replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=False,+ logs=False,+ screenshot=False,+ perf_report=False,+ )++ assert result["capture_type"] == "gpu_trace"+ assert result["requested_outputs"] == {+ "metadata": True,+ "logs": True,+ "screenshot": False,+ "perf_report": True,+ }+ assert any(".ngfx-gputrace inputs may not produce metadata" in warning for warning in result["analysis"]["warnings"])++ @patch("cli_anything.nsight_graphics.core.replay.backend.run_command")+ @patch("cli_anything.nsight_graphics.core.replay.backend.probe_installation")+ def test_replay_analyze_filters_no_error_log_marker(self, probe_mock, run_mock, tmp_path):+ capture_file = tmp_path / "frame.ngfx-capture"+ capture_file.write_text("capture", encoding="utf-8")+ probe_mock.return_value = {+ "version": "2026.1.0",+ "tool_mode": "unified+split",+ "compatibility_mode": "unified+split",+ "binaries": {"ngfx_replay": "C:/Nsight/ngfx-replay.exe"},+ }++ def fake_run(command, timeout=120, cwd=None):+ stdout = "No log messages found with severity >= 2\n" if "--metadata-logs-errors" in command else ""+ return {+ "ok": True,+ "returncode": 0,+ "stdout": stdout,+ "stderr": "",+ "command": " ".join(command),+ }++ run_mock.side_effect = fake_run++ result = replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=False,+ logs=True,+ screenshot=False,+ perf_report=False,+ )++ assert result["ok"] is True+ assert result["logs"]["status"] == "no_errors"+ assert result["logs"]["error_line_count"] == 0+ assert result["logs"]["error_summary"] == []+ assert result["logs"]["raw_error_summary"] == ["No log messages found with severity >= 2"]+ assert any("no severity >= 2 errors" in item for item in result["analysis"]["highlights"])++ @patch("cli_anything.nsight_graphics.core.replay.backend.run_command")+ @patch("cli_anything.nsight_graphics.core.replay.backend.probe_installation")+ def test_replay_analyze_reports_gputrace_replay_incompatibility(self, probe_mock, run_mock, tmp_path):+ capture_file = tmp_path / "trace.ngfx-gputrace"+ capture_file.write_text("trace", encoding="utf-8")+ probe_mock.return_value = {+ "version": "2026.1.0",+ "tool_mode": "unified+split",+ "compatibility_mode": "unified+split",+ "binaries": {"ngfx_replay": "C:/Nsight/ngfx-replay.exe"},+ }++ def fake_run(command, timeout=120, cwd=None):+ is_log_command = "--metadata-logs" in command or "--metadata-logs-errors" in command+ return {+ "ok": not is_log_command,+ "returncode": 1 if is_log_command else 0,+ "stdout": "ERROR: Invalid file header (trace.ngfx-gputrace)\n" if is_log_command else "",+ "stderr": "",+ "command": " ".join(command),+ }++ run_mock.side_effect = fake_run++ result = replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=True,+ logs=True,+ screenshot=False,+ perf_report=False,+ )++ assert result["ok"] is False+ assert result["metadata"]["present"] == {"summary": False, "functions": False, "objects": False}+ assert result["logs"]["error_line_count"] == 1+ assert "Invalid file header" in result["logs"]["error_summary"][0]+ assert any(".ngfx-gputrace inputs may not produce metadata" in warning for warning in result["analysis"]["warnings"])+ assert any("Replay command failures" in warning for warning in result["analysis"]["warnings"])++ @patch("cli_anything.nsight_graphics.core.replay.backend.probe_installation")+ def test_replay_analyze_requires_ngfx_replay(self, probe_mock, tmp_path):+ capture_file = tmp_path / "frame.ngfx-capture"+ capture_file.write_text("capture", encoding="utf-8")+ probe_mock.return_value = {+ "binaries": {"ngfx_replay": None},+ }+ with pytest.raises(RuntimeError, match="ngfx-replay.exe is required"):+ replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=True,+ logs=False,+ screenshot=False,+ perf_report=False,+ )++ def test_replay_analyze_rejects_unknown_capture_extension(self, tmp_path):+ capture_file = tmp_path / "frame.rdc"+ capture_file.write_text("capture", encoding="utf-8")+ with pytest.raises(ValueError, match="Unsupported Nsight capture file extension"):+ replay.analyze_capture(+ nsight_path=None,+ capture_file=str(capture_file),+ output_dir=str(tmp_path / "analysis"),+ metadata=True,+ logs=False,+ screenshot=False,+ perf_report=False,+ )+class TestCLIHelp:def test_root_help(self):@@ -690,6 +1125,7 @@ class TestCLIHelp:(["frame", "--help"], "capture"),(["gpu-trace", "--help"], "capture"),(["gpu-trace", "--help"], "summarize"),+ (["replay", "--help"], "analyze"),(["cpp", "--help"], "capture"),],)@@ -702,6 +1138,42 @@ class TestCLIHelp:assert result.exit_code == 0assert needle in result.output+ def test_replay_analyze_json_cli(self, tmp_path):+ from click.testing import CliRunner+ from cli_anything.nsight_graphics.nsight_graphics_cli import cli++ capture_file = tmp_path / "frame.ngfx-capture"+ capture_file.write_text("capture", encoding="utf-8")+ runner = CliRunner()+ with patch("cli_anything.nsight_graphics.nsight_graphics_cli.replay.analyze_capture") as analyze_mock:+ analyze_mock.return_value = {+ "ok": True,+ "capture_file": str(capture_file),+ "capture_type": "graphics_capture",+ "output_dir": str(tmp_path / "analysis"),+ "artifact_count": 1,+ }+ result = runner.invoke(+ cli,+ [+ "--json",+ "replay",+ "analyze",+ "--capture-file",+ str(capture_file),+ "--output-dir",+ str(tmp_path / "analysis"),+ ],+ )++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["ok"] is True+ analyze_mock.assert_called_once()+ assert analyze_mock.call_args.kwargs["metadata"] is False+ assert analyze_mock.call_args.kwargs["logs"] is False+ assert analyze_mock.call_args.kwargs["perf_report"] is False+class TestCLISubprocess:def test_cli_help_subprocess(self):diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.pyindex 8d596072b..fa120747a 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.py@@ -15,26 +15,13 @@ import pytestfrom cli_anything.nsight_graphics.utils.nsight_graphics_backend import probe_installationHARNESS_ROOT = str(Path(__file__).resolve().parents[3])-DEFAULT_TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_TEST_EXE", "").strip()-DEFAULT_TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_TEST_ARGS", "").strip()-DEFAULT_TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_TEST_WORKDIR", "").strip()--FRAME_TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_FRAME_TEST_EXE", "").strip() or DEFAULT_TEST_EXE-FRAME_TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_FRAME_TEST_ARGS", "").strip() or DEFAULT_TEST_ARGS-FRAME_TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_FRAME_TEST_WORKDIR", "").strip() or DEFAULT_TEST_WORKDIR--GPU_TRACE_TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_GPU_TRACE_TEST_EXE", "").strip() or DEFAULT_TEST_EXE-GPU_TRACE_TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_GPU_TRACE_TEST_ARGS", "").strip() or DEFAULT_TEST_ARGS-GPU_TRACE_TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_GPU_TRACE_TEST_WORKDIR", "").strip() or DEFAULT_TEST_WORKDIR--CPP_TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_CPP_TEST_EXE", "").strip() or DEFAULT_TEST_EXE-CPP_TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_CPP_TEST_ARGS", "").strip() or DEFAULT_TEST_ARGS-CPP_TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_CPP_TEST_WORKDIR", "").strip() or DEFAULT_TEST_WORKDIR-+TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_TEST_EXE", "").strip()+TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_TEST_ARGS", "").strip()+TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_TEST_WORKDIR", "").strip()+TEST_CAPTURE_FILE = os.environ.get("NSIGHT_GRAPHICS_TEST_CAPTURE_FILE", "").strip()HAS_NSIGHT = bool(probe_installation().get("ok"))-HAS_FRAME_TEST_EXE = bool(FRAME_TEST_EXE and os.path.isfile(FRAME_TEST_EXE))-HAS_GPU_TRACE_TEST_EXE = bool(GPU_TRACE_TEST_EXE and os.path.isfile(GPU_TRACE_TEST_EXE))-HAS_CPP_TEST_EXE = bool(CPP_TEST_EXE and os.path.isfile(CPP_TEST_EXE))+HAS_TEST_EXE = bool(TEST_EXE and os.path.isfile(TEST_EXE))+HAS_TEST_CAPTURE_FILE = bool(TEST_CAPTURE_FILE and os.path.isfile(TEST_CAPTURE_FILE))def _resolve_cli(name: str) -> list[str]:@@ -63,18 +50,8 @@ def _resolve_cli(name: str) -> list[str]:CLI_BASE = _resolve_cli("cli-anything-nsight-graphics")skip_no_nsight = pytest.mark.skipif(not HAS_NSIGHT, reason="Nsight Graphics not installed")-skip_no_frame_target = pytest.mark.skipif(- not HAS_FRAME_TEST_EXE,- reason="NSIGHT_GRAPHICS_FRAME_TEST_EXE or NSIGHT_GRAPHICS_TEST_EXE not set or missing",-)-skip_no_gpu_trace_target = pytest.mark.skipif(- not HAS_GPU_TRACE_TEST_EXE,- reason="NSIGHT_GRAPHICS_GPU_TRACE_TEST_EXE or NSIGHT_GRAPHICS_TEST_EXE not set or missing",-)-skip_no_cpp_target = pytest.mark.skipif(- not HAS_CPP_TEST_EXE,- reason="NSIGHT_GRAPHICS_CPP_TEST_EXE or NSIGHT_GRAPHICS_TEST_EXE not set or missing",-)+skip_no_target = pytest.mark.skipif(not HAS_TEST_EXE, reason="NSIGHT_GRAPHICS_TEST_EXE not set or missing")+skip_no_capture = pytest.mark.skipif(not HAS_TEST_CAPTURE_FILE, reason="NSIGHT_GRAPHICS_TEST_CAPTURE_FILE not set or missing")def _run_json(*args: str, timeout: int = 600) -> dict:@@ -91,13 +68,13 @@ def _run_json(*args: str, timeout: int = 600) -> dict:return json.loads(result.stdout)-def _target_args(exe_path: str, args_text: str, workdir: str) -> list[str]:- """Build repeated CLI args for a configured activity target."""- args = ["--exe", exe_path]- if workdir:- args.extend(["--dir", workdir])- if args_text:- for entry in shlex.split(args_text, posix=os.name != "nt"):+def _target_args() -> list[str]:+ """Build repeated CLI args for the configured test executable."""+ args = ["--exe", TEST_EXE]+ if TEST_WORKDIR:+ args.extend(["--dir", TEST_WORKDIR])+ if TEST_ARGS:+ for entry in shlex.split(TEST_ARGS, posix=os.name != "nt"):args.extend(["--arg", entry])return args@@ -107,56 +84,104 @@ class TestDoctorE2E:def test_doctor_info(self):data = _run_json("doctor", "info", timeout=60)assert data["ok"] is True- assert data["compatibility_mode"] in {"unified", "split"}+ assert data["compatibility_mode"] in {"unified", "split", "unified+split"}assert data["resolved_executable"]@skip_no_nsight+@skip_no_targetclass TestTargetedE2E:- @skip_no_frame_targetdef test_frame_capture(self, tmp_path):data = _run_json("--output-dir",str(tmp_path),"frame","capture",- *_target_args(FRAME_TEST_EXE, FRAME_TEST_ARGS, FRAME_TEST_WORKDIR),+ *_target_args(),"--wait-seconds","1",)assert data["ok"] is Trueassert data["artifacts"]assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])+ capture_files = [Path(item["path"]) for item in data["artifacts"] if Path(item["path"]).suffix.lower() == ".ngfx-capture"]+ if capture_files:+ analysis = _run_json(+ "replay",+ "analyze",+ "--capture-file",+ str(capture_files[0]),+ "--output-dir",+ str(tmp_path / "frame_replay_analysis"),+ "--metadata",+ "--logs",+ timeout=600,+ )+ assert analysis["ok"] is True+ assert analysis["metadata"]["present"]["summary"] is True+ assert analysis["analysis"]["summary"]["primary_api"]+ assert analysis["analysis"]["summary"]["function_event_count"] > 0- @skip_no_gpu_trace_targetdef test_gpu_trace_capture(self, tmp_path):data = _run_json("--output-dir",str(tmp_path),"gpu-trace","capture",- *_target_args(GPU_TRACE_TEST_EXE, GPU_TRACE_TEST_ARGS, GPU_TRACE_TEST_WORKDIR),+ *_target_args(),"--start-after-ms","1000","--limit-to-frames","1","--auto-export",+ "--summarize",)assert data["ok"] is Trueassert data["artifacts"]assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])+ assert data["summary"]["tables"]["trace_frame"]["metric_count"] > 0+ assert "metric_inventory" in data["summary"]+ assert data["summary"]["analysis"]["frame_budget"]["bucket"] in {+ "within_60fps_budget",+ "over_60fps_budget",+ "over_30fps_budget",+ }- @skip_no_cpp_targetdef test_cpp_capture(self, tmp_path):data = _run_json("--output-dir",str(tmp_path),"cpp","capture",- *_target_args(CPP_TEST_EXE, CPP_TEST_ARGS, CPP_TEST_WORKDIR),+ *_target_args(),"--wait-seconds","1",)assert data["ok"] is Trueassert data["artifacts"]assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])+++@skip_no_nsight+@skip_no_capture+class TestReplayE2E:+ def test_replay_analyze_existing_capture(self, tmp_path):+ data = _run_json(+ "replay",+ "analyze",+ "--capture-file",+ TEST_CAPTURE_FILE,+ "--output-dir",+ str(tmp_path),+ "--metadata",+ "--logs",+ timeout=600,+ )+ assert data["ok"] is True+ assert data["artifacts"]+ assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])+ assert data["metadata"]["present"]["summary"] is True+ assert data["metadata"]["summary"]["primary_api"]+ assert data["metadata"]["functions"]["total"] > 0+ assert data["metadata"]["objects"]["total"] > 0+ assert "log_error_count" in data["analysis"]["summary"]diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/commands.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/commands.pyindex cdea16813..077a21727 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/commands.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/commands.py@@ -3,6 +3,7 @@from __future__ import annotationsimport subprocess+from pathlib import Pathfrom typing import Optional, Sequencefrom cli_anything.nsight_graphics.utils.backend.discovery import INSTALL_INSTRUCTIONS@@ -22,6 +23,15 @@ def require_launch_target(*, project: Optional[str], exe: Optional[str]) -> Noneraise ValueError("Specify --exe or set --project at the root level.")+def prepare_output_dir(output_dir: Optional[str]) -> Optional[str]:+ """Resolve and create an explicit output directory before invoking Nsight."""+ if not output_dir:+ return None+ resolved = Path(output_dir).resolve()+ resolved.mkdir(parents=True, exist_ok=True)+ return str(resolved)++def ensure_exactly_one(label: str, flags: dict[str, bool]) -> str:"""Validate that exactly one flag in the set is selected."""selected = [name for name, enabled in flags.items() if enabled]@@ -148,3 +158,14 @@ def build_split_capture_command(else:command.append("--capture-hotkey")return command+++def build_replay_command(+ binaries: dict[str, Optional[str]],+ *,+ capture_file: str,+ extra_args: Sequence[str] = (),+) -> list[str]:+ """Build a command line for ngfx-replay."""+ replay = require_binary(binaries, "ngfx_replay")+ return [replay, *extra_args, capture_file]diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/discovery.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/discovery.pyindex e1585351d..1b2d36e2e 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/discovery.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/backend/discovery.py@@ -200,9 +200,13 @@ def _override_value(def detect_tool_mode(binaries: dict[str, Optional[str]]) -> str:"""Return compatibility mode for the discovered binaries."""- if binaries.get("ngfx_capture") or binaries.get("ngfx_replay"):+ has_unified = bool(binaries.get("ngfx"))+ has_split = bool(binaries.get("ngfx_capture") or binaries.get("ngfx_replay"))+ if has_unified and has_split:+ return "unified+split"+ if has_split:return "split"- if binaries.get("ngfx"):+ if has_unified:return "unified"return "missing"@@ -474,7 +478,7 @@ def probe_installation(nsight_path: Optional[str] = None) -> dict[str, Any]:)if mode == "missing":warnings.append(INSTALL_INSTRUCTIONS)- if mode == "split" and not binaries.get("ngfx"):+ if mode == "split":warnings.append("Split capture/replay tools were found without ngfx.exe; launch, attach, ""GPU Trace, and C++ Capture helpers may be unavailable."diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.pyindex bfbde70e6..35ea68ca5 100644--- a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.py+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.py@@ -4,11 +4,13 @@ from __future__ import annotationsfrom cli_anything.nsight_graphics.utils.backend.commands import (build_split_capture_command,+ build_replay_command,build_unified_command,ensure_at_most_one,ensure_exactly_one,format_env_values,format_program_args,+ prepare_output_dir,require_binary,require_launch_target,)@@ -75,6 +77,7 @@ __all__ = ["_scan_directory","_version_sort_key","activity_artifact_roots",+ "build_replay_command","build_split_capture_command","build_unified_command","default_output_dir",@@ -89,6 +92,7 @@ __all__ = ["list_installations","parse_option_help","parse_unified_help",+ "prepare_output_dir","probe_installation","require_binary","require_launch_target",diff --git a/nsight-graphics/agent-harness/setup.py b/nsight-graphics/agent-harness/setup.pyindex bfa2e2c60..70d7dfe5f 100644--- a/nsight-graphics/agent-harness/setup.py+++ b/nsight-graphics/agent-harness/setup.py@@ -9,7 +9,7 @@ _LONG_DESC = _README.read_text(encoding="utf-8") if _README.is_file() else ""setup(name="cli-anything-nsight-graphics",- version="0.1.0",+ version="0.2.0",description="CLI harness for NVIDIA Nsight Graphics orchestration",long_description=_LONG_DESC,long_description_content_type="text/markdown",diff --git a/registry.json b/registry.jsonindex 7deef2280..57ee02753 100644--- a/registry.json+++ b/registry.json@@ -710,14 +710,14 @@{"name": "nsight-graphics","display_name": "Nsight Graphics CLI",- "version": "0.1.0",- "description": "Windows-first Nsight Graphics CLI for Graphics/Frame capture, GPU Trace, Generate C++ Capture, and one-step GPU Trace summary",- "requires": "NVIDIA Nsight Graphics installation with ngfx.exe or newer split capture/replay tools",+ "version": "0.2.0",+ "description": "Windows-first Nsight Graphics CLI for Graphics/OpenGL capture, GPU Trace summary, Generate C++ Capture, and ngfx-replay analysis",+ "requires": "NVIDIA Nsight Graphics installation with ngfx.exe plus optional split capture/replay tools","homepage": "https://developer.nvidia.com/nsight-graphics","source_url": null,"install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=nsight-graphics/agent-harness","entry_point": "cli-anything-nsight-graphics",- "skill_md": "nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md",+ "skill_md": "skills/cli-anything-nsight-graphics/SKILL.md","category": "graphics","contributors": [{diff --git a/skills/cli-anything-nsight-graphics/SKILL.md b/skills/cli-anything-nsight-graphics/SKILL.mdindex 17cfa47f4..7eaf047c2 100644--- a/skills/cli-anything-nsight-graphics/SKILL.md+++ b/skills/cli-anything-nsight-graphics/SKILL.md@@ -1,7 +1,7 @@---name: "cli-anything-nsight-graphics"-description: Windows-first CLI harness for Nsight Graphics launch, frame capture, GPU Trace, and C++ Capture orchestration-version: 0.1.0+description: Windows-first CLI harness for Nsight Graphics capture, GPU Trace summary, and ngfx-replay analysis+version: 0.2.0command: cli-anything-nsight-graphicsinstall: pip install cli-anything-nsight-graphicsrequires:@@ -23,8 +23,10 @@ Command-line orchestration of official NVIDIA Nsight Graphics activities.- Probe installed Nsight binaries and compatibility mode- Launch an application detached under Nsight- Attach Nsight to a running PID-- Trigger Frame Debugger capture+- Trigger Graphics Capture or OpenGL Frame Debugger capture- Trigger GPU Trace capture, auto-export, and summarize+- Analyze existing `.ngfx-capture` files through `ngfx-replay`+- Report clear compatibility diagnostics for `.ngfx-gputrace` inputs- Trigger Generate C++ Capture## Commands@@ -40,8 +42,8 @@ cli-anything-nsight-graphics --nsight-path "C:\Path\To\Nsight Graphics 2024.2\ho### launch```bash-cli-anything-nsight-graphics launch detached --activity "Frame Debugger" --exe "C:\Path\To\App.exe"-cli-anything-nsight-graphics launch attach --activity "Frame Debugger" --pid 12345+cli-anything-nsight-graphics launch detached --activity "Graphics Capture" --exe "C:\Path\To\App.exe"+cli-anything-nsight-graphics launch attach --activity "Graphics Capture" --pid 12345```### frame capture@@ -66,6 +68,14 @@ cli-anything-nsight-graphics gpu-trace summarize ^--input-dir D:\traces```+### Replay analysis++```bash+cli-anything-nsight-graphics --json replay analyze ^+ --capture-file D:\captures\frame.ngfx-capture ^+ --output-dir D:\analysis+```+### Generate C++ Capture```bash@@ -80,8 +90,21 @@ cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^- Use `doctor versions` to list detected installs when multiple Nsight Graphics versions exist.- Use `--nsight-path` to force a specific install directory or `ngfx.exe`.- Use `--json` for programmatic workflows.-- Prefer `gpu-trace capture --auto-export --summarize` for one-step performance triage.+- Prefer `gpu-trace capture --auto-export --summarize` for one-step performance+ triage. The summary includes exported table inventory, metric inventory,+ frame-budget classification, workload classification, throughput ranking,+ bottleneck hints, and warnings for empty event/regime tables.+- Use `replay analyze` when the input is an existing `.ngfx-capture` file. With+ no analysis switches it exports metadata, logs, captured log errors, and a+ replay performance report, then adds structured `analysis.highlights` /+ `analysis.warnings`.+- `ngfx-replay` documents its input as a Graphics Capture file. `.ngfx-gputrace`+ inputs are accepted for clear diagnostics, but on Nsight Graphics 2026.1.0+ they may report `Invalid file header`; use `gpu-trace summarize` for exported+ GPU Trace table analysis.+- `replay analyze` uses official `ngfx-replay` metadata/log/screenshot/perf-report+ outputs; it is not a RenderDoc-style shader, pipeline, texture, or resource inspector.- Frame/GPU/C++ capture commands require a launch target through `--exe` or apreconfigured root-level `--project`.-- V1 is orchestration-focused; it does not expose shader, pipeline, or resource- inspection commands.+- If a global `cli-anything-nsight-graphics` command points at an old worktree,+ reinstall from `nsight-graphics/agent-harness` with `python -m pip install -e .`.