From 9ce1df44117192ad34de1839dc837c3b452de475 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 1 Dec 2026 21:10:09 +0100 Subject: [PATCH 001/184] =?UTF-8?q?=F0=9F=90=9B=20handle=20coauthors=20wit?= =?UTF-8?q?hout=20github=20accounts=20in=20release=20evidence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHub returns HTTP 404 for a co-author login that has no account, such as a bot or unmapped identity, and the lookup aborted the whole release evidence collection. Unmapped co-authors now resolve to no user, while other lookup failures still raise. --- .../scripts/collect-release-evidence.py | 12 +++++++- .../scripts/test-release-evidence.py | 29 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/skills/git-remote-release/scripts/collect-release-evidence.py b/skills/git-remote-release/scripts/collect-release-evidence.py index cd0efdf..999ca86 100644 --- a/skills/git-remote-release/scripts/collect-release-evidence.py +++ b/skills/git-remote-release/scripts/collect-release-evidence.py @@ -21,6 +21,16 @@ def github(endpoint): return pages +def github_user(login): + """Return the REST user, or None when GitHub has no account for the login (HTTP 404).""" + try: + return github("users/" + quote(login, safe=""))[0] + except RuntimeError as error: + if "HTTP 404" in str(error): + return None + raise + + def github_authors(repository, sha): """Resolve trailer identities through GitHub, never through name/email guesses.""" owner, name = repository.split("/") @@ -53,7 +63,7 @@ def github_authors(repository, sha): if actor.get("user"): login = actor["user"]["login"] if login.casefold() not in accounts: - accounts[login.casefold()] = github("users/" + quote(login, safe=""))[0] + accounts[login.casefold()] = github_user(login) actor["user"] = accounts[login.casefold()] return authors diff --git a/skills/git-remote-release/scripts/test-release-evidence.py b/skills/git-remote-release/scripts/test-release-evidence.py index f3119c7..e23cb5a 100644 --- a/skills/git-remote-release/scripts/test-release-evidence.py +++ b/skills/git-remote-release/scripts/test-release-evidence.py @@ -4,6 +4,7 @@ import contextlib import io import json +import subprocess import sys import tempfile import unittest @@ -319,6 +320,34 @@ def authors(repository, sha): self.assertEqual(len(evidence["new_contributors"]), 1) self.assertIn("@coauthor-bot", evidence["new_contributors"][0]) + def test_coauthor_without_github_account_is_unmapped_not_incomplete(self): + def graphql(*args, **kwargs): + page = {"data": {"repository": {"object": {"authors": { + "totalCount": 2, "pageInfo": {"hasNextPage": False}, + "nodes": [{"name": "Copilot", "user": {"login": "Copilot"}}, + {"name": "Human", "user": {"login": "human"}}]}}}}} + return subprocess.CompletedProcess(args, 0, stdout=json.dumps([page]), stderr="") + def github(endpoint): + if endpoint == "users/Copilot": + raise RuntimeError(f"{endpoint}: gh: Not Found (HTTP 404)") + return [{"login": "human", "type": "User"}] + with patch.object(collector.subprocess, "run", side_effect=graphql), \ + patch.object(collector, "github", side_effect=github): + actors = collector.github_authors("example/widget", "abc") + self.assertIsNone(actors[0]["user"]) + self.assertEqual(actors[1]["user"], {"login": "human", "type": "User"}) + + def test_coauthor_lookup_failure_other_than_404_still_raises(self): + def graphql(*args, **kwargs): + page = {"data": {"repository": {"object": {"authors": { + "totalCount": 1, "pageInfo": {"hasNextPage": False}, + "nodes": [{"name": "Human", "user": {"login": "human"}}]}}}}} + return subprocess.CompletedProcess(args, 0, stdout=json.dumps([page]), stderr="") + with patch.object(collector.subprocess, "run", side_effect=graphql), \ + patch.object(collector, "github", side_effect=RuntimeError("users/human: gh: HTTP 403")): + with self.assertRaises(RuntimeError): + collector.github_authors("example/widget", "abc") + def test_failed_coauthor_mapping_fails_closed(self): self.initial_routes() self.routes["/pulls/22/commits?per_page=100"][0][0]["commit"]["message"] += "\nCo-authored-by: X " From 7b48503e8bf95793fd891ef203cc9d5881c34695 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Wed, 2 Dec 2026 19:54:44 +0100 Subject: [PATCH 002/184] =?UTF-8?q?=F0=9F=94=A7=20roll=20file-based=20apps?= =?UTF-8?q?=20forward=20to=20newer=20majors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agentic tooling targets .NET 10 but must also run where only a newer major runtime such as .NET 11 is installed. RollForward=Major lets each file-based app start on the newest compatible major runtime. --- skills/dotnet-docfx-digest/scripts/agents.cs | 1 + skills/dotnet-docfx-digest/scripts/docfx.cs | 1 + skills/dotnet-remote-testing/scripts/remote-test.cs | 1 + skills/dotnet-segregated-assets/scripts/segregate-assets.cs | 1 + skills/git-repo-digest/scripts/digest.cs | 1 + 5 files changed, 5 insertions(+) diff --git a/skills/dotnet-docfx-digest/scripts/agents.cs b/skills/dotnet-docfx-digest/scripts/agents.cs index d68c856..238303f 100644 --- a/skills/dotnet-docfx-digest/scripts/agents.cs +++ b/skills/dotnet-docfx-digest/scripts/agents.cs @@ -1,4 +1,5 @@ #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index 28c828e..37e2c50 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -1,6 +1,7 @@ #!/usr/bin/env dotnet #:package MSBuild.StructuredLogger@2.3.269 #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false diff --git a/skills/dotnet-remote-testing/scripts/remote-test.cs b/skills/dotnet-remote-testing/scripts/remote-test.cs index 004d148..8b04ec6 100644 --- a/skills/dotnet-remote-testing/scripts/remote-test.cs +++ b/skills/dotnet-remote-testing/scripts/remote-test.cs @@ -1,4 +1,5 @@ #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false diff --git a/skills/dotnet-segregated-assets/scripts/segregate-assets.cs b/skills/dotnet-segregated-assets/scripts/segregate-assets.cs index 2827282..32fda05 100644 --- a/skills/dotnet-segregated-assets/scripts/segregate-assets.cs +++ b/skills/dotnet-segregated-assets/scripts/segregate-assets.cs @@ -1,4 +1,5 @@ #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false diff --git a/skills/git-repo-digest/scripts/digest.cs b/skills/git-repo-digest/scripts/digest.cs index f1c7ccc..980717a 100644 --- a/skills/git-repo-digest/scripts/digest.cs +++ b/skills/git-repo-digest/scripts/digest.cs @@ -1,4 +1,5 @@ #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false From 6b66a9c7162d0be5eced0072084a2cbd4a844f59 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Wed, 2 Dec 2026 19:54:45 +0100 Subject: [PATCH 003/184] =?UTF-8?q?=F0=9F=9A=9A=20move=20docfx=20example?= =?UTF-8?q?=20fixture=20under=20evals=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eval fixtures belong under evals/files so preparation can validate and stage them. The InventoryWorker architecture sample moves there and every reference to the old scripts/fixtures path follows it. --- skills/dotnet-docfx-digest/evals/evals.json | 20 +++++++++---------- .../InventoryWorker/InventoryWorker.csproj | 0 .../app/InventoryWorker/Program.cs | 0 .../files}/example-architecture/evidence.md | 0 .../InventoryWorker.Tests.csproj | 0 .../InventoryWorkerTest.cs | 0 .../InventoryWorker.Tests/MiddlewareTest.cs | 0 .../InventoryWorker.Tests/StandaloneTest.cs | 0 .../scripts/test-quality.ps1 | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/app/InventoryWorker/InventoryWorker.csproj (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/app/InventoryWorker/Program.cs (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/evidence.md (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs (100%) rename skills/dotnet-docfx-digest/{scripts/fixtures => evals/files}/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs (100%) diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index 09c17ac..51ea444 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1208,11 +1208,11 @@ "id": 115, "prompt": "Improve the ManagedApplicationFixture API-reference example using the attached InventoryWorker application and xUnit v3 test projects. The old page displays InventoryWorkerTest and WorkerProgram.Main together as one independently runnable file. Explain and preserve what the test proves, keep the API page concise, and validate the real application/test graph. Do not edit codebeltnet/xunit or use stub fixtures.", "files": [ - "scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj", - "scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs", - "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", - "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", - "scripts/fixtures/example-architecture/evidence.md" + "evals/files/example-architecture/app/InventoryWorker/InventoryWorker.csproj", + "evals/files/example-architecture/app/InventoryWorker/Program.cs", + "evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", + "evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", + "evals/files/example-architecture/evidence.md" ], "expected_output": "Establishes the developer task and assembly-selection contract from the pinned implementation and functional tests. Presents labelled application/test files with actual project/package prerequisites, binds them to the maintained source/project context, preserves Main, fixture injection, Fact and assertions, and distinguishes build evidence from real runner execution. Recommends the upstream documentation correction separately without modifying that repository.", "expectations": [ @@ -1298,11 +1298,11 @@ "id": 121, "prompt": "Document a partial assertion from the attached InventoryWorker functional test, retaining a meaningful principal fixture example. The excerpt omits imports and fixture initialization. Offline project compilation is available, but runtime verification is unavailable in this environment. Explain what is omitted and offer optional maintained source context using the supplied application, test and project evidence. Do not claim the excerpt is independently executable or that compilation proves it ran; retain any existing working one-shot reproduction guidance.", "files": [ - "scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj", - "scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs", - "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", - "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", - "scripts/fixtures/example-architecture/evidence.md" + "evals/files/example-architecture/app/InventoryWorker/InventoryWorker.csproj", + "evals/files/example-architecture/app/InventoryWorker/Program.cs", + "evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", + "evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", + "evals/files/example-architecture/evidence.md" ], "expected_output": "Labels the partial excerpt and omitted containing context, retains essential fixture usage and assertions, and binds compilation to the supplied maintained source/project. Explains how application, functional test and project references teach registration/startup, fixture initialization and assembly ownership. Distinguishes compilation from unavailable runtime evidence and does not downgrade an available faithful one-shot path to source-only guidance.", "expectations": [ diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj b/skills/dotnet-docfx-digest/evals/files/example-architecture/app/InventoryWorker/InventoryWorker.csproj similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj rename to skills/dotnet-docfx-digest/evals/files/example-architecture/app/InventoryWorker/InventoryWorker.csproj diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs b/skills/dotnet-docfx-digest/evals/files/example-architecture/app/InventoryWorker/Program.cs similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs rename to skills/dotnet-docfx-digest/evals/files/example-architecture/app/InventoryWorker/Program.cs diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md b/skills/dotnet-docfx-digest/evals/files/example-architecture/evidence.md similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md rename to skills/dotnet-docfx-digest/evals/files/example-architecture/evidence.md diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj b/skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj rename to skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs b/skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs rename to skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs b/skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs rename to skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs b/skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs similarity index 100% rename from skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs rename to skills/dotnet-docfx-digest/evals/files/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs diff --git a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 index d037ecd..1bb67be 100644 --- a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 @@ -2699,7 +2699,7 @@ internal static class ConditionalInventory # Build only the temp copy; the source fixture tree must remain free of bin/obj artifacts. $architecture = Join-Path ([System.IO.Path]::GetTempPath()) ('dotnet-docfx-architecture-' + [guid]::NewGuid().ToString('N')) try { - $fixtureRoot = Join-Path $PSScriptRoot 'fixtures/example-architecture' + $fixtureRoot = Join-Path $PSScriptRoot '../evals/files/example-architecture' New-Item -ItemType Directory -Path $architecture | Out-Null Copy-Item -Path (Join-Path $fixtureRoot '*') -Destination $architecture -Recurse Write-Utf8File (Join-Path $architecture 'AGENTS.md') "`nManaged DocFX guidance.`n" From c19ce27703c5a0cc88038dc09551bbd95986774a Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Wed, 2 Dec 2026 19:54:45 +0100 Subject: [PATCH 004/184] =?UTF-8?q?=E2=9C=A8=20report=20job=20object=20acc?= =?UTF-8?q?ounting=20for=20owned=20processes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measurement tooling needs peak commit memory, process counts and CPU time for a whole Windows job tree. The owned-process wrapper now exposes these read-only figures through QueryAccounting. --- scripts/eval-runners/windows-owned-process.cs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/scripts/eval-runners/windows-owned-process.cs b/scripts/eval-runners/windows-owned-process.cs index c303ff3..0837e04 100644 --- a/scripts/eval-runners/windows-owned-process.cs +++ b/scripts/eval-runners/windows-owned-process.cs @@ -1,3 +1,4 @@ +#nullable disable using System; using System.ComponentModel; using System.Diagnostics; @@ -52,6 +53,8 @@ private struct JobLimits [DllImport("kernel32.dll", SetLastError = true)] private static extern bool QueryInformationJobObject(SafeFileHandle job, int kind, byte[] value, int size, IntPtr returned); [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool QueryInformationJobObject(SafeFileHandle job, int kind, out JobLimits value, int size, IntPtr returned); + [DllImport("kernel32.dll", SetLastError = true)] private static extern bool TerminateJobObject(SafeFileHandle job, uint exitCode); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AssignProcessToJobObject(SafeFileHandle job, SafeFileHandle process); @@ -80,6 +83,7 @@ private static extern bool CreateProcessW(string application, StringBuilder comm public bool HasExited => process.HasExited; public int ExitCode => process.ExitCode; public bool WaitForExit(int milliseconds) => process.WaitForExit(milliseconds); + public System.Threading.Tasks.Task WaitForExitAsync(CancellationToken cancellationToken) => process.WaitForExitAsync(cancellationToken); private static void Check(bool success, string operation) { @@ -193,6 +197,20 @@ public void StopOwnedProcesses(int milliseconds) throw new TimeoutException("Windows job termination grace expired before all owned processes exited."); } + // Read-only accounting for the whole owned tree, used by measurement tooling. PeakJobMemory is the + // peak committed (private) memory of all live job processes combined, not a working-set figure. + public JobAccounting QueryAccounting() + { + var accounting = new byte[48]; + Check(QueryInformationJobObject(job, 1, accounting, accounting.Length, IntPtr.Zero), "QueryInformationJobObject"); + Check(QueryInformationJobObject(job, 9, out JobLimits limits, Marshal.SizeOf(), IntPtr.Zero), "QueryInformationJobObject"); + return new JobAccounting( + (ulong)limits.PeakJobMemory, + BitConverter.ToUInt32(accounting, 36), + BitConverter.ToUInt32(accounting, 40), + TimeSpan.FromTicks(BitConverter.ToInt64(accounting, 0) + BitConverter.ToInt64(accounting, 8))); + } + public void Dispose() { job?.Dispose(); @@ -202,4 +220,20 @@ public void Dispose() process?.Dispose(); } } + + public readonly struct JobAccounting + { + public JobAccounting(ulong peakJobCommitBytes, uint totalProcesses, uint activeProcesses, TimeSpan totalCpuTime) + { + PeakJobCommitBytes = peakJobCommitBytes; + TotalProcesses = totalProcesses; + ActiveProcesses = activeProcesses; + TotalCpuTime = totalCpuTime; + } + + public ulong PeakJobCommitBytes { get; } + public uint TotalProcesses { get; } + public uint ActiveProcesses { get; } + public TimeSpan TotalCpuTime { get; } + } } From 16489b2c8ffbca0e5130b81da0d44f3c6ba73d55 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Wed, 2 Dec 2026 19:54:45 +0100 Subject: [PATCH 005/184] =?UTF-8?q?=E2=9C=A8=20add=20agentic=20tooling=20d?= =?UTF-8?q?otnet=20solution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repository infrastructure moves from ad hoc PowerShell into a .NET solution under tooling. It provides the validate-local scheduler, measurement harness and shared process helpers with central package management. --- tooling/Agentic.Tooling.slnx | 9 + tooling/Directory.Build.props | 14 + tooling/Directory.Packages.props | 12 + tooling/global.json | 5 + .../Agentic.Tooling/Agentic.Tooling.csproj | 14 + .../Diagnostics/ProgressFile.cs | 121 +++++ .../Diagnostics/ProgressWriter.cs | 79 ++++ .../Agentic.Tooling/Execution/ChildProcess.cs | 196 ++++++++ .../Execution/ExecutableResolver.cs | 35 ++ .../Measurement/EnvironmentSnapshot.cs | 82 ++++ .../Measurement/MeasureCommand.cs | 122 +++++ .../Measurement/MeasuredProcess.cs | 124 +++++ .../Measurement/MeasuredRun.cs | 71 +++ .../Measurement/OutputTimeline.cs | 76 +++ .../Measurement/SummarizeCommand.cs | 95 ++++ .../Agentic.Tooling/Measurement/Workload.cs | 92 ++++ tooling/src/Agentic.Tooling/Program.cs | 198 ++++++++ .../Agentic.Tooling/Validation/SuiteMatrix.cs | 86 ++++ .../Validation/ValidateLocalCommand.cs | 431 ++++++++++++++++++ 19 files changed, 1862 insertions(+) create mode 100644 tooling/Agentic.Tooling.slnx create mode 100644 tooling/Directory.Build.props create mode 100644 tooling/Directory.Packages.props create mode 100644 tooling/global.json create mode 100644 tooling/src/Agentic.Tooling/Agentic.Tooling.csproj create mode 100644 tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs create mode 100644 tooling/src/Agentic.Tooling/Diagnostics/ProgressWriter.cs create mode 100644 tooling/src/Agentic.Tooling/Execution/ChildProcess.cs create mode 100644 tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/EnvironmentSnapshot.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/MeasureCommand.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/MeasuredProcess.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/MeasuredRun.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/OutputTimeline.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/SummarizeCommand.cs create mode 100644 tooling/src/Agentic.Tooling/Measurement/Workload.cs create mode 100644 tooling/src/Agentic.Tooling/Program.cs create mode 100644 tooling/src/Agentic.Tooling/Validation/SuiteMatrix.cs create mode 100644 tooling/src/Agentic.Tooling/Validation/ValidateLocalCommand.cs diff --git a/tooling/Agentic.Tooling.slnx b/tooling/Agentic.Tooling.slnx new file mode 100644 index 0000000..19f70e1 --- /dev/null +++ b/tooling/Agentic.Tooling.slnx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tooling/Directory.Build.props b/tooling/Directory.Build.props new file mode 100644 index 0000000..63c04f7 --- /dev/null +++ b/tooling/Directory.Build.props @@ -0,0 +1,14 @@ + + + + net10.0 + Major + latest + enable + enable + true + true + en + + diff --git a/tooling/Directory.Packages.props b/tooling/Directory.Packages.props new file mode 100644 index 0000000..c28a235 --- /dev/null +++ b/tooling/Directory.Packages.props @@ -0,0 +1,12 @@ + + + true + + + + + + + + + diff --git a/tooling/global.json b/tooling/global.json new file mode 100644 index 0000000..3140116 --- /dev/null +++ b/tooling/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/tooling/src/Agentic.Tooling/Agentic.Tooling.csproj b/tooling/src/Agentic.Tooling/Agentic.Tooling.csproj new file mode 100644 index 0000000..f228cda --- /dev/null +++ b/tooling/src/Agentic.Tooling/Agentic.Tooling.csproj @@ -0,0 +1,14 @@ + + + Exe + agentic-tooling + Agentic.Tooling + + + + + + + + + diff --git a/tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs b/tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs new file mode 100644 index 0000000..bd09753 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs @@ -0,0 +1,121 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Agentic.Tooling.Diagnostics; + +/// Work counts at one instant. Only verified facts; nothing is estimated. +internal sealed record ProgressCounts(int Total, int Completed, int Failed, int Active, int Pending); + +/// One unit of work that is currently executing. +internal sealed record ActiveWork(string Name, double ElapsedSeconds, double? SecondsSinceLastOutput); + +/// +/// A small JSON snapshot of a running operation, rewritten atomically on every event and heartbeat, for hosts that +/// buffer a command's output until it exits. A reader correlates it by operationId and pid, and treats a +/// running snapshot whose staleAfterUtc has passed as stale: the writer stopped updating it without +/// recording a terminal state. A terminal state (succeeded, failed, cancelled) is written only once +/// the outcome is known. +/// +/// +/// On Windows a reader that opens the file without delete sharing (the .NET default) makes the atomic replace fail. The +/// writer retries within a short budget, then keeps the previous snapshot and reports the failure through +/// writeFailed; the file is auxiliary to stderr, so contention never fails the operation itself. A read that +/// meets the replace itself can be refused, or find no file, for an instant, so a reader retries. +/// +internal sealed class ProgressFile(string path, string operation, TimeSpan heartbeatInterval, Action? writeFailed = null) +{ + public const string Schema = "codebeltnet/agentic/progress/1"; + + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + private readonly Lock gate = new(); + private readonly DateTime startedUtc = DateTime.UtcNow; + + public string Path { get; } = System.IO.Path.GetFullPath(path); + + public string OperationId { get; } = Guid.NewGuid().ToString("N"); + + /// A running snapshot gives up quickly: the next event or heartbeat replaces it anyway. + internal static TimeSpan RunningWriteBudget { get; } = TimeSpan.FromMilliseconds(500); + + /// The terminal snapshot is written once, so it waits longer for a reader to let go. + internal static TimeSpan TerminalWriteBudget { get; } = TimeSpan.FromSeconds(5); + + /// Publishes a running snapshot. Returns when the previous snapshot stayed in place. + public bool Running(ProgressCounts counts, IReadOnlyList active, string lastEvent) => + Write("running", counts, active, lastEvent, outcome: null, RunningWriteBudget); + + /// Publishes the terminal snapshot. Returns when the previous snapshot stayed in place. + public bool Terminal(string state, ProgressCounts counts, string lastEvent, object outcome) => + Write(state, counts, [], lastEvent, outcome, TerminalWriteBudget); + + private bool Write(string state, ProgressCounts counts, IReadOnlyList active, string lastEvent, object? outcome, TimeSpan budget) + { + var now = DateTime.UtcNow; + var snapshot = new + { + schema = Schema, + operation, + operationId = OperationId, + pid = Environment.ProcessId, + state, + startedUtc = Format(startedUtc), + updatedUtc = Format(now), + // Three missed heartbeats. A terminal snapshot never goes stale. + staleAfterUtc = state == "running" ? Format(now + (heartbeatInterval * 3)) : null, + heartbeatSeconds = heartbeatInterval.TotalSeconds, + elapsedSeconds = Math.Round((now - startedUtc).TotalSeconds, 1), + counts, + active, + lastEvent, + outcome, + }; + + var text = JsonSerializer.Serialize(snapshot, Json); + var temporary = Path + "." + OperationId + ".tmp"; + lock (gate) + { + var clock = Stopwatch.StartNew(); + for (var attempt = 0; ; attempt++) + { + try + { + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path)!); + File.WriteAllText(temporary, text); + File.Move(temporary, Path, overwrite: true); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + if (clock.Elapsed >= budget) + { + TryDelete(temporary); + writeFailed?.Invoke($"progress file {Path} kept its previous snapshot; writing the {state} snapshot failed for {clock.Elapsed.TotalSeconds:0.0} s: {exception.Message}"); + return false; + } + + Thread.Sleep(Math.Min(50, 5 << Math.Min(attempt, 4))); + } + } + } + } + + private static void TryDelete(string file) + { + try + { + File.Delete(file); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + + private static string Format(DateTime value) => value.ToString("o", CultureInfo.InvariantCulture); +} diff --git a/tooling/src/Agentic.Tooling/Diagnostics/ProgressWriter.cs b/tooling/src/Agentic.Tooling/Diagnostics/ProgressWriter.cs new file mode 100644 index 0000000..53a7a38 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Diagnostics/ProgressWriter.cs @@ -0,0 +1,79 @@ +using System.Diagnostics; +using System.Globalization; + +namespace Agentic.Tooling.Diagnostics; + +/// +/// Append-only, plain-text operation feedback on stderr. Stdout stays reserved for machine-readable results. +/// [HEARTBEAT] lines report liveness only; they never claim progress that was not verified. +/// +internal sealed class ProgressWriter(TextWriter writer, string operation, bool quiet, bool heartbeats, TimeSpan heartbeatInterval) +{ + private readonly Stopwatch clock = Stopwatch.StartNew(); + private readonly Lock gate = new(); + + public static readonly TimeSpan DefaultHeartbeatInterval = TimeSpan.FromSeconds(10); + + public TimeSpan HeartbeatInterval { get; } = heartbeatInterval; + + public bool HeartbeatsEnabled => heartbeats && !quiet; + + public TimeSpan Elapsed => clock.Elapsed; + + public void Start(string detail) => Write("START", detail); + + public void Progress(string detail) => Write("PROGRESS", detail); + + public void Heartbeat(string detail) + { + if (HeartbeatsEnabled) + { + Write("HEARTBEAT", detail); + } + } + + public void Warning(string detail) => Write("WARN", detail, force: true); + + public void Complete(string detail) => Write("COMPLETE", detail, force: true); + + public void Failed(string detail) => Write("FAILED", detail, force: true); + + /// Emits liveness heartbeats until cancelled, independent of whether the observed work produces output. + public async Task HeartbeatUntilCancelledAsync(Func describe, CancellationToken cancellationToken) + { + if (!HeartbeatsEnabled) + { + return; + } + + using var timer = new PeriodicTimer(HeartbeatInterval); + try + { + while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false)) + { + Heartbeat(describe()); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + } + + public static string FormatElapsed(TimeSpan elapsed) => elapsed.TotalSeconds < 60 + ? elapsed.TotalSeconds.ToString("0.0", CultureInfo.InvariantCulture) + "s" + : $"{(int)elapsed.TotalMinutes}m {elapsed.Seconds:00}s"; + + private void Write(string kind, string detail, bool force = false) + { + if (quiet && !force) + { + return; + } + + lock (gate) + { + writer.WriteLine($"[{kind}] {operation} | {detail} | elapsed: {FormatElapsed(clock.Elapsed)}"); + writer.Flush(); + } + } +} diff --git a/tooling/src/Agentic.Tooling/Execution/ChildProcess.cs b/tooling/src/Agentic.Tooling/Execution/ChildProcess.cs new file mode 100644 index 0000000..2020006 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Execution/ChildProcess.cs @@ -0,0 +1,196 @@ +using System.Diagnostics; +using Agentic.Evals; + +namespace Agentic.Tooling.Execution; + +/// What to run. Arguments are passed verbatim through . +internal sealed record ChildProcessRequest( + string FileName, + IReadOnlyList Arguments, + string WorkingDirectory, + IReadOnlyDictionary? Environment = null, + TimeSpan? Timeout = null); + +/// Resource accounting for the whole process tree, where the platform provides it. +internal sealed record ChildProcessAccounting(double PeakCommitMiB, long TotalProcesses, long ActiveProcesses, double CpuSeconds); + +/// Terminal outcome of a child process tree. is null when the tree was killed. +internal sealed record ChildProcessOutcome( + int? ExitCode, + bool TimedOut, + bool Cancelled, + bool LingeringProcesses, + TimeSpan Elapsed, + string Ownership, + ChildProcessAccounting? Accounting); + +/// +/// Runs one child process tree with concurrent stdout and stderr draining, a timeout and cancellation that both kill +/// the whole tree. On Windows the root is created suspended and assigned to a Job Object before its first instruction +/// (, the established ownership code), so no descendant escapes termination or +/// accounting. Elsewhere the tree is killed with . +/// +internal static class ChildProcess +{ + public const string WindowsOwnership = "suspended-start-job"; + public const string PortableOwnership = "process-group"; + + private static readonly TimeSpan DrainGrace = TimeSpan.FromSeconds(10); + + /// + /// Starts the process, invokes for every output line (second argument true for stderr, + /// possibly from two threads at once), and returns when the tree has ended and both pipes are drained or the drain + /// grace has passed. Cancellation is reported in the outcome rather than thrown, so callers can still record it. + /// + public static async Task RunAsync( + ChildProcessRequest request, + Action onLine, + Action? onStarted, + CancellationToken cancellationToken) + { + var startInfo = new ProcessStartInfo + { + FileName = ExecutableResolver.Resolve(request.FileName), + WorkingDirectory = request.WorkingDirectory, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in request.Arguments) + { + startInfo.ArgumentList.Add(argument); + } + + foreach (var (key, value) in request.Environment ?? new Dictionary()) + { + startInfo.Environment[key] = value; + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + if (request.Timeout is { } limit && limit > TimeSpan.Zero) + { + timeout.CancelAfter(limit); + } + + return OperatingSystem.IsWindows() + ? await RunOwnedAsync(startInfo, onLine, onStarted, timeout.Token, cancellationToken).ConfigureAwait(false) + : await RunPortableAsync(startInfo, onLine, onStarted, timeout.Token, cancellationToken).ConfigureAwait(false); + } + + private static async Task RunOwnedAsync( + ProcessStartInfo startInfo, Action onLine, Action? onStarted, CancellationToken stop, CancellationToken cancellation) + { + var clock = Stopwatch.StartNew(); + using var process = new WindowsOwnedProcess { StartInfo = startInfo }; + process.Start(); + process.StandardInput.Close(); + var pumps = Task.WhenAll(PumpAsync(process.StandardOutput, onLine, false), PumpAsync(process.StandardError, onLine, true)); + onStarted?.Invoke(); + + var killed = false; + try + { + await process.WaitForExitAsync(stop).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + killed = true; + process.StopOwnedProcesses(5000); + } + + var elapsed = clock.Elapsed; + var lingering = !await DrainAsync(pumps).ConfigureAwait(false); + var accounting = process.QueryAccounting(); + lingering |= accounting.ActiveProcesses > 0; + return new ChildProcessOutcome( + killed ? null : process.ExitCode, + TimedOut: killed && !cancellation.IsCancellationRequested, + Cancelled: killed && cancellation.IsCancellationRequested, + lingering, + elapsed, + WindowsOwnership, + new ChildProcessAccounting( + Math.Round(accounting.PeakJobCommitBytes / 1048576.0, 1), + accounting.TotalProcesses, + accounting.ActiveProcesses, + accounting.TotalCpuTime.TotalSeconds)); + } + + private static async Task RunPortableAsync( + ProcessStartInfo startInfo, Action onLine, Action? onStarted, CancellationToken stop, CancellationToken cancellation) + { + var clock = Stopwatch.StartNew(); + using var process = new Process { StartInfo = startInfo }; + process.Start(); + process.StandardInput.Close(); + var pumps = Task.WhenAll(PumpAsync(process.StandardOutput, onLine, false), PumpAsync(process.StandardError, onLine, true)); + onStarted?.Invoke(); + + var killed = false; + try + { + await process.WaitForExitAsync(stop).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + killed = true; + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); + } + + var elapsed = clock.Elapsed; + var lingering = !await DrainAsync(pumps).ConfigureAwait(false); + return new ChildProcessOutcome( + killed ? null : process.ExitCode, + TimedOut: killed && !cancellation.IsCancellationRequested, + Cancelled: killed && cancellation.IsCancellationRequested, + lingering, + elapsed, + PortableOwnership, + Accounting: null); + } + + /// + /// Reads one pipe to its end on a dedicated background thread. The redirected pipes are synchronous handles on + /// Windows, so ReadLineAsync would block a thread-pool thread for the child's whole lifetime; with a suite + /// matrix that pins two pool threads per child, and when the CPU is saturated the pool stops adding threads, which + /// starves timer-driven heartbeats and progress updates exactly while the work is heaviest. + /// + private static Task PumpAsync(StreamReader reader, Action onLine, bool isStderr) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread( + () => + { + try + { + while (reader.ReadLine() is { } line) + { + onLine(line, isStderr); + } + + completion.TrySetResult(); + } + catch (Exception exception) + { + completion.TrySetException(exception); + } + }, + maxStackSize: 256 * 1024) + { + IsBackground = true, + Name = isStderr ? "child stderr" : "child stdout", + }; + thread.Start(); + return completion.Task; + } + + /// Waits for both pipes to close. False means a surviving descendant still holds them open. + private static async Task DrainAsync(Task pumps) + { + var finished = await Task.WhenAny(pumps, Task.Delay(DrainGrace)).ConfigureAwait(false); + return finished == pumps; + } +} diff --git a/tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs b/tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs new file mode 100644 index 0000000..07f1db5 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs @@ -0,0 +1,35 @@ +namespace Agentic.Tooling.Execution; + +/// +/// Resolves a command name against PATH (and PATHEXT on Windows). The Windows owned-process launcher +/// calls CreateProcessW with an explicit application name, which performs no search of its own. +/// +internal static class ExecutableResolver +{ + public static string Resolve(string command) + { + if (Path.IsPathRooted(command) || command.Contains(Path.DirectorySeparatorChar) || command.Contains(Path.AltDirectorySeparatorChar)) + { + var full = Path.GetFullPath(command); + return File.Exists(full) ? full : throw new FileNotFoundException($"Executable '{command}' was not found.", full); + } + + var extensions = OperatingSystem.IsWindows() + ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.CMD;.BAT").Split(';', StringSplitOptions.RemoveEmptyEntries) + : []; + var candidates = Path.HasExtension(command) || extensions.Length == 0 ? [command] : extensions.Select(e => command + e).Prepend(command); + foreach (var directory in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var candidate in candidates) + { + var path = Path.Combine(directory.Trim('"'), candidate); + if (File.Exists(path) && (OperatingSystem.IsWindows() ? Path.HasExtension(path) : true)) + { + return path; + } + } + } + + throw new FileNotFoundException($"Executable '{command}' was not found on PATH."); + } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/EnvironmentSnapshot.cs b/tooling/src/Agentic.Tooling/Measurement/EnvironmentSnapshot.cs new file mode 100644 index 0000000..4a4dab8 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/EnvironmentSnapshot.cs @@ -0,0 +1,82 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Agentic.Tooling.Execution; + +namespace Agentic.Tooling.Measurement; + +/// Toolchain and machine facts recorded beside every measurement session, so results stay interpretable. +internal static class EnvironmentSnapshot +{ + public static async Task> CaptureAsync(MeasureOptions options, string sessionTemp, CancellationToken cancellationToken) + { + async Task Capture(string file, params string[] arguments) + { + try + { + return await RunAsync(file, arguments, options.RepositoryRoot, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) when (exception is FileNotFoundException or System.ComponentModel.Win32Exception or TimeoutException) + { + return null; + } + } + + var harnessDirectory = AppContext.BaseDirectory; + return new Dictionary + { + ["schema"] = "codebeltnet/agentic/measurement-environment/1", + ["capturedUtc"] = DateTime.UtcNow.ToString("o"), + ["os"] = RuntimeInformation.OSDescription.Trim(), + ["architecture"] = RuntimeInformation.OSArchitecture.ToString(), + ["logicalProcessors"] = Environment.ProcessorCount, + ["harnessRuntime"] = RuntimeInformation.FrameworkDescription, + ["measuredRepository"] = Path.GetFullPath(options.RepositoryRoot), + ["measuredSha"] = await Capture("git", "-C", options.RepositoryRoot, "rev-parse", "HEAD").ConfigureAwait(false), + ["measuredWorkingTreeStatus"] = await Capture("git", "-C", options.RepositoryRoot, "status", "--porcelain", "--untracked-files=all").ConfigureAwait(false), + ["harnessSha"] = await Capture("git", "-C", harnessDirectory, "rev-parse", "HEAD").ConfigureAwait(false), + // ":/" anchors pathspecs at the repository root; a bare path would resolve against the bin directory. + ["harnessWorkingTreeDirty"] = !string.IsNullOrEmpty(await Capture("git", "-C", harnessDirectory, "status", "--porcelain", "--untracked-files=all", "--", ":/tooling", ":/scripts/eval-runners/windows-owned-process.cs").ConfigureAwait(false)), + ["workloads"] = Path.GetFullPath(options.WorkloadsPath), + ["runsPerWorkload"] = options.Runs, + ["isolatedTemp"] = sessionTemp, + ["dotnetVersion"] = await Capture("dotnet", "--version").ConfigureAwait(false), + ["dotnetSdks"] = await Capture("dotnet", "--list-sdks").ConfigureAwait(false), + ["pwshVersion"] = await Capture("pwsh", "-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()").ConfigureAwait(false), + ["pythonVersion"] = await Capture(OperatingSystem.IsWindows() ? "python" : "python3", "--version").ConfigureAwait(false), + ["gitVersion"] = await Capture("git", "--version").ConfigureAwait(false), + }; + } + + private static async Task RunAsync(string file, string[] arguments, string workingDirectory, CancellationToken cancellationToken) + { + var startInfo = new ProcessStartInfo(ExecutableResolver.Resolve(file)) + { + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (var argument in arguments) + { + startInfo.ArgumentList.Add(argument); + } + + using var process = Process.Start(startInfo) ?? throw new InvalidOperationException($"Could not start '{file}'."); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + var stdout = process.StandardOutput.ReadToEndAsync(timeout.Token); + var stderr = process.StandardError.ReadToEndAsync(timeout.Token); + try + { + await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + process.Kill(entireProcessTree: true); + throw new TimeoutException($"'{file}' did not finish within 30 seconds."); + } + + await stderr.ConfigureAwait(false); + return (await stdout.ConfigureAwait(false)).Trim(); + } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/MeasureCommand.cs b/tooling/src/Agentic.Tooling/Measurement/MeasureCommand.cs new file mode 100644 index 0000000..e972176 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/MeasureCommand.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Agentic.Tooling.Diagnostics; + +namespace Agentic.Tooling.Measurement; + +internal sealed record MeasureOptions +{ + public required string WorkloadsPath { get; init; } + + public required string RepositoryRoot { get; init; } + + public required string OutputDirectory { get; init; } + + public int Runs { get; init; } = 3; + + public string[] Only { get; init; } = []; + + public bool Quiet { get; init; } + + public bool NoHeartbeat { get; init; } +} + +/// +/// Runs every selected workload times, run-major (all workloads for run 1, then +/// run 2, ...), sequentially so runs never contend with each other. Appends one JSON line per run to +/// runs.jsonl and writes each run's timestamped output to logs/. +/// +internal static class MeasureCommand +{ + public static async Task RunAsync(MeasureOptions options, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken) + { + var set = WorkloadSet.Load(options.WorkloadsPath); + var unknown = options.Only.Except(set.Workloads.Select(w => w.Name), StringComparer.Ordinal).ToArray(); + if (unknown.Length > 0) + { + stderr.WriteLine($"Unknown workload(s): {string.Join(", ", unknown)}"); + return 2; + } + + var workloads = Select(set, options.Only); + if (workloads.Length == 0) + { + stderr.WriteLine("No workload applies to this platform and selection."); + return 2; + } + + Directory.CreateDirectory(options.OutputDirectory); + var runsPath = Path.Combine(options.OutputDirectory, "runs.jsonl"); + + // A fresh temp directory per session, so run 1 starts with empty temp-based build caches. + var sessionTemp = Path.Combine(Path.GetTempPath(), "agentic-measure-" + Guid.NewGuid().ToString("N")[..12]); + Directory.CreateDirectory(sessionTemp); + var environment = new Dictionary(set.Environment, StringComparer.Ordinal) + { + ["TEMP"] = sessionTemp, + ["TMP"] = sessionTemp, + ["TMPDIR"] = sessionTemp, + }; + + await File.WriteAllTextAsync( + Path.Combine(options.OutputDirectory, "environment.json"), + JsonSerializer.Serialize(await EnvironmentSnapshot.CaptureAsync(options, sessionTemp, cancellationToken).ConfigureAwait(false), MeasurementJson.Indented), + cancellationToken).ConfigureAwait(false); + + var total = workloads.Length * options.Runs; + var progress = new ProgressWriter(stderr, "measure", options.Quiet, !options.NoHeartbeat, ProgressWriter.DefaultHeartbeatInterval); + progress.Start($"{workloads.Length} workload(s) x {options.Runs} run(s) | sequential | output: {options.OutputDirectory}"); + var completed = 0; + var failed = 0; + foreach (var run in Enumerable.Range(1, options.Runs)) + { + foreach (var workload in workloads) + { + var label = $"{workload.Name} run {run}/{options.Runs}"; + var logPath = Path.Combine(options.OutputDirectory, "logs", $"{workload.Name}.{run}.log"); + var result = await MeasuredProcess.RunAsync( + workload, run, options.RepositoryRoot, environment, logPath, + (liveness, token) => progress.HeartbeatUntilCancelledAsync(() => + { + var state = liveness(); + return $"{completed}/{total} completed | running {label} | child output lines: {state.OutputLines}, last {state.SecondsSinceLastOutput.ToString("0", CultureInfo.InvariantCulture)}s ago (liveness only)"; + }, token), + cancellationToken).ConfigureAwait(false); + + await AppendLineAsync(runsPath, JsonSerializer.Serialize(result, MeasurementJson.Options), cancellationToken).ConfigureAwait(false); + completed++; + var outcome = result.TimedOut ? "TIMEOUT" : $"exit {result.ExitCode}"; + if (result.TimedOut || result.ExitCode != 0) + { + failed++; + } + + progress.Progress($"{completed}/{total} completed | {failed} non-zero | {label}: {outcome}, {result.WallSeconds.ToString("0.00", CultureInfo.InvariantCulture)}s"); + } + } + + progress.Complete($"{completed}/{total} runs measured | {failed} non-zero or timed out | {runsPath}"); + stdout.WriteLine(runsPath); + return 0; + } + + /// + /// Without , every workload except those that require explicit selection; with it, exactly the + /// named workloads. Either way, only workloads that apply to the current platform. + /// + internal static Workload[] Select(WorkloadSet set, string[] only) => + (only.Length == 0 + ? set.Workloads.Where(w => !w.RequiresExplicitSelection) + : set.Workloads.Where(w => only.Contains(w.Name, StringComparer.Ordinal))) + .Where(w => w.AppliesToCurrentPlatform()) + .ToArray(); + + private static async Task AppendLineAsync(string path, string line, CancellationToken cancellationToken) + { + // One complete line per write keeps the JSONL file valid even if the session is interrupted. + await using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read); + var bytes = Encoding.UTF8.GetBytes(line + "\n"); + await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/MeasuredProcess.cs b/tooling/src/Agentic.Tooling/Measurement/MeasuredProcess.cs new file mode 100644 index 0000000..355c770 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/MeasuredProcess.cs @@ -0,0 +1,124 @@ +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using Agentic.Tooling.Execution; + +namespace Agentic.Tooling.Measurement; + +/// Live state of a running measurement, exposed for liveness heartbeats. +internal sealed record RunLiveness(double ElapsedSeconds, long OutputLines, double SecondsSinceLastOutput); + +/// +/// Executes one workload run through and measures it. On Windows the Job Object accounting +/// supplies peak memory, process count and CPU; on Linux the enclosing cgroup supplies memory and CPU, and process +/// counts are reported as unavailable rather than estimated. +/// +internal static class MeasuredProcess +{ + public static async Task RunAsync( + Workload workload, + int run, + string repositoryRoot, + IReadOnlyDictionary environment, + string logPath, + Func, CancellationToken, Task>? onStarted, + CancellationToken cancellationToken) + { + var request = new ChildProcessRequest( + workload.Command[0], + workload.Command.Skip(1).ToArray(), + Path.GetFullPath(Path.Combine(repositoryRoot, workload.WorkingDirectory)), + environment, + TimeSpan.FromSeconds(workload.TimeoutSeconds)); + + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(logPath))!); + await using var log = new StreamWriter(logPath, append: false); + var clock = new Stopwatch(); + var timeline = new OutputTimeline(clock, log); + var startedUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); + using var liveness = new CancellationTokenSource(); + var observer = Task.CompletedTask; + var cpuBefore = OperatingSystem.IsWindows() ? null : CgroupCpuSeconds(); + + clock.Start(); + var outcome = await ChildProcess.RunAsync( + request, + timeline.Record, + () => observer = onStarted?.Invoke(() => Liveness(clock, timeline), liveness.Token) ?? Task.CompletedTask, + cancellationToken).ConfigureAwait(false); + + await liveness.CancelAsync().ConfigureAwait(false); + await observer.ConfigureAwait(false); + if (outcome.Cancelled) + { + throw new OperationCanceledException(cancellationToken); + } + + var wall = outcome.Elapsed.TotalSeconds; + var (maxSilence, maxStderrSilence) = timeline.Complete(wall); + var accounting = outcome.Accounting; + var cpuAfter = OperatingSystem.IsWindows() ? null : CgroupCpuSeconds(); + var cgroupPeak = OperatingSystem.IsWindows() ? null : CgroupMemoryPeakBytes(); + return new MeasuredRun + { + Workload = workload.Name, + Audience = workload.Audience, + Run = run, + StartedUtc = startedUtc, + Platform = PlatformLabel(), + ExitCode = outcome.ExitCode, + TimedOut = outcome.TimedOut, + WallSeconds = Round(wall), + FirstOutputSeconds = Round(timeline.FirstOutput), + FirstStderrSeconds = Round(timeline.FirstStderr), + MaxSilenceSeconds = Round(maxSilence), + MaxStderrSilenceSeconds = Round(maxStderrSilence), + StdoutLines = timeline.StdoutLines, + StderrLines = timeline.StderrLines, + PeakMemoryMiB = accounting?.PeakCommitMiB ?? (cgroupPeak is { } bytes ? Math.Round(bytes / 1048576.0, 1) : null), + PeakMemorySemantics = accounting is not null ? "windows-job-peak-commit" : cgroupPeak is null ? null : "cgroup-memory-peak", + ProcessesCreated = accounting?.TotalProcesses, + CpuSeconds = accounting is not null + ? Round(accounting.CpuSeconds) + : cpuBefore is { } before && cpuAfter is { } after ? Round(after - before) : null, + Ownership = outcome.Ownership, + LingeringProcesses = outcome.LingeringProcesses, + Command = string.Join(' ', workload.Command), + }; + } + + private static RunLiveness Liveness(Stopwatch clock, OutputTimeline timeline) => + new(clock.Elapsed.TotalSeconds, timeline.TotalLines(), timeline.SecondsSinceLastOutput()); + + private static double? CgroupCpuSeconds() + { + const string path = "/sys/fs/cgroup/cpu.stat"; + if (!File.Exists(path)) + { + return null; + } + + foreach (var line in File.ReadLines(path)) + { + if (line.StartsWith("usage_usec ", StringComparison.Ordinal)) + { + return long.Parse(line.AsSpan(11), CultureInfo.InvariantCulture) / 1_000_000.0; + } + } + + return null; + } + + private static long? CgroupMemoryPeakBytes() + { + const string path = "/sys/fs/cgroup/memory.peak"; + return File.Exists(path) && long.TryParse(File.ReadAllText(path).Trim(), CultureInfo.InvariantCulture, out var value) ? value : null; + } + + private static string PlatformLabel() => + $"{RuntimeInformation.OSDescription.Trim()} {RuntimeInformation.OSArchitecture}".ToLowerInvariant(); + + private static double Round(double value) => Math.Round(value, 3); + + private static double? Round(double? value) => value is { } v ? Math.Round(v, 3) : null; +} diff --git a/tooling/src/Agentic.Tooling/Measurement/MeasuredRun.cs b/tooling/src/Agentic.Tooling/Measurement/MeasuredRun.cs new file mode 100644 index 0000000..2f48062 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/MeasuredRun.cs @@ -0,0 +1,71 @@ +namespace Agentic.Tooling.Measurement; + +/// +/// One measured execution. Every field states its own semantics; fields that a platform cannot measure are +/// rather than estimated. +/// +internal sealed record MeasuredRun +{ + public const string SchemaId = "codebeltnet/agentic/measurement/1"; + + public string Schema { get; init; } = SchemaId; + + public required string Workload { get; init; } + + public required string Audience { get; init; } + + /// 1-based run index within the session. Run 1 is the first execution in a fresh session temp directory. + public required int Run { get; init; } + + public required string StartedUtc { get; init; } + + public required string Platform { get; init; } + + public int? ExitCode { get; init; } + + public bool TimedOut { get; init; } + + public required double WallSeconds { get; init; } + + /// Seconds from launch to the first line on either stream. + public double? FirstOutputSeconds { get; init; } + + /// Seconds from launch to the first stderr line (diagnostic and progress channel). + public double? FirstStderrSeconds { get; init; } + + /// Longest interval without a line on either stream, including launch to first line and last line to exit. + public required double MaxSilenceSeconds { get; init; } + + /// Longest interval without a stderr line, including launch to first stderr line and last stderr line to exit. + public required double MaxStderrSilenceSeconds { get; init; } + + public required long StdoutLines { get; init; } + + public required long StderrLines { get; init; } + + /// Peak memory in MiB and what it means; see . + public double? PeakMemoryMiB { get; init; } + + /// + /// windows-job-peak-commit: peak committed private memory of all live processes in the Job Object combined. + /// cgroup-memory-peak: Linux cgroup v2 memory.peak of the enclosing cgroup (includes the harness). + /// + public string? PeakMemorySemantics { get; init; } + + /// Processes created in the Job Object, including the root. Windows only. + public long? ProcessesCreated { get; init; } + + /// User plus kernel CPU seconds of the measured tree (Windows job) or enclosing cgroup (Linux, includes harness). + public double? CpuSeconds { get; init; } + + /// + /// suspended-start-job: created suspended and assigned to the job before its first instruction, so no + /// descendant escapes accounting. process-group: portable start; descendants are only killed on timeout. + /// + public required string Ownership { get; init; } + + /// True when processes were still alive in the job after the root exited and output drained. + public bool LingeringProcesses { get; init; } + + public required string Command { get; init; } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/OutputTimeline.cs b/tooling/src/Agentic.Tooling/Measurement/OutputTimeline.cs new file mode 100644 index 0000000..a071b15 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/OutputTimeline.cs @@ -0,0 +1,76 @@ +using System.Diagnostics; + +namespace Agentic.Tooling.Measurement; + +/// +/// Thread-safe record of when each stdout and stderr line arrived, measured from launch. Lines are written to a +/// per-run log with their arrival time so silent intervals can be inspected afterwards. +/// +internal sealed class OutputTimeline(Stopwatch clock, TextWriter log) +{ + private readonly Lock gate = new(); + private double lastAny; + private double lastStderr; + private double maxSilence; + private double maxStderrSilence; + + public double? FirstOutput { get; private set; } + + public double? FirstStderr { get; private set; } + + public long StdoutLines { get; private set; } + + public long StderrLines { get; private set; } + + public void Record(string line, bool isStderr) + { + lock (gate) + { + var now = clock.Elapsed.TotalSeconds; + maxSilence = Math.Max(maxSilence, now - lastAny); + lastAny = now; + FirstOutput ??= now; + if (isStderr) + { + maxStderrSilence = Math.Max(maxStderrSilence, now - lastStderr); + lastStderr = now; + FirstStderr ??= now; + StderrLines++; + } + else + { + StdoutLines++; + } + + log.Write(now.ToString("0000.000", System.Globalization.CultureInfo.InvariantCulture)); + log.Write(isStderr ? " E " : " O "); + log.WriteLine(line); + } + } + + /// Seconds since the last line on either stream, for liveness heartbeats. + public double SecondsSinceLastOutput() + { + lock (gate) + { + return clock.Elapsed.TotalSeconds - lastAny; + } + } + + public long TotalLines() + { + lock (gate) + { + return StdoutLines + StderrLines; + } + } + + /// Closes the timeline at seconds and returns the silence maxima including the tail. + public (double MaxSilence, double MaxStderrSilence) Complete(double end) + { + lock (gate) + { + return (Math.Max(maxSilence, end - lastAny), Math.Max(maxStderrSilence, end - lastStderr)); + } + } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/SummarizeCommand.cs b/tooling/src/Agentic.Tooling/Measurement/SummarizeCommand.cs new file mode 100644 index 0000000..7ac3c8c --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/SummarizeCommand.cs @@ -0,0 +1,95 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace Agentic.Tooling.Measurement; + +/// Per-workload statistics over measured runs: median, range and sample count, never extrapolated. +internal sealed record WorkloadSummary( + string Workload, + string Audience, + int Samples, + int NonZeroOrTimedOut, + double MedianWallSeconds, + double MinWallSeconds, + double MaxWallSeconds, + double? FirstRunWallSeconds, + double? MedianFirstOutputSeconds, + double? MedianFirstStderrSeconds, + double MaxSilenceSeconds, + double MaxStderrSilenceSeconds, + double? MedianPeakMemoryMiB, + string? PeakMemorySemantics, + double? MedianProcessesCreated, + double? MedianCpuSeconds); + +internal static class SummarizeCommand +{ + public static IReadOnlyList Read(string path) => + File.ReadLines(path) + .Where(line => !string.IsNullOrWhiteSpace(line)) + .Select(line => JsonSerializer.Deserialize(line, MeasurementJson.Options)!) + .ToArray(); + + public static IReadOnlyList Summarize(IEnumerable runs) => + runs.GroupBy(r => r.Workload, StringComparer.Ordinal) + .Select(group => + { + var items = group.OrderBy(r => r.Run).ToArray(); + var wall = items.Select(r => r.WallSeconds).ToArray(); + return new WorkloadSummary( + group.Key, + items[0].Audience, + items.Length, + items.Count(r => r.TimedOut || r.ExitCode != 0), + Median(wall)!.Value, + wall.Min(), + wall.Max(), + items.FirstOrDefault(r => r.Run == 1)?.WallSeconds, + Median(items.Select(r => r.FirstOutputSeconds)), + Median(items.Select(r => r.FirstStderrSeconds)), + items.Max(r => r.MaxSilenceSeconds), + items.Max(r => r.MaxStderrSilenceSeconds), + Median(items.Select(r => r.PeakMemoryMiB)), + items[0].PeakMemorySemantics, + Median(items.Select(r => (double?)r.ProcessesCreated)), + Median(items.Select(r => r.CpuSeconds))); + }) + .OrderBy(s => s.Workload, StringComparer.Ordinal) + .ToArray(); + + /// Median of the values present; when no run produced the value. + public static double? Median(IEnumerable values) + { + var sorted = values.Where(v => v.HasValue).Select(v => v!.Value).Order().ToArray(); + if (sorted.Length == 0) + { + return null; + } + + var middle = sorted.Length / 2; + return sorted.Length % 2 == 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; + } + + private static double? Median(IEnumerable values) => Median(values.Select(v => (double?)v)); + + public static string ToMarkdown(IReadOnlyList summaries) + { + static string S(double? value, string unit = " s") => value is { } v ? v.ToString("0.00", CultureInfo.InvariantCulture) + unit : "n/a"; + static string N(double? value) => value is { } v ? v.ToString("#,0", CultureInfo.InvariantCulture) : "n/a"; + + var builder = new StringBuilder(); + builder.AppendLine("| Workload | Audience | Samples | Non-zero | Median wall | Range | Run 1 | First output | First stderr | Longest silence | Longest stderr silence | Peak memory (MiB) | Processes | CPU |"); + builder.AppendLine("|---|---|---:|---:|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|"); + foreach (var s in summaries) + { + builder.AppendLine(string.Join(" | ", + $"| `{s.Workload}`", s.Audience, s.Samples.ToString(CultureInfo.InvariantCulture), s.NonZeroOrTimedOut.ToString(CultureInfo.InvariantCulture), + S(s.MedianWallSeconds), $"{S(s.MinWallSeconds, string.Empty)} to {S(s.MaxWallSeconds)}", S(s.FirstRunWallSeconds), + S(s.MedianFirstOutputSeconds), S(s.MedianFirstStderrSeconds), S(s.MaxSilenceSeconds), S(s.MaxStderrSilenceSeconds), + N(s.MedianPeakMemoryMiB), N(s.MedianProcessesCreated), S(s.MedianCpuSeconds)) + " |"); + } + + return builder.ToString(); + } +} diff --git a/tooling/src/Agentic.Tooling/Measurement/Workload.cs b/tooling/src/Agentic.Tooling/Measurement/Workload.cs new file mode 100644 index 0000000..1df223a --- /dev/null +++ b/tooling/src/Agentic.Tooling/Measurement/Workload.cs @@ -0,0 +1,92 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Agentic.Tooling.Measurement; + +/// +/// A named, repeatable command whose execution is measured. Baseline and candidate measurements use the same +/// workload file, so that both run the identical workload. +/// +internal sealed record Workload +{ + public required string Name { get; init; } + + /// Who experiences this cost: consumer (skill users and agents) or maintainer (tests, CI). + public required string Audience { get; init; } + + public required string[] Command { get; init; } + + /// Working directory relative to the measured repository root. + public string WorkingDirectory { get; init; } = "."; + + public int TimeoutSeconds { get; init; } = 900; + + public string? Description { get; init; } + + /// + /// When true the workload runs only if named with --only. Used for runs that need explicit approval each + /// time, such as the full local validation matrix. + /// + public bool RequiresExplicitSelection { get; init; } + + /// Optional platform filter: windows, linux or macos. Empty means every platform. + public string[] Platforms { get; init; } = []; + + public bool AppliesToCurrentPlatform() => + Platforms.Length == 0 + || Platforms.Any(p => (p == "windows" && OperatingSystem.IsWindows()) || (p == "linux" && OperatingSystem.IsLinux()) || (p == "macos" && OperatingSystem.IsMacOS())); +} + +internal sealed record WorkloadSet +{ + public const string SchemaId = "codebeltnet/agentic/workloads/1"; + + public required string Schema { get; init; } + + /// Environment applied to every workload, so baseline and candidate share the same settings. + public Dictionary Environment { get; init; } = new(StringComparer.Ordinal); + + public required Workload[] Workloads { get; init; } + + public static WorkloadSet Load(string path) + { + var set = JsonSerializer.Deserialize(File.ReadAllText(path), MeasurementJson.Options) + ?? throw new InvalidDataException($"Workload file '{path}' is empty."); + if (set.Schema != SchemaId) + { + throw new InvalidDataException($"Workload file '{path}' declares schema '{set.Schema}', expected '{SchemaId}'."); + } + + var duplicate = set.Workloads.GroupBy(w => w.Name, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1); + if (duplicate is not null) + { + throw new InvalidDataException($"Workload '{duplicate.Key}' is defined more than once."); + } + + foreach (var workload in set.Workloads) + { + if (workload.Command.Length == 0) + { + throw new InvalidDataException($"Workload '{workload.Name}' has an empty command."); + } + + if (workload.Audience is not ("consumer" or "maintainer")) + { + throw new InvalidDataException($"Workload '{workload.Name}' audience must be 'consumer' or 'maintainer'."); + } + } + + return set; + } +} + +internal static class MeasurementJson +{ + public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.Never, + WriteIndented = false, + }; + + public static readonly JsonSerializerOptions Indented = new(Options) { WriteIndented = true }; +} diff --git a/tooling/src/Agentic.Tooling/Program.cs b/tooling/src/Agentic.Tooling/Program.cs new file mode 100644 index 0000000..e7e6c42 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Program.cs @@ -0,0 +1,198 @@ +using Agentic.Tooling.Measurement; +using Agentic.Tooling.Validation; + +namespace Agentic.Tooling; + +internal static class Program +{ + private const string Usage = """ + Usage: + agentic-tooling measure --workloads --repo-root --out [--runs ] [--only ]... [--quiet] [--no-heartbeat] + agentic-tooling summarize --runs-file [--json] + agentic-tooling validate-local [--max-concurrency ] [--timeout-seconds ] [--deadline-seconds ] [--output-root ] + [--workflow-path ] [--repository-root ] [--progress-file ] [--list-suites] [--json] + [--quiet] [--no-heartbeat] [--heartbeat-seconds ] + + measure Runs workloads sequentially and records one JSON line per run (runs.jsonl), per-run logs and environment.json. + Progress and heartbeats go to stderr; stdout receives only the runs.jsonl path. + Every session gives its workloads a fresh temp directory, so run 1 starts with empty temp-based caches. + Workload file: + { "schema": "codebeltnet/agentic/workloads/1", "environment": { "NAME": "value" }, + "workloads": [ { "name": "x", "audience": "consumer|maintainer", "command": ["exe", "arg"] } ] } + Optional per workload: workingDirectory, timeoutSeconds, description, platforms, requiresExplicitSelection. + The definitions and results of one investigation are working files; keep them under .bot/. + summarize Prints per-workload median, range and sample count as Markdown (or JSON with --json) on stdout. + validate-local + Runs every suite of the CI validation matrix locally, one process per suite, with bounded concurrency, + per-suite timeouts that kill whole process trees, and terminal-marker verification. Progress and + heartbeats go to stderr and to a progress file (default /progress.json); stdout receives + the summary.json path, or the summary itself with --json. Exit 0 only when every suite passed verified. + """; + + public static async Task Main(string[] args) + { + using var cancellation = new CancellationTokenSource(); + Console.CancelKeyPress += (_, e) => + { + e.Cancel = true; + cancellation.Cancel(); + }; + + try + { + return args.FirstOrDefault() switch + { + "measure" => await MeasureCommand.RunAsync(ParseMeasure(args[1..]), Console.Out, Console.Error, cancellation.Token).ConfigureAwait(false), + "summarize" => Summarize(args[1..]), + "validate-local" => await ValidateLocalCommand.RunAsync(ParseValidateLocal(args[1..]), Console.Out, Console.Error, cancellation.Token).ConfigureAwait(false), + "--help" or "-h" or null => Help(0), + _ => Help(2), + }; + } + catch (ArgumentException exception) + { + Console.Error.WriteLine(exception.Message); + return Help(2); + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + Console.Error.WriteLine("[CANCELLED] agentic-tooling | cancelled by user; owned process trees were terminated."); + return 130; + } + } + + private static int Help(int exitCode) + { + (exitCode == 0 ? Console.Out : Console.Error).WriteLine(Usage); + return exitCode; + } + + private static MeasureOptions ParseMeasure(string[] args) + { + var arguments = new ArgumentReader(args); + return new MeasureOptions + { + WorkloadsPath = arguments.Required("--workloads"), + RepositoryRoot = Path.GetFullPath(arguments.Required("--repo-root")), + OutputDirectory = Path.GetFullPath(arguments.Required("--out")), + Runs = int.Parse(arguments.Optional("--runs") ?? "3", System.Globalization.CultureInfo.InvariantCulture), + Only = arguments.Many("--only"), + Quiet = arguments.Flag("--quiet"), + NoHeartbeat = arguments.Flag("--no-heartbeat"), + }.Validate(arguments); + } + + private static MeasureOptions Validate(this MeasureOptions options, ArgumentReader arguments) + { + arguments.EnsureConsumed(); + if (options.Runs < 1) + { + throw new ArgumentException("--runs must be at least 1."); + } + + return options; + } + + private static ValidateLocalOptions ParseValidateLocal(string[] args) + { + var arguments = new ArgumentReader(args); + var options = new ValidateLocalOptions + { + MaxConcurrency = Integer(arguments, "--max-concurrency", Environment.ProcessorCount, 1, 128), + TimeoutSeconds = Integer(arguments, "--timeout-seconds", 900, 0, 86400), + DeadlineSeconds = Integer(arguments, "--deadline-seconds", 0, 0, 86400), + OutputRoot = arguments.Optional("--output-root"), + WorkflowPath = arguments.Optional("--workflow-path"), + RepositoryRoot = arguments.Optional("--repository-root"), + ProgressFile = arguments.Optional("--progress-file"), + ListSuites = arguments.Flag("--list-suites"), + Json = arguments.Flag("--json"), + Quiet = arguments.Flag("--quiet"), + NoHeartbeat = arguments.Flag("--no-heartbeat"), + HeartbeatSeconds = Integer(arguments, "--heartbeat-seconds", 10, 1, 300), + }; + arguments.EnsureConsumed(); + return options; + } + + private static int Integer(ArgumentReader arguments, string name, int fallback, int minimum, int maximum) + { + var text = arguments.Optional(name); + if (text is null) + { + return fallback; + } + + if (!int.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var value) || value < minimum || value > maximum) + { + throw new ArgumentException($"{name} must be an integer from {minimum} to {maximum}."); + } + + return value; + } + + private static int Summarize(string[] args) + { + var arguments = new ArgumentReader(args); + var path = arguments.Required("--runs-file"); + var json = arguments.Flag("--json"); + arguments.EnsureConsumed(); + var summaries = SummarizeCommand.Summarize(SummarizeCommand.Read(path)); + Console.Out.Write(json + ? System.Text.Json.JsonSerializer.Serialize(summaries, MeasurementJson.Indented) + Environment.NewLine + : SummarizeCommand.ToMarkdown(summaries)); + return 0; + } +} + +/// Minimal option reader: --name value, repeated values and flags; rejects anything unrecognized. +internal sealed class ArgumentReader(string[] args) +{ + private readonly bool[] consumed = new bool[args.Length]; + + public string Required(string name) => Optional(name) ?? throw new ArgumentException($"Missing required option {name}."); + + public string? Optional(string name) => Many(name) is [var single] ? single : Many(name) is [] ? null : throw new ArgumentException($"Option {name} may be given only once."); + + public string[] Many(string name) + { + var values = new List(); + for (var i = 0; i < args.Length; i++) + { + if (args[i] != name) + { + continue; + } + + if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + throw new ArgumentException($"Option {name} requires a value."); + } + + consumed[i] = consumed[i + 1] = true; + values.Add(args[i + 1]); + } + + return [.. values]; + } + + public bool Flag(string name) + { + var index = Array.IndexOf(args, name); + if (index >= 0) + { + consumed[index] = true; + } + + return index >= 0; + } + + public void EnsureConsumed() + { + var unknown = args.Where((_, i) => !consumed[i]).ToArray(); + if (unknown.Length > 0) + { + throw new ArgumentException($"Unrecognized argument(s): {string.Join(' ', unknown)}"); + } + } +} diff --git a/tooling/src/Agentic.Tooling/Validation/SuiteMatrix.cs b/tooling/src/Agentic.Tooling/Validation/SuiteMatrix.cs new file mode 100644 index 0000000..eaa84e0 --- /dev/null +++ b/tooling/src/Agentic.Tooling/Validation/SuiteMatrix.cs @@ -0,0 +1,86 @@ +using System.Text.RegularExpressions; + +namespace Agentic.Tooling.Validation; + +/// One CI matrix entry: { name: ..., script: ..., suite: ... }. +internal sealed record SuiteEntry(string Name, string Script, string Suite); + +/// +/// The CI workflow is the coverage source of truth: every literal { name, script, suite } entry is one +/// independently scheduled suite, so local runs and CI cover the same checks. +/// +internal static partial class SuiteMatrix +{ + public static IReadOnlyList Load(string workflowPath) + { + if (!File.Exists(workflowPath)) + { + throw new ValidationSetupException($"Validation workflow was not found at '{workflowPath}'."); + } + + var entries = EntryPattern().Matches(File.ReadAllText(workflowPath)) + .Select(match => new SuiteEntry(match.Groups["name"].Value, match.Groups["script"].Value, match.Groups["suite"].Value)) + .ToArray(); + if (entries.Length == 0) + { + throw new ValidationSetupException("The validation workflow defines no suite entries."); + } + + if (entries.Select(entry => entry.Name).Distinct(StringComparer.Ordinal).Count() != entries.Length) + { + throw new ValidationSetupException("Validation suite names must be unique."); + } + + return entries; + } + + [GeneratedRegex(@"\{ name: (?[\w-]+), script: (?