From b6a4dcfdc7a84ca635b3a66c9f133a6d1f8065e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Mon, 16 Nov 2026 01:48:46 +0300 Subject: [PATCH 1/3] fix: bound post-test process snapshots --- .github/workflows/ci.yml | 1 + .github/workflows/native.yml | 4 ++ docs/architecture/hosting-and-packaging.md | 4 +- docs/engineering/quality-gates.md | 3 +- .../Native/NativeProcessSnapshotTests.cs | 69 +++++++++++++++++++ .../Native/NativeProcessSnapshot.cs | 4 +- .../Native/NativeProcesses.cs | 8 +-- 7 files changed, 85 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 384fa3d..7090a05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -294,6 +294,7 @@ jobs: retention-days: 7 - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index dadf643..a298832 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -121,6 +121,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') @@ -224,6 +225,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') @@ -331,6 +333,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') @@ -458,6 +461,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') diff --git a/docs/architecture/hosting-and-packaging.md b/docs/architecture/hosting-and-packaging.md index fd1b071..490b7c4 100644 --- a/docs/architecture/hosting-and-packaging.md +++ b/docs/architecture/hosting-and-packaging.md @@ -312,7 +312,9 @@ not a second distributed product. The entry is compiled separately from the solu and pulls the manifest runtime image before this command; neither preparation runs inside the test step's budget. The proof still inspects the local image before using it. - `snapshot --output ` records PID, process name, CPU, working set, age and command line, - sorted by CPU descending, in `processes.txt`; its first 25 rows also reach the job log. + sorted by CPU descending, in `processes.txt` and logs its first 25 rows with a two-minute query + bound, using one bounded CIM query for Windows command lines and an empty command-line field + for a row without one. - `validate --receipts [--manifest ]` checks the manifest's complete ordered receipt set, common source/SDK/version/dependency identities, successful publish and three test runs, effective properties, warning results, manifest runner/image identities, payload manifests, archive diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index 0dbbff6..ff6262b 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -243,7 +243,8 @@ snapshots; upload failures remain blocking. Artifact names are unique per job/pe Completed receipts are uploaded only after successful proof; validation has no `always()` override and starts only when all needed jobs succeed. Both workflows prebuild the file-based entry in a normal step before tests. Process snapshots run with `always()` and -`--no-build` through the shared `snapshot` subcommand in both workflows. Upload errors remain +`--no-build` through the shared `snapshot` subcommand in both workflows, with five-minute bounds on +the CI, native-build, Linux-proof and package snapshot steps. Upload errors remain blocking. The validation success and its log establish the complete-set result; no index file or separate job-result input stands in for that dependency graph. The native workflow must be green at the pull request's head before queue entry, including hosted parsing and all six RIDs. diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs index 3cbf2e2..cd31841 100644 --- a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs @@ -3,13 +3,38 @@ using OpenCode.Mcp.Tools.Native; using OpenCode.Mcp.Tools.Native.Abstractions; using OpenCode.Mcp.Tools.Tests.Native.Support; +using Testably.Abstractions; using Testably.Abstractions.Testing; using TUnit.Assertions.Enums; namespace OpenCode.Mcp.Tools.Tests.Native; +[NotInParallel("processes")] public sealed class NativeProcessSnapshotTests { + private const string SnapshotQuery = "$ErrorActionPreference='Stop'; $commandLines=@{}; if ($IsWindows) {try {Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | ForEach-Object {$commandLines[[int]$_.ProcessId]=$_.CommandLine}} catch {$commandLines=@{}}}; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if ($IsWindows) {$commandLines[$_.Id]} else {$_.CommandLine}}} | ConvertTo-Json -Compress"; + + [Test] + [Timeout(30_000)] + public async Task RecordAsync_Should_Send_One_Two_Minute_PowerShell_Query(CancellationToken token) + { + var files = new MockFileSystem(); + var now = DateTimeOffset.UtcNow; + var runner = new FakeNativeProcessRunner + { + Response = async (request, _) => + { + await Assert.That(request.Timeout).IsEqualTo(TimeSpan.FromMinutes(2)); + await Assert.That(request.FileName).IsEqualTo("pwsh"); + await Assert.That(request.Arguments).IsEquivalentTo(["-NoProfile", "-NonInteractive", "-Command", SnapshotQuery], CollectionOrdering.Matching); + return new NativeProcessResult(0, Query(now), ""); + }, + }; + await new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), TextWriter.Null) + .RecordAsync(files.Path.Combine(files.Path.GetTempPath(), "snapshot"), () => now, token); + await Assert.That(runner.Calls).Count().IsEqualTo(1); + } + [Test] [Timeout(30_000)] public async Task RecordAsync_Should_Timestamp_After_The_Process_Query(CancellationToken token) @@ -63,6 +88,50 @@ public async Task RecordAsync_Should_Preserve_The_Ci_Evidence_Fields_And_Cpu_Ord await Assert.That(logged.Select(static line => int.Parse(line.Split('|')[0], CultureInfo.InvariantCulture))).IsEquivalentTo(order.Take(25), CollectionOrdering.Matching); } + [Test] + [Timeout(30_000)] + public async Task RecordAsync_Should_Format_Null_CommandLine_As_Empty_In_Cpu_Order(CancellationToken token) + { + var files = new MockFileSystem(); + var now = new DateTimeOffset(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + var rows = new[] + { + new { Id = 1, ProcessName = "lower", CPU = 1, WorkingSet64 = 1_048_576L, StartTime = now, CommandLine = (string?)"command" }, + new { Id = 2, ProcessName = "higher", CPU = 2, WorkingSet64 = 2_097_152L, StartTime = now, CommandLine = (string?)null }, + }; + var runner = new FakeNativeProcessRunner { Response = (_, _) => Task.FromResult(new NativeProcessResult(0, JsonSerializer.Serialize(rows), "")) }; + var root = files.Path.Combine(files.Path.GetTempPath(), "snapshot"); + await new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), TextWriter.Null).RecordAsync(root, () => now, token); + await Assert.That(await files.File.ReadAllLinesAsync(files.Path.Combine(root, "processes.txt"), token)).IsEquivalentTo( + ["2|higher|cpu=" + 2d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=2MB|age=0s|", "1|lower|cpu=" + 1d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=1MB|age=0s|command"], CollectionOrdering.Matching); + } + + [Test] + [Timeout(150_000)] + public async Task RecordAsync_Should_Query_The_Real_Test_Host(CancellationToken token) + { + var files = new MockFileSystem(); + var runner = new FakeNativeProcessRunner + { + Response = async (request, cancellation) => + { + var result = await new SystemNativeProcessRunner().RunAsync(request, cancellation); + await Assert.That(result.ExitCode).IsEqualTo(0); + using var json = JsonDocument.Parse(result.StandardOutput); + await Assert.That(json.RootElement.ValueKind).IsEqualTo(JsonValueKind.Array); + var host = json.RootElement.EnumerateArray().Single(row => row.GetProperty("Id").GetInt32() == Environment.ProcessId); + await Assert.That(host.GetProperty("ProcessName").GetString()).IsNotNullOrEmpty(); + if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()) + { + await Assert.That(host.GetProperty("CommandLine").GetString()).IsNotNullOrEmpty(); + } + return result; + }, + }; + await new NativeProcessSnapshot(files, runner, new RealFileSystem().Path.GetTempPath(), TextWriter.Null) + .RecordAsync(files.Path.Combine(files.Path.GetTempPath(), "snapshot"), () => DateTimeOffset.UtcNow, token); + } + private static string Query(DateTimeOffset now) => JsonSerializer.Serialize(Enumerable.Range(0, 26).Select(index => new { Id = index, diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs b/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs index ddf00ce..02c23f9 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs @@ -7,13 +7,13 @@ namespace OpenCode.Mcp.Tools.Native; internal sealed class NativeProcessSnapshot(IFileSystem files, INativeProcessRunner runner, string root, TextWriter output) { - private const string Query = "$ErrorActionPreference='Stop'; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},CommandLine | ConvertTo-Json -Compress"; + private const string Query = "$ErrorActionPreference='Stop'; $commandLines=@{}; if ($IsWindows) {try {Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | ForEach-Object {$commandLines[[int]$_.ProcessId]=$_.CommandLine}} catch {$commandLines=@{}}}; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if ($IsWindows) {$commandLines[$_.Id]} else {$_.CommandLine}}} | ConvertTo-Json -Compress"; public async Task RecordAsync(string directory, Func timestamp, CancellationToken token) { files.Directory.CreateDirectory(directory); var json = await new NativeProcesses(runner, root).RequireAsync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", Query], - new Dictionary(StringComparer.Ordinal), token).ConfigureAwait(false); + new Dictionary(StringComparer.Ordinal), token, TimeSpan.FromMinutes(2)).ConfigureAwait(false); var now = timestamp(); using var processes = JsonDocument.Parse(json); var lines = processes.RootElement.EnumerateArray().OrderByDescending(static process => Cpu(process)) diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeProcesses.cs b/tools/OpenCode.Mcp.Tools/Native/NativeProcesses.cs index b2fde60..05dc9c1 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeProcesses.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeProcesses.cs @@ -6,14 +6,14 @@ namespace OpenCode.Mcp.Tools.Native; internal sealed class NativeProcesses(INativeProcessRunner runner, string root) { public Task RunAsync(string fileName, IReadOnlyList arguments, - IReadOnlyDictionary environment, CancellationToken token) => + IReadOnlyDictionary environment, CancellationToken token, TimeSpan? timeout = null) => runner.RunAsync(new NativeProcessRequest(fileName, arguments, root, environment, - TimeSpan.FromMinutes(fileName == "dotnet" && arguments.Count != 0 && arguments[0] == "test" ? 30 : 35)), token); + timeout ?? TimeSpan.FromMinutes(fileName == "dotnet" && arguments.Count != 0 && arguments[0] == "test" ? 30 : 35)), token); public async Task RequireAsync(string fileName, IReadOnlyList arguments, - IReadOnlyDictionary environment, CancellationToken token) + IReadOnlyDictionary environment, CancellationToken token, TimeSpan? timeout = null) { - var result = await RunAsync(fileName, arguments, environment, token).ConfigureAwait(false); + var result = await RunAsync(fileName, arguments, environment, token, timeout).ConfigureAwait(false); if (result.ExitCode != 0) { throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture, $"{fileName} {string.Join(' ', arguments)} exited {result.ExitCode}:\n{result.Output}")); From c10bd354243bfde69b4e4930ad68d5b9804d89dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Mon, 16 Nov 2026 01:58:01 +0300 Subject: [PATCH 2/3] ci: bound all post-test process snapshots --- .github/workflows/native.yml | 2 ++ docs/architecture/hosting-and-packaging.md | 2 +- docs/engineering/quality-gates.md | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index a298832..71ab1a8 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -1880,6 +1880,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') exit $LASTEXITCODE @@ -1977,6 +1978,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after tests if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') diff --git a/docs/architecture/hosting-and-packaging.md b/docs/architecture/hosting-and-packaging.md index 490b7c4..23283d6 100644 --- a/docs/architecture/hosting-and-packaging.md +++ b/docs/architecture/hosting-and-packaging.md @@ -1,6 +1,6 @@ # Hosting and Packaging Architecture -Date: 2026-11-15 +Date: 2026-11-16 Canonical current rules for product identity, projects, the build toolchain, dependencies, versioning, the Aspire development graph, Native AOT, NuGet packaging, installation and release diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index ff6262b..7a2bf10 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -1,6 +1,6 @@ # Engineering Quality Gates -Date: 2026-11-15 +Date: 2026-11-16 Canonical quality policy for product code, repository tooling, tests, analyzers, dependencies, performance evidence, and completion claims. @@ -244,7 +244,7 @@ Completed receipts are uploaded only after successful proof; validation has no `always()` override and starts only when all needed jobs succeed. Both workflows prebuild the file-based entry in a normal step before tests. Process snapshots run with `always()` and `--no-build` through the shared `snapshot` subcommand in both workflows, with five-minute bounds on -the CI, native-build, Linux-proof and package snapshot steps. Upload errors remain +every process-snapshot step. Upload errors remain blocking. The validation success and its log establish the complete-set result; no index file or separate job-result input stands in for that dependency graph. The native workflow must be green at the pull request's head before queue entry, including hosted parsing and all six RIDs. From aa7c3d9899ff7c80d4fbcfa15355f5f6f4023e14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Mon, 16 Nov 2026 02:20:45 +0300 Subject: [PATCH 3/3] fix: isolate optional process command line queries --- .github/workflows/native.yml | 1 + .github/workflows/verify-channel.yml | 1 + docs/architecture/hosting-and-packaging.md | 7 +- docs/engineering/quality-gates.md | 4 +- .../Native/NativeProcessSnapshotTests.cs | 107 +++++++++++++++--- .../Native/NativeProcessSnapshot.cs | 50 +++++++- 6 files changed, 144 insertions(+), 26 deletions(-) diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index 71ab1a8..a3d66ae 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -531,6 +531,7 @@ jobs: exit $LASTEXITCODE - name: Record processes after assembly if: always() + timeout-minutes: 5 run: | $ErrorActionPreference = 'Stop' dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'process-snapshot') diff --git a/.github/workflows/verify-channel.yml b/.github/workflows/verify-channel.yml index 629858a..c91a10c 100644 --- a/.github/workflows/verify-channel.yml +++ b/.github/workflows/verify-channel.yml @@ -533,6 +533,7 @@ jobs: exit $LASTEXITCODE - name: Always record prebuilt process snapshot if: always() + timeout-minutes: 5 run: | dotnet run --no-build tools/native.cs -- snapshot --output (Join-Path $env:RUNNER_TEMP 'channel-snapshot') exit $LASTEXITCODE diff --git a/docs/architecture/hosting-and-packaging.md b/docs/architecture/hosting-and-packaging.md index 23283d6..82a48af 100644 --- a/docs/architecture/hosting-and-packaging.md +++ b/docs/architecture/hosting-and-packaging.md @@ -312,9 +312,10 @@ not a second distributed product. The entry is compiled separately from the solu and pulls the manifest runtime image before this command; neither preparation runs inside the test step's budget. The proof still inspects the local image before using it. - `snapshot --output ` records PID, process name, CPU, working set, age and command line, - sorted by CPU descending, in `processes.txt` and logs its first 25 rows with a two-minute query - bound, using one bounded CIM query for Windows command lines and an empty command-line field - for a row without one. + sorted by CPU descending, in `processes.txt` and logs its first 25 rows. The process query has a + two-minute bound; Windows command lines use a separate 45-second CIM query before it. Missing + command lines have empty fields; a failed command-line query is reported as the first line of + the snapshot and of the log. - `validate --receipts [--manifest ]` checks the manifest's complete ordered receipt set, common source/SDK/version/dependency identities, successful publish and three test runs, effective properties, warning results, manifest runner/image identities, payload manifests, archive diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index 7a2bf10..d2cecbe 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -243,8 +243,8 @@ snapshots; upload failures remain blocking. Artifact names are unique per job/pe Completed receipts are uploaded only after successful proof; validation has no `always()` override and starts only when all needed jobs succeed. Both workflows prebuild the file-based entry in a normal step before tests. Process snapshots run with `always()` and -`--no-build` through the shared `snapshot` subcommand in both workflows, with five-minute bounds on -every process-snapshot step. Upload errors remain +`--no-build` through the shared `snapshot` subcommand in CI, Native and channel verification, with +five-minute bounds on every process-snapshot step. Upload errors remain blocking. The validation success and its log establish the complete-set result; no index file or separate job-result input stands in for that dependency graph. The native workflow must be green at the pull request's head before queue entry, including hosted parsing and all six RIDs. diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs index cd31841..421ffcd 100644 --- a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs @@ -12,27 +12,53 @@ namespace OpenCode.Mcp.Tools.Tests.Native; [NotInParallel("processes")] public sealed class NativeProcessSnapshotTests { - private const string SnapshotQuery = "$ErrorActionPreference='Stop'; $commandLines=@{}; if ($IsWindows) {try {Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | ForEach-Object {$commandLines[[int]$_.ProcessId]=$_.CommandLine}} catch {$commandLines=@{}}}; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if ($IsWindows) {$commandLines[$_.Id]} else {$_.CommandLine}}} | ConvertTo-Json -Compress"; + private const string SnapshotQuery = "$ErrorActionPreference='Stop'; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if (-not $IsWindows) {$_.CommandLine}}} | ConvertTo-Json -Compress"; + private const string CommandLineQuery = "$ErrorActionPreference='Stop'; Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"; [Test] + [Arguments("timeout", "command lines unavailable: CIM query timed out after 45 s")] + [Arguments("exit", "command lines unavailable: CIM query exited 7")] + [Arguments("unreadable", "command lines unavailable: CIM query returned unreadable output")] + [Arguments("", "command lines unavailable: CIM query returned unreadable output")] [Timeout(30_000)] - public async Task RecordAsync_Should_Send_One_Two_Minute_PowerShell_Query(CancellationToken token) + public async Task RecordAsync_Should_Report_Unavailable_CommandLines_And_Still_Query_Processes(string failure, string diagnostic, CancellationToken token) { var files = new MockFileSystem(); var now = DateTimeOffset.UtcNow; var runner = new FakeNativeProcessRunner { - Response = async (request, _) => + Response = (request, _) => request.Arguments[^1].Contains("Get-CimInstance", StringComparison.Ordinal) ? failure switch { - await Assert.That(request.Timeout).IsEqualTo(TimeSpan.FromMinutes(2)); - await Assert.That(request.FileName).IsEqualTo("pwsh"); - await Assert.That(request.Arguments).IsEquivalentTo(["-NoProfile", "-NonInteractive", "-Command", SnapshotQuery], CollectionOrdering.Matching); - return new NativeProcessResult(0, Query(now), ""); - }, + "timeout" => throw new OperationCanceledException("query timeout"), + "exit" => Task.FromResult(new NativeProcessResult(7, "", "query failed")), + _ => Task.FromResult(new NativeProcessResult(0, failure, "")), + } : Task.FromResult(new NativeProcessResult(0, Query(now), "")), + }; + var root = files.Path.Combine(files.Path.GetTempPath(), "snapshot"); + using var output = new StringWriter(CultureInfo.InvariantCulture); + await new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), output).RecordAsync(root, () => now, token); + var expected = Enumerable.Range(0, 26).Reverse().Select(index => string.Create(CultureInfo.CurrentCulture, + $"{index}|process{index}|cpu={index:N1}s|ws={index}MB|age={index}s|{(OperatingSystem.IsWindows() ? "" : "command" + index.ToString(CultureInfo.InvariantCulture))}")).ToArray(); + await Assert.That(await files.File.ReadAllLinesAsync(files.Path.Combine(root, "processes.txt"), token)) + .IsEquivalentTo(OperatingSystem.IsWindows() ? [diagnostic, .. expected] : expected, CollectionOrdering.Matching); + string[] logged = OperatingSystem.IsWindows() ? [diagnostic, .. expected.Take(25)] : [.. expected.Take(25)]; + await Assert.That(output.ToString().Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)).IsEquivalentTo(logged, CollectionOrdering.Matching); + await AssertRequestsAsync(runner); + } + + [Test] + [Timeout(30_000)] + public async Task RecordAsync_Should_Send_Bounded_PowerShell_Queries_In_Order(CancellationToken token) + { + var files = new MockFileSystem(); + var now = DateTimeOffset.UtcNow; + var runner = new FakeNativeProcessRunner + { + Response = (_, _) => Task.FromResult(new NativeProcessResult(0, Query(now), "")), }; await new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), TextWriter.Null) .RecordAsync(files.Path.Combine(files.Path.GetTempPath(), "snapshot"), () => now, token); - await Assert.That(runner.Calls).Count().IsEqualTo(1); + await AssertRequestsAsync(runner); } [Test] @@ -47,7 +73,7 @@ public async Task RecordAsync_Should_Timestamp_After_The_Process_Query(Cancellat { var started = now.AddSeconds(2); now = now.AddSeconds(5); - var json = JsonSerializer.Serialize(new[] { new { Id = 7, ProcessName = "inside-query", CPU = 1, WorkingSet64 = 1_048_576L, StartTime = started, CommandLine = "query-child" } }); + var json = JsonSerializer.Serialize(new[] { new { Id = 7, ProcessId = 7, ProcessName = "inside-query", CPU = 1, WorkingSet64 = 1_048_576L, StartTime = started, CommandLine = "query-child" } }); return Task.FromResult(new NativeProcessResult(0, json, "")); }, }; @@ -99,15 +125,42 @@ public async Task RecordAsync_Should_Format_Null_CommandLine_As_Empty_In_Cpu_Ord new { Id = 1, ProcessName = "lower", CPU = 1, WorkingSet64 = 1_048_576L, StartTime = now, CommandLine = (string?)"command" }, new { Id = 2, ProcessName = "higher", CPU = 2, WorkingSet64 = 2_097_152L, StartTime = now, CommandLine = (string?)null }, }; - var runner = new FakeNativeProcessRunner { Response = (_, _) => Task.FromResult(new NativeProcessResult(0, JsonSerializer.Serialize(rows), "")) }; + var commandLines = new[] { new { ProcessId = 99, CommandLine = "unrelated" }, new { ProcessId = 1, CommandLine = "mapped-command" } }; + var runner = new FakeNativeProcessRunner + { + Response = (request, _) => Task.FromResult(new NativeProcessResult(0, + request.Arguments[^1] == CommandLineQuery ? JsonSerializer.Serialize(commandLines) : JsonSerializer.Serialize(rows), "")), + }; var root = files.Path.Combine(files.Path.GetTempPath(), "snapshot"); await new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), TextWriter.Null).RecordAsync(root, () => now, token); await Assert.That(await files.File.ReadAllLinesAsync(files.Path.Combine(root, "processes.txt"), token)).IsEquivalentTo( - ["2|higher|cpu=" + 2d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=2MB|age=0s|", "1|lower|cpu=" + 1d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=1MB|age=0s|command"], CollectionOrdering.Matching); + ["2|higher|cpu=" + 2d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=2MB|age=0s|", "1|lower|cpu=" + 1d.ToString("N1", CultureInfo.CurrentCulture) + "s|ws=1MB|age=0s|" + (OperatingSystem.IsWindows() ? "mapped-command" : "command")], CollectionOrdering.Matching); } [Test] - [Timeout(150_000)] + [Timeout(30_000)] + public async Task RecordAsync_Should_Propagate_Caller_Cancellation(CancellationToken token) + { + var files = new MockFileSystem(); + using var caller = CancellationTokenSource.CreateLinkedTokenSource(token); + var runner = new FakeNativeProcessRunner + { + Response = async (_, cancellation) => + { + await caller.CancelAsync(); + cancellation.ThrowIfCancellationRequested(); + return new NativeProcessResult(0, "", ""); + }, + }; + var root = files.Path.Combine(files.Path.GetTempPath(), "snapshot"); + await Assert.That(() => new NativeProcessSnapshot(files, runner, files.Path.GetTempPath(), TextWriter.Null) + .RecordAsync(root, () => DateTimeOffset.UtcNow, caller.Token)).ThrowsExactly(); + await Assert.That(files.File.Exists(files.Path.Combine(root, "processes.txt"))).IsFalse(); + await Assert.That(runner.Calls.Select(static call => call.Arguments[^1])).IsEquivalentTo([OperatingSystem.IsWindows() ? CommandLineQuery : SnapshotQuery], CollectionOrdering.Matching); + } + + [Test] + [Timeout(195_000)] public async Task RecordAsync_Should_Query_The_Real_Test_Host(CancellationToken token) { var files = new MockFileSystem(); @@ -119,9 +172,13 @@ public async Task RecordAsync_Should_Query_The_Real_Test_Host(CancellationToken await Assert.That(result.ExitCode).IsEqualTo(0); using var json = JsonDocument.Parse(result.StandardOutput); await Assert.That(json.RootElement.ValueKind).IsEqualTo(JsonValueKind.Array); - var host = json.RootElement.EnumerateArray().Single(row => row.GetProperty("Id").GetInt32() == Environment.ProcessId); - await Assert.That(host.GetProperty("ProcessName").GetString()).IsNotNullOrEmpty(); - if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()) + var id = request.Arguments[^1] == CommandLineQuery ? "ProcessId" : "Id"; + var host = json.RootElement.EnumerateArray().Single(row => row.GetProperty(id).GetInt32() == Environment.ProcessId); + if (id == "Id") + { + await Assert.That(host.GetProperty("ProcessName").GetString()).IsNotNullOrEmpty(); + } + if (id == "ProcessId" || OperatingSystem.IsLinux()) { await Assert.That(host.GetProperty("CommandLine").GetString()).IsNotNullOrEmpty(); } @@ -130,11 +187,29 @@ public async Task RecordAsync_Should_Query_The_Real_Test_Host(CancellationToken }; await new NativeProcessSnapshot(files, runner, new RealFileSystem().Path.GetTempPath(), TextWriter.Null) .RecordAsync(files.Path.Combine(files.Path.GetTempPath(), "snapshot"), () => DateTimeOffset.UtcNow, token); + var recorded = await files.File.ReadAllLinesAsync(files.Path.Combine(files.Path.GetTempPath(), "snapshot", "processes.txt"), token); + if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()) + { + await Assert.That(recorded.Single(line => line.StartsWith(Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + "|", StringComparison.Ordinal)).Split('|')[5]).IsNotNullOrEmpty(); + } + } + + private static async Task AssertRequestsAsync(FakeNativeProcessRunner runner) + { + string[] queries = OperatingSystem.IsWindows() ? [CommandLineQuery, SnapshotQuery] : [SnapshotQuery]; + await Assert.That(runner.Calls.Select(static call => call.Arguments[^1])).IsEquivalentTo(queries, CollectionOrdering.Matching); + foreach (var call in runner.Calls) + { + await Assert.That(call.FileName).IsEqualTo("pwsh"); + await Assert.That(call.Arguments).IsEquivalentTo(["-NoProfile", "-NonInteractive", "-Command", call.Arguments[^1]], CollectionOrdering.Matching); + await Assert.That(call.Timeout).IsEqualTo(call.Arguments[^1] == CommandLineQuery ? TimeSpan.FromSeconds(45) : TimeSpan.FromMinutes(2)); + } } private static string Query(DateTimeOffset now) => JsonSerializer.Serialize(Enumerable.Range(0, 26).Select(index => new { Id = index, + ProcessId = index, ProcessName = "process" + index.ToString(CultureInfo.InvariantCulture), CPU = index, WorkingSet64 = index * 1_048_576L, diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs b/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs index 02c23f9..166ec44 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeProcessSnapshot.cs @@ -7,32 +7,72 @@ namespace OpenCode.Mcp.Tools.Native; internal sealed class NativeProcessSnapshot(IFileSystem files, INativeProcessRunner runner, string root, TextWriter output) { - private const string Query = "$ErrorActionPreference='Stop'; $commandLines=@{}; if ($IsWindows) {try {Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | ForEach-Object {$commandLines[[int]$_.ProcessId]=$_.CommandLine}} catch {$commandLines=@{}}}; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if ($IsWindows) {$commandLines[$_.Id]} else {$_.CommandLine}}} | ConvertTo-Json -Compress"; + private const string Query = "$ErrorActionPreference='Stop'; Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64,@{Name='StartTime';Expression={try {$_.StartTime.ToUniversalTime().ToString('O')} catch {$null}}},@{Name='CommandLine';Expression={if (-not $IsWindows) {$_.CommandLine}}} | ConvertTo-Json -Compress"; + private const string CommandLineQuery = "$ErrorActionPreference='Stop'; Get-CimInstance Win32_Process -Property ProcessId,CommandLine -OperationTimeoutSec 30 | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"; public async Task RecordAsync(string directory, Func timestamp, CancellationToken token) { files.Directory.CreateDirectory(directory); + var commandLines = new Dictionary(); + var unavailable = OperatingSystem.IsWindows() ? await QueryCommandLinesAsync(commandLines, token).ConfigureAwait(false) : null; var json = await new NativeProcesses(runner, root).RequireAsync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", Query], new Dictionary(StringComparer.Ordinal), token, TimeSpan.FromMinutes(2)).ConfigureAwait(false); var now = timestamp(); using var processes = JsonDocument.Parse(json); var lines = processes.RootElement.EnumerateArray().OrderByDescending(static process => Cpu(process)) - .Select(process => Format(process, now)).ToArray(); - await files.File.WriteAllLinesAsync(files.Path.Combine(directory, "processes.txt"), lines, token).ConfigureAwait(false); + .Select(process => Format(process, now, commandLines)).ToArray(); + await files.File.WriteAllLinesAsync(files.Path.Combine(directory, "processes.txt"), unavailable is null ? lines : [unavailable, .. lines], token).ConfigureAwait(false); + if (unavailable is not null) + { + await output.WriteLineAsync(unavailable.AsMemory(), token).ConfigureAwait(false); + } foreach (var line in lines.Take(25)) { await output.WriteLineAsync(line.AsMemory(), token).ConfigureAwait(false); } } + private async Task QueryCommandLinesAsync(Dictionary commandLines, CancellationToken token) + { + NativeProcessResult result; + try + { + result = await new NativeProcesses(runner, root).RunAsync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", CommandLineQuery], + new Dictionary(StringComparer.Ordinal), token, TimeSpan.FromSeconds(45)).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!token.IsCancellationRequested) + { + return "command lines unavailable: CIM query timed out after 45 s"; + } + if (result.ExitCode != 0) + { + return string.Create(CultureInfo.InvariantCulture, $"command lines unavailable: CIM query exited {result.ExitCode}"); + } + try + { + using var json = JsonDocument.Parse(result.StandardOutput); + IEnumerable rows = json.RootElement.ValueKind == JsonValueKind.Array ? json.RootElement.EnumerateArray() : [json.RootElement]; + foreach (var row in rows) + { + commandLines.Add(row.GetProperty("ProcessId").GetInt32(), row.GetProperty("CommandLine").GetString()); + } + return null; + } + catch (Exception error) when (error is JsonException or InvalidOperationException or KeyNotFoundException) + { + commandLines.Clear(); + return "command lines unavailable: CIM query returned unreadable output"; + } + } + private static double? Cpu(JsonElement process) => process.GetProperty("CPU").ValueKind == JsonValueKind.Null ? null : process.GetProperty("CPU").GetDouble(); - private static string Format(JsonElement process, DateTimeOffset now) + private static string Format(JsonElement process, DateTimeOffset now, IReadOnlyDictionary commandLines) { var started = process.GetProperty("StartTime"); var age = started.ValueKind == JsonValueKind.Null ? -1 : Convert.ToInt32((now - started.GetDateTimeOffset()).TotalSeconds); return string.Format(CultureInfo.CurrentCulture, "{0}|{1}|cpu={2:N1}s|ws={3}MB|age={4}s|{5}", process.GetProperty("Id").GetInt32(), process.GetProperty("ProcessName").GetString(), Cpu(process), Convert.ToInt32(process.GetProperty("WorkingSet64").GetInt64() / 1_048_576d), - age, process.GetProperty("CommandLine").GetString()); + age, OperatingSystem.IsWindows() ? commandLines.GetValueOrDefault(process.GetProperty("Id").GetInt32()) : process.GetProperty("CommandLine").GetString()); } }