Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/native.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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')
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/verify-channel.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions docs/architecture/hosting-and-packaging.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 <directory>` 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 <dir> [--manifest <path>]` 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
Expand Down
5 changes: 3 additions & 2 deletions docs/engineering/quality-gates.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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.
Expand Down
146 changes: 145 additions & 1 deletion tests/OpenCode.Mcp.Tools.Tests/Native/NativeProcessSnapshotTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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, ""));
},
};
Expand Down Expand Up @@ -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<OperationCanceledException>();
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,
Expand Down
Loading
Loading