From 7827d6946376cb350bc3e9d0987cf90ed6b0502e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Fri, 20 Nov 2026 16:57:55 +0300 Subject: [PATCH] ci: reuse green PR CI results in merge queue Extract the native inspection path into InspectAsync to keep RunAsync within MA0051 after adding the reuse command. --- .github/workflows/ci.yml | 229 ++++++++++++++++-- docs/engineering/quality-gates.md | 57 +++-- docs/engineering/workflow.md | 9 +- .../Ci/MergeGroupReuseDecisionTests.cs | 89 +++++++ .../Ci/MergeGroupReuseRunnerTests.cs | 85 +++++++ .../NativeApplicationTests.MergeGroupReuse.cs | 50 ++++ .../Native/NativeArgumentsTests.cs | 29 ++- .../Support/MergeGroupReuseFixture.cs | 149 ++++++++++++ .../Ci/MergeGroupReuseDecision.cs | 119 +++++++++ .../Ci/MergeGroupReuseRunner.cs | 41 ++++ .../Native/NativeApplication.cs | 25 +- .../Native/NativeArguments.cs | 6 +- .../Native/NativeCommand.cs | 2 +- 13 files changed, 843 insertions(+), 47 deletions(-) create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseDecisionTests.cs create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseRunnerTests.cs create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.MergeGroupReuse.cs create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Support/MergeGroupReuseFixture.cs create mode 100644 tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseDecision.cs create mode 100644 tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseRunner.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7090a05..ba06ee2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,10 +81,199 @@ jobs: } "code=$code" >> $env:GITHUB_OUTPUT + - name: Record the tested tree + if: github.event_name == 'pull_request' + run: | + $ErrorActionPreference = 'Stop' + $trees = git rev-parse 'HEAD^{tree}' 'HEAD^1^{tree}' + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve the tested trees.' } + [IO.File]::WriteAllText((Join-Path $env:RUNNER_TEMP 'tested-tree'), ($trees -join "`n") + "`n") + + - name: Upload the tested tree + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@v7 + with: + name: tested-tree-${{ github.run_attempt }} + path: ${{ runner.temp }}/tested-tree + retention-days: 7 + if-no-files-found: error + + reuse: + name: Reuse tested tree + if: github.event_name == 'merge_group' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + actions: read + pull-requests: read + outputs: + reuse: ${{ steps.guard.outputs.reuse || steps.decide.outputs.reuse }} + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Guard against self-vouching before executing repository tooling + id: guard + env: + QUEUE_REF: ${{ github.ref }} + QUEUE_BASE: ${{ github.event.merge_group.base_sha }} + QUEUE_FETCH_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + $facts = Join-Path $env:RUNNER_TEMP 'reuse' + New-Item -ItemType Directory -Path $facts | Out-Null + function Save-Fact($name, $value) { [IO.File]::WriteAllText((Join-Path $facts $name), $value) } + function Save-Revision($name, $revision) { + $sha = git rev-parse --verify $revision + if ($LASTEXITCODE -ne 0) { $sha = '' } + Save-Fact $name $sha + return $sha + } + Save-Fact 'queue-ref' $env:QUEUE_REF + Save-Fact 'base' $env:QUEUE_BASE + $null = Save-Revision 'tree' 'HEAD^{tree}' + $parents = git rev-list --parents -n 1 HEAD + $parentCount = if ($LASTEXITCODE -eq 0) { $parents.Split(' ').Length - 1 } else { '' } + Save-Fact 'parent-count' $parentCount + $head = Save-Revision 'head' 'HEAD^2' + $reason = & { + try { + if ($parentCount -ne 2 -or !$head) { throw 'Cannot resolve the guard revisions.' } + # Determine the common ancestor before the shallow fetch can change the history walk. + $mergeBase = git merge-base 'HEAD^1' $head + $mergeBaseExit = $LASTEXITCODE + $credential = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("x-access-token:$env:QUEUE_FETCH_TOKEN")) + $env:QUEUE_FETCH_AUTH = "AUTHORIZATION: basic $credential" + git --config-env=http.https://github.com/.extraheader=QUEUE_FETCH_AUTH fetch --no-tags --depth=1 origin refs/heads/master | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Cannot fetch master.' } + $masterTip = git rev-parse --verify FETCH_HEAD + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve the fetched master tip.' } + if ($env:QUEUE_BASE -cne $masterTip -or $parents.Split(' ')[1] -cne $masterTip) { return 'rule 5: base differs from master' } + if ($mergeBaseExit -ne 0) { throw 'Cannot resolve the merge base.' } + $paths = Join-Path $facts 'changed-paths' + git diff --name-only --no-renames -z $mergeBase $head > $paths + if ($LASTEXITCODE -ne 0) { throw 'Cannot read the changed paths.' } + if (!(Save-Revision 'base-tree' "$($env:QUEUE_BASE)^{tree}")) { throw 'Cannot resolve the base tree.' } + $comparison = [StringComparison]::OrdinalIgnoreCase + # Keep these guarded paths in sync with MergeGroupReuseDecision.IsGuarded. + foreach ($path in [IO.File]::ReadAllText($paths, [Text.UTF8Encoding]::new($false, $true)).Split([char]0)) { + $leaf = $path.Split('/')[-1] + if ($path.StartsWith('.github/', $comparison) -or $path.StartsWith('tools/', $comparison) -or + $leaf.StartsWith('Directory.Build.', $comparison) -or $leaf.Equals('Directory.Packages.props', $comparison) -or + $leaf.Equals('global.json', $comparison) -or $leaf.Equals('nuget.config', $comparison)) { + return 'rule 5: guarded path' + } + } + } catch { + 'unavailable guard facts' + } + } + $env:QUEUE_FETCH_AUTH = $null + $env:QUEUE_FETCH_TOKEN = $null + git config --local --unset-all http.https://github.com/.extraheader 2>$null + $global:LASTEXITCODE = 0 + if ($reason) { + @('reuse=false', "reason=$reason", 'blocked=true') >> $env:GITHUB_OUTPUT + @('### Merge-group reuse', 'reuse=false', "reason=$reason") >> $env:GITHUB_STEP_SUMMARY + } + exit 0 + + - name: Setup .NET SDK + if: steps.guard.outputs.blocked != 'true' + uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - name: Log resolved SDK + if: steps.guard.outputs.blocked != 'true' + run: | + $ErrorActionPreference = 'Stop' + dotnet --version + exit $LASTEXITCODE + + - name: Gather GitHub facts + id: facts + if: steps.guard.outputs.blocked != 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + $facts = Join-Path $env:RUNNER_TEMP 'reuse' + $api = "repos/$env:GITHUB_REPOSITORY" + function Get-Fact($name, $endpoint, $collection) { + $file = Join-Path $facts $name + [IO.File]::WriteAllText($file, '') + if (!$endpoint) { return } + try { + if ($collection) { + $pages = gh api --paginate --slurp $endpoint + if ($LASTEXITCODE -ne 0) { throw "Cannot fetch $name." } + # Check the fetch before flattening its pages. jq preserves the timestamp strings. + $pages | jq --arg collection $collection '{($collection): [ .[][$collection][] ]}' > $file + } else { + gh api $endpoint > $file + } + if ($LASTEXITCODE -ne 0) { throw "Cannot write $name." } + if ($collection -cin 'workflow_runs', 'artifacts') { + Get-Content -LiteralPath $file -Raw | ConvertFrom-Json + } + } catch { + Write-Warning "Cannot gather $name." + [IO.File]::WriteAllText($file, '') + } + } + $queue = ([string](Get-Content (Join-Path $facts 'queue-ref') -Raw)).Trim() + $head = ([string](Get-Content (Join-Path $facts 'head') -Raw)).Trim() + $prEndpoint = if ($queue -cmatch '^refs/heads/gh-readonly-queue/master/pr-(\d+)-') { "$api/pulls/$($Matches[1])" } + $null = Get-Fact 'pr.json' $prEndpoint + $runs = Get-Fact 'runs.json' "$api/actions/workflows/ci.yml/runs?event=pull_request&head_sha=$head&per_page=100" 'workflow_runs' + $latest = $runs.workflow_runs | Where-Object { $_.path -ceq '.github/workflows/ci.yml' -and $_.event -ceq 'pull_request' -and $_.head_sha -ceq $head } | + Sort-Object -Property created_at, id -Descending | Select-Object -First 1 + $id, $attempt = $latest.id, $latest.run_attempt + $run = if ($id -and $attempt) { "$api/actions/runs/$id" } + $null = Get-Fact 'jobs.json' $(if ($run) { "$run/attempts/$attempt/jobs?per_page=100" }) 'jobs' + $artifacts = Get-Fact 'artifacts.json' $(if ($run) { "$run/artifacts?per_page=100" }) 'artifacts' + $treeFile = Join-Path $facts 'tested-tree' + [IO.File]::WriteAllText($treeFile, '') + if ($run) { "link=$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$id/attempts/$attempt" >> $env:GITHUB_OUTPUT } + $artifact = @($artifacts.artifacts | Where-Object { $_.name -ceq "tested-tree-$attempt" -and $_.expired -eq $false }) + if ($artifact.Count -ne 1 -or !$artifact[0].id) { exit 0 } + try { + $zipFile = Join-Path $facts 'artifact.zip' + gh api "$api/actions/artifacts/$($artifact[0].id)/zip" > $zipFile + if ($LASTEXITCODE -ne 0) { throw 'Cannot download artifact.' } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = [IO.Compression.ZipFile]::OpenRead($zipFile) + $entry = @($zip.Entries | Where-Object { $_.FullName -ceq 'tested-tree' }) + if ($entry.Count -ne 1) { throw 'Expected one tested-tree entry.' } + [IO.Compression.ZipFileExtensions]::ExtractToFile($entry[0], $treeFile, $true) + } catch { + Write-Warning 'Cannot extract the tested tree.' + [IO.File]::WriteAllText($treeFile, '') + } finally { + if ($zip) { $zip.Dispose() } + } + exit 0 + + - name: Decide reuse + id: decide + if: steps.guard.outputs.blocked != 'true' + env: + REUSED_RUN: ${{ steps.facts.outputs.link }} + run: | + $ErrorActionPreference = 'Stop' + dotnet run tools/native.cs -- merge-group-reuse --facts (Join-Path $env:RUNNER_TEMP 'reuse') --output $env:GITHUB_OUTPUT + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + @('### Merge-group reuse', (Get-Content $env:GITHUB_OUTPUT -Raw), "Run: $env:REUSED_RUN") >> $env:GITHUB_STEP_SUMMARY + lint: name: Lint - needs: changes - if: needs.changes.outputs.code == 'true' + needs: [changes, reuse] + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.code == 'true' && !(needs.reuse.result == 'success' && needs.reuse.outputs.reuse == 'true') }} runs-on: ubuntu-24.04 timeout-minutes: 30 steps: @@ -165,8 +354,8 @@ jobs: build-and-test: name: Build and test (${{ matrix.os }}) - needs: changes - if: needs.changes.outputs.code == 'true' + needs: [changes, reuse] + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.code == 'true' && !(needs.reuse.result == 'success' && needs.reuse.outputs.reuse == 'true') }} runs-on: ${{ matrix.os }} timeout-minutes: 55 permissions: @@ -310,7 +499,7 @@ jobs: ci-result: name: CI result - needs: [changes, lint, build-and-test] + needs: [changes, reuse, lint, build-and-test] if: always() runs-on: ubuntu-24.04 timeout-minutes: 5 @@ -318,25 +507,35 @@ jobs: steps: - name: Require every needed job env: + EVENT: ${{ github.event_name }} + REUSE_RESULT: ${{ needs.reuse.result }} + REUSE: ${{ needs.reuse.outputs.reuse }} CHANGES: ${{ needs.changes.result }} CODE: ${{ needs.changes.outputs.code }} LINT: ${{ needs.lint.result }} BUILD_AND_TEST: ${{ needs.build-and-test.result }} run: | $ErrorActionPreference = 'Stop' - Write-Output "changes=$env:CHANGES code=$env:CODE lint=$env:LINT build-and-test=$env:BUILD_AND_TEST" + Write-Output "event=$env:EVENT reuse-result=$env:REUSE_RESULT reuse=$env:REUSE changes=$env:CHANGES code=$env:CODE lint=$env:LINT build-and-test=$env:BUILD_AND_TEST" $errors = [System.Collections.Generic.List[string]]::new() if ($env:CHANGES -cne 'success') { $errors.Add('Changes must succeed.') } - switch -CaseSensitive ($env:CODE) { - 'true' { - if ($env:LINT -cne 'success') { $errors.Add('Code changes require successful lint.') } - if ($env:BUILD_AND_TEST -cne 'success') { $errors.Add('Code changes require successful build/test legs.') } - } - 'false' { - if ($env:LINT -cne 'skipped') { $errors.Add('Documentation-only changes require skipped lint.') } - if ($env:BUILD_AND_TEST -cne 'skipped') { $errors.Add('Documentation-only changes require skipped build/test legs.') } + if ($env:REUSE_RESULT -ceq 'success' -and $env:REUSE -ceq 'true') { + if ($env:EVENT -cne 'merge_group') { $errors.Add('Reuse requires a merge group.') } + if ($env:CODE -cne 'true' -and $env:CODE -cne 'false') { $errors.Add('Code classification must be true or false.') } + if ($env:LINT -cne 'skipped') { $errors.Add('Reuse requires skipped lint.') } + if ($env:BUILD_AND_TEST -cne 'skipped') { $errors.Add('Reuse requires skipped build/test legs.') } + } else { + switch -CaseSensitive ($env:CODE) { + 'true' { + if ($env:LINT -cne 'success') { $errors.Add('Code changes require successful lint.') } + if ($env:BUILD_AND_TEST -cne 'success') { $errors.Add('Code changes require successful build/test legs.') } + } + 'false' { + if ($env:LINT -cne 'skipped') { $errors.Add('Documentation-only changes require skipped lint.') } + if ($env:BUILD_AND_TEST -cne 'skipped') { $errors.Add('Documentation-only changes require skipped build/test legs.') } + } + default { $errors.Add('Code classification must be true or false.') } } - default { $errors.Add('Code classification must be true or false.') } } foreach ($message in $errors) { Write-Output "::error::$message" } if ($errors.Count -gt 0) { exit 1 } diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index 4d0b09d..c30c73f 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -498,11 +498,32 @@ This is the decided CI contract; `../ROADMAP.md` records whether it is in place. parent; merge groups compare with their declared base, including preceding queue entries. Git supplies NUL-separated paths with rename detection disabled, so a source-to-Markdown rename still selects code. Only an ordinal `.md` suffix or the exact root `LICENSE` path is exempt. + On pull requests, `Changes` uploads `tested-tree-` with seven-day retention. + Its two lines record the synthetic merge commit's tree and its first parent's tree, in that order. +- **Reuse job.** The `reuse` job runs on `merge_group` with a 10-minute bound and read-only + `contents: read`, `actions: read`, and `pull-requests: read` permissions. It reuses CI only when + all five conditions hold: + 1. The group commit has two parents, the `master` queue ref identifies a pull request, and the + head and declared base are valid commit hashes. The second parent supplies the head. + 2. The pull request still has that head and targets `master`. + 3. The head's latest `pull_request` run of `.github/workflows/ci.yml` finished successfully, + and its latest attempt has one successful `CI result` job. + 4. The attempt has one unexpired tested-tree artifact with the expected name, created during its + successful `Changes` job. The recorded trees equal the group's tree and declared base tree. + 5. The pull request leaves guarded paths untouched, compared case-insensitively. These are + `.github/**`, `tools/**`, and any `Directory.Build.*`, `Directory.Packages.props`, `global.json`, + or `nuget.config` file. Before .NET setup or repository tooling runs, the shell checks these + paths and verifies that `base_sha` and the first parent match `origin/master`, so a stacked + entry cannot run unmerged tooling from an earlier queue entry. + + Missing, invalid, or uncertain evidence uses the usual CI job selection. “Re-run failed jobs” + leaves a successful `Changes` job in its old attempt, so the new attempt has no tested-tree + artifact and runs full CI. The job summary records the decision and links the selected run attempt. - **Lint job.** One Linux job restores the local tools, runs Slopwatch, the Release build with the analyzer wall, both format passes, and the "Verify native tool entry" step (the separate file-app build and empty-receipt smoke). -- **Aspire home input.** The CI task supplies an owned `ASPIRE_HOME` under each job's temporary - directory before every build and test command, and retains it through that job's tests. Dashboard +- **Aspire home input.** Lint and build/test supply an owned `ASPIRE_HOME` under each job's temporary + directory before building or testing the solution, and retain it through that job's tests. Dashboard data stays beneath that home. The AppHost SDK's normal build acquires its paired CLI bundle through `DnxPinned`; no global Aspire, Docker, native compiler or certificate-trust preparation is required for this HTTP-only, container-free graph. Build output is never shared between OSes. @@ -512,18 +533,17 @@ This is the decided CI contract; `../ROADMAP.md` records whether it is in place. every test step so TUnit does not upload with the ambient runtime token. These managed legs establish no native coverage for any RID. - **`CI result`.** One fail-closed job named `CI result` runs with `if: always()`, needs every - other job, and is the one required check: a skipped matrix leg reports under its unexpanded name, - so the legs cannot be required one by one. A change that reaches code needs every job green; a - documentation-only change needs the changes job green and the skipped jobs skipped. + other job, and is the one required check. A skipped matrix leg reports under its unexpanded + name, so the legs cannot be required one by one. The verdict table below governs job results. - **Merge queue.** Everything lands on the default branch through the merge queue, which requires the `CI result` check (`workflow.md`). - **Least privilege and bounds.** The workflow has `contents: read`; each build/test leg adds - `checks: write` for its test report, and nothing else is granted. A superseded pull request run - is cancelled, while each default-branch push has a per-commit concurrency group so a newer commit - does not cancel its pending or running workflow; every job has a bounded timeout. The .NET SDK is set - up from `global.json` and each job logs the version that resolved. Steps run in `pwsh` and check - every command's exit code. Job bounds are 5 minutes for classification, 30 for lint, 55 for each - build/test leg and 5 for the aggregate check. + `checks: write` for its test report. The reuse job's additional read permissions are listed above. + CI cancels a superseded pull request run. Each default-branch push has a per-commit concurrency + group so a newer commit cannot cancel its pending or running workflow. Every job has a bounded + timeout. Jobs that use the SDK set it up from `global.json` and log the resolved version. + Steps run in `pwsh` and check every command's exit code. Job bounds are 5 minutes for + classification, 10 for reuse, 30 for lint, 55 for each build/test leg and 5 for the aggregate check. - **Artifacts.** Each build/test leg uploads `artifacts/test-results/**` with `if: always()`, an OS-specific artifact name and seven-day retention. This directory holds the test platform's TRX files, TUnit HTML and JSON reports and, on a hang, hang-dump files; all are uploaded. No redaction @@ -555,14 +575,15 @@ After a failed test step, if the build succeeded and the run was not cancelled, step runs `dotnet test --solution OpenCode.Mcp.slnx --configuration Release --no-build --treenode-filter "/*/*/*/*[Category!=Package]" --list-tests`. This lists tests without executing them again. Both steps disable TUnit artifact upload. -`CI result` accepts exactly these dependency states; missing, failed, cancelled or invalid states -fail closed: +`CI result` first requires `Changes` to succeed. A reuse claim means the reuse job succeeded +and returned `true`. The check accepts only the passing combinations below. -| Changes result | Code output | Lint result | Build/test result | Verdict | -|---|---|---|---|---| -| `success` | `true` | `success` | `success` | Pass | -| `success` | `false` | `skipped` | `skipped` | Pass | -| Any other combination | | | | Fail | +| Changes result | Reuse claim | Event | Code output | Lint result | Build/test result | Verdict | +|---|---|---|---|---|---|---| +| `success` | Yes | `merge_group` | `true` or `false` | `skipped` | `skipped` | Pass | +| `success` | No | Any | `true` | `success` | `success` | Pass | +| `success` | No | Any | `false` | `skipped` | `skipped` | Pass | +| Any other combination | | | | | | Fail | Review workflow syntax before submission and require hosted parse validation; a local build does not parse workflow YAML. diff --git a/docs/engineering/workflow.md b/docs/engineering/workflow.md index 70d1f4f..263cfc0 100644 --- a/docs/engineering/workflow.md +++ b/docs/engineering/workflow.md @@ -1,6 +1,6 @@ # Repository Workflow -Date: 2026-11-14 +Date: 2026-11-20 Canonical working agreements for research, implementation, temporary work, verification, and Git history. @@ -152,9 +152,10 @@ operational state in `../ROADMAP.md`; the rules below are the contract they impl requires the queue and the `CI result` check, for administrators too. - A pull request joins the queue on the maintainer's approval, once the `CI result` check of its own head is green. The queue tests it again on top of current `master` and the entries ahead of - it, and merges only on that green: a green result from an older base is not enough. After the - merge, the work is done when the CI the merge commit triggers on `master` is green; a merge of - only Markdown or `LICENSE` triggers none, and its queue result stands. + it, except when [CI proves the same trees can reuse the pull request's result](quality-gates.md#continuous-integration). + The queue merges only on a green queue result. After the merge, the work is done when the CI + the merge commit triggers on `master` is green. A merge of only Markdown or `LICENSE` triggers + none, and its queue result stands. - CI runs on every pull request and queue entry. A change that touches only Markdown or `LICENSE` passes without the build and test jobs. Never put `[skip ci]` in a pull request's commits: the required check would not report, and the pull request could not join the queue. diff --git a/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseDecisionTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseDecisionTests.cs new file mode 100644 index 0000000..a37ebf1 --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseDecisionTests.cs @@ -0,0 +1,89 @@ +using OpenCode.Mcp.Tools.Ci; +using OpenCode.Mcp.Tools.Tests.Support; + +namespace OpenCode.Mcp.Tools.Tests.Ci; + +public sealed class MergeGroupReuseDecisionTests +{ + [Test] + public async Task Reason_Should_Allow_Reuse_When_All_Rules_Hold() => + await Assert.That(MergeGroupReuseDecision.Reason(new MergeGroupReuseFixture().Facts)).IsEqualTo(MergeGroupReuseFixture.ApprovedReason); + + [Test] + [Arguments("artifact-at-start")] + [Arguments("artifact-at-end")] + [Arguments("crlf-tested-tree")] + public async Task Reason_Should_Allow_Reuse_When_Evidence_Is_On_An_Accepted_Boundary(string row) => + await Assert.That(MergeGroupReuseDecision.Reason(new MergeGroupReuseFixture().WithRow(row).Facts)).IsEqualTo(MergeGroupReuseFixture.ApprovedReason); + + [Test] + [Arguments("one-parent", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("invalid-queue-ref", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("invalid-pr-number", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("non-pr-queue-ref", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("invalid-head", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("invalid-base", MergeGroupReuseFixture.InvalidGroupReason)] + [Arguments("moved-head", MergeGroupReuseFixture.ChangedPullRequestReason)] + [Arguments("feature-base", MergeGroupReuseFixture.ChangedPullRequestReason)] + [Arguments("different-pr", MergeGroupReuseFixture.ChangedPullRequestReason)] + [Arguments("no-run", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("failed-attempt", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("running-attempt", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("invalid-attempt", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("newer-failed-run", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("other-workflow", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("other-event", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("other-run-head", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("failed-result", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("old-result", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("other-run-result", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("duplicate-result", MergeGroupReuseFixture.NoGreenResultReason)] + [Arguments("no-artifact", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("old-artifact", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("different-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("different-base-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("non-hash-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("non-hash-base-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("missing-base-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("extra-tested-tree-line", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("blank-tested-tree-line", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("extra-tested-tree-newline", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("empty-base-tree", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("replacement-after", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("replacement-before", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("duplicate-artifact", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("expired-artifact", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("failed-changes", MergeGroupReuseFixture.UnprovenTreeReason)] + [Arguments("malformed", MergeGroupReuseFixture.MalformedFactsReason)] + [Arguments("wrong-json-type", MergeGroupReuseFixture.MalformedFactsReason)] + [Arguments("null-run-time", MergeGroupReuseFixture.MalformedFactsReason)] + public async Task Reason_Should_Report_The_Refusal_When_A_Fact_Changes(string row, string expected) + { + var facts = new MergeGroupReuseFixture().WithRow(row).Facts; + string? reason = null; + await Assert.That(() => reason = MergeGroupReuseDecision.Reason(facts)).ThrowsNothing(); + await Assert.That(reason).IsEqualTo(expected); + } + + [Test] + [Arguments(".github/workflows/ci.yml")] + [Arguments(".GITHUB/workflows/ci.yml")] + [Arguments("tools/example.cs")] + [Arguments("TOOLS/example.cs")] + [Arguments("tools/Directory.Build.props")] + [Arguments("Directory.Build.user")] + [Arguments("nested/directory.build.props")] + [Arguments("nested/Directory.Build.targets")] + [Arguments("nested/Directory.Build.rsp")] + [Arguments("nested/Directory.Packages.props")] + [Arguments("global.json")] + [Arguments("nested/Global.json")] + [Arguments("nested/nuget.config")] + [Arguments("nested/NuGet.Config")] + public async Task Reason_Should_Refuse_Reuse_When_Any_Path_Is_Guarded(string path) => + await Assert.That(MergeGroupReuseDecision.Reason(new MergeGroupReuseFixture().WithChangedPath(path).Facts)).IsEqualTo(MergeGroupReuseFixture.GuardedPathReason); + + [Test] + public async Task Reason_Should_Refuse_Reuse_When_A_Fact_Is_Missing() => + await Assert.That(MergeGroupReuseDecision.Reason(new MergeGroupReuseFixture().WithoutTree().Facts)).IsEqualTo(MergeGroupReuseFixture.MalformedFactsReason); +} diff --git a/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseRunnerTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseRunnerTests.cs new file mode 100644 index 0000000..2708332 --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Ci/MergeGroupReuseRunnerTests.cs @@ -0,0 +1,85 @@ +using System.Globalization; +using System.IO.Abstractions; +using NSubstitute; +using OpenCode.Mcp.Tools.Ci; +using OpenCode.Mcp.Tools.Tests.Support; +using Testably.Abstractions.Testing; + +namespace OpenCode.Mcp.Tools.Tests.Ci; + +public sealed class MergeGroupReuseRunnerTests +{ + [Test] + [Arguments("all", "true", MergeGroupReuseFixture.ApprovedReason)] + [Arguments("different-tree", "false", MergeGroupReuseFixture.UnprovenTreeReason)] + public async Task RunAsync_Should_Append_The_Decision_And_Report_Its_Reason(string row, string reuse, string reason, CancellationToken token) + { + var files = new MockFileSystem(); + var root = files.Path.Combine(files.Path.GetTempPath(), "facts"); + var outputFile = files.Path.Combine(root, "github-output"); + await new MergeGroupReuseFixture().WithRow(row).WriteAsync(files, root, token); + await files.File.WriteAllTextAsync(outputFile, "existing=value\n", token); + using var output = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" }; + + await new MergeGroupReuseRunner(files, output).RunAsync(root, outputFile, token); + + await Assert.That(await files.File.ReadAllTextAsync(outputFile, token)).IsEqualTo($"existing=value\nreuse={reuse}\nreason={reason}\n"); + await Assert.That(output.ToString()).IsEqualTo(reason + "\n"); + } + + [Test] + public async Task RunAsync_Should_Report_And_Append_A_Refusal_When_A_Fact_Is_Unreadable(CancellationToken token) + { + var files = new MockFileSystem(); + var root = files.Path.Combine(files.Path.GetTempPath(), "facts"); + var outputFile = files.Path.Combine(root, "github-output"); + await new MergeGroupReuseFixture().WithoutTree().WriteAsync(files, root, token); + await files.File.WriteAllTextAsync(outputFile, "", token); + var missing = await Assert.ThrowsAsync(() => files.File.ReadAllTextAsync(files.Path.Combine(root, "tree"), token)); + var diagnostic = await Assert.That(missing).IsNotNull(); + using var output = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" }; + + await new MergeGroupReuseRunner(files, output).RunAsync(root, outputFile, token); + + await Assert.That(await files.File.ReadAllTextAsync(outputFile, token)).IsEqualTo($"reuse=false\nreason={MergeGroupReuseFixture.UnreadableFactsReason}\n"); + await Assert.That(output.ToString()).IsEqualTo($"Cannot read reuse facts: {diagnostic.Message}\n{MergeGroupReuseFixture.UnreadableFactsReason}\n"); + } + + [Test] + public async Task RunAsync_Should_Report_The_Write_Error_And_Reason_When_Output_Is_Unwritable(CancellationToken token) + { + var files = new MockFileSystem(); + var root = files.Path.Combine(files.Path.GetTempPath(), "facts"); + var outputFile = files.Path.Combine(root, "github-output"); + await new MergeGroupReuseFixture().WriteAsync(files, root, token); + var file = Substitute.For(); + file.ReadAllTextAsync(Arg.Any(), token).Returns(call => files.File.ReadAllTextAsync(call.Arg(), token)); + file.AppendAllTextAsync(outputFile, Arg.Any(), token).Returns(_ => Task.FromException(new IOException("read-only output"))); + var decorated = Substitute.For(); + decorated.File.Returns(file); + decorated.Path.Returns(files.Path); + using var output = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" }; + + await new MergeGroupReuseRunner(decorated, output).RunAsync(root, outputFile, token); + + await Assert.That(output.ToString()).IsEqualTo($"Cannot write reuse decision: read-only output\n{MergeGroupReuseFixture.ApprovedReason}\n"); + await Assert.That(files.File.Exists(outputFile)).IsFalse(); + } + + [Test] + public async Task RunAsync_Should_Propagate_Cancellation_While_Reading_Facts(CancellationToken token) + { + var files = new MockFileSystem(); + var root = files.Path.Combine(files.Path.GetTempPath(), "facts"); + var outputFile = files.Path.Combine(root, "github-output"); + await new MergeGroupReuseFixture().WriteAsync(files, root, token); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + using var output = new StringWriter(CultureInfo.InvariantCulture); + var runner = new MergeGroupReuseRunner(files, output); + + await Assert.That(() => runner.RunAsync(root, outputFile, cancelled.Token)).Throws(); + await Assert.That(output.ToString()).IsEmpty(); + await Assert.That(files.File.Exists(outputFile)).IsFalse(); + } +} diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.MergeGroupReuse.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.MergeGroupReuse.cs new file mode 100644 index 0000000..e3c03b3 --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.MergeGroupReuse.cs @@ -0,0 +1,50 @@ +using System.Globalization; +using OpenCode.Mcp.Tools.Native; +using OpenCode.Mcp.Tools.Tests.Native.Support; +using OpenCode.Mcp.Tools.Tests.Support; +using Testably.Abstractions.Testing; + +namespace OpenCode.Mcp.Tools.Tests.Native; + +public sealed partial class NativeApplicationTests +{ + [Test] + [Arguments(false, "true", MergeGroupReuseFixture.ApprovedReason)] + [Arguments(true, "false", MergeGroupReuseFixture.UnreadableFactsReason)] + public async Task RunAsync_Should_Report_Merge_Group_Reuse_Without_A_Native_Manifest(bool missingTree, string reuse, string reason, CancellationToken token) + { + var files = new MockFileSystem(); + var root = files.Path.Combine(files.Path.GetTempPath(), "checkout"); + var facts = files.Path.Combine(root, "facts folder"); + var outputFile = files.Path.Combine(root, "github output"); + var fixture = new MergeGroupReuseFixture(); + if (missingTree) + { + fixture.WithoutTree(); + } + await fixture.WriteAsync(files, facts, token); + await files.File.WriteAllTextAsync(outputFile, "existing=value\n", token); + using var output = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" }; + using var errors = new StringWriter(CultureInfo.InvariantCulture); + var host = new NativeHost("fixture", "fixture", "fixture", "fixture", new Dictionary(StringComparer.Ordinal)) { WorkingDirectory = root }; + var runner = new FakeNativeProcessRunner(); + var application = new NativeApplication(files, runner, new FixtureHostReader(host), new FileUnixModes(files), output, errors); + + var result = await application.RunAsync(["merge-group-reuse", "--facts", "facts folder", "--output", "github output"], token); + + await Assert.That(result).IsEqualTo(0); + await Assert.That(await files.File.ReadAllTextAsync(outputFile, token)).IsEqualTo($"existing=value\nreuse={reuse}\nreason={reason}\n"); + if (missingTree) + { + var missing = await Assert.ThrowsAsync(() => files.File.ReadAllTextAsync(files.Path.Combine(facts, "tree"), token)); + var diagnostic = await Assert.That(missing).IsNotNull(); + await Assert.That(output.ToString()).IsEqualTo($"Cannot read reuse facts: {diagnostic.Message}\n{reason}\n"); + } + else + { + await Assert.That(output.ToString()).IsEqualTo(reason + "\n"); + } + await Assert.That(errors.ToString()).IsEmpty(); + await Assert.That(runner.Calls).IsEmpty(); + } +} diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs index cf69b40..0578d51 100644 --- a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs @@ -86,7 +86,34 @@ await Assert.That(() => NativeArguments.Parse(["pack-child"])) await Assert.That(() => NativeArguments.Parse(["pack-child", "--rid", "win-x64"])) .ThrowsExactly().WithMessage("Arguments: missing --evidence.", StringComparison.Ordinal); await Assert.That(() => NativeArguments.Parse([])).ThrowsExactly() - .WithMessage("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication or snapshot.", StringComparison.Ordinal); + .WithMessage("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication, snapshot or merge-group-reuse.", StringComparison.Ordinal); + } + + [Test] + public async Task Parse_Should_Preserve_Merge_Group_Reuse_Paths() + { + NativeCommand? command = null; + await Assert.That(() => command = NativeArguments.Parse(["merge-group-reuse", "--output", "github output", "--facts", "facts folder"])).ThrowsNothing(); + await Assert.That(command).IsEqualTo(new NativeCommand("merge-group-reuse", null, "github output", null, null, null, Facts: "facts folder")); + } + + [Test] + public async Task Parse_Should_Refuse_Invalid_Merge_Group_Reuse_Options() + { + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--output", "out"])) + .ThrowsExactly().WithMessage("Arguments: missing --facts.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--facts", "facts"])) + .ThrowsExactly().WithMessage("Arguments: missing --output.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--facts", "--output", "out"])) + .ThrowsExactly().WithMessage("Arguments: missing value for --facts.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--facts", "facts", "--output"])) + .ThrowsExactly().WithMessage("Arguments: missing value for --output.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--facts", "one", "--facts", "two"])) + .ThrowsExactly().WithMessage("Arguments: duplicate --facts.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--output", "one", "--output", "two"])) + .ThrowsExactly().WithMessage("Arguments: duplicate --output.", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["merge-group-reuse", "--manifest", "manifest"])) + .ThrowsExactly().WithMessage("Arguments: unknown option --manifest for merge-group-reuse.", StringComparison.Ordinal); } [Test] diff --git a/tests/OpenCode.Mcp.Tools.Tests/Support/MergeGroupReuseFixture.cs b/tests/OpenCode.Mcp.Tools.Tests/Support/MergeGroupReuseFixture.cs new file mode 100644 index 0000000..f35148a --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Support/MergeGroupReuseFixture.cs @@ -0,0 +1,149 @@ +using System.IO.Abstractions; +using System.Text.Json; + +namespace OpenCode.Mcp.Tools.Tests.Support; + +internal sealed class MergeGroupReuseFixture +{ + public const string ApprovedReason = "all rules hold"; + public const string InvalidGroupReason = "rule 1: invalid group"; + public const string ChangedPullRequestReason = "rule 2: PR changed"; + public const string NoGreenResultReason = "rule 3: no green latest CI result"; + public const string UnprovenTreeReason = "rule 4: unproven tree"; + public const string GuardedPathReason = "rule 5: guarded path"; + public const string MalformedFactsReason = "malformed facts"; + public const string UnreadableFactsReason = "unreadable facts"; + + private const string Head = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string Base = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + private const string Tree = "cccccccccccccccccccccccccccccccccccccccc"; + private const string BaseTree = "dddddddddddddddddddddddddddddddddddddddd"; + private const string Workflow = ".github/workflows/ci.yml"; + private const string ArtifactName = "tested-tree-2"; + private const string Latest = "2026-11-20T08:00:00Z"; + private const string Started = "2026-11-20T08:01:00Z"; + private const string Uploaded = "2026-11-20T08:02:00Z"; + private const string Completed = "2026-11-20T08:03:00Z"; + + private readonly Dictionary facts = new(StringComparer.Ordinal) + { + ["queue-ref"] = "refs/heads/gh-readonly-queue/master/pr-42-" + Base + "\n", + ["parent-count"] = "2\n", + ["head"] = Head + "\n", + ["base"] = Base + "\n", + ["tree"] = Tree + "\n", + ["base-tree"] = BaseTree + "\n", + ["tested-tree"] = Tree + "\n" + BaseTree + "\n", + ["changed-paths"] = "src/ordinary.cs\0doc/readme.md\0", + ["pr.json"] = PullRequest(Head), + ["runs.json"] = Runs(Run(109, "2026-11-19T08:00:00Z"), Run(100, Latest), Run(101, Latest)), + ["jobs.json"] = Jobs(Job("CI result"), Job("Changes")), + ["artifacts.json"] = Artifacts(Artifact()), + }; + + public IReadOnlyDictionary Facts => facts; + + public MergeGroupReuseFixture WithRow(string row) + { + if (row == "all") + { + return this; + } + if (row is "non-hash-tree" or "non-hash-base-tree") + { + var tree = row == "non-hash-tree" ? "not-a-hash" : Tree; + var baseTree = row == "non-hash-base-tree" ? "not-a-hash" : BaseTree; + facts["tree"] = tree; + facts["base-tree"] = baseTree; + facts["tested-tree"] = tree + "\n" + baseTree + "\n"; + return this; + } + var change = row switch + { + "one-parent" => ("parent-count", "1"), + "invalid-queue-ref" => ("queue-ref", "refs/heads/gh-readonly-queue/main/pr-42-base"), + "invalid-pr-number" => ("queue-ref", "refs/heads/gh-readonly-queue/master/pr-0-base"), + "non-pr-queue-ref" => ("queue-ref", "refs/heads/gh-readonly-queue/master/rq-42-deadbeef"), + "invalid-head" => ("head", Head[..39]), + "invalid-base" => ("base", "g" + Base[1..]), + "moved-head" => ("pr.json", PullRequest(Base)), + "feature-base" => ("pr.json", PullRequest(Head, branch: "feature")), + "different-pr" => ("pr.json", PullRequest(Head, number: 43)), + "no-run" => ("runs.json", Runs()), + "failed-attempt" => ("runs.json", Runs(Run(101, Latest, conclusion: "failure"))), + "running-attempt" => ("runs.json", Runs(Run(101, Latest, status: "in_progress", conclusion: null))), + "invalid-attempt" => ("runs.json", Runs(Run(101, Latest, attempt: 0))), + "newer-failed-run" => ("runs.json", Runs(Run(101, Latest), Run(102, Latest, conclusion: "failure"))), + "other-workflow" => ("runs.json", Runs(Run(101, Latest, path: ".github/workflows/other.yml"))), + "other-event" => ("runs.json", Runs(Run(101, Latest, eventName: "push"))), + "other-run-head" => ("runs.json", Runs(Run(101, Latest, head: Base))), + "failed-result" => ("jobs.json", Jobs(Job("CI result", conclusion: "failure"), Job("Changes"))), + "old-result" => ("jobs.json", Jobs(Job("CI result", attempt: 1), Job("Changes"))), + "other-run-result" => ("jobs.json", Jobs(Job("CI result", runId: 100), Job("Changes"))), + "duplicate-result" => ("jobs.json", Jobs(Job("CI result"), Job("CI result"), Job("Changes"))), + "no-artifact" => ("artifacts.json", Artifacts()), + "old-artifact" => ("artifacts.json", Artifacts(Artifact(name: "tested-tree-1"))), + "different-tree" => ("tree", Base), + "different-base-tree" => ("base-tree", Base), + "missing-base-tree" => ("tested-tree", Tree + "\n"), + "extra-tested-tree-line" => ("tested-tree", Tree + "\n" + BaseTree + "\n" + Base + "\n"), + "blank-tested-tree-line" => ("tested-tree", Tree + "\n\n" + BaseTree + "\n"), + "extra-tested-tree-newline" => ("tested-tree", Tree + "\n" + BaseTree + "\n\n"), + "crlf-tested-tree" => ("tested-tree", Tree + "\r\n" + BaseTree + "\r\n"), + "empty-base-tree" => ("base-tree", ""), + "replacement-after" => ("artifacts.json", Artifacts(Artifact(created: "2026-11-20T08:04:00Z"))), + "replacement-before" => ("artifacts.json", Artifacts(Artifact(created: Latest))), + "artifact-at-start" => ("artifacts.json", Artifacts(Artifact(created: Started))), + "artifact-at-end" => ("artifacts.json", Artifacts(Artifact(created: Completed))), + "duplicate-artifact" => ("artifacts.json", Artifacts(Artifact(), Artifact())), + "expired-artifact" => ("artifacts.json", Artifacts(Artifact(expired: true))), + "failed-changes" => ("jobs.json", Jobs(Job("CI result"), Job("Changes", conclusion: "failure"))), + "malformed" => ("pr.json", "{"), + "wrong-json-type" => ("artifacts.json", Artifacts(new { name = ArtifactName, expired = "no", created_at = Uploaded })), + "null-run-time" => ("runs.json", Runs(Run(101, null))), + _ => throw new ArgumentOutOfRangeException(nameof(row), row, "Unknown reuse fact row."), + }; + facts[change.Item1] = change.Item2; + return this; + } + + public MergeGroupReuseFixture WithChangedPath(string path) + { + facts["changed-paths"] += path + "\0"; + return this; + } + + public MergeGroupReuseFixture WithoutTree() + { + _ = facts.Remove("tree"); + return this; + } + + public async Task WriteAsync(IFileSystem files, string directory, CancellationToken token) + { + _ = files.Directory.CreateDirectory(directory); + foreach (var (name, content) in facts) + { + await files.File.WriteAllTextAsync(files.Path.Combine(directory, name), content, token).ConfigureAwait(false); + } + } + + private static string PullRequest(string head, string branch = "master", long number = 42) => + JsonSerializer.Serialize(new { number, head = new { sha = head }, @base = new { @ref = branch } }); + + private static string Runs(params object[] runs) => JsonSerializer.Serialize(new { workflow_runs = runs }); + + private static object Run(long id, string? created, string status = "completed", string? conclusion = "success", + string path = Workflow, long attempt = 2, string eventName = "pull_request", string head = Head) => + new { id, path, @event = eventName, head_sha = head, created_at = created, status, conclusion, run_attempt = attempt }; + + private static string Jobs(params object[] jobs) => JsonSerializer.Serialize(new { jobs }); + + private static object Job(string name, string conclusion = "success", long attempt = 2, long runId = 101) => + new { name, conclusion, run_id = runId, run_attempt = attempt, started_at = Started, completed_at = Completed }; + + private static string Artifacts(params object[] artifacts) => JsonSerializer.Serialize(new { artifacts }); + + private static object Artifact(string name = ArtifactName, string created = Uploaded, bool expired = false) => + new { name, expired, created_at = created }; +} diff --git a/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseDecision.cs b/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseDecision.cs new file mode 100644 index 0000000..6668920 --- /dev/null +++ b/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseDecision.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using System.Text.Json; + +namespace OpenCode.Mcp.Tools.Ci; + +internal static class MergeGroupReuseDecision +{ + internal const string ApprovedReason = "all rules hold"; + + public static string Reason(IReadOnlyDictionary facts) + { + try + { + var head = facts["head"].Trim(); + if (!TryGetGroupNumber(facts, head, out var prNumber)) + { + return "rule 1: invalid group"; + } + using var pr = JsonDocument.Parse(facts["pr.json"]); + var pull = pr.RootElement; + if (pull.GetProperty("number").GetInt64() != prNumber || !pull.GetProperty("head").GetProperty("sha").ValueEquals(head) + || !pull.GetProperty("base").GetProperty("ref").ValueEquals("master")) + { + return "rule 2: PR changed"; + } + using var runs = JsonDocument.Parse(facts["runs.json"]); + var latest = LatestRun(runs.RootElement, head); + if (latest.ValueKind == JsonValueKind.Undefined || !latest.GetProperty("status").ValueEquals("completed") + || !latest.GetProperty("conclusion").ValueEquals("success") || latest.GetProperty("run_attempt").GetInt64() < 1) + { + return "rule 3: no green latest CI result"; + } + var attempt = latest.GetProperty("run_attempt").GetInt64(); + var id = latest.GetProperty("id").GetInt64(); + using var jobs = JsonDocument.Parse(facts["jobs.json"]); + var attemptJobs = jobs.RootElement.GetProperty("jobs").EnumerateArray() + .Where(job => job.GetProperty("run_id").GetInt64() == id && job.GetProperty("run_attempt").GetInt64() == attempt) + .ToArray(); + if (SuccessfulJob(attemptJobs, "CI result").ValueKind == JsonValueKind.Undefined) + { + return "rule 3: no green latest CI result"; + } + if (!HasArtifact(facts["artifacts.json"], attempt, SuccessfulJob(attemptJobs, "Changes")) || !TreesMatch(facts)) + { + return "rule 4: unproven tree"; + } + return facts["changed-paths"].Split('\0', StringSplitOptions.RemoveEmptyEntries).Any(IsGuarded) + ? "rule 5: guarded path" + : ApprovedReason; + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or OverflowException) + { + return "malformed facts"; + } + } + + private static bool TryGetGroupNumber(IReadOnlyDictionary facts, string head, out long number) + { + number = 0; + var queue = facts["queue-ref"].Trim().Split('/'); + return facts["parent-count"].Trim() == "2" && queue.Length == 5 + && string.Join('/', queue[..4]) == "refs/heads/gh-readonly-queue/master" + && queue[4].StartsWith("pr-", StringComparison.Ordinal) + && long.TryParse(queue[4].Split('-').ElementAtOrDefault(1), CultureInfo.InvariantCulture, out number) + && number > 0 && IsHash(head) && IsHash(facts["base"].Trim()); + } + + private static JsonElement LatestRun(JsonElement runs, string head) => runs.GetProperty("workflow_runs").EnumerateArray() + .Where(run => run.GetProperty("path").ValueEquals(".github/workflows/ci.yml") + && run.GetProperty("event").ValueEquals("pull_request") && run.GetProperty("head_sha").ValueEquals(head)) + .OrderByDescending(static run => Date(run, "created_at")) + .ThenByDescending(static run => run.GetProperty("id").GetInt64()) + .FirstOrDefault(); + + private static JsonElement SuccessfulJob(IEnumerable jobs, string name) + { + var matches = jobs.Where(job => job.GetProperty("name").ValueEquals(name)).ToArray(); + return matches.Length == 1 && matches[0].GetProperty("conclusion").ValueEquals("success") ? matches[0] : default; + } + + private static bool HasArtifact(string json, long attempt, JsonElement changes) + { + using var artifacts = JsonDocument.Parse(json); + var name = "tested-tree-" + attempt.ToString(CultureInfo.InvariantCulture); + var matches = artifacts.RootElement.GetProperty("artifacts").EnumerateArray() + .Where(artifact => artifact.GetProperty("name").ValueEquals(name)).ToArray(); + if (matches.Length != 1 || matches[0].GetProperty("expired").GetBoolean() || changes.ValueKind == JsonValueKind.Undefined) + { + return false; + } + var created = Date(matches[0], "created_at"); + return created >= Date(changes, "started_at") && created <= Date(changes, "completed_at"); + } + + private static bool TreesMatch(IReadOnlyDictionary facts) + { + var testedTree = facts["tested-tree"]; + var testedTrees = (testedTree.EndsWith('\n') ? testedTree[..^1] : testedTree).Split('\n', StringSplitOptions.TrimEntries); + var tree = facts["tree"].Trim(); + var baseTree = facts["base-tree"].Trim(); + return testedTrees.Length == 2 && IsHash(tree) && tree == testedTrees[0] && IsHash(baseTree) && baseTree == testedTrees[1]; + } + + private static bool IsHash(string value) => value.Length == 40 && value.All(char.IsAsciiHexDigit); + + private static DateTimeOffset Date(JsonElement value, string field) => + DateTimeOffset.Parse(value.GetProperty(field).GetString() ?? throw new FormatException("Missing timestamp."), CultureInfo.InvariantCulture); + + private static bool IsGuarded(string path) + { + var leaf = path.Split('/')[^1]; + // Keep these guarded paths in sync with the reuse guard in .github/workflows/ci.yml. + return path.StartsWith(".github/", StringComparison.OrdinalIgnoreCase) || path.StartsWith("tools/", StringComparison.OrdinalIgnoreCase) + || leaf.StartsWith("Directory.Build.", StringComparison.OrdinalIgnoreCase) + || string.Equals(leaf, "Directory.Packages.props", StringComparison.OrdinalIgnoreCase) + || string.Equals(leaf, "global.json", StringComparison.OrdinalIgnoreCase) + || string.Equals(leaf, "nuget.config", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseRunner.cs b/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseRunner.cs new file mode 100644 index 0000000..7f69f7a --- /dev/null +++ b/tools/OpenCode.Mcp.Tools/Ci/MergeGroupReuseRunner.cs @@ -0,0 +1,41 @@ +using System.IO.Abstractions; + +namespace OpenCode.Mcp.Tools.Ci; + +internal sealed class MergeGroupReuseRunner(IFileSystem files, TextWriter output) +{ + public async Task RunAsync(string factsDirectory, string outputFile, CancellationToken token) + { + var facts = await ReadFactsAsync(factsDirectory, token).ConfigureAwait(false); + var reason = facts is null ? "unreadable facts" : MergeGroupReuseDecision.Reason(facts); + try + { + var reuse = reason == MergeGroupReuseDecision.ApprovedReason ? "true" : "false"; + await files.File.AppendAllTextAsync(outputFile, $"reuse={reuse}\nreason={reason}\n", token).ConfigureAwait(false); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException) + { + await output.WriteLineAsync($"Cannot write reuse decision: {exception.Message}".AsMemory(), token).ConfigureAwait(false); + } + await output.WriteLineAsync(reason.AsMemory(), token).ConfigureAwait(false); + } + + private async Task?> ReadFactsAsync(string factsDirectory, CancellationToken token) + { + string[] names = ["queue-ref", "parent-count", "head", "base", "base-tree", "tree", "tested-tree", "changed-paths", "pr.json", "runs.json", "jobs.json", "artifacts.json"]; + var facts = new Dictionary(StringComparer.Ordinal); + try + { + foreach (var name in names) + { + facts.Add(name, await files.File.ReadAllTextAsync(files.Path.Combine(factsDirectory, name), token).ConfigureAwait(false)); + } + return facts; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException) + { + await output.WriteLineAsync($"Cannot read reuse facts: {exception.Message}".AsMemory(), token).ConfigureAwait(false); + return null; + } + } +} diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs b/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs index 7383f79..ec7f8b2 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs @@ -2,6 +2,7 @@ using System.IO.Abstractions; using System.Text.Json; using System.Xml; +using OpenCode.Mcp.Tools.Ci; using OpenCode.Mcp.Tools.Native.Abstractions; using OpenCode.Mcp.Tools.Packaging; @@ -22,6 +23,13 @@ public async Task RunAsync(IReadOnlyList arguments, CancellationTok files.Path.GetFullPath(command.Output ?? throw new InvalidOperationException("Missing snapshot output."), root), (clock ?? TimeProvider.System).GetUtcNow, token).ConfigureAwait(false); return 0; } + if (command.Operation == "merge-group-reuse") + { + var facts = files.Path.GetFullPath(command.Facts ?? throw new InvalidOperationException("Missing reuse facts directory."), root); + var outputFile = files.Path.GetFullPath(command.Output ?? throw new InvalidOperationException("Missing reuse output."), root); + await new MergeGroupReuseRunner(files, output).RunAsync(facts, outputFile, token).ConfigureAwait(false); + return 0; + } var manifest = await new NativeManifestStore(files).ReadAsync(files.Path.GetFullPath(command.Manifest, root), token).ConfigureAwait(false); if (command.Operation == "matrix") { @@ -56,12 +64,7 @@ public async Task RunAsync(IReadOnlyList arguments, CancellationTok NativeDiagnostics.Refuse(NativePublishPolicy.HostDiagnostics(rid, host.Os, host.OsArchitecture, host.ProcessArchitecture)); if (command.Operation == "inspect") { - var processes = new NativeProcesses(runner, root); - var toolchain = await new NativePrerequisites(files, processes).CheckAsync(rid, host, token).ConfigureAwait(false); - var inspection = await new NativeInspector(files, processes).InspectAsync(rid, - files.Path.GetFullPath(command.Path ?? throw new InvalidOperationException("Missing inspection path."), root), toolchain, token).ConfigureAwait(false); - await output.WriteLineAsync(inspection.AsMemory(), token).ConfigureAwait(false); - return 0; + return await InspectAsync(command, rid, host, token).ConfigureAwait(false); } var publishDirectory = command.PublishDirectory is null ? null : files.Path.GetFullPath(command.PublishDirectory, root); var destination = publishDirectory is null ? files.Path.GetFullPath(command.Evidence ?? command.Output ?? files.Path.Combine("artifacts", "native", rid), root) @@ -90,6 +93,16 @@ public async Task RunAsync(IReadOnlyList arguments, CancellationTok } } + private async Task InspectAsync(NativeCommand command, string rid, NativeHost host, CancellationToken token) + { + var processes = new NativeProcesses(runner, host.WorkingDirectory); + var toolchain = await new NativePrerequisites(files, processes).CheckAsync(rid, host, token).ConfigureAwait(false); + var inspection = await new NativeInspector(files, processes).InspectAsync(rid, + files.Path.GetFullPath(command.Path ?? throw new InvalidOperationException("Missing inspection path."), host.WorkingDirectory), toolchain, token).ConfigureAwait(false); + await output.WriteLineAsync(inspection.AsMemory(), token).ConfigureAwait(false); + return 0; + } + private async Task RunBuildAsync(string operation, NativeBuildRequest request, string? publishDirectory, CancellationToken token) { if (operation == "pack-child") diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs b/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs index 1c05af1..5427aaa 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs @@ -6,7 +6,7 @@ public static NativeCommand Parse(IReadOnlyList arguments) { if (arguments.Count == 0) { - throw new InvalidOperationException("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication or snapshot."); + throw new InvalidOperationException("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication, snapshot or merge-group-reuse."); } var operation = arguments[0]; string[] required = operation switch @@ -23,6 +23,7 @@ public static NativeCommand Parse(IReadOnlyList arguments) "assets" => ["--receipts", "--evidence", "--output", "--version"], "publication" => ["--receipts", "--feed", "--assets", "--version", "--commit"], "snapshot" => ["--output"], + "merge-group-reuse" => ["--facts", "--output"], _ => throw new InvalidOperationException("Arguments: unknown command " + operation + "."), }; var values = new Dictionary(StringComparer.Ordinal); @@ -51,7 +52,8 @@ public static NativeCommand Parse(IReadOnlyList arguments) var command = new NativeCommand(operation, values.GetValueOrDefault("--rid"), values.GetValueOrDefault("--output"), values.GetValueOrDefault("--publish-directory"), values.GetValueOrDefault("--path"), values.GetValueOrDefault("--receipts"), GithubOutput: values.GetValueOrDefault("--github-output"), Evidence: values.GetValueOrDefault("--evidence"), Feed: values.GetValueOrDefault("--feed"), - Version: values.GetValueOrDefault("--version"), Assets: values.GetValueOrDefault("--assets"), Commit: values.GetValueOrDefault("--commit")); + Version: values.GetValueOrDefault("--version"), Assets: values.GetValueOrDefault("--assets"), Commit: values.GetValueOrDefault("--commit"), + Facts: values.GetValueOrDefault("--facts")); return values.TryGetValue("--manifest", out var manifest) ? command with { Manifest = manifest } : command; } } diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs b/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs index a802228..85da4ec 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs @@ -2,4 +2,4 @@ namespace OpenCode.Mcp.Tools.Native; internal sealed record NativeCommand(string Operation, string? Rid, string? Output, string? PublishDirectory, string? Path, string? Receipts, string Manifest = "packaging/native-manifest.json", string? GithubOutput = null, string? Evidence = null, string? Feed = null, string? Version = null, - string? Assets = null, string? Commit = null); + string? Assets = null, string? Commit = null, string? Facts = null);