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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ jobs:
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Guard against self-vouching before executing repository tooling
- name: Gather the group's facts
id: guard
env:
QUEUE_REF: ${{ github.ref }}
Expand All @@ -140,12 +140,9 @@ jobs:
reason="unavailable guard facts"
else
gather base-tree git rev-parse "$QUEUE_BASE^{tree}" || true
shopt -s nocasematch
while IFS= read -r -d '' path; do
case "$path" in
.github/* | tools/* | Directory.Build.props | */Directory.Build.props | Directory.Build.targets | */Directory.Build.targets | Directory.Packages.props | */Directory.Packages.props | Directory.Build.rsp | */Directory.Build.rsp | global.json | */global.json | nuget.config | */nuget.config) reason="rule 5: guarded path" ;;
esac
done < "$facts/changed-paths"
if ! git worktree add --detach "$RUNNER_TEMP/judge" "$QUEUE_BASE"; then
reason="unavailable judge"
fi
fi
if [ -n "$reason" ]; then
printf 'reuse=false\nreason=%s\nblocked=true\n' "$reason" >> "$GITHUB_OUTPUT"
Expand All @@ -155,7 +152,7 @@ jobs:
if: steps.guard.outputs.blocked != 'true'
uses: actions/setup-dotnet@v6
with:
global-json-file: global.json
global-json-file: ${{ runner.temp }}/judge/global.json
dotnet-version: 10.0.x
- name: Gather GitHub facts
id: facts
Expand Down Expand Up @@ -183,6 +180,7 @@ jobs:
- name: Decide reuse
id: decide
if: steps.guard.outputs.blocked != 'true'
working-directory: ${{ runner.temp }}/judge
env:
REUSED_RUN: ${{ steps.facts.outputs.link }}
run: |
Expand Down
14 changes: 8 additions & 6 deletions docs/engineering/quality-gates.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,14 @@ attempt's successful `CI result` only with recorded proof of the exact same tree
two parents, its second parent is still the queued PR's head, and that PR targets `master`.
The attempt's unique, unexpired `tested-tree-<run_attempt>` artifact must record the group's tree
and the same base tree its diff uses, and have been created within that attempt's successful
`Changes` job window. The PR's changes
from its merge base must touch neither `.github/` nor `tools/`, nor any `Directory.Build.props`,
`Directory.Build.targets`, `Directory.Packages.props`, `Directory.Build.rsp`, `global.json` or
`nuget.config` at any depth, matched case-insensitively. The workflow checks this guard before executing repository tooling.
In practice, a PR whose base has not moved since its green run and which does not touch CI or the
tool avoids the second full run. Any missing, malformed or uncertain fact, or a failed reuse job,
`Changes` job window. The decision is built and run from the merge group's base commit, in a
separate worktree outside the workspace, with the base's own `global.json`, so a PR is judged by
the base's tool and the base's rules, never its own. The PR's changes from its merge base must not
touch `.github/`, matched case-insensitively, because the workflow that gathers the facts and calls
the judge always comes from the group's tree; review covers a workflow change, as for any required
check.
In practice, a PR whose base has not moved since its green run and which does not touch `.github/`
avoids the second full run. Any missing, malformed or uncertain fact, or a failed reuse job,
means the normal full CI runs. `Changes` must still succeed; the reuse branch of `CI result`
accepts only a merge group with all four heavy jobs skipped.

Expand Down
4 changes: 2 additions & 2 deletions docs/engineering/workflow.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Repository Workflow

Date: 2026-11-09
Date: 2026-11-14

Canonical working agreements for research, implementation, temporary work, verification, and Git
history.
Expand Down Expand Up @@ -89,7 +89,7 @@ single-owner rules.
`master` requires the queue and the `CI result` check, for administrators too.
- A pull request joins the queue 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, except when the recorded tested-tree proof and self-vouching guard in `quality-gates.md`
green, except when the recorded tested-tree proof and the base-commit judge in `quality-gates.md`
permit reuse of its green PR result. Otherwise the repository guards count exactly over every
test file, so 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,21 @@ public sealed class MergeGroupReuseCommandTests
[Arguments("expired-artifact", "rule 4: unproven tree")]
[Arguments("failed-changes", "rule 4: unproven tree")]
[Arguments(".github/workflows/ci.yml", "rule 5: guarded path")]
[Arguments("tools/example.cs", "rule 5: guarded path")]
[Arguments("tools/Directory.Build.props", "rule 5: guarded path")]
[Arguments("global.json", "rule 5: guarded path")]
[Arguments("nested/Directory.Build.targets", "rule 5: guarded path")]
[Arguments("nested/Directory.Packages.props", "rule 5: guarded path")]
[Arguments("nested/Directory.Build.rsp", "rule 5: guarded path")]
[Arguments("nested/nuget.config", "rule 5: guarded path")]
[Arguments("nested/NuGet.Config", "rule 5: guarded path")]
[Arguments("nested/Global.json", "rule 5: guarded path")]
[Arguments("nested/directory.build.props", "rule 5: guarded path")]
[Arguments("tools/example.cs", "all rules hold")]
[Arguments("tools/Directory.Build.props", "all rules hold")]
[Arguments("global.json", "all rules hold")]
[Arguments("Directory.Packages.props", "all rules hold")]
[Arguments("nested/Directory.Build.targets", "all rules hold")]
[Arguments("nested/Directory.Packages.props", "all rules hold")]
[Arguments("nested/Directory.Build.rsp", "all rules hold")]
[Arguments("nested/nuget.config", "all rules hold")]
[Arguments("nested/NuGet.Config", "all rules hold")]
[Arguments("nested/Global.json", "all rules hold")]
[Arguments("nested/directory.build.props", "all rules hold")]
[Arguments(".GITHUB/workflows/ci.yml", "rule 5: guarded path")]
[Arguments("TOOLS/example.cs", "rule 5: guarded path")]
[Arguments("TOOLS/example.cs", "all rules hold")]
[Arguments("tools/example.cs+different-tree", "rule 4: unproven tree")]
[Arguments("Directory.Packages.props+different-base-tree", "rule 4: unproven tree")]
[Arguments("malformed", "malformed facts")]
[Arguments("missing", "unreadable facts")]
public async Task Execute_Should_Write_The_Decision_And_Reason(string row, string reason, CancellationToken cancellationToken)
Expand All @@ -67,11 +70,18 @@ public async Task Execute_Should_Write_The_Decision_And_Reason(string row, strin

await Assert.That(exitCode).IsEqualTo(0);
await Assert.That(await fileSystem.File.ReadAllTextAsync("output", cancellationToken)).IsEqualTo(
$"reuse={(row == "all" ? "true" : "false")}\nreason={reason}\n");
$"reuse={(reason == "all rules hold" ? "true" : "false")}\nreason={reason}\n");
}

private static void ApplyRow(Dictionary<string, string> facts, string row)
{
var parts = row.Split('+');
if (parts.Length == 2)
{
facts["changed-paths"] = parts[0] + '\0';
row = parts[1];
}

// These documents are built below with non-null arrays and members.
var runs = JsonNode.Parse(facts["runs.json"])!["workflow_runs"]!.AsArray();
var jobs = JsonNode.Parse(facts["jobs.json"])!["jobs"]!.AsArray();
Expand All @@ -80,7 +90,7 @@ private static void ApplyRow(Dictionary<string, string> facts, string row)
facts["runs.json"] = new JsonObject { ["workflow_runs"] = runs.DeepClone() }.ToJsonString();
facts["jobs.json"] = new JsonObject { ["jobs"] = jobs.DeepClone() }.ToJsonString();
facts["artifacts.json"] = new JsonObject { ["artifacts"] = artifacts.DeepClone() }.ToJsonString();
if (row.Contains('/', StringComparison.Ordinal) || row == "global.json")
if (row.Contains('/', StringComparison.Ordinal) || row is "global.json" or "Directory.Packages.props")
{
facts["changed-paths"] = row + '\0';
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Text.RegularExpressions;
using OpenCode.Sdk.Tools.Tests.RepositoryGates.Support;
using OpenCode.Sdk.Tools.Tests.Support;
using Testably.Abstractions;
using TUnit.Assertions.Enums;
Expand All @@ -13,11 +13,12 @@ public sealed class CiBenchmarkGuardTests
[Test]
public async Task Ci_Should_Keep_The_Ordered_Sdk_Dry_Commands()
{
var workflow = await WorkflowAsync();
await Assert.That(Job(workflow, "build-and-test")).DoesNotContain("--job Dry");
await Assert.That(Job(workflow, "publish-nightly")).Contains("needs: [lint, build-and-test, benchmark-sdk]");
await Assert.That(Job(workflow, "publish-nightly")).Contains("if: ${{ !cancelled() && github.ref == 'refs/heads/master' && github.event_name == 'push' && needs.lint.result == 'success' && needs.build-and-test.result == 'success' && needs.benchmark-sdk.result == 'success' }}");
var matrix = Job(workflow, "benchmark-sdk");
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
await Assert.That(CiWorkflow.Job(workflow, "build-and-test")).DoesNotContain("--job Dry");
await Assert.That(CiWorkflow.Job(workflow, "publish-nightly")).Contains("needs: [lint, build-and-test, benchmark-sdk]");
await Assert.That(CiWorkflow.Job(workflow, "publish-nightly")).Contains("if: ${{ !cancelled() && github.ref == 'refs/heads/master' && github.event_name == 'push' && needs.lint.result == 'success' && needs.build-and-test.result == 'success' && needs.benchmark-sdk.result == 'success' }}");
var matrix = CiWorkflow.Job(workflow, "benchmark-sdk");
await Assert.That(matrix).Contains("needs: [changes, reuse]");
await Assert.That(matrix).Contains("if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.benchmarks == 'true' && !(needs.reuse.result == 'success' && needs.reuse.outputs.reuse == 'true') }}");
await Assert.That(matrix).Contains("fail-fast: false");
Expand All @@ -42,7 +43,9 @@ await Assert.That(matrix.Split('\n').Select(static line => line.Trim()).Where(st
[Test]
public async Task Ci_Should_Run_Cold_Start_Once_On_The_Net10_Leg()
{
var matrix = Job(await WorkflowAsync(), "benchmark-sdk");
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
var matrix = CiWorkflow.Job(workflow, "benchmark-sdk");
await Assert.That(matrix).Contains(" - name: SDK cold start (net10)\n");
var start = matrix.IndexOf(" - name: SDK cold start (net10)\n", StringComparison.Ordinal);
var end = matrix.IndexOf("\n - name: ", start + 1, StringComparison.Ordinal);
Expand All @@ -57,7 +60,9 @@ public async Task Ci_Should_Run_Cold_Start_Once_On_The_Net10_Leg()
[Test]
public async Task Ci_Should_Run_Generator_Stages_In_Their_Own_Job_Without_Runtimes()
{
var stage = Job(await WorkflowAsync(), "benchmark-generator-stage");
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
var stage = CiWorkflow.Job(workflow, "benchmark-generator-stage");
await Assert.That(stage).Contains("needs: [changes, reuse]");
await Assert.That(stage).Contains("if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.benchmarks-generator == 'true' && !(needs.reuse.result == 'success' && needs.reuse.outputs.reuse == 'true') }}");
await Assert.That(stage).Contains("- name: Generator stages\n");
Expand All @@ -79,7 +84,9 @@ await Assert.That(Commands(stage)).IsEquivalentTo([
[Test]
public async Task Ci_Should_Bound_Every_Dry_Step()
{
var timeouts = DrySteps(await WorkflowAsync()).Select(static step =>
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
var timeouts = DrySteps(workflow).Select(static step =>
step.Split('\n').SingleOrDefault(static line => line.TrimStart().StartsWith("timeout-minutes:", StringComparison.Ordinal))?.Trim() ?? "<missing>");
await Assert.That(timeouts).IsEquivalentTo([
"timeout-minutes: 20", "timeout-minutes: 20",
Expand All @@ -89,8 +96,9 @@ await Assert.That(timeouts).IsEquivalentTo([
[Test]
public async Task Ci_Should_Require_The_Stage_Result_Only_When_Selected()
{
var workflow = await WorkflowAsync();
var changes = Job(workflow, "changes");
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
var changes = CiWorkflow.Job(workflow, "changes");
await Assert.That(changes).Contains("benchmarks: ${{ steps.diff.outputs.benchmarks }}");
await Assert.That(changes).Contains("echo \"benchmarks=true\" >> \"$GITHUB_OUTPUT\"");
await Assert.That(changes).Contains("src/* | tools/OpenCode.Sdk.Tools/* | tools/curation.json | tools/generation-profile.txt | spec/* | tests/OpenCode.Sdk.Performance.Tests/* | tests/Shared/BenchmarkExitPolicy.cs | tests/Shared/GeneratorPeakMemoryPolicy.cs | tests/Directory.Build.props | Directory.Build.props | Directory.Build.targets | Directory.Packages.props | global.json | nuget.config | .github/workflows/ci.yml) benchmarks=true ;;");
Expand All @@ -100,7 +108,7 @@ public async Task Ci_Should_Require_The_Stage_Result_Only_When_Selected()
await Assert.That(changes).Contains("benchmarks_generator=false");
await Assert.That(changes).Contains(" tools/* | tests/OpenCode.Sdk.Tools.Tests/* | tests/OpenCode.Sdk.Performance.Tests/* | spec/* | tests/Shared/BenchmarkExitPolicy.cs | tests/Shared/GeneratorPeakMemoryPolicy.cs | tests/Directory.Build.props | Directory.Build.props | Directory.Build.targets | Directory.Packages.props | global.json | nuget.config | .github/workflows/ci.yml) benchmarks_generator=true ;;");
await Assert.That(changes).Contains("echo \"benchmarks-generator=$benchmarks_generator\" >> \"$GITHUB_OUTPUT\"");
var aggregate = Job(workflow, "ci-result");
var aggregate = CiWorkflow.Job(workflow, "ci-result");
await Assert.That(aggregate).Contains("needs: [changes, reuse, lint, build-and-test, benchmark-sdk, benchmark-generator-stage]");
await Assert.That(aggregate).Contains("SDK_BENCHMARKS: ${{ needs.changes.outputs.benchmarks }}");
await Assert.That(aggregate).Contains("SDK: ${{ needs.benchmark-sdk.result }}");
Expand All @@ -124,16 +132,6 @@ await Assert.That(aggregate).Contains("""
""");
}

private static async Task<string> WorkflowAsync()
{
var fileSystem = new RealFileSystem();
return (await fileSystem.File.ReadAllTextAsync(fileSystem.Path.Combine(new RepositoryRoot(fileSystem).Locate(), ".github", "workflows", "ci.yml")))
.ReplaceLineEndings("\n");
}

private static string Job(string workflow, string name) =>
Regex.Match(workflow, $@"(?ms)^ {Regex.Escape(name)}:\n.*?(?=^ \S|\z)", RegexOptions.None, Regex.InfiniteMatchTimeout).Value;

private static IEnumerable<string> DrySteps(string workflow) =>
workflow.Split(" - name: ", StringSplitOptions.None).Where(static step => step.Contains("--job Dry", StringComparison.Ordinal));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using OpenCode.Sdk.Tools.Tests.RepositoryGates.Support;
using OpenCode.Sdk.Tools.Tests.Support;
using Testably.Abstractions;
using TUnit.Assertions.Enums;

namespace OpenCode.Sdk.Tools.Tests.RepositoryGates;

public sealed class CiMergeGroupReuseTests
{
[Test]
public async Task Ci_Should_Build_And_Run_The_Reuse_Judge_From_The_Base_Worktree()
{
var fileSystem = new RealFileSystem();
var workflow = await new CiWorkflow(fileSystem).ReadAsync(new RepositoryRoot(fileSystem).Locate());
var reuse = CiWorkflow.Job(workflow, "reuse");
await Assert.That(reuse).Contains("QUEUE_BASE: ${{ github.event.merge_group.base_sha }}");
await Assert.That(reuse).Contains("if ! git worktree add --detach \"$RUNNER_TEMP/judge\" \"$QUEUE_BASE\"; then");
var steps = reuse.Split(" - name: ", StringSplitOptions.None);
var dotnetSteps = steps.Where(static step => step.Split('\n').Select(static line => line.TrimStart())
.Any(static line => line.StartsWith("dotnet ", StringComparison.Ordinal) || line.StartsWith("run: dotnet ", StringComparison.Ordinal)))
.Select(static step => step[..step.IndexOf('\n', StringComparison.Ordinal)]);
await Assert.That(dotnetSteps).IsEquivalentTo(["Decide reuse"], CollectionOrdering.Matching);
var setup = steps.Single(static step => step.StartsWith("Setup .NET SDK\n", StringComparison.Ordinal));
await Assert.That(setup).Contains("global-json-file: ${{ runner.temp }}/judge/global.json");
var decide = steps.Single(static step => step.StartsWith("Decide reuse\n", StringComparison.Ordinal));
await Assert.That(decide).Contains("working-directory: ${{ runner.temp }}/judge");
await Assert.That(decide.Split('\n').Select(static line => line.Trim()).Where(static line => line.StartsWith("dotnet ", StringComparison.Ordinal)))
.IsEquivalentTo(["dotnet run --file tools/opencode-tool.cs -- merge-group-reuse --facts \"$RUNNER_TEMP/reuse\" --output \"$GITHUB_OUTPUT\""], CollectionOrdering.Matching);
await Assert.That(reuse).DoesNotContain("GITHUB_WORKSPACE");
await Assert.That(reuse).DoesNotContain("github.workspace");

var permissions = reuse.Split('\n').SkipWhile(static line => line != " permissions:").Skip(1)
.TakeWhile(static line => line.StartsWith(" ", StringComparison.Ordinal)).Select(static line => line.Trim());
await Assert.That(permissions).IsEquivalentTo([
"contents: read", "actions: read", "pull-requests: read",
], CollectionOrdering.Matching);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.IO.Abstractions;
using System.Text.RegularExpressions;

namespace OpenCode.Sdk.Tools.Tests.RepositoryGates.Support;

internal sealed class CiWorkflow(IFileSystem fileSystem)
{
public async Task<string> ReadAsync(string root) =>
(await fileSystem.File.ReadAllTextAsync(fileSystem.Path.Combine(root, ".github", "workflows", "ci.yml")))
.ReplaceLineEndings("\n");

public static string Job(string workflow, string name) =>
Regex.Match(workflow, $@"(?ms)^ {Regex.Escape(name)}:\n.*?(?=^ \S|\z)", RegexOptions.None, Regex.InfiniteMatchTimeout).Value;
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ private static bool ProvenanceHolds(IReadOnlyDictionary<string, string> facts, J
}

private static bool IsGuarded(string path) =>
path.StartsWith(".github/", StringComparison.OrdinalIgnoreCase) || path.StartsWith("tools/", StringComparison.OrdinalIgnoreCase) ||
path.Split('/')[^1].ToUpperInvariant() is "DIRECTORY.BUILD.PROPS" or "DIRECTORY.BUILD.TARGETS" or "DIRECTORY.PACKAGES.PROPS" or
"DIRECTORY.BUILD.RSP" or "GLOBAL.JSON" or "NUGET.CONFIG";
path.StartsWith(".github/", StringComparison.OrdinalIgnoreCase);

private static bool IsHash(string value) => value.Trim().Length == 40 && value.Trim().All(char.IsAsciiHexDigit);
private static string? Text(JsonElement element, string name) => element.GetProperty(name).GetString();
Expand Down
Loading