From 00d5235020fdf09e70f1a3f62773f06b955170a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sat, 14 Nov 2026 16:48:41 +0300 Subject: [PATCH 1/5] feat: add verified candidate publication lane Collect the complete feed-stage diagnostics before refusing publication. --- .github/workflows/release.yml | 577 ++++++++++++++++++ docs/architecture/hosting-and-packaging.md | 8 + docs/engineering/quality-gates.md | 21 + docs/engineering/workflow.md | 25 +- .../NativeApplicationTests.Publication.cs | 38 ++ .../Native/NativeArgumentsTests.cs | 28 +- .../Native/NativePublicationValidatorTests.cs | 130 ++++ .../Support/NativePublicationScenario.cs | 85 +++ .../Native/NativeApplication.cs | 45 +- .../Native/NativeArguments.cs | 5 +- .../Native/NativeCommand.cs | 3 +- .../Native/NativePublicationRequest.cs | 3 + .../Native/NativePublicationValidator.cs | 110 ++++ 13 files changed, 1064 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.Publication.cs create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Native/NativePublicationValidatorTests.cs create mode 100644 tests/OpenCode.Mcp.Tools.Tests/Native/Support/NativePublicationScenario.cs create mode 100644 tools/OpenCode.Mcp.Tools/Native/NativePublicationRequest.cs create mode 100644 tools/OpenCode.Mcp.Tools/Native/NativePublicationValidator.cs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3b64c73 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,577 @@ +name: Release + +on: + workflow_dispatch: + inputs: + target: + description: Exact publication target (dry-run publishes nothing) + required: true + type: choice + options: [github-packages, nuget, github-release, dry-run] + commit: + description: Full candidate commit SHA + required: true + type: string + native-run-id: + description: Successful manual Native candidate run + required: true + type: string + version: + description: Exact committed candidate version + required: true + type: string + files: + description: Feed recovery only; comma-separated candidate package basenames (empty selects all seven) + required: false + type: string + github-packages-verification-run-id: + description: Successful GitHub Packages verification run (required for nuget) + required: false + type: string + nuget-verification-run-id: + description: Successful NuGet verification run (required for github-release) + required: false + type: string + release-notes: + description: Literal approved release notes (required for github-release) + required: false + type: string + +permissions: {} + +concurrency: + group: release + cancel-in-progress: false + +defaults: + run: + shell: pwsh + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: "true" + DOTNET_NOLOGO: "true" + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "true" + +jobs: + preflight: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + actions: read + outputs: + feed: ${{ steps.inventory.outputs.feed }} + assets: ${{ steps.inventory.outputs.assets }} + selected: ${{ steps.absence.outputs.selected }} + sdk-version: ${{ steps.record.outputs.sdk-version }} + steps: + - name: Require master dispatch + env: + DISPATCH_REF: ${{ github.ref }} + run: | + if ($env:DISPATCH_REF -cne 'refs/heads/master') { throw 'Release dispatch must use refs/heads/master.' } + - &checkout + name: Checkout candidate + uses: actions/checkout@v7 + with: + ref: ${{ inputs.commit }} + fetch-depth: 0 + persist-credentials: false + - name: Verify full candidate commit and master ancestry + env: + COMMIT: ${{ inputs.commit }} + run: | + $ErrorActionPreference = 'Stop' + if ($env:COMMIT -cnotmatch '^[0-9a-f]{40}$') { throw 'commit must be a full SHA.' } + $head = git rev-parse HEAD + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($head -cne $env:COMMIT) { throw 'Checkout does not equal the candidate commit.' } + git fetch --no-tags origin +refs/heads/master:refs/remotes/origin/master + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + git merge-base --is-ancestor $env:COMMIT origin/master + if ($LASTEXITCODE -ne 0) { throw 'master does not contain the candidate commit.' } + - name: Verify Native run provenance + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + NATIVE_RUN_ID: ${{ inputs.native-run-id }} + COMMIT: ${{ inputs.commit }} + run: | + $ErrorActionPreference = 'Stop' + if ($env:NATIVE_RUN_ID -notmatch '^[1-9][0-9]*$') { throw 'native-run-id must be a run ID.' } + $workflow = gh api "repos/$env:REPOSITORY/actions/workflows/native.yml" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $run = gh api "repos/$env:REPOSITORY/actions/runs/$env:NATIVE_RUN_ID" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($run.repository.full_name -cne $env:REPOSITORY -or $run.workflow_id -ne $workflow.id -or + $run.name -cne 'Native' -or $run.event -cne 'workflow_dispatch' -or $run.status -cne 'completed' -or + $run.conclusion -cne 'success' -or $run.head_branch -cne 'master' -or $run.head_sha -cne $env:COMMIT) { + throw 'Native run does not identify a successful manual candidate from this repository on master.' + } + - &initialize + name: Initialize owned SDK environment + run: | + "DOTNET_INSTALL_DIR=$(Join-Path $env:RUNNER_TEMP 'dotnet')" >> $env:GITHUB_ENV + "ASPIRE_HOME=$(Join-Path $env:RUNNER_TEMP 'aspire-home')" >> $env:GITHUB_ENV + - &sdk + name: Setup candidate .NET SDK + uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + - name: Verify committed version without an override + env: + VERSION: ${{ inputs.version }} + run: | + $ErrorActionPreference = 'Stop' + $version = dotnet msbuild src/OpenCode.Mcp/OpenCode.Mcp.csproj -p:Configuration=Release -nodeReuse:false -p:UseSharedCompilation=false -getProperty:Version + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($version -isnot [string] -or $version -cne $env:VERSION) { throw 'version differs from the evaluated candidate version.' } + - &tree + name: Refetch master and verify workflow tree + env: + COMMIT: ${{ inputs.commit }} + run: | + $ErrorActionPreference = 'Stop' + git fetch --no-tags origin +refs/heads/master:refs/remotes/origin/master + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $candidate = git rev-parse "$($env:COMMIT):.github/workflows" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $master = git rev-parse 'origin/master:.github/workflows' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($candidate -cne $master) { throw 'Candidate workflow tree differs from the current master tip.' } + - name: Verify promotion run provenance + id: promotion + if: inputs.target == 'nuget' || inputs.target == 'github-release' + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + TARGET: ${{ inputs.target }} + GITHUB_VERIFICATION: ${{ inputs.github-packages-verification-run-id }} + NUGET_VERIFICATION: ${{ inputs.nuget-verification-run-id }} + run: | + $ErrorActionPreference = 'Stop' + $id = if ($env:TARGET -ceq 'nuget') { $env:GITHUB_VERIFICATION } else { $env:NUGET_VERIFICATION } + if ($id -notmatch '^[1-9][0-9]*$') { throw 'The preceding channel verification run ID is required.' } + $workflow = gh api "repos/$env:REPOSITORY/actions/workflows/verify-channel.yml" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $run = gh api "repos/$env:REPOSITORY/actions/runs/$id" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($run.repository.full_name -cne $env:REPOSITORY -or $run.workflow_id -ne $workflow.id -or + $run.event -cne 'workflow_dispatch' -or $run.status -cne 'completed' -or $run.conclusion -cne 'success' -or + $run.head_branch -cne 'master' -or $run.run_attempt -lt 1) { + throw 'Promotion evidence must be a successful manual verify-channel run for the candidate on master.' + } + "run-id=$id" >> $env:GITHUB_OUTPUT + "attempt=$($run.run_attempt)" >> $env:GITHUB_OUTPUT + - name: Download promotion evidence + if: inputs.target == 'nuget' || inputs.target == 'github-release' + uses: actions/download-artifact@v8 + with: + name: channel-verification + path: ${{ runner.temp }}/channel-verification + run-id: ${{ steps.promotion.outputs.run-id }} + github-token: ${{ github.token }} + # channel-verification contains one JSON document. Identity fields are strings: + # channel, version, commit, nativeRunId, verificationRunId; runAttempt is an integer. + # runtimes is manifest-ordered: { rid, runner, tests: { total, passed, failed, + # skipped }, results: [retained Actions artifact URLs] }. Totals are integers. + - name: Validate promotion identity and all manifest results + if: inputs.target == 'nuget' || inputs.target == 'github-release' + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + TARGET: ${{ inputs.target }} + VERSION: ${{ inputs.version }} + COMMIT: ${{ inputs.commit }} + NATIVE_RUN_ID: ${{ inputs.native-run-id }} + VERIFICATION_RUN_ID: ${{ steps.promotion.outputs.run-id }} + VERIFICATION_ATTEMPT: ${{ steps.promotion.outputs.attempt }} + run: | + $ErrorActionPreference = 'Stop' + $files = @(Get-ChildItem -LiteralPath (Join-Path $env:RUNNER_TEMP 'channel-verification') -Force) + if ($files.Count -ne 1 -or $files[0].PSIsContainer -or $files[0].Extension -cne '.json') { throw 'Expected one channel-verification JSON document.' } + $proof = Get-Content -LiteralPath $files[0].FullName -Raw | ConvertFrom-Json + $channel = if ($env:TARGET -ceq 'nuget') { 'github-packages' } else { 'nuget' } + if ($proof.channel -cne $channel -or $proof.version -cne $env:VERSION -or $proof.commit -cne $env:COMMIT -or + $proof.nativeRunId -cne $env:NATIVE_RUN_ID -or $proof.verificationRunId -cne $env:VERIFICATION_RUN_ID -or + $proof.runAttempt -ne [long]$env:VERIFICATION_ATTEMPT) { throw 'Promotion artifact candidate identity differs.' } + $manifest = Get-Content packaging/native-manifest.json -Raw | ConvertFrom-Json + if ($proof.runtimes -isnot [array] -or $proof.runtimes.Count -ne $manifest.runtimes.Count) { throw 'Promotion artifact must cover every manifest host.' } + $pages = gh api --paginate --slurp "repos/$env:REPOSITORY/actions/runs/$env:VERIFICATION_RUN_ID/artifacts?per_page=100" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $links = @($pages.artifacts | Where-Object { -not $_.expired } | ForEach-Object { "https://github.com/$env:REPOSITORY/actions/runs/$env:VERIFICATION_RUN_ID/artifacts/$($_.id)" }) + for ($i = 0; $i -lt $manifest.runtimes.Count; $i++) { + $leg = $proof.runtimes[$i] + $expected = $manifest.runtimes[$i] + if ($leg.rid -cne $expected.rid -or $leg.runner -cne $expected.runner) { throw 'Promotion RID/runner order differs from the manifest.' } + foreach ($field in @('total', 'passed', 'failed', 'skipped')) { + if ($leg.tests.$field -isnot [long] -and $leg.tests.$field -isnot [int]) { throw 'Promotion test totals must be integers.' } + } + if ($leg.tests.passed -le 0 -or $leg.tests.failed -ne 0 -or $leg.tests.skipped -lt 0 -or + $leg.tests.total -ne ($leg.tests.passed + $leg.tests.skipped)) { throw 'Promotion requires successful nonzero per-leg test totals.' } + if ($leg.results -isnot [array] -or $leg.results.Count -eq 0) { throw 'Promotion leg has no retained results.' } + foreach ($link in $leg.results) { + if ($links -cnotcontains $link) { throw 'Promotion result does not link to a retained artifact of the verification run.' } + } + } + - &absence + name: Check selected target absence and recovery prerequisites + id: absence + env: + TARGET: ${{ inputs.target }} + VERSION: ${{ inputs.version }} + FILES: ${{ inputs.files }} + RELEASE_NOTES: ${{ inputs.release-notes }} + REPOSITORY: ${{ github.repository }} + API_TOKEN: ${{ github.token }} + PACKAGES_READ_TOKEN: ${{ secrets.GH_PACKAGES_READ_TOKEN }} + run: | + $ErrorActionPreference = 'Stop' + function Get-Response($url, $token) { + $headers = @{ Accept = 'application/json' } + if ($token) { + $headers.Accept = 'application/vnd.github+json' + $headers.Authorization = "Bearer $token" + $headers['X-GitHub-Api-Version'] = '2022-11-28' + } + return Invoke-WebRequest -Uri $url -Headers $headers -SkipHttpErrorCheck + } + function Read-GitHub($response) { + $value = ConvertFrom-Json -InputObject $response.Content -NoEnumerate + if ($response.StatusCode -eq 404 -and $value.message -ceq 'Not Found') { return $null } + if ($response.StatusCode -ne 200) { throw "GitHub metadata request failed: HTTP $($response.StatusCode)." } + if ($null -eq $value) { throw 'Malformed GitHub metadata response.' } + return ,$value + } + function Test-GitHubVersion($id) { + $encoded = [Uri]::EscapeDataString($id) + for ($page = 1; ; $page++) { + $response = Get-Response "https://api.github.com/orgs/opencode-dotnet/packages/nuget/$encoded/versions?per_page=100&page=$page" $env:PACKAGES_READ_TOKEN + $versions = Read-GitHub $response + if ($null -eq $versions) { return $false } + if ($versions -isnot [array]) { throw 'Malformed GitHub package-version response.' } + foreach ($version in $versions) { + if ($version.name -isnot [string] -or [string]::IsNullOrEmpty($version.name)) { throw 'Malformed GitHub package version.' } + if ($version.name -ceq $env:VERSION) { return $true } + } + if ($versions.Count -lt 100) { return $false } + } + } + function Test-NuGetVersion($id) { + $response = Get-Response "https://api.nuget.org/v3-flatcontainer/$($id.ToLowerInvariant())/index.json" '' + if ($response.StatusCode -eq 404) { return $false } + if ($response.StatusCode -ne 200) { throw "NuGet metadata request failed: HTTP $($response.StatusCode)." } + $value = $response.Content | ConvertFrom-Json + if ($value.versions -isnot [array] -or @($value.versions | Where-Object { $_ -isnot [string] }).Count) { throw 'Malformed NuGet version response.' } + return $value.versions -ccontains $env:VERSION.ToLowerInvariant() + } + $manifest = Get-Content packaging/native-manifest.json -Raw | ConvertFrom-Json + $ids = @($manifest.runtimes | ForEach-Object { "OpenCodeDotNet.Mcp.$($_.rid)" }) + @('OpenCodeDotNet.Mcp') + $names = @($ids | ForEach-Object { "$($_).$env:VERSION.nupkg" }) + $selection = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + if ([string]::IsNullOrEmpty($env:FILES)) { + foreach ($name in $names) { [void]$selection.Add($name) } + } else { + if ($env:TARGET -ceq 'github-release') { throw 'files recovers feed pushes only; draft release recovery is not supported.' } + foreach ($item in $env:FILES.Split(',')) { + $name = $item.Trim() + if ($names -cnotcontains $name -or -not $selection.Add($name)) { throw "Unknown or duplicate candidate package basename: $name" } + } + } + $selected = @($names | Where-Object { $selection.Contains($_) }) + "selected=$(ConvertTo-Json -InputObject $selected -Compress)" >> $env:GITHUB_OUTPUT + if ($env:TARGET -in @('github-packages', 'dry-run')) { + if ([string]::IsNullOrWhiteSpace($env:PACKAGES_READ_TOKEN)) { throw 'GH_PACKAGES_READ_TOKEN is required for GitHub Packages metadata.' } + $user = Read-GitHub (Get-Response 'https://api.github.com/user' $env:PACKAGES_READ_TOKEN) + if ([string]::IsNullOrEmpty($user.login)) { throw 'GitHub Packages read-token authentication failed.' } + } + foreach ($feed in @('github-packages', 'nuget') | Where-Object { $env:TARGET -ceq $_ -or $env:TARGET -ceq 'dry-run' }) { + $present = @() + $missing = @() + for ($i = 0; $i -lt $ids.Count; $i++) { + $exists = if ($feed -ceq 'github-packages') { Test-GitHubVersion $ids[$i] } else { Test-NuGetVersion $ids[$i] } + if ($exists) { $present += $names[$i] } else { $missing += $names[$i] } + } + Write-Output "$feed present: $($present -join ', ')" + Write-Output "$feed missing: $($missing -join ', ')" + if (@($selected | Where-Object { $present -ccontains $_ }).Count) { throw "$feed already contains a selected version." } + $root = $names[-1] + if ($selection.Contains($root)) { + $unselectedChildren = @($names[0..($names.Count - 2)] | Where-Object { -not $selection.Contains($_) }) + if (@($unselectedChildren | Where-Object { $present -cnotcontains $_ }).Count) { throw "$feed recovery cannot push the root while an unselected child is absent." } + } + } + if ($env:TARGET -in @('github-release', 'dry-run')) { + if ($env:TARGET -ceq 'github-release' -and [string]::IsNullOrWhiteSpace($env:RELEASE_NOTES)) { throw 'Literal approved release-notes are required.' } + $tag = "v$env:VERSION" + for ($page = 1; ; $page++) { + $releases = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/releases?per_page=100&page=$page" $env:API_TOKEN) + if ($releases -isnot [array]) { throw 'Malformed release-list response.' } + foreach ($release in $releases) { + if ($release.tag_name -isnot [string]) { throw 'Malformed release identity.' } + if ($release.tag_name -ceq $tag) { throw 'The release identity already exists, including drafts.' } + } + if ($releases.Count -lt 100) { break } + } + $encodedTag = [Uri]::EscapeDataString($tag) + $ref = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/git/ref/tags/$encodedTag" $env:API_TOKEN) + if ($null -ne $ref) { throw 'The release tag already exists.' } + } + - &feed-download + name: Download original candidate feed + uses: actions/download-artifact@v8 + with: + name: native-package-feed + path: artifacts/feed + run-id: ${{ inputs.native-run-id }} + github-token: ${{ github.token }} + - &assets-download + name: Download original candidate release assets + uses: actions/download-artifact@v8 + with: + name: native-release-assets + path: artifacts/release-assets + run-id: ${{ inputs.native-run-id }} + github-token: ${{ github.token }} + - name: Download completed candidate evidence + uses: actions/download-artifact@v8 + with: + pattern: native-complete-* + path: artifacts/native-receipts + merge-multiple: false + run-id: ${{ inputs.native-run-id }} + github-token: ${{ github.token }} + - name: Build managed native tool entry only + run: | + dotnet build tools/native.cs + exit $LASTEXITCODE + - name: Validate publication candidate bytes + env: + VERSION: ${{ inputs.version }} + COMMIT: ${{ inputs.commit }} + run: | + dotnet run --no-build tools/native.cs -- publication --receipts artifacts/native-receipts --feed artifacts/feed --assets artifacts/release-assets --version $env:VERSION --commit $env:COMMIT + exit $LASTEXITCODE + - name: Record validated inventories and digests + id: inventory + run: &inventory-code | + $ErrorActionPreference = 'Stop' + foreach ($kind in @('feed', 'assets')) { + $root = (Resolve-Path $(if ($kind -ceq 'feed') { 'artifacts/feed' } else { 'artifacts/release-assets' })).Path + [string[]]$paths = @(Get-ChildItem -LiteralPath $root -Recurse -Force -File | ForEach-Object { [IO.Path]::GetRelativePath($root, $_.FullName).Replace('\', '/') }) + [Array]::Sort($paths, [StringComparer]::Ordinal) + $entries = @($paths | ForEach-Object { + $file = Get-Item -LiteralPath (Join-Path $root $_) + [ordered]@{ path = $_; size = $file.Length; sha256 = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() } + }) + [string[]]$directories = @(Get-ChildItem -LiteralPath $root -Recurse -Force -Directory | ForEach-Object { [IO.Path]::GetRelativePath($root, $_.FullName).Replace('\', '/') }) + [Array]::Sort($directories, [StringComparer]::Ordinal) + $json = ConvertTo-Json -InputObject ([ordered]@{ files = $entries; directories = $directories }) -Depth 6 -Compress + $expected = if ($kind -ceq 'feed') { $env:EXPECTED_FEED } else { $env:EXPECTED_ASSETS } + if ($env:GITHUB_JOB -cne 'preflight' -and [string]::IsNullOrEmpty($expected)) { throw 'Validated preflight inventory is required.' } + if ($expected -and $json -cne $expected) { throw "$kind differs from the validated preflight file set or digests." } + "$kind=$json" >> $env:GITHUB_OUTPUT + Write-Output "$kind candidate inventory: $json" + "$kind candidate inventory: $json" >> $env:GITHUB_STEP_SUMMARY + } + - name: Record candidate identity SDK and canonical push selection + id: record + env: + COMMIT: ${{ inputs.commit }} + NATIVE_RUN_ID: ${{ inputs.native-run-id }} + VERSION: ${{ inputs.version }} + SELECTED: ${{ steps.absence.outputs.selected }} + run: | + $ErrorActionPreference = 'Stop' + $manifest = Get-Content packaging/native-manifest.json -Raw | ConvertFrom-Json + $receipt = Get-Content "artifacts/native-receipts/native-complete-$($manifest.runtimes[0].rid)/receipt.json" -Raw | ConvertFrom-Json + "sdk-version=$($receipt.sdkVersion)" >> $env:GITHUB_OUTPUT + $record = "Candidate commit=$env:COMMIT Native-run=$env:NATIVE_RUN_ID version=$env:VERSION receipt-SDK=$($receipt.sdkVersion) selected-child-first-root-last=$env:SELECTED" + Write-Output $record + $record >> $env:GITHUB_STEP_SUMMARY + + github-packages: + if: inputs.target == 'github-packages' + needs: preflight + runs-on: ubuntu-24.04 + timeout-minutes: 30 + environment: release + permissions: + contents: read + actions: read + packages: write + steps: + - *checkout + - *initialize + - *sdk + - *feed-download + - *assets-download + - &compare + name: Require exact preflight inventories and digests + env: + EXPECTED_FEED: ${{ needs.preflight.outputs.feed }} + EXPECTED_ASSETS: ${{ needs.preflight.outputs.assets }} + run: *inventory-code + - *tree + - *absence + - name: Push selected packages once child-first root-last + env: + SELECTED: ${{ needs.preflight.outputs.selected }} + PUSH_KEY: ${{ github.token }} + PUSH_SOURCE: https://nuget.pkg.github.com/opencode-dotnet/index.json + run: &push-code | + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + if ([string]::IsNullOrWhiteSpace($env:PUSH_KEY)) { throw 'Publication credential is required.' } + $selected = ConvertFrom-Json -InputObject $env:SELECTED -NoEnumerate + $digests = [ordered]@{} + foreach ($name in $selected) { $digests[$name] = (Get-FileHash -LiteralPath (Join-Path 'artifacts/feed' $name) -Algorithm SHA256).Hash.ToLowerInvariant() } + $attempted = [Collections.Generic.List[string]]::new() + $accepted = [Collections.Generic.List[string]]::new() + $failed = [Collections.Generic.List[string]]::new() + try { + foreach ($name in $selected) { + $attempted.Add($name) + try { + $response = dotnet nuget push (Join-Path 'artifacts/feed' $name) --source $env:PUSH_SOURCE --api-key $env:PUSH_KEY 2>&1 + $code = $LASTEXITCODE + $text = ($response | Out-String).Replace($env:PUSH_KEY, '') + Write-Output "$name candidate SHA-256=$($digests[$name]) exit=$code`n$text" + "$name candidate SHA-256=$($digests[$name]) exit=$code`n$text" >> $env:GITHUB_STEP_SUMMARY + if ($code -ne 0) { throw "Push refused for $name (exit $code)." } + $accepted.Add($name) + } catch { + $failed.Add($name) + throw + } + } + } finally { + $record = [ordered]@{ attempted = @($attempted); accepted = @($accepted); failed = @($failed); + unattempted = @($selected | Where-Object { -not $attempted.Contains($_) }); candidateSha256 = $digests } + $json = ConvertTo-Json -InputObject $record -Depth 5 -Compress + Write-Output $json + $json >> $env:GITHUB_STEP_SUMMARY + 'Accepted push responses do not establish indexed presence. Channel verification supplies that evidence.' >> $env:GITHUB_STEP_SUMMARY + } + + nuget: + if: inputs.target == 'nuget' + needs: preflight + runs-on: ubuntu-24.04 + timeout-minutes: 30 + environment: release + permissions: + contents: read + actions: read + id-token: write + steps: + - *checkout + - *initialize + - *sdk + - *feed-download + - *assets-download + - *compare + - *tree + - *absence + - name: NuGet.org login immediately before pushes + id: login + uses: NuGet/login@v1 + with: + user: ${{ vars.NUGET_TRUSTED_PUBLISHING_USER }} + - name: Push selected packages once child-first root-last + env: + SELECTED: ${{ needs.preflight.outputs.selected }} + PUSH_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} + PUSH_SOURCE: https://api.nuget.org/v3/index.json + run: *push-code + + github-release: + if: inputs.target == 'github-release' + needs: preflight + runs-on: ubuntu-24.04 + timeout-minutes: 30 + environment: release + permissions: + contents: write + actions: read + steps: + - *checkout + - *feed-download + - *assets-download + - *compare + - *tree + - *absence + - name: Create draft upload read back and publish once + env: + API_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + COMMIT: ${{ inputs.commit }} + VERSION: ${{ inputs.version }} + RELEASE_NOTES: ${{ inputs.release-notes }} + ASSET_INVENTORY: ${{ needs.preflight.outputs.assets }} + run: | + $ErrorActionPreference = 'Stop' + $headers = @{ Authorization = "Bearer $env:API_TOKEN"; Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28' } + $api = "https://api.github.com/repos/$env:REPOSITORY" + $tag = "v$env:VERSION" + $preview = $env:VERSION.Split('+')[0].Contains('-', [StringComparison]::Ordinal) + $latest = if ($preview) { 'false' } else { 'true' } + $body = @{ tag_name = $tag; target_commitish = $env:COMMIT; name = $tag; body = $env:RELEASE_NOTES; + draft = $true; prerelease = $preview; make_latest = $latest; generate_release_notes = $false } | ConvertTo-Json + $draft = Invoke-RestMethod -Uri "$api/releases" -Headers $headers -Method Post -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($body)) + if ($draft.draft -ne $true -or $draft.tag_name -cne $tag -or $draft.target_commitish -cne $env:COMMIT -or + $draft.body -cne $env:RELEASE_NOTES -or $draft.prerelease -ne $preview) { throw 'Created draft differs from the approved release identity.' } + Write-Output "Draft release $($draft.html_url)" + "Draft release $($draft.html_url)" >> $env:GITHUB_STEP_SUMMARY + $expected = (ConvertFrom-Json -InputObject $env:ASSET_INVENTORY).files + $upload = $draft.upload_url.Split('{')[0] + foreach ($file in $expected) { + $name = [Uri]::EscapeDataString($file.path) + $asset = Invoke-RestMethod -Uri "$($upload)?name=$name" -Headers $headers -Method Post -ContentType 'application/octet-stream' -InFile (Join-Path 'artifacts/release-assets' $file.path) + Write-Output "Uploaded $($asset.name) API digest=$($asset.digest)" + } + $assets = @() + for ($page = 1; ; $page++) { + $batch = Invoke-RestMethod -Uri "$api/releases/$($draft.id)/assets?per_page=100&page=$page" -Headers $headers + if ($batch -isnot [array]) { throw 'Malformed release assets response.' } + $assets += $batch + if ($batch.Count -lt 100) { break } + } + if ($assets.Count -ne $expected.Count) { throw 'Uploaded asset count differs from the candidate.' } + $owned = Join-Path $env:RUNNER_TEMP ("release-readback-" + [Guid]::NewGuid().ToString('N')) + [void](New-Item -ItemType Directory -Path $owned) + try { + foreach ($file in $expected) { + $matches = @($assets | Where-Object { $_.name -ceq $file.path }) + if ($matches.Count -ne 1 -or $matches[0].size -ne $file.size -or $matches[0].state -cne 'uploaded') { throw "Uploaded asset name/size differs: $($file.path)" } + $asset = $matches[0] + $download = Join-Path $owned $file.path + $binaryHeaders = $headers.Clone() + $binaryHeaders.Accept = 'application/octet-stream' + Invoke-WebRequest -Uri "$api/releases/assets/$($asset.id)" -Headers $binaryHeaders -OutFile $download + $digest = (Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash.ToLowerInvariant() + if ($digest -cne $file.sha256) { throw "Release asset read-back digest differs: $($file.path)" } + $record = "$($file.path) candidate/read-back SHA-256=$digest API digest=$($asset.digest)" + Write-Output $record + $record >> $env:GITHUB_STEP_SUMMARY + } + } finally { + Remove-Item -LiteralPath $owned -Recurse -Force + } + $publish = @{ draft = $false; make_latest = $latest } | ConvertTo-Json + $release = Invoke-RestMethod -Uri "$api/releases/$($draft.id)" -Headers $headers -Method Patch -ContentType 'application/json' -Body $publish + $confirmed = Invoke-RestMethod -Uri "$api/releases/$($draft.id)" -Headers $headers + if ($release.draft -ne $false -or $confirmed.draft -ne $false -or $confirmed.tag_name -cne $tag -or + $confirmed.target_commitish -cne $env:COMMIT -or $confirmed.body -cne $env:RELEASE_NOTES -or $confirmed.prerelease -ne $preview) { + throw 'Published release does not identify the approved candidate.' + } + $encodedTag = [Uri]::EscapeDataString($tag) + $ref = Invoke-RestMethod -Uri "$api/git/ref/tags/$encodedTag" -Headers $headers + $object = $ref.object + while ($object.type -ceq 'tag') { + $annotated = Invoke-RestMethod -Uri "$api/git/tags/$($object.sha)" -Headers $headers + $object = $annotated.object + } + if ($object.type -cne 'commit' -or $object.sha -cne $env:COMMIT) { throw 'Published peeled tag does not identify the candidate commit.' } + Write-Output "Published $($confirmed.html_url) at $env:COMMIT" + "Published $($confirmed.html_url) at $env:COMMIT" >> $env:GITHUB_STEP_SUMMARY diff --git a/docs/architecture/hosting-and-packaging.md b/docs/architecture/hosting-and-packaging.md index 8290e3e..7469b99 100644 --- a/docs/architecture/hosting-and-packaging.md +++ b/docs/architecture/hosting-and-packaging.md @@ -550,6 +550,14 @@ or packaged-startup claim. ## Installation and release boundaries +Publication consumes the candidate's seven original packages and release-assets artifact without +rebuilding, repacking, re-archiving or renaming. A candidate's workflow tree must equal master's at +publication. + +NuGet.org repository signing changes the package envelope. Real-channel identity is therefore +established through the running native payload's complete paths and SHA-256 values, not downloaded +package-envelope equality. + The product target includes PowerShell and shell installers, WinGet, Homebrew, suitable deb and rpm packages, a Windows MSI, and a macOS pkg. Archive-only delivery does not close that target. Each surface is a separate delivery increment after native and package proof, never a placeholder. diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index 21822ce..78e0c0c 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -324,6 +324,27 @@ order. The pull request's hosted `Native` run proves assembly and upload, not pu behaviour or a live-channel download. Dispatch retention is confirmed on an authorized manual candidate run. +### Publication pass + +Publication is separate from managed, native and local-package acceptance. A publication candidate +is one successful manual Native run on master, identified by its full commit SHA and run ID. +Publication consumes that run's validated package feed and release-assets artifact unchanged. + +The manual release workflow checks candidate provenance, evaluated version, workflow-tree equality, +target absence and artifact integrity before publication. A dry run performs those checks without +publication privileges or an environment deployment. Publishing requires the `release` environment +and the maintainer's separate authorization. + +Real-channel acceptance requires every manifest RID's verification leg to succeed against the selected +published channel. Feed acceptance uses cold global-tool and DNX acquisition and complete +running-payload path/SHA-256 equality with candidate evidence. NuGet.org's repository-signed package +envelope is not compared with the original package digest. Release acceptance checks downloaded archive +hashes against both the published checksum file and independent candidate receipts before execution. + +Secret-bearing channel jobs retain the existing test guards but upload only selected +credential-redacted TRX and process snapshots. Credential files, acquisition stores and memory dumps +are not uploaded. Existing credential-free CI artifact policy is unchanged. + ### Linux builder verification The builder recipe and publication contract are owned by diff --git a/docs/engineering/workflow.md b/docs/engineering/workflow.md index fe96242..e5e8a33 100644 --- a/docs/engineering/workflow.md +++ b/docs/engineering/workflow.md @@ -1,6 +1,6 @@ # Repository Workflow -Date: 2026-11-05 +Date: 2026-11-14 Canonical working agreements for research, implementation, temporary work, verification, and Git history. @@ -73,6 +73,29 @@ alone, and the pull request passes the full gate: A NuGetAudit advisory fails restore; its remedy is a prompt pin bump through this procedure, never a suppression or an audit override (`quality-gates.md`). +## Publication procedure + +Settings and public identities require the maintainer's approval before the release lane is enabled. +Every feed publication and GitHub Release requires his own word with the exact target, candidate +commit, Native run ID, version, filenames and digests. Approval of a candidate or dry run authorizes +no publication. + +Promote GitHub Packages first, make all seven packages public with the maintainer's explicit +irreversible-visibility approval, and verify that channel. Ask separately for NuGet.org publication +with the successful GitHub Packages verification run ID. Ask separately for the GitHub Release with +its tag, asset digests, release-notes text and successful NuGet verification run ID. + +The lane dispatches the workflow after the word; the maintainer approves the waiting `release` job +in GitHub. The lane never approves deployments, publishes releases or changes package visibility +with its own credentials. + +Hold workflow-tree changes from candidate selection until release publication. Partial publication +blocks promotion. Record push responses and the verified present/missing sets; ask for exactly the +missing-file recovery or abandonment. Never retry a push automatically or reuse rebuilt bytes under +a published version. Expired candidate artifacts require abandonment and a new version. The `files` +input recovers feed pushes only; a partial draft release is left for the maintainer's decision, not +automatically resumed or cleaned up. + ## Documentation sessions Research and decision sessions end with a documentation pass. Current canon or ADR updates when a diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.Publication.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.Publication.cs new file mode 100644 index 0000000..5bec2fe --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeApplicationTests.Publication.cs @@ -0,0 +1,38 @@ +using System.Globalization; +using OpenCode.Mcp.Tools.Native; +using OpenCode.Mcp.Tools.Tests.Native.Support; + +namespace OpenCode.Mcp.Tools.Tests.Native; + +public sealed partial class NativeApplicationTests +{ + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task RunAsync_Should_Validate_Publication_Without_Changing_The_Candidate(bool refused, CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + if (refused) + { + scenario.Files.File.Delete(scenario.Asset("win-x64.zip")); + } + var before = await scenario.CaptureAsync(token); + var directories = scenario.Files.Directory.GetDirectories(scenario.Candidate.Build.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).ToArray(); + using var output = new StringWriter(CultureInfo.InvariantCulture); + using var errors = new StringWriter(CultureInfo.InvariantCulture); + var host = scenario.Candidate.Build.Host with { Os = "unsupported", OsArchitecture = "unsupported", ProcessArchitecture = "unsupported" }; + var application = new NativeApplication(scenario.Files, scenario.Candidate.Runner, new FixtureHostReader(host), scenario.Candidate.Builder.Native.Modes, output, errors); + var root = host.WorkingDirectory; + var result = await application.RunAsync(["publication", "--receipts", scenario.Files.Path.GetRelativePath(root, scenario.Request.Receipts), + "--feed", scenario.Files.Path.GetRelativePath(root, scenario.Feed), "--assets", scenario.Files.Path.GetRelativePath(root, scenario.Request.Assets), + "--version", scenario.Request.Version, "--commit", scenario.Commit], token); + await Assert.That(result).IsEqualTo(refused ? 2 : 0); + await Assert.That(output.ToString().Replace("\r\n", "\n", StringComparison.Ordinal)).IsEqualTo(refused ? "" : "Publication candidate is complete.\n"); + await Assert.That(errors.ToString().Replace("\r\n", "\n", StringComparison.Ordinal)) + .IsEqualTo(refused ? "Missing release asset: opencode-mcp-" + scenario.Request.Version + "-win-x64.zip\n" : ""); + await scenario.AssertUnchangedAsync(before, token); + await Assert.That(scenario.Files.Directory.GetDirectories(scenario.Candidate.Build.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)) + .IsEquivalentTo(directories, TUnit.Assertions.Enums.CollectionOrdering.Matching); + await Assert.That(scenario.Candidate.Runner.Calls).IsEmpty(); + } +} diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs index a2afa6e..cf69b40 100644 --- a/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativeArgumentsTests.cs @@ -4,6 +4,32 @@ namespace OpenCode.Mcp.Tools.Tests.Native; public sealed class NativeArgumentsTests { + [Test] + public async Task Parse_Should_Select_Publication_And_Require_All_Inputs() + { + string[] arguments = ["publication", "--receipts", "completed tree", "--feed", "candidate feed", "--assets", "release assets", "--version", "exact version", "--commit", "full commit"]; + var command = NativeArguments.Parse(arguments); + await Assert.That(command).IsEqualTo(new NativeCommand("publication", null, null, null, null, "completed tree", + Feed: "candidate feed", Version: "exact version", Assets: "release assets", Commit: "full commit")); + for (var index = 1; index < arguments.Length; index += 2) + { + var name = arguments[index]; + await Assert.That(() => NativeArguments.Parse(arguments[..index])) + .ThrowsExactly().WithMessage("Arguments: missing " + name + ".", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["publication", name, "one", name, "two"])) + .ThrowsExactly().WithMessage("Arguments: duplicate " + name + ".", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["publication", name])) + .ThrowsExactly().WithMessage("Arguments: missing value for " + name + ".", StringComparison.Ordinal); + await Assert.That(() => NativeArguments.Parse(["publication", name, "--feed", "value"])) + .ThrowsExactly().WithMessage("Arguments: missing value for " + name + ".", StringComparison.Ordinal); + } + foreach (var name in new[] { "--rid", "--manifest", "--output", "--unknown" }) + { + await Assert.That(() => NativeArguments.Parse(["publication", name, "value"])) + .ThrowsExactly().WithMessage("Arguments: unknown option " + name + " for publication.", StringComparison.Ordinal); + } + } + [Test] public async Task Parse_Should_Select_Assets_And_Require_All_Four_Inputs() { @@ -60,7 +86,7 @@ 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 or snapshot.", StringComparison.Ordinal); + .WithMessage("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication or snapshot.", StringComparison.Ordinal); } [Test] diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/NativePublicationValidatorTests.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/NativePublicationValidatorTests.cs new file mode 100644 index 0000000..12efc88 --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/NativePublicationValidatorTests.cs @@ -0,0 +1,130 @@ +using OpenCode.Mcp.Tools.Native; +using OpenCode.Mcp.Tools.Tests.Native.Support; +using TUnit.Assertions.Enums; + +namespace OpenCode.Mcp.Tools.Tests.Native; + +public sealed class NativePublicationValidatorTests +{ + private static readonly string[] Rids = ["win-x64", "win-arm64", "linux-x64", "linux-arm64", "osx-x64", "osx-arm64"]; + + [Test] + public async Task ValidateAsync_Should_Bind_Every_Receipt_To_The_Candidate(CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + foreach (var child in scenario.Candidate.Builder.Children) + { + await scenario.Candidate.WriteReceiptAsync(child.Receipt with { SourceStatus = " M development" }, token); + } + var request = scenario.Request with { Version = "different-version", Commit = "different-commit" }; + var result = await new NativePublicationValidator(scenario.Files, scenario.Candidate.Builder.Native.Modes).ValidateAsync(request, token); + await Assert.That(result).IsEquivalentTo(Rids + .SelectMany(static rid => new[] { rid + ": Receipt version must be different-version.", rid + ": Receipt source commit must be different-commit.", + rid + ": Candidate receipt source status must be empty." }), CollectionOrdering.Matching); + } + + [Test] + [Arguments("native")] + [Arguments("feed")] + public async Task ValidateAsync_Should_Preserve_The_Complete_Native_And_Feed_Refusals(string stage, CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + string[] expected; + if (stage == "native") + { + scenario.Files.File.Delete(scenario.Files.Path.Combine(scenario.Candidate.Directory("win-arm64"), "payload-manifest.json")); + scenario.Files.File.Delete(scenario.Candidate.Archive("win-arm64")); + scenario.Files.File.Delete(scenario.Files.Path.Combine(scenario.Candidate.Directory("osx-x64"), "payload", "LICENSE")); + expected = ["osx-x64: Missing payload file: LICENSE", "win-arm64: Missing payload manifest.", "win-arm64: Missing archive."]; + } + else + { + scenario.Files.File.Delete(scenario.Files.Path.Combine(scenario.Feed, scenario.Candidate.Builder.PackageFileName)); + await scenario.Files.File.WriteAllTextAsync(scenario.Files.Path.Combine(scenario.Feed, "z-extra"), "extra", token); + await scenario.Files.File.WriteAllTextAsync(scenario.Files.Path.Combine(scenario.Feed, "a-extra"), "extra", token); + scenario.Files.Directory.CreateDirectory(scenario.Files.Path.Combine(scenario.Feed, "extra-directory")); + expected = ["Missing feed file: " + scenario.Candidate.Builder.PackageFileName, "Unexpected feed file: a-extra", "Unexpected feed file: z-extra", "Unexpected feed directory: extra-directory"]; + } + scenario.Files.File.Delete(scenario.Checksums); + await AssertRefusalAsync(scenario, expected, token); + } + + [Test] + [Arguments("receipt.json")] + [Arguments("payload-manifest.json")] + public async Task ValidateAsync_Should_Require_Byte_Identical_Feed_Evidence(string name, CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + foreach (var rid in new[] { "osx-arm64", "win-x64" }) + { + var path = scenario.FeedEvidence(rid, name); + await scenario.Files.File.WriteAllTextAsync(path, await scenario.Files.File.ReadAllTextAsync(path, token) + " \n", token); + } + var description = name == "receipt.json" ? "receipt" : "payload manifest"; + await AssertRefusalAsync(scenario, ["win-x64: Feed " + description + " differs from completed evidence.", + "osx-arm64: Feed " + description + " differs from completed evidence."], token); + } + + [Test] + public async Task ValidateAsync_Should_Complete_The_Feed_Stage_Before_Refusing(CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + scenario.Files.File.Delete(scenario.Files.Path.Combine(scenario.Feed, scenario.Candidate.Builder.PackageFileName)); + scenario.Files.File.Delete(scenario.Checksums); + var retained = scenario.FeedEvidence("win-x64", "receipt.json"); + await scenario.Files.File.WriteAllTextAsync(retained, await scenario.Files.File.ReadAllTextAsync(retained, token) + " \n", token); + await AssertRefusalAsync(scenario, ["Missing feed file: " + scenario.Candidate.Builder.PackageFileName, + "win-x64: Feed receipt differs from completed evidence."], token); + } + + [Test] + public async Task ValidateAsync_Should_Require_The_Exact_Release_Asset_Set(CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + scenario.Files.File.Delete(scenario.Asset("win-x64.zip")); + scenario.Files.File.Delete(scenario.Asset("linux-arm64.tar.gz")); + scenario.Files.File.Delete(scenario.Checksums); + foreach (var name in new[] { "z-extra", "a-extra" }) + { + await scenario.Files.File.WriteAllTextAsync(scenario.Files.Path.Combine(scenario.Request.Assets, name), "extra", token); + } + scenario.Files.Directory.CreateDirectory(scenario.Files.Path.Combine(scenario.Request.Assets, "z-directory")); + scenario.Files.Directory.CreateDirectory(scenario.Files.Path.Combine(scenario.Request.Assets, "a-directory")); + await scenario.Files.File.WriteAllTextAsync(scenario.Files.Path.Combine(scenario.Request.Assets, "a-directory", "nested"), "extra", token); + await AssertRefusalAsync(scenario, ["Missing release asset: opencode-mcp-" + scenario.Request.Version + "-win-x64.zip", + "Missing release asset: opencode-mcp-" + scenario.Request.Version + "-linux-arm64.tar.gz", "Missing release asset: SHA256SUMS", + "Unexpected release asset: a-directory/nested", "Unexpected release asset: a-extra", "Unexpected release asset: z-extra", + "Unexpected release directory: a-directory", "Unexpected release directory: z-directory"], token); + } + + [Test] + public async Task ValidateAsync_Should_Compare_Archives_With_Receipts_Not_Only_Checksums(CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + await scenario.ChangeArchiveAndChecksumsAsync(token); + await AssertRefusalAsync(scenario, ["linux-x64: Release archive digest differs from receipt.", + "SHA256SUMS differs from the receipt-ordered release checksums."], token); + } + + [Test] + [Arguments("order")] + [Arguments("digest")] + [Arguments("filename")] + [Arguments("BOM")] + [Arguments("CRLF")] + [Arguments("self")] + [Arguments("extra")] + public async Task ValidateAsync_Should_Require_Receipt_Ordered_Checksum_Bytes(string fault, CancellationToken token) + { + var scenario = await NativePublicationScenario.CreateAsync(token); + await scenario.RewriteChecksumsAsync(fault, token); + await AssertRefusalAsync(scenario, ["SHA256SUMS differs from the receipt-ordered release checksums."], token); + } + + private static async Task AssertRefusalAsync(NativePublicationScenario scenario, IReadOnlyList expected, CancellationToken token) + { + var before = await scenario.CaptureAsync(token); + await Assert.That(await scenario.ValidateAsync(token)).IsEquivalentTo(expected, CollectionOrdering.Matching); + await scenario.AssertUnchangedAsync(before, token); + } +} diff --git a/tests/OpenCode.Mcp.Tools.Tests/Native/Support/NativePublicationScenario.cs b/tests/OpenCode.Mcp.Tools.Tests/Native/Support/NativePublicationScenario.cs new file mode 100644 index 0000000..2ac8b76 --- /dev/null +++ b/tests/OpenCode.Mcp.Tools.Tests/Native/Support/NativePublicationScenario.cs @@ -0,0 +1,85 @@ +using System.IO.Abstractions; +using System.Security.Cryptography; +using System.Text; +using OpenCode.Mcp.Tools.Native; +using TUnit.Assertions.Enums; + +namespace OpenCode.Mcp.Tools.Tests.Native.Support; + +internal sealed class NativePublicationScenario(NativeReleaseAssetsScenario assets) +{ + public NativeReleaseAssetsScenario Candidate { get; } = assets; + public IFileSystem Files => Candidate.Files; + public string Feed => Candidate.Builder.Feed; + public string Commit => Candidate.Builder.Receipt.SourceCommit; + public NativePublicationRequest Request => new(Candidate.Manifest, Candidate.Receipts, Feed, Candidate.Output, Candidate.Version, Commit); + public string Checksums => Files.Path.Combine(Candidate.Output, "SHA256SUMS"); + + public static async Task CreateAsync(CancellationToken token) + { + var candidate = await NativeReleaseAssetsScenario.CreateAsync(token); + foreach (var child in candidate.Builder.Children) + { + await candidate.WriteReceiptAsync(child.Receipt with { SourceStatus = "" }, token); + } + await candidate.Builder.WriteFeedAsync(token); + using var output = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + await new NativeReleaseAssets(candidate.Files, candidate.Builder.Native.Modes).BuildAsync(candidate.Request, output, token); + return new(candidate); + } + + public Task> ValidateAsync(CancellationToken token) => + new NativePublicationValidator(Files, Candidate.Builder.Native.Modes).ValidateAsync(Request, token); + + public string Asset(string suffix) => Files.Path.Combine(Candidate.Output, "opencode-mcp-" + Candidate.Version + "-" + suffix); + public string FeedEvidence(string rid, string name) => Files.Path.Combine(Feed, "evidence", rid, name); + + public async Task RewriteChecksumsAsync(string fault, CancellationToken token) + { + var text = await Files.File.ReadAllTextAsync(Checksums, token); + var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries); + text = fault switch + { + "order" => string.Join('\n', lines.Reverse()) + "\n", + "digest" => new string('0', 64) + text[64..], + "filename" => text.Replace("-win-x64.zip", "-wrong.zip", StringComparison.Ordinal), + "BOM" => "\uFEFF" + text, + "CRLF" => text.Replace("\n", "\r\n", StringComparison.Ordinal), + "self" => text + new string('0', 64) + " SHA256SUMS\n", + "extra" => text + "\n", + _ => text, + }; + await Files.File.WriteAllBytesAsync(Checksums, Encoding.UTF8.GetBytes(text), token); + } + + public async Task> CaptureAsync(CancellationToken token) + { + var snapshot = new Dictionary(StringComparer.Ordinal); + foreach (var path in Files.Directory.GetFiles(Candidate.Build.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)) + { + snapshot.Add(path, await Files.File.ReadAllBytesAsync(path, token)); + } + return snapshot; + } + + public async Task AssertUnchangedAsync(IReadOnlyDictionary before, CancellationToken token) + { + await Assert.That(Files.Directory.GetFiles(Candidate.Build.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)) + .IsEquivalentTo(before.Keys, CollectionOrdering.Matching); + foreach (var pair in before) + { + await Assert.That(await Files.File.ReadAllBytesAsync(pair.Key, token)).IsEquivalentTo(pair.Value, CollectionOrdering.Matching); + } + } + + public async Task ChangeArchiveAndChecksumsAsync(CancellationToken token) + { + var path = Asset("linux-x64.tar.gz"); + var original = Convert.ToHexStringLower(SHA256.HashData(await Files.File.ReadAllBytesAsync(path, token))); + await Files.File.WriteAllBytesAsync(path, [1, 2, 3], token); + byte[] changedBytes = [1, 2, 3]; + var changed = Convert.ToHexStringLower(SHA256.HashData(changedBytes)); + var text = await Files.File.ReadAllTextAsync(Checksums, token); + await Files.File.WriteAllBytesAsync(Checksums, Encoding.UTF8.GetBytes(text.Replace(original, changed, StringComparison.Ordinal)), token); + } +} diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs b/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs index 75df9b7..799c7cd 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeApplication.cs @@ -30,10 +30,7 @@ public async Task RunAsync(IReadOnlyList arguments, CancellationTok } if (command.Operation == "validate") { - var diagnostics = await new NativeReceiptValidator(files, modes).ValidateAsync(manifest, - files.Path.GetFullPath(command.Receipts ?? throw new InvalidOperationException("Missing receipts directory."), root), token).ConfigureAwait(false); - NativeDiagnostics.Refuse(diagnostics); - await output.WriteLineAsync("Native receipt set is complete.".AsMemory(), token).ConfigureAwait(false); + await ValidateReceiptsAsync(command, root, manifest, token).ConfigureAwait(false); return 0; } if (command.Operation == "pack-root") @@ -43,11 +40,12 @@ public async Task RunAsync(IReadOnlyList arguments, CancellationTok } if (command.Operation == "assets") { - await new NativeReleaseAssets(files, modes).BuildAsync(new NativeReleaseAssetRequest(manifest, - files.Path.GetFullPath(command.Receipts ?? throw new InvalidOperationException("Missing receipts directory."), root), - files.Path.GetFullPath(command.Evidence ?? throw new InvalidOperationException("Missing evidence directory."), root), - files.Path.GetFullPath(command.Output ?? throw new InvalidOperationException("Missing release assets output."), root), - command.Version ?? throw new InvalidOperationException("Missing release version.")), output, token).ConfigureAwait(false); + await BuildAssetsAsync(command, root, manifest, token).ConfigureAwait(false); + return 0; + } + if (command.Operation == "publication") + { + await ValidatePublicationAsync(command, root, manifest, token).ConfigureAwait(false); return 0; } var rid = command.Rid ?? throw new InvalidOperationException("Missing RID."); @@ -122,4 +120,33 @@ private async Task PackRootAsync(NativeCommand command, NativeHost host, NativeM var feed = files.Path.GetFullPath(command.Feed ?? throw new InvalidOperationException("Missing feed directory."), root); await new McpPackageBuilder(files, runner, modes).PackRootAsync(new NativeBuildRequest(root, receipts, "", host, manifest), feed, output, token).ConfigureAwait(false); } + + private async Task ValidateReceiptsAsync(NativeCommand command, string root, NativeManifest manifest, CancellationToken token) + { + var diagnostics = await new NativeReceiptValidator(files, modes).ValidateAsync(manifest, + files.Path.GetFullPath(command.Receipts ?? throw new InvalidOperationException("Missing receipts directory."), root), token).ConfigureAwait(false); + NativeDiagnostics.Refuse(diagnostics); + await output.WriteLineAsync("Native receipt set is complete.".AsMemory(), token).ConfigureAwait(false); + } + + private async Task BuildAssetsAsync(NativeCommand command, string root, NativeManifest manifest, CancellationToken token) + { + await new NativeReleaseAssets(files, modes).BuildAsync(new NativeReleaseAssetRequest(manifest, + files.Path.GetFullPath(command.Receipts ?? throw new InvalidOperationException("Missing receipts directory."), root), + files.Path.GetFullPath(command.Evidence ?? throw new InvalidOperationException("Missing evidence directory."), root), + files.Path.GetFullPath(command.Output ?? throw new InvalidOperationException("Missing release assets output."), root), + command.Version ?? throw new InvalidOperationException("Missing release version.")), output, token).ConfigureAwait(false); + } + + private async Task ValidatePublicationAsync(NativeCommand command, string root, NativeManifest manifest, CancellationToken token) + { + var request = new NativePublicationRequest(manifest, + files.Path.GetFullPath(command.Receipts ?? throw new InvalidOperationException("Missing receipts directory."), root), + files.Path.GetFullPath(command.Feed ?? throw new InvalidOperationException("Missing feed directory."), root), + files.Path.GetFullPath(command.Assets ?? throw new InvalidOperationException("Missing release assets directory."), root), + command.Version ?? throw new InvalidOperationException("Missing publication version."), + command.Commit ?? throw new InvalidOperationException("Missing publication commit.")); + NativeDiagnostics.Refuse(await new NativePublicationValidator(files, modes).ValidateAsync(request, token).ConfigureAwait(false)); + await output.WriteLineAsync("Publication candidate is complete.".AsMemory(), token).ConfigureAwait(false); + } } diff --git a/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs b/tools/OpenCode.Mcp.Tools/Native/NativeArguments.cs index 85fe57b..1c05af1 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 or snapshot."); + throw new InvalidOperationException("Arguments: use verify, stage, inspect, validate, matrix, control, prove-linux, pack-child, pack-root, assets, publication or snapshot."); } var operation = arguments[0]; string[] required = operation switch @@ -21,6 +21,7 @@ public static NativeCommand Parse(IReadOnlyList arguments) "pack-child" => ["--rid", "--evidence"], "pack-root" => ["--receipts", "--feed"], "assets" => ["--receipts", "--evidence", "--output", "--version"], + "publication" => ["--receipts", "--feed", "--assets", "--version", "--commit"], "snapshot" => ["--output"], _ => throw new InvalidOperationException("Arguments: unknown command " + operation + "."), }; @@ -50,7 +51,7 @@ 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")); + Version: values.GetValueOrDefault("--version"), Assets: values.GetValueOrDefault("--assets"), Commit: values.GetValueOrDefault("--commit")); 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 2b8a396..a802228 100644 --- a/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs +++ b/tools/OpenCode.Mcp.Tools/Native/NativeCommand.cs @@ -1,4 +1,5 @@ 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 Manifest = "packaging/native-manifest.json", string? GithubOutput = null, string? Evidence = null, string? Feed = null, string? Version = null, + string? Assets = null, string? Commit = null); diff --git a/tools/OpenCode.Mcp.Tools/Native/NativePublicationRequest.cs b/tools/OpenCode.Mcp.Tools/Native/NativePublicationRequest.cs new file mode 100644 index 0000000..9bcd703 --- /dev/null +++ b/tools/OpenCode.Mcp.Tools/Native/NativePublicationRequest.cs @@ -0,0 +1,3 @@ +namespace OpenCode.Mcp.Tools.Native; + +internal sealed record NativePublicationRequest(NativeManifest Manifest, string Receipts, string Feed, string Assets, string Version, string Commit); diff --git a/tools/OpenCode.Mcp.Tools/Native/NativePublicationValidator.cs b/tools/OpenCode.Mcp.Tools/Native/NativePublicationValidator.cs new file mode 100644 index 0000000..25c6616 --- /dev/null +++ b/tools/OpenCode.Mcp.Tools/Native/NativePublicationValidator.cs @@ -0,0 +1,110 @@ +using System.IO.Abstractions; +using System.Text; +using OpenCode.Mcp.Tools.Native.Abstractions; +using OpenCode.Mcp.Tools.Packaging; + +namespace OpenCode.Mcp.Tools.Native; + +internal sealed class NativePublicationValidator(IFileSystem files, IUnixFileModes modes) +{ + public async Task> ValidateAsync(NativePublicationRequest request, CancellationToken token) + { + ArgumentNullException.ThrowIfNull(request); + var diagnostics = await new NativeReceiptValidator(files, modes).ValidateAsync(request.Manifest, request.Receipts, token).ConfigureAwait(false); + if (diagnostics.Count != 0) + { + return diagnostics; + } + var locations = await new NativeEvidenceStore(files).ReadReceiptLocationsAsync(request.Receipts, token).ConfigureAwait(false); + var byRid = locations.ToDictionary(static location => location.Receipt.Rid, StringComparer.Ordinal); + var ordered = request.Manifest.Runtimes.Select(runtime => byRid[runtime.Rid]).ToArray(); + diagnostics = IdentityDiagnostics(request, ordered); + if (diagnostics.Count != 0) + { + return diagnostics; + } + var identity = new PackageIdentity("OpenCodeDotNet.Mcp", request.Version, "opencode-mcp", [.. request.Manifest.Runtimes.Select(static runtime => runtime.Rid)]); + var feedDiagnostics = new List(await new McpPackageFeed(files).ValidateAsync(request.Feed, request.Manifest, identity, token).ConfigureAwait(false)); + feedDiagnostics.AddRange(await CompareFeedEvidenceAsync(request, ordered, token).ConfigureAwait(false)); + return feedDiagnostics.Count != 0 ? feedDiagnostics.AsReadOnly() : await ValidateAssetsAsync(request, ordered, token).ConfigureAwait(false); + } + + private static string[] IdentityDiagnostics(NativePublicationRequest request, NativeReceiptLocation[] ordered) + { + var diagnostics = new List(); + foreach (var receipt in ordered.Select(static location => location.Receipt)) + { + if (!string.Equals(receipt.Version, request.Version, StringComparison.Ordinal)) + { + diagnostics.Add(receipt.Rid + ": Receipt version must be " + request.Version + "."); + } + if (!string.Equals(receipt.SourceCommit, request.Commit, StringComparison.Ordinal)) + { + diagnostics.Add(receipt.Rid + ": Receipt source commit must be " + request.Commit + "."); + } + if (receipt.SourceStatus.Length != 0) + { + diagnostics.Add(receipt.Rid + ": Candidate receipt source status must be empty."); + } + } + return [.. diagnostics]; + } + + private async Task> CompareFeedEvidenceAsync(NativePublicationRequest request, NativeReceiptLocation[] ordered, CancellationToken token) + { + var diagnostics = new List(); + foreach (var location in ordered) + { + foreach (var name in new[] { "receipt.json", "payload-manifest.json" }) + { + var retainedPath = files.Path.Combine(request.Feed, "evidence", location.Receipt.Rid, name); + if (!files.File.Exists(retainedPath)) + { + continue; + } + var completed = await files.File.ReadAllBytesAsync(files.Path.Combine(location.Directory, name), token).ConfigureAwait(false); + var retained = await files.File.ReadAllBytesAsync(retainedPath, token).ConfigureAwait(false); + if (!completed.SequenceEqual(retained)) + { + diagnostics.Add(location.Receipt.Rid + ": Feed " + (name == "receipt.json" ? "receipt" : "payload manifest") + " differs from completed evidence."); + } + } + } + return diagnostics.AsReadOnly(); + } + + private async Task> ValidateAssetsAsync(NativePublicationRequest request, NativeReceiptLocation[] ordered, CancellationToken token) + { + var names = ordered.Select(location => "opencode-mcp-" + request.Version + "-" + location.Receipt.Rid + new NativeRid(location.Receipt.Rid).ArchiveExtension).ToArray(); + var diagnostics = new List(AssetSetDiagnostics(request.Assets, [.. names, "SHA256SUMS"])); + var store = new NativeEvidenceStore(files); + var checksums = new StringBuilder(); + for (var index = 0; index < ordered.Length; index++) + { + var receipt = ordered[index].Receipt; + var path = files.Path.Combine(request.Assets, names[index]); + if (files.File.Exists(path) && !string.Equals(await store.DigestAsync(path, token).ConfigureAwait(false), receipt.ArchiveSha256, StringComparison.Ordinal)) + { + diagnostics.Add(receipt.Rid + ": Release archive digest differs from receipt."); + } + checksums.Append(receipt.ArchiveSha256).Append(" ").Append(names[index]).Append('\n'); + } + var checksumPath = files.Path.Combine(request.Assets, "SHA256SUMS"); + if (files.File.Exists(checksumPath) && !(await files.File.ReadAllBytesAsync(checksumPath, token).ConfigureAwait(false)).SequenceEqual(Encoding.UTF8.GetBytes(checksums.ToString()))) + { + diagnostics.Add("SHA256SUMS differs from the receipt-ordered release checksums."); + } + return diagnostics.AsReadOnly(); + } + + private IReadOnlyList AssetSetDiagnostics(string directory, string[] expected) + { + var actual = files.Directory.Exists(directory) ? files.Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories) + .Select(path => files.Path.GetRelativePath(directory, path).Replace(files.Path.DirectorySeparatorChar, '/')).ToArray() : []; + var directories = files.Directory.Exists(directory) ? files.Directory.EnumerateDirectories(directory, "*", SearchOption.AllDirectories) + .Select(path => files.Path.GetRelativePath(directory, path).Replace(files.Path.DirectorySeparatorChar, '/')).ToArray() : []; + return [.. expected.Except(actual, StringComparer.Ordinal).Select(static name => "Missing release asset: " + name), + .. actual.Except(expected, StringComparer.Ordinal).Order(StringComparer.Ordinal).Select(static name => "Unexpected release asset: " + name), + .. directories.Order(StringComparer.Ordinal).Select(static name => "Unexpected release directory: " + name)]; + } +} From 8b6e599669aadb3fa2ab1051d6989a1d9e21e358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sat, 14 Nov 2026 17:42:03 +0300 Subject: [PATCH 2/5] ci: harden release lane publication checks --- .github/workflows/release.yml | 50 ++++++++++++++++++++----------- docs/engineering/quality-gates.md | 11 +++++-- docs/engineering/workflow.md | 13 ++++++-- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3b64c73..c4b71b8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -59,6 +59,7 @@ jobs: permissions: contents: read actions: read + packages: read outputs: feed: ${{ steps.inventory.outputs.feed }} assets: ${{ steps.inventory.outputs.assets }} @@ -82,7 +83,7 @@ jobs: COMMIT: ${{ inputs.commit }} run: | $ErrorActionPreference = 'Stop' - if ($env:COMMIT -cnotmatch '^[0-9a-f]{40}$') { throw 'commit must be a full SHA.' } + if ($env:COMMIT -cnotmatch '^[0-9a-f]{40}\z') { throw 'commit must be a full SHA.' } $head = git rev-parse HEAD if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($head -cne $env:COMMIT) { throw 'Checkout does not equal the candidate commit.' } @@ -98,7 +99,7 @@ jobs: COMMIT: ${{ inputs.commit }} run: | $ErrorActionPreference = 'Stop' - if ($env:NATIVE_RUN_ID -notmatch '^[1-9][0-9]*$') { throw 'native-run-id must be a run ID.' } + if ($env:NATIVE_RUN_ID -notmatch '^[1-9][0-9]*\z') { throw 'native-run-id must be a run ID.' } $workflow = gh api "repos/$env:REPOSITORY/actions/workflows/native.yml" | ConvertFrom-Json if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $run = gh api "repos/$env:REPOSITORY/actions/runs/$env:NATIVE_RUN_ID" | ConvertFrom-Json @@ -134,6 +135,8 @@ jobs: $ErrorActionPreference = 'Stop' git fetch --no-tags origin +refs/heads/master:refs/remotes/origin/master if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + git merge-base --is-ancestor $env:COMMIT origin/master + if ($LASTEXITCODE -ne 0) { throw 'master does not contain the candidate commit.' } $candidate = git rev-parse "$($env:COMMIT):.github/workflows" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $master = git rev-parse 'origin/master:.github/workflows' @@ -151,7 +154,7 @@ jobs: run: | $ErrorActionPreference = 'Stop' $id = if ($env:TARGET -ceq 'nuget') { $env:GITHUB_VERIFICATION } else { $env:NUGET_VERIFICATION } - if ($id -notmatch '^[1-9][0-9]*$') { throw 'The preceding channel verification run ID is required.' } + if ($id -notmatch '^[1-9][0-9]*\z') { throw 'The preceding channel verification run ID is required.' } $workflow = gh api "repos/$env:REPOSITORY/actions/workflows/verify-channel.yml" | ConvertFrom-Json if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $run = gh api "repos/$env:REPOSITORY/actions/runs/$id" | ConvertFrom-Json @@ -224,9 +227,9 @@ jobs: RELEASE_NOTES: ${{ inputs.release-notes }} REPOSITORY: ${{ github.repository }} API_TOKEN: ${{ github.token }} - PACKAGES_READ_TOKEN: ${{ secrets.GH_PACKAGES_READ_TOKEN }} run: | $ErrorActionPreference = 'Stop' + if ($env:RELEASE_NOTES -cmatch '\r') { throw 'release-notes must not contain a carriage return.' } function Get-Response($url, $token) { $headers = @{ Accept = 'application/json' } if ($token) { @@ -236,9 +239,9 @@ jobs: } return Invoke-WebRequest -Uri $url -Headers $headers -SkipHttpErrorCheck } - function Read-GitHub($response) { + function Read-GitHub($response, $absenceMessage) { $value = ConvertFrom-Json -InputObject $response.Content -NoEnumerate - if ($response.StatusCode -eq 404 -and $value.message -ceq 'Not Found') { return $null } + if ($response.StatusCode -eq 404 -and $absenceMessage -and $value.message -ceq $absenceMessage) { return $null } if ($response.StatusCode -ne 200) { throw "GitHub metadata request failed: HTTP $($response.StatusCode)." } if ($null -eq $value) { throw 'Malformed GitHub metadata response.' } return ,$value @@ -246,8 +249,8 @@ jobs: function Test-GitHubVersion($id) { $encoded = [Uri]::EscapeDataString($id) for ($page = 1; ; $page++) { - $response = Get-Response "https://api.github.com/orgs/opencode-dotnet/packages/nuget/$encoded/versions?per_page=100&page=$page" $env:PACKAGES_READ_TOKEN - $versions = Read-GitHub $response + $response = Get-Response "https://api.github.com/orgs/opencode-dotnet/packages/nuget/$encoded/versions?per_page=100&page=$page" $env:API_TOKEN + $versions = Read-GitHub $response 'Package not found.' if ($null -eq $versions) { return $false } if ($versions -isnot [array]) { throw 'Malformed GitHub package-version response.' } foreach ($version in $versions) { @@ -280,11 +283,6 @@ jobs: } $selected = @($names | Where-Object { $selection.Contains($_) }) "selected=$(ConvertTo-Json -InputObject $selected -Compress)" >> $env:GITHUB_OUTPUT - if ($env:TARGET -in @('github-packages', 'dry-run')) { - if ([string]::IsNullOrWhiteSpace($env:PACKAGES_READ_TOKEN)) { throw 'GH_PACKAGES_READ_TOKEN is required for GitHub Packages metadata.' } - $user = Read-GitHub (Get-Response 'https://api.github.com/user' $env:PACKAGES_READ_TOKEN) - if ([string]::IsNullOrEmpty($user.login)) { throw 'GitHub Packages read-token authentication failed.' } - } foreach ($feed in @('github-packages', 'nuget') | Where-Object { $env:TARGET -ceq $_ -or $env:TARGET -ceq 'dry-run' }) { $present = @() $missing = @() @@ -304,18 +302,24 @@ jobs: if ($env:TARGET -in @('github-release', 'dry-run')) { if ($env:TARGET -ceq 'github-release' -and [string]::IsNullOrWhiteSpace($env:RELEASE_NOTES)) { throw 'Literal approved release-notes are required.' } $tag = "v$env:VERSION" + $releaseScope = if ($env:GITHUB_JOB -ceq 'preflight') { 'published releases' } else { 'releases, including drafts' } for ($page = 1; ; $page++) { - $releases = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/releases?per_page=100&page=$page" $env:API_TOKEN) + $releases = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/releases?per_page=100&page=$page" $env:API_TOKEN) '' if ($releases -isnot [array]) { throw 'Malformed release-list response.' } foreach ($release in $releases) { if ($release.tag_name -isnot [string]) { throw 'Malformed release identity.' } - if ($release.tag_name -ceq $tag) { throw 'The release identity already exists, including drafts.' } + if ($release.tag_name -ceq $tag) { throw "The release identity already exists in $releaseScope." } } if ($releases.Count -lt 100) { break } } $encodedTag = [Uri]::EscapeDataString($tag) - $ref = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/git/ref/tags/$encodedTag" $env:API_TOKEN) + $ref = Read-GitHub (Get-Response "https://api.github.com/repos/$env:REPOSITORY/git/ref/tags/$encodedTag" $env:API_TOKEN) 'Not Found' if ($null -ne $ref) { throw 'The release tag already exists.' } + $record = if ($env:GITHUB_JOB -ceq 'preflight') { + 'Checked published releases and the tag only; drafts are checked by the github-release job before it creates anything.' + } else { 'Checked releases, including drafts, and the tag.' } + Write-Output $record + $record >> $env:GITHUB_STEP_SUMMARY } - &feed-download name: Download original candidate feed @@ -417,6 +421,7 @@ jobs: - name: Push selected packages once child-first root-last env: SELECTED: ${{ needs.preflight.outputs.selected }} + EXPECTED_FEED: ${{ needs.preflight.outputs.feed }} PUSH_KEY: ${{ github.token }} PUSH_SOURCE: https://nuget.pkg.github.com/opencode-dotnet/index.json run: &push-code | @@ -424,8 +429,13 @@ jobs: $PSNativeCommandUseErrorActionPreference = $false if ([string]::IsNullOrWhiteSpace($env:PUSH_KEY)) { throw 'Publication credential is required.' } $selected = ConvertFrom-Json -InputObject $env:SELECTED -NoEnumerate + $expected = (ConvertFrom-Json -InputObject $env:EXPECTED_FEED).files $digests = [ordered]@{} - foreach ($name in $selected) { $digests[$name] = (Get-FileHash -LiteralPath (Join-Path 'artifacts/feed' $name) -Algorithm SHA256).Hash.ToLowerInvariant() } + foreach ($name in $selected) { + $digests[$name] = (Get-FileHash -LiteralPath (Join-Path 'artifacts/feed' $name) -Algorithm SHA256).Hash.ToLowerInvariant() + $matches = @($expected | Where-Object { $_.path -ceq $name }) + if ($matches.Count -ne 1 -or $digests[$name] -cne $matches[0].sha256) { throw "Package differs from the validated preflight digest: $name" } + } $attempted = [Collections.Generic.List[string]]::new() $accepted = [Collections.Generic.List[string]]::new() $failed = [Collections.Generic.List[string]]::new() @@ -481,6 +491,7 @@ jobs: - name: Push selected packages once child-first root-last env: SELECTED: ${{ needs.preflight.outputs.selected }} + EXPECTED_FEED: ${{ needs.preflight.outputs.feed }} PUSH_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} PUSH_SOURCE: https://api.nuget.org/v3/index.json run: *push-code @@ -511,6 +522,7 @@ jobs: ASSET_INVENTORY: ${{ needs.preflight.outputs.assets }} run: | $ErrorActionPreference = 'Stop' + if ($env:RELEASE_NOTES -cmatch '\r') { throw 'release-notes must not contain a carriage return.' } $headers = @{ Authorization = "Bearer $env:API_TOKEN"; Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28' } $api = "https://api.github.com/repos/$env:REPOSITORY" $tag = "v$env:VERSION" @@ -518,6 +530,10 @@ jobs: $latest = if ($preview) { 'false' } else { 'true' } $body = @{ tag_name = $tag; target_commitish = $env:COMMIT; name = $tag; body = $env:RELEASE_NOTES; draft = $true; prerelease = $preview; make_latest = $latest; generate_release_notes = $false } | ConvertTo-Json + $encodedTag = [Uri]::EscapeDataString($tag) + $ref = Invoke-WebRequest -Uri "$api/git/ref/tags/$encodedTag" -Headers $headers -SkipHttpErrorCheck + if ($ref.StatusCode -eq 200) { throw 'The release tag already exists.' } + if ($ref.StatusCode -ne 404 -or ($ref.Content | ConvertFrom-Json).message -cne 'Not Found') { throw "Release tag absence request failed: HTTP $($ref.StatusCode)." } $draft = Invoke-RestMethod -Uri "$api/releases" -Headers $headers -Method Post -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($body)) if ($draft.draft -ne $true -or $draft.tag_name -cne $tag -or $draft.target_commitish -cne $env:COMMIT -or $draft.body -cne $env:RELEASE_NOTES -or $draft.prerelease -ne $preview) { throw 'Created draft differs from the approved release identity.' } diff --git a/docs/engineering/quality-gates.md b/docs/engineering/quality-gates.md index 78e0c0c..e8c4a46 100644 --- a/docs/engineering/quality-gates.md +++ b/docs/engineering/quality-gates.md @@ -332,8 +332,15 @@ Publication consumes that run's validated package feed and release-assets artifa The manual release workflow checks candidate provenance, evaluated version, workflow-tree equality, target absence and artifact integrity before publication. A dry run performs those checks without -publication privileges or an environment deployment. Publishing requires the `release` environment -and the maintainer's separate authorization. +publication privileges or an environment deployment. Its release-identity check proves absence of +published releases and the tag, not drafts; the `github-release` job checks drafts with +`contents: write` before creating anything. + +Publishing requires the `release` environment and the maintainer's separate authorization. The +environment binds NuGet.org publication through its Trusted Publishing policy. For GitHub Packages +and GitHub Releases, the gate is procedural: a branch copy of a workflow can request `packages: write` +or `contents: write` with `GITHUB_TOKEN`. The lane therefore dispatches no workflow but master's +`release.yml` for publication. Real-channel acceptance requires every manifest RID's verification leg to succeed against the selected published channel. Feed acceptance uses cold global-tool and DNX acquisition and complete diff --git a/docs/engineering/workflow.md b/docs/engineering/workflow.md index e5e8a33..dff0f11 100644 --- a/docs/engineering/workflow.md +++ b/docs/engineering/workflow.md @@ -85,9 +85,16 @@ irreversible-visibility approval, and verify that channel. Ask separately for Nu with the successful GitHub Packages verification run ID. Ask separately for the GitHub Release with its tag, asset digests, release-notes text and successful NuGet verification run ID. -The lane dispatches the workflow after the word; the maintainer approves the waiting `release` job -in GitHub. The lane never approves deployments, publishes releases or changes package visibility -with its own credentials. +The lane dispatches no workflow but master's `release.yml` for publication after the word; the +maintainer approves the waiting `release` job in GitHub. The `release` environment binds NuGet.org +through its Trusted Publishing policy. Its GitHub Packages and GitHub Releases gate is procedural: +a branch copy of a workflow can request `packages: write` or `contents: write` with `GITHUB_TOKEN`. +The lane never approves deployments, publishes releases or changes package visibility with its own +credentials. + +A dry run proves published-release and tag absence, not draft absence. The `github-release` job +checks drafts with `contents: write` before creating anything; see the +[publication pass](quality-gates.md#publication-pass). Hold workflow-tree changes from candidate selection until release publication. Partial publication blocks promotion. Record push responses and the verified present/missing sets; ask for exactly the From 747d22c2de85e74ace01db19da693879e586b2d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sat, 14 Nov 2026 18:09:29 +0300 Subject: [PATCH 3/5] ci: create release tag atomically before draft --- .github/workflows/release.yml | 17 +++++++++++------ docs/engineering/workflow.md | 7 +++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c4b71b8..f2f32ab 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -59,7 +59,7 @@ jobs: permissions: contents: read actions: read - packages: read + packages: read # GitHub Packages absence check for github-packages and dry-run targets. outputs: feed: ${{ steps.inventory.outputs.feed }} assets: ${{ steps.inventory.outputs.assets }} @@ -250,6 +250,7 @@ jobs: $encoded = [Uri]::EscapeDataString($id) for ($page = 1; ; $page++) { $response = Get-Response "https://api.github.com/orgs/opencode-dotnet/packages/nuget/$encoded/versions?per_page=100&page=$page" $env:API_TOKEN + # Package not found. also covers packages this repository's Actions cannot see. $versions = Read-GitHub $response 'Package not found.' if ($null -eq $versions) { return $false } if ($versions -isnot [array]) { throw 'Malformed GitHub package-version response.' } @@ -291,7 +292,11 @@ jobs: if ($exists) { $present += $names[$i] } else { $missing += $names[$i] } } Write-Output "$feed present: $($present -join ', ')" - Write-Output "$feed missing: $($missing -join ', ')" + $record = if ($feed -ceq 'github-packages') { + "$feed absent as seen by this repository's Actions access: $($missing -join ', ')" + } else { "$feed missing: $($missing -join ', ')" } + Write-Output $record + $record >> $env:GITHUB_STEP_SUMMARY if (@($selected | Where-Object { $present -ccontains $_ }).Count) { throw "$feed already contains a selected version." } $root = $names[-1] if ($selection.Contains($root)) { @@ -530,10 +535,10 @@ jobs: $latest = if ($preview) { 'false' } else { 'true' } $body = @{ tag_name = $tag; target_commitish = $env:COMMIT; name = $tag; body = $env:RELEASE_NOTES; draft = $true; prerelease = $preview; make_latest = $latest; generate_release_notes = $false } | ConvertTo-Json - $encodedTag = [Uri]::EscapeDataString($tag) - $ref = Invoke-WebRequest -Uri "$api/git/ref/tags/$encodedTag" -Headers $headers -SkipHttpErrorCheck - if ($ref.StatusCode -eq 200) { throw 'The release tag already exists.' } - if ($ref.StatusCode -ne 404 -or ($ref.Content | ConvertFrom-Json).message -cne 'Not Found') { throw "Release tag absence request failed: HTTP $($ref.StatusCode)." } + $tagBody = @{ ref = "refs/tags/$tag"; sha = $env:COMMIT } | ConvertTo-Json + $ref = Invoke-WebRequest -Uri "$api/git/refs" -Headers $headers -Method Post -ContentType 'application/json' -Body $tagBody -SkipHttpErrorCheck + if ($ref.StatusCode -eq 422) { throw 'Release tag creation refused: HTTP 422 (the ref may already exist).' } + if ($ref.StatusCode -ne 201) { throw "Release tag creation failed: HTTP $($ref.StatusCode)." } $draft = Invoke-RestMethod -Uri "$api/releases" -Headers $headers -Method Post -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($body)) if ($draft.draft -ne $true -or $draft.tag_name -cne $tag -or $draft.target_commitish -cne $env:COMMIT -or $draft.body -cne $env:RELEASE_NOTES -or $draft.prerelease -ne $preview) { throw 'Created draft differs from the approved release identity.' } diff --git a/docs/engineering/workflow.md b/docs/engineering/workflow.md index dff0f11..27b9c91 100644 --- a/docs/engineering/workflow.md +++ b/docs/engineering/workflow.md @@ -80,6 +80,10 @@ Every feed publication and GitHub Release requires his own word with the exact t commit, Native run ID, version, filenames and digests. Approval of a candidate or dry run authorizes no publication. +Precondition: no `OpenCodeDotNet.Mcp` or `OpenCodeDotNet.Mcp.*` package exists on GitHub Packages +except those `release.yml` published, because the absence check sees only packages this +repository's Actions can access. + Promote GitHub Packages first, make all seven packages public with the maintainer's explicit irreversible-visibility approval, and verify that channel. Ask separately for NuGet.org publication with the successful GitHub Packages verification run ID. Ask separately for the GitHub Release with @@ -102,6 +106,9 @@ missing-file recovery or abandonment. Never retry a push automatically or reuse a published version. Expired candidate artifacts require abandonment and a new version. The `files` input recovers feed pushes only; a partial draft release is left for the maintainer's decision, not automatically resumed or cleaned up. +The release job creates the tag at the candidate commit before creating the draft. A failure after +tag creation leaves the tag (and possibly a draft) for the maintainer's decision; the next attempt +for that version refuses until he decides. No tag is automatically deleted. ## Documentation sessions From 9329a4d82e66d698ba99a4b6b129de4e022f53ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sat, 14 Nov 2026 18:19:51 +0300 Subject: [PATCH 4/5] ci: check the new release tag's commit before creating the draft --- .github/workflows/release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f2f32ab..64d9f5e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -539,6 +539,9 @@ jobs: $ref = Invoke-WebRequest -Uri "$api/git/refs" -Headers $headers -Method Post -ContentType 'application/json' -Body $tagBody -SkipHttpErrorCheck if ($ref.StatusCode -eq 422) { throw 'Release tag creation refused: HTTP 422 (the ref may already exist).' } if ($ref.StatusCode -ne 201) { throw "Release tag creation failed: HTTP $($ref.StatusCode)." } + # The draft binds to whatever commit the tag names, so re-read the new ref just before creating it. + $created = Invoke-RestMethod -Uri "$api/git/ref/tags/$([Uri]::EscapeDataString($tag))" -Headers $headers + if ($created.object.type -cne 'commit' -or $created.object.sha -cne $env:COMMIT) { throw 'The new release tag does not point at the candidate commit.' } $draft = Invoke-RestMethod -Uri "$api/releases" -Headers $headers -Method Post -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($body)) if ($draft.draft -ne $true -or $draft.tag_name -cne $tag -or $draft.target_commitish -cne $env:COMMIT -or $draft.body -cne $env:RELEASE_NOTES -or $draft.prerelease -ne $preview) { throw 'Created draft differs from the approved release identity.' } From 26583a075435f03c224a72e3172712c22b199a3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sat, 14 Nov 2026 18:29:11 +0300 Subject: [PATCH 5/5] ci: check the release tag again right before publishing the draft --- .github/workflows/release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 64d9f5e..ba45efb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -583,6 +583,9 @@ jobs: Remove-Item -LiteralPath $owned -Recurse -Force } $publish = @{ draft = $false; make_latest = $latest } | ConvertTo-Json + # Publication binds the release to the tag's commit at this moment, so check the tag again first. + $beforePublish = Invoke-RestMethod -Uri "$api/git/ref/tags/$([Uri]::EscapeDataString($tag))" -Headers $headers + if ($beforePublish.object.type -cne 'commit' -or $beforePublish.object.sha -cne $env:COMMIT) { throw 'The release tag no longer points at the candidate commit; the draft is left unpublished.' } $release = Invoke-RestMethod -Uri "$api/releases/$($draft.id)" -Headers $headers -Method Patch -ContentType 'application/json' -Body $publish $confirmed = Invoke-RestMethod -Uri "$api/releases/$($draft.id)" -Headers $headers if ($release.draft -ne $false -or $confirmed.draft -ne $false -or $confirmed.tag_name -cne $tag -or