Compare commits

...
6 Commits
Author SHA1 Message Date
mathiasandClaude Opus 4.8 8ebad95adf feat(tools): add tbd_ship — CI-gated trunk-based ship (#40)
CD / Build & Import (push) Has been skipped
CD / Lint / Test / Vet (push) Failing after 5s
CD / Deploy via GitOps (push) Has been skipped
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>
2026-07-04 00:40:02 +02:00
mathiasandClaude Opus 4.8 169040c073 chore(context): re-sync adapters from root AGENT.md (skills → mathias/skills repo)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 00:39:35 +02:00
mathiasandClaude Opus 4.8 834a994af9 chore(housekeeping): canonical git.d-ma.be host + honest version string
CD / Lint / Test / Vet (push) Successful in 6s
CD / Build & Import (push) Successful in 21s
CD / Deploy via GitOps (push) Has been skipped
- Dockerfile: GOPRIVATE and the http→https insteadOf rewrite now name
  git.d-ma.be (was the pre-rename gitea.d-ma.be; masked at build time only by
  GOPROXY=direct + GOSUMDB=off).
- .context/PROJECT.md Repo URL → git.d-ma.be, adapters regenerated
  (CLAUDE.md, AGENTS.md, .cursorrules, .aider.conventions.md, system-prompt.txt).
- main.go: version is now a `-ldflags -X main.version` overridable var defaulting
  to "dev" instead of a hardcoded, drifting "0.1.0".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:58:34 +02:00
mathiasandClaude Opus 4.8 0a12e905c9 fix(create_project): drop defunct hyperguild new-project from finalize guidance (#46)
CD / Deploy via GitOps (push) Has been skipped
CD / Lint / Test / Vet (push) Successful in 7s
CD / Build & Import (push) Successful in 22s
The infra#179 partial_failure message and the tool descriptor told callers to
"Finalize locally with `hyperguild new-project`" — but that command does not
exist (the hyperguild CLI only has tier/brain/mode; it was specced, never built).
It pointed users at a dead end.

Extracted the message into a pure infra179FinalizeMessage() and reworded it to
name the actual remaining work — cloning the repo and substituting the leftover
__PROJECT_NAME__ / __MODULE_PATH__ placeholders, or retrying — with no reference
to any scaffolding CLI. Descriptor updated to match. Unit-tested the wording.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:45:25 +02:00
mathiasandClaude Opus 4.8 72ba89be63 feat(auth): adopt chassis v0.3.0 — auth audit logs + 503 on Dex outage (#6, #9)
CD / Build & Import (push) Successful in 22s
CD / Lint / Test / Vet (push) Successful in 7s
CD / Deploy via GitOps (push) Has been skipped
Bumps mcp-chassis to v0.3.0, which adds structured audit logging on every auth
rejection and returns 503 temporarily_unavailable (not a silent 401) when Dex is
unreachable at validation time. Wires slog.SetDefault so those audit lines flow
through gitea-mcp's JSON handler.

Together with the earlier /healthz jwt-status reporting and startup degradation
warning, this closes #6 (Dex-down is now observable and distinct from a bad
token) and #9 (auth failures are audit-logged: reason, IP, token type, hashed
fingerprint — never the raw token).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:17:39 +02:00
mathiasandClaude Opus 4.8 9b7f53bdda feat(auth): document caller header precedence + warn on conflict (#10)
CallerMiddleware silently preferred X-Auth-Request-User over X-Forwarded-User
with no explanation and no signal when both were set. Documented the precedence
(X-Auth-Request-User is the verified OIDC identity oauth2-proxy sets, so it is
authoritative; X-Forwarded-User is a fallback), and it now takes a *slog.Logger
and warns when both headers are present and disagree, so a proxy
misconfiguration is visible instead of silently resolved. Table-driven tests
cover precedence (both/single/none) and the conflict-warning path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 22:57:24 +02:00
20 changed files with 604 additions and 38 deletions
+2 -2
View File
@@ -263,7 +263,7 @@ unconditionally on every host, every harness.
## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list.
Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Clone it to `~/dev/skills/` and run `SKILLS_CHECKOUT_DIR="$PWD" bash install.sh` there to wire every skill into your harnesses (Claude Code, Crush, Antigravity, Mistral Vibe) as native, on-demand skills. (Use `install.sh`, not `task install` — the latter is currently broken, skills#7.) Load at task start — not "on demand" but on schedule, before writing code. Browse `~/dev/skills/SKILLS_INDEX.md` for the full list.
**Skill trigger table — load before starting, not after getting stuck:**
@@ -288,7 +288,7 @@ Shared engineering skills are available in `~/dev/.skills/`. Load at task start
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+1 -1
View File
@@ -9,7 +9,7 @@
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+2 -2
View File
@@ -268,7 +268,7 @@ unconditionally on every host, every harness.
## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list.
Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Clone it to `~/dev/skills/` and run `SKILLS_CHECKOUT_DIR="$PWD" bash install.sh` there to wire every skill into your harnesses (Claude Code, Crush, Antigravity, Mistral Vibe) as native, on-demand skills. (Use `install.sh`, not `task install` — the latter is currently broken, skills#7.) Load at task start — not "on demand" but on schedule, before writing code. Browse `~/dev/skills/SKILLS_INDEX.md` for the full list.
**Skill trigger table — load before starting, not after getting stuck:**
@@ -293,7 +293,7 @@ Shared engineering skills are available in `~/dev/.skills/`. Load at task start
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+2 -2
View File
@@ -266,7 +266,7 @@ unconditionally on every host, every harness.
## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list.
Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Clone it to `~/dev/skills/` and run `SKILLS_CHECKOUT_DIR="$PWD" bash install.sh` there to wire every skill into your harnesses (Claude Code, Crush, Antigravity, Mistral Vibe) as native, on-demand skills. (Use `install.sh`, not `task install` — the latter is currently broken, skills#7.) Load at task start — not "on demand" but on schedule, before writing code. Browse `~/dev/skills/SKILLS_INDEX.md` for the full list.
**Skill trigger table — load before starting, not after getting stuck:**
@@ -291,7 +291,7 @@ Shared engineering skills are available in `~/dev/.skills/`. Load at task start
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+2 -2
View File
@@ -263,7 +263,7 @@ unconditionally on every host, every harness.
## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list.
Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Clone it to `~/dev/skills/` and run `SKILLS_CHECKOUT_DIR="$PWD" bash install.sh` there to wire every skill into your harnesses (Claude Code, Crush, Antigravity, Mistral Vibe) as native, on-demand skills. (Use `install.sh`, not `task install` — the latter is currently broken, skills#7.) Load at task start — not "on demand" but on schedule, before writing code. Browse `~/dev/skills/SKILLS_INDEX.md` for the full list.
**Skill trigger table — load before starting, not after getting stuck:**
@@ -288,7 +288,7 @@ Shared engineering skills are available in `~/dev/.skills/`. Load at task start
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+1 -1
View File
@@ -9,7 +9,7 @@
- **Name**: gitea-mcp
- **Owner**: Mathias
- **Client**: personal
- **Repo**: https://gitea.d-ma.be/mathias/gitea-mcp
- **Repo**: https://git.d-ma.be/mathias/gitea-mcp
- **Status**: active
## Stack
+3 -3
View File
@@ -1,13 +1,13 @@
FROM golang:1.26-alpine AS build
WORKDIR /src
# Fetch internal gitea-hosted Go modules (e.g. mcp-chassis) without going
# Fetch internal git-hosted Go modules (e.g. mcp-chassis) without going
# through proxy.golang.org and without HTTP→HTTPS surprises. Gitea returns
# http:// in its go-import meta tag, so rewrite to https here and bypass
# the module proxy + sumdb.
RUN apk add --no-cache git && \
git config --global url."https://gitea.d-ma.be/".insteadOf "http://gitea.d-ma.be/"
ENV GOPRIVATE=gitea.d-ma.be
git config --global url."https://git.d-ma.be/".insteadOf "http://git.d-ma.be/"
ENV GOPRIVATE=git.d-ma.be
ENV GOPROXY=direct
ENV GOSUMDB=off
+10 -2
View File
@@ -18,8 +18,16 @@ import (
"git.d-ma.be/mathias/gitea-mcp/internal/tools"
)
// version is the build version, overridable via -ldflags "-X main.version=<tag>".
// Defaults to "dev" for local / un-stamped builds (was a hardcoded, drifting
// "0.1.0" — it now tells the truth instead of a stale literal).
var version = "dev"
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Route the chassis's package-level slog (auth audit logs, gitea-mcp#9) through
// the same structured handler as the rest of the server.
slog.SetDefault(logger)
cfg, err := config.Load()
if err != nil {
@@ -56,7 +64,7 @@ func main() {
mux := http.NewServeMux()
mux.Handle("/mcp", mcp.OriginAllowlist(cfg.OriginAllowlist)(
chassisauth.BearerMiddleware(cfg.StaticToken, jwtValidator, "gitea", resourceMetadataURL,
auth.CallerMiddleware(mcpSrv),
auth.CallerMiddleware(logger, mcpSrv),
),
))
mux.Handle("/healthz", newHealthzHandler(cfg.DexIssuerURL != "", jwtValidator != nil, jwtInitErr))
@@ -66,7 +74,7 @@ func main() {
}
addr := ":" + cfg.Port
logger.Info("gitea-mcp starting", "addr", addr, "version", "0.1.0")
logger.Info("gitea-mcp starting", "addr", addr, "version", version)
if err := http.ListenAndServe(addr, mux); err != nil {
logger.Error("server stopped", "err", err)
os.Exit(1)
+1 -1
View File
@@ -3,7 +3,7 @@ module git.d-ma.be/mathias/gitea-mcp
go 1.26.2
require (
git.d-ma.be/mathias/mcp-chassis v0.2.0
git.d-ma.be/mathias/mcp-chassis v0.3.0
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/stretchr/testify v1.11.1
)
+2 -2
View File
@@ -1,5 +1,5 @@
git.d-ma.be/mathias/mcp-chassis v0.2.0 h1:6fLmb7xqRa2nNVWsHaUbbfbArgDXJw/gDhb09clBIjo=
git.d-ma.be/mathias/mcp-chassis v0.2.0/go.mod h1:Ks7EK2UnGAN0H3rJjKUxUagX8/ZBdtLrOlcUbv0RwH8=
git.d-ma.be/mathias/mcp-chassis v0.3.0 h1:lV/vDsjrDeZojT7lhcwolM1lMZpsnEKEvf4kEHrxIa0=
git.d-ma.be/mathias/mcp-chassis v0.3.0/go.mod h1:Ks7EK2UnGAN0H3rJjKUxUagX8/ZBdtLrOlcUbv0RwH8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+26 -3
View File
@@ -2,17 +2,40 @@ package auth
import (
"context"
"log/slog"
"net/http"
)
type ctxKey struct{}
func CallerMiddleware(next http.Handler) http.Handler {
// CallerMiddleware extracts the authenticated username from the reverse-proxy
// identity headers and stashes it in the request context for Caller().
//
// Header precedence: X-Auth-Request-User takes priority over X-Forwarded-User.
// X-Auth-Request-User is the header oauth2-proxy sets from the *verified* OIDC
// identity, so it is authoritative. X-Forwarded-User is a weaker, proxy-set
// convention some setups populate instead; it is used only as a fallback when
// X-Auth-Request-User is absent. If a proxy sets BOTH and they disagree, the
// verified X-Auth-Request-User still wins and we log a warning so the
// misconfiguration is visible rather than silently resolved (#10).
//
// logger may be nil, in which case the conflict warning is skipped.
func CallerMiddleware(logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("X-Auth-Request-User")
authUser := r.Header.Get("X-Auth-Request-User")
fwdUser := r.Header.Get("X-Forwarded-User")
user := authUser
if user == "" {
user = r.Header.Get("X-Forwarded-User")
user = fwdUser
}
if logger != nil && authUser != "" && fwdUser != "" && authUser != fwdUser {
logger.Warn("conflicting caller identity headers; using X-Auth-Request-User",
"x_auth_request_user", authUser,
"x_forwarded_user", fwdUser)
}
ctx := context.WithValue(r.Context(), ctxKey{}, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
+63 -9
View File
@@ -1,7 +1,9 @@
package auth_test
import (
"bytes"
"context"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
@@ -10,17 +12,69 @@ import (
"github.com/stretchr/testify/assert"
)
func TestCallerFromContext(t *testing.T) {
called := false
h := auth.CallerMiddleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
called = true
assert.Equal(t, "mathiasbq", auth.Caller(r.Context()))
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(bytes.NewBuffer(nil), nil))
}
// Header precedence: X-Auth-Request-User (verified OIDC identity) wins over
// X-Forwarded-User, and X-Forwarded-User is only a fallback when the former is
// absent.
func TestCallerHeaderPrecedence(t *testing.T) {
tests := []struct {
name string
authReq string
forwarded string
wantCaller string
}{
{"auth-request only", "mathiasbq", "", "mathiasbq"},
{"forwarded fallback", "", "fwduser", "fwduser"},
{"both present, same", "same", "same", "same"},
{"both present, differ → auth-request wins", "authuser", "fwduser", "authuser"},
{"neither", "", "", ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var got string
h := auth.CallerMiddleware(discardLogger(), http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
got = auth.Caller(r.Context())
}))
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("X-Auth-Request-User", "mathiasbq")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
assert.True(t, called)
if tc.authReq != "" {
req.Header.Set("X-Auth-Request-User", tc.authReq)
}
if tc.forwarded != "" {
req.Header.Set("X-Forwarded-User", tc.forwarded)
}
h.ServeHTTP(httptest.NewRecorder(), req)
assert.Equal(t, tc.wantCaller, got)
})
}
}
// When both headers are present and disagree, a warning is logged so the proxy
// misconfiguration is visible rather than silent.
func TestCallerConflictingHeadersLogsWarning(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn}))
h := auth.CallerMiddleware(logger, http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("X-Auth-Request-User", "authuser")
req.Header.Set("X-Forwarded-User", "fwduser")
h.ServeHTTP(httptest.NewRecorder(), req)
logged := buf.String()
assert.Contains(t, logged, "conflicting")
assert.Contains(t, logged, "authuser")
assert.Contains(t, logged, "fwduser")
// No warning when they agree.
buf.Reset()
req2 := httptest.NewRequest(http.MethodPost, "/", nil)
req2.Header.Set("X-Auth-Request-User", "same")
req2.Header.Set("X-Forwarded-User", "same")
h.ServeHTTP(httptest.NewRecorder(), req2)
assert.Empty(t, buf.String(), "no warning expected when headers agree")
}
func TestCallerEmptyWhenHeaderMissing(t *testing.T) {
+2
View File
@@ -16,10 +16,12 @@ type PullRequest struct {
Draft bool `json:"draft"`
Head struct {
Ref string `json:"ref"`
Sha string `json:"sha"`
} `json:"head"`
Base struct {
Ref string `json:"ref"`
} `json:"base"`
Mergeable bool `json:"mergeable"`
}
type CreatePullRequestArgs struct {
+17 -6
View File
@@ -48,7 +48,7 @@ func NewCreateProjectFromTemplate(c *gitea.Client, a *allowlist.Allowlist, tmplO
func (t *CreateProjectFromTemplate) Descriptor() registry.ToolDescriptor {
return registry.ToolDescriptor{
Name: "create_project_from_template",
Description: "Create a new project repo from a template. Best-effort substitution of placeholders (__PROJECT_NAME__, __MODULE_PATH__) in every file's content AND path (e.g. renaming cmd/__PROJECT_NAME__/): it completes only if the generated branch is promptly writable. If gitea's async generate is slow (infra#179) the repo is still created and partial_failure explains how to finalize locally (`hyperguild new-project`). Check files_substituted and partial_failure. Defaults to the server-configured template; pass template_name to override (e.g. template-go-agent). Pass dispatch_allow=true to also inject a .dispatch-allow file so the project is immediately dispatch-eligible (dispatch#3).",
Description: "Create a new project repo from a template. Best-effort substitution of placeholders (__PROJECT_NAME__, __MODULE_PATH__) in every file's content AND path (e.g. renaming cmd/__PROJECT_NAME__/): it completes only if the generated branch is promptly writable. If gitea's async generate is slow (infra#179) the repo is still created and partial_failure explains how to finish substituting the placeholders manually. Check files_substituted and partial_failure. Defaults to the server-configured template; pass template_name to override (e.g. template-go-agent). Pass dispatch_allow=true to also inject a .dispatch-allow file so the project is immediately dispatch-eligible (dispatch#3).",
InputSchema: json.RawMessage(`{
"type":"object",
"properties":{
@@ -209,11 +209,7 @@ func (t *CreateProjectFromTemplate) Call(ctx context.Context, raw json.RawMessag
// is best-effort).
if strings.Contains(result.PartialFailure, "branch does not exist") ||
strings.Contains(result.PartialFailure, "not found") {
result.PartialFailure = fmt.Sprintf(
"repo created, but its branch (%s) was not writable within %ds — gitea's "+
"template-generate is slow-async on this instance (infra#179), so substitution "+
"is incomplete (%d file(s) done). Finalize locally with `hyperguild new-project` "+
"(clone + substitute, no API race). Underlying: %s",
result.PartialFailure = infra179FinalizeMessage(
branch, substitutionBudget, len(result.FilesSubstituted), result.PartialFailure)
}
@@ -227,6 +223,21 @@ func (t *CreateProjectFromTemplate) Call(ctx context.Context, raw json.RawMessag
return textOK(result)
}
// infra179FinalizeMessage explains the best-effort outcome when gitea's slow
// async template-generate (infra#179) leaves the branch unwritable within the
// budget. It names the concrete remaining work — substituting the two
// placeholders — rather than pointing at a specific tool, so the guidance stays
// correct regardless of scaffolding-CLI state (gitea-mcp#46).
func infra179FinalizeMessage(branch string, budget, done int, underlying string) string {
return fmt.Sprintf(
"repo created, but its branch (%s) was not writable within %ds — gitea's "+
"template-generate is slow-async on this instance (infra#179), so substitution "+
"is incomplete (%d file(s) done). Finish it by cloning the repo and replacing the "+
"remaining __PROJECT_NAME__ / __MODULE_PATH__ placeholders (in file contents and "+
"paths), then pushing; or retry create once the branch settles. Underlying: %s",
branch, budget, done, underlying)
}
// substitutionBudget bounds how long we retry the first write while the freshly
// generated branch becomes writable. gitea's /generate returns (and serves reads)
// before the branch ref is committed, so writes 404 "branch does not exist" for a
@@ -0,0 +1,22 @@
package tools
import (
"strings"
"testing"
)
// #46: the infra#179 finalize guidance must not point at a non-existent command
// (`hyperguild new-project` was never built). It should name the real remaining
// work — substituting the placeholders — so the caller isn't sent to a dead end.
func TestInfra179FinalizeMessage(t *testing.T) {
msg := infra179FinalizeMessage("main", 5, 2, "branch does not exist")
for _, want := range []string{"infra#179", "__PROJECT_NAME__", "__MODULE_PATH__", "branch does not exist"} {
if !strings.Contains(msg, want) {
t.Errorf("message missing %q\ngot: %s", want, msg)
}
}
if strings.Contains(msg, "hyperguild new-project") {
t.Errorf("message must not reference the defunct `hyperguild new-project` command\ngot: %s", msg)
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ const prFixture = `{
func callerContext(user string) context.Context {
var capturedCtx context.Context
h := auth.CallerMiddleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
h := auth.CallerMiddleware(nil, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
capturedCtx = r.Context()
}))
req := httptest.NewRequest("POST", "/", nil)
+1
View File
@@ -33,6 +33,7 @@ func RegisterAll(
reg.Register(NewPRGet(c, a))
reg.Register(NewPRList(c, a))
reg.Register(NewPRMerge(c, a))
reg.Register(NewTBDShip(c, a))
reg.Register(NewPRComment(c, a))
reg.Register(NewPRFilesDiff(c, a))
reg.Register(NewWorkflowRunTrigger(c, a, giteaBaseURL))
+276
View File
@@ -0,0 +1,276 @@
package tools
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
"git.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"git.d-ma.be/mathias/gitea-mcp/internal/auth"
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
"git.d-ma.be/mathias/gitea-mcp/internal/identity"
"git.d-ma.be/mathias/gitea-mcp/internal/registry"
)
// TBDShip is the intent verb for the trunk-based loop: branch → write → PR →
// (CI-green) auto-merge → clean up. The safety is the CI gate — it fails closed
// on anything that isn't a fully-green, unprotected, cleanly-mergeable change.
type TBDShip struct {
c *gitea.Client
a *allowlist.Allowlist
}
func NewTBDShip(c *gitea.Client, a *allowlist.Allowlist) *TBDShip { return &TBDShip{c: c, a: a} }
const (
shipCIPollInterval = 5 * time.Second
shipCIMaxTimeoutSec = 600
)
func (t *TBDShip) Descriptor() registry.ToolDescriptor {
return registry.ToolDescriptor{
Name: "tbd_ship",
Description: "Trunk-based ship of a single-file change: branch from base, write the file, open a PR, and auto-merge (squash) to base ONLY when the head commit's CI is fully green. Fails closed to PR-only (never merges) when CI is pending, red, or absent, when the base branch requires reviews, or when the merge isn't clean — returning the PR for manual handling with a reason. Set ci_timeout_seconds to poll CI to completion (default 0 = snapshot, which returns pending right after opening the PR). Returns {merged, pr_url, pr_number, ci_status, reason, branch}.",
InputSchema: json.RawMessage(`{
"type":"object",
"properties":{
"owner":{"type":"string"},
"repo":{"type":"string"},
"path":{"type":"string","description":"File path to create or update."},
"content":{"type":"string","description":"Full file content (plain text)."},
"message":{"type":"string","description":"Commit message."},
"base":{"type":"string","description":"Base branch to ship to. Default 'main'."},
"branch":{"type":"string","description":"Short-lived branch name. Default derived: tbd/<slug>-<hash>."},
"pr_title":{"type":"string","description":"PR title. Default: the commit message."},
"pr_body":{"type":"string"},
"delete_branch":{"type":"boolean","description":"Delete the branch after a successful merge. Default true."},
"ci_timeout_seconds":{"type":"integer","minimum":0,"maximum":600,"description":"Poll CI up to this long for the head commit's runs to complete. Default 0 (single snapshot)."}
},
"required":["owner","repo","path","content","message"]
}`),
}
}
type tbdShipArgs struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Path string `json:"path"`
Content string `json:"content"`
Message string `json:"message"`
Base string `json:"base"`
Branch string `json:"branch"`
PRTitle string `json:"pr_title"`
PRBody string `json:"pr_body"`
DeleteBranch *bool `json:"delete_branch"`
CITimeoutSec int `json:"ci_timeout_seconds"`
}
// shipGate is the decision produced by evaluateShipGate.
type shipGate struct {
merge bool
ciStatus string // none | pending | failed | success
reason string // non-empty iff merge == false
}
// classifyCI reduces a set of workflow runs for one commit to a single status.
// Fail-closed: only "success" (all runs completed and successful) permits a
// merge; anything else — no runs, still-running, or any non-success conclusion
// (failure/cancelled/skipped) — blocks it.
func classifyCI(runs []gitea.WorkflowRun) string {
if len(runs) == 0 {
return "none"
}
for _, r := range runs {
if r.Status != "completed" {
return "pending"
}
}
for _, r := range runs {
if r.Conclusion != "success" {
return "failed"
}
}
return "success"
}
// evaluateShipGate is the load-bearing safety of tbd_ship. It returns merge=true
// only when CI is fully green AND the base branch is not review-protected. Every
// other state fails closed to PR-only with an explanatory reason (#40).
func evaluateShipGate(runs []gitea.WorkflowRun, bp *gitea.BranchProtection) shipGate {
ci := classifyCI(runs)
// Review-protected base can't be auto-merged regardless of CI.
if bp != nil && bp.Protected && bp.RequiredApprovals > 0 {
return shipGate{false, ci, fmt.Sprintf(
"base branch requires %d approving review(s) — auto-merge disabled; PR opened for manual merge", bp.RequiredApprovals)}
}
switch ci {
case "success":
return shipGate{true, ci, ""}
case "pending":
return shipGate{false, ci, "CI is still running for the head commit — PR opened; re-invoke once checks complete, or merge manually"}
case "failed":
return shipGate{false, ci, "CI failed for the head commit — PR opened, not merged"}
default: // none
return shipGate{false, ci, "no CI runs found for the head commit — fail-closed: a change with no CI gate is never auto-merged to trunk; PR opened for manual merge"}
}
}
var shipSlugRe = regexp.MustCompile(`[^a-z0-9]+`)
// deriveBranch builds a deterministic short-lived branch name from the change,
// so the same change maps to the same branch and distinct changes don't collide.
func deriveBranch(message, path, content string) string {
slug := strings.Trim(shipSlugRe.ReplaceAllString(strings.ToLower(message), "-"), "-")
if len(slug) > 32 {
slug = strings.Trim(slug[:32], "-")
}
if slug == "" {
slug = "change"
}
sum := sha256.Sum256([]byte(path + "\x00" + content + "\x00" + message))
return "tbd/" + slug + "-" + hex.EncodeToString(sum[:])[:8]
}
func (t *TBDShip) Call(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
var args tbdShipArgs
if err := parseArgs(raw, &args); err != nil {
return nil, err
}
if err := t.a.Check(args.Owner); err != nil {
return nil, err
}
if args.Path == "" || args.Content == "" || args.Message == "" {
return nil, fmt.Errorf("path, content, and message are required: %w", gitea.ErrValidation)
}
base := args.Base
if base == "" {
base = "main"
}
branch := args.Branch
if branch == "" {
branch = deriveBranch(args.Message, args.Path, args.Content)
}
deleteBranch := true
if args.DeleteBranch != nil {
deleteBranch = *args.DeleteBranch
}
// Probe base-branch protection up front — a real error fails closed.
bp, err := t.c.GetBranchProtection(ctx, args.Owner, args.Repo, base)
if err != nil {
return nil, fmt.Errorf("branch protection probe: %w", err)
}
// Branch from base, write the change, open the PR.
if err := t.c.CreateBranch(ctx, args.Owner, args.Repo, branch, base); err != nil {
return nil, fmt.Errorf("create branch %s: %w", branch, err)
}
// A pre-existing file at path needs its blob sha to update; a new file does not.
sha := ""
if fc, ferr := t.c.GetFileContents(ctx, args.Owner, args.Repo, args.Path, branch); ferr == nil {
sha = fc.Sha
} else if !errors.Is(ferr, gitea.ErrNotFound) {
return nil, fmt.Errorf("read %s on %s: %w", args.Path, branch, ferr)
}
if _, err := t.c.UpsertFile(ctx, args.Owner, args.Repo, args.Path, gitea.UpsertFileArgs{
Branch: branch,
Content: base64.StdEncoding.EncodeToString([]byte(args.Content)),
Message: args.Message,
Sha: sha,
}); err != nil {
return nil, fmt.Errorf("write %s on %s: %w", args.Path, branch, err)
}
prTitle := args.PRTitle
if prTitle == "" {
prTitle = args.Message
}
pr, err := t.c.CreatePullRequest(ctx, args.Owner, args.Repo, gitea.CreatePullRequestArgs{
Title: prTitle,
Body: identity.ApplyFooter(args.PRBody, auth.Caller(ctx)),
Head: branch,
Base: base,
})
if err != nil {
return nil, fmt.Errorf("open PR: %w", err)
}
// CI gate on the PR head commit.
runs := t.pollRuns(ctx, args.Owner, args.Repo, pr.Head.Sha, args.CITimeoutSec)
gate := evaluateShipGate(runs, bp)
result := map[string]any{
"merged": false,
"pr_number": pr.Number,
"pr_url": pr.HTMLURL,
"branch": branch,
"ci_status": gate.ciStatus,
}
if !gate.merge {
result["reason"] = gate.reason
return textOK(result)
}
// Green + unprotected → squash-merge, then delete the short-lived branch.
if err := t.c.MergePullRequest(ctx, args.Owner, args.Repo, pr.Number, gitea.MergePRArgs{Do: "squash"}); err != nil {
if errors.Is(err, gitea.ErrConflict) {
result["reason"] = "base moved and the merge is not clean — PR opened, not merged; resolve the conflict and merge manually"
return textOK(result)
}
return nil, fmt.Errorf("merge PR #%d: %w", pr.Number, err)
}
result["merged"] = true
if deleteBranch {
if derr := t.c.DeleteBranch(ctx, args.Owner, args.Repo, branch); derr == nil {
result["branch_deleted"] = true
}
}
return textOK(result)
}
// pollRuns lists the head commit's workflow runs, polling up to timeoutSec for
// them to reach a terminal state. timeoutSec == 0 is a single snapshot (no
// sleep). A listing error yields no runs → the gate fails closed.
func (t *TBDShip) pollRuns(ctx context.Context, owner, repo, headSHA string, timeoutSec int) []gitea.WorkflowRun {
if timeoutSec < 0 {
timeoutSec = 0
}
if timeoutSec > shipCIMaxTimeoutSec {
timeoutSec = shipCIMaxTimeoutSec
}
deadline := time.Now().Add(time.Duration(timeoutSec) * time.Second)
for {
runs := t.listRuns(ctx, owner, repo, headSHA)
switch classifyCI(runs) {
case "success", "failed":
return runs // terminal — no point waiting
}
if time.Now().After(deadline) {
return runs // out of time — return whatever we have (none/pending)
}
select {
case <-ctx.Done():
return runs
case <-time.After(shipCIPollInterval):
}
}
}
func (t *TBDShip) listRuns(ctx context.Context, owner, repo, headSHA string) []gitea.WorkflowRun {
resp, err := t.c.ListWorkflowRuns(ctx, owner, repo, gitea.ListWorkflowRunsArgs{HeadSHA: headSHA, Limit: 50})
if err != nil || resp == nil {
return nil
}
return resp.WorkflowRuns
}
+53
View File
@@ -0,0 +1,53 @@
package tools
import (
"testing"
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
)
// The ship gate is the load-bearing safety of tbd_ship: it must NEVER return
// merge=true unless CI is fully green AND the base isn't review-protected.
// Every non-green / unknown / protected state fails closed to PR-only (#40).
func TestEvaluateShipGate(t *testing.T) {
run := func(status, concl string) gitea.WorkflowRun {
return gitea.WorkflowRun{Status: status, Conclusion: concl}
}
protected := &gitea.BranchProtection{Protected: true, RequiredApprovals: 1}
open := &gitea.BranchProtection{Protected: false}
tests := []struct {
name string
runs []gitea.WorkflowRun
bp *gitea.BranchProtection
wantMerge bool
wantCI string
}{
{"all green → merge", []gitea.WorkflowRun{run("completed", "success")}, open, true, "success"},
{"in_progress → no merge", []gitea.WorkflowRun{run("in_progress", "")}, open, false, "pending"},
{"queued → no merge", []gitea.WorkflowRun{run("queued", "")}, open, false, "pending"},
{"failed → no merge", []gitea.WorkflowRun{run("completed", "failure")}, open, false, "failed"},
{"cancelled → no merge (fail-closed)", []gitea.WorkflowRun{run("completed", "cancelled")}, open, false, "failed"},
{"no runs → no merge (no CI gate)", nil, open, false, "none"},
{"mixed success+queued → no merge", []gitea.WorkflowRun{run("completed", "success"), run("queued", "")}, open, false, "pending"},
{"green but protected → no merge", []gitea.WorkflowRun{run("completed", "success")}, protected, false, "success"},
{"no runs + protected → no merge", nil, protected, false, "none"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
g := evaluateShipGate(tc.runs, tc.bp)
if g.merge != tc.wantMerge {
t.Errorf("merge = %v, want %v (reason: %q)", g.merge, tc.wantMerge, g.reason)
}
if g.ciStatus != tc.wantCI {
t.Errorf("ciStatus = %q, want %q", g.ciStatus, tc.wantCI)
}
if !tc.wantMerge && g.reason == "" {
t.Errorf("no-merge decision must carry a reason")
}
if tc.wantMerge && g.reason != "" {
t.Errorf("merge decision must have empty reason, got %q", g.reason)
}
})
}
}
+116
View File
@@ -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)
}