feat(tools): add tbd_ship — CI-gated trunk-based ship (#40)
An intent verb for the trunk-based loop: branch from base → write the file → open a PR → auto-merge (squash) → delete the branch. One call instead of orchestrating file_write_branch + pr_create + workflow_run_status + pr_merge + branch_delete and remembering the conventions each time. The load-bearing safety is a pure, fail-closed CI gate (evaluateShipGate): merge=true ONLY when every workflow run for the PR head commit is completed+success AND the base branch is not review-protected. Every other state — CI pending / red / absent, review-required base, or an unclean merge — fails closed to PR-only and returns the PR with a reason. A change with no CI gate is never auto-merged to trunk (cf. agentsquad#36: non-compiling code reviewer-approved straight to main with no CI wall). - ci_timeout_seconds polls the head commit's runs to completion (default 0 = snapshot, returns pending right after opening the PR). - Derives a deterministic short-lived branch (tbd/<slug>-<hash>); handles new and existing files (fetches the blob sha for updates). - Adds head.sha + mergeable to the PR struct. - Tests: full gate matrix (green/pending/red/cancelled/none/mixed/protected) + Call happy-merge, no-CI fail-closed, red fail-closed, allowlist. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
package tools_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"git.d-ma.be/mathias/gitea-mcp/internal/allowlist"
|
||||
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
|
||||
"git.d-ma.be/mathias/gitea-mcp/internal/tools"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// shipFake serves the whole tbd_ship flow; runsJSON is the workflow_runs array
|
||||
// for the head commit, letting each test drive the CI gate.
|
||||
func shipFake(t *testing.T, runsJSON string, merged, deleted *atomic.Bool) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == http.MethodGet && strings.Contains(p, "/branch_protections/"):
|
||||
w.WriteHeader(http.StatusNotFound) // unprotected
|
||||
_, _ = w.Write([]byte(`{"message":"not found"}`))
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(p, "/branches"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"name":"tbd/x","commit":{"id":"abc"}}`))
|
||||
case r.Method == http.MethodGet && strings.Contains(p, "/contents/"):
|
||||
w.WriteHeader(http.StatusNotFound) // new file
|
||||
_, _ = w.Write([]byte(`{"message":"not found"}`))
|
||||
case (r.Method == http.MethodPost || r.Method == http.MethodPut) && strings.Contains(p, "/contents/"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"content":{"path":"x","sha":"s"},"commit":{"sha":"c"}}`))
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"number":7,"title":"t","html_url":"http://x/pulls/7","state":"open","head":{"ref":"tbd/x","sha":"abc"},"base":{"ref":"main"}}`))
|
||||
case r.Method == http.MethodGet && strings.Contains(p, "/actions/runs"):
|
||||
_, _ = w.Write([]byte(`{"total_count":0,"workflow_runs":` + runsJSON + `}`))
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls/7/merge"):
|
||||
merged.Store(true)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
case r.Method == http.MethodDelete && strings.Contains(p, "/branches/"):
|
||||
deleted.Store(true)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
default:
|
||||
t.Errorf("unexpected request: %s %s", r.Method, p)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func callShip(t *testing.T, srvURL, args string) map[string]any {
|
||||
t.Helper()
|
||||
tool := tools.NewTBDShip(gitea.NewClient(srvURL, "tok"), allowlist.New([]string{"mathias"}))
|
||||
out, err := tool.Call(context.Background(), json.RawMessage(args))
|
||||
require.NoError(t, err)
|
||||
var res map[string]any
|
||||
require.NoError(t, json.Unmarshal(out, &res))
|
||||
return res
|
||||
}
|
||||
|
||||
// Green CI + unprotected base → squash-merge + branch deleted.
|
||||
func TestTBDShip_GreenCI_Merges(t *testing.T) {
|
||||
var merged, deleted atomic.Bool
|
||||
srv := shipFake(t, `[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]`, &merged, &deleted)
|
||||
defer srv.Close()
|
||||
|
||||
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
||||
|
||||
assert.Equal(t, true, res["merged"])
|
||||
assert.Equal(t, "success", res["ci_status"])
|
||||
assert.Equal(t, float64(7), res["pr_number"])
|
||||
assert.True(t, merged.Load(), "merge endpoint must be called")
|
||||
assert.True(t, deleted.Load(), "branch must be deleted after merge")
|
||||
}
|
||||
|
||||
// No CI runs for the head commit → fail closed: PR opened, NOT merged.
|
||||
func TestTBDShip_NoCI_FailsClosed(t *testing.T) {
|
||||
var merged, deleted atomic.Bool
|
||||
srv := shipFake(t, `[]`, &merged, &deleted)
|
||||
defer srv.Close()
|
||||
|
||||
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
||||
|
||||
assert.Equal(t, false, res["merged"])
|
||||
assert.Equal(t, "none", res["ci_status"])
|
||||
assert.NotEmpty(t, res["reason"])
|
||||
assert.False(t, merged.Load(), "merge must NOT be called when there is no CI")
|
||||
assert.Equal(t, float64(7), res["pr_number"], "PR is still opened for manual merge")
|
||||
}
|
||||
|
||||
// Red CI → fail closed.
|
||||
func TestTBDShip_RedCI_FailsClosed(t *testing.T) {
|
||||
var merged, deleted atomic.Bool
|
||||
srv := shipFake(t, `[{"id":1,"status":"completed","conclusion":"failure","head_sha":"abc"}]`, &merged, &deleted)
|
||||
defer srv.Close()
|
||||
|
||||
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
||||
|
||||
assert.Equal(t, false, res["merged"])
|
||||
assert.Equal(t, "failed", res["ci_status"])
|
||||
assert.False(t, merged.Load(), "merge must NOT be called when CI is red")
|
||||
}
|
||||
|
||||
func TestTBDShip_AllowlistRejects(t *testing.T) {
|
||||
tool := tools.NewTBDShip(gitea.NewClient("http://unused", ""), allowlist.New([]string{"mathias"}))
|
||||
_, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"evil","repo":"r","path":"p","content":"c","message":"m"}`))
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user