diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 67ff9ce..4d9380c 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$|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"
+ fi
+
+ e2e:
+ name: e2e
+ needs: changes
+ if: needs.changes.outputs.e2e == 'true'
+ uses: ./.github/workflows/e2e.yml
diff --git a/.github/workflows/core-drift.yml b/.github/workflows/core-drift.yml
new file mode 100644
index 0000000..b963985
--- /dev/null
+++ b/.github/workflows/core-drift.yml
@@ -0,0 +1,65 @@
+# 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
+ # 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:
+ client-id: ${{ secrets.SDK_BOT_CLIENT_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"
diff --git a/.github/workflows/core-watch.yml b/.github/workflows/core-watch.yml
new file mode 100644
index 0000000..eaa3b31
--- /dev/null
+++ b/.github/workflows/core-watch.yml
@@ -0,0 +1,89 @@
+# 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
+ # 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:
+ client-id: ${{ secrets.SDK_BOT_CLIENT_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/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/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml
new file mode 100644
index 0000000..1c004fd
--- /dev/null
+++ b/.github/workflows/release-tag.yml
@@ -0,0 +1,75 @@
+# 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
+ # 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:
+ client-id: ${{ secrets.SDK_BOT_CLIENT_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 }}
+ 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
+ # 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
+ 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/e2e/harness_test.go b/e2e/harness_test.go
new file mode 100644
index 0000000..0081f54
--- /dev/null
+++ b/e2e/harness_test.go
@@ -0,0 +1,288 @@
+// 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) {
+ // 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; clientOrSkip skips every test individually.
+ return m.Run()
+ }
+
+ cfg, err := gateway.LoadConfig(gatewayName)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "e2e: failed to load gateway config: %v\n", err)
+ return 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)
+ return 1
+ }
+ sharedClient = client
+ defer func() { _ = sharedClient.Close() }()
+
+ if err := waitForPersistenceReady(sharedClient); err != nil {
+ fmt.Fprintf(os.Stderr, "e2e: %v\n", err)
+ return 1
+ }
+ if err := importTestProfiles(sharedClient); err != nil {
+ fmt.Fprintf(os.Stderr, "e2e: %v\n", err)
+ return 1
+ }
+
+ return m.Run()
+}
+
+// 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)
+}
+
+// clientOrSkip returns the shared gateway client, skipping the calling test
+// when OPENSHELL_GATEWAY was not set at process startup.
+func clientOrSkip(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/profiles_test.go b/e2e/profiles_test.go
new file mode 100644
index 0000000..23f5703
--- /dev/null
+++ b/e2e/profiles_test.go
@@ -0,0 +1,101 @@
+// 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"
+ "github.com/ai-openshell/sdk-go/openshell/v1/types"
+)
+
+// 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
+// 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 (ai-openshell/sdk-go#12).
+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",
+ }},
+ },
+ {
+ 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,
+ }},
+ },
+}
+
+// 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()
+
+ 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, globalScope, p.ID)
+ items = append(items, v1.ProfileImportItem{Profile: p, Source: "e2e/profiles_test.go"})
+ }
+ res, err := profiles.Import(ctx, globalScope, 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
+}
+
+// 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
new file mode 100644
index 0000000..8e65295
--- /dev/null
+++ b/e2e/providers_test.go
@@ -0,0 +1,327 @@
+// 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)
+}
+
+// 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()
+ 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):
+ }
+ }
+}
+
+// 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 := clientOrSkip(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(), 90*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: boundCredentialPolicy(providerName, "api.anthropic.com"),
+ Providers: []string{providerName},
+ Command: []string{"sleep", "infinity"},
+ })
+ 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 := clientOrSkip(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 := 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,
+ // which the SDK can't import until NetworkEndpoint carries access and
+ // 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)
+ 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: boundCredentialPolicy(providerName, "integrate.api.nvidia.com"),
+ Command: []string{"sleep", "infinity"},
+ })
+ 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 := clientOrSkip(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..3f7fcd7
--- /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 := clientOrSkip(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"},
+ })
+ 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 := clientOrSkip(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 := clientOrSkip(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 := clientOrSkip(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{})
+ 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{})
+ require.True(t, v1.IsAlreadyExists(err), "expected AlreadyExists, got %v", err)
+}
+
+func TestSandboxListScopedAndAllWorkspaces(t *testing.T) {
+ client := clientOrSkip(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{})
+ 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{})
+ 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 := clientOrSkip(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{},
+ v1.WithLabels(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{},
+ v1.WithLabels(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..1ac5546
--- /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 := clientOrSkip(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 := clientOrSkip(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 := clientOrSkip(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 := clientOrSkip(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 := clientOrSkip(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)
+}
diff --git a/hack/automation/README.md b/hack/automation/README.md
index f227143..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-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-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 |
|------|-----------|---------|
@@ -13,9 +13,8 @@ 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`. |
| Workflow | Script |
|----------|--------|
@@ -23,4 +22,3 @@ Workflows run them with a token of the `ai-openshell-sdk-bot` GitHub App, never
| `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
new file mode 100644
index 0000000..2120bb9
--- /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.
+- 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/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" < " 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/open-bump-pr.sh b/hack/automation/open-bump-pr.sh
new file mode 100755
index 0000000..0c32c02
--- /dev/null
+++ b/hack/automation/open-bump-pr.sh
@@ -0,0 +1,206 @@
+#!/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 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
+
+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). 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."
+ 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
+# 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
+
+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
diff --git a/hack/automation/report-failure.sh b/hack/automation/report-failure.sh
new file mode 100755
index 0000000..7f95121
--- /dev/null
+++ b/hack/automation/report-failure.sh
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# report-failure.sh: record a failed automation run in the drift issue.
+#
+# Usage: report-failure.sh [--dry-run]
+#
+# 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
+# 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/start-gateway.sh b/hack/automation/start-gateway.sh
new file mode 100755
index 0000000..a36fc6a
--- /dev/null
+++ b/hack/automation/start-gateway.sh
@@ -0,0 +1,117 @@
+#!/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). 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}
+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"
+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.
+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 ..."
+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..1296e68
--- /dev/null
+++ b/hack/automation/stop-gateway.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# stop-gateway.sh: stop the E2E gateway started by start-gateway.sh, save its
+# 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 ]
+#
+# 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
+
+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."
diff --git a/hack/automation/tag-release.sh b/hack/automation/tag-release.sh
new file mode 100755
index 0000000..a5a9985
--- /dev/null
+++ b/hack/automation/tag-release.sh
@@ -0,0 +1,118 @@
+#!/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 ] [--since ]
+#
+# Reads the pin from buf.gen.yaml at (default: $GITHUB_SHA, else
+# 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}
+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 ;;
+ --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_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 ]; 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
+
+# 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="$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
+ 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
+
+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
+ echo
+else
+ echo "WARNING: the Go module proxy did not serve $pin yet; it will on the next request." >&2
+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
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/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 11d79ce..cb408f2 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
@@ -230,12 +227,33 @@ 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"]
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"
+
+[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/..."
]