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..a3d66ae 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') @@ -527,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') @@ -1876,6 +1881,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 @@ -1973,6 +1979,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/.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 fd1b071..82a48af 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 @@ -312,7 +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`; its first 25 rows also reach the job log. + 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 0dbbff6..d2cecbe 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. @@ -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 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 3cbf2e2..421ffcd 100644 --- a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs @@ -3,13 +3,64 @@ 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'; 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_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 = (request, _) => request.Arguments[^1].Contains("Get-CimInstance", StringComparison.Ordinal) ? failure switch + { + "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 AssertRequestsAsync(runner); + } + [Test] [Timeout(30_000)] public async Task RecordAsync_Should_Timestamp_After_The_Process_Query(CancellationToken token) @@ -22,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, "")); }, }; @@ -63,9 +114,102 @@ 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 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|" + (OperatingSystem.IsWindows() ? "mapped-command" : "command")], CollectionOrdering.Matching); + } + + [Test] + [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(); + 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 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(); + } + return result; + }, + }; + 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 ddf00ce..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'; 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'; 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).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)) - .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()); } } 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}"));