From 3940b1b6a0c20b750e7ff1a6b4ff2fd981c1ba49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 09:53:26 +0100 Subject: [PATCH 01/29] build: list the vendored conformance fixtures in one file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit conformance:check reads hack/conformance-fixtures.txt, so the core bump automation can refresh the same fixtures it checks. Signed-off-by: Roland Huß --- hack/conformance-fixtures.txt | 6 ++++++ mise.toml | 5 +---- 2 files changed, 7 insertions(+), 4 deletions(-) create mode 100644 hack/conformance-fixtures.txt diff --git a/hack/conformance-fixtures.txt b/hack/conformance-fixtures.txt new file mode 100644 index 0000000..d3ca21f --- /dev/null +++ b/hack/conformance-fixtures.txt @@ -0,0 +1,6 @@ +# Fixtures vendored from core's sdk/conformance/ at the pinned tag, one path +# per line. conformance:check compares them with core; core bump PRs +# refresh them (hack/automation/open-bump-pr.sh). +openshell/v1/oidc/testdata/oauth-client-credentials.json +openshell/v1/oidc/testdata/oidc-token-bundle.json +openshell/v1/gateway/testdata/oidc-token-bundle.json diff --git a/mise.toml b/mise.toml index 11d79ce..5363a1a 100644 --- a/mise.toml +++ b/mise.toml @@ -79,10 +79,7 @@ FAILED=0 TMP=$(mktemp) trap 'rm -f "$TMP"' EXIT -for local in \ - openshell/v1/oidc/testdata/oauth-client-credentials.json \ - openshell/v1/oidc/testdata/oidc-token-bundle.json \ - openshell/v1/gateway/testdata/oidc-token-bundle.json; do +for local in $(grep -v '^#' hack/conformance-fixtures.txt); do name=$(basename "$local") status=$(curl -sS -o "$TMP" -w '%{http_code}' "$BASE/$name") if [ "$status" = 404 ]; then From 476aec7232fd13f73c9a6eae964105886dc116de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 09:53:27 +0100 Subject: [PATCH 02/29] feat(hack): list new core tags and open update proposals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core-tags.sh prints core release tags newer than the pin: every newer stable tag and the newest pre-release if it is ahead of them (--all for every tag). open-bump-pr.sh builds branch core/ in a temporary worktree, moves the pin, regenerates the bindings, refreshes the vendored fixtures, and opens a PR labeled core-bump plus stable or prerelease with the proto diff between the two core tags. It skips tags that already have a branch or a merged proposal, closes older pre-release proposals, and closes proposals whose core tag was deleted. --dry-run changes nothing on GitHub. Signed-off-by: Roland Huß --- hack/automation/bump-pr-body.md | 16 +++ hack/automation/core-tags.sh | 65 +++++++++++ hack/automation/open-bump-pr.sh | 199 ++++++++++++++++++++++++++++++++ 3 files changed, 280 insertions(+) create mode 100644 hack/automation/bump-pr-body.md create mode 100755 hack/automation/core-tags.sh create mode 100755 hack/automation/open-bump-pr.sh diff --git a/hack/automation/bump-pr-body.md b/hack/automation/bump-pr-body.md new file mode 100644 index 0000000..20ef237 --- /dev/null +++ b/hack/automation/bump-pr-body.md @@ -0,0 +1,16 @@ +Move the core pin from `{{OLD}}` to `{{NEW}}` ({{KIND}}). + +- Core changes: [{{OLD}}...{{NEW}}]({{COMPARE_URL}}) +- Regenerated bindings: {{GENERATED}} +- E2E runs against `{{IMAGE}}` +- Conformance fixtures: +{{FIXTURES}} + +## Proto changes + +{{PROTO_DIFF}} + +## Before merging + +- CI and E2E must pass. If the SDK needs changes for this core version, push them to this branch, or add the `agent:adapt` label to get a first draft. +- Merging a stable pin tags the SDK release `{{NEW}}`. Pre-release pins are not tagged; a newer pre-release proposal replaces this one. diff --git a/hack/automation/core-tags.sh b/hack/automation/core-tags.sh new file mode 100755 index 0000000..82dec3b --- /dev/null +++ b/hack/automation/core-tags.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# core-tags.sh: print NVIDIA/OpenShell release tags newer than the pin, +# oldest first. +# +# Usage: core-tags.sh [--all] [--pin ] +# +# Release tags are vX.Y.Z and vX.Y.Z-pre.N; a pre-release sorts below its +# stable version. By default every newer stable tag is printed, plus the +# newest pre-release when it is newer than all of them: one proposal for the +# current release train instead of one per pre-release. --all prints every +# newer tag. --pin overrides the pin read from buf.gen.yaml. +set -euo pipefail + +repo=${CORE_REPO:-NVIDIA/OpenShell} +all=0 +pin= + +while [ $# -gt 0 ]; do + case $1 in + --all) all=1; shift ;; + --pin) pin=${2:?--pin needs a tag}; shift 2 ;; + *) echo "usage: $0 [--all] [--pin ]" >&2; exit 2 ;; + esac +done + +[ -n "$pin" ] || pin=$(yq -r '.inputs[0].tag' buf.gen.yaml) + +# key : "major minor patch rank pre" with rank 1 for stable, 0 for pre. +key() { + awk -v t="$1" 'BEGIN { + s = t; sub(/^v/, "", s) + pre = ""; rank = 1 + if (index(s, "-pre.")) { pre = substr(s, index(s, "-pre.") + 5); s = substr(s, 1, index(s, "-pre.") - 1); rank = 0 } + split(s, v, ".") + printf "%d %d %d %d %d\n", v[1], v[2], v[3], rank, (pre == "" ? 0 : pre) + }' +} + +newer=$( + gh api --paginate "repos/$repo/git/matching-refs/tags/v" --jq '.[].ref' | + sed 's#^refs/tags/##' | + { grep -E '^v[0-9]+\.[0-9]+\.[0-9]+(-pre\.[0-9]+)?$' || true; } | + while read -r t; do echo "$(key "$t") $t"; done | + awk -v p="$(key "$pin")" ' + BEGIN { split(p, k, " ") } + { + for (i = 1; i <= 5; i++) { + if ($i + 0 > k[i] + 0) { print; next } + if ($i + 0 < k[i] + 0) next + } + }' | + sort -n -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 | + awk '{ print $6 }' +) + +[ -n "$newer" ] || exit 0 +if [ "$all" -eq 1 ]; then + echo "$newer" + exit 0 +fi + +# Stable tags, then the last tag if it is a pre-release (newer than every stable). +grep -v -- '-pre\.' <<<"$newer" || true +last=$(tail -1 <<<"$newer") +case $last in *-pre.*) echo "$last" ;; esac diff --git a/hack/automation/open-bump-pr.sh b/hack/automation/open-bump-pr.sh new file mode 100755 index 0000000..41e3e28 --- /dev/null +++ b/hack/automation/open-bump-pr.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# open-bump-pr.sh: open the update proposal that moves the core pin to . +# +# Usage: open-bump-pr.sh [--dry-run] [--base ] +# +# Run from the root of an sdk-go clone. Builds branch core/ from +# origin/main (or --base) in a temporary worktree: pin change, regenerated +# bindings, refreshed conformance fixtures, one commit +# "chore(core): track ". Then pushes it and opens a PR labeled +# core-bump plus stable or prerelease, and closes open pre-release proposals +# for older tags. --dry-run does the local part, prints the PR body, and +# changes nothing on GitHub. +# +# Skips the tag when branch core/ exists on origin or a PR from it was +# merged. When the core tag no longer exists, closes an open proposal for it. +# Git identity and GH_TOKEN come from the environment (the App in CI). +set -euo pipefail + +core_repo=${CORE_REPO:-NVIDIA/OpenShell} +sdk_repo=${SDK_REPO:-ai-openshell/sdk-go} +image=ghcr.io/nvidia/openshell/gateway +diff_cap=400 + +tag= +dry=0 +base=origin/main +while [ $# -gt 0 ]; do + case $1 in + --dry-run) dry=1; shift ;; + --base) base=${2:?--base needs a ref}; shift 2 ;; + -*) echo "usage: $0 [--dry-run] [--base ]" >&2; exit 2 ;; + *) [ -z "$tag" ] || { echo "usage: $0 [--dry-run]" >&2; exit 2; }; tag=$1; shift ;; + esac +done +[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-pre\.[0-9]+)?$ ]] || { + echo "ERROR: '$tag' is not a core release tag (vX.Y.Z or vX.Y.Z-pre.N)" >&2 + exit 2 +} + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +body_tmpl="$here/bump-pr-body.md" +branch="core/$tag" +case $tag in *-pre.*) kind=prerelease ;; *) kind=stable ;; esac + +die() { echo "ERROR: $*" >&2; exit 1; } + +# older : true when release tag a sorts below b (vX.Y.Z-pre.N < vX.Y.Z). +older() { + awk -v a="$1" -v b="$2" ' + function key(t, s, pre, rank, v) { + s = t; sub(/^v/, "", s); pre = 0; rank = 1 + if (index(s, "-pre.")) { pre = substr(s, index(s, "-pre.") + 5) + 0; s = substr(s, 1, index(s, "-pre.") - 1); rank = 0 } + split(s, v, ".") + return sprintf("%06d%06d%06d%d%06d", v[1], v[2], v[3], rank, pre) + } + BEGIN { exit !(key(a) < key(b)) }' +} +run() { if [ "$dry" -eq 1 ]; then echo "dry-run: $*"; else "$@"; fi; } + +[ "$(git rev-parse --show-toplevel)" = "$(pwd -P)" ] || die "run this from the root of the sdk-go clone" +[ -f "$body_tmpl" ] || die "$body_tmpl is missing" + +open_pr_for_branch() { + gh pr list -R "$sdk_repo" --head "$branch" --state open --json number --jq '.[0].number // empty' +} + +# The core tag may have been deleted (a withdrawn pre-release). +if ! gh api "repos/$core_repo/git/ref/tags/$tag" --silent 2>/dev/null; then + n=$(open_pr_for_branch) + if [ -n "$n" ]; then + echo "Core tag $tag is gone; closing #$n." + run gh pr close "$n" -R "$sdk_repo" --delete-branch \ + --comment "Core tag \`$tag\` no longer exists in $core_repo, so this proposal is closed." + else + echo "Core tag $tag does not exist; nothing to do." + fi + exit 0 +fi + +if [ -n "$(git ls-remote --heads origin "$branch")" ]; then + echo "Branch $branch exists on origin; skipping $tag." + exit 0 +fi +if [ -n "$(gh pr list -R "$sdk_repo" --head "$branch" --state merged --json number --jq '.[0].number // empty')" ]; then + echo "A proposal for $tag was merged already; skipping." + exit 0 +fi + +git fetch --quiet origin +git rev-parse --verify --quiet "$base^{commit}" >/dev/null || die "base $base is not a commit" +old=$(git show "$base:buf.gen.yaml" | yq -r '.inputs[0].tag') +[ "$old" != "$tag" ] || { echo "The pin on $base is $tag already; skipping."; exit 0; } + +work=$(mktemp -d) +cleanup() { git worktree remove --force "$work/wt" >/dev/null 2>&1 || true; rm -rf "$work"; } +trap cleanup EXIT +git worktree add --quiet -b "$branch" "$work/wt" "$base" + +( + cd "$work/wt" + yq -i ".inputs[0].tag = \"$tag\"" buf.gen.yaml + mise run --quiet proto:gen >/dev/null + + # Refresh vendored fixtures; one not in the tag yet is left as is. + : >"$work/fixtures.txt" + for local in $(grep -v '^#' hack/conformance-fixtures.txt); do + name=$(basename "$local") + status=$(curl -sS -o "$work/fixture" -w '%{http_code}' \ + "https://raw.githubusercontent.com/$core_repo/$tag/sdk/conformance/$name") + case $status in + 200) + if ! cmp -s "$work/fixture" "$local"; then + cp "$work/fixture" "$local" + echo "- \`$local\` updated from core \`$tag\`" >>"$work/fixtures.txt" + fi + ;; + 404) echo "- \`$local\` is not in core \`$tag\` yet, left unchanged" >>"$work/fixtures.txt" ;; + *) echo "ERROR: fetching $name at $tag returned HTTP $status" >&2; exit 1 ;; + esac + done + + # Keep the README's "generated from OpenShell core vX.Y.Z" line in step + # with stable pins. + if [ "$kind" = stable ]; then + sed -i.bak "s/generated from OpenShell core ${old}/generated from OpenShell core ${tag}/" README.md && rm -f README.md.bak + fi + + git add -A + git commit --quiet --signoff -m "chore(core): track $tag" -m "Move the core pin from $old to $tag and regenerate the bindings." +) + +# Proto diff between the two core tags. The compare API caps its file list at +# 300 entries, so fetch both tags shallow and blobless and diff locally; only +# the proto/ blobs are downloaded. +compare_url="https://github.com/$core_repo/compare/$old...$tag" +git init --quiet --bare "$work/core.git" +git -C "$work/core.git" fetch --quiet --depth=1 --filter=blob:none --no-tags \ + "https://github.com/$core_repo.git" "refs/tags/$old:refs/tags/$old" "refs/tags/$tag:refs/tags/$tag" +proto_diff=$(git -C "$work/core.git" diff "$old" "$tag" -- proto/) +if [ -z "$proto_diff" ]; then + proto_section="No changes under \`proto/\` between \`$old\` and \`$tag\`." +else + lines=$(wc -l <<<"$proto_diff" | tr -d ' ') + shown=$(head -n "$diff_cap" <<<"$proto_diff") + proto_section=$(printf '```diff\n%s\n```' "$shown") + if [ "$lines" -gt "$diff_cap" ]; then + proto_section=$(printf '%s\n\nShowing %s of %s lines; see the [full compare](%s).' "$proto_section" "$diff_cap" "$lines" "$compare_url") + fi +fi +generated=$(git diff --stat "$base" "$branch" -- proto/ | tail -1 | sed "s/^ *//") +fixtures=$(cat "$work/fixtures.txt") + +body="$work/body.md" +OLD="$old" NEW="$tag" KIND="$kind" COMPARE_URL="$compare_url" IMAGE="$image:${tag#v}" \ +GENERATED="${generated:-no generated files changed}" FIXTURES="${fixtures:-- no fixture changes}" \ +PROTO_DIFF="$proto_section" \ + awk '{ + while (match($0, /\{\{[A-Z_]+\}\}/)) { + key = substr($0, RSTART + 2, RLENGTH - 4) + $0 = substr($0, 1, RSTART - 1) ENVIRON[key] substr($0, RSTART + RLENGTH) + } + print + }' "$body_tmpl" >"$body" + +echo "Proposal for $tag ($kind), pin $old -> $tag:" +git log --format=' %h %an <%ae> %s' "$base..$branch" +git diff --stat "$base" "$branch" | tail -1 | sed 's/^/ /' + +if [ "$dry" -eq 1 ]; then + echo + echo "PR title: chore(core): track $tag" + echo "PR body:" + sed 's/^/ | /' "$body" + cleanup + git branch -D "$branch" >/dev/null + echo + echo "dry-run: nothing pushed; local branch $branch removed." + exit 0 +fi + +git push --quiet origin "$branch" +url=$(gh pr create -R "$sdk_repo" --base main --head "$branch" \ + --title "chore(core): track $tag" --body-file "$body" \ + --label core-bump --label "$kind") +echo "Opened $url" +new=${url##*/} + +# Close open pre-release proposals for older tags; this one supersedes them. +gh pr list -R "$sdk_repo" --label core-bump --label prerelease --state open \ + --json number,headRefName --jq '.[] | "\(.number) \(.headRefName)"' | + while read -r n head; do + other=${head#core/} + [ "$n" != "$new" ] && [ "$other" != "$tag" ] || continue + if older "$other" "$tag"; then + echo "Closing #$n ($other), superseded by #$new." + gh pr close "$n" -R "$sdk_repo" --delete-branch \ + --comment "Superseded by #$new, which tracks core \`$tag\`." + fi + done From a40125f8359ac9722e29d7f67d80deff3ad55c54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 09:53:27 +0100 Subject: [PATCH 03/29] feat(hack): tag the lockstep SDK release for a stable pin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tag-release.sh creates the SDK tag vX.Y.Z when a commit on main moves the pin to stable core vX.Y.Z, publishes the GitHub release with the merged proposal's body, and asks the Go module proxy for the version. Pre-release pins and commits that leave the pin alone create nothing, and an existing tag at another commit fails the run. Signed-off-by: Roland Huß --- hack/automation/tag-release.sh | 86 ++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100755 hack/automation/tag-release.sh diff --git a/hack/automation/tag-release.sh b/hack/automation/tag-release.sh new file mode 100755 index 0000000..46e1ee9 --- /dev/null +++ b/hack/automation/tag-release.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# tag-release.sh: create the lockstep SDK release for a stable core pin. +# +# Usage: tag-release.sh [--dry-run] [--force] [--sha ] +# +# Reads the pin from buf.gen.yaml at (default: $GITHUB_SHA, else +# HEAD). A pre-release pin creates nothing. Without --force, a commit that +# did not change buf.gen.yaml creates nothing either, so ordinary pushes to +# main are no-ops. Then: +# - tag vX.Y.Z missing: create it (lightweight) at , create the +# GitHub release with the merged proposal's body plus +# "Matches OpenShell core vX.Y.Z", and ask the Go module proxy for it +# - tag at already: nothing to do +# - tag at another commit: fail +set -euo pipefail + +sdk_repo=${SDK_REPO:-ai-openshell/sdk-go} +module=github.com/ai-openshell/sdk-go +dry=0 +force=0 +sha=${GITHUB_SHA:-} + +while [ $# -gt 0 ]; do + case $1 in + --dry-run) dry=1; shift ;; + --force) force=1; shift ;; + --sha) sha=${2:?--sha needs a commit}; shift 2 ;; + *) echo "usage: $0 [--dry-run] [--force] [--sha ]" >&2; exit 2 ;; + esac +done +[ -n "$sha" ] || sha=$(git rev-parse HEAD) +sha=$(git rev-parse "$sha^{commit}") + +pin=$(git show "$sha:buf.gen.yaml" | yq -r '.inputs[0].tag') +if ! [[ "$pin" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Pin $pin is not a stable release; no SDK tag." + exit 0 +fi + +if [ "$force" -eq 0 ] && [ -z "$(git diff --name-only "$sha^" "$sha" -- buf.gen.yaml 2>/dev/null)" ]; then + echo "$(git rev-parse --short "$sha") does not change buf.gen.yaml; no SDK tag." + exit 0 +fi + +# gh prints the error body on stdout for a 404, so only trust a successful call. +if ! existing=$(gh api "repos/$sdk_repo/git/ref/tags/$pin" --jq '.object.sha' 2>/dev/null); then + existing= +fi +if [ -n "$existing" ]; then + if [ "$existing" = "$sha" ]; then + echo "Tag $pin already points at $(git rev-parse --short "$sha"); nothing to do." + exit 0 + fi + echo "ERROR: tag $pin exists at $existing, not at $sha. SDK tags never move; fix this by hand." >&2 + exit 1 +fi + +# Release notes: the body of the PR that merged this commit, then the match line. +notes=$(mktemp) +trap 'rm -f "$notes"' EXIT +if ! pr_body=$(gh api "repos/$sdk_repo/commits/$sha/pulls" --jq '.[0].body // empty' 2>/dev/null); then + pr_body= +fi +{ + [ -z "$pr_body" ] || printf '%s\n\n' "$pr_body" + echo "Matches OpenShell core $pin." +} >"$notes" + +if [ "$dry" -eq 1 ]; then + echo "dry-run: would create tag $pin at $sha" + echo "dry-run: would create release $pin with notes:" + sed 's/^/ | /' "$notes" + echo "dry-run: would request https://proxy.golang.org/$module/@v/$pin.info" + exit 0 +fi + +gh api -X POST "repos/$sdk_repo/git/refs" -f ref="refs/tags/$pin" -f sha="$sha" --silent +echo "Created tag $pin at $sha." +gh release create "$pin" -R "$sdk_repo" --verify-tag --title "$pin" --notes-file "$notes" + +# Best effort: the proxy fetches the version on first request. +if curl -fsS --max-time 60 "https://proxy.golang.org/$module/@v/$pin.info"; then + echo +else + echo "WARNING: the Go module proxy did not serve $pin yet; it will on the next request." >&2 +fi From 109ada132006b2dc1faa652b854abea81b544fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 09:53:27 +0100 Subject: [PATCH 04/29] ci: watch core releases and tag SDK releases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core-watch runs hourly and on dispatch, and opens a proposal per new core tag. release-tag runs on pushes to main and on dispatch for a given commit. Both use the ai-openshell-sdk-bot App token, scoped to the permissions they need, so their pushes and PRs trigger CI. Failures are reported through report-failure.sh, a job-summary stub until the drift issue exists. Adds the core:tags, core:bump, and release:tag tasks. Signed-off-by: Roland Huß --- .github/workflows/core-watch.yml | 86 +++++++++++++++++++++++++++++++ .github/workflows/release-tag.yml | 69 +++++++++++++++++++++++++ hack/automation/report-failure.sh | 15 ++++++ mise.toml | 12 +++++ 4 files changed, 182 insertions(+) create mode 100644 .github/workflows/core-watch.yml create mode 100644 .github/workflows/release-tag.yml create mode 100755 hack/automation/report-failure.sh diff --git a/.github/workflows/core-watch.yml b/.github/workflows/core-watch.yml new file mode 100644 index 0000000..d46166d --- /dev/null +++ b/.github/workflows/core-watch.yml @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Opens one update proposal per new core release tag (hack/automation/). +name: core-watch + +on: + schedule: + - cron: "17 * * * *" + workflow_dispatch: + inputs: + tag: + description: Core tag to propose (vX.Y.Z or vX.Y.Z-pre.N); empty proposes every new tag + required: false + default: "" + +permissions: + contents: read + +concurrency: + group: core-watch + cancel-in-progress: false + +jobs: + watch: + name: watch + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.SDK_BOT_APP_ID }} + private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + permission-issues: write + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + token: ${{ steps.app-token.outputs.token }} + persist-credentials: true + + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + + - name: Install tools + run: mise install --locked + + - name: Set the bot identity + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + run: | + set -euo pipefail + id=$(gh api "users/${APP_SLUG}[bot]" --jq .id) + git config user.name "${APP_SLUG}[bot]" + git config user.email "${id}+${APP_SLUG}[bot]@users.noreply.github.com" + + - name: Propose new core tags + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + INPUT_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + if [ -n "$INPUT_TAG" ]; then + tags=$INPUT_TAG + else + tags=$(hack/automation/core-tags.sh) + fi + if [ -z "$tags" ]; then + echo "No core tags newer than $(mise run --quiet core:version)." + exit 0 + fi + for t in $tags; do + hack/automation/open-bump-pr.sh "$t" + done + + - name: Report failure + if: failure() + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: hack/automation/report-failure.sh core-watch "$RUN_URL" diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml new file mode 100644 index 0000000..1e42bd8 --- /dev/null +++ b/.github/workflows/release-tag.yml @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Tags the lockstep SDK release when a stable core pin lands on main. +name: release-tag + +on: + push: + branches: [main] + workflow_dispatch: + inputs: + sha: + description: Commit on main to tag (default the tip); the pin there must be stable + required: false + default: "" + +permissions: + contents: read + +concurrency: + group: release-tag + cancel-in-progress: false + +jobs: + tag: + name: tag + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.SDK_BOT_APP_ID }} + private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: read + permission-issues: write + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + + - name: Install tools + run: mise install --locked yq + + - name: Tag the release + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + EVENT: ${{ github.event_name }} + INPUT_SHA: ${{ inputs.sha }} + run: | + set -euo pipefail + if [ "$EVENT" = workflow_dispatch ]; then + hack/automation/tag-release.sh --force --sha "${INPUT_SHA:-$GITHUB_SHA}" + else + hack/automation/tag-release.sh + fi + + - name: Report failure + if: failure() + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: hack/automation/report-failure.sh release-tag "$RUN_URL" diff --git a/hack/automation/report-failure.sh b/hack/automation/report-failure.sh new file mode 100755 index 0000000..ed551aa --- /dev/null +++ b/hack/automation/report-failure.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# report-failure.sh: record a failed automation run. +# +# Usage: report-failure.sh +# +# Until the drift issue exists (core-drift.yml), the failure goes to the job +# summary only; update-drift-issue.sh replaces this with a dated line in the +# "Core main drift" issue. +set -euo pipefail +[ $# -eq 2 ] || { echo "usage: $0 " >&2; exit 2; } +line="- $(date -u +%Y-%m-%d) $1 $2" +echo "Automation failure: $line" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + echo "$line" >>"$GITHUB_STEP_SUMMARY" +fi diff --git a/mise.toml b/mise.toml index 5363a1a..04689ef 100644 --- a/mise.toml +++ b/mise.toml @@ -236,3 +236,15 @@ run = [ [tasks."docs:build"] description = "Build the mdbook docs into docs/book" run = "mdbook build docs" + +[tasks."core:tags"] +description = "List core release tags newer than the pin (newest pre-release only, --all for every tag)" +run = "hack/automation/core-tags.sh" + +[tasks."core:bump"] +description = "Open the update proposal for a core tag: mise run core:bump -- [--dry-run]" +run = "hack/automation/open-bump-pr.sh" + +[tasks."release:tag"] +description = "Tag the lockstep SDK release for a stable pin (--dry-run prints what it would do)" +run = "hack/automation/tag-release.sh" From 9258c70f9e92d62ea71179d2c31b5d84ccd8bc58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 10:02:42 +0100 Subject: [PATCH 05/29] feat(hack): check core main for drift against the pin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit drift-check.sh runs buf breaking (FILE rules) from core main against the pinned tag for the proto files the SDK generates, regenerates the bindings from main in a temporary worktree and builds and vets against them, and lists RPCs the SDK does not call yet. It writes a markdown report with a 'Pin | Core main | Result' header and exits 1 on breaking changes or a failed build. Uncovered RPCs are informational. Signed-off-by: Roland Huß --- hack/automation/drift-check.sh | 120 +++++++++++++++++++++++++++++++++ mise.toml | 4 ++ 2 files changed, 124 insertions(+) create mode 100755 hack/automation/drift-check.sh diff --git a/hack/automation/drift-check.sh b/hack/automation/drift-check.sh new file mode 100755 index 0000000..ef6da17 --- /dev/null +++ b/hack/automation/drift-check.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# drift-check.sh: compare core main with the pinned core tag. +# +# Usage: drift-check.sh --out +# +# Run from the root of an sdk-go clone. Three checks: +# 1. buf breaking: core main against the pinned tag (FILE rules), for the +# proto files the SDK generates (the M options in buf.gen.yaml) +# 2. regenerate and build: bindings from core main in a temporary +# worktree, then go build ./... && go vet ./... +# 3. uncovered RPCs: methods in the regenerated proto/openshellv1 gRPC +# stubs that no SDK code under openshell/v1 calls (fakes and tests +# excluded); informational, it does not fail the check +# Writes a markdown report with the header +# "Pin: | Core main: | Result: pass|fail" and one section per +# check. Exits 0 when checks 1 and 2 pass, 1 otherwise. +set -euo pipefail + +core_url=${CORE_URL:-https://github.com/NVIDIA/OpenShell.git} +out= +while [ $# -gt 0 ]; do + case $1 in + --out) out=${2:?--out needs a file}; shift 2 ;; + *) echo "usage: $0 --out " >&2; exit 2 ;; + esac +done +[ -n "$out" ] || { echo "usage: $0 --out " >&2; exit 2; } +[ "$(git rev-parse --show-toplevel)" = "$(pwd -P)" ] || { + echo "ERROR: run this from the root of the sdk-go clone" >&2 + exit 1 +} +case $out in /*) ;; *) out="$(pwd)/$out" ;; esac + +pin=$(yq -r '.inputs[0].tag' buf.gen.yaml) +main_sha=$(git ls-remote "$core_url" refs/heads/main | cut -f1) +[ -n "$main_sha" ] || { echo "ERROR: cannot resolve core main" >&2; exit 1; } + +work=$(mktemp -d) +cleanup() { git worktree remove --force "$work/wt" >/dev/null 2>&1 || true; rm -rf "$work"; } +trap cleanup EXIT +result=pass +fence() { printf '```text\n%s\n```\n' "$1"; } + +# 1. buf breaking for the files the SDK generates. +files=$(yq -r '.plugins[0].opt[] | select(test("^M")) | sub("^M"; "") | sub("=.*"; "")' buf.gen.yaml) +path_args=() +for f in $files; do path_args+=(--path "proto/$f"); done +# Core's root buf.yaml has two modules; this config keeps only proto/, so +# its imports resolve the same way buf generate sees them. +if breaking=$(buf breaking "${core_url}#ref=${main_sha}" \ + --against "${core_url}#tag=${pin}" \ + --config '{"version":"v2","modules":[{"path":"proto"}],"breaking":{"use":["FILE"]}}' \ + "${path_args[@]}" 2>&1); then + breaking_section="No breaking changes in $(echo $files | sed 's/ /, /g') between \`$pin\` and main." +else + result=fail + breaking_section="Breaking changes between \`$pin\` and main: + +$(fence "$breaking")" +fi + +# 2. Regenerate from main and build. +git worktree add --quiet --detach "$work/wt" HEAD +if build=$( + cd "$work/wt" && + yq -i 'del(.inputs[0].tag) | .inputs[0].ref = "'"$main_sha"'"' buf.gen.yaml && + buf generate 2>&1 && + go build ./... 2>&1 && + go vet ./... 2>&1 +); then + changed=$(git -C "$work/wt" diff --stat -- proto/ | tail -1 | sed 's/^ *//') + build_section="Bindings from main build and vet cleanly (${changed:-no generated files change})." +else + result=fail + build_section="Regenerating from main or building against it fails: + +$(fence "$(tail -n 60 <<<"$build")")" +fi + +# 3. RPCs the SDK does not call yet. Full method names look like +# "/openshell.v1.OpenShell/CreateSandbox". +uncovered="" +if ls "$work/wt"/proto/openshellv1/*_grpc.pb.go >/dev/null 2>&1; then + methods=$(grep -ho '"/[a-zA-Z0-9_.]*\.[A-Za-z0-9_]*/[A-Za-z0-9_]*"' "$work/wt"/proto/openshellv1/*_grpc.pb.go | + tr -d '"' | sort -u) + for m in $methods; do + service=${m#/}; service=${service%%/*}; service=${service##*.} + method=${m##*/} + if ! grep -rqE "\.${method}\(" openshell/v1 --include='*.go' \ + --exclude='*_test.go' --exclude-dir=fake; then + uncovered+="- ${service}.${method}"$'\n' + fi + done +fi +if [ -z "$uncovered" ]; then + uncovered_section="Every RPC in the regenerated stubs is called by the SDK." +else + uncovered_section="RPCs in core main that the SDK does not call yet ($(grep -c . <<<"$uncovered")): + +${uncovered%$'\n'}" +fi + +cat >"$out" < Date: Wed, 4 Nov 2026 10:02:42 +0100 Subject: [PATCH 06/29] feat(hack): keep one drift issue and record automation failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit update-drift-issue.sh writes the drift report into the single open 'Core main drift' issue (label core-drift), creating it on drift and closing it once the check passes and no failures are pending. report-failure.sh appends a dated line to the issue's 'Automation failures' section, which the report updates carry over. Both take --dry-run. Signed-off-by: Roland Huß --- hack/automation/README.md | 1 + hack/automation/drift-issue.sh | 33 ++++++++++++++ hack/automation/report-failure.sh | 50 ++++++++++++++++----- hack/automation/update-drift-issue.sh | 62 +++++++++++++++++++++++++++ 4 files changed, 136 insertions(+), 10 deletions(-) create mode 100644 hack/automation/drift-issue.sh create mode 100755 hack/automation/update-drift-issue.sh diff --git a/hack/automation/README.md b/hack/automation/README.md index f227143..28eadf3 100644 --- a/hack/automation/README.md +++ b/hack/automation/README.md @@ -13,6 +13,7 @@ Workflows run them with a token of the `ai-openshell-sdk-bot` GitHub App, never | `drift-check.sh --out ` | `core:drift` | Compare core `main` against the pin: `buf breaking`, regenerate and build, uncovered RPCs. Writes the markdown report. | | `update-drift-issue.sh ` | | Create, update, or close the single `Core main drift` issue from a report. | | `report-failure.sh ` | | Append a dated failure line to the drift issue. Called from `if: failure()` steps. | +| `drift-issue.sh` | | Shared helpers for the two drift issue scripts (sourced, not run). | | `start-gateway.sh `, `stop-gateway.sh` | | Run the published gateway container for a core version with the Docker driver and a plaintext endpoint for the E2E lane, and collect its log. | | `adapt-context.sh ` | | Build the `## Adaptation task` comment for the agent workflow: pin diff, proto diff, failed log tail, uncovered RPCs. | | `adapt-task-body.md` | | Comment template for `adapt-context.sh`. | diff --git a/hack/automation/drift-issue.sh b/hack/automation/drift-issue.sh new file mode 100644 index 0000000..769c496 --- /dev/null +++ b/hack/automation/drift-issue.sh @@ -0,0 +1,33 @@ +# drift-issue.sh: shared helpers for the "Core main drift" issue. Sourced by +# update-drift-issue.sh and report-failure.sh. +# shellcheck shell=bash + +sdk_repo=${SDK_REPO:-ai-openshell/sdk-go} +drift_title="Core main drift" +drift_label=core-drift +failures_heading="## Automation failures" + +# Prints the number of the open drift issue, or nothing. +drift_issue_number() { + gh issue list -R "$sdk_repo" --label "$drift_label" --state open \ + --json number,title --jq ".[] | select(.title == \"$drift_title\") | .number" | head -1 +} + +# Prints the "- " lines of a body's failures section. +failure_lines() { + awk -v h="$failures_heading" ' + $0 == h { f = 1; next } + f && /^## / { f = 0 } + f && /^- / { print }' <<<"$1" +} + +# compose_body +compose_body() { + printf '%s\n\n%s\n\n' "$1" "$failures_heading" + if [ -n "$2" ]; then + printf '%s\n\n' "$2" + else + printf 'None.\n\n' + fi + printf '%s\n' "Automation appends a dated line here when core-watch, release-tag, or core-drift fails. Delete a line once it is handled; the issue closes when the drift check passes and no lines are left." +} diff --git a/hack/automation/report-failure.sh b/hack/automation/report-failure.sh index ed551aa..7f95121 100755 --- a/hack/automation/report-failure.sh +++ b/hack/automation/report-failure.sh @@ -1,15 +1,45 @@ #!/usr/bin/env bash -# report-failure.sh: record a failed automation run. +# report-failure.sh: record a failed automation run in the drift issue. # -# Usage: report-failure.sh +# Usage: report-failure.sh [--dry-run] # -# Until the drift issue exists (core-drift.yml), the failure goes to the job -# summary only; update-drift-issue.sh replaces this with a dated line in the -# "Core main drift" issue. +# Appends "- " to the "## Automation failures" section +# of the open "Core main drift" issue, creating the issue when none is open. +# Also writes the line to the job summary. set -euo pipefail -[ $# -eq 2 ] || { echo "usage: $0 " >&2; exit 2; } -line="- $(date -u +%Y-%m-%d) $1 $2" -echo "Automation failure: $line" -if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then - echo "$line" >>"$GITHUB_STEP_SUMMARY" +# shellcheck source=hack/automation/drift-issue.sh +. "$(dirname "${BASH_SOURCE[0]}")/drift-issue.sh" + +dry=0 +args=() +for a in "$@"; do + case $a in --dry-run) dry=1 ;; *) args+=("$a") ;; esac +done +[ ${#args[@]} -eq 2 ] || { echo "usage: $0 [--dry-run]" >&2; exit 2; } +line="- $(date -u +%Y-%m-%d) ${args[0]} ${args[1]}" +[ -z "${GITHUB_STEP_SUMMARY:-}" ] || echo "Automation failure: $line" >>"$GITHUB_STEP_SUMMARY" + +n=$(drift_issue_number) +if [ -n "$n" ]; then + current=$(gh issue view "$n" -R "$sdk_repo" --json body --jq .body) + report=$(awk -v h="$failures_heading" '$0 == h { exit } { print }' <<<"$current" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}') + failures=$(failure_lines "$current") +else + report="No drift report yet; the next core-drift run fills this in." + failures= +fi +failures=$(printf '%s\n%s' "$failures" "$line" | sed '/^$/d') +body=$(compose_body "$report" "$failures") + +if [ "$dry" -eq 1 ]; then + if [ -n "$n" ]; then target="update #$n"; else target="create the issue"; fi + echo "dry-run: would $target with:" + sed 's/^/ | /' <<<"$body" + exit 0 +fi +if [ -n "$n" ]; then + gh issue edit "$n" -R "$sdk_repo" --body "$body" >/dev/null + echo "Recorded the failure in #$n." +else + gh issue create -R "$sdk_repo" --title "$drift_title" --label "$drift_label" --body "$body" fi diff --git a/hack/automation/update-drift-issue.sh b/hack/automation/update-drift-issue.sh new file mode 100755 index 0000000..b1ebe90 --- /dev/null +++ b/hack/automation/update-drift-issue.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# update-drift-issue.sh: keep the single "Core main drift" issue current. +# +# Usage: update-drift-issue.sh [--dry-run] +# +# The report comes from drift-check.sh. The issue body is the report plus the +# "## Automation failures" section, which is carried over unchanged. With +# "Result: fail" or pending failures, the issue is created or its body +# replaced. With "Result: pass" and no pending failures, an open issue is +# closed with a comment, and nothing is created. +set -euo pipefail +# shellcheck source=hack/automation/drift-issue.sh +. "$(dirname "${BASH_SOURCE[0]}")/drift-issue.sh" + +report= +dry=0 +for a in "$@"; do + case $a in + --dry-run) dry=1 ;; + -*) echo "usage: $0 [--dry-run]" >&2; exit 2 ;; + *) report=$a ;; + esac +done +[ -f "$report" ] || { echo "usage: $0 [--dry-run]" >&2; exit 2; } + +text=$(cat "$report") +header=$(head -1 <<<"$text") +case $header in +*"Result: pass"*) result=pass ;; +*"Result: fail"*) result=fail ;; +*) echo "ERROR: $report has no 'Result: pass|fail' header" >&2; exit 1 ;; +esac + +n=$(drift_issue_number) +failures= +[ -z "$n" ] || failures=$(failure_lines "$(gh issue view "$n" -R "$sdk_repo" --json body --jq .body)") +body=$(compose_body "$text" "$failures") + +if [ "$result" = pass ] && [ -z "$failures" ]; then + if [ -z "$n" ]; then + echo "Drift check passes and no failures are pending; no issue needed." + exit 0 + fi + echo "Closing #$n: the drift check passes and no failures are pending." + [ "$dry" -eq 1 ] && exit 0 + gh issue edit "$n" -R "$sdk_repo" --body "$body" >/dev/null + gh issue close "$n" -R "$sdk_repo" --comment "The drift check passes against core main ($(sed 's/.*Core main: \([0-9a-f]*\).*/\1/' <<<"$header")) and no automation failures are pending." + exit 0 +fi + +if [ "$dry" -eq 1 ]; then + if [ -n "$n" ]; then target="update #$n"; else target="create the issue"; fi + echo "dry-run: would $target with:" + sed 's/^/ | /' <<<"$body" + exit 0 +fi +if [ -n "$n" ]; then + gh issue edit "$n" -R "$sdk_repo" --body "$body" >/dev/null + echo "Updated #$n." +else + gh issue create -R "$sdk_repo" --title "$drift_title" --label "$drift_label" --body "$body" +fi From 8f8da7ecdeb216d88e9936b780d5853b7b1416e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 10:02:42 +0100 Subject: [PATCH 07/29] ci: run the core drift check nightly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core-drift runs drift-check.sh and update-drift-issue.sh with an App token scoped to issues. A run that produces no report is recorded as an automation failure. Signed-off-by: Roland Huß --- .github/workflows/core-drift.yml | 62 ++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 .github/workflows/core-drift.yml diff --git a/.github/workflows/core-drift.yml b/.github/workflows/core-drift.yml new file mode 100644 index 0000000..5e94853 --- /dev/null +++ b/.github/workflows/core-drift.yml @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Nightly comparison of core main with the pinned core tag; keeps the single +# "Core main drift" issue current (hack/automation/drift-check.sh). +name: core-drift + +on: + schedule: + - cron: "41 4 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: core-drift + cancel-in-progress: false + +jobs: + drift: + name: drift + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.SDK_BOT_APP_ID }} + private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} + permission-issues: write + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + + - name: Install tools + run: mise install --locked + + # Exit 1 with a report means drift; the issue records it. No report + # means the check itself broke, which the failure step records. + - name: Check drift against core main + run: | + hack/automation/drift-check.sh --out drift-report.md || true + test -s drift-report.md + cat drift-report.md >>"$GITHUB_STEP_SUMMARY" + + - name: Update the drift issue + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + run: hack/automation/update-drift-issue.sh drift-report.md + + - name: Report failure + if: failure() + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: hack/automation/report-failure.sh core-drift "$RUN_URL" From 9ca452d4cbb18da1bcb03596c17d891f7d0cfa90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 10:02:42 +0100 Subject: [PATCH 08/29] ci: shellcheck the hack scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit workflows:check also runs shellcheck over hack/automation and hack/migration. Fixes the one warning it found in port-pr.sh (an unquoted command substitution passed to git add). Signed-off-by: Roland Huß --- hack/migration/port-pr.sh | 2 +- mise.toml | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/hack/migration/port-pr.sh b/hack/migration/port-pr.sh index 5782a39..832f98f 100755 --- a/hack/migration/port-pr.sh +++ b/hack/migration/port-pr.sh @@ -121,7 +121,7 @@ if [ "$fix" -eq 1 ]; then else echo "Rewrote the old module path on:" sed 's/^/ /' <<<"$fixed" - git add -- $(sed 's/:[0-9]*$//' <<<"$fixed" | sort -u) + sed 's/:[0-9]*$//' <<<"$fixed" | sort -u | while IFS= read -r f; do git add -- "$f"; done fi exit 0 fi diff --git a/mise.toml b/mise.toml index dac367c..5a49eaf 100644 --- a/mise.toml +++ b/mise.toml @@ -227,10 +227,11 @@ echo "Proto check passed: generated files match core $(yq -r '.inputs[0].tag' bu """ [tasks."workflows:check"] -description = "Lint GitHub workflows with actionlint (with shellcheck) and zizmor" +description = "Lint GitHub workflows (actionlint with shellcheck, zizmor) and the hack/ scripts (shellcheck)" run = [ "actionlint", "zizmor --offline --min-severity medium .github", + "shellcheck -x -S warning hack/automation/*.sh hack/migration/*.sh", ] [tasks."docs:build"] From 7b874ba0b649fc118add8930361d9870d4a730b0 Mon Sep 17 00:00:00 2001 From: Jiri Petrlik Date: Mon, 17 Aug 2026 17:33:36 +0200 Subject: [PATCH 09/29] test: E2E tests for Go SDK Signed-off-by: Jiri Petrlik --- e2e/harness_test.go | 279 ++++++++++++++++++++++++++++++ e2e/providers_test.go | 308 +++++++++++++++++++++++++++++++++ e2e/sandbox_lifecycle_test.go | 314 ++++++++++++++++++++++++++++++++++ e2e/workspace_test.go | 137 +++++++++++++++ 4 files changed, 1038 insertions(+) create mode 100644 e2e/harness_test.go create mode 100644 e2e/providers_test.go create mode 100644 e2e/sandbox_lifecycle_test.go create mode 100644 e2e/workspace_test.go diff --git a/e2e/harness_test.go b/e2e/harness_test.go new file mode 100644 index 0000000..5adae37 --- /dev/null +++ b/e2e/harness_test.go @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build e2e + +// Package e2e contains end-to-end tests for the Go SDK, run against a real +// OpenShell gateway with `mise run e2e:go` (Podman) or +// `mise run e2e:go:docker` (Docker). +package e2e + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + "github.com/ai-openshell/sdk-go/openshell/v1/gateway" + "github.com/ai-openshell/sdk-go/openshell/v1/types" +) + +var ( + sharedClient *v1.Client + gatewayName string +) + +func TestMain(m *testing.M) { + gatewayName = os.Getenv("OPENSHELL_GATEWAY") + if gatewayName == "" { + // No gateway configured; requireClient skips every test individually. + os.Exit(m.Run()) + } + + cfg, err := gateway.LoadConfig(gatewayName) + if err != nil { + fmt.Fprintf(os.Stderr, "e2e: failed to load gateway config: %v\n", err) + os.Exit(1) + } + + var opts []gateway.ClientOption + if opt := mtlsClientOption(cfg.Dir); opt != nil { + opts = append(opts, opt) + } + + client, err := gateway.NewClient(gatewayName, opts...) + if err != nil { + fmt.Fprintf(os.Stderr, "e2e: failed to build gateway client: %v\n", err) + os.Exit(1) + } + sharedClient = client + + if err := waitForPersistenceReady(sharedClient); err != nil { + fmt.Fprintf(os.Stderr, "e2e: %v\n", err) + _ = sharedClient.Close() + os.Exit(1) + } + + code := m.Run() + _ = sharedClient.Close() + os.Exit(code) +} + +// mtlsClientOption inspects /mtls for an on-disk certificate bundle +// written by e2e_register_mtls_gateway (see e2e/support/gateway-common.sh) +// and returns a ClientOption applying it. Returns nil when no bundle is +// present (e.g. plaintext or OIDC e2e lanes), so callers should skip it. +func mtlsClientOption(dir string) gateway.ClientOption { + mtlsDir := filepath.Join(dir, "mtls") + caPath := filepath.Join(mtlsDir, "ca.crt") + if _, err := os.Stat(caPath); err != nil { + return nil + } + + cfg := &types.TLSConfig{CAFile: caPath} + + certPath := filepath.Join(mtlsDir, "tls.crt") + keyPath := filepath.Join(mtlsDir, "tls.key") + if _, err := os.Stat(certPath); err == nil { + if _, err := os.Stat(keyPath); err == nil { + cfg.CertFile = certPath + cfg.KeyFile = keyPath + } + } + + return gateway.WithTLS(cfg) +} + +// requireClient returns the shared gateway client, skipping the calling test +// when OPENSHELL_GATEWAY was not set at process startup. +func requireClient(t *testing.T) *v1.Client { + t.Helper() + if gatewayName == "" { + t.Skip("OPENSHELL_GATEWAY not set") + } + return sharedClient +} + +// waitForPersistenceReady polls the gateway until its persistence layer is +// initialized, tolerating the transient errors observed right after the +// gateway process starts (transport not yet listening, sqlite migrations +// not yet applied). +func waitForPersistenceReady(client *v1.Client) error { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + var lastErr error + for range 60 { + _, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{PageSize: 1}) + if err == nil { + return nil + } + lastErr = err + if v1.IsUnavailable(err) { + time.Sleep(2 * time.Second) + continue + } + if strings.Contains(err.Error(), "no such table: objects") { + time.Sleep(1 * time.Second) + continue + } + return fmt.Errorf("unexpected error waiting for persistence: %w", err) + } + return fmt.Errorf("openshell-server persistence is not initialized after 60 attempts: %w", lastErr) +} + +// uniqueName returns a process-unique resource name so parallel tests never +// collide on the same sandbox/workspace/provider name. +func uniqueName(prefix string) string { + return fmt.Sprintf("%s-%09d", prefix, time.Now().UnixNano()%1_000_000_000) +} + +func requireSandboxResponse(t *testing.T, sandbox *v1.Sandbox, workspace, name string) { + t.Helper() + require.NotNil(t, sandbox) + require.NotEmpty(t, sandbox.ID) + require.Equal(t, workspace, sandbox.Workspace) + require.Equal(t, name, sandbox.Name) + require.False(t, sandbox.CreatedAt.IsZero()) + require.NotZero(t, sandbox.ResourceVersion) +} + +func requireReadySandbox(t *testing.T, sandbox *v1.Sandbox, id string) { + t.Helper() + require.NotNil(t, sandbox) + require.Equal(t, id, sandbox.ID) + require.Equal(t, v1.SandboxReady, sandbox.Status.Phase) +} + +func readEnvVar(ctx context.Context, client *v1.Client, workspace, sandboxName, key string) (string, error) { + command := []string{"sh", "-c", `if value=$(printenv "$1"); then printf "%s" "$value"; else printf NOT_SET; fi`, "--", key} + result, err := client.Exec().Run(ctx, workspace, sandboxName, command, v1.ExecOptions{}) + // A supervisor reconnect can make one reverse relay miss its opening window. + // Retry only that transport timeout; repeated failures still fail the test. + if err != nil && ctx.Err() == nil && v1.IsDeadlineExceeded(err) && strings.Contains(err.Error(), "relay open timed out") { + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-time.After(250 * time.Millisecond): + } + result, err = client.Exec().Run(ctx, workspace, sandboxName, command, v1.ExecOptions{}) + } + if err != nil { + return "", err + } + if result.ExitCode != 0 { + return "", fmt.Errorf("exec exited %d: %s", result.ExitCode, string(result.Stderr)) + } + if len(result.Stderr) != 0 { + return "", fmt.Errorf("exec wrote unexpected stderr: %s", string(result.Stderr)) + } + return string(result.Stdout), nil +} + +func isPlaceholderForEnvKey(value, key string) bool { + const prefix = "openshell:resolve:env:" + suffix, ok := strings.CutPrefix(value, prefix) + if !ok { + return false + } + if suffix == key { + return true + } + + discriminator, placeholderKey, ok := strings.Cut(suffix, "_") + if !ok || placeholderKey != key || len(discriminator) < 2 { + return false + } + + switch discriminator[0] { + case 'v': + for _, char := range discriminator[1:] { + if char < '0' || char > '9' { + return false + } + } + return true + case 's': + if len(discriminator) != 65 { + return false + } + for _, char := range discriminator[1:] { + if !((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f')) { + return false + } + } + return true + default: + return false + } +} + +func TestIsPlaceholderForEnvKey(t *testing.T) { + stableHandle := strings.Repeat("a1", 32) + tests := []struct { + name string + value string + key string + want bool + }{ + {name: "plain", value: "openshell:resolve:env:API_KEY", key: "API_KEY", want: true}, + {name: "revisioned", value: "openshell:resolve:env:v12_API_KEY", key: "API_KEY", want: true}, + {name: "stable handle", value: "openshell:resolve:env:s" + stableHandle + "_API_KEY", key: "API_KEY", want: true}, + {name: "overlapping key suffix", value: "openshell:resolve:env:v12_LONG_API_KEY", key: "API_KEY", want: false}, + {name: "revision requires digits", value: "openshell:resolve:env:vnext_API_KEY", key: "API_KEY", want: false}, + {name: "stable handle requires lowercase hex", value: "openshell:resolve:env:s" + strings.ToUpper(stableHandle) + "_API_KEY", key: "API_KEY", want: false}, + {name: "stable handle requires 64 characters", value: "openshell:resolve:env:sabc_API_KEY", key: "API_KEY", want: false}, + {name: "wrong key", value: "openshell:resolve:env:v12_OTHER_KEY", key: "API_KEY", want: false}, + {name: "raw secret", value: "secret", key: "API_KEY", want: false}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.want, isPlaceholderForEnvKey(test.value, test.key)) + }) + } +} + +// pollUntil calls fetch until the predicate is satisfied, the local polling +// timeout expires, or ctx is done, whichever happens first. +func pollUntil[T any](t *testing.T, ctx context.Context, fetch func() T, predicate func(T) bool) T { + t.Helper() + deadline := time.NewTimer(35 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + + for { + value := fetch() + if predicate(value) { + return value + } + select { + case <-ctx.Done(): + t.Fatalf("context done while polling; last observed %v: %v", value, ctx.Err()) + case <-deadline.C: + t.Fatalf("timed out waiting for expected value, last observed %v", value) + case <-ticker.C: + } + } +} + +// defaultPolicy returns a baseline sandbox policy sufficient for exec-based tests. +func defaultPolicy() *v1.SandboxPolicy { + return &v1.SandboxPolicy{ + Version: 1, + Filesystem: &v1.FilesystemPolicy{ + IncludeWorkdir: true, + ReadOnly: []string{"/usr", "/lib", "/lib64", "/proc", "/etc", "/app", "/dev/urandom"}, + ReadWrite: []string{"/sandbox", "/tmp", "/dev/null"}, + }, + Landlock: &v1.LandlockPolicy{Compatibility: "best_effort"}, + Process: &v1.ProcessPolicy{RunAsUser: "10001", RunAsGroup: "10001"}, + } +} diff --git a/e2e/providers_test.go b/e2e/providers_test.go new file mode 100644 index 0000000..9e6a1c1 --- /dev/null +++ b/e2e/providers_test.go @@ -0,0 +1,308 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build e2e + +// Provider credentials are fetched at runtime by the sandbox supervisor. +// Sandboxed child processes must see placeholder values (never raw secrets), +// and only when a provider is actually attached to the sandbox. +package e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" +) + +// requireProviderResponse checks the stable public fields returned by provider +// APIs. Credentials are write-only and intentionally omitted from Go SDK +// provider responses. +func requireProviderResponse(t *testing.T, provider *v1.Provider, workspace, name, providerType string) { + t.Helper() + require.NotNil(t, provider) + require.NotEmpty(t, provider.ID) + require.Equal(t, workspace, provider.Workspace) + require.Equal(t, name, provider.Name) + require.Equal(t, providerType, provider.Type) + require.NotZero(t, provider.ResourceVersion) + require.Empty(t, provider.Spec.Credentials) +} + +func deleteProviderIgnoreNotFound(ctx context.Context, t *testing.T, client *v1.Client, workspace, name string) { + t.Helper() + _, err := client.Providers().Delete(ctx, workspace, name) + if err != nil && !v1.IsNotFound(err) { + require.NoError(t, err) + } +} + +// detachProviderBestEffort clears a provider from a sandbox's spec before the +// sandbox is deleted. Sandbox deletion removes the gateway's Sandbox record +// asynchronously (via a background watcher), so a provider-delete cleanup +// racing right behind a sandbox-delete cleanup can still see the sandbox as +// attached and fail with a conflict unless the attachment is cleared +// synchronously first. +func detachProviderBestEffort(ctx context.Context, client *v1.Client, workspace, sandboxName, providerName string) { + if current, err := client.Sandboxes().Get(ctx, workspace, sandboxName); err == nil { + _, _ = client.Sandboxes().DetachProvider(ctx, workspace, sandboxName, providerName, current.ResourceVersion) + } +} + +// attachProviderRetry attaches a provider to a sandbox, retrying with a +// freshly fetched resource version whenever the gateway reports a +// concurrent-modification conflict (e.g. a status update racing the +// optimistic-concurrency check between Get and AttachProvider). +func attachProviderRetry(ctx context.Context, t *testing.T, client *v1.Client, workspace, sandboxName, providerName string) *v1.AttachProviderResult { + t.Helper() + const maxAttempts = 50 + for attempt := 1; attempt <= maxAttempts; attempt++ { + current, err := client.Sandboxes().Get(ctx, workspace, sandboxName) + require.NoError(t, err) + result, err := client.Sandboxes().AttachProvider(ctx, workspace, sandboxName, providerName, current.ResourceVersion) + if err == nil { + return result + } + if !v1.IsConflict(err) { + require.NoError(t, err) + } + if attempt%10 == 0 { + t.Logf("attach provider still conflicted after %d attempts: %v", attempt, err) + } + if attempt == maxAttempts { + t.Fatalf("attach provider still conflicted after %d attempts: %v", attempt, err) + } + select { + case <-ctx.Done(): + t.Fatalf("context done while retrying attach provider: %v", ctx.Err()) + case <-time.After(200 * time.Millisecond): + } + } + return nil +} + +// detachProviderRetry mirrors attachProviderRetry for detach. +func detachProviderRetry(ctx context.Context, t *testing.T, client *v1.Client, workspace, sandboxName, providerName string) *v1.DetachProviderResult { + t.Helper() + const maxAttempts = 50 + for attempt := 1; attempt <= maxAttempts; attempt++ { + current, err := client.Sandboxes().Get(ctx, workspace, sandboxName) + require.NoError(t, err) + result, err := client.Sandboxes().DetachProvider(ctx, workspace, sandboxName, providerName, current.ResourceVersion) + if err == nil { + return result + } + if !v1.IsConflict(err) { + require.NoError(t, err) + } + if attempt%10 == 0 { + t.Logf("detach provider still conflicted after %d attempts: %v", attempt, err) + } + if attempt == maxAttempts { + t.Fatalf("detach provider still conflicted after %d attempts: %v", attempt, err) + } + select { + case <-ctx.Done(): + t.Fatalf("context done while retrying detach provider: %v", ctx.Err()) + case <-time.After(200 * time.Millisecond): + } + } + return nil +} + +func TestProviderCredentialsAvailableAsEnvVar(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + providerName := uniqueName("prov-env") + const secret = "sk-e2e-test-key-12345" + provider, err := client.Providers().Create(ctx, "default", &v1.Provider{ + Name: providerName, + Type: "claude-code", + Spec: v1.ProviderSpec{Credentials: map[string]string{"ANTHROPIC_API_KEY": secret}}, + }) + require.NoError(t, err) + requireProviderResponse(t, provider, "default", providerName, "claude-code") + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + deleteProviderIgnoreNotFound(cleanupCtx, t, client, "default", providerName) + }) + + sandboxName := uniqueName("sb-penv") + sandbox, err := client.Sandboxes().Create(ctx, "default", sandboxName, &v1.SandboxSpec{ + Policy: defaultPolicy(), + Providers: []string{providerName}, + Command: []string{"sleep", "infinity"}, + }, nil) + require.NoError(t, err) + requireSandboxResponse(t, sandbox, "default", sandboxName) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + detachProviderBestEffort(cleanupCtx, client, "default", sandboxName, providerName) + _, err := client.Sandboxes().Delete(cleanupCtx, "default", sandboxName) + require.NoError(t, err) + }) + + ready, err := client.Sandboxes().WaitReady(ctx, "default", sandboxName) + require.NoError(t, err) + requireReadySandbox(t, ready, sandbox.ID) + + value, err := readEnvVar(ctx, client, "default", sandboxName, "ANTHROPIC_API_KEY") + require.NoError(t, err) + require.True(t, isPlaceholderForEnvKey(value, "ANTHROPIC_API_KEY"), "expected a placeholder, got %q", value) + require.NotEqual(t, secret, value) +} + +func TestProfilelessProviderCreationIsRejected(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + providerName := uniqueName("prov-generic") + _, err := client.Providers().Create(ctx, "default", &v1.Provider{ + Name: providerName, + Type: "generic", + Spec: v1.ProviderSpec{Credentials: map[string]string{ + "CUSTOM_SERVICE_TOKEN": "token-generic-123", + "CUSTOM_SERVICE_URL": "https://internal.example.test/api", + }}, + }) + require.Error(t, err) + require.True(t, v1.IsInvalidArgument(err), "expected InvalidArgument, got: %v", err) + require.ErrorContains(t, err, "provider profile 'generic' was not found") +} + +func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + providerName := uniqueName("prov-attach") + provider, err := client.Providers().Create(ctx, "default", &v1.Provider{ + Name: providerName, + Type: "nvidia", + Spec: v1.ProviderSpec{Credentials: map[string]string{"NVIDIA_API_KEY": "nvapi-e2e-test-key"}}, + }) + require.NoError(t, err) + requireProviderResponse(t, provider, "default", providerName, "nvidia") + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + deleteProviderIgnoreNotFound(cleanupCtx, t, client, "default", providerName) + }) + + sandboxName := uniqueName("sb-patt") + sandbox, err := client.Sandboxes().Create(ctx, "default", sandboxName, &v1.SandboxSpec{ + Policy: defaultPolicy(), + Command: []string{"sleep", "infinity"}, + }, nil) + require.NoError(t, err) + requireSandboxResponse(t, sandbox, "default", sandboxName) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + detachProviderBestEffort(cleanupCtx, client, "default", sandboxName, providerName) + _, err := client.Sandboxes().Delete(cleanupCtx, "default", sandboxName) + require.NoError(t, err) + }) + + ready, err := client.Sandboxes().WaitReady(ctx, "default", sandboxName) + require.NoError(t, err) + requireReadySandbox(t, ready, sandbox.ID) + + value, err := readEnvVar(ctx, client, "default", sandboxName, "NVIDIA_API_KEY") + require.NoError(t, err) + require.Equal(t, "NOT_SET", value) + + attachResult := attachProviderRetry(ctx, t, client, "default", sandboxName, providerName) + require.True(t, attachResult.Attached) + requireSandboxResponse(t, attachResult.Sandbox, "default", sandboxName) + require.Equal(t, sandbox.ID, attachResult.Sandbox.ID) + require.Contains(t, attachResult.Sandbox.Spec.Providers, providerName) + + value = pollUntil(t, ctx, func() string { + v, err := readEnvVar(ctx, client, "default", sandboxName, "NVIDIA_API_KEY") + require.NoError(t, err) + return v + }, func(v string) bool { return v != "NOT_SET" }) + require.True(t, isPlaceholderForEnvKey(value, "NVIDIA_API_KEY"), "expected a placeholder, got %q", value) + + detachResult := detachProviderRetry(ctx, t, client, "default", sandboxName, providerName) + require.True(t, detachResult.Detached) + requireSandboxResponse(t, detachResult.Sandbox, "default", sandboxName) + require.Equal(t, sandbox.ID, detachResult.Sandbox.ID) + require.NotContains(t, detachResult.Sandbox.Spec.Providers, providerName) + + value = pollUntil(t, ctx, func() string { + v, err := readEnvVar(ctx, client, "default", sandboxName, "NVIDIA_API_KEY") + require.NoError(t, err) + return v + }, func(v string) bool { return v == "NOT_SET" }) + require.Equal(t, "NOT_SET", value) +} + +func TestProviderCRUDResponseContract(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + providerName := uniqueName("prov-crud") + const secret = "sk-e2e-provider-crud-12345" + created, err := client.Providers().Create(ctx, "default", &v1.Provider{ + Name: providerName, + Type: "claude-code", + Labels: map[string]string{"e2e": "provider-response-contract"}, + Spec: v1.ProviderSpec{ + Credentials: map[string]string{"ANTHROPIC_API_KEY": secret}, + }, + }) + require.NoError(t, err) + requireProviderResponse(t, created, "default", providerName, "claude-code") + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + deleteProviderIgnoreNotFound(cleanupCtx, t, client, "default", providerName) + }) + require.Equal(t, "provider-response-contract", created.Labels["e2e"]) + + fetched, err := client.Providers().Get(ctx, "default", providerName) + require.NoError(t, err) + requireProviderResponse(t, fetched, "default", providerName, "claude-code") + require.Equal(t, created.ID, fetched.ID) + + updatedInput := *fetched + // Get omits write-only credentials, so leave them unchanged in this update. + updatedInput.Spec.Credentials = nil + updatedInput.Spec.Config = map[string]string{"e2e-response-contract": "updated"} + updated, err := client.Providers().Update(ctx, "default", &updatedInput) + require.NoError(t, err) + requireProviderResponse(t, updated, "default", providerName, "claude-code") + require.Equal(t, "updated", updated.Spec.Config["e2e-response-contract"]) + require.Greater(t, updated.ResourceVersion, fetched.ResourceVersion) + + providers, err := client.Providers().ListAll(ctx, "default") + require.NoError(t, err) + for _, listed := range providers { + if listed.Name == providerName { + requireProviderResponse(t, listed, "default", providerName, "claude-code") + require.Equal(t, updated.ID, listed.ID) + require.Equal(t, "updated", listed.Spec.Config["e2e-response-contract"]) + return + } + } + t.Fatalf("expected provider %q in List response", providerName) +} diff --git a/e2e/sandbox_lifecycle_test.go b/e2e/sandbox_lifecycle_test.go new file mode 100644 index 0000000..adf6830 --- /dev/null +++ b/e2e/sandbox_lifecycle_test.go @@ -0,0 +1,314 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "slices" + "testing" + "time" + + "github.com/stretchr/testify/require" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" +) + +func TestSandboxCRUDAndExec(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + + name := uniqueName("sb-crud") + policy := defaultPolicy() + sb, err := client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{ + Policy: policy, + Command: []string{"sleep", "infinity"}, + }, nil) + require.NoError(t, err) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cleanupCancel() + _, err := client.Sandboxes().Delete(cleanupCtx, "default", name) + require.NoError(t, err) + }) + requireSandboxResponse(t, sb, "default", name) + require.Equal(t, policy, sb.Spec.Policy) + + ready, err := client.Sandboxes().WaitReady(ctx, "default", name) + require.NoError(t, err) + requireReadySandbox(t, ready, sb.ID) + + fetched, err := client.Sandboxes().Get(ctx, "default", name) + require.NoError(t, err) + requireSandboxResponse(t, fetched, "default", name) + require.Equal(t, sb.ID, fetched.ID) + require.Equal(t, policy, fetched.Spec.Policy) + + sandboxes, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{PageSize: 100}) + require.NoError(t, err) + require.True(t, containsID(sandboxes, sb.ID)) + + result, err := client.Exec().Run(ctx, "default", name, []string{"sh", "-c", "printf sandbox-ok"}, v1.ExecOptions{}) + require.NoError(t, err) + require.Equal(t, 0, result.ExitCode) + require.Equal(t, "sandbox-ok", string(result.Stdout)) + require.Empty(t, result.Stderr) + + failedResult, err := client.Exec().Run(ctx, "default", name, + []string{"sh", "-c", "printf exec-failed >&2; exit 42"}, v1.ExecOptions{}) + require.NoError(t, err) + require.Equal(t, 42, failedResult.ExitCode) + require.Empty(t, failedResult.Stdout) + require.Contains(t, string(failedResult.Stderr), "exec-failed") + + // Exec launches share the same sandbox filesystem across calls. + writeResult, err := client.Exec().Run(ctx, "default", name, + []string{"sh", "-c", "echo persisted > /sandbox/exec-persistence.txt"}, v1.ExecOptions{}) + require.NoError(t, err) + require.Equal(t, 0, writeResult.ExitCode) + require.Empty(t, writeResult.Stderr) + + readResult, err := client.Exec().Run(ctx, "default", name, + []string{"cat", "/sandbox/exec-persistence.txt"}, v1.ExecOptions{}) + require.NoError(t, err) + require.Equal(t, 0, readResult.ExitCode) + require.Equal(t, "persisted\n", string(readResult.Stdout)) + require.Empty(t, readResult.Stderr) +} + +func TestSandboxGetNonexistentNotFound(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + _, err := client.Sandboxes().Get(ctx, "default", uniqueName("no-such-sb")) + require.True(t, v1.IsNotFound(err), "expected NotFound, got %v", err) +} + +func TestSandboxDeleteNonexistentNotFound(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + _, err := client.Sandboxes().Delete(ctx, "default", uniqueName("no-such-sb")) + require.True(t, v1.IsNotFound(err), "expected NotFound, got %v", err) +} + +func TestSandboxCreateDuplicateAlreadyExists(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + name := uniqueName("sb-dup") + sandbox, err := client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}, nil) + require.NoError(t, err) + requireSandboxResponse(t, sandbox, "default", name) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cleanupCancel() + _, err := client.Sandboxes().Delete(cleanupCtx, "default", name) + require.NoError(t, err) + }) + + _, err = client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}, nil) + require.True(t, v1.IsAlreadyExists(err), "expected AlreadyExists, got %v", err) +} + +func TestSandboxListScopedAndAllWorkspaces(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + otherWorkspace := uniqueName("list-ws") + _, err := client.Workspaces().Create(ctx, otherWorkspace, nil) + require.NoError(t, err) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + // Sandbox deletion (registered after this cleanup, so it runs first + // under LIFO ordering) only asynchronously clears the store row via a + // background watcher. Workspace deletion is blocked while any + // sandbox still references it, so wait for the workspace to drain + // before attempting the delete. + waitForWorkspaceSandboxesGone(cleanupCtx, client, otherWorkspace) + _, _ = client.Workspaces().Delete(cleanupCtx, otherWorkspace) + }) + + defaultName := uniqueName("ls-def") + defaultSandbox, err := client.Sandboxes().Create(ctx, "default", defaultName, &v1.SandboxSpec{}, nil) + require.NoError(t, err) + requireSandboxResponse(t, defaultSandbox, "default", defaultName) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, _ = client.Sandboxes().Delete(cleanupCtx, "default", defaultName) + }) + + otherName := uniqueName("ls-oth") + otherSandbox, err := client.Sandboxes().Create(ctx, otherWorkspace, otherName, &v1.SandboxSpec{}, nil) + require.NoError(t, err) + requireSandboxResponse(t, otherSandbox, otherWorkspace, otherName) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, _ = client.Sandboxes().Delete(cleanupCtx, otherWorkspace, otherName) + }) + + defaultList, err := client.Sandboxes().ListAll(ctx, "default") + require.NoError(t, err) + require.True(t, containsID(defaultList, defaultSandbox.ID)) + require.False(t, containsID(defaultList, otherSandbox.ID)) + + otherList, err := client.Sandboxes().ListAll(ctx, otherWorkspace) + require.NoError(t, err) + require.True(t, containsID(otherList, otherSandbox.ID)) + require.False(t, containsID(otherList, defaultSandbox.ID)) + + allList, err := client.Sandboxes().ListAll(ctx, "", v1.ListOptions{AllWorkspaces: true}) + require.NoError(t, err) + require.True(t, containsID(allList, defaultSandbox.ID)) + require.True(t, containsID(allList, otherSandbox.ID)) +} + +func TestSandboxLabelsAndSelectors(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + suffix := uniqueName("lbl") + jobA := fmt.Sprintf("%s-a", suffix) + jobB := fmt.Sprintf("%s-b", suffix) + groupSelector := fmt.Sprintf("aiq-test=%s", suffix) + primarySelector := fmt.Sprintf("aiq-test=%s,role=primary", suffix) + + refA, err := client.Sandboxes().Create(ctx, "default", jobA, &v1.SandboxSpec{}, + map[string]string{"aiq-test": suffix, "role": "primary"}) + require.NoError(t, err) + requireSandboxResponse(t, refA, "default", jobA) + deletedA := false + t.Cleanup(func() { + if deletedA { + return + } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, _ = client.Sandboxes().Delete(cleanupCtx, "default", jobA) + }) + + refB, err := client.Sandboxes().Create(ctx, "default", jobB, &v1.SandboxSpec{}, + map[string]string{"aiq-test": suffix, "role": "secondary"}) + require.NoError(t, err) + requireSandboxResponse(t, refB, "default", jobB) + deletedB := false + t.Cleanup(func() { + if deletedB { + return + } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, _ = client.Sandboxes().Delete(cleanupCtx, "default", jobB) + }) + + require.Equal(t, "primary", refA.Labels["role"]) + + fetchedA, err := client.Sandboxes().Get(ctx, "default", jobA) + require.NoError(t, err) + requireSandboxResponse(t, fetchedA, "default", jobA) + require.Equal(t, "primary", fetchedA.Labels["role"]) + + fetchedB, err := client.Sandboxes().Get(ctx, "default", jobB) + require.NoError(t, err) + requireSandboxResponse(t, fetchedB, "default", jobB) + require.Equal(t, "secondary", fetchedB.Labels["role"]) + + primaryOnly, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{LabelSelector: primarySelector}) + require.NoError(t, err) + require.ElementsMatch(t, []string{jobA}, names(primaryOnly)) + + both, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{LabelSelector: groupSelector}) + require.NoError(t, err) + require.ElementsMatch(t, []string{jobA, jobB}, names(both)) + + _, err = client.Sandboxes().Delete(ctx, "default", jobA) + require.NoError(t, err) + deletedA = true + + // Sandbox deletion becomes list-visible asynchronously, so poll until the + // compute driver's deletion event drains through the background watcher. + remaining := pollUntil(t, ctx, func() []string { + list, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{LabelSelector: groupSelector}) + require.NoError(t, err) + return names(list) + }, func(values []string) bool { return elementsMatch(values, []string{jobB}) }) + require.ElementsMatch(t, []string{jobB}, remaining) + + _, err = client.Sandboxes().Delete(ctx, "default", jobB) + require.NoError(t, err) + deletedB = true + + empty := pollUntil(t, ctx, func() []string { + list, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{LabelSelector: groupSelector}) + require.NoError(t, err) + return names(list) + }, func(values []string) bool { return len(values) == 0 }) + require.Empty(t, empty) +} + +func elementsMatch(a, b []string) bool { + return slices.Equal(slices.Sorted(slices.Values(a)), slices.Sorted(slices.Values(b))) +} + +// waitForWorkspaceSandboxesGone polls until a workspace has no sandboxes +// left, up to a 20s deadline. It is best-effort: cleanup proceeds regardless +// of whether the deadline is reached, since the subsequent workspace delete +// is itself best-effort in callers of this helper. +func waitForWorkspaceSandboxesGone(ctx context.Context, client *v1.Client, workspace string) { + deadline := time.Now().Add(20 * time.Second) + for { + list, err := client.Sandboxes().ListAll(ctx, workspace) + if err == nil && len(list) == 0 { + return + } + if time.Now().After(deadline) { + return + } + select { + case <-ctx.Done(): + return + case <-time.After(time.Second): + } + } +} + +func containsID(sandboxes []*v1.Sandbox, id string) bool { + for _, sb := range sandboxes { + if sb.ID == id { + return true + } + } + return false +} + +func names(sandboxes []*v1.Sandbox) []string { + result := make([]string, 0, len(sandboxes)) + for _, sb := range sandboxes { + result = append(result, sb.Name) + } + return result +} diff --git a/e2e/workspace_test.go b/e2e/workspace_test.go new file mode 100644 index 0000000..dd82faf --- /dev/null +++ b/e2e/workspace_test.go @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build e2e + +package e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" +) + +func requireWorkspaceResponse(t *testing.T, workspace *v1.Workspace, name string) { + t.Helper() + require.NotNil(t, workspace) + require.NotEmpty(t, workspace.ID) + require.Equal(t, name, workspace.Name) + require.False(t, workspace.CreatedAt.IsZero()) + require.NotZero(t, workspace.ResourceVersion) +} + +func TestWorkspaceCRUD(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + name := uniqueName("ws-crud") + ws, err := client.Workspaces().Create(ctx, name, nil) + require.NoError(t, err) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, err := client.Workspaces().Delete(cleanupCtx, name) + require.NoError(t, err) + }) + require.Equal(t, name, ws.Name) + require.Equal(t, v1.WorkspaceActive, ws.Phase) + requireWorkspaceResponse(t, ws, name) + + fetched, err := client.Workspaces().Get(ctx, name) + require.NoError(t, err) + require.Equal(t, name, fetched.Name) + require.Equal(t, v1.WorkspaceActive, fetched.Phase) + requireWorkspaceResponse(t, fetched, name) + require.Equal(t, ws.ID, fetched.ID) +} + +func TestWorkspaceCreateWithLabels(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + name := uniqueName("ws-lbl") + ws, err := client.Workspaces().Create(ctx, name, map[string]string{"env": "test", "team": "infra"}) + require.NoError(t, err) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, err := client.Workspaces().Delete(cleanupCtx, name) + require.NoError(t, err) + }) + require.Equal(t, "test", ws.Labels["env"]) + require.Equal(t, "infra", ws.Labels["team"]) + requireWorkspaceResponse(t, ws, name) + + fetched, err := client.Workspaces().Get(ctx, name) + require.NoError(t, err) + require.Equal(t, "test", fetched.Labels["env"]) + require.Equal(t, "infra", fetched.Labels["team"]) + requireWorkspaceResponse(t, fetched, name) + require.Equal(t, ws.ID, fetched.ID) +} + +func TestWorkspaceListIncludesCreated(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + name := uniqueName("ws-list") + _, err := client.Workspaces().Create(ctx, name, nil) + require.NoError(t, err) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cleanupCancel() + _, err := client.Workspaces().Delete(cleanupCtx, name) + require.NoError(t, err) + }) + + workspaces, err := client.Workspaces().ListAll(ctx) + require.NoError(t, err) + + found := false + hasDefault := false + for _, ws := range workspaces { + if ws.Name == name { + found = true + } + if ws.Name == "default" { + hasDefault = true + } + } + require.True(t, found, "expected created workspace %q in list", name) + require.True(t, hasDefault, "expected \"default\" workspace in list") +} + +func TestWorkspaceDeleteNonexistentNotFound(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + _, err := client.Workspaces().Delete(ctx, uniqueName("no-such-ws")) + require.True(t, v1.IsNotFound(err), "expected NotFound, got %v", err) +} + +func TestWorkspaceGetNonexistentNotFound(t *testing.T) { + client := requireClient(t) + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + _, err := client.Workspaces().Get(ctx, uniqueName("no-ws")) + require.True(t, v1.IsNotFound(err), "expected NotFound, got %v", err) +} From 57c438e874259761d041b8910e2a37eebefb6611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:21:05 +0100 Subject: [PATCH 10/29] test(e2e): use CreateOption for sandbox labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite from NVIDIA/OpenShell#3338 predates the switch of Sandboxes().Create from a labels map to CreateOption values. Pass labels through v1.WithLabels and drop the nil maps. Signed-off-by: Roland Huß --- e2e/sandbox_lifecycle_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/e2e/sandbox_lifecycle_test.go b/e2e/sandbox_lifecycle_test.go index adf6830..d5f27a4 100644 --- a/e2e/sandbox_lifecycle_test.go +++ b/e2e/sandbox_lifecycle_test.go @@ -112,7 +112,7 @@ func TestSandboxCreateDuplicateAlreadyExists(t *testing.T) { defer cancel() name := uniqueName("sb-dup") - sandbox, err := client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}, nil) + sandbox, err := client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}) require.NoError(t, err) requireSandboxResponse(t, sandbox, "default", name) t.Cleanup(func() { @@ -122,7 +122,7 @@ func TestSandboxCreateDuplicateAlreadyExists(t *testing.T) { require.NoError(t, err) }) - _, err = client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}, nil) + _, err = client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{}) require.True(t, v1.IsAlreadyExists(err), "expected AlreadyExists, got %v", err) } @@ -149,7 +149,7 @@ func TestSandboxListScopedAndAllWorkspaces(t *testing.T) { }) defaultName := uniqueName("ls-def") - defaultSandbox, err := client.Sandboxes().Create(ctx, "default", defaultName, &v1.SandboxSpec{}, nil) + defaultSandbox, err := client.Sandboxes().Create(ctx, "default", defaultName, &v1.SandboxSpec{}) require.NoError(t, err) requireSandboxResponse(t, defaultSandbox, "default", defaultName) t.Cleanup(func() { @@ -159,7 +159,7 @@ func TestSandboxListScopedAndAllWorkspaces(t *testing.T) { }) otherName := uniqueName("ls-oth") - otherSandbox, err := client.Sandboxes().Create(ctx, otherWorkspace, otherName, &v1.SandboxSpec{}, nil) + otherSandbox, err := client.Sandboxes().Create(ctx, otherWorkspace, otherName, &v1.SandboxSpec{}) require.NoError(t, err) requireSandboxResponse(t, otherSandbox, otherWorkspace, otherName) t.Cleanup(func() { @@ -198,7 +198,7 @@ func TestSandboxLabelsAndSelectors(t *testing.T) { primarySelector := fmt.Sprintf("aiq-test=%s,role=primary", suffix) refA, err := client.Sandboxes().Create(ctx, "default", jobA, &v1.SandboxSpec{}, - map[string]string{"aiq-test": suffix, "role": "primary"}) + v1.WithLabels(map[string]string{"aiq-test": suffix, "role": "primary"})) require.NoError(t, err) requireSandboxResponse(t, refA, "default", jobA) deletedA := false @@ -212,7 +212,7 @@ func TestSandboxLabelsAndSelectors(t *testing.T) { }) refB, err := client.Sandboxes().Create(ctx, "default", jobB, &v1.SandboxSpec{}, - map[string]string{"aiq-test": suffix, "role": "secondary"}) + v1.WithLabels(map[string]string{"aiq-test": suffix, "role": "secondary"})) require.NoError(t, err) requireSandboxResponse(t, refB, "default", jobB) deletedB := false From e67b070b4a1d499f4888018fbfcf0d3442ab2ce2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:22:44 +0100 Subject: [PATCH 11/29] feat(hack): run the published gateway for E2E from core's compose files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit start-gateway.sh fetches deploy/docker/docker-compose.yml and gateway.toml from core at the given tag, pins the supervisor and sandbox images to the same version, starts the gateway with the Docker driver, waits for /readyz, and registers it as gateway 'e2e' for the SDK. It first waits up to 15 minutes for the gateway image of a fresh tag. stop-gateway.sh saves the gateway log and removes the gateway and the sandbox containers it created. Signed-off-by: Roland Huß --- hack/automation/start-gateway.sh | 104 +++++++++++++++++++++++++++++++ hack/automation/stop-gateway.sh | 23 +++++++ 2 files changed, 127 insertions(+) create mode 100755 hack/automation/start-gateway.sh create mode 100755 hack/automation/stop-gateway.sh diff --git a/hack/automation/start-gateway.sh b/hack/automation/start-gateway.sh new file mode 100755 index 0000000..7014402 --- /dev/null +++ b/hack/automation/start-gateway.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# start-gateway.sh: run the published OpenShell gateway for a core version +# with the Docker compute driver, for the E2E lane. +# +# Usage: start-gateway.sh [--state-dir ] +# +# Uses core's own deployment files, deploy/docker/docker-compose.yml and +# gateway.toml, at the core tag: an init container generates the supervisor +# JWT keys, and the gateway serves plaintext gRPC on 127.0.0.1:8080 and +# /readyz on 127.0.0.1:8081. The supervisor and sandbox images are pinned to +# the same version instead of :latest. Then registers the gateway as "e2e" +# for the SDK in $XDG_CONFIG_HOME/openshell. Waits up to 15 minutes for the +# gateway image of a fresh tag to be published. +# +# Needs docker with the compose plugin and a host path /var/lib/openshell +# (core's compose file bind-mounts it at the same path). stop-gateway.sh +# undoes everything. +set -euo pipefail + +core_repo=${CORE_REPO:-NVIDIA/OpenShell} +registry=ghcr.io/nvidia/openshell +name=e2e +port=8080 +health_port=8081 + +tag= +state=${OPENSHELL_E2E_STATE:-${RUNNER_TEMP:-/tmp}/openshell-e2e} +while [ $# -gt 0 ]; do + case $1 in + --state-dir) state=${2:?--state-dir needs a path}; shift 2 ;; + -*) echo "usage: $0 [--state-dir ]" >&2; exit 2 ;; + *) tag=$1; shift ;; + esac +done +[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-pre\.[0-9]+)?$ ]] || { + echo "usage: $0 (vX.Y.Z or vX.Y.Z-pre.N)" >&2 + exit 2 +} +semver=${tag#v} +mkdir -p "$state" +echo "$tag" >"$state/core-version" + +# Core pushes images after tagging; a proposal can be faster than that. +manifest_exists() { + local token + token=$(curl -fsS "https://ghcr.io/token?scope=repository:nvidia/openshell/gateway:pull" | jq -r .token) || return 1 + curl -fsS -o /dev/null -H "Authorization: Bearer $token" \ + -H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.oci.image.manifest.v1+json' \ + "https://ghcr.io/v2/nvidia/openshell/gateway/manifests/$semver" +} +for i in $(seq 1 15); do + manifest_exists && break + if [ "$i" -eq 15 ]; then + echo "ERROR: gateway image for $semver not published yet, re-run later" >&2 + exit 1 + fi + echo "Waiting for $registry/gateway:$semver ($i/15) ..." + sleep 60 +done + +# Core's deployment files at the tag. +base="https://raw.githubusercontent.com/$core_repo/$tag/deploy/docker" +curl -fsSL "$base/docker-compose.yml" -o "$state/docker-compose.yml" +curl -fsSL "$base/gateway.toml" -o "$state/gateway.toml" +sed -i.bak \ + -e "s#\"$registry/supervisor:latest\"#\"$registry/supervisor:$semver\"#" \ + -e "s#\"$registry/sandbox:latest\"#\"$registry/sandbox:$semver\"#" \ + "$state/gateway.toml" && rm -f "$state/gateway.toml.bak" +grep -q "supervisor:$semver" "$state/gateway.toml" || { + echo "ERROR: could not pin the supervisor image in core's gateway.toml at $tag" >&2 + exit 1 +} + +compose() { IMAGE_TAG=$semver docker compose -p openshell-e2e -f "$state/docker-compose.yml" "$@"; } +echo "Starting gateway $semver ..." +compose up -d --quiet-pull + +for i in $(seq 1 90); do + if curl -fsS -o /dev/null "http://127.0.0.1:$health_port/readyz"; then + break + fi + if [ "$i" -eq 90 ]; then + echo "ERROR: gateway not ready after 180 s" >&2 + compose logs --no-color gateway | tail -n 80 >&2 || true + exit 1 + fi + sleep 2 +done +echo "Gateway $semver ready on 127.0.0.1:$port." + +config_home=${XDG_CONFIG_HOME:-$HOME/.config} +dir="$config_home/openshell/gateways/$name" +mkdir -p "$dir" +cat >"$dir/metadata.json" <"$config_home/openshell/active_gateway" +echo "Registered gateway '$name' in $config_home/openshell; run the suite with OPENSHELL_GATEWAY=$name." diff --git a/hack/automation/stop-gateway.sh b/hack/automation/stop-gateway.sh new file mode 100755 index 0000000..8469c5b --- /dev/null +++ b/hack/automation/stop-gateway.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# stop-gateway.sh: stop the E2E gateway started by start-gateway.sh, save its +# log, and remove the sandbox containers it created. +# +# Usage: stop-gateway.sh [--state-dir ] +# +# Writes /gateway.log. Safe to run when nothing is running. +set -uo pipefail + +state=${OPENSHELL_E2E_STATE:-${RUNNER_TEMP:-/tmp}/openshell-e2e} +[ "${1:-}" != --state-dir ] || state=${2:?--state-dir needs a path} +[ -f "$state/docker-compose.yml" ] || { echo "No E2E gateway state in $state."; exit 0; } + +semver=$(sed 's/^v//' "$state/core-version" 2>/dev/null || echo latest) +compose() { IMAGE_TAG=$semver docker compose -p openshell-e2e -f "$state/docker-compose.yml" "$@"; } + +compose logs --no-color --timestamps >"$state/gateway.log" 2>&1 +echo "Gateway log: $state/gateway.log" +# Sandbox containers carry the namespace label from core's gateway.toml. +ids=$(docker ps -aq --filter label=openshell.sandbox_namespace=openshell) +[ -z "$ids" ] || docker rm -f $ids >/dev/null +compose down --volumes --remove-orphans >/dev/null 2>&1 +echo "Gateway stopped." From cf23bd4dc61d80e2456cb8d575e979e06a6ca0d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:22:45 +0100 Subject: [PATCH 12/29] ci: run the E2E suite against the published gateway MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit e2e.yml starts the gateway for a core version (default the pin), runs mise run e2e, and uploads the gateway log on failure. ci.yml calls it for pull requests that change the pin, the bindings, the SDK code, the suite, or the gateway scripts. Signed-off-by: Roland Huß --- .github/workflows/ci.yml | 30 ++++++++++++++++++ .github/workflows/e2e.yml | 66 +++++++++++++++++++++++++++++++++++++++ mise.toml | 4 +++ 3 files changed, 100 insertions(+) create mode 100644 .github/workflows/e2e.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 67ff9ce..2717a97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,3 +55,33 @@ jobs: - name: Lint workflows run: mise run workflows:check + + changes: + name: changes + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + e2e: ${{ steps.diff.outputs.e2e }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - id: diff + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + if git diff --name-only "${BASE_SHA}...HEAD" | grep -qE '^(buf\.gen\.yaml$|proto/|openshell/|e2e/|hack/automation/(start|stop)-gateway\.sh$)'; then + echo "e2e=true" >>"$GITHUB_OUTPUT" + else + echo "e2e=false" >>"$GITHUB_OUTPUT" + fi + + e2e: + name: e2e + needs: changes + if: needs.changes.outputs.e2e == 'true' + uses: ./.github/workflows/e2e.yml diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000..b2e9e5d --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Runs the E2E suite against the published gateway of a core version, started +# from core's deploy/docker files (hack/automation/start-gateway.sh). +name: e2e + +on: + workflow_call: + inputs: + core-version: + description: Core version (default the pin in buf.gen.yaml) + type: string + default: "" + workflow_dispatch: + inputs: + core-version: + description: Core version, for example v0.1.7 (default the pin in buf.gen.yaml) + type: string + default: "" + +permissions: + contents: read + +jobs: + e2e: + name: e2e + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + + - name: Install tools + run: mise install --locked go yq + + - name: Start the gateway + env: + CORE_VERSION: ${{ inputs.core-version }} + run: | + set -euo pipefail + version=${CORE_VERSION:-$(yq -r '.inputs[0].tag' buf.gen.yaml)} + echo "Core version: $version" >>"$GITHUB_STEP_SUMMARY" + hack/automation/start-gateway.sh "$version" + + - name: Run the E2E suite + env: + OPENSHELL_GATEWAY: e2e + run: mise run e2e + + - name: Stop the gateway + if: always() + run: hack/automation/stop-gateway.sh + + - name: Upload the gateway log + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: gateway-log + path: ${{ runner.temp }}/openshell-e2e/gateway.log + if-no-files-found: ignore diff --git a/mise.toml b/mise.toml index 5a49eaf..cb408f2 100644 --- a/mise.toml +++ b/mise.toml @@ -253,3 +253,7 @@ run = "hack/automation/tag-release.sh" [tasks."core:drift"] description = "Compare core main with the pin: mise run core:drift -- --out " run = "hack/automation/drift-check.sh" + +[tasks.e2e] +description = "Run the E2E suite against the gateway named in OPENSHELL_GATEWAY (see hack/automation/start-gateway.sh)" +run = "go vet -tags=e2e ./e2e/... && go test -tags=e2e -timeout 8m -parallel ${E2E_PARALLEL:-5} ./e2e/..." From d7b13084754558197981594da0789608cb13e686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:46:20 +0100 Subject: [PATCH 13/29] fix(hack): make the E2E gateway's health port reachable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core's gateway.toml binds the health server to 127.0.0.1 inside the container, so the published port 8081 never answers and the readiness wait times out. Bind it to all container interfaces; the compose file publishes it on the host's loopback only. Signed-off-by: Roland Huß --- hack/automation/start-gateway.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/hack/automation/start-gateway.sh b/hack/automation/start-gateway.sh index 7014402..88780b7 100755 --- a/hack/automation/start-gateway.sh +++ b/hack/automation/start-gateway.sh @@ -70,6 +70,15 @@ grep -q "supervisor:$semver" "$state/gateway.toml" || { echo "ERROR: could not pin the supervisor image in core's gateway.toml at $tag" >&2 exit 1 } +# Core's file binds the health server to loopback inside the container, where +# the published port can't reach it. Bind it to all container interfaces; the +# compose file publishes the port on the host's 127.0.0.1 only. +sed -i.bak 's#^health_bind_address *= *"127\.0\.0\.1:8081"#health_bind_address = "0.0.0.0:8081"#' \ + "$state/gateway.toml" && rm -f "$state/gateway.toml.bak" +grep -q '^health_bind_address = "0.0.0.0:8081"' "$state/gateway.toml" || { + echo "ERROR: could not rebind the health server in core's gateway.toml at $tag" >&2 + exit 1 +} compose() { IMAGE_TAG=$semver docker compose -p openshell-e2e -f "$state/docker-compose.yml" "$@"; } echo "Starting gateway $semver ..." From 8dee0b471e96c34eb3a03b67181e96a6daee3715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:53:24 +0100 Subject: [PATCH 14/29] test(e2e): import the provider profiles the suite uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since NVIDIA/OpenShell#3383 the gateway ships no provider profiles, so creating a claude-code or nvidia provider fails until the profile is imported. TestMain now imports both into the default workspace, based on core's example profiles, replacing earlier copies so reruns start from the same definitions. Signed-off-by: Roland Huß --- e2e/harness_test.go | 5 +++ e2e/profiles_test.go | 73 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 e2e/profiles_test.go diff --git a/e2e/harness_test.go b/e2e/harness_test.go index 5adae37..58fc2b6 100644 --- a/e2e/harness_test.go +++ b/e2e/harness_test.go @@ -59,6 +59,11 @@ func TestMain(m *testing.M) { _ = sharedClient.Close() os.Exit(1) } + if err := importTestProfiles(sharedClient); err != nil { + fmt.Fprintf(os.Stderr, "e2e: %v\n", err) + _ = sharedClient.Close() + os.Exit(1) + } code := m.Run() _ = sharedClient.Close() diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go new file mode 100644 index 0000000..76ef408 --- /dev/null +++ b/e2e/profiles_test.go @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "time" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" +) + +// The gateway ships no provider profiles; every profile a provider uses must +// be imported first. These fixtures follow core's example profiles +// (providers/claude-code.yaml and providers/nvidia.yaml), reduced to the +// credentials and endpoints the tests rely on. +var testProfiles = []v1.ProviderProfile{ + { + ID: "claude-code", + DisplayName: "Claude Code", + Description: "E2E fixture based on core's providers/claude-code.yaml", + Category: v1.ProfileCategoryAgent, + InferenceCapable: true, + Credentials: []v1.ProfileCredential{{ + Name: "api_key", + EnvVars: []string{"ANTHROPIC_API_KEY", "CLAUDE_API_KEY"}, + Required: true, + AuthStyle: "header", + HeaderName: "x-api-key", + }}, + Endpoints: []v1.NetworkEndpoint{{Host: "api.anthropic.com", Port: 443, Protocol: "rest"}}, + }, + { + ID: "nvidia", + DisplayName: "NVIDIA", + Description: "E2E fixture based on core's providers/nvidia.yaml", + Category: v1.ProfileCategoryInference, + InferenceCapable: true, + Credentials: []v1.ProfileCredential{{ + Name: "api_key", + EnvVars: []string{"NVIDIA_API_KEY"}, + Required: true, + }}, + Endpoints: []v1.NetworkEndpoint{{Host: "integrate.api.nvidia.com", Port: 443, Protocol: "rest"}}, + }, +} + +// importTestProfiles replaces the fixtures in the default workspace, so a +// rerun against the same gateway starts from the same definitions. +func importTestProfiles(client *v1.Client) error { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + profiles := client.Providers().Profiles() + items := make([]v1.ProfileImportItem, 0, len(testProfiles)) + for _, p := range testProfiles { + // A missing profile is the normal case; any other problem shows up in + // the import below. + _, _ = profiles.Delete(ctx, "default", p.ID) + items = append(items, v1.ProfileImportItem{Profile: p, Source: "e2e/profiles_test.go"}) + } + res, err := profiles.Import(ctx, "default", items) + if err != nil { + return fmt.Errorf("import provider profiles: %w", err) + } + if !res.Imported { + return fmt.Errorf("import provider profiles: rejected: %+v", res.Diagnostics) + } + return nil +} From 5dbd3dd788ebbfaf08b76322aa5dffe5c547cc8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 11:57:14 +0100 Subject: [PATCH 15/29] test(e2e): import the fixture profiles with plain endpoints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gateway rejects an endpoint protocol without access or rules, and the SDK's NetworkEndpoint can't express those yet. The tests only need the credentials, so the fixtures use host and port only. Signed-off-by: Roland Huß --- e2e/profiles_test.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go index 76ef408..94f643c 100644 --- a/e2e/profiles_test.go +++ b/e2e/profiles_test.go @@ -16,7 +16,9 @@ import ( // The gateway ships no provider profiles; every profile a provider uses must // be imported first. These fixtures follow core's example profiles // (providers/claude-code.yaml and providers/nvidia.yaml), reduced to the -// credentials and endpoints the tests rely on. +// credentials and endpoints the tests rely on. The endpoints are plain +// host/port entries: the SDK's NetworkEndpoint has no access or rules fields +// yet, and the gateway rejects a protocol without them. var testProfiles = []v1.ProviderProfile{ { ID: "claude-code", @@ -31,7 +33,7 @@ var testProfiles = []v1.ProviderProfile{ AuthStyle: "header", HeaderName: "x-api-key", }}, - Endpoints: []v1.NetworkEndpoint{{Host: "api.anthropic.com", Port: 443, Protocol: "rest"}}, + Endpoints: []v1.NetworkEndpoint{{Host: "api.anthropic.com", Port: 443}}, }, { ID: "nvidia", @@ -44,7 +46,7 @@ var testProfiles = []v1.ProviderProfile{ EnvVars: []string{"NVIDIA_API_KEY"}, Required: true, }}, - Endpoints: []v1.NetworkEndpoint{{Host: "integrate.api.nvidia.com", Port: 443, Protocol: "rest"}}, + Endpoints: []v1.NetworkEndpoint{{Host: "integrate.api.nvidia.com", Port: 443}}, }, } From 3d99fc47a684836386d90f6bdb644efb241f06d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 12:00:38 +0100 Subject: [PATCH 16/29] test(e2e): import the fixture profiles without endpoints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A credentialed L4 endpoint also needs allow_uninspected_credentials, which NetworkEndpoint can't express either. The tests only exercise credentials, so the fixtures declare no endpoints. Signed-off-by: Roland Huß --- e2e/profiles_test.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go index 94f643c..4304564 100644 --- a/e2e/profiles_test.go +++ b/e2e/profiles_test.go @@ -16,9 +16,10 @@ import ( // The gateway ships no provider profiles; every profile a provider uses must // be imported first. These fixtures follow core's example profiles // (providers/claude-code.yaml and providers/nvidia.yaml), reduced to the -// credentials and endpoints the tests rely on. The endpoints are plain -// host/port entries: the SDK's NetworkEndpoint has no access or rules fields -// yet, and the gateway rejects a protocol without them. +// the credentials the tests rely on. They declare no endpoints: the gateway +// requires L7 rules, access, or allow_uninspected_credentials on a +// credentialed endpoint, and the SDK's NetworkEndpoint can't express those +// yet. var testProfiles = []v1.ProviderProfile{ { ID: "claude-code", @@ -33,7 +34,6 @@ var testProfiles = []v1.ProviderProfile{ AuthStyle: "header", HeaderName: "x-api-key", }}, - Endpoints: []v1.NetworkEndpoint{{Host: "api.anthropic.com", Port: 443}}, }, { ID: "nvidia", @@ -46,7 +46,6 @@ var testProfiles = []v1.ProviderProfile{ EnvVars: []string{"NVIDIA_API_KEY"}, Required: true, }}, - Endpoints: []v1.NetworkEndpoint{{Host: "integrate.api.nvidia.com", Port: 443}}, }, } From 2d4d3528c5354a7260780a680d6ca49e448eb1c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 12:18:12 +0100 Subject: [PATCH 17/29] test(e2e): import the fixture profiles globally MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A provider without a profile workspace resolves its type against global profiles, so profiles imported into the default workspace were not found. Import and delete the fixtures in the global scope, as core's E2E harness does with --global. Signed-off-by: Roland Huß --- e2e/profiles_test.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go index 4304564..9047e2c 100644 --- a/e2e/profiles_test.go +++ b/e2e/profiles_test.go @@ -49,8 +49,12 @@ var testProfiles = []v1.ProviderProfile{ }, } -// importTestProfiles replaces the fixtures in the default workspace, so a -// rerun against the same gateway starts from the same definitions. +// globalScope selects global provider profiles. A provider without a profile +// workspace resolves its type against them, as the tests' providers do. +const globalScope = "" + +// importTestProfiles replaces the global fixtures, so a rerun against the +// same gateway starts from the same definitions. func importTestProfiles(client *v1.Client) error { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() @@ -60,10 +64,10 @@ func importTestProfiles(client *v1.Client) error { for _, p := range testProfiles { // A missing profile is the normal case; any other problem shows up in // the import below. - _, _ = profiles.Delete(ctx, "default", p.ID) + _, _ = profiles.Delete(ctx, globalScope, p.ID) items = append(items, v1.ProfileImportItem{Profile: p, Source: "e2e/profiles_test.go"}) } - res, err := profiles.Import(ctx, "default", items) + res, err := profiles.Import(ctx, globalScope, items) if err != nil { return fmt.Errorf("import provider profiles: %w", err) } From 569e4b011866b584616ca71176b7fa360aff273d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 14:50:53 +0100 Subject: [PATCH 18/29] test(e2e): bind provider credentials in the sandbox policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fixture profiles declare no endpoints, and the gateway withholds credentials of endpointless profiles unless the sandbox policy binds them to an endpoint. The credential tests now create their sandboxes with such a binding, as core's E2E does. Also drops the leftover nil CreateOption arguments. Signed-off-by: Roland Huß --- e2e/profiles_test.go | 23 +++++++++++++++++++++++ e2e/providers_test.go | 8 ++++---- e2e/sandbox_lifecycle_test.go | 2 +- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go index 9047e2c..4d2135f 100644 --- a/e2e/profiles_test.go +++ b/e2e/profiles_test.go @@ -11,6 +11,7 @@ import ( "time" v1 "github.com/ai-openshell/sdk-go/openshell/v1" + "github.com/ai-openshell/sdk-go/openshell/v1/types" ) // The gateway ships no provider profiles; every profile a provider uses must @@ -76,3 +77,25 @@ func importTestProfiles(client *v1.Client) error { } return nil } + +// boundCredentialPolicy is defaultPolicy plus one endpoint bound to the +// provider's credentials. The fixture profiles declare no endpoints, and the +// gateway withholds credentials of such profiles unless the sandbox policy +// binds them explicitly (core's +// test_endpointless_profile_credentials_use_explicit_policy_binding). +func boundCredentialPolicy(provider, host string) *v1.SandboxPolicy { + p := defaultPolicy() + p.NetworkPolicies = map[string]v1.NetworkPolicyRule{ + "e2e_credentials": { + Name: "e2e_credentials", + Endpoints: []v1.PolicyNetworkEndpoint{{ + Host: host, + Port: 443, + Protocol: "rest", + Access: v1.NetworkAccessPresetFull, + CredentialBinding: &types.NetworkCredentialBinding{Provider: provider}, + }}, + }, + } + return p +} diff --git a/e2e/providers_test.go b/e2e/providers_test.go index 9e6a1c1..7e1accc 100644 --- a/e2e/providers_test.go +++ b/e2e/providers_test.go @@ -137,10 +137,10 @@ func TestProviderCredentialsAvailableAsEnvVar(t *testing.T) { sandboxName := uniqueName("sb-penv") sandbox, err := client.Sandboxes().Create(ctx, "default", sandboxName, &v1.SandboxSpec{ - Policy: defaultPolicy(), + Policy: boundCredentialPolicy(providerName, "api.anthropic.com"), Providers: []string{providerName}, Command: []string{"sleep", "infinity"}, - }, nil) + }) require.NoError(t, err) requireSandboxResponse(t, sandbox, "default", sandboxName) t.Cleanup(func() { @@ -205,9 +205,9 @@ func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { sandboxName := uniqueName("sb-patt") sandbox, err := client.Sandboxes().Create(ctx, "default", sandboxName, &v1.SandboxSpec{ - Policy: defaultPolicy(), + Policy: boundCredentialPolicy(providerName, "integrate.api.nvidia.com"), Command: []string{"sleep", "infinity"}, - }, nil) + }) require.NoError(t, err) requireSandboxResponse(t, sandbox, "default", sandboxName) t.Cleanup(func() { diff --git a/e2e/sandbox_lifecycle_test.go b/e2e/sandbox_lifecycle_test.go index d5f27a4..145f347 100644 --- a/e2e/sandbox_lifecycle_test.go +++ b/e2e/sandbox_lifecycle_test.go @@ -29,7 +29,7 @@ func TestSandboxCRUDAndExec(t *testing.T) { sb, err := client.Sandboxes().Create(ctx, "default", name, &v1.SandboxSpec{ Policy: policy, Command: []string{"sleep", "infinity"}, - }, nil) + }) require.NoError(t, err) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 2*time.Minute) From 2c490d6fccd0e87ccf367c395cc6c4ef53ffab73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 14:55:01 +0100 Subject: [PATCH 19/29] test(e2e): wait for sandbox deletion before deleting providers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A sandbox whose policy binds a provider's credentials can't detach it, so deleting the provider right after the sandbox fails with a conflict until the asynchronous sandbox deletion ends. Retry on conflict. Skip the attach/detach test, which needs a profile with endpoints that the SDK can't import yet. Signed-off-by: Roland Huß --- e2e/providers_test.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/e2e/providers_test.go b/e2e/providers_test.go index 7e1accc..bc2dad7 100644 --- a/e2e/providers_test.go +++ b/e2e/providers_test.go @@ -32,11 +32,24 @@ func requireProviderResponse(t *testing.T, provider *v1.Provider, workspace, nam require.Empty(t, provider.Spec.Credentials) } +// deleteProviderIgnoreNotFound retries while the provider is still attached: +// a sandbox whose policy binds the provider's credentials can't detach it, so +// the attachment only goes away once the asynchronous sandbox deletion ends. func deleteProviderIgnoreNotFound(ctx context.Context, t *testing.T, client *v1.Client, workspace, name string) { t.Helper() - _, err := client.Providers().Delete(ctx, workspace, name) - if err != nil && !v1.IsNotFound(err) { - require.NoError(t, err) + for { + _, err := client.Providers().Delete(ctx, workspace, name) + if err == nil || v1.IsNotFound(err) { + return + } + if !v1.IsConflict(err) || ctx.Err() != nil { + require.NoError(t, err) + return + } + select { + case <-ctx.Done(): + case <-time.After(2 * time.Second): + } } } @@ -130,7 +143,7 @@ func TestProviderCredentialsAvailableAsEnvVar(t *testing.T) { require.NoError(t, err) requireProviderResponse(t, provider, "default", providerName, "claude-code") t.Cleanup(func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 90*time.Second) defer cleanupCancel() deleteProviderIgnoreNotFound(cleanupCtx, t, client, "default", providerName) }) @@ -184,6 +197,12 @@ func TestProfilelessProviderCreationIsRejected(t *testing.T) { func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { client := requireClient(t) + // The gateway delivers credentials of an endpointless profile only through + // a sandbox policy binding, and a binding can't name a provider that isn't + // attached yet. Attaching later therefore needs a profile with endpoints, + // which the SDK can't import until NetworkEndpoint carries access and + // rules (tracked as an sdk-go issue). + t.Skip("needs a provider profile with endpoints; the SDK can't import one yet") t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) From c267f41312c5486f9080a1512d68b14a5bb81e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 15:33:06 +0100 Subject: [PATCH 20/29] test(e2e): reference the profile endpoint issue in the workarounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roland Huß --- e2e/profiles_test.go | 2 +- e2e/providers_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/e2e/profiles_test.go b/e2e/profiles_test.go index 4d2135f..23f5703 100644 --- a/e2e/profiles_test.go +++ b/e2e/profiles_test.go @@ -20,7 +20,7 @@ import ( // the credentials the tests rely on. They declare no endpoints: the gateway // requires L7 rules, access, or allow_uninspected_credentials on a // credentialed endpoint, and the SDK's NetworkEndpoint can't express those -// yet. +// yet (ai-openshell/sdk-go#12). var testProfiles = []v1.ProviderProfile{ { ID: "claude-code", diff --git a/e2e/providers_test.go b/e2e/providers_test.go index bc2dad7..c060c36 100644 --- a/e2e/providers_test.go +++ b/e2e/providers_test.go @@ -201,8 +201,8 @@ func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { // a sandbox policy binding, and a binding can't name a provider that isn't // attached yet. Attaching later therefore needs a profile with endpoints, // which the SDK can't import until NetworkEndpoint carries access and - // rules (tracked as an sdk-go issue). - t.Skip("needs a provider profile with endpoints; the SDK can't import one yet") + // rules (ai-openshell/sdk-go#12). + t.Skip("needs a provider profile with endpoints; the SDK can't import one yet (ai-openshell/sdk-go#12)") t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) From d68695fe97647fbc503d12873cc187b6e21df412 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 4 Nov 2026 18:47:22 +0100 Subject: [PATCH 21/29] ci: mint bot tokens from the sdk-bot environment with the client ID MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per the App setup on #6: the App is ai-openshell-go-sdk, its secrets are SDK_BOT_CLIENT_ID and SDK_BOT_PRIVATE_KEY (app-id is deprecated in create-github-app-token v3.3.0), and they live in the sdk-bot environment, which only main can deploy to. As repository secrets, any pushed branch could mint a bot token, push to a PR as the bot, and then approve it. core-watch, release-tag, and core-drift run from main and now use environment: sdk-bot. Signed-off-by: Roland Huß --- .github/workflows/core-drift.yml | 5 ++++- .github/workflows/core-watch.yml | 5 ++++- .github/workflows/release-tag.yml | 5 ++++- hack/automation/README.md | 2 +- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/.github/workflows/core-drift.yml b/.github/workflows/core-drift.yml index 5e94853..b963985 100644 --- a/.github/workflows/core-drift.yml +++ b/.github/workflows/core-drift.yml @@ -20,13 +20,16 @@ concurrency: jobs: drift: name: drift + # The bot secrets live in the sdk-bot environment, which only main can + # deploy to, so a pushed branch can't mint a bot token. + environment: sdk-bot runs-on: ubuntu-latest timeout-minutes: 20 steps: - id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: - app-id: ${{ secrets.SDK_BOT_APP_ID }} + client-id: ${{ secrets.SDK_BOT_CLIENT_ID }} private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} permission-issues: write diff --git a/.github/workflows/core-watch.yml b/.github/workflows/core-watch.yml index d46166d..eaa3b31 100644 --- a/.github/workflows/core-watch.yml +++ b/.github/workflows/core-watch.yml @@ -24,13 +24,16 @@ concurrency: jobs: watch: name: watch + # The bot secrets live in the sdk-bot environment, which only main can + # deploy to, so a pushed branch can't mint a bot token. + environment: sdk-bot runs-on: ubuntu-latest timeout-minutes: 20 steps: - id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: - app-id: ${{ secrets.SDK_BOT_APP_ID }} + client-id: ${{ secrets.SDK_BOT_CLIENT_ID }} private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} permission-contents: write permission-pull-requests: write diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 1e42bd8..323923b 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -24,13 +24,16 @@ concurrency: jobs: tag: name: tag + # The bot secrets live in the sdk-bot environment, which only main can + # deploy to, so a pushed branch can't mint a bot token. + environment: sdk-bot runs-on: ubuntu-latest timeout-minutes: 10 steps: - id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: - app-id: ${{ secrets.SDK_BOT_APP_ID }} + client-id: ${{ secrets.SDK_BOT_CLIENT_ID }} private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} permission-contents: write permission-pull-requests: read diff --git a/hack/automation/README.md b/hack/automation/README.md index 28eadf3..ffde621 100644 --- a/hack/automation/README.md +++ b/hack/automation/README.md @@ -2,7 +2,7 @@ Every workflow under `.github/workflows/` wraps one of these scripts through a mise task, so each job can be run locally before it runs in CI. Scripts that write to GitHub take `--dry-run` and print what they would do instead. -Workflows run them with a token of the `ai-openshell-sdk-bot` GitHub App, never with `GITHUB_TOKEN`, so their pushes and PRs trigger CI. +Workflows run them with a token of the `ai-openshell-go-sdk` GitHub App (`ai-openshell-go-sdk[bot]`; secrets `SDK_BOT_CLIENT_ID` and `SDK_BOT_PRIVATE_KEY` in the `sdk-bot` environment, which only `main` can deploy to), never with `GITHUB_TOKEN`, so their pushes and PRs trigger CI. | File | mise task | Purpose | |------|-----------|---------| From 82068952c28ca5ec0da5c02d2dabda6a668ad8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 08:02:54 +0100 Subject: [PATCH 22/29] docs(automation): drop references to the deferred adaptation workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit adapt.yml, adapt-context.sh, and the agent:adapt label are not part of this PR: a label trigger runs in PR context, which the sdk-bot environment restricted to main rules out, so the adaptation workflow gets its own design later. Signed-off-by: Roland Huß --- hack/automation/README.md | 3 --- hack/automation/bump-pr-body.md | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/hack/automation/README.md b/hack/automation/README.md index ffde621..2523c48 100644 --- a/hack/automation/README.md +++ b/hack/automation/README.md @@ -15,8 +15,6 @@ Workflows run them with a token of the `ai-openshell-go-sdk` GitHub App (`ai-ope | `report-failure.sh ` | | Append a dated failure line to the drift issue. Called from `if: failure()` steps. | | `drift-issue.sh` | | Shared helpers for the two drift issue scripts (sourced, not run). | | `start-gateway.sh `, `stop-gateway.sh` | | Run the published gateway container for a core version with the Docker driver and a plaintext endpoint for the E2E lane, and collect its log. | -| `adapt-context.sh ` | | Build the `## Adaptation task` comment for the agent workflow: pin diff, proto diff, failed log tail, uncovered RPCs. | -| `adapt-task-body.md` | | Comment template for `adapt-context.sh`. | | Workflow | Script | |----------|--------| @@ -24,4 +22,3 @@ Workflows run them with a token of the `ai-openshell-go-sdk` GitHub App (`ai-ope | `release-tag.yml` (push to `main`) | `tag-release.sh` | | `core-drift.yml` (nightly) | `drift-check.sh`, then `update-drift-issue.sh` | | `e2e.yml` (reusable) | `start-gateway.sh`, `mise run e2e`, `stop-gateway.sh` | -| `adapt.yml` (label `agent:adapt`) | `adapt-context.sh` | diff --git a/hack/automation/bump-pr-body.md b/hack/automation/bump-pr-body.md index 20ef237..2120bb9 100644 --- a/hack/automation/bump-pr-body.md +++ b/hack/automation/bump-pr-body.md @@ -12,5 +12,5 @@ Move the core pin from `{{OLD}}` to `{{NEW}}` ({{KIND}}). ## Before merging -- CI and E2E must pass. If the SDK needs changes for this core version, push them to this branch, or add the `agent:adapt` label to get a first draft. +- CI and E2E must pass. If the SDK needs changes for this core version, push them to this branch. - Merging a stable pin tags the SDK release `{{NEW}}`. Pre-release pins are not tagged; a newer pre-release proposal replaces this one. From 0617220db1cac0b2823ef9e811d83e6814cc8170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 17:59:41 +0100 Subject: [PATCH 23/29] test(e2e): close the shared client with a deferred call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestMain now delegates to run(m), so the shared client is closed by one deferred call instead of before every os.Exit. Signed-off-by: Roland Huß --- e2e/harness_test.go | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/e2e/harness_test.go b/e2e/harness_test.go index 58fc2b6..7e4859f 100644 --- a/e2e/harness_test.go +++ b/e2e/harness_test.go @@ -30,16 +30,23 @@ var ( ) func TestMain(m *testing.M) { + // os.Exit skips deferred calls, so the setup and its cleanup live in run. + os.Exit(run(m)) +} + +// run sets up the shared client, runs the tests, and closes the client. It +// returns the process exit code. +func run(m *testing.M) int { gatewayName = os.Getenv("OPENSHELL_GATEWAY") if gatewayName == "" { // No gateway configured; requireClient skips every test individually. - os.Exit(m.Run()) + return m.Run() } cfg, err := gateway.LoadConfig(gatewayName) if err != nil { fmt.Fprintf(os.Stderr, "e2e: failed to load gateway config: %v\n", err) - os.Exit(1) + return 1 } var opts []gateway.ClientOption @@ -50,24 +57,21 @@ func TestMain(m *testing.M) { client, err := gateway.NewClient(gatewayName, opts...) if err != nil { fmt.Fprintf(os.Stderr, "e2e: failed to build gateway client: %v\n", err) - os.Exit(1) + return 1 } sharedClient = client + defer func() { _ = sharedClient.Close() }() if err := waitForPersistenceReady(sharedClient); err != nil { fmt.Fprintf(os.Stderr, "e2e: %v\n", err) - _ = sharedClient.Close() - os.Exit(1) + return 1 } if err := importTestProfiles(sharedClient); err != nil { fmt.Fprintf(os.Stderr, "e2e: %v\n", err) - _ = sharedClient.Close() - os.Exit(1) + return 1 } - code := m.Run() - _ = sharedClient.Close() - os.Exit(code) + return m.Run() } // mtlsClientOption inspects /mtls for an on-disk certificate bundle From cdb3494ebac8270656ddc40bbab4d6feefe38d2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 17:59:41 +0100 Subject: [PATCH 24/29] test(e2e): rename requireClient to clientOrSkip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The helper skips the test when no gateway is configured; it doesn't assert. The require prefix stays with the helpers that fail the test. Signed-off-by: Roland Huß --- e2e/harness_test.go | 6 +++--- e2e/providers_test.go | 8 ++++---- e2e/sandbox_lifecycle_test.go | 12 ++++++------ e2e/workspace_test.go | 10 +++++----- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/e2e/harness_test.go b/e2e/harness_test.go index 7e4859f..0081f54 100644 --- a/e2e/harness_test.go +++ b/e2e/harness_test.go @@ -39,7 +39,7 @@ func TestMain(m *testing.M) { func run(m *testing.M) int { gatewayName = os.Getenv("OPENSHELL_GATEWAY") if gatewayName == "" { - // No gateway configured; requireClient skips every test individually. + // No gateway configured; clientOrSkip skips every test individually. return m.Run() } @@ -99,9 +99,9 @@ func mtlsClientOption(dir string) gateway.ClientOption { return gateway.WithTLS(cfg) } -// requireClient returns the shared gateway client, skipping the calling test +// clientOrSkip returns the shared gateway client, skipping the calling test // when OPENSHELL_GATEWAY was not set at process startup. -func requireClient(t *testing.T) *v1.Client { +func clientOrSkip(t *testing.T) *v1.Client { t.Helper() if gatewayName == "" { t.Skip("OPENSHELL_GATEWAY not set") diff --git a/e2e/providers_test.go b/e2e/providers_test.go index c060c36..8e65295 100644 --- a/e2e/providers_test.go +++ b/e2e/providers_test.go @@ -127,7 +127,7 @@ func detachProviderRetry(ctx context.Context, t *testing.T, client *v1.Client, w } func TestProviderCredentialsAvailableAsEnvVar(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) @@ -175,7 +175,7 @@ func TestProviderCredentialsAvailableAsEnvVar(t *testing.T) { } func TestProfilelessProviderCreationIsRejected(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -196,7 +196,7 @@ func TestProfilelessProviderCreationIsRejected(t *testing.T) { } func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) // The gateway delivers credentials of an endpointless profile only through // a sandbox policy binding, and a binding can't name a provider that isn't // attached yet. Attaching later therefore needs a profile with endpoints, @@ -273,7 +273,7 @@ func TestAttachDetachProviderUpdatesCredentials(t *testing.T) { } func TestProviderCRUDResponseContract(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) diff --git a/e2e/sandbox_lifecycle_test.go b/e2e/sandbox_lifecycle_test.go index 145f347..3f7fcd7 100644 --- a/e2e/sandbox_lifecycle_test.go +++ b/e2e/sandbox_lifecycle_test.go @@ -18,7 +18,7 @@ import ( ) func TestSandboxCRUDAndExec(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) @@ -83,7 +83,7 @@ func TestSandboxCRUDAndExec(t *testing.T) { } func TestSandboxGetNonexistentNotFound(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -94,7 +94,7 @@ func TestSandboxGetNonexistentNotFound(t *testing.T) { } func TestSandboxDeleteNonexistentNotFound(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -105,7 +105,7 @@ func TestSandboxDeleteNonexistentNotFound(t *testing.T) { } func TestSandboxCreateDuplicateAlreadyExists(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) @@ -127,7 +127,7 @@ func TestSandboxCreateDuplicateAlreadyExists(t *testing.T) { } func TestSandboxListScopedAndAllWorkspaces(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) @@ -185,7 +185,7 @@ func TestSandboxListScopedAndAllWorkspaces(t *testing.T) { } func TestSandboxLabelsAndSelectors(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) diff --git a/e2e/workspace_test.go b/e2e/workspace_test.go index dd82faf..1ac5546 100644 --- a/e2e/workspace_test.go +++ b/e2e/workspace_test.go @@ -25,7 +25,7 @@ func requireWorkspaceResponse(t *testing.T, workspace *v1.Workspace, name string } func TestWorkspaceCRUD(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -53,7 +53,7 @@ func TestWorkspaceCRUD(t *testing.T) { } func TestWorkspaceCreateWithLabels(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -81,7 +81,7 @@ func TestWorkspaceCreateWithLabels(t *testing.T) { } func TestWorkspaceListIncludesCreated(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -115,7 +115,7 @@ func TestWorkspaceListIncludesCreated(t *testing.T) { } func TestWorkspaceDeleteNonexistentNotFound(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -126,7 +126,7 @@ func TestWorkspaceDeleteNonexistentNotFound(t *testing.T) { } func TestWorkspaceGetNonexistentNotFound(t *testing.T) { - client := requireClient(t) + client := clientOrSkip(t) t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) From 261776bf235bd5439beab28400f3fc81fa98c967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 18:01:21 +0100 Subject: [PATCH 25/29] fix(hack): never reopen a closed proposal, and stop on API errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit open-bump-pr.sh skipped a tag only when its branch existed or a PR from it was merged. A proposal closed by a maintainer, or closed as superseded by a newer pre-release (which deletes the branch), came back on the next hourly run. Skip the tag when any PR from the branch exists. The core tag lookup treated every failure as a deleted tag and closed the open proposal. Only a 404 means the tag is gone now; other errors fail the run, which reports to the drift issue. Signed-off-by: Roland Huß --- hack/automation/open-bump-pr.sh | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/hack/automation/open-bump-pr.sh b/hack/automation/open-bump-pr.sh index 41e3e28..0c32c02 100755 --- a/hack/automation/open-bump-pr.sh +++ b/hack/automation/open-bump-pr.sh @@ -11,8 +11,9 @@ # for older tags. --dry-run does the local part, prints the PR body, and # changes nothing on GitHub. # -# Skips the tag when branch core/ exists on origin or a PR from it was -# merged. When the core tag no longer exists, closes an open proposal for it. +# Skips the tag when branch core/ exists on origin or any PR from it +# exists (merged or closed), so a closed proposal is never reopened. When the +# core tag no longer exists, closes an open proposal for it. # Git identity and GH_TOKEN come from the environment (the App in CI). set -euo pipefail @@ -64,8 +65,10 @@ open_pr_for_branch() { gh pr list -R "$sdk_repo" --head "$branch" --state open --json number --jq '.[0].number // empty' } -# The core tag may have been deleted (a withdrawn pre-release). -if ! gh api "repos/$core_repo/git/ref/tags/$tag" --silent 2>/dev/null; then +# The core tag may have been deleted (a withdrawn pre-release). Only a 404 +# means that; any other failure (rate limit, 5xx) stops the run. +if ! err=$(gh api "repos/$core_repo/git/ref/tags/$tag" --silent 2>&1); then + grep -q 'HTTP 404' <<<"$err" || die "looking up core tag $tag failed: $err" n=$(open_pr_for_branch) if [ -n "$n" ]; then echo "Core tag $tag is gone; closing #$n." @@ -81,8 +84,12 @@ if [ -n "$(git ls-remote --heads origin "$branch")" ]; then echo "Branch $branch exists on origin; skipping $tag." exit 0 fi -if [ -n "$(gh pr list -R "$sdk_repo" --head "$branch" --state merged --json number --jq '.[0].number // empty')" ]; then - echo "A proposal for $tag was merged already; skipping." +# Any earlier proposal is final: merged, closed by a maintainer, or closed as +# superseded by a newer pre-release. Its branch may be gone, so ask for PRs. +prev=$(gh pr list -R "$sdk_repo" --head "$branch" --state all --json number,state \ + --jq '.[0] | select(.) | "#\(.number) (\(.state | ascii_downcase))"') +if [ -n "$prev" ]; then + echo "Proposal $prev exists for $tag already; skipping." exit 0 fi From 2386235c02a56d879821747c48c58b1780cd2470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 18:01:22 +0100 Subject: [PATCH 26/29] fix(hack): finish half-done releases and see pin changes behind the tip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tag-release.sh created the tag and then the release. When the release step failed, a re-run saw the tag at the commit and stopped, so the release was never created. Check the tag and the release separately and create whichever is missing; API errors other than 404 fail the run. It also decided by diffing only the pushed commit against its parent, so a push of several commits or a rebase merge could miss a pin change that was not the tip. The push workflow now passes the commit before the push as --since, and the script compares the pins at both commits. Signed-off-by: Roland Huß --- .github/workflows/release-tag.yml | 5 +- hack/automation/tag-release.sh | 94 +++++++++++++++++++++---------- 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 323923b..1c004fd 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -56,12 +56,15 @@ jobs: GH_TOKEN: ${{ steps.app-token.outputs.token }} EVENT: ${{ github.event_name }} INPUT_SHA: ${{ inputs.sha }} + BEFORE: ${{ github.event.before }} run: | set -euo pipefail if [ "$EVENT" = workflow_dispatch ]; then hack/automation/tag-release.sh --force --sha "${INPUT_SHA:-$GITHUB_SHA}" else - hack/automation/tag-release.sh + # Compare against the commit before the push, so a pin change + # that isn't the pushed tip still counts. + hack/automation/tag-release.sh --since "$BEFORE" fi - name: Report failure diff --git a/hack/automation/tag-release.sh b/hack/automation/tag-release.sh index 46e1ee9..a5a9985 100755 --- a/hack/automation/tag-release.sh +++ b/hack/automation/tag-release.sh @@ -1,17 +1,19 @@ #!/usr/bin/env bash # tag-release.sh: create the lockstep SDK release for a stable core pin. # -# Usage: tag-release.sh [--dry-run] [--force] [--sha ] +# Usage: tag-release.sh [--dry-run] [--force] [--sha ] [--since ] # # Reads the pin from buf.gen.yaml at (default: $GITHUB_SHA, else -# HEAD). A pre-release pin creates nothing. Without --force, a commit that -# did not change buf.gen.yaml creates nothing either, so ordinary pushes to -# main are no-ops. Then: -# - tag vX.Y.Z missing: create it (lightweight) at , create the -# GitHub release with the merged proposal's body plus -# "Matches OpenShell core vX.Y.Z", and ask the Go module proxy for it -# - tag at already: nothing to do -# - tag at another commit: fail +# HEAD). A pre-release pin creates nothing. Without --force, nothing is +# created either when the pin at equals the pin at --since (default: +# the parent of ), so ordinary pushes to main are no-ops. The push +# workflow passes the commit before the push as --since, which covers pushes +# of several commits and rebase merges. Then, each step only when missing: +# - tag vX.Y.Z (lightweight) at ; a tag at another commit fails +# - the GitHub release with the merged proposal's body plus +# "Matches OpenShell core vX.Y.Z" +# - a request to the Go module proxy for the version +# A re-run after a partial failure finishes the missing steps. set -euo pipefail sdk_repo=${SDK_REPO:-ai-openshell/sdk-go} @@ -19,64 +21,94 @@ module=github.com/ai-openshell/sdk-go dry=0 force=0 sha=${GITHUB_SHA:-} +since= +usage() { echo "usage: $0 [--dry-run] [--force] [--sha ] [--since ]" >&2; exit 2; } while [ $# -gt 0 ]; do case $1 in --dry-run) dry=1; shift ;; --force) force=1; shift ;; --sha) sha=${2:?--sha needs a commit}; shift 2 ;; - *) echo "usage: $0 [--dry-run] [--force] [--sha ]" >&2; exit 2 ;; + --since) since=${2:?--since needs a commit}; shift 2 ;; + *) usage ;; esac done [ -n "$sha" ] || sha=$(git rev-parse HEAD) sha=$(git rev-parse "$sha^{commit}") +short=$(git rev-parse --short "$sha") -pin=$(git show "$sha:buf.gen.yaml" | yq -r '.inputs[0].tag') +pin_at() { git show "$1:buf.gen.yaml" 2>/dev/null | yq -r '.inputs[0].tag'; } + +pin=$(pin_at "$sha") if ! [[ "$pin" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "Pin $pin is not a stable release; no SDK tag." exit 0 fi -if [ "$force" -eq 0 ] && [ -z "$(git diff --name-only "$sha^" "$sha" -- buf.gen.yaml 2>/dev/null)" ]; then - echo "$(git rev-parse --short "$sha") does not change buf.gen.yaml; no SDK tag." - exit 0 +if [ "$force" -eq 0 ]; then + # A new branch push reports an all-zero "before"; fall back to the parent. + if [ -z "$since" ] || ! git rev-parse --verify --quiet "$since^{commit}" >/dev/null; then + since="$sha^" + fi + if [ "$(pin_at "$since" || true)" = "$pin" ]; then + echo "The pin is $pin both at $short and at $(git rev-parse --short "$since"); no SDK tag." + exit 0 + fi fi -# gh prints the error body on stdout for a 404, so only trust a successful call. -if ! existing=$(gh api "repos/$sdk_repo/git/ref/tags/$pin" --jq '.object.sha' 2>/dev/null); then - existing= -fi -if [ -n "$existing" ]; then - if [ "$existing" = "$sha" ]; then - echo "Tag $pin already points at $(git rev-parse --short "$sha"); nothing to do." - exit 0 +# get_or_empty : the value, empty on 404, and fail on any other +# error. gh prints the error body on stdout for a 404, so stdout is only used +# after a successful call. +get_or_empty() { + local out err + if out=$(gh api "$1" --jq "$2" 2>"${tmp}/err"); then + printf '%s' "$out" + else + err=$(cat "${tmp}/err") + grep -q 'HTTP 404' <<<"$err" || { echo "ERROR: gh api $1 failed: $err" >&2; return 1; } fi +} +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +existing=$(get_or_empty "repos/$sdk_repo/git/ref/tags/$pin" '.object.sha') +if [ -n "$existing" ] && [ "$existing" != "$sha" ]; then echo "ERROR: tag $pin exists at $existing, not at $sha. SDK tags never move; fix this by hand." >&2 exit 1 fi +release=$(get_or_empty "repos/$sdk_repo/releases/tags/$pin" '.id') +if [ -n "$existing" ] && [ -n "$release" ]; then + echo "Tag $pin and its release exist at $short already; nothing to do." + exit 0 +fi # Release notes: the body of the PR that merged this commit, then the match line. -notes=$(mktemp) -trap 'rm -f "$notes"' EXIT -if ! pr_body=$(gh api "repos/$sdk_repo/commits/$sha/pulls" --jq '.[0].body // empty' 2>/dev/null); then - pr_body= -fi +notes="$tmp/notes.md" +pr_body=$(get_or_empty "repos/$sdk_repo/commits/$sha/pulls" '.[0].body // empty') { [ -z "$pr_body" ] || printf '%s\n\n' "$pr_body" echo "Matches OpenShell core $pin." } >"$notes" if [ "$dry" -eq 1 ]; then - echo "dry-run: would create tag $pin at $sha" + if [ -n "$existing" ]; then + echo "dry-run: tag $pin exists at $sha" + else + echo "dry-run: would create tag $pin at $sha" + fi echo "dry-run: would create release $pin with notes:" sed 's/^/ | /' "$notes" echo "dry-run: would request https://proxy.golang.org/$module/@v/$pin.info" exit 0 fi -gh api -X POST "repos/$sdk_repo/git/refs" -f ref="refs/tags/$pin" -f sha="$sha" --silent -echo "Created tag $pin at $sha." -gh release create "$pin" -R "$sdk_repo" --verify-tag --title "$pin" --notes-file "$notes" +if [ -z "$existing" ]; then + gh api -X POST "repos/$sdk_repo/git/refs" -f ref="refs/tags/$pin" -f sha="$sha" --silent + echo "Created tag $pin at $sha." +fi +if [ -z "$release" ]; then + gh release create "$pin" -R "$sdk_repo" --verify-tag --title "$pin" --notes-file "$notes" +fi # Best effort: the proxy fetches the version on first request. if curl -fsS --max-time 60 "https://proxy.golang.org/$module/@v/$pin.info"; then From 5ac6985487f6391cff55ba1310c338f4bab9e7ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 18:01:54 +0100 Subject: [PATCH 27/29] ci: run E2E when its workflow, tools, or dependencies change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The path filter now also matches .github/workflows/e2e.yml, mise.toml, go.mod, and go.sum. Signed-off-by: Roland Huß --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2717a97..4d9380c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,7 +74,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | set -euo pipefail - if git diff --name-only "${BASE_SHA}...HEAD" | grep -qE '^(buf\.gen\.yaml$|proto/|openshell/|e2e/|hack/automation/(start|stop)-gateway\.sh$)'; then + if git diff --name-only "${BASE_SHA}...HEAD" | grep -qE '^(buf\.gen\.yaml$|go\.(mod|sum)$|mise\.toml$|proto/|openshell/|e2e/|hack/automation/(start|stop)-gateway\.sh$|\.github/workflows/e2e\.yml$)'; then echo "e2e=true" >>"$GITHUB_OUTPUT" else echo "e2e=false" >>"$GITHUB_OUTPUT" From 7695dc3752d891ac5fa6f0b53c53efdcead28c8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 18:01:54 +0100 Subject: [PATCH 28/29] fix(hack): check the sandbox image pin and clean up the E2E registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit start-gateway.sh verified only the supervisor image pin; it now checks the sandbox image pin too. stop-gateway.sh removes the "e2e" gateway registration and the active-gateway pointer when it still names it. The header no longer claims stop undoes everything and says the scripts are for throwaway CI hosts, since the sandbox cleanup matches core's default namespace label. Signed-off-by: Roland Huß --- hack/automation/start-gateway.sh | 16 ++++++++++------ hack/automation/stop-gateway.sh | 9 ++++++++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/hack/automation/start-gateway.sh b/hack/automation/start-gateway.sh index 88780b7..a36fc6a 100755 --- a/hack/automation/start-gateway.sh +++ b/hack/automation/start-gateway.sh @@ -13,8 +13,10 @@ # gateway image of a fresh tag to be published. # # Needs docker with the compose plugin and a host path /var/lib/openshell -# (core's compose file bind-mounts it at the same path). stop-gateway.sh -# undoes everything. +# (core's compose file bind-mounts it at the same path). Meant for throwaway +# CI hosts: it registers the gateway as the active one, and stop-gateway.sh +# removes every container labelled with core's default sandbox namespace, +# including sandboxes of another local gateway that uses the same namespace. set -euo pipefail core_repo=${CORE_REPO:-NVIDIA/OpenShell} @@ -66,10 +68,12 @@ sed -i.bak \ -e "s#\"$registry/supervisor:latest\"#\"$registry/supervisor:$semver\"#" \ -e "s#\"$registry/sandbox:latest\"#\"$registry/sandbox:$semver\"#" \ "$state/gateway.toml" && rm -f "$state/gateway.toml.bak" -grep -q "supervisor:$semver" "$state/gateway.toml" || { - echo "ERROR: could not pin the supervisor image in core's gateway.toml at $tag" >&2 - exit 1 -} +for img in supervisor sandbox; do + grep -q "\"$registry/$img:$semver\"" "$state/gateway.toml" || { + echo "ERROR: could not pin the $img image in core's gateway.toml at $tag" >&2 + exit 1 + } +done # Core's file binds the health server to loopback inside the container, where # the published port can't reach it. Bind it to all container interfaces; the # compose file publishes the port on the host's 127.0.0.1 only. diff --git a/hack/automation/stop-gateway.sh b/hack/automation/stop-gateway.sh index 8469c5b..1296e68 100755 --- a/hack/automation/stop-gateway.sh +++ b/hack/automation/stop-gateway.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # stop-gateway.sh: stop the E2E gateway started by start-gateway.sh, save its -# log, and remove the sandbox containers it created. +# log, remove the sandbox containers, and remove the "e2e" gateway +# registration (and the active-gateway pointer when it still names "e2e"). # # Usage: stop-gateway.sh [--state-dir ] # @@ -20,4 +21,10 @@ echo "Gateway log: $state/gateway.log" ids=$(docker ps -aq --filter label=openshell.sandbox_namespace=openshell) [ -z "$ids" ] || docker rm -f $ids >/dev/null compose down --volumes --remove-orphans >/dev/null 2>&1 + +config_home=${XDG_CONFIG_HOME:-$HOME/.config} +rm -rf "$config_home/openshell/gateways/e2e" +if [ "$(cat "$config_home/openshell/active_gateway" 2>/dev/null)" = e2e ]; then + rm -f "$config_home/openshell/active_gateway" +fi echo "Gateway stopped." From de002ecb76bc2aec1b8314ccb6119279f9f6d0a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Thu, 5 Nov 2026 18:06:07 +0100 Subject: [PATCH 29/29] docs(automation): name the App ai-openshell-sdk-go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The App was registered as ai-openshell-sdk-go, following the repository naming convention. Signed-off-by: Roland Huß --- hack/automation/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/automation/README.md b/hack/automation/README.md index 2523c48..748431b 100644 --- a/hack/automation/README.md +++ b/hack/automation/README.md @@ -2,7 +2,7 @@ Every workflow under `.github/workflows/` wraps one of these scripts through a mise task, so each job can be run locally before it runs in CI. Scripts that write to GitHub take `--dry-run` and print what they would do instead. -Workflows run them with a token of the `ai-openshell-go-sdk` GitHub App (`ai-openshell-go-sdk[bot]`; secrets `SDK_BOT_CLIENT_ID` and `SDK_BOT_PRIVATE_KEY` in the `sdk-bot` environment, which only `main` can deploy to), never with `GITHUB_TOKEN`, so their pushes and PRs trigger CI. +Workflows run them with a token of the `ai-openshell-sdk-go` GitHub App (`ai-openshell-sdk-go[bot]`; secrets `SDK_BOT_CLIENT_ID` and `SDK_BOT_PRIVATE_KEY` in the `sdk-bot` environment, which only `main` can deploy to), never with `GITHUB_TOKEN`, so their pushes and PRs trigger CI. | File | mise task | Purpose | |------|-----------|---------|