Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(sandbox): add tenant skill snapshot infrastructure

hailongzhao00fe0356681b
diff --git a/internal/application/repository/tenant_skill.go b/internal/application/repository/tenant_skill.go
new file mode 100644
index 000000000..d464f9a7c
--- /dev/null
+++ b/internal/application/repository/tenant_skill.go
@@ -0,0 +1,195 @@
+package repository
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "gorm.io/gorm"
+)
+
+// TenantSkillRepository persists skills installed onto sandbox configs and the
+// snapshot chain ledger.
+type TenantSkillRepository interface {
+ // CreateSkill inserts a metadata projection row before provider-side image work starts.
+ CreateSkill(ctx context.Context, e *types.TenantSkillEntity) error
+ // GetSkill returns nil (no error) when the skill does not exist or belongs
+ // to another workspace/config, so callers can render a 404 directly.
+ GetSkill(ctx context.Context, tenantID uint64, configID, skillID string) (*types.TenantSkillEntity, error)
+ // GetSkillByName scopes lookup by config because skill names are only unique within a config.
+ GetSkillByName(ctx context.Context, tenantID uint64, configID, name string) (*types.TenantSkillEntity, error)
+ // ListSkillsByConfig returns the installed skill projection for one sandbox config.
+ ListSkillsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
+ // UpdateSkill writes the mutable projection fields after install/remove state changes.
+ UpdateSkill(ctx context.Context, e *types.TenantSkillEntity) error
+ // DeleteSkill soft-deletes metadata only; image cleanup is represented by snapshots.
+ DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
+ // ListStaleInstalling finds abandoned install/remove runs for the reaper.
+ ListStaleInstalling(ctx context.Context, olderThan time.Time) ([]*types.TenantSkillEntity, error)
+
+ // CreateSnapshotRow records provider work before creating the billable snapshot.
+ CreateSnapshotRow(ctx context.Context, e *types.TenantSkillSnapshotEntity) error
+ // MarkSnapshotState updates ledger state and stores the provider snapshot ID once known.
+ MarkSnapshotState(ctx context.Context, id, state, snapshotID string) error
+ // ListSnapshotsByConfig returns the full chain for audit and troubleshooting.
+ ListSnapshotsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillSnapshotEntity, error)
+ // DeleteSnapshotRowsByConfig removes ledger rows only when an entire sandbox
+ // config is deleted and its provider-side snapshots are already gone; never
+ // call this during an ordinary image switch (old snapshots stay in the ledger).
+ DeleteSnapshotRowsByConfig(ctx context.Context, tenantID uint64, configID string) error
+}
+
+type tenantSkillRepository struct{ db *gorm.DB }
+
+// NewTenantSkillRepository returns a GORM-backed implementation.
+func NewTenantSkillRepository(db *gorm.DB) TenantSkillRepository {
+ return &tenantSkillRepository{db: db}
+}
+
+func (r *tenantSkillRepository) CreateSkill(ctx context.Context, e *types.TenantSkillEntity) error {
+ return r.db.WithContext(ctx).Create(e).Error
+}
+
+func (r *tenantSkillRepository) GetSkill(
+ ctx context.Context, tenantID uint64, configID, skillID string,
+) (*types.TenantSkillEntity, error) {
+ var e types.TenantSkillEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ? AND id = ?", tenantID, configID, skillID).
+ First(&e).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &e, nil
+}
+
+func (r *tenantSkillRepository) GetSkillByName(
+ ctx context.Context, tenantID uint64, configID, name string,
+) (*types.TenantSkillEntity, error) {
+ var e types.TenantSkillEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ? AND name = ?", tenantID, configID, name).
+ First(&e).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &e, nil
+}
+
+func (r *tenantSkillRepository) ListSkillsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) ([]*types.TenantSkillEntity, error) {
+ var list []*types.TenantSkillEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).
+ Order("created_at ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+// UpdateSkill writes the mutable columns explicitly so a zero-valued field on
+// the passed entity cannot silently wipe state written by a concurrent job.
+func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.TenantSkillEntity) error {
+ return r.db.WithContext(ctx).
+ Model(&types.TenantSkillEntity{}).
+ Where("tenant_id = ? AND sandbox_config_id = ? AND id = ?", e.TenantID, e.SandboxConfigID, e.ID).
+ Updates(map[string]any{
+ "name": e.Name,
+ "version": e.Version,
+ "description": e.Description,
+ "instructions": e.Instructions,
+ "bundle_ref": e.BundleRef,
+ "bundle_sha256": e.BundleSHA256,
+ "enabled": e.Enabled,
+ "installed_snapshot_id": e.InstalledSnapshotID,
+ "status": e.Status,
+ "error": e.Error,
+ "installing_since": e.InstallingSince,
+ "updated_at": time.Now(),
+ }).Error
+}
+
+func (r *tenantSkillRepository) DeleteSkill(
+ ctx context.Context, tenantID uint64, configID, skillID string,
+) error {
+ return r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ? AND id = ?", tenantID, configID, skillID).
+ Delete(&types.TenantSkillEntity{}).Error
+}
+
+func (r *tenantSkillRepository) ListStaleInstalling(
+ ctx context.Context, olderThan time.Time,
+) ([]*types.TenantSkillEntity, error) {
+ var list []*types.TenantSkillEntity
+ err := r.db.WithContext(ctx).
+ Where("status IN ? AND installing_since IS NOT NULL AND installing_since < ?",
+ []string{types.SkillStatusInstalling, types.SkillStatusRemoving}, olderThan).
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+func (r *tenantSkillRepository) CreateSnapshotRow(
+ ctx context.Context, e *types.TenantSkillSnapshotEntity,
+) error {
+ return r.db.WithContext(ctx).Create(e).Error
+}
+
+// MarkSnapshotState moves a ledger row and, when the snapshot has just been
+// created, records its provider-side ID.
+func (r *tenantSkillRepository) MarkSnapshotState(
+ ctx context.Context, id, state, snapshotID string,
+) error {
+ updates := map[string]any{"state": state, "updated_at": time.Now()}
+ if snapshotID != "" {
+ updates["snapshot_id"] = snapshotID
+ }
+ if state == types.SkillSnapshotStateSuperseded {
+ now := time.Now()
+ updates["superseded_at"] = &now
+ }
+ return r.db.WithContext(ctx).
+ Model(&types.TenantSkillSnapshotEntity{}).
+ Where("id = ?", id).
+ Updates(updates).Error
+}
+
+func (r *tenantSkillRepository) ListSnapshotsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) ([]*types.TenantSkillSnapshotEntity, error) {
+ var list []*types.TenantSkillSnapshotEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).
+ Order("generation ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+// DeleteSnapshotRowsByConfig removes all ledger rows for a sandbox config.
+// This is only legitimate when the entire sandbox config is being deleted and
+// its provider-side snapshots have already been destroyed. During an ordinary
+// image switch, old snapshots are never deleted—the ledger records their IDs
+// and deleting rows would leave those IDs dangling. Here the config itself no
+// longer exists, so keeping rows would point at a deleted config instead.
+func (r *tenantSkillRepository) DeleteSnapshotRowsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) error {
+ return r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).
+ Delete(&types.TenantSkillSnapshotEntity{}).Error
+}
diff --git a/internal/application/repository/tenant_skill_test.go b/internal/application/repository/tenant_skill_test.go
new file mode 100644
index 000000000..ecb0ca382
--- /dev/null
+++ b/internal/application/repository/tenant_skill_test.go
@@ -0,0 +1,129 @@
+package repository
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+)
+
+func newSkillTestRepo(t *testing.T) TenantSkillRepository {
+ t.Helper()
+ db, err := gorm.Open(sqlite.Open("file:"+uuid.NewString()+"?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(
+ &types.TenantSkillEntity{}, &types.TenantSkillSnapshotEntity{},
+ ))
+ // AutoMigrate cannot express the partial unique index, so add it here to
+ // match the production migration.
+ require.NoError(t, db.Exec(
+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skills_config_name
+ ON tenant_skills (sandbox_config_id, name) WHERE deleted_at IS NULL`).Error)
+ return NewTenantSkillRepository(db)
+}
+
+func skillRow(id, configID, name string) *types.TenantSkillEntity {
+ return &types.TenantSkillEntity{
+ ID: id, TenantID: 7, SandboxConfigID: configID, Name: name,
+ Status: types.SkillStatusInstalling, Enabled: true,
+ }
+}
+
+func TestSkillRepoIsolatesConfigs(t *testing.T) {
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-b", "cfg-2", "pdf")))
+
+ list, err := repo.ListSkillsByConfig(ctx, 7, "cfg-1")
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ require.Equal(t, "sk-a", list[0].ID)
+
+ got, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-b")
+ require.NoError(t, err)
+ require.Nil(t, got, "a skill from another config must read as absent, not as an error")
+}
+
+func TestSkillRepoUpdatePersistsPointerAndStatus(t *testing.T) {
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+
+ row, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ row.Status = types.SkillStatusReady
+ row.InstalledSnapshotID = "snap-1"
+ row.Enabled = false
+ require.NoError(t, repo.UpdateSkill(ctx, row))
+
+ got, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, got.Status)
+ require.Equal(t, "snap-1", got.InstalledSnapshotID)
+ require.False(t, got.Enabled, "disabling a skill must round-trip; it is the visibility switch")
+}
+
+func TestSnapshotLedgerRecordsChain(t *testing.T) {
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{
+ ID: "ins-1", TenantID: 7, SandboxConfigID: "cfg-1", SkillID: "sk-a",
+ ParentSnapshotID: "tpl-base", Generation: 1,
+ Trigger: types.SkillSnapshotTriggerInstall,
+ State: types.SkillSnapshotStateBuilding,
+ }))
+
+ require.NoError(t, repo.MarkSnapshotState(ctx, "ins-1", types.SkillSnapshotStateActive, "snap-1"))
+
+ rows, err := repo.ListSnapshotsByConfig(ctx, 7, "cfg-1")
+ require.NoError(t, err)
+ require.Len(t, rows, 1)
+ require.Equal(t, types.SkillSnapshotStateActive, rows[0].State)
+ require.Equal(t, "snap-1", rows[0].SnapshotID)
+}
+
+func TestListStaleInstallingFindsAbandonedRuns(t *testing.T) {
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ cutoff := time.Now().Add(-time.Hour)
+
+ oldInstalling := skillRow("sk-old-install", "cfg-1", "old-install")
+ sinceOld := cutoff.Add(-time.Hour)
+ oldInstalling.InstallingSince = &sinceOld
+ require.NoError(t, repo.CreateSkill(ctx, oldInstalling))
+
+ oldRemoving := skillRow("sk-old-remove", "cfg-1", "old-remove")
+ oldRemoving.Status = types.SkillStatusRemoving
+ sinceRemove := cutoff.Add(-30 * time.Minute)
+ oldRemoving.InstallingSince = &sinceRemove
+ require.NoError(t, repo.CreateSkill(ctx, oldRemoving))
+
+ fresh := skillRow("sk-new", "cfg-1", "new")
+ now := time.Now()
+ fresh.InstallingSince = &now
+ require.NoError(t, repo.CreateSkill(ctx, fresh))
+
+ ready := skillRow("sk-ready", "cfg-1", "ready")
+ ready.Status = types.SkillStatusReady
+ readySince := cutoff.Add(-2 * time.Hour)
+ ready.InstallingSince = &readySince
+ require.NoError(t, repo.CreateSkill(ctx, ready))
+
+ atCutoff := skillRow("sk-at-cutoff", "cfg-1", "at-cutoff")
+ atCutoff.InstallingSince = &cutoff
+ require.NoError(t, repo.CreateSkill(ctx, atCutoff))
+
+ stale, err := repo.ListStaleInstalling(ctx, cutoff)
+ require.NoError(t, err)
+ require.Len(t, stale, 2)
+ ids := []string{stale[0].ID, stale[1].ID}
+ require.ElementsMatch(t, []string{"sk-old-install", "sk-old-remove"}, ids)
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index 52954a17a..14693d205 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -165,6 +165,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewMCPToolApprovalRepository))
must(container.Provide(repository.NewMCPOAuthRepository))
must(container.Provide(repository.NewTenantSandboxConfigRepository))
+ must(container.Provide(repository.NewTenantSkillRepository))
must(container.Provide(repository.NewCustomAgentRepository))
must(container.Provide(repository.NewOrganizationRepository))
must(container.Provide(repository.NewKBShareRepository))
diff --git a/internal/sandbox/cube_mock_test.go b/internal/sandbox/cube_mock_test.go
index 0abbe668c..baa6c5c59 100644
--- a/internal/sandbox/cube_mock_test.go
+++ b/internal/sandbox/cube_mock_test.go
@@ -22,16 +22,28 @@ import (
// endpoints that the Cube SDK speaks to. CubeRemoteClient tests exercise the
// adapter through its public surface without requiring a real Cube deployment.
type cubeMockServer struct {
- server *httptest.Server
- mu sync.Mutex
- createBody map[string]any
- createCount atomic.Int32
- killCount atomic.Int32
- nextID atomic.Int64
- sandboxes map[string]map[string]any // sandboxID → sandbox state record
- executor func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)
- files map[string]map[string][]byte // sandboxID → path → content
- cmdHistory []commandRecord
+ server *httptest.Server
+ mu sync.Mutex
+ createBody map[string]any
+ createCount atomic.Int32
+ killCount atomic.Int32
+ nextID atomic.Int64
+ sandboxes map[string]map[string]any // sandboxID → sandbox state record
+ snapshots []cubeMockSnapshot
+ snapshotSeq int64
+ snapshotPageSize int
+ snapshotStuckPagination bool // always return the same non-empty next token
+ snapshotDeleteFailWith int // when set, DELETE /templates/:id returns this status
+ snapshotCreateBody map[string]any
+ executor func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)
+ files map[string]map[string][]byte // sandboxID → path → content
+ cmdHistory []commandRecord
+}
+
+type cubeMockSnapshot struct {
+ id string
+ sandboxID string
+ names []string
}
type commandRecord struct {
@@ -77,6 +89,12 @@ func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) {
m.handleList(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/connect") && r.Method == http.MethodPost:
m.handleConnect(w, r)
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/snapshots") && r.Method == http.MethodPost:
+ m.handleCreateSnapshot(w, r)
+ case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
+ m.handleListSnapshots(w, r)
+ case strings.HasPrefix(r.URL.Path, "/templates/") && r.Method == http.MethodDelete:
+ m.handleDeleteSnapshot(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodGet:
m.handleGetInfo(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodDelete:
@@ -184,6 +202,107 @@ func (m *cubeMockServer) handleDelete(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
+func (m *cubeMockServer) handleCreateSnapshot(w http.ResponseWriter, r *http.Request) {
+ id := extractSandboxID(r.URL.Path, "/snapshots")
+ body, _ := io.ReadAll(r.Body)
+ var raw map[string]any
+ _ = json.Unmarshal(body, &raw)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if _, ok := m.sandboxes[id]; !ok {
+ writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
+ return
+ }
+ m.snapshotCreateBody = raw
+ m.snapshotSeq++
+ snapshotID := "snap-" + strconv.FormatInt(m.snapshotSeq, 10)
+ var names []string
+ if rawName, ok := raw["name"].(string); ok {
+ if name := strings.TrimSpace(rawName); name != "" {
+ names = []string{name}
+ }
+ }
+ m.snapshots = append(m.snapshots, cubeMockSnapshot{
+ id: snapshotID,
+ sandboxID: id,
+ names: names,
+ })
+ writeJSON(w, http.StatusCreated, map[string]any{
+ "snapshotID": snapshotID,
+ "names": names,
+ })
+}
+
+func (m *cubeMockServer) handleListSnapshots(w http.ResponseWriter, r *http.Request) {
+ sandboxID := r.URL.Query().Get("sandboxID")
+ start := 0
+ if token := r.URL.Query().Get("nextToken"); token != "" {
+ if parsed, err := strconv.Atoi(token); err == nil && parsed > 0 {
+ start = parsed
+ }
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ pageSize := m.snapshotPageSize
+ if pageSize <= 0 {
+ pageSize = len(m.snapshots)
+ }
+
+ filtered := make([]cubeMockSnapshot, 0, len(m.snapshots))
+ for _, snapshot := range m.snapshots {
+ if sandboxID != "" && snapshot.sandboxID != sandboxID {
+ continue
+ }
+ filtered = append(filtered, snapshot)
+ }
+ if start > len(filtered) {
+ start = len(filtered)
+ }
+ end := start + pageSize
+ if end > len(filtered) {
+ end = len(filtered)
+ }
+ items := make([]map[string]any, 0, end-start)
+ for _, snapshot := range filtered[start:end] {
+ items = append(items, map[string]any{
+ "snapshotID": snapshot.id,
+ "names": snapshot.names,
+ })
+ }
+ if m.snapshotStuckPagination {
+ w.Header().Set("x-next-token", "stuck")
+ } else if end < len(filtered) {
+ w.Header().Set("x-next-token", strconv.Itoa(end))
+ }
+ writeJSON(w, http.StatusOK, items)
+}
+
+func (m *cubeMockServer) handleDeleteSnapshot(w http.ResponseWriter, r *http.Request) {
+ id := strings.TrimPrefix(r.URL.Path, "/templates/")
+
+ m.mu.Lock()
+ failWith := m.snapshotDeleteFailWith
+ m.mu.Unlock()
+ if failWith != 0 {
+ writeJSON(w, failWith, map[string]string{"message": "internal error"})
+ return
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for i, snapshot := range m.snapshots {
+ if snapshot.id != id {
+ continue
+ }
+ m.snapshots = append(m.snapshots[:i], m.snapshots[i+1:]...)
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ writeJSON(w, http.StatusNotFound, map[string]string{"message": "template not found"})
+}
+
// handleEnvd intercepts data-plane requests that the Cube SDK sends through
// the proxy. These carry a Host header like "49983-{sandboxID}.cube.app".
func (m *cubeMockServer) handleEnvd(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go
index d6a83c208..ed9a7dbc6 100644
--- a/internal/sandbox/cube_remote_client.go
+++ b/internal/sandbox/cube_remote_client.go
@@ -127,8 +127,11 @@ func (c *CubeRemoteClient) Capabilities() RemoteSandboxCapabilities {
SupportsPauseResume: true,
SupportsTimeoutRefresh: true,
SupportsFilesystemEnumeration: true,
- // Cube's CreateOptions has no volume-mount field yet; revisit when the
- // official Go SDK reaches v0.6.0.
+ // Cube stores snapshots as templates, so a snapshot ID can be handed
+ // straight back as CreateOptions.TemplateID.
+ SupportsSnapshots: true,
+ // CreateOptions still has no volume-mount field; skills ride on
+ // snapshots instead, so this stays false.
SupportsVolumes: false,
}
}
@@ -656,6 +659,80 @@ func (c *CubeRemoteClient) Stat(
}, nil
}
+// CreateSnapshot snapshots a running sandbox. Cube exposes this on *Sandbox,
+// so we connect by ID first (same shape as Delete).
+func (c *CubeRemoteClient) CreateSnapshot(
+ ctx context.Context, sandboxID string, name string,
+) (RemoteSnapshotRef, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return RemoteSnapshotRef{}, cubeInvalidRequest("CreateSnapshot", "sandbox ID is required", nil)
+ }
+ sb, err := c.client.Connect(ctx, sandboxID)
+ if err != nil {
+ return RemoteSnapshotRef{}, normalizeCubeError("CreateSnapshot", err)
+ }
+ info, err := sb.CreateSnapshot(ctx, strings.TrimSpace(name))
+ if err != nil {
+ return RemoteSnapshotRef{}, normalizeCubeError("CreateSnapshot", err)
+ }
+ if info == nil || strings.TrimSpace(info.SnapshotID) == "" {
+ return RemoteSnapshotRef{}, cubeInvalidRequest(
+ "CreateSnapshot", "provider returned an empty snapshot ID", nil)
+ }
+ return RemoteSnapshotRef{ID: info.SnapshotID, Names: info.Names}, nil
+}
+
+// DeleteSnapshot removes a snapshot. Cube returns an API error for a missing
+// template; we map not-found to success so cleanup is idempotent.
+func (c *CubeRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
+ if strings.TrimSpace(snapshotID) == "" {
+ return cubeInvalidRequest("DeleteSnapshot", "snapshot ID is required", nil)
+ }
+ if err := c.client.DeleteSnapshot(ctx, snapshotID); err != nil {
+ normalized := normalizeCubeError("DeleteSnapshot", err)
+ if IsRemoteNotFound(normalized) {
+ return nil
+ }
+ return normalized
+ }
+ return nil
+}
+
+// ListSnapshots pages through every snapshot, optionally filtered by source
+// sandbox. Used only by the orphan-reconciliation task.
+func (c *CubeRemoteClient) ListSnapshots(
+ ctx context.Context, sandboxID string,
+) ([]RemoteSnapshotRef, error) {
+ var (
+ out []RemoteSnapshotRef
+ token string
+ )
+ for {
+ page, next, err := c.client.ListSnapshots(ctx, cubesandbox.ListSnapshotsOptions{
+ SandboxID: strings.TrimSpace(sandboxID),
+ Limit: 100,
+ NextToken: token,
+ })
+ if err != nil {
+ return nil, normalizeCubeError("ListSnapshots", err)
+ }
+ for _, item := range page {
+ out = append(out, RemoteSnapshotRef{ID: item.SnapshotID, Names: item.Names})
+ }
+ if next == "" {
+ return out, nil
+ }
+ // A provider/SDK bug that echoes the same non-empty pagination token
+ // would otherwise spin forever and block skill-image orphan cleanup.
+ // Fail fast instead of hanging until the context is cancelled.
+ if next == token {
+ return nil, cubeInvalidRequest("ListSnapshots",
+ "provider returned the same pagination token", nil)
+ }
+ token = next
+ }
+}
+
// --- helpers -----------------------------------------------------------------
// isSDKNotFound spots the SDK's "resource missing" errors without having to
@@ -879,7 +956,11 @@ func normalizeCubeError(op string, err error) error {
case errors.Is(err, cubesandbox.ErrAuthentication):
kind = RemoteErrorKindAuthentication
case errors.Is(err, cubesandbox.ErrTemplateNotFound):
- kind = RemoteErrorKindInvalidRequest
+ if op == "DeleteSnapshot" {
+ kind = RemoteErrorKindNotFound
+ } else {
+ kind = RemoteErrorKindInvalidRequest
+ }
case errors.Is(err, cubesandbox.ErrSandboxNotFound):
kind = RemoteErrorKindNotFound
default:
@@ -975,6 +1056,7 @@ func cubeCredentialPresence(value string) string {
}
var (
- _ RemoteSandboxClient = (*CubeRemoteClient)(nil)
- _ RemoteSandboxHandle = (*cubeRemoteHandle)(nil)
+ _ RemoteSandboxClient = (*CubeRemoteClient)(nil)
+ _ RemoteSnapshotManager = (*CubeRemoteClient)(nil)
+ _ RemoteSandboxHandle = (*cubeRemoteHandle)(nil)
)
diff --git a/internal/sandbox/cube_remote_client_test.go b/internal/sandbox/cube_remote_client_test.go
index b9737b3df..c5eca9104 100644
--- a/internal/sandbox/cube_remote_client_test.go
+++ b/internal/sandbox/cube_remote_client_test.go
@@ -33,9 +33,100 @@ func TestCubeRemoteClientProviderAndCapabilities(t *testing.T) {
SupportsPauseResume: true,
SupportsTimeoutRefresh: true,
SupportsFilesystemEnumeration: true,
+ SupportsSnapshots: true,
}, client.Capabilities())
}
+func TestCubeRemoteClientCreateSnapshot(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+
+ ref, err := client.CreateSnapshot(ctx, handle.ID(), "weknora-sk-cfg1-g1")
+
+ require.NoError(t, err)
+ require.Equal(t, "snap-1", ref.ID)
+ require.Equal(t, []string{"weknora-sk-cfg1-g1"}, ref.Names)
+ mock.mu.Lock()
+ body := mock.snapshotCreateBody
+ mock.mu.Unlock()
+ require.Equal(t, "weknora-sk-cfg1-g1", body["name"])
+}
+
+func TestCubeRemoteClientCreateSnapshotRejectsEmptySandboxID(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+
+ _, err := client.CreateSnapshot(context.Background(), " ", "n")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestCubeRemoteClientDeleteSnapshotTreatsMissingAsSuccess(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+
+ err := client.DeleteSnapshot(context.Background(), "snap-missing")
+
+ require.NoError(t, err, "a missing snapshot must not fail the delete path")
+}
+
+func TestCubeRemoteClientDeleteSnapshotRejectsEmptySnapshotID(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+
+ err := client.DeleteSnapshot(context.Background(), " ")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestCubeRemoteClientDeleteSnapshotReturnsUnexpectedErrors(t *testing.T) {
+ mock := newCubeMockServer(t)
+ mock.snapshotDeleteFailWith = http.StatusInternalServerError
+ client := newTestCubeRemoteClient(t, mock)
+
+ err := client.DeleteSnapshot(context.Background(), "snap-any")
+
+ require.Error(t, err)
+ require.False(t, IsRemoteNotFound(err))
+}
+
+func TestCubeRemoteClientListSnapshotsRejectsStuckPagination(t *testing.T) {
+ mock := newCubeMockServer(t)
+ mock.snapshotStuckPagination = true
+ client := newTestCubeRemoteClient(t, mock)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ _, err := client.ListSnapshots(ctx, "")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestCubeRemoteClientListSnapshotsPagesAllResults(t *testing.T) {
+ mock := newCubeMockServer(t)
+ mock.snapshotPageSize = 1
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+ first, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ second, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ firstRef, err := client.CreateSnapshot(ctx, first.ID(), "weknora-sk-cfg1-g1")
+ require.NoError(t, err)
+ secondRef, err := client.CreateSnapshot(ctx, first.ID(), "weknora-sk-cfg2-g1")
+ require.NoError(t, err)
+ _, err = client.CreateSnapshot(ctx, second.ID(), "other")
+ require.NoError(t, err)
+
+ list, err := client.ListSnapshots(ctx, first.ID())
+
+ require.NoError(t, err)
+ require.Equal(t, []RemoteSnapshotRef{firstRef, secondRef}, list)
+}
+
func TestCubeRemoteClientCreateWritesLifecyclePayload(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go
index 222bbf1dd..d16ffd6f9 100644
--- a/internal/sandbox/e2b_remote_client.go
+++ b/internal/sandbox/e2b_remote_client.go
@@ -143,7 +143,10 @@ func (c *E2BRemoteClient) Capabilities() RemoteSandboxCapabilities {
SupportsPauseResume: true,
SupportsTimeoutRefresh: true,
SupportsFilesystemEnumeration: true,
- SupportsVolumes: true,
+ // E2B stores snapshots as templates, so a snapshot ID can be handed
+ // straight back as CreateOptions.TemplateID.
+ SupportsSnapshots: true,
+ SupportsVolumes: true,
}
}
@@ -920,6 +923,115 @@ func (c *E2BRemoteClient) Stat(
}, nil
}
+// CreateSnapshot snapshots a running sandbox. E2B exposes snapshots on the
+// connected sandbox handle, so the adapter reattaches first like Delete does.
+func (c *E2BRemoteClient) CreateSnapshot(
+ ctx context.Context, sandboxID string, name string,
+) (RemoteSnapshotRef, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return RemoteSnapshotRef{}, e2bInvalidRequest("CreateSnapshot", "sandbox ID is required", nil)
+ }
+ timeoutSeconds, err := e2bTimeoutSeconds(
+ RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ c.timeout,
+ )
+ if err != nil {
+ return RemoteSnapshotRef{}, e2bInvalidRequest("CreateSnapshot", err.Error(), err)
+ }
+ sandbox, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)
+ if err != nil {
+ return RemoteSnapshotRef{}, normalizeE2BError("CreateSnapshot", err)
+ }
+ if sandbox == nil || strings.TrimSpace(sandbox.ID) == "" ||
+ sandbox.ID != sandboxID {
+ return RemoteSnapshotRef{}, NewRemoteError(
+ SandboxTypeE2B, "CreateSnapshot", RemoteErrorKindInternal,
+ "e2b returned a mismatched sandbox handle", nil,
+ )
+ }
+
+ var info *e2b.SnapshotInfo
+ if trimmed := strings.TrimSpace(name); trimmed != "" {
+ info, err = sandbox.CreateSnapshot(ctx, trimmed)
+ } else {
+ info, err = sandbox.CreateSnapshot(ctx)
+ }
+ if err != nil {
+ return RemoteSnapshotRef{}, normalizeE2BError("CreateSnapshot", err)
+ }
+ if info == nil || strings.TrimSpace(info.SnapshotID) == "" {
+ return RemoteSnapshotRef{}, e2bInvalidRequest(
+ "CreateSnapshot", "provider returned an empty snapshot ID", nil)
+ }
+ return RemoteSnapshotRef{ID: info.SnapshotID, Names: info.Names}, nil
+}
+
+// DeleteSnapshot removes a snapshot. go-e2b reports a missing snapshot as
+// (false, nil), so cleanup stays idempotent while genuine provider errors
+// still surface through the neutral error taxonomy.
+func (c *E2BRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
+ if strings.TrimSpace(snapshotID) == "" {
+ return e2bInvalidRequest("DeleteSnapshot", "snapshot ID is required", nil)
+ }
+ if _, err := c.client.DeleteSnapshot(ctx, snapshotID); err != nil {
+ normalized := normalizeE2BError("DeleteSnapshot", err)
+ if IsRemoteNotFound(normalized) {
+ return nil
+ }
+ return normalized
+ }
+ return nil
+}
+
+// ListSnapshots pages through every snapshot, optionally filtered by source
+// sandbox. Used only by the skill-image orphan-reconciliation task.
+func (c *E2BRemoteClient) ListSnapshots(
+ ctx context.Context, sandboxID string,
+) ([]RemoteSnapshotRef, error) {
+ baseOptions := []e2b.ListSnapshotsOption{e2b.WithSnapshotLimit(100)}
+ if trimmed := strings.TrimSpace(sandboxID); trimmed != "" {
+ baseOptions = append(baseOptions, e2b.WithSnapshotSandboxID(trimmed))
+ }
+
+ var (
+ out []RemoteSnapshotRef
+ token string
+ )
+ for {
+ options := append([]e2b.ListSnapshotsOption(nil), baseOptions...)
+ if token != "" {
+ options = append(options, e2b.WithSnapshotNextToken(token))
+ }
+ page, err := c.client.ListSnapshots(ctx, options...)
+ if err != nil {
+ return nil, normalizeE2BError("ListSnapshots", err)
+ }
+ if page == nil {
+ return nil, NewRemoteError(
+ SandboxTypeE2B,
+ "ListSnapshots",
+ RemoteErrorKindInternal,
+ "e2b returned an empty snapshot list page",
+ nil,
+ )
+ }
+ for _, item := range page.Snapshots {
+ out = append(out, RemoteSnapshotRef{ID: item.SnapshotID, Names: item.Names})
+ }
+ if page.NextToken == "" {
+ return out, nil
+ }
+ // A provider/SDK bug that echoes the same non-empty pagination token
+ // would otherwise spin forever and block skill-image orphan cleanup.
+ // Fail fast instead of hanging until the context is cancelled.
+ if page.NextToken == token {
+ return nil, e2bInvalidRequest("ListSnapshots",
+ "provider returned the same pagination token", nil)
+ }
+ token = page.NextToken
+ }
+}
+
// --- helpers -----------------------------------------------------------------
// e2bTimeoutSeconds maps the neutral RemoteTimeoutPolicy onto E2B's integer
@@ -1119,6 +1231,7 @@ func e2bRemoteEntryType(fileType string) RemoteDirEntryType {
}
var (
- _ RemoteSandboxClient = (*E2BRemoteClient)(nil)
- _ RemoteSandboxHandle = (*e2bRemoteHandle)(nil)
+ _ RemoteSandboxClient = (*E2BRemoteClient)(nil)
+ _ RemoteSnapshotManager = (*E2BRemoteClient)(nil)
+ _ RemoteSandboxHandle = (*e2bRemoteHandle)(nil)
)
diff --git a/internal/sandbox/e2b_remote_client_test.go b/internal/sandbox/e2b_remote_client_test.go
index ce9436ccb..09737b58a 100644
--- a/internal/sandbox/e2b_remote_client_test.go
+++ b/internal/sandbox/e2b_remote_client_test.go
@@ -51,16 +51,25 @@ type e2bMockServer struct {
connectID string
deleteID string
- mu sync.Mutex
- v2Queries []url.Values
- repeatV2NextToken bool
- unsafeV2NextToken string
- sandboxes map[string]map[string]any // sandboxID → SandboxInfo JSON
+ mu sync.Mutex
+ v2Queries []url.Values
+ snapshotQueries []url.Values
+ repeatV2NextToken bool
+ unsafeV2NextToken string
+ repeatSnapshotNextToken bool
+ snapshotPageSize int
+ snapshotDeleteFailWith int
+ snapshotCreateBody map[string]any
+ sandboxes map[string]map[string]any // sandboxID -> SandboxInfo JSON
+ snapshots map[string]map[string]any // snapshotID -> SnapshotInfo JSON
}
func newE2BMockServer(t *testing.T) *e2bMockServer {
t.Helper()
- m := &e2bMockServer{sandboxes: map[string]map[string]any{}}
+ m := &e2bMockServer{
+ sandboxes: map[string]map[string]any{},
+ snapshots: map[string]map[string]any{},
+ }
m.server = httptest.NewServer(http.HandlerFunc(m.handle))
t.Cleanup(m.server.Close)
return m
@@ -103,6 +112,32 @@ func (m *e2bMockServer) handle(w http.ResponseWriter, r *http.Request) {
case r.URL.Path == "/v2/sandboxes" && r.Method == http.MethodGet:
m.handleListV2(w, r)
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") &&
+ strings.HasSuffix(r.URL.Path, "/snapshots") &&
+ r.Method == http.MethodPost:
+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/sandboxes/"), "/snapshots")
+ if _, ok := m.sandboxes[id]; !ok {
+ http.NotFound(w, r)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ _ = json.Unmarshal(body, &m.snapshotCreateBody)
+ snapshotID := "snap-" + strconv.Itoa(len(m.snapshots)+1)
+ name, _ := m.snapshotCreateBody["name"].(string)
+ names := []string{}
+ if name != "" {
+ names = append(names, name)
+ }
+ m.snapshots[snapshotID] = map[string]any{
+ "snapshotID": snapshotID,
+ "sandboxID": id,
+ "names": names,
+ }
+ writeJSON(w, http.StatusCreated, m.snapshots[snapshotID])
+
+ case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
+ m.handleListSnapshots(w, r)
+
case strings.HasPrefix(r.URL.Path, "/sandboxes/") &&
strings.HasSuffix(r.URL.Path, "/connect") &&
r.Method == http.MethodPost:
@@ -146,6 +181,19 @@ func (m *e2bMockServer) handle(w http.ResponseWriter, r *http.Request) {
delete(m.sandboxes, id)
w.WriteHeader(http.StatusNoContent)
+ case strings.HasPrefix(r.URL.Path, "/templates/") && r.Method == http.MethodDelete:
+ if m.snapshotDeleteFailWith != 0 {
+ http.Error(w, "delete failed", m.snapshotDeleteFailWith)
+ return
+ }
+ id := strings.TrimPrefix(r.URL.Path, "/templates/")
+ if _, ok := m.snapshots[id]; !ok {
+ http.NotFound(w, r)
+ return
+ }
+ delete(m.snapshots, id)
+ w.WriteHeader(http.StatusNoContent)
+
default:
http.NotFound(w, r)
}
@@ -225,6 +273,55 @@ func (m *e2bMockServer) handleListV2(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, items)
}
+func (m *e2bMockServer) handleListSnapshots(w http.ResponseWriter, r *http.Request) {
+ m.mu.Lock()
+ m.snapshotQueries = append(m.snapshotQueries, r.URL.Query())
+ repeatToken := m.repeatSnapshotNextToken
+ pageSize := m.snapshotPageSize
+ m.mu.Unlock()
+
+ sandboxID := r.URL.Query().Get("sandboxID")
+ ids := make([]string, 0, len(m.snapshots))
+ for id, info := range m.snapshots {
+ if sandboxID != "" && info["sandboxID"] != sandboxID {
+ continue
+ }
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+
+ limit := 100
+ if pageSize > 0 {
+ limit = pageSize
+ }
+ if raw := r.URL.Query().Get("limit"); raw != "" {
+ if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && pageSize == 0 {
+ limit = parsed
+ }
+ }
+ start := 0
+ if raw := r.URL.Query().Get("nextToken"); raw != "" && raw != "repeat" {
+ start, _ = strconv.Atoi(raw)
+ }
+ if start > len(ids) {
+ start = len(ids)
+ }
+ end := start + limit
+ if end > len(ids) {
+ end = len(ids)
+ }
+ items := make([]map[string]any, 0, end-start)
+ for _, id := range ids[start:end] {
+ items = append(items, m.snapshots[id])
+ }
+ if repeatToken {
+ w.Header().Set("X-Next-Token", "repeat")
+ } else if end < len(ids) {
+ w.Header().Set("X-Next-Token", strconv.Itoa(end))
+ }
+ writeJSON(w, http.StatusOK, items)
+}
+
func mockMetadataMatches(raw any, expected map[string]string) bool {
if len(expected) == 0 {
return true
@@ -258,15 +355,108 @@ func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {
client := newTestE2BRemoteClient(t, newE2BMockServer(t))
require.Equal(t, SandboxTypeE2B, client.Provider())
- caps := client.Capabilities()
- require.True(t, caps.SupportsReconnect)
- require.True(t, caps.SupportsMetadata)
- require.True(t, caps.SupportsListSandboxes)
- require.True(t, caps.SupportsPauseResume)
- require.True(t, caps.SupportsTimeoutRefresh)
- // The go-e2b SDK now supports ListDir/Stat/MakeDir/Remove via a
- // forked SDK (replaced in go.mod). Filesystem enumeration is enabled.
- require.True(t, caps.SupportsFilesystemEnumeration)
+ require.Equal(t, RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ SupportsMetadata: true,
+ SupportsListSandboxes: true,
+ SupportsPauseResume: true,
+ SupportsTimeoutRefresh: true,
+ SupportsFilesystemEnumeration: true,
+ SupportsSnapshots: true,
+ SupportsVolumes: true,
+ }, client.Capabilities())
+}
+
+func TestE2BRemoteClientCreateSnapshot(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+
+ ref, err := client.CreateSnapshot(ctx, handle.ID(), "weknora-sk-cfg1-g1")
+
+ require.NoError(t, err)
+ require.Equal(t, "snap-1", ref.ID)
+ require.Equal(t, []string{"weknora-sk-cfg1-g1"}, ref.Names)
+ require.Equal(t, "weknora-sk-cfg1-g1", mock.snapshotCreateBody["name"])
+ require.Equal(t, int32(1), mock.connectCount.Load())
+}
+
+func TestE2BRemoteClientCreateSnapshotRejectsEmptySandboxID(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+
+ _, err := client.CreateSnapshot(context.Background(), " ", "n")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestE2BRemoteClientDeleteSnapshotTreatsMissingAsSuccess(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+
+ err := client.DeleteSnapshot(context.Background(), "snap-missing")
+
+ require.NoError(t, err, "a missing snapshot must not fail the delete path")
+}
+
+func TestE2BRemoteClientDeleteSnapshotRejectsEmptySnapshotID(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+
+ err := client.DeleteSnapshot(context.Background(), " ")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestE2BRemoteClientDeleteSnapshotReturnsUnexpectedErrors(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.snapshotDeleteFailWith = http.StatusInternalServerError
+ client := newTestE2BRemoteClient(t, mock)
+
+ err := client.DeleteSnapshot(context.Background(), "snap-any")
+
+ require.Error(t, err)
+ require.False(t, IsRemoteNotFound(err))
+}
+
+func TestE2BRemoteClientListSnapshotsRejectsStuckPagination(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.repeatSnapshotNextToken = true
+ client := newTestE2BRemoteClient(t, mock)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ _, err := client.ListSnapshots(ctx, "")
+
+ require.Error(t, err)
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestE2BRemoteClientListSnapshotsPagesAllResults(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.snapshotPageSize = 1
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+ first, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ second, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ firstRef, err := client.CreateSnapshot(ctx, first.ID(), "weknora-sk-cfg1-g1")
+ require.NoError(t, err)
+ secondRef, err := client.CreateSnapshot(ctx, first.ID(), "weknora-sk-cfg2-g1")
+ require.NoError(t, err)
+ _, err = client.CreateSnapshot(ctx, second.ID(), "other")
+ require.NoError(t, err)
+
+ list, err := client.ListSnapshots(ctx, first.ID())
+
+ require.NoError(t, err)
+ require.Equal(t, []RemoteSnapshotRef{firstRef, secondRef}, list)
+ require.Len(t, mock.snapshotQueries, 2)
+ require.Equal(t, first.ID(), mock.snapshotQueries[0].Get("sandboxID"))
+ require.Equal(t, "100", mock.snapshotQueries[0].Get("limit"))
+ require.Equal(t, "1", mock.snapshotQueries[1].Get("nextToken"))
}
func TestE2BRemoteClientListTemplatesReconcilesStandardTemplateBuildStatus(t *testing.T) {
diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go
index e329e340c..b6ae18850 100644
--- a/internal/sandbox/remote_client.go
+++ b/internal/sandbox/remote_client.go
@@ -336,6 +336,11 @@ type RemoteSandboxCapabilities struct {
// staging tools that would otherwise fail at request time.
SupportsFilesystemEnumeration bool
+ // SupportsSnapshots reports whether the provider can snapshot a running
+ // sandbox into a reusable image. Snapshot IDs double as template IDs on
+ // both Cube and E2B, which is what makes skill images work.
+ SupportsSnapshots bool
+
// SupportsVolumes is true when the provider can mount a named volume into
// a sandbox at creation time (RemoteCreateRequest.VolumeMounts). Callers
// use this to tell an operator up front that a backend cannot serve
@@ -413,3 +418,41 @@ func cloneMetadata(source map[string]string) map[string]string {
}
return result
}
+
+// RemoteSnapshotRef identifies one provider-side snapshot. ID can be passed
+// straight back as RemoteCreateRequest.TemplateID: both Cube and E2B store
+// snapshots as templates.
+type RemoteSnapshotRef struct {
+ ID string
+ Names []string
+}
+
+// RemoteSnapshotManager is an optional capability used only by the skill
+// install/remove paths. Session execution never touches it.
+type RemoteSnapshotManager interface {
+ // CreateSnapshot snapshots a running sandbox. An empty name lets the
+ // provider generate one. The provider pauses the sandbox while the
+ // snapshot is taken.
+ CreateSnapshot(ctx context.Context, sandboxID string, name string) (RemoteSnapshotRef, error)
+
+ // DeleteSnapshot removes a snapshot. A missing snapshot is NOT an error:
+ // both SDKs treat delete as idempotent and so must every adapter.
+ DeleteSnapshot(ctx context.Context, snapshotID string) error
+
+ // ListSnapshots lists snapshots. An empty sandboxID lists all of them.
+ ListSnapshots(ctx context.Context, sandboxID string) ([]RemoteSnapshotRef, error)
+}
+
+// SnapshotManagerFrom narrows a client to its snapshot capability. It returns
+// false for providers that cannot snapshot (docker/local), so callers can fall
+// back to the base template instead of failing.
+func SnapshotManagerFrom(client RemoteSandboxClient) (RemoteSnapshotManager, bool) {
+ if client == nil {
+ return nil, false
+ }
+ mgr, ok := client.(RemoteSnapshotManager)
+ if !ok {
+ return nil, false
+ }
+ return mgr, true
+}
diff --git a/internal/sandbox/remote_fake_test.go b/internal/sandbox/remote_fake_test.go
index ed52fc72b..4c5505951 100644
--- a/internal/sandbox/remote_fake_test.go
+++ b/internal/sandbox/remote_fake_test.go
@@ -28,6 +28,11 @@ type fakeRemoteRecord struct {
startedAt time.Time
}
+type fakeRemoteWriteFile struct {
+ path string
+ content []byte
+}
+
type fakeRemoteClient struct {
mu sync.Mutex
provider RemoteProvider
@@ -52,6 +57,11 @@ type fakeRemoteClient struct {
makeDirPaths []string
execRequests []RemoteExecRequest
+ writeFiles []fakeRemoteWriteFile
+
+ // snapshots maps snapshotID -> source sandboxID.
+ snapshots map[string]string
+ snapshotSeq int
}
func newFakeRemoteClient(provider RemoteProvider) *fakeRemoteClient {
@@ -240,11 +250,17 @@ func (c *fakeRemoteClient) Exec(
}
func (c *fakeRemoteClient) WriteFile(
- context.Context,
- RemoteSandboxHandle,
- string,
- []byte,
+ _ context.Context,
+ _ RemoteSandboxHandle,
+ path string,
+ content []byte,
) error {
+ c.mu.Lock()
+ c.writeFiles = append(c.writeFiles, fakeRemoteWriteFile{
+ path: path,
+ content: append([]byte(nil), content...),
+ })
+ c.mu.Unlock()
return nil
}
@@ -283,6 +299,46 @@ func (c *fakeRemoteClient) Stat(
return nil, nil
}
+func (c *fakeRemoteClient) CreateSnapshot(
+ ctx context.Context, sandboxID string, name string,
+) (RemoteSnapshotRef, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.snapshots == nil {
+ c.snapshots = map[string]string{}
+ }
+ c.snapshotSeq++
+ id := fmt.Sprintf("snap-%d", c.snapshotSeq)
+ c.snapshots[id] = sandboxID
+ names := []string(nil)
+ if name != "" {
+ names = []string{name}
+ }
+ return RemoteSnapshotRef{ID: id, Names: names}, nil
+}
+
+func (c *fakeRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.snapshots, snapshotID) // missing snapshot is success
+ return nil
+}
+
+func (c *fakeRemoteClient) ListSnapshots(
+ ctx context.Context, sandboxID string,
+) ([]RemoteSnapshotRef, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var out []RemoteSnapshotRef
+ for id, src := range c.snapshots {
+ if sandboxID != "" && src != sandboxID {
+ continue
+ }
+ out = append(out, RemoteSnapshotRef{ID: id})
+ }
+ return out, nil
+}
+
func (c *fakeRemoteClient) addSandbox(
id string,
templateID string,
diff --git a/internal/sandbox/remote_sandbox.go b/internal/sandbox/remote_sandbox.go
index 1c9a9598b..e558d4269 100644
--- a/internal/sandbox/remote_sandbox.go
+++ b/internal/sandbox/remote_sandbox.go
@@ -113,6 +113,31 @@ func (s *RemoteSandbox) ExecuteOnHandle(
return nil, ErrInvalidScript
}
+ // Skills installed into the image are already on disk; uploading them again
+ // would both waste a round trip and shadow the venv layout next to them.
+ if remote := strings.TrimSpace(cfg.RemoteScriptPath); remote != "" {
+ skillDir, ok := SkillDirForImageScript(remote)
+ if !ok {
+ // RemoteScriptPath is only trusted for installed image skills; rejecting
+ // other paths avoids silently executing arbitrary sandbox files with
+ // image-skill defaults when callers pass an unvalidated path.
+ return nil, ErrInvalidScript
+ }
+ command, baseArgs := SkillInterpreterCommand(skillDir, remote)
+ request := RemoteExecRequest{
+ Command: command,
+ Args: append(baseArgs, cfg.Args...),
+ Stdin: cfg.Stdin,
+ Env: cfg.Env,
+ WorkDir: SessionWorkspaceRoot,
+ User: DefaultSandboxExecUser,
+ Timeout: effectiveTimeout(cfg, 0),
+ }
+ start := time.Now()
+ execResult, err := s.client.Exec(ctx, handle, request)
+ return remoteExecuteResult(execResult, err, time.Since(start)), nil
+ }
+
content, err := readScriptContent(cfg)
if err != nil {
return nil, err
diff --git a/internal/sandbox/remote_sandbox_test.go b/internal/sandbox/remote_sandbox_test.go
new file mode 100644
index 000000000..c66d07655
--- /dev/null
+++ b/internal/sandbox/remote_sandbox_test.go
@@ -0,0 +1,76 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExecuteOnHandleRunsRemoteScriptWithoutUploading(t *testing.T) {
+ ctx := context.Background()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
+ require.NoError(t, err)
+
+ skillDir := SkillDirFor("sk-1")
+ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
+ RemoteScriptPath: skillDir + "/scripts/run.py",
+ Args: []string{"--flag"},
+ })
+
+ require.NoError(t, err)
+ client.mu.Lock()
+ writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
+ execs := append([]RemoteExecRequest(nil), client.execRequests...)
+ client.mu.Unlock()
+ require.Empty(t, writes,
+ "a script that already lives in the image must not be re-uploaded")
+ require.Len(t, execs, 1)
+ last := execs[0]
+ require.Equal(t, SessionWorkspaceRoot, last.WorkDir)
+ require.Equal(t, DefaultSandboxExecUser, last.User)
+ require.Contains(t, last.Args[len(last.Args)-1], "--flag")
+ require.Contains(t, last.Args[1], skillDir+"/.venv/bin/python")
+}
+
+func TestExecuteOnHandleNestedRemoteScriptUsesSkillRootVenv(t *testing.T) {
+ ctx := context.Background()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
+ require.NoError(t, err)
+
+ skillDir := SkillDirFor("sk-1")
+ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
+ RemoteScriptPath: skillDir + "/scripts/tools/run.py",
+ })
+
+ require.NoError(t, err)
+ client.mu.Lock()
+ execs := append([]RemoteExecRequest(nil), client.execRequests...)
+ client.mu.Unlock()
+ require.Len(t, execs, 1)
+ require.Contains(t, execs[0].Args[1], skillDir+"/.venv/bin/python")
+}
+
+func TestExecuteOnHandleRejectsRemoteScriptOutsideSkillRoot(t *testing.T) {
+ ctx := context.Background()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
+ require.NoError(t, err)
+
+ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
+ RemoteScriptPath: "/workspace/run.py",
+ })
+
+ require.ErrorIs(t, err, ErrInvalidScript)
+ client.mu.Lock()
+ writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
+ execs := append([]RemoteExecRequest(nil), client.execRequests...)
+ client.mu.Unlock()
+ require.Empty(t, writes)
+ require.Empty(t, execs)
+}
diff --git a/internal/sandbox/remote_snapshot_test.go b/internal/sandbox/remote_snapshot_test.go
new file mode 100644
index 000000000..8fabba233
--- /dev/null
+++ b/internal/sandbox/remote_snapshot_test.go
@@ -0,0 +1,55 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSnapshotManagerFromDetectsCapability(t *testing.T) {
+ t.Run("client implementing the interface is returned", func(t *testing.T) {
+ client := newFakeRemoteClient(SandboxTypeCube)
+ client.capabilities.SupportsSnapshots = true
+
+ mgr, ok := SnapshotManagerFrom(client)
+
+ require.True(t, ok)
+ require.NotNil(t, mgr)
+ })
+
+ t.Run("client without snapshot support is rejected", func(t *testing.T) {
+ client := &noSnapshotClient{}
+
+ mgr, ok := SnapshotManagerFrom(client)
+
+ require.False(t, ok)
+ require.Nil(t, mgr)
+ })
+}
+
+func TestFakeSnapshotRoundTrip(t *testing.T) {
+ ctx := context.Background()
+ client := newFakeRemoteClient(SandboxTypeCube)
+
+ ref, err := client.CreateSnapshot(ctx, "sb-1", "weknora-sk-abc-g1")
+ require.NoError(t, err)
+ require.NotEmpty(t, ref.ID)
+
+ list, err := client.ListSnapshots(ctx, "sb-1")
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ require.Equal(t, ref.ID, list[0].ID)
+
+ // Deleting twice must be idempotent: a missing snapshot is not an error.
+ require.NoError(t, client.DeleteSnapshot(ctx, ref.ID))
+ require.NoError(t, client.DeleteSnapshot(ctx, ref.ID))
+
+ list, err = client.ListSnapshots(ctx, "sb-1")
+ require.NoError(t, err)
+ require.Empty(t, list)
+}
+
+// noSnapshotClient implements RemoteSandboxClient without the snapshot methods,
+// so SnapshotManagerFrom must reject it.
+type noSnapshotClient struct{ RemoteSandboxClient }
diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go
index 75e435fa1..ed683aad5 100644
--- a/internal/sandbox/sandbox.go
+++ b/internal/sandbox/sandbox.go
@@ -179,6 +179,11 @@ type ExecuteConfig struct {
// backend ignores it. When empty, those backends fall back to an ephemeral
// (one-shot) sandbox created and torn down inside the single Execute call.
SessionID string
+
+ // RemoteScriptPath is an absolute path to a script that already exists
+ // inside the sandbox image (installed skills). When set, the executor
+ // skips the upload step and runs it in place.
+ RemoteScriptPath string
}
// ExecuteResult contains the result of script execution
diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go
index d15bd28ed..91824635a 100644
--- a/internal/sandbox/session_manager.go
+++ b/internal/sandbox/session_manager.go
@@ -365,7 +365,7 @@ func (m *SessionBoundManager) ensureExecutionOutputDir(
func executionOutputDir(cfg *ExecuteConfig) string {
if cfg != nil && cfg.Env != nil {
if dir := strings.TrimSpace(cfg.Env[skillOutputEnvVar]); dir != "" {
- if clean, err := cleanSessionWorkDir(dir); err == nil {
+ if clean, err := cleanSessionWorkDir(dir, false); err == nil {
return clean
}
}
@@ -512,9 +512,25 @@ func (m *SessionBoundManager) ReadSessionFile(
return m.client.ReadFile(ctx, handle, filePath)
}
+// ShellExecOptions carries per-call shell execution knobs. The install-only
+// flags are explicit so skill image maintenance can write under /opt without
+// loosening work_dir or user privileges for ordinary chat sessions.
+type ShellExecOptions struct {
+ WorkDir string
+ Timeout time.Duration
+ Env map[string]string
+
+ // AllowSkillsRoot lets installer calls work inside the skills image root.
+ // See cleanSessionWorkDir for why the work_dir allowlist is lexical only.
+ AllowSkillsRoot bool
+ // AsRoot is reserved for install/maintenance commands that need to write
+ // outside /workspace; ordinary sessions must keep the provider default user.
+ AsRoot bool
+}
+
// ExecShellCommand runs a shell one-liner inside the session's persistent
-// sandbox. Fallback is explicitly refused so shell_exec never escapes onto
-// the host machine.
+// sandbox. It preserves the shell_exec tool contract: /workspace-only work_dir
+// validation and provider default user.
func (m *SessionBoundManager) ExecShellCommand(
ctx context.Context,
sessionID string,
@@ -522,6 +538,22 @@ func (m *SessionBoundManager) ExecShellCommand(
workDir string,
timeout time.Duration,
env map[string]string,
+) (*ExecuteResult, error) {
+ return m.ExecShellCommandWithOptions(ctx, sessionID, command, ShellExecOptions{
+ WorkDir: workDir,
+ Timeout: timeout,
+ Env: env,
+ })
+}
+
+// ExecShellCommandWithOptions runs a shell command with install-only options.
+// Fallback is explicitly refused so even privileged installer calls never
+// escape onto the WeKnora host machine.
+func (m *SessionBoundManager) ExecShellCommandWithOptions(
+ ctx context.Context,
+ sessionID string,
+ command string,
+ opts ShellExecOptions,
) (*ExecuteResult, error) {
if err := m.requireRemoteBackend(); err != nil {
return nil, fmt.Errorf(
@@ -535,6 +567,7 @@ func (m *SessionBoundManager) ExecShellCommand(
if strings.TrimSpace(command) == "" {
return nil, errors.New("sandbox: command required for ExecShellCommand")
}
+ timeout := opts.Timeout
if timeout <= 0 {
timeout = m.config.DefaultTimeout
}
@@ -542,9 +575,9 @@ func (m *SessionBoundManager) ExecShellCommand(
timeout = DefaultTimeout
}
- workDir = strings.TrimSpace(workDir)
+ workDir := strings.TrimSpace(opts.WorkDir)
if workDir != "" {
- cleanWorkDir, err := cleanSessionWorkDir(workDir)
+ cleanWorkDir, err := cleanSessionWorkDir(workDir, opts.AllowSkillsRoot)
if err != nil {
return nil, err
}
@@ -561,17 +594,23 @@ func (m *SessionBoundManager) ExecShellCommand(
}
}
+ // Named explicitly rather than left to each adapter's default. This command
+ // line comes from the model, so it is the one exec path an injected prompt
+ // reaches directly, and the account it runs as must not depend on which
+ // backend the workspace happens to have selected. Only a caller inside the
+ // server may ask for root, and only image maintenance does.
+ user := DefaultSandboxExecUser
+ if opts.AsRoot {
+ user = "root"
+ }
+
start := time.Now()
execResult, execErr := m.client.Exec(ctx, handle, RemoteExecRequest{
Command: command,
Shell: true,
- Env: env,
+ Env: opts.Env,
WorkDir: workDir,
- // Named explicitly rather than left to each adapter's default. This
- // command line comes from the model, so it is the one exec path an
- // injected prompt reaches directly, and the account it runs as must
- // not depend on which backend the workspace happens to have selected.
- User: DefaultSandboxExecUser,
+ User: user,
Timeout: timeout,
})
duration := time.Since(start)
@@ -777,14 +816,39 @@ func cleanSessionInputPath(filePath string) (string, error) {
)
}
-func cleanSessionWorkDir(workDir string) (string, error) {
+// cleanSessionWorkDir keeps shell_exec inside directories we are willing to let
+// an agent work in. Ordinary sessions get /workspace only.
+//
+// Validation is lexical (path.Clean plus prefix checks): a symlink under an
+// allowed root that resolves elsewhere at execution time is not detected and
+// that is intentional. The only caller that passes allowSkillsRoot also passes
+// AsRoot and runs arbitrary install shell commands, so a symlink would grant
+// nothing those commands cannot already reach via cd or absolute paths. For
+// ordinary sessions the allowlist is unchanged and its lexical nature is
+// pre-existing. The allowlist stops casual wandering and makes intent
+// auditable; the real isolation boundary is the remote sandbox itself.
+//
+// allowSkillsRoot widens it to the skills image root for install/maintenance
+// sessions, so the installer agent can set work_dir to the skill directory and
+// run ordinary relative commands instead of composing long absolute paths. It
+// is a widening, not a removal: everything outside these two roots is still
+// refused.
+func cleanSessionWorkDir(workDir string, allowSkillsRoot bool) (string, error) {
clean := path.Clean(strings.TrimSpace(workDir))
if clean == SessionWorkspaceRoot || strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {
return clean, nil
}
+ if allowSkillsRoot &&
+ (clean == SkillsImageRoot || strings.HasPrefix(clean, SkillsImageRoot+"/")) {
+ return clean, nil
+ }
+ allowed := SessionWorkspaceRoot
+ if allowSkillsRoot {
+ allowed = SessionWorkspaceRoot + ", " + SkillsImageRoot
+ }
return "", fmt.Errorf(
- "sandbox: work dir %q is outside %s",
- workDir, SessionWorkspaceRoot,
+ "sandbox: work dir %q is outside allowed roots (%s)",
+ workDir, allowed,
)
}
diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go
index b8c7bd5a4..cc011235d 100644
--- a/internal/sandbox/session_manager_test.go
+++ b/internal/sandbox/session_manager_test.go
@@ -132,3 +132,105 @@ func TestSessionBoundManagerShellExecRunsAsSandboxUser(t *testing.T) {
require.Len(t, shell, 1)
require.Equal(t, DefaultSandboxExecUser, shell[0].User)
}
+
+func TestCleanSessionWorkDirRejectsSkillRootByDefault(t *testing.T) {
+ _, err := cleanSessionWorkDir(SkillDirFor("sk-1"), false)
+ require.Error(t, err, "ordinary sessions must stay inside /workspace")
+
+ got, err := cleanSessionWorkDir(SkillDirFor("sk-1"), true)
+ require.NoError(t, err, "install sessions need to work inside the skills root")
+ require.Equal(t, SkillDirFor("sk-1"), got)
+}
+
+func TestCleanSessionWorkDirStillRejectsArbitraryPathsInInstallMode(t *testing.T) {
+ _, err := cleanSessionWorkDir("/etc", true)
+ require.Error(t, err, "install mode widens the allowlist, it does not remove it")
+}
+
+func TestExecShellCommandWithOptionsRunsAsRootOnlyWhenAsked(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ mgr, client := newSessionManagerExecTestHarness(t)
+
+ _, err := mgr.ExecShellCommandWithOptions(ctx, "sess-1", "echo hi", ShellExecOptions{})
+ require.NoError(t, err)
+ last := lastExecRequest(t, client)
+ require.Equal(t, DefaultSandboxExecUser, last.User,
+ "ordinary shell_exec must stay on the non-root sandbox account")
+
+ _, err = mgr.ExecShellCommandWithOptions(ctx, "sess-1", "echo hi", ShellExecOptions{
+ AsRoot: true,
+ AllowSkillsRoot: true,
+ WorkDir: SkillDirFor("sk-1"),
+ })
+ require.NoError(t, err)
+ last = lastExecRequest(t, client)
+ require.Equal(t, "root", last.User)
+ require.Equal(t, SkillDirFor("sk-1"), last.WorkDir)
+}
+
+func TestExecShellCommandKeepsOrdinaryRemoteRequest(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ mgr, client := newSessionManagerExecTestHarness(t)
+ env := map[string]string{"A": "B"}
+
+ _, err := mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "/workspace/project", time.Second, env)
+ require.NoError(t, err)
+
+ last := lastExecRequest(t, client)
+ require.Equal(t, RemoteExecRequest{
+ Command: "echo hi",
+ Shell: true,
+ Env: env,
+ WorkDir: "/workspace/project",
+ User: DefaultSandboxExecUser,
+ Timeout: time.Second,
+ }, last)
+}
+
+func TestExecShellCommandEmptyWorkDirLeavesRemoteRequestUnset(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ mgr, client := newSessionManagerExecTestHarness(t)
+
+ _, err := mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "", time.Second, nil)
+ require.NoError(t, err)
+
+ last := lastExecRequest(t, client)
+ require.Empty(t, last.WorkDir)
+ require.Equal(t, DefaultSandboxExecUser, last.User)
+}
+
+func TestExecShellCommandRejectsInvalidWorkDir(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ mgr, _ := newSessionManagerExecTestHarness(t)
+
+ _, err := mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "/etc", time.Second, nil)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "outside allowed roots")
+ require.Contains(t, err.Error(), SessionWorkspaceRoot)
+}
+
+func newSessionManagerExecTestHarness(t *testing.T) (*SessionBoundManager, *fakeRemoteClient) {
+ t.Helper()
+
+ client := newFakeRemoteClient(SandboxTypeCube)
+ cfg := DefaultConfig()
+ cfg.CubeTemplate = "tpl-test"
+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: &fakeSessionExistenceChecker{exists: true},
+ SkipHealthProbe: true,
+ })
+ require.NoError(t, err)
+ return mgr, client
+}
+
+func lastExecRequest(t *testing.T, client *fakeRemoteClient) RemoteExecRequest {
+ t.Helper()
+
+ client.mu.Lock()
+ defer client.mu.Unlock()
+ require.NotEmpty(t, client.execRequests)
+ return client.execRequests[len(client.execRequests)-1]
+}
diff --git a/internal/sandbox/skill_image.go b/internal/sandbox/skill_image.go
new file mode 100644
index 000000000..ff77c4dca
--- /dev/null
+++ b/internal/sandbox/skill_image.go
@@ -0,0 +1,39 @@
+package sandbox
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// SkillImageFingerprint identifies the provider account a skill snapshot lives
+// in. Snapshots are not visible across accounts, so when credentials change the
+// stored snapshot silently stops existing for us - this fingerprint is how we
+// notice and fall back instead of booting sessions against a dead image ID.
+func SkillImageFingerprint(provider, apiKey, apiURL string) string {
+ sum := sha256.Sum256([]byte(strings.Join([]string{
+ strings.TrimSpace(provider),
+ strings.TrimSpace(apiKey),
+ strings.TrimSpace(apiURL),
+ }, "\n")))
+ return hex.EncodeToString(sum[:])
+}
+
+// skillImageTemplateOverride returns the snapshot ID that should replace the
+// base template, or "" when the base template must be kept.
+func skillImageTemplateOverride(
+ image *types.SkillImageConfig, provider, apiKey, apiURL string,
+) string {
+ if image == nil || strings.TrimSpace(image.SnapshotID) == "" {
+ return ""
+ }
+ if image.OwnerFingerprint == "" {
+ return ""
+ }
+ if image.OwnerFingerprint != SkillImageFingerprint(provider, apiKey, apiURL) {
+ return ""
+ }
+ return strings.TrimSpace(image.SnapshotID)
+}
diff --git a/internal/sandbox/skill_paths.go b/internal/sandbox/skill_paths.go
new file mode 100644
index 000000000..f29278a88
--- /dev/null
+++ b/internal/sandbox/skill_paths.go
@@ -0,0 +1,74 @@
+package sandbox
+
+import (
+ "fmt"
+ "path"
+ "strings"
+)
+
+const (
+ // SkillsImageRoot is where installed skills live inside the snapshot image.
+ // It is outside /workspace on purpose: /workspace is per-session scratch
+ // and is wiped before every snapshot.
+ SkillsImageRoot = "/opt/weknora/tenant/skills"
+
+ // SkillsManifestPath lists what the image claims to contain. It is a
+ // troubleshooting aid, never the source of truth for execution.
+ SkillsManifestPath = SkillsImageRoot + "/.manifest.json"
+)
+
+const skillShellArgv0 = "weknora-skill"
+
+// SkillDirFor returns the image directory of a skill. The key is the skill
+// name from SKILL.md: that is what the installer writes, and what the agent
+// is told to execute. The database id stays a row key and is not part of
+// the path.
+func SkillDirFor(skillName string) string {
+ return path.Join(SkillsImageRoot, skillName)
+}
+
+// SkillDirForImageScript returns the owning skill directory for an image script.
+// It anchors on SkillsImageRoot so nested script layouts still use the venv that
+// was installed beside the skill, not a shallower scripts directory.
+func SkillDirForImageScript(scriptPath string) (string, bool) {
+ cleanRoot := path.Clean(SkillsImageRoot)
+ cleanScript := path.Clean(scriptPath)
+ prefix := cleanRoot + "/"
+ if !strings.HasPrefix(cleanScript, prefix) {
+ return "", false
+ }
+
+ rest := strings.TrimPrefix(cleanScript, prefix)
+ parts := strings.SplitN(rest, "/", 2)
+ if len(parts) != 2 || parts[0] == "" {
+ return "", false
+ }
+ return path.Join(cleanRoot, parts[0]), true
+}
+
+// SkillInterpreterCommand picks how to run one script of a skill.
+//
+// The interpreter is derived per script rather than stored per skill: one skill
+// may ship both .py and .js entry points, so a single stored "interpreter"
+// column could never be right for all of them.
+//
+// For Python we prefer the skill's own venv. The choice is made inside the
+// sandbox with a shell conditional instead of an extra round trip to stat the
+// path, because the extra Exec would double the latency of every skill call.
+func SkillInterpreterCommand(skillDir, scriptPath string) (string, []string) {
+ switch {
+ case strings.HasSuffix(scriptPath, ".py"):
+ venvPython := path.Join(skillDir, ".venv", "bin", "python")
+ script := shellQuote(scriptPath)
+ return "/bin/sh", []string{"-c", fmt.Sprintf(
+ `if [ -x %s ]; then exec %s %s "$@"; else exec python3 %s "$@"; fi`,
+ shellQuote(venvPython), shellQuote(venvPython), script, script,
+ ), skillShellArgv0}
+ case strings.HasSuffix(scriptPath, ".js"), strings.HasSuffix(scriptPath, ".mjs"):
+ return "node", []string{scriptPath}
+ case strings.HasSuffix(scriptPath, ".sh"):
+ return "/bin/sh", []string{scriptPath}
+ default:
+ return "/bin/sh", []string{scriptPath}
+ }
+}
diff --git a/internal/sandbox/skill_paths_test.go b/internal/sandbox/skill_paths_test.go
new file mode 100644
index 000000000..dcb58b911
--- /dev/null
+++ b/internal/sandbox/skill_paths_test.go
@@ -0,0 +1,87 @@
+package sandbox
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSkillDirFor(t *testing.T) {
+ require.Equal(t, "/opt/weknora/tenant/skills/sk-1", SkillDirFor("sk-1"))
+}
+
+func TestSkillDirForImageScript(t *testing.T) {
+ t.Run("flat script path resolves to skill directory", func(t *testing.T) {
+ skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/sk-1/run.py")
+ require.True(t, ok)
+ require.Equal(t, SkillsImageRoot+"/sk-1", skillDir)
+ })
+
+ t.Run("nested script path resolves to skill directory", func(t *testing.T) {
+ skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/sk-1/scripts/tools/run.py")
+ require.True(t, ok)
+ require.Equal(t, SkillsImageRoot+"/sk-1", skillDir)
+ })
+
+ t.Run("path outside image skill root is rejected", func(t *testing.T) {
+ skillDir, ok := SkillDirForImageScript("/workspace/run.py")
+ require.False(t, ok)
+ require.Empty(t, skillDir)
+ })
+}
+
+func TestSkillInterpreterCommand(t *testing.T) {
+ dir := SkillDirFor("sk-1")
+
+ t.Run("python prefers the skill's own venv", func(t *testing.T) {
+ cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.py")
+ require.Equal(t, "/bin/sh", cmd)
+ require.Len(t, args, 3)
+ require.Equal(t, "-c", args[0])
+ require.Contains(t, args[1], dir+"/.venv/bin/python",
+ "a skill with its own venv must not be run by the system interpreter")
+ require.Contains(t, args[1], "else", "there must be a fallback when the venv is absent")
+ require.Equal(t, "weknora-skill", args[2])
+ })
+
+ t.Run("javascript uses node", func(t *testing.T) {
+ cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.js")
+ require.Equal(t, "node", cmd)
+ require.Equal(t, []string{dir + "/scripts/run.js"}, args)
+ })
+
+ t.Run("shell scripts run with sh", func(t *testing.T) {
+ cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.sh")
+ require.Equal(t, "/bin/sh", cmd)
+ require.Equal(t, []string{dir + "/scripts/run.sh"}, args)
+ })
+
+ t.Run("unknown extension falls back to sh", func(t *testing.T) {
+ cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run")
+ require.Equal(t, "/bin/sh", cmd)
+ require.Equal(t, []string{dir + "/scripts/run"}, args)
+ })
+}
+
+func TestSkillInterpreterCommandPythonForwardsAllCallerArgs(t *testing.T) {
+ if _, err := os.Stat("/bin/sh"); err != nil {
+ t.Skipf("shell is not available: %v", err)
+ }
+
+ dir := t.TempDir()
+ scriptPath := filepath.Join(dir, "run.py")
+ require.NoError(t, os.WriteFile(scriptPath, []byte(`import sys
+print("\n".join(sys.argv[1:]))
+`), 0o644))
+
+ cmd, baseArgs := SkillInterpreterCommand(dir, scriptPath)
+ require.Equal(t, "/bin/sh", cmd)
+
+ args := append(append([]string{}, baseArgs...), "--first", "value", "--third")
+ output, err := exec.Command(cmd, args...).CombinedOutput()
+ require.NoError(t, err, string(output))
+ require.Equal(t, "--first\nvalue\n--third\n", string(output))
+}
diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.go
index 7ea49a287..2772b61c5 100644
--- a/internal/sandbox/tenant_config.go
+++ b/internal/sandbox/tenant_config.go
@@ -120,6 +120,24 @@ func ResolveEffectiveConfig(
case SandboxTypeDocker:
applyDockerRuntimeDefaults(&effective)
}
+ // A skill snapshot is just a template ID on both providers, so overriding
+ // the template field here is the entire session-side change. Everything
+ // downstream keeps reading CubeTemplate / E2BTemplate and needs no knowledge
+ // of skills.
+ switch effective.Type {
+ case SandboxTypeCube:
+ if snapshot := skillImageTemplateOverride(
+ tenantCfg.SkillImage, "cube", effective.CubeAPIKey, effective.CubeAPIURL,
+ ); snapshot != "" {
+ effective.CubeTemplate = snapshot
+ }
+ case SandboxTypeE2B:
+ if snapshot := skillImageTemplateOverride(
+ tenantCfg.SkillImage, "e2b", effective.E2BAPIKey, effective.E2BAPIURL,
+ ); snapshot != "" {
+ effective.E2BTemplate = snapshot
+ }
+ }
// Deliberately after the runtime defaults: TTLs and HTTP timeouts have
// built-in fallbacks, endpoints and credentials do not.
if err := RequireCompleteConfig(&effective); err != nil {
diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.go
index d28eec7a1..83adb4570 100644
--- a/internal/sandbox/tenant_config_test.go
+++ b/internal/sandbox/tenant_config_test.go
@@ -274,3 +274,103 @@ func TestEffectiveTemplateIDPerProvider(t *testing.T) {
require.Empty(t, EffectiveTemplateID(&Config{Type: SandboxTypeLocal}))
require.Empty(t, EffectiveTemplateID(nil))
}
+
+func TestResolveEffectiveConfigUsesSkillSnapshotAsTemplate(t *testing.T) {
+ global := DefaultConfig()
+
+ base := &types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIURL: "https://203.0.113.10", ProxyURL: "https://203.0.113.11",
+ SandboxDomain: "cube.example.com", APIKey: "key-1", TemplateID: "tpl-base",
+ },
+ }
+ fp := SkillImageFingerprint("cube", "key-1", "https://203.0.113.10")
+
+ t.Run("usable snapshot overrides the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: fp}
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "snap-1", eff.CubeTemplate)
+ })
+
+ t.Run("fingerprint mismatch falls back to the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{
+ SnapshotID: "snap-1", OwnerFingerprint: "fingerprint-of-another-account",
+ }
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "tpl-base", eff.CubeTemplate,
+ "a snapshot from another account is invisible; the session must still boot")
+ })
+
+ t.Run("empty snapshot keeps the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{OwnerFingerprint: fp}
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "tpl-base", eff.CubeTemplate)
+ })
+}
+
+func TestResolveEffectiveConfigUsesSkillSnapshotAsE2BTemplate(t *testing.T) {
+ global := DefaultConfig()
+
+ base := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIURL: "https://203.0.113.20", SandboxDomain: "e2b.example.com",
+ APIKey: "key-1", TemplateID: "tpl-base",
+ },
+ }
+ fp := SkillImageFingerprint("e2b", "key-1", "https://203.0.113.20")
+ cubeFp := SkillImageFingerprint("cube", "key-1", "https://203.0.113.20")
+
+ t.Run("usable snapshot overrides the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: fp}
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "snap-1", eff.E2BTemplate)
+ })
+
+ t.Run("fingerprint mismatch falls back to the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{
+ SnapshotID: "snap-1", OwnerFingerprint: cubeFp,
+ }
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "tpl-base", eff.E2BTemplate,
+ "a snapshot whose fingerprint was computed for cube must not override e2b; the session must still boot")
+ })
+
+ t.Run("empty snapshot keeps the base template", func(t *testing.T) {
+ cfg := *base
+ cfg.SkillImage = &types.SkillImageConfig{OwnerFingerprint: fp}
+
+ eff, err := ResolveEffectiveConfig(&cfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, "tpl-base", eff.E2BTemplate)
+ })
+}
+
+func TestSkillImageFingerprintIsStableAndDiscriminating(t *testing.T) {
+ a := SkillImageFingerprint("cube", "key-1", "https://a.example.com")
+ require.Equal(t, a, SkillImageFingerprint("cube", "key-1", "https://a.example.com"))
+ require.NotEqual(t, a, SkillImageFingerprint("cube", "key-2", "https://a.example.com"))
+ require.NotEqual(t, a, SkillImageFingerprint("e2b", "key-1", "https://a.example.com"))
+}
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index a312bacf1..ce0251bf4 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -654,6 +654,10 @@ type TenantSandboxConfig struct {
// etc.).
VolumeMount *VolumeMountConfig `json:"volume_mount,omitempty"`
+ // SkillImage points at the snapshot that carries this config's installed
+ // skills. Empty means "use the base template".
+ SkillImage *SkillImageConfig `json:"skill_image,omitempty"`
+
// ── 后端专属配置(同一时刻只有一个生效,由 SandboxType 决定)───
Cube *CubeSandboxConfig `json:"cube,omitempty"`
@@ -787,6 +791,28 @@ type VolumeMountConfig struct {
VolumeOwnerFingerprint string `json:"volume_owner_fingerprint,omitempty"`
}
+// SkillImageConfig is the pointer to the snapshot that carries the skills
+// installed on this sandbox config. Snapshot IDs double as template IDs, so
+// nothing else is needed to boot sessions from it.
+//
+// It holds no secrets, so it is not encrypted by TenantSandboxConfig.Value.
+type SkillImageConfig struct {
+ // SnapshotID is the currently effective snapshot; empty = base template.
+ SnapshotID string `json:"snapshot_id,omitempty"`
+ // Generation increments on every successful install/remove, for naming
+ // and troubleshooting.
+ Generation int `json:"generation,omitempty"`
+ // BuiltAt records when this generation was produced.
+ BuiltAt time.Time `json:"built_at,omitempty"`
+ // BaseTemplateID is the template this chain was originally built from;
+ // the rebuild path starts over from it.
+ BaseTemplateID string `json:"base_template_id,omitempty"`
+ // OwnerFingerprint identifies the provider account that owns the snapshot.
+ // Snapshots are invisible across accounts, so a mismatch means "fall back
+ // to the base template" rather than "fail".
+ OwnerFingerprint string `json:"owner_fingerprint,omitempty"`
+}
+
// Value implements the driver.Valuer interface. Every secret-bearing field
// (Cube.APIKey, E2B.APIKey and all EnvVars values) is encrypted before
// persisting. EnvVars are included because environment variables routinely
diff --git a/internal/types/tenant_skill.go b/internal/types/tenant_skill.go
new file mode 100644
index 000000000..6c493391a
--- /dev/null
+++ b/internal/types/tenant_skill.go
@@ -0,0 +1,103 @@
+package types
+
+import (
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// Skill install lifecycle. removing is separate from installing so the reaper
+// can tell "never finished installing" from "never finished being removed".
+const (
+ SkillStatusInstalling = "installing"
+ SkillStatusReady = "ready"
+ SkillStatusFailed = "failed"
+ SkillStatusRemoving = "removing"
+)
+
+// Snapshot ledger states. deleted is written only after a real provider-side
+// delete, which today happens only when the whole sandbox config is removed.
+const (
+ SkillSnapshotStateBuilding = "building"
+ SkillSnapshotStateActive = "active"
+ SkillSnapshotStateSuperseded = "superseded"
+ SkillSnapshotStateDeleted = "deleted"
+)
+
+const (
+ SkillSnapshotTriggerInstall = "install"
+ SkillSnapshotTriggerRemove = "remove"
+ SkillSnapshotTriggerRebuild = "rebuild"
+)
+
+// TenantSkillEntity is one skill installed onto one sandbox config.
+//
+// There is deliberately no entry_script / interpreter / smoke_command column:
+// a skill may ship several executables across languages, so none of those is a
+// single value. The interpreter is derived from the on-image path convention at
+// execution time instead (see skills.Manager).
+type TenantSkillEntity struct {
+ // ID is the row key. It is not the directory name inside the image.
+ ID string `gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64
+ SandboxConfigID string `gorm:"type:varchar(36)"`
+
+ // Name is the SKILL.md frontmatter name and the directory under
+ // /opt/weknora/tenant/skills. Same-name reinstalls keep this value so the
+ // image path stays stable.
+ Name string `gorm:"type:varchar(255);not null"`
+ Version string `gorm:"type:varchar(64)"`
+ Description string `gorm:"type:text"`
+ // Instructions is the SKILL.md body (level 2 disclosure).
+ Instructions string `gorm:"type:text"`
+
+ // BundleRef locates the uploaded archive in the tenant's file service.
+ BundleRef string `gorm:"type:varchar(1024)"`
+ BundleSHA256 string `gorm:"type:varchar(64)"`
+
+ // Enabled controls visibility to the agent only. The files stay in the
+ // image either way; removal is a separate flow that rebuilds the snapshot.
+ Enabled bool `gorm:"default:true"`
+
+ // InstalledSnapshotID is the snapshot produced by this skill's install,
+ // kept for audit and chain troubleshooting.
+ InstalledSnapshotID string `gorm:"type:varchar(255)"`
+
+ Status string `gorm:"type:varchar(32);not null"`
+ Error string `gorm:"type:text"`
+ // InstallingSince drives the stuck-run reaper for both install and remove.
+ InstallingSince *time.Time
+
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ DeletedAt gorm.DeletedAt
+}
+
+// TableName pins the table so GORM's pluralizer cannot drift.
+func (e *TenantSkillEntity) TableName() string { return "tenant_skills" }
+
+// TenantSkillSnapshotEntity is the image-chain ledger. It exists because
+// snapshots are billable provider resources whose IDs we hand out: we must be
+// able to say which generation came from which parent, and never leave a
+// snapshot nobody knows about.
+type TenantSkillSnapshotEntity struct {
+ // ID is the install ID; it also seeds the snapshot name.
+ ID string `gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `gorm:"index"`
+ SandboxConfigID string `gorm:"type:varchar(36);index"`
+ SkillID string `gorm:"type:varchar(36);index"`
+
+ SnapshotID string `gorm:"type:varchar(255)"`
+ ParentSnapshotID string `gorm:"type:varchar(255)"`
+ Generation int
+
+ Trigger string `gorm:"type:varchar(16)"`
+ State string `gorm:"type:varchar(16);index"`
+
+ SupersededAt *time.Time
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+// TableName pins the table so GORM's pluralizer cannot drift.
+func (e *TenantSkillSnapshotEntity) TableName() string { return "tenant_skill_snapshots" }
diff --git a/migrations/versioned/000086_tenant_skills.down.sql b/migrations/versioned/000086_tenant_skills.down.sql
new file mode 100644
index 000000000..e9d23eca3
--- /dev/null
+++ b/migrations/versioned/000086_tenant_skills.down.sql
@@ -0,0 +1,4 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000086 down] Dropping tenant skill tables'; END $$;
+
+DROP TABLE IF EXISTS tenant_skill_snapshots;
+DROP TABLE IF EXISTS tenant_skills;
diff --git a/migrations/versioned/000086_tenant_skills.up.sql b/migrations/versioned/000086_tenant_skills.up.sql
new file mode 100644
index 000000000..ad3028bfe
--- /dev/null
+++ b/migrations/versioned/000086_tenant_skills.up.sql
@@ -0,0 +1,57 @@
+-- Description: Skills installed onto a sandbox config, plus the snapshot chain
+-- ledger. Skills live inside the config's snapshot image; these tables are the
+-- metadata projection and the audit trail for the provider-side snapshots.
+DO $$ BEGIN RAISE NOTICE '[Migration 000086] Creating tenant_skills'; END $$;
+
+CREATE TABLE IF NOT EXISTS tenant_skills (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ sandbox_config_id VARCHAR(36) NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ version VARCHAR(64),
+ description TEXT,
+ instructions TEXT,
+ bundle_ref VARCHAR(1024),
+ bundle_sha256 VARCHAR(64),
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ installed_snapshot_id VARCHAR(255),
+ status VARCHAR(32) NOT NULL,
+ error TEXT,
+ installing_since TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ deleted_at TIMESTAMPTZ
+);
+
+COMMENT ON COLUMN tenant_skills.name IS 'Also the directory name inside the image: /opt/weknora/tenant/skills/<name>';
+COMMENT ON COLUMN tenant_skills.enabled IS 'Visibility to the agent only; files stay in the image until the skill is removed';
+
+-- The unique index doubles as the "list skills of a config" index: its leftmost
+-- prefix is sandbox_config_id. status/enabled are low-cardinality and are
+-- filtered in memory (a config holds tens of skills, not millions).
+CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skills_config_name
+ ON tenant_skills (sandbox_config_id, name) WHERE deleted_at IS NULL;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000086] Creating tenant_skill_snapshots'; END $$;
+
+CREATE TABLE IF NOT EXISTS tenant_skill_snapshots (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ sandbox_config_id VARCHAR(36) NOT NULL,
+ skill_id VARCHAR(36),
+ snapshot_id VARCHAR(255),
+ parent_snapshot_id VARCHAR(255),
+ generation INTEGER NOT NULL DEFAULT 0,
+ trigger VARCHAR(16) NOT NULL,
+ state VARCHAR(16) NOT NULL,
+ superseded_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+COMMENT ON TABLE tenant_skill_snapshots IS 'Image chain ledger. Old snapshots are kept (state=superseded), never deleted on switch, so the recorded IDs stay resolvable.';
+
+CREATE INDEX IF NOT EXISTS idx_tenant_skill_snapshots_config
+ ON tenant_skill_snapshots (sandbox_config_id);
+CREATE INDEX IF NOT EXISTS idx_tenant_skill_snapshots_state
+ ON tenant_skill_snapshots (state);