Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: unify error handling (#3328)
Kyle Mendell2d305b0d98a6
diff --git a/.github/.golangci.yml b/.github/.golangci.ymlindex 18ba7272f..e3b5689b6 100644--- a/.github/.golangci.yml+++ b/.github/.golangci.yml@@ -88,9 +88,17 @@ linters:- whitespace- zerologlintsettings:+ forbidigo:+ forbid:+ - pattern: ^errors\.(Wrap|Wrapf|WithStack)$+ msg: use WrapIf, WrapIff, or WithStackIf so an existing stack is preservedgomoddirectives:# replace directives (=> ../cli, => ../types). Allow them.replace-local: true+ importas:+ alias:+ - pkg: errors+ alias: stderrorsexclusions:generated: laxpresets:diff --git a/backend/api/buildables.go b/backend/api/buildables.goindex 30b19d442..773a4b904 100644--- a/backend/api/buildables.go+++ b/backend/api/buildables.go@@ -3,12 +3,12 @@package apiimport (- "errors""net/http""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/buildables"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"@@ -70,23 +70,20 @@ func registerAutoLoginRoutes(apiGroup *echo.Group, authService *services.AuthSerif err != nil {switch {case errors.Is(err, services.ErrInvalidCredentials):- return c.JSON(http.StatusUnauthorized, base.ErrorResponse{Error: (&common.InvalidCredentialsError{}).Error()})+ return c.JSON(http.StatusUnauthorized, base.ErrorResponse{Error: "Invalid username or password"})case errors.Is(err, services.ErrLocalAuthDisabled):- return c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: (&common.LocalAuthDisabledError{}).Error()})+ return c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: "Local authentication is disabled"})default:- return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.AuthFailedError{Err: err}).Error()})+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "Authentication failed"})}}var userResp user.Userif mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {- return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.UserMappingError{Err: mapErr}).Error()})+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "Failed to map user"})}- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())- if maxAge < 0 {- maxAge = 0- }+ maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)maxAge += 60c.Response().Header().Set("Set-Cookie", cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromRequest(c.Request())))diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.goindex 5b93319b3..711b377dc 100644--- a/backend/api/handlers/activities.go+++ b/backend/api/handlers/activities.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "errors""fmt""hash/fnv""io"@@ -12,6 +11,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/models"diff --git a/backend/api/handlers/apikeys.go b/backend/api/handlers/apikeys.goindex 979dc8626..88b82e633 100644--- a/backend/api/handlers/apikeys.go+++ b/backend/api/handlers/apikeys.go@@ -2,12 +2,12 @@ package handlersimport ("context"- "errors""net/http"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/types/v2/apikey"@@ -181,7 +181,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInputapiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.ApiKeyListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())}return &ListApiKeysOutput{@@ -207,7 +207,7 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInpif errors.Is(err, services.ErrApiKeyPermissionEscalation) {return nil, huma.Error403Forbidden(err.Error())}- return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to create API key")}return &CreateApiKeyOutput{@@ -222,7 +222,7 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInpfunc (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*GetApiKeyOutput, error) {apiKey, err := h.apiKeyService.GetApiKey(ctx, input.ID)if err != nil {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}return &GetApiKeyOutput{@@ -243,7 +243,7 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInpapiKey, err := h.apiKeyService.UpdateApiKey(ctx, callerPerms, input.ID, input.Body)if err != nil {if errors.Is(err, services.ErrApiKeyNotFound) {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}if errors.Is(err, services.ErrApiKeyProtected) {return nil, huma.Error403Forbidden("static API keys cannot be updated")@@ -254,7 +254,7 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInpif errors.Is(err, services.ErrApiKeyPersonalNoGrants) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError((&common.ApiKeyUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to update API key")}return &UpdateApiKeyOutput{@@ -269,12 +269,12 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInpfunc (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {if errors.Is(err, services.ErrApiKeyNotFound) {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}if errors.Is(err, services.ErrApiKeyProtected) {return nil, huma.Error403Forbidden("static API keys cannot be deleted")}- return nil, huma.Error500InternalServerError((&common.ApiKeyDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to delete API key")}return &DeleteApiKeyOutput{@@ -296,7 +296,7 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*Likeys, err := h.apiKeyService.ListApiKeysByUser(ctx, user.ID)if err != nil {- return nil, huma.Error500InternalServerError((&common.ApiKeyListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())}return &ListMyApiKeysOutput{@@ -324,7 +324,7 @@ func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKeapiKey, err := h.apiKeyService.CreatePersonalApiKey(ctx, user.ID, input.Body)if err != nil {- return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to create API key")}return &CreateApiKeyOutput{@@ -352,20 +352,20 @@ func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyIexisting, err := h.apiKeyService.GetApiKey(ctx, input.ID)if err != nil {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}if existing.UserID == nil || *existing.UserID != user.ID {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {if errors.Is(err, services.ErrApiKeyNotFound) {- return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())+ return nil, huma.Error404NotFound("API key not found")}if errors.Is(err, services.ErrApiKeyProtected) {return nil, huma.Error403Forbidden("this API key cannot be deleted")}- return nil, huma.Error500InternalServerError((&common.ApiKeyDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to delete API key")}return &DeleteApiKeyOutput{diff --git a/backend/api/handlers/appimages.go b/backend/api/handlers/appimages.goindex a28075023..f251c6d6b 100644--- a/backend/api/handlers/appimages.go+++ b/backend/api/handlers/appimages.go@@ -6,8 +6,8 @@ import ("path/filepath""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services")@@ -148,7 +148,7 @@ func (h *AppImagesHandler) getImageByFilenameInternal(filename string) (*GetAppIfunc (h *AppImagesHandler) getImageWithColor(name string, colorOverride string) (*GetAppImageOutput, error) {imageData, mimeType, err := h.appImagesService.GetImageWithColor(name, colorOverride)if err != nil {- return nil, huma.Error500InternalServerError((&common.ImageRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve image").Error())}// Always disable logo caching so theme/logo updates are reflected immediately.diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.goindex 1c3bb4d70..793157b5b 100644--- a/backend/api/handlers/auth.go+++ b/backend/api/handlers/auth.go@@ -3,7 +3,6 @@ package handlersimport ("bytes""context"- "errors""fmt"stdimage "image""image/jpeg"@@ -14,6 +13,8 @@ import ("net/http""time"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -218,27 +219,27 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutput, error) {localAuthEnabled, err := h.authService.IsLocalAuthEnabled(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.AuthSettingsCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to check authentication settings")}if !localAuthEnabled {- return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())+ return nil, huma.Error400BadRequest("Local authentication is disabled")}userModel, tokenPair, err := h.authService.Login(ctx, input.Body.Username, input.Body.Password, sessionMetaFromContextInternal(ctx, input.UserAgent))if err != nil {switch {case errors.Is(err, services.ErrInvalidCredentials):- return nil, huma.Error401Unauthorized((&common.InvalidCredentialsError{}).Error())+ return nil, huma.Error401Unauthorized("Invalid username or password")case errors.Is(err, services.ErrLocalAuthDisabled):- return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())+ return nil, huma.Error400BadRequest("Local authentication is disabled")default:- return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Authentication failed")}}userResp, err := h.userService.ToUserResponseDto(ctx, *userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)@@ -288,17 +289,17 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpufunc (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {userID, exists := humamw.GetUserIDFromContext(ctx)if !exists {- return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())+ return nil, huma.Error401Unauthorized("Not authenticated")}userModel, err := h.userService.GetUser(ctx, userID)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to get user information")}out, err := h.userService.ToUserResponseDto(ctx, *userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &GetCurrentUserOutput{@@ -314,10 +315,10 @@ func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInputtokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken, sessionMetaFromContextInternal(ctx, input.UserAgent))if err != nil {switch {- case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken), common.IsTokenValidationError(err), common.IsSessionRevokedError(err), errors.Is(err, services.ErrTokenVersionMismatch):- return nil, huma.Error401Unauthorized((&common.InvalidTokenError{}).Error())+ case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken), errors.Is(err, common.ErrTokenValidation), errors.Is(err, common.ErrSessionRevoked), errors.Is(err, services.ErrTokenVersionMismatch):+ return nil, huma.Error401Unauthorized("Invalid or expired refresh token")default:- return nil, huma.Error500InternalServerError((&common.TokenRefreshError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to refresh token")}}@@ -352,7 +353,7 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI}if input.Body.CurrentPassword == "" {- return nil, huma.Error400BadRequest((&common.PasswordRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Current password is required")}currentSessionID, _ := humamw.GetCurrentSessionIDFromContext(ctx)@@ -360,9 +361,9 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordIif err != nil {switch {case errors.Is(err, services.ErrInvalidCredentials):- return nil, huma.Error401Unauthorized((&common.IncorrectPasswordError{}).Error())+ return nil, huma.Error401Unauthorized("Current password is incorrect")default:- return nil, huma.Error500InternalServerError((&common.PasswordChangeError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to change password")}}@@ -415,7 +416,7 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfiluserModel, err := h.userService.GetUser(ctx, currentUser.ID)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to get user information")}if input.Body.DisplayName != nil {@@ -440,12 +441,12 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfilupdated, err := h.userService.UpdateUser(ctx, userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to update user")}out, err := h.userService.ToUserResponseDto(ctx, *updated)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &UpdateMyProfileOutput{@@ -508,12 +509,12 @@ func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarI// Reload user so the response reflects the new AvatarURLupdatedUser, err := h.userService.GetUser(ctx, currentUser.ID)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to get user information")}out, err := h.userService.ToUserResponseDto(ctx, *updatedUser)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &UploadMyAvatarOutput{@@ -550,12 +551,12 @@ func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*DelupdatedUser, err := h.userService.GetUser(ctx, currentUser.ID)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to get user information")}out, err := h.userService.ToUserResponseDto(ctx, *updatedUser)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &DeleteMyAvatarOutput{diff --git a/backend/api/handlers/container_registries.go b/backend/api/handlers/container_registries.goindex 7cd111a94..0ee3fc818 100644--- a/backend/api/handlers/container_registries.go+++ b/backend/api/handlers/container_registries.go@@ -5,9 +5,9 @@ import ("log/slog""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -202,7 +202,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Liregistries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.RegistryListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list registries").Error())}return &ListContainerRegistriesOutput{@@ -218,7 +218,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Lifunc (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *struct{}) (*GetContainerRegistryPullUsageOutput, error) {usage, err := h.registryService.GetRegistryPullUsage(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.RegistryRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve registry").Error())}return &GetContainerRegistryPullUsageOutput{@@ -234,14 +234,14 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Crreg, err := h.registryService.CreateRegistry(ctx, input.Body)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryCreationError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create registry").Error())}h.triggerRemoteRegistrySync(ctx, "registry creation")out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}return &CreateContainerRegistryOutput{@@ -257,12 +257,12 @@ func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetCoreg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())}out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}return &GetContainerRegistryOutput{@@ -278,14 +278,14 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Upreg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryUpdateError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update registry").Error())}h.triggerRemoteRegistrySync(ctx, "registry update")out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}return &UpdateContainerRegistryOutput{@@ -300,7 +300,7 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Upfunc (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*DeleteContainerRegistryOutput, error) {if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryDeletionError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete registry").Error())}h.triggerRemoteRegistrySync(ctx, "registry deletion")@@ -320,13 +320,13 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Testreg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())}// ECR registries use a different auth flow: generate a temporary token via AWS API.if reg.RegistryType == "ecr" {if err := h.registryService.TestECRRegistry(ctx, reg); err != nil {- return nil, huma.Error400BadRequest((&common.RegistryTestError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Registry test failed").Error())}return &TestContainerRegistryOutput{Body: base.ApiResponse[base.MessageResponse]{@@ -340,11 +340,11 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestdecryptedToken, err := crypto.Decrypt(reg.Token)if err != nil {- return nil, huma.Error500InternalServerError((&common.TokenDecryptionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to decrypt token").Error())}if err := h.registryService.TestRegistry(ctx, reg.URL, reg.Username, decryptedToken); err != nil {- return nil, huma.Error400BadRequest((&common.RegistryTestError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Registry test failed").Error())}msg := "Authentication succeeded"@@ -366,7 +366,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Testfunc (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*SyncContainerRegistriesOutput, error) {if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistrySyncError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync registries").Error())}return &SyncContainerRegistriesOutput{diff --git a/backend/api/handlers/containers.go b/backend/api/handlers/containers.goindex ddd585310..9439d6e06 100644--- a/backend/api/handlers/containers.go+++ b/backend/api/handlers/containers.go@@ -9,9 +9,9 @@ import ("net/netip""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -289,7 +289,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContairesult, err := h.containerService.ListContainersPaginated(ctx, params, true, input.IncludeInternal, input.GroupBy)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list containers").Error())}return &ListContainersOutput{@@ -306,7 +306,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContaifunc (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*GetContainerStatusCountsOutput, error) {containers, _, _, _, err := h.dockerService.GetAllContainers(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerStatusCountsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get container counts").Error())}if !input.IncludeInternal {@@ -552,15 +552,15 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateConconfig := buildContainerConfig(input.Body)portBindings := network.PortMap{}if err := applyLegacyPortBindings(input.Body, config, portBindings); err != nil {- return nil, huma.Error400BadRequest((&common.InvalidPortFormatError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid port format").Error())}if err := applyExposedPorts(input.Body.ExposedPorts, config); err != nil {- return nil, huma.Error400BadRequest((&common.InvalidPortFormatError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid port format").Error())}hostConfig := buildHostConfigBase(input.Body, portBindings)if err := applyHostConfigOverrides(input.Body, config, hostConfig, portBindings); err != nil {- return nil, huma.Error400BadRequest((&common.InvalidPortFormatError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid port format").Error())}applyLegacyResourceLimits(input.Body, hostConfig)@@ -568,7 +568,7 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateConcontainerJSON, err := h.containerService.CreateContainer(ctx, config, hostConfig, networkingConfig, input.Body.Name, *user, input.Body.Credentials)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create container").Error())}out := containertypes.Created{@@ -590,7 +590,7 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateConfunc (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*GetContainerOutput, error) {details, err := h.containerService.GetContainerDetails(ctx, input.ContainerID)if err != nil {- return nil, huma.Error404NotFound((&common.ContainerRetrievalError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())}return &GetContainerOutput{@@ -612,7 +612,7 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerAreturn h.containerService.StartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerStartError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start container").Error())},})}@@ -628,7 +628,7 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAcreturn h.containerService.StopContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerStopError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to stop container").Error())},})}@@ -644,7 +644,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containereturn h.containerService.RestartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerRestartError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to restart container").Error())},})}@@ -661,7 +661,7 @@ func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainreturn h.containerService.KillContainer(runtimeCtx, containerID, signal, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerKillError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to kill container").Error())},})}@@ -677,7 +677,7 @@ func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerAreturn h.containerService.PauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerPauseError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to pause container").Error())},})}@@ -693,7 +693,7 @@ func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *Containereturn h.containerService.UnpauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError((&common.ContainerUnpauseError{Err: err}).Error())+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to unpause container").Error())},})}@@ -768,7 +768,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Containif err != nil {activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container redeploy failed", err)- return nil, huma.Error500InternalServerError((&common.ContainerRedeployError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to redeploy container").Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container redeployed", nil)@@ -809,7 +809,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteConactivityID, runtimeCtx := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", models.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes})if err := h.containerService.DeleteContainer(runtimeCtx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", err)- return nil, huma.Error500InternalServerError((&common.ContainerDeleteError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete container").Error())}activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)diff --git a/backend/api/handlers/customize.go b/backend/api/handlers/customize.goindex 6be5c78cb..8ce90a6a7 100644--- a/backend/api/handlers/customize.go+++ b/backend/api/handlers/customize.go@@ -7,7 +7,6 @@ import ("github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/types/v2/category"@@ -78,7 +77,7 @@ func filterCustomizeCategoriesInternal(ps *authz.PermissionSet, categories []cat// Search searches customization options by query.func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInput) (*SearchCustomizeOutput, error) {if strings.TrimSpace(input.Body.Query) == "" {- return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Query parameter is required")}ps, _ := humamw.PermissionsFromContext(ctx)diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.goindex addce85c4..8445ef301 100644--- a/backend/api/handlers/dashboard.go+++ b/backend/api/handlers/dashboard.go@@ -2,11 +2,13 @@ package handlersimport ("context"- "errors"+ stderrors "errors""io""net/http""time"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -161,7 +163,7 @@ func (h *DashboardHandler) runLocalDashboardStreamProducerInternal(ctx context.CDebugAllGood: debugAllGood,})if err == nil && snapshot == nil {- err = &common.DashboardSnapshotUnavailableError{}+ err = common.Classify(common.ErrUnavailable, errors.New("dashboard snapshot not available"))}if err != nil {if ctx.Err() != nil {@@ -332,7 +334,7 @@ func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Contreturn nil, err}if !out.Success {- return nil, &common.DashboardSnapshotUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("dashboard snapshot not available"))}return &out.Data, nil}@@ -381,7 +383,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont}if len(errs) == attempted {- return nil, errors.Join(errs...)+ return nil, stderrors.Join(errs...)}return snapshot, nil}@@ -390,10 +392,10 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont// endpoint is absent (404 on older agents) or speaks an incompatible payload// shape (decode failure) — the cases the legacy composition can recover from.func isDashboardEndpointMissingInternal(err error) bool {- if statusErr, ok := errors.AsType[*remenv.StatusError](err); ok && statusErr.StatusCode == http.StatusNotFound {+ if statusErr, ok := stderrors.AsType[*remenv.StatusError](err); ok && statusErr.StatusCode == http.StatusNotFound {return true}- _, ok := errors.AsType[*remenv.DecodeError](err)+ _, ok := stderrors.AsType[*remenv.DecodeError](err)return ok}@@ -403,9 +405,9 @@ func isDashboardEndpointMissingInternal(err error) bool {// both indicate a version mismatch between manager and agent.func classifyDashboardStreamErrorInternal(err error) (string, string) {if isDashboardEndpointMissingInternal(err) {- return (&common.AgentDashboardUnsupportedError{}).Error(), dashboardtypes.StreamErrorCodeAgentIncompatible+ return "Agent does not provide the dashboard endpoint — the agent is likely running an older Arcane version and should be upgraded", dashboardtypes.StreamErrorCodeAgentIncompatible}- if transportErr, ok := errors.AsType[*remenv.TransportError](err); ok {+ if transportErr, ok := stderrors.AsType[*remenv.TransportError](err); ok {return transportErr.Error(), dashboardtypes.StreamErrorCodeUnreachable}return err.Error(), ""diff --git a/backend/api/handlers/edge_mtls_ca.go b/backend/api/handlers/edge_mtls_ca.goindex 68d7642c6..c20427c32 100644--- a/backend/api/handlers/edge_mtls_ca.go+++ b/backend/api/handlers/edge_mtls_ca.go@@ -3,13 +3,13 @@ package handlersimport ("crypto/x509""encoding/pem"- "errors"- "fmt""math""os""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"typesenvironment "github.com/getarcaneapp/arcane/types/v2/environment"@@ -33,10 +33,10 @@ func generatedEdgeMTLSCAPathInternal(cfg *config.Config) (string, error) {}caPath, err := edge.GeneratedManagerMTLSCAPath(edgeCfg)if err != nil {- return "", fmt.Errorf("resolve edge mTLS CA path: %w", err)+ return "", errors.WrapIf(err, "resolve edge mTLS CA path")}if _, err := os.Stat(caPath); err != nil {- return "", fmt.Errorf("stat edge mTLS CA: %w", err)+ return "", errors.WrapIf(err, "stat edge mTLS CA")}return caPath, nil@@ -61,10 +61,10 @@ func generatedEdgeMTLSClientCertPathInternal(cfg *config.Config, envID string) (certPath, err := edge.GeneratedManagerClientMTLSCertPath(edgeCfg, envID)if err != nil {- return "", fmt.Errorf("resolve generated edge mTLS client certificate path: %w", err)+ return "", errors.WrapIf(err, "resolve generated edge mTLS client certificate path")}if _, err := os.Stat(certPath); err != nil {- return "", fmt.Errorf("stat generated edge mTLS client certificate: %w", err)+ return "", errors.WrapIf(err, "stat generated edge mTLS client certificate")}return certPath, nil@@ -78,7 +78,7 @@ func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID stricertPEM, err := os.ReadFile(certPath)if err != nil {- return nil, fmt.Errorf("read generated edge mTLS client certificate: %w", err)+ return nil, errors.WrapIf(err, "read generated edge mTLS client certificate")}block, _ := pem.Decode(certPEM)@@ -88,7 +88,7 @@ func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID stricert, err := x509.ParseCertificate(block.Bytes)if err != nil {- return nil, fmt.Errorf("parse generated edge mTLS client certificate: %w", err)+ return nil, errors.WrapIf(err, "parse generated edge mTLS client certificate")}expiresAt := cert.NotAfter.UTC()diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.goindex d4f74c83e..6da9d9c17 100644--- a/backend/api/handlers/environments.go+++ b/backend/api/handlers/environments.go@@ -15,9 +15,9 @@ import ("strings""time"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -391,7 +391,7 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEnenvs, paginationResp, err := h.environmentService.ListEnvironmentsPaginated(ctx, params, accessibleEnvIDs)if err != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to fetch environments")}for i := range envs {h.applyEdgeRuntimeStateInternal(&envs[i])@@ -467,7 +467,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Concreated, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)if err != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create environment").Error())}// Generate API key for environment@@ -493,7 +493,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Conout, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to map environment")}h.applyEdgeRuntimeStateInternal(&out)@@ -515,7 +515,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Contextcreated, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)if err != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create environment").Error())}// Sync registries and git repositories in background (intentionally detached from request context)@@ -525,7 +525,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Contextout, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to map environment")}h.applyEdgeRuntimeStateInternal(&out)@@ -543,12 +543,12 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Contextfunc (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvironmentInput) (*GetEnvironmentOutput, error) {env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)if err != nil {- return nil, huma.Error404NotFound((&common.EnvironmentNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Environment not found")}out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](env)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to map environment")}h.applyEdgeRuntimeStateInternal(&out)if env.IsEdge {@@ -580,14 +580,14 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat}updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates, userID, username)if updateErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentUpdateError{Err: updateErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to update environment")}h.triggerPostUpdateTasksInternal(ctx, input.ID, updated, &input.Body)out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](updated)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to map environment")}h.applyEdgeRuntimeStateInternal(&out)@@ -629,7 +629,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat// Re-map with updated environment dataout, mapErr = mapper.MapOne[*models.Environment, environment.Environment](updated)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to map environment")}h.applyEdgeRuntimeStateInternal(&out)@@ -654,7 +654,7 @@ func (h *EnvironmentHandler) applyEdgeRuntimeStateInternal(env *environment.Envi// DeleteEnvironment deletes an environment.func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *DeleteEnvironmentInput) (*DeleteEnvironmentOutput, error) {if input.ID == localDockerEnvironmentID {- return nil, huma.Error400BadRequest((&common.LocalEnvironmentDeletionError{}).Error())+ return nil, huma.Error400BadRequest("Cannot delete local environment")}user, _ := humamw.GetCurrentUserFromContext(ctx)@@ -664,7 +664,7 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Deletusername = new(user.Username)}if err := h.environmentService.DeleteEnvironment(ctx, input.ID, userID, username); err != nil {- return nil, huma.Error500InternalServerError((&common.EnvironmentDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete environment").Error())}return &DeleteEnvironmentOutput{@@ -707,7 +707,7 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn// UpdateHeartbeat updates the heartbeat for an environment.func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateHeartbeatInput) (*UpdateHeartbeatOutput, error) {if err := h.environmentService.UpdateEnvironmentHeartbeat(ctx, input.ID); err != nil {- return nil, huma.Error500InternalServerError((&common.HeartbeatUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to update heartbeat")}return &UpdateHeartbeatOutput{@@ -732,7 +732,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu}if err := h.settingsService.SetStringSetting(ctx, "agentToken", h.cfg.AgentToken); err != nil {- return nil, huma.Error500InternalServerError((&common.AgentTokenPersistenceError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to persist agent token")}return &PairAgentOutput{diff --git a/backend/api/handlers/events.go b/backend/api/handlers/events.goindex 8a88c965e..2a4ca751a 100644--- a/backend/api/handlers/events.go+++ b/backend/api/handlers/events.go@@ -7,9 +7,9 @@ import ("net/http""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -117,7 +117,7 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *services.EventServif _, err := eventService.CreateEvent(c.Request().Context(), input); err != nil {return c.JSON(http.StatusInternalServerError, base.ApiResponse[base.MessageResponse]{Success: false,- Data: base.MessageResponse{Message: (&common.EventCreationError{Err: err}).Error()},+ Data: base.MessageResponse{Message: errors.WithMessage(err, "Failed to create event").Error()},})}@@ -204,7 +204,7 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (events, paginationResp, err := h.eventService.ListEventsPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.EventListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list events").Error())}return &ListEventsOutput{@@ -220,7 +220,7 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*GetEventStatsOutput, error) {counts, err := h.eventService.GetEventSeverityCounts(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.EventStatsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load event statistics").Error())}return &GetEventStatsOutput{@@ -234,7 +234,7 @@ func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput)// GetEventsByEnvironment returns events for a specific environment.func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEventsByEnvironmentInput) (*GetEventsByEnvironmentOutput, error) {if input.EnvironmentID == "" {- return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Environment ID is required")}params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)@@ -248,7 +248,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEveevents, paginationResp, err := h.eventService.GetEventsByEnvironmentPaginated(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.EventListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list events").Error())}return &GetEventsByEnvironmentOutput{@@ -263,11 +263,11 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve// DeleteEvent deletes an event.func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput) (*DeleteEventOutput, error) {if input.EventID == "" {- return nil, huma.Error400BadRequest((&common.EventIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Event ID is required")}if err := h.eventService.DeleteEvent(ctx, input.EventID); err != nil {- return nil, huma.Error500InternalServerError((&common.EventDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete event").Error())}return &DeleteEventOutput{diff --git a/backend/api/handlers/federated.go b/backend/api/handlers/federated.goindex d521db4cb..ae6e404b5 100644--- a/backend/api/handlers/federated.go+++ b/backend/api/handlers/federated.go@@ -4,6 +4,7 @@ import ("context""net/http"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -253,13 +254,13 @@ func writeFederatedTokenExchangeErrorInternal(c echo.Context, err error) error {description := "token exchange rejected"switch {- case common.IsErrorFederatedCredentialInvalidRequest(err):+ case errors.Is(err, common.ErrFederatedCredentialInvalidRequest):code = "invalid_request"description = "invalid token exchange request"- case common.IsErrorFederatedCredentialInvalidGrant(err),- common.IsErrorFederatedCredentialNotFound(err):+ case errors.Is(err, common.ErrFederatedCredentialInvalidGrant),+ errors.Is(err, common.ErrFederatedCredentialNotFound):code = "invalid_grant"- case common.IsErrorFederatedCredentialInvalid(err):+ case errors.Is(err, common.ErrFederatedCredentialInvalid):code = "invalid_request"default:code = "server_error"@@ -274,12 +275,12 @@ func writeFederatedTokenExchangeErrorInternal(c echo.Context, err error) error {func federatedCredentialManagementErrorInternal(err error) error {switch {- case common.IsErrorFederatedCredentialNotFound(err):+ case errors.Is(err, common.ErrFederatedCredentialNotFound):return huma.Error404NotFound("federated credential not found")- case common.IsErrorFederatedCredentialInvalid(err),- common.IsErrorFederatedCredentialInvalidRequest(err):+ case errors.Is(err, common.ErrFederatedCredentialInvalid),+ errors.Is(err, common.ErrFederatedCredentialInvalidRequest):return huma.Error400BadRequest("invalid federated credential")- case common.IsErrorFederatedCredentialPermissionEscalation(err):+ case errors.Is(err, common.ErrFederatedCredentialPermissionEscalation):return huma.Error403Forbidden("permission denied")default:return huma.Error500InternalServerError("federated credential operation failed")diff --git a/backend/api/handlers/git_repositories.go b/backend/api/handlers/git_repositories.goindex dea1f94ae..76b6113b8 100644--- a/backend/api/handlers/git_repositories.go+++ b/backend/api/handlers/git_repositories.go@@ -3,8 +3,8 @@ package handlersimport ("context"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -130,7 +130,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *Listrepositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.GitRepositoryListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list git repositories").Error())}return &ListGitRepositoriesOutput{@@ -149,11 +149,11 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crearepo, err := h.repoService.CreateRepository(ctx, input.Body, actor)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryCreationError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create git repository")}body, mapErr := mapOneAPIResponseInternal[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {- return (&common.GitRepositoryMappingError{Err: err}).Error()+ return "Failed to map git repository"})if mapErr != nil {return nil, mapErr@@ -169,11 +169,11 @@ func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRrepo, err := h.repoService.GetRepositoryByID(ctx, input.ID)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryRetrievalError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve git repository")}body, mapErr := mapOneAPIResponseInternal[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {- return (&common.GitRepositoryMappingError{Err: err}).Error()+ return "Failed to map git repository"})if mapErr != nil {return nil, mapErr@@ -191,11 +191,11 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Updarepo, err := h.repoService.UpdateRepository(ctx, input.ID, input.Body, actor)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryUpdateError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update git repository")}body, mapErr := mapOneAPIResponseInternal[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {- return (&common.GitRepositoryMappingError{Err: err}).Error()+ return "Failed to map git repository"})if mapErr != nil {return nil, mapErr@@ -212,7 +212,7 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Deleif err := h.repoService.DeleteRepository(ctx, input.ID, actor); err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryDeletionError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete git repository")}return &DeleteGitRepositoryOutput{@@ -230,7 +230,7 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGiactor := currentActorInternal(ctx)if err := h.repoService.TestConnection(ctx, input.ID, input.Branch, actor); err != nil {- return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())}return &TestGitRepositoryOutput{@@ -247,7 +247,7 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGifunc (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*ListBranchesOutput, error) {branches, err := h.repoService.ListBranches(ctx, input.ID)if err != nil {- return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())}return &ListBranchesOutput{@@ -268,7 +268,7 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilresult, err := h.repoService.BrowseFiles(ctx, input.ID, input.Branch, input.Path)if err != nil {- return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())}return &BrowseFilesOutput{@@ -283,7 +283,7 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilfunc (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*SyncGitRepositoriesOutput, error) {if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositorySyncError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync git repositories").Error())}return &SyncGitRepositoriesOutput{diff --git a/backend/api/handlers/gitops_syncs.go b/backend/api/handlers/gitops_syncs.goindex ebdc2ae6e..278d2a964 100644--- a/backend/api/handlers/gitops_syncs.go+++ b/backend/api/handlers/gitops_syncs.go@@ -3,9 +3,9 @@ package handlersimport ("context"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -157,7 +157,7 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSyncsyncs, paginationResp, counts, err := h.syncService.GetSyncsPaginated(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.GitOpsSyncListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list GitOps syncs").Error())}return &ListGitOpsSyncsOutput{@@ -181,11 +181,11 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSsync, err := h.syncService.CreateSync(ctx, input.EnvironmentID, input.Body, actor)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncCreationError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create GitOps sync").Error())}body, mapErr := mapOneAPIResponseInternal[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {- return (&common.GitOpsSyncMappingError{Err: err}).Error()+ return "Failed to map GitOps sync"})if mapErr != nil {return nil, mapErr@@ -218,11 +218,11 @@ func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInpsync, err := h.syncService.GetSyncByID(ctx, input.EnvironmentID, input.SyncID)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncRetrievalError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve GitOps sync")}body, mapErr := mapOneAPIResponseInternal[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {- return (&common.GitOpsSyncMappingError{Err: err}).Error()+ return "Failed to map GitOps sync"})if mapErr != nil {return nil, mapErr@@ -244,11 +244,11 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSsync, err := h.syncService.UpdateSync(ctx, input.EnvironmentID, input.SyncID, input.Body, actor)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncUpdateError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update GitOps sync").Error())}body, mapErr := mapOneAPIResponseInternal[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {- return (&common.GitOpsSyncMappingError{Err: err}).Error()+ return "Failed to map GitOps sync"})if mapErr != nil {return nil, mapErr@@ -265,7 +265,7 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSif err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID, actor); err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncDeletionError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete GitOps sync")}return &DeleteGitOpsSyncOutput{@@ -285,7 +285,7 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncIresult, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID, actor)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncPerformError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to perform GitOps sync")}return &PerformSyncOutput{@@ -301,7 +301,7 @@ func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusIstatus, err := h.syncService.GetSyncStatus(ctx, input.EnvironmentID, input.SyncID)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncStatusError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to get GitOps sync status")}return &GetSyncStatusOutput{@@ -317,7 +317,7 @@ func (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFiresponse, err := h.syncService.BrowseFiles(ctx, input.EnvironmentID, input.SyncID, input.Path)if err != nil {apiErr := models.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncBrowseError{Err: err}).Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to browse GitOps sync files")}return &BrowseSyncFilesOutput{diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.goindex 5f1ad3e25..d1e7c13ba 100644--- a/backend/api/handlers/helpers.go+++ b/backend/api/handlers/helpers.go@@ -3,13 +3,14 @@ package handlersimport ("context"json "encoding/json/v2"- "errors"+ stderrors "errors""mime/multipart""strings"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -76,7 +77,7 @@ func toPaginationResponseInternal(p pagination.Response) base.PaginationResponsefunc requireUserInternal(ctx context.Context) (*models.User, error) {user, exists := humamw.GetCurrentUserFromContext(ctx)if !exists || user == nil {- return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())+ return nil, huma.Error401Unauthorized("Not authenticated")}return user, nil}@@ -84,13 +85,13 @@ func requireUserInternal(ctx context.Context) (*models.User, error) {func openUploadedFileInternal(form multipart.Form) (multipart.File, *multipart.FileHeader, error) {files := form.File["file"]if len(files) == 0 {- return nil, nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())+ return nil, nil, huma.Error400BadRequest("No file uploaded")}fileHeader := files[0]file, err := fileHeader.Open()if err != nil {- return nil, nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())+ return nil, nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to read upload").Error())}return file, fileHeader, nil@@ -217,15 +218,15 @@ func marshalRemoteRequestBodyInternal(requestBody any) ([]byte, error) {}func translateRemoteProxyErrorInternal(err error) error {- if transportErr, ok := errors.AsType[*remenv.TransportError](err); ok {+ if transportErr, ok := stderrors.AsType[*remenv.TransportError](err); ok {return huma.Error502BadGateway("failed to proxy request to environment: " + transportErr.Error())}- if statusErr, ok := errors.AsType[*remenv.StatusError](err); ok {+ if statusErr, ok := stderrors.AsType[*remenv.StatusError](err); ok {return huma.NewError(statusErr.StatusCode, "environment returned error: "+string(statusErr.Body), nil)}- if decodeErr, ok := errors.AsType[*remenv.DecodeError](err); ok {+ if decodeErr, ok := stderrors.AsType[*remenv.DecodeError](err); ok {return huma.Error500InternalServerError("failed to decode environment response: " + decodeErr.Error())}diff --git a/backend/api/handlers/image_updates.go b/backend/api/handlers/image_updates.goindex cd359151f..f0d81f31f 100644--- a/backend/api/handlers/image_updates.go+++ b/backend/api/handlers/image_updates.go@@ -5,9 +5,9 @@ import ("net/http""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -149,13 +149,13 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServfunc (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckImageUpdateInput) (*CheckImageUpdateOutput, error) {if input.ImageRef == "" {- return nil, huma.Error400BadRequest((&common.ImageRefRequiredError{}).Error())+ return nil, huma.Error400BadRequest("imageRef query parameter is required")}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.imageUpdateService.CheckImageUpdate(runtimeCtx, input.ImageRef)if err != nil {- return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())}return &CheckImageUpdateOutput{@@ -168,13 +168,13 @@ func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckIfunc (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *CheckImageUpdateByIDInput) (*CheckImageUpdateByIDOutput, error) {if input.ImageID == "" {- return nil, huma.Error400BadRequest((&common.ImageIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("imageId parameter is required")}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.imageUpdateService.CheckImageUpdateByID(runtimeCtx, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())}return &CheckImageUpdateByIDOutput{@@ -199,7 +199,7 @@ func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *CheruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)results, err := h.imageUpdateService.CheckMultipleImages(runtimeCtx, input.Body.ImageRefs, input.Body.Credentials)if err != nil {- return nil, huma.Error500InternalServerError((&common.BatchImageUpdateCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image updates").Error())}return &CheckMultipleImagesOutput{@@ -214,7 +214,7 @@ func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAllruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)results, err := h.imageUpdateService.CheckAllImages(runtimeCtx, 0, input.Body.Credentials)if err != nil {- return nil, huma.Error500InternalServerError((&common.AllImageUpdateCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check all images").Error())}return &CheckAllImagesOutput{@@ -238,7 +238,7 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Getresult, err := h.imageService.GetUpdateInfoByImageRefs(ctx, imageRefs)if err != nil {- return nil, huma.Error500InternalServerError((&common.BatchImageUpdateCheckError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image updates").Error())}return &GetUpdateInfoByRefsOutput{@@ -252,7 +252,7 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Getfunc (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*GetUpdateSummaryOutput, error) {summary, err := h.imageUpdateService.GetUpdateSummary(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.UpdateSummaryError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get update summary").Error())}return &GetUpdateSummaryOutput{diff --git a/backend/api/handlers/images.go b/backend/api/handlers/images.goindex 5324c161d..395be6062 100644--- a/backend/api/handlers/images.go+++ b/backend/api/handlers/images.go@@ -2,7 +2,7 @@ package handlersimport ("context"- "errors"+ stderrors "errors""fmt""io""mime/multipart"@@ -10,10 +10,10 @@ import ("net/url""strings"+ "emperror.dev/errors""github.com/containerd/platforms""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -381,7 +381,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (images, paginationResp, err := h.imageService.ListImagesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.ImageListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list images").Error())}if images == nil {@@ -401,7 +401,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*GetImageOutput, error) {out, err := h.imageService.GetImageDetail(ctx, input.ImageID)if err != nil {- return nil, huma.Error404NotFound((&common.ImageNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Image not found").Error())}return &GetImageOutput{@@ -570,7 +570,7 @@ func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput)}if err := h.imageService.RemoveImage(ctx, input.ImageID, input.Force, *user); err != nil {- return nil, huma.Error500InternalServerError((&common.ImageRemovalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to remove image").Error())}return &RemoveImageOutput{@@ -692,7 +692,7 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (// ListImageBuilds returns a paginated list of image build history entries.func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuildsInput) (*ListImageBuildsOutput, error) {if input.EnvironmentID == "" {- return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Environment ID is required")}params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)@@ -705,7 +705,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuilbuilds, paginationResp, err := h.buildService.ListImageBuildsByEnvironmentPaginated(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.BuildHistoryListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list build history").Error())}if builds == nil {@@ -724,7 +724,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil// GetImageBuild returns a single build history entry.func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildInput) (*GetImageBuildOutput, error) {if input.EnvironmentID == "" {- return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Environment ID is required")}if input.BuildID == "" {@@ -736,7 +736,7 @@ func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildInif errors.Is(err, gorm.ErrRecordNotFound) {return nil, huma.Error404NotFound("build not found")}- return nil, huma.Error500InternalServerError((&common.BuildHistoryRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve build history").Error())}return &GetImageBuildOutput{@@ -757,7 +757,7 @@ func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput)Until: until,})if err != nil {- return nil, huma.Error500InternalServerError((&common.ImagePruneError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune images").Error())}out := image.NewPruneReport(*report)@@ -832,20 +832,20 @@ func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageU_, iu, un, tot, err := h.dockerService.GetAllImages(ctx)if err != nil {- errs = append(errs, fmt.Errorf("get images: %w", err))+ errs = append(errs, errors.WrapIf(err, "get images"))} else {inuse, unused, total = iu, un, tot}sz, err := h.imageService.GetTotalImageSize(ctx)if err != nil {- errs = append(errs, fmt.Errorf("get total image size: %w", err))+ errs = append(errs, errors.WrapIf(err, "get total image size"))} else {totalSize = sz}if len(errs) > 0 {- return nil, huma.Error500InternalServerError((&common.ImageUsageCountsError{Err: errors.Join(errs...)}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(stderrors.Join(errs...), "Failed to get image usage counts").Error())}return &GetImageUsageCountsOutput{@@ -871,7 +871,7 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)// Get file from multipart formfiles := input.RawBody.File["file"]if len(files) == 0 {- return nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())+ return nil, huma.Error400BadRequest("No file uploaded")}fileHeader := files[0]@@ -880,7 +880,7 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)// Validate file extensionlowerName := strings.ToLower(fileName)if !strings.HasSuffix(lowerName, ".tar") && !strings.HasSuffix(lowerName, ".tar.gz") && !strings.HasSuffix(lowerName, ".tgz") && !strings.HasSuffix(lowerName, ".tar.xz") {- return nil, huma.Error400BadRequest((&common.InvalidFileFormatError{}).Error())+ return nil, huma.Error400BadRequest("Invalid file format. Only Docker image tar archives are allowed (.tar, .tar.gz, .tgz, .tar.xz)")}// Get max upload size from settings@@ -895,14 +895,14 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)// Open the filefile, err := fileHeader.Open()if err != nil {- return nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to read upload").Error())}defer func() { _ = file.Close() }()// Load the imageresult, err := h.imageService.LoadImageFromReader(ctx, file, fileName, *user, maxSizeBytes)if err != nil {- return nil, huma.Error500InternalServerError((&common.ImageLoadError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load image").Error())}return &UploadImageOutput{diff --git a/backend/api/handlers/networks.go b/backend/api/handlers/networks.goindex a81c685b7..23fefae27 100644--- a/backend/api/handlers/networks.go+++ b/backend/api/handlers/networks.go@@ -8,9 +8,9 @@ import ("sort""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -178,7 +178,7 @@ func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInnetworks, paginationResp, counts, err := h.networkService.ListNetworksPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list networks").Error())}return &ListNetworksOutput{@@ -194,7 +194,7 @@ func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInfunc (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetworkCountsInput) (*GetNetworkCountsOutput, error) {_, inuse, unused, total, err := h.dockerService.GetAllNetworks(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkUsageCountsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get network counts").Error())}return &GetNetworkCountsOutput{@@ -240,12 +240,12 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkreturn createErr})if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create network").Error())}out, err := mapper.MapOne[dockernetwork.CreateResponse, networktypes.CreateResponse](*response)if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -260,12 +260,12 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkfunc (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput) (*GetNetworkOutput, error) {networkInspect, err := h.networkService.GetNetworkByID(ctx, input.NetworkID)if err != nil {- return nil, huma.Error404NotFound((&common.NetworkNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Network not found").Error())}out, err := mapper.MapOne[dockernetwork.Inspect, networktypes.Inspect](*networkInspect)if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}// Ensure ID is mapped correctly@@ -383,7 +383,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkreturn h.networkService.RemoveNetwork(runtimeCtx, input.NetworkID, *user)})if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkRemovalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to remove network").Error())}return &DeleteNetworkOutput{@@ -411,12 +411,12 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksreturn pruneErr})if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkPruneError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune networks").Error())}out, err := mapper.MapOne[dockernetwork.PruneReport, networktypes.PruneReport](*report)if err != nil {- return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.goindex 1ce903ae3..9033e17e1 100644--- a/backend/api/handlers/notifications.go+++ b/backend/api/handlers/notifications.go@@ -2,13 +2,13 @@ package handlersimport ("context"- "errors""net/http""strings"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -175,7 +175,7 @@ func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, in}settings, err := h.notificationService.GetAllSettings(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.NotificationSettingsListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list notification settings").Error())}responses := make([]notification.Response, len(settings))@@ -199,7 +199,7 @@ func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, inputsettings, err := h.notificationService.GetSettingsByProvider(ctx, provider)if err != nil {- return nil, huma.Error404NotFound((&common.NotificationSettingsNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Settings not found")}response := notification.Response{@@ -218,7 +218,7 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con}provider := models.NotificationProvider(input.Body.Provider)if !models.IsValidNotificationProvider(provider) {- return nil, huma.Error400BadRequest((&common.InvalidNotificationProviderError{}).Error())+ return nil, huma.Error400BadRequest("invalid provider")}settings, err := h.notificationService.CreateOrUpdateSettings(@@ -228,7 +228,7 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Conmodels.JSON(input.Body.Config),)if err != nil {- return nil, huma.Error500InternalServerError((&common.NotificationSettingsUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update notification settings").Error())}response := notification.Response{@@ -248,7 +248,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, inprovider := models.NotificationProvider(input.Provider)if err := h.notificationService.DeleteSettings(ctx, provider); err != nil {- return nil, huma.Error500InternalServerError((&common.NotificationSettingsDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete notification settings").Error())}return &DeleteNotificationSettingsOutput{@@ -271,7 +271,7 @@ func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNwarning, err := h.notificationService.TestNotification(ctx, input.EnvironmentID, provider, testType)if err != nil {- return nil, huma.Error500InternalServerError((&common.NotificationTestError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to send test notification").Error())}return &TestNotificationOutput{diff --git a/backend/api/handlers/oidc.go b/backend/api/handlers/oidc.goindex 767c29961..dfd1eff8e 100644--- a/backend/api/handlers/oidc.go+++ b/backend/api/handlers/oidc.go@@ -7,6 +7,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -252,7 +253,7 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput) (*GetOidcStatusOutput, error) {status, err := h.authService.GetOidcConfigurationStatus(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.OidcStatusError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve OIDC status").Error())}return &GetOidcStatusOutput{@@ -264,7 +265,7 @@ func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput)func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInput) (*GetOidcConfigOutput, error) {config, err := h.authService.GetOidcConfig(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.OidcConfigError{}).Error())+ return nil, huma.Error500InternalServerError("Failed to get OIDC configuration")}appUrl := ""@@ -291,10 +292,10 @@ func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInpfunc (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlInput) (*GetOidcAuthUrlOutput, error) {enabled, err := h.authService.IsOidcEnabled(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())+ return nil, huma.Error500InternalServerError("Failed to check OIDC status")}if !enabled {- return nil, huma.Error400BadRequest((&common.OidcDisabledError{}).Error())+ return nil, huma.Error400BadRequest("OIDC authentication is disabled")}appUrl := ""@@ -313,7 +314,7 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlIauthUrl, stateCookieValue, err := h.oidcService.GenerateAuthURL(ctx, input.Body.RedirectUri, origin, mobileRedirectURI)if err != nil {- return nil, huma.Error500InternalServerError((&common.OidcAuthUrlGenerationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate OIDC auth URL").Error())}// Build state cookie (600 seconds = 10 minutes)@@ -331,7 +332,7 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlIfunc (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCallbackInput) (*HandleOidcCallbackOutput, error) {// Validate state cookieif input.OidcStateCookie == "" {- return nil, huma.Error400BadRequest((&common.OidcStateCookieError{}).Error())+ return nil, huma.Error400BadRequest("Missing or invalid OIDC state cookie")}appUrl := ""@@ -352,13 +353,13 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCuserInfo, tokenResp, err := h.oidcService.HandleCallback(ctx, input.Body.Code, input.Body.State, input.OidcStateCookie, origin, mobileRedirectURI)if err != nil {slog.WarnContext(ctx, "OIDC callback failed", "error", err, "origin", origin, "state_present", input.Body.State != "", "code_present", input.Body.Code != "")- return nil, huma.Error400BadRequest((&common.OidcCallbackError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "OIDC callback failed").Error())}// Complete loginuserModel, tokenPair, err := h.authService.OidcLogin(ctx, *userInfo, tokenResp, sessionMetaFromContextInternal(ctx, input.UserAgent))if err != nil {- return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Authentication failed")}// Build cookies: clear the state cookie always; only set the session@@ -374,7 +375,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCuserDto, err := h.userService.ToUserResponseDto(ctx, *userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &HandleOidcCallbackOutput{@@ -393,16 +394,16 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCfunc (h *OidcHandler) InitiateDeviceAuth(ctx context.Context, _ *InitiateDeviceAuthInput) (*InitiateDeviceAuthOutput, error) {enabled, err := h.authService.IsOidcEnabled(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())+ return nil, huma.Error500InternalServerError("Failed to check OIDC status")}if !enabled {- return nil, huma.Error400BadRequest((&common.OidcDisabledError{}).Error())+ return nil, huma.Error400BadRequest("OIDC authentication is disabled")}response, err := h.oidcService.InitiateDeviceAuth(ctx)if err != nil {slog.WarnContext(ctx, "Device authorization initiation failed", "error", err)- return nil, huma.Error500InternalServerError((&common.OidcAuthUrlGenerationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate OIDC auth URL").Error())}return &InitiateDeviceAuthOutput{@@ -430,13 +431,13 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDereturn nil, huma.Error403Forbidden("access_denied")default:slog.WarnContext(ctx, "Device token exchange failed", "error", err)- return nil, huma.Error400BadRequest((&common.OidcCallbackError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "OIDC callback failed").Error())}}userModel, tokenPair, err := h.authService.OidcLogin(ctx, *userInfo, tokenResp, sessionMetaFromContextInternal(ctx, input.UserAgent))if err != nil {- return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Authentication failed")}maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)@@ -446,7 +447,7 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDeuserDto, err := h.userService.ToUserResponseDto(ctx, *userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &ExchangeDeviceTokenOutput{@@ -490,7 +491,7 @@ func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOi}mapping, err := h.roleService.CreateOidcMapping(ctx, claimValue, roleID, input.Body.EnvironmentID)if err != nil {- if common.IsInvalidRoleAssignmentError(err) {+ if errors.Is(err, common.ErrInvalidRoleAssignment) {return nil, huma.Error400BadRequest(err.Error())}return nil, huma.Error500InternalServerError("failed to create mapping: " + err.Error())@@ -512,13 +513,13 @@ func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOi}mapping, err := h.roleService.UpdateOidcMapping(ctx, input.ID, claimValue, roleID, input.Body.EnvironmentID)if err != nil {- if common.IsOidcMappingNotFoundError(err) {+ if errors.Is(err, common.ErrOidcMappingNotFound) {return nil, huma.Error404NotFound("mapping not found")}- if common.IsOidcMappingEnvManagedError(err) {+ if errors.Is(err, common.ErrOidcMappingEnvManaged) {return nil, huma.Error409Conflict(err.Error())}- if common.IsInvalidRoleAssignmentError(err) {+ if errors.Is(err, common.ErrInvalidRoleAssignment) {return nil, huma.Error400BadRequest(err.Error())}return nil, huma.Error500InternalServerError("failed to update mapping: " + err.Error())@@ -531,10 +532,10 @@ func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOifunc (h *OidcHandler) DeleteOidcRoleMapping(ctx context.Context, input *DeleteOidcRoleMappingInput) (*DeleteOidcRoleMappingOutput, error) {if err := h.roleService.DeleteOidcMapping(ctx, input.ID); err != nil {- if common.IsOidcMappingNotFoundError(err) {+ if errors.Is(err, common.ErrOidcMappingNotFound) {return nil, huma.Error404NotFound("mapping not found")}- if common.IsOidcMappingEnvManagedError(err) {+ if errors.Is(err, common.ErrOidcMappingEnvManaged) {return nil, huma.Error409Conflict(err.Error())}return nil, huma.Error500InternalServerError("failed to delete mapping: " + err.Error())diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.goindex edb4c7632..8bfaf5e8e 100644--- a/backend/api/handlers/projects.go+++ b/backend/api/handlers/projects.go@@ -2,7 +2,7 @@ package handlersimport ("context"- "errors"+ stderrors "errors""fmt""io""log/slog"@@ -10,6 +10,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -453,7 +454,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInif errors.Is(err, context.Canceled) {return nil, huma.Error500InternalServerError("Request was canceled")}- return nil, huma.Error500InternalServerError((&common.ProjectListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list projects").Error())}if projects == nil {@@ -473,7 +474,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInfunc (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*GetProjectStatusCountsOutput, error) {_, running, stopped, total, archived, err := h.projectService.GetProjectStatusCounts(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.ProjectStatusCountsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project status counts").Error())}return &GetProjectStatusCountsOutput{@@ -492,7 +493,7 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetP// DeployProject deploys a Docker Compose project.func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProjectInput) (*huma.StreamResponse, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -565,10 +566,10 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpuif err := h.projectService.DownProject(downCtx, input.ProjectID, *user); err != nil {activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", err)- if _, ok := errors.AsType[*common.ProjectArchivedError](err); ok {- return nil, huma.Error400BadRequest((&common.ProjectDownError{Err: err}).Error())+ if errors.Is(err, common.ErrProjectArchived) {+ return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError((&common.ProjectDownError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to bring down project").Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", nil)@@ -585,13 +586,13 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu}func projectUpdateHTTPErrorInternal(err error) error {- if conflictErr, ok := errors.AsType[*volumes.ProjectVolumeRenameConflictError](err); ok {+ if conflictErr, ok := stderrors.AsType[*volumes.ProjectVolumeRenameConflictError](err); ok {return huma.Error409Conflict(conflictErr.Error())}- if inUseErr, ok := errors.AsType[*volumes.ProjectVolumeRenameInUseError](err); ok {+ if inUseErr, ok := stderrors.AsType[*volumes.ProjectVolumeRenameInUseError](err); ok {return huma.Error409Conflict(inUseErr.Error())}- if spaceErr, ok := errors.AsType[*volumes.ProjectVolumeRenameInsufficientSpaceError](err); ok {+ if spaceErr, ok := stderrors.AsType[*volumes.ProjectVolumeRenameInsufficientSpaceError](err); ok {return huma.NewError(http.StatusInsufficientStorage, spaceErr.Error())}return projectFileHTTPError(err)@@ -600,14 +601,14 @@ func projectUpdateHTTPErrorInternal(err error) error {// projectFileHTTPError maps project file management errors to HTTP errors.// It returns nil when err is not a project file error.func projectFileHTTPError(err error) error {- if conflictErr, ok := errors.AsType[*common.ProjectFileConflictError](err); ok {- return huma.Error409Conflict(conflictErr.Error())+ if errors.Is(err, common.ErrProjectFileConflict) {+ return huma.Error409Conflict(err.Error())}- if forbiddenErr, ok := errors.AsType[*common.ProjectFileForbiddenError](err); ok {- return huma.Error403Forbidden(forbiddenErr.Error())+ if errors.Is(err, common.ErrProjectFileForbidden) {+ return huma.Error403Forbidden(err.Error())}- if badRequestErr, ok := errors.AsType[*common.ProjectFileBadRequestError](err); ok {- return huma.Error400BadRequest(badRequestErr.Error())+ if errors.Is(err, common.ErrProjectFileBadRequest) {+ return huma.Error400BadRequest(err.Error())}return nil}@@ -641,7 +642,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectif httpErr := projectFileHTTPError(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error500InternalServerError((&common.ProjectCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create project").Error())}var response project.CreateReponse@@ -670,12 +671,12 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject// GetProject returns a project by ID.func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, project.DetailsOptions{})if err != nil {- return nil, huma.Error404NotFound((&common.ProjectDetailsError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())}return &GetProjectOutput{@@ -688,12 +689,12 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*GetProjectOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, opts)if err != nil {- return nil, huma.Error404NotFound((&common.ProjectDetailsError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())}return &GetProjectOutput{@@ -735,7 +736,7 @@ func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjecfunc (h *ProjectHandler) GetProjectFile(ctx context.Context, input *GetProjectFileInput) (*GetProjectFileOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}if input.RelativePath == "" {return nil, huma.Error400BadRequest("relativePath is required")@@ -743,16 +744,12 @@ func (h *ProjectHandler) GetProjectFile(ctx context.Context, input *GetProjectFifile, err := h.projectService.GetProjectFileContent(ctx, input.ProjectID, input.RelativePath)if err != nil {- var badRequestErr *common.ProjectFileBadRequestError- var forbiddenErr *common.ProjectFileForbiddenError- var notFoundErr *common.ProjectFileNotFoundError-switch {- case errors.As(err, &badRequestErr):+ case errors.Is(err, common.ErrProjectFileBadRequest):return nil, huma.Error400BadRequest(err.Error())- case errors.As(err, &forbiddenErr):+ case errors.Is(err, common.ErrProjectFileForbidden):return nil, huma.Error403Forbidden(err.Error())- case errors.As(err, ¬FoundErr):+ case errors.Is(err, common.ErrProjectFileNotFound):return nil, huma.Error404NotFound("project file not found")default:return nil, huma.Error500InternalServerError("internal error")@@ -809,7 +806,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjeif err := h.projectService.DestroyProject(destroyCtx, input.ProjectID, removeFiles, removeVolumes, *user); err != nil {activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", err)- return nil, huma.Error500InternalServerError((&common.ProjectDestroyError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to destroy project").Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", nil)@@ -828,7 +825,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje// UpdateProject updates a Docker Compose project.func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*UpdateProjectOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -856,7 +853,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectif httpErr := projectUpdateHTTPErrorInternal(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())}// Skip the recursive directory walks on save: the file tree is only@@ -872,7 +869,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectIncludeUpdateInfo: true,})if err != nil {- return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project details").Error())}details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -887,7 +884,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject// UpdateProjectInclude updates an include file within a project.func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateProjectIncludeInput) (*UpdateProjectIncludeOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -915,7 +912,7 @@ func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *Updatereturn h.projectService.UpdateProjectIncludeFile(runtimeCtx, input.ProjectID, input.Body.RelativePath, input.Body.Content, *user)})if err != nil {- return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())}details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, project.DetailsOptions{@@ -927,7 +924,7 @@ func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateIncludeUpdateInfo: true,})if err != nil {- return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project details").Error())}details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -998,7 +995,7 @@ func (h *ProjectHandler) redeployProjectActivityConfigInternal(options *project.return h.projectService.RedeployProject(runtimeCtx, projectID, user, options)},Error: projectArchivedActionErrorInternal(func(err error) error {- return huma.Error400BadRequest((&common.ProjectRedeploymentError{Err: err}).Error())+ return huma.Error400BadRequest(errors.WithMessage(err, "Failed to redeploy project").Error())}),}}@@ -1017,7 +1014,7 @@ func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []return h.projectService.UpdateProjectServices(runtimeCtx, projectID, services, user)},Error: projectArchivedActionErrorInternal(func(err error) error {- return huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())+ return huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())}),}}@@ -1035,14 +1032,14 @@ func (h *ProjectHandler) restartProjectActivityConfigInternal(services []string)return h.projectService.RestartProject(runtimeCtx, projectID, services, user)},Error: projectArchivedActionErrorInternal(func(err error) error {- return huma.Error400BadRequest((&common.ProjectRestartError{Err: err}).Error())+ return huma.Error400BadRequest(errors.WithMessage(err, "Failed to restart project").Error())}),}}func projectArchivedActionErrorInternal(fallback func(error) error) func(error) error {return func(err error) error {- if _, ok := errors.AsType[*common.ProjectArchivedError](err); ok {+ if errors.Is(err, common.ErrProjectArchived) {return huma.Error400BadRequest(err.Error())}return fallback(err)@@ -1068,7 +1065,7 @@ func (h *ProjectHandler) runProjectActivityActionResponseInternal(func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, environmentID, projectID string, cfg projectActivityActionConfigInternal) (base.MessageResponse, error) {if projectID == "" {- return base.MessageResponse{}, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return base.MessageResponse{}, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -1102,7 +1099,7 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, efunc (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjectInput) (*ArchiveProjectOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -1111,10 +1108,10 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje}if err := h.projectService.ArchiveProject(ctx, input.ProjectID, *user); err != nil {- if _, ok := errors.AsType[*common.ProjectMustBeStoppedError](err); ok {+ if errors.Is(err, common.ErrProjectMustBeStopped) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError((&common.ProjectArchiveError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to archive project").Error())}return &ArchiveProjectOutput{@@ -1127,7 +1124,7 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjefunc (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveProjectInput) (*UnarchiveProjectOutput, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -1136,7 +1133,7 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP}if err := h.projectService.UnarchiveProject(ctx, input.ProjectID, *user); err != nil {- return nil, huma.Error500InternalServerError((&common.ProjectUnarchiveError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to unarchive project").Error())}return &UnarchiveProjectOutput{@@ -1150,7 +1147,7 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP// PullProjectImages pulls all images for a project with streaming progress.func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProjectImagesInput) (*huma.StreamResponse, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)@@ -1208,7 +1205,7 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje// BuildProjectImages builds compose services with build directives.func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildProjectInput) (*huma.StreamResponse, error) {if input.ProjectID == "" {- return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Project ID is required")}user, err := requireUserInternal(ctx)diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.goindex 50e50bc61..245c6ef5e 100644--- a/backend/api/handlers/roles.go+++ b/backend/api/handlers/roles.go@@ -4,6 +4,7 @@ import ("context""net/http"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -202,7 +203,7 @@ func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*Lifunc (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRoleOutput, error) {role, err := h.roleService.GetRole(ctx, input.ID)if err != nil {- if common.IsRoleNotFoundError(err) {+ if errors.Is(err, common.ErrRoleNotFound) {return nil, huma.Error404NotFound("role not found")}return nil, huma.Error500InternalServerError("failed to get role: " + err.Error())@@ -216,19 +217,19 @@ func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*callerPS, _ := humamw.PermissionsFromContext(ctx)if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {switch {- case common.IsUnknownPermissionError(err):+ case errors.Is(err, common.ErrUnknownPermission):return nil, huma.Error400BadRequest(err.Error())- case common.IsRolePermissionEscalationError(err):+ case errors.Is(err, common.ErrRolePermissionEscalation):return nil, huma.Error403Forbidden(err.Error())}return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())}role, err := h.roleService.CreateRole(ctx, input.Body.Name, input.Body.Description, input.Body.Permissions)if err != nil {- if common.IsRoleNameTakenError(err) {+ if errors.Is(err, common.ErrRoleNameTaken) {return nil, huma.Error409Conflict("role name already in use")}- if common.IsUnknownPermissionError(err) {+ if errors.Is(err, common.ErrUnknownPermission) {return nil, huma.Error400BadRequest(err.Error())}return nil, huma.Error500InternalServerError("failed to create role: " + err.Error())@@ -242,9 +243,9 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*callerPS, _ := humamw.PermissionsFromContext(ctx)if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {switch {- case common.IsUnknownPermissionError(err):+ case errors.Is(err, common.ErrUnknownPermission):return nil, huma.Error400BadRequest(err.Error())- case common.IsRolePermissionEscalationError(err):+ case errors.Is(err, common.ErrRolePermissionEscalation):return nil, huma.Error403Forbidden(err.Error())}return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())@@ -252,13 +253,13 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*role, err := h.roleService.UpdateRole(ctx, input.ID, input.Body.Name, input.Body.Description, input.Body.Permissions)if err != nil {switch {- case common.IsRoleNotFoundError(err):+ case errors.Is(err, common.ErrRoleNotFound):return nil, huma.Error404NotFound("role not found")- case common.IsRoleBuiltInError(err):+ case errors.Is(err, common.ErrRoleBuiltIn):return nil, huma.Error403Forbidden("built-in roles cannot be modified")- case common.IsRoleNameTakenError(err):+ case errors.Is(err, common.ErrRoleNameTaken):return nil, huma.Error409Conflict("role name already in use")- case common.IsUnknownPermissionError(err):+ case errors.Is(err, common.ErrUnknownPermission):return nil, huma.Error400BadRequest(err.Error())}return nil, huma.Error500InternalServerError("failed to update role: " + err.Error())@@ -271,11 +272,11 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*DeleteRoleOutput, error) {if err := h.roleService.DeleteRole(ctx, input.ID); err != nil {switch {- case common.IsRoleNotFoundError(err):+ case errors.Is(err, common.ErrRoleNotFound):return nil, huma.Error404NotFound("role not found")- case common.IsRoleBuiltInError(err):+ case errors.Is(err, common.ErrRoleBuiltIn):return nil, huma.Error403Forbidden("built-in roles cannot be deleted")- case common.IsNoGlobalAdminRemainsError(err):+ case errors.Is(err, common.ErrNoGlobalAdminRemains):return nil, huma.Error409Conflict(err.Error())}return nil, huma.Error500InternalServerError("failed to delete role: " + err.Error())@@ -312,9 +313,9 @@ func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUser}if err := h.roleService.SetUserAssignments(ctx, input.UserID, desired); err != nil {switch {- case common.IsInvalidRoleAssignmentError(err):+ case errors.Is(err, common.ErrInvalidRoleAssignment):return nil, huma.Error400BadRequest(err.Error())- case common.IsNoGlobalAdminRemainsError(err):+ case errors.Is(err, common.ErrNoGlobalAdminRemains):return nil, huma.Error409Conflict(err.Error())}return nil, huma.Error500InternalServerError("failed to set assignments: " + err.Error())diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.goindex b1dcc3628..2f9765b5c 100644--- a/backend/api/handlers/settings.go+++ b/backend/api/handlers/settings.go@@ -2,16 +2,16 @@ package handlersimport ("context"- "errors""fmt""net/http""os""strconv""strings"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -259,7 +259,7 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublivar settingsDto []settings.PublicSettingif err := mapper.MapStructList(settingsList, &settingsDto); err != nil {- return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map settings")}return &GetPublicSettingsOutput{Body: h.appendRuntimeSettingsInternal(settingsDto, false)}, nil@@ -299,7 +299,7 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInpvar settingsDto []settings.PublicSettingif err := mapper.MapStructList(settingsList, &settingsDto); err != nil {- return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map settings")}return &GetSettingsOutput{Body: h.appendRuntimeSettingsInternal(settingsDto, true)}, nil@@ -353,7 +353,7 @@ func (h *SettingsHandler) validateSettingsUpdateInput(input settings.Update) errfunc (h *SettingsHandler) updateSettingsForRemoteEnvironment(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {// Check if trying to update auth settings on non-local environment.if hasAuthSettingsUpdateInternal(input.Body) {- return nil, huma.Error403Forbidden((&common.AuthSettingsUpdateError{}).Error())+ return nil, huma.Error403Forbidden("Authentication settings can only be updated from the main environment")}apiResp, err := proxyRemoteJSONInternal[base.ApiResponse[[]settings.SettingDto]](ctx, h.environmentService, input.EnvironmentID, http.MethodPut, "/api/environments/0/settings", input.Body)@@ -384,7 +384,7 @@ func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context,updatedSettings, err := h.settingsService.UpdateSettings(ctx, input)if err != nil {- return nil, huma.Error500InternalServerError((&common.SettingsUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to update settings")}settingDtos := make([]settings.SettingDto, 0, len(updatedSettings))@@ -421,7 +421,7 @@ func hasAuthSettingsUpdateInternal(req settings.Update) bool {// Search searches settings by query.func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput) (*SearchSettingsOutput, error) {if strings.TrimSpace(input.Body.Query) == "" {- return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Query parameter is required")}ps, _ := humamw.PermissionsFromContext(ctx)diff --git a/backend/api/handlers/swarm.go b/backend/api/handlers/swarm.goindex 3d25d7fbd..833007833 100644--- a/backend/api/handlers/swarm.go+++ b/backend/api/handlers/swarm.go@@ -7,6 +7,7 @@ import ("net/http""strings"+ "emperror.dev/errors""github.com/containerd/errdefs""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"@@ -645,7 +646,7 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServiceparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListServicesPaginated(ctx, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmServiceListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm services").Error())}if items == nil {items = []swarmtypes.ServiceSummary{}@@ -669,9 +670,9 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInpservice, err := h.swarmService.GetService(ctx, input.ServiceID)if err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm service not found").Error())}- return nil, mapSwarmServiceError(err, (&common.SwarmServiceNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm service not found").Error())}return &GetSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceInspect]{Success: true, Data: *service}}, nil@@ -691,7 +692,7 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInpfunc (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*CreateSwarmServiceOutput, error) {resp, err := h.swarmService.CreateService(ctx, input.Body)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmServiceCreateError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to create swarm service").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.create", "swarm_service", resp.ID, "", map[string]any{"serviceId": resp.ID})@@ -713,7 +714,7 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServfunc (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*UpdateSwarmServiceOutput, error) {resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.update", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -736,9 +737,9 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServfunc (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*DeleteSwarmServiceOutput, error) {if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm service not found").Error())}- return nil, mapSwarmServiceError(err, (&common.SwarmServiceRemoveError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to remove swarm service").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.delete", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -760,7 +761,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSerparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListServiceTasksPaginated(ctx, input.ServiceID, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -783,7 +784,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSerfunc (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*RollbackSwarmServiceOutput, error) {resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.rollback", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -805,7 +806,7 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmfunc (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*ScaleSwarmServiceOutput, error) {resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.scale", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID, "replicas": input.Body.Replicas})@@ -827,7 +828,7 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInputparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmNodeListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm nodes").Error())}if items == nil {items = []swarmtypes.NodeSummary{}@@ -851,9 +852,9 @@ func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)if err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound((&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm node not found").Error())}- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}return &GetSwarmNodeOutput{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil@@ -879,9 +880,9 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwanode, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)if err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound((&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm node not found").Error())}- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}user, err := requireUserInternal(ctx)@@ -1026,7 +1027,7 @@ func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdent// when the node update fails.func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*UpdateSwarmNodeOutput, error) {if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.update", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -1047,7 +1048,7 @@ func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInp// when the node cannot be removed.func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInput) (*DeleteSwarmNodeOutput, error) {if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.delete", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID, "force": input.Force})@@ -1068,7 +1069,7 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp// when the promotion fails.func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*PromoteSwarmNodeOutput, error) {if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.promote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -1089,7 +1090,7 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI// when the demotion fails.func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*DemoteSwarmNodeOutput, error) {if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.demote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -1111,7 +1112,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTaparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListNodeTasksPaginated(ctx, input.NodeID, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -1134,7 +1135,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInputparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListTasksPaginated(ctx, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -1157,7 +1158,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInpparams := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListStacksPaginated(ctx, input.EnvironmentID, params)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmStackListError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to list swarm stacks").Error())}if items == nil {items = []swarmtypes.StackSummary{}@@ -1181,7 +1182,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInpfunc (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*DeploySwarmStackOutput, error) {resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmStackDeployError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to deploy swarm stack").Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.deploy", "swarm_stack", input.Body.Name, input.Body.Name, map[string]any{"stack": input.Body.Name})@@ -1386,7 +1387,7 @@ func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatusfunc (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*GetSwarmInfoOutput, error) {info, err := h.swarmService.GetSwarmInfo(ctx)if err != nil {- return nil, mapSwarmServiceError(err, (&common.SwarmInspectError{Err: err}).Error())+ return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to inspect swarm").Error())}return &GetSwarmInfoOutput{Body: base.ApiResponse[swarmtypes.SwarmInfo]{Success: true, Data: *info}}, nil@@ -1946,13 +1947,13 @@ func mapSwarmServiceError(err error, fallback string) error {if err == nil {return nil}- if common.IsSwarmNotEnabledError(err) {- return huma.Error409Conflict((&common.SwarmNotEnabledError{}).Error())+ if errors.Is(err, common.ErrSwarmNotEnabled) {+ return huma.Error409Conflict("Swarm mode is not enabled")}- if common.IsSwarmManagerRequiredError(err) {- return huma.Error403Forbidden((&common.SwarmManagerRequiredError{}).Error())+ if errors.Is(err, common.ErrSwarmManagerRequired) {+ return huma.Error403Forbidden("Swarm manager access required")}- if common.IsSwarmConfigImmutableError(err) || common.IsSwarmSecretImmutableError(err) {+ if errors.Is(err, common.ErrSwarmConfigImmutable) || errors.Is(err, common.ErrSwarmSecretImmutable) {return huma.Error400BadRequest(err.Error())}if errdefs.IsNotFound(err) {diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.goindex daa34a1a3..6e3a1499f 100644--- a/backend/api/handlers/system.go+++ b/backend/api/handlers/system.go@@ -2,11 +2,12 @@ package handlersimport ("context"- "errors""log/slog""net/http""strings"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"dockersystem "github.com/moby/moby/api/types/system""github.com/moby/moby/client"@@ -277,12 +278,12 @@ func (h *SystemHandler) rejectIfAgentModeInternal() error {func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*SystemHealthOutput, error) {dockerClient, err := h.dockerService.GetClient(ctx)if err != nil {- return nil, huma.Error503ServiceUnavailable((&common.DockerConnectionError{Err: err}).Error())+ return nil, huma.Error503ServiceUnavailable(errors.WithMessage(err, "Failed to connect to Docker").Error())}_, err = dockerClient.Ping(ctx, client.PingOptions{})if err != nil {- return nil, huma.Error503ServiceUnavailable((&common.DockerPingError{Err: err}).Error())+ return nil, huma.Error503ServiceUnavailable(errors.WithMessage(err, "Docker is not responsive").Error())}return &SystemHealthOutput{}, nil@@ -292,17 +293,17 @@ func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoInput) (*GetDockerInfoOutput, error) {dockerClient, err := h.dockerService.GetClient(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.DockerConnectionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to connect to Docker").Error())}version, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})if err != nil {- return nil, huma.Error500InternalServerError((&common.DockerVersionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get Docker version").Error())}infoResult, err := dockerClient.Info(ctx, client.InfoOptions{})if err != nil {- return nil, huma.Error500InternalServerError((&common.DockerInfoError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get Docker info").Error())}info := infoResult.Info@@ -403,7 +404,7 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllCruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.systemService.StartAllContainers(runtimeCtx, input.EnvironmentID)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerStartAllError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start containers").Error())}return &StartAllContainersOutput{@@ -419,7 +420,7 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.systemService.StartAllStoppedContainers(runtimeCtx, input.EnvironmentID)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerStartStoppedError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start stopped containers").Error())}return &StartAllStoppedContainersOutput{@@ -435,7 +436,7 @@ func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllConruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.systemService.StopAllContainers(runtimeCtx, input.EnvironmentID)if err != nil {- return nil, huma.Error500InternalServerError((&common.ContainerStopAllError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to stop containers").Error())}return &StopAllContainersOutput{@@ -451,9 +452,9 @@ func (h *SystemHandler) ConvertDockerRun(ctx context.Context, input *ConvertDockresult, err := convert.Convert(input.Body.DockerRunCommand, converttypes.Options{})if err != nil {if errors.Is(err, converttypes.ErrParse) {- return nil, huma.Error400BadRequest((&common.DockerRunParseError{Err: err}).Error())+ return nil, huma.Error400BadRequest("Failed to parse docker run command. Please check the syntax.")}- return nil, huma.Error500InternalServerError((&common.DockerComposeConversionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to convert to Docker Compose format.")}serviceName := ""@@ -480,7 +481,7 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckUBody: UpgradeCheckResultData{CanUpgrade: false,Error: true,- Message: (&common.UpgradeCheckError{Err: err}).Error(),+ Message: errors.WithMessage(err, "Failed to check for updates").Error(),},}, nil}@@ -507,11 +508,11 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradif err != nil {slog.Error("System upgrade failed", "error", err, "user", user.Username)- if common.IsUpgradeInProgressError(err) {- return nil, huma.Error409Conflict((&common.UpgradeTriggerError{Err: err}).Error())+ if errors.Is(err, common.ErrUpgradeInProgress) {+ return nil, huma.Error409Conflict(errors.WithMessage(err, "Failed to initiate upgrade").Error())}- return nil, huma.Error500InternalServerError((&common.UpgradeTriggerError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())}return &TriggerUpgradeOutput{@@ -544,10 +545,10 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdajob, err := h.upgradeService.StartUpdateAll(runtimeCtx, *user, h.environmentService)if err != nil {- if common.IsUpdateAllInProgressError(err) {+ if errors.Is(err, common.ErrUpdateAllInProgress) {return nil, huma.Error409Conflict(err.Error())}- return nil, huma.Error500InternalServerError((&common.UpgradeTriggerError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())}return &TriggerUpdateAllOutput{diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.goindex 28f0f4959..a9591f97d 100644--- a/backend/api/handlers/templates.go+++ b/backend/api/handlers/templates.go@@ -5,6 +5,7 @@ import (json "encoding/json/v2""net/url"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -334,7 +335,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatetemplates, paginationResp, err := h.templateService.GetAllTemplatesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.TemplateListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())}return &ListTemplatesOutput{@@ -350,12 +351,12 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatefunc (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*GetAllTemplatesOutput, error) {templates, err := h.templateService.GetAllTemplates(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.TemplateListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())}out, mapErr := mapper.MapSlice[models.ComposeTemplate, template.Template](templates)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}return &GetAllTemplatesOutput{@@ -369,7 +370,7 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplate// GetTemplate returns a template by ID.func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInput) (*GetTemplateOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}// Path parameter arrives URL-encoded (e.g. "remote%3Areg%3Aslug" for remote IDs that@@ -377,20 +378,20 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp// matching against cached / stored template IDs.id, decodeErr := url.PathUnescape(input.ID)if decodeErr != nil {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}tmpl, err := h.templateService.GetTemplate(ctx, id)if err != nil {- if common.IsTemplateNotFoundError(err) {- return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())+ if errors.Is(err, common.ErrTemplateNotFound) {+ return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError((&common.TemplateRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template").Error())}var out template.Templateif mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {- return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}return &GetTemplateOutput{@@ -404,20 +405,20 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp// GetTemplateContent returns template content with parsed data.func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemplateContentInput) (*GetTemplateContentOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}id, decodeErr := url.PathUnescape(input.ID)if decodeErr != nil {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}contentData, err := h.templateService.GetTemplateContentWithParsedData(ctx, id)if err != nil {- if common.IsTemplateNotFoundError(err) {- return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())+ if errors.Is(err, common.ErrTemplateNotFound) {+ return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError((&common.TemplateContentError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template content").Error())}return &GetTemplateContentOutput{@@ -442,12 +443,12 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl}if err := h.templateService.CreateTemplate(ctx, tmpl); err != nil {- return nil, huma.Error500InternalServerError((&common.TemplateCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create template").Error())}var out template.Templateif mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {- return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}return &CreateTemplateOutput{@@ -461,12 +462,12 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl// UpdateTemplate updates a template.func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplateInput) (*UpdateTemplateOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}id, decodeErr := url.PathUnescape(input.ID)if decodeErr != nil {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}updates := &models.ComposeTemplate{@@ -481,20 +482,20 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl}if err := h.templateService.UpdateTemplate(ctx, id, updates); err != nil {- if common.IsTemplateNotFoundError(err) {- return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())+ if errors.Is(err, common.ErrTemplateNotFound) {+ return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError((&common.TemplateUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update template").Error())}updated, err := h.templateService.GetTemplate(ctx, id)if err != nil {- return nil, huma.Error500InternalServerError((&common.TemplateRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template").Error())}var out template.Templateif mapErr := mapper.MapStruct(updated, &out); mapErr != nil {- return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}return &UpdateTemplateOutput{@@ -508,19 +509,19 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl// DeleteTemplate deletes a template.func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplateInput) (*DeleteTemplateOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}id, decodeErr := url.PathUnescape(input.ID)if decodeErr != nil {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}if err := h.templateService.DeleteTemplate(ctx, id); err != nil {- if common.IsTemplateNotFoundError(err) {- return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())+ if errors.Is(err, common.ErrTemplateNotFound) {+ return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError((&common.TemplateDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete template").Error())}return &DeleteTemplateOutput{@@ -536,33 +537,33 @@ func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTempl// DownloadTemplate downloads a remote template to local storage.func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTemplateInput) (*DownloadTemplateOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}id, decodeErr := url.PathUnescape(input.ID)if decodeErr != nil {- return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Template ID is required")}tmpl, err := h.templateService.GetTemplate(ctx, id)if err != nil {- if common.IsTemplateNotFoundError(err) {- return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())+ if errors.Is(err, common.ErrTemplateNotFound) {+ return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError((&common.TemplateDownloadError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to download template").Error())}if !tmpl.IsRemote {- return nil, huma.Error400BadRequest((&common.TemplateAlreadyLocalError{}).Error())+ return nil, huma.Error400BadRequest("Template is already local")}localTemplate, err := h.templateService.DownloadTemplate(ctx, tmpl)if err != nil {- return nil, huma.Error500InternalServerError((&common.TemplateDownloadError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to download template").Error())}var out template.Templateif mapErr := mapper.MapStruct(localTemplate, &out); mapErr != nil {- return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}return &DownloadTemplateOutput{@@ -596,11 +597,11 @@ func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefault// SaveDefaultTemplates saves the default compose and env templates.func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDefaultTemplatesInput) (*SaveDefaultTemplatesOutput, error) {if err := h.templateService.SaveComposeTemplate(input.Body.ComposeContent); err != nil {- return nil, huma.Error500InternalServerError((&common.DefaultTemplateSaveError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())}if err := h.templateService.SaveEnvTemplate(input.Body.EnvContent); err != nil {- return nil, huma.Error500InternalServerError((&common.DefaultTemplateSaveError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())}return &SaveDefaultTemplatesOutput{@@ -617,12 +618,12 @@ func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDfunc (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegistriesInput) (*GetTemplateRegistriesOutput, error) {registries, err := h.templateService.GetRegistries(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.RegistryFetchError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to fetch registry")}out, mapErr := mapper.MapSlice[models.TemplateRegistry, template.TemplateRegistry](registries)if mapErr != nil {- return nil, huma.Error500InternalServerError((&common.RegistryFetchError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError("Failed to fetch registry")}// Overlay the last fetch error from the in-memory tracker so the UI can@@ -652,12 +653,12 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplEnabled: input.Body.Enabled,}if err := h.templateService.CreateRegistry(ctx, registry); err != nil {- return nil, huma.Error500InternalServerError((&common.RegistryCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create registry").Error())}var out template.TemplateRegistryif mapErr := mapper.MapStruct(registry, &out); mapErr != nil {- return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}return &CreateTemplateRegistryOutput{@@ -671,7 +672,7 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl// UpdateRegistry updates a template registry.func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*UpdateTemplateRegistryOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Registry ID is required")}updates := &models.TemplateRegistry{@@ -682,9 +683,9 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl}if err := h.templateService.UpdateRegistry(ctx, input.ID, updates); err != nil {if err.Error() == "registry not found" {- return nil, huma.Error404NotFound((&common.RegistryNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Registry not found")}- return nil, huma.Error500InternalServerError((&common.RegistryUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update registry").Error())}return &UpdateTemplateRegistryOutput{@@ -700,14 +701,14 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl// DeleteRegistry deletes a template registry.func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*DeleteTemplateRegistryOutput, error) {if input.ID == "" {- return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Registry ID is required")}if err := h.templateService.DeleteRegistry(ctx, input.ID); err != nil {if err.Error() == "registry not found" {- return nil, huma.Error404NotFound((&common.RegistryNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Registry not found")}- return nil, huma.Error500InternalServerError((&common.RegistryDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete registry").Error())}return &DeleteTemplateRegistryOutput{@@ -723,17 +724,17 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTempl// FetchRegistry fetches templates from a remote registry URL.func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*FetchTemplateRegistryOutput, error) {if input.URL == "" {- return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())+ return nil, huma.Error400BadRequest("Query parameter is required")}body, err := h.templateService.FetchRaw(ctx, input.URL)if err != nil {- return nil, huma.Error502BadGateway((&common.RegistryFetchError{Err: err}).Error())+ return nil, huma.Error502BadGateway("Failed to fetch registry")}var registry template.RemoteRegistryif err := json.Unmarshal(body, ®istry); err != nil {- return nil, huma.Error502BadGateway((&common.InvalidJSONResponseError{Err: err}).Error())+ return nil, huma.Error502BadGateway("Invalid JSON response")}return &FetchTemplateRegistryOutput{diff --git a/backend/api/handlers/templates_test.go b/backend/api/handlers/templates_test.goindex 42795f677..35e5b023e 100644--- a/backend/api/handlers/templates_test.go+++ b/backend/api/handlers/templates_test.go@@ -141,7 +141,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.EchExpiresAt: time.Now().Add(time.Hour),}).Error)- authService := services.NewAuthService(userService, nil, nil, services.NewSessionService(databaseDB), nil, "test-secret", &config.Config{})+ authService := services.NewAuthService(userService, nil, nil, services.NewSessionService(databaseDB), nil, "test-secret", &config.Config{}, nil)templateService := services.NewTemplateService(context.Background(), nil, httpClient, nil)router := echo.New()diff --git a/backend/api/handlers/updater.go b/backend/api/handlers/updater.goindex 85d427b7a..097288783 100644--- a/backend/api/handlers/updater.go+++ b/backend/api/handlers/updater.go@@ -4,9 +4,9 @@ import ("context""net/http"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -116,7 +116,7 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)out, err := h.updaterService.ApplyPending(runtimeCtx, options)if err != nil {- return nil, huma.Error500InternalServerError((&common.UpdaterRunError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())}return &RunUpdaterOutput{@@ -148,7 +148,7 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdatehistory, err := h.updaterService.GetHistory(ctx, limit)if err != nil {- return nil, huma.Error500InternalServerError((&common.UpdaterHistoryError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get updater history").Error())}return &GetUpdaterHistoryOutput{@@ -164,7 +164,7 @@ func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateContaruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)if err != nil {- return nil, huma.Error500InternalServerError((&common.UpdaterRunError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())}return &UpdateContainerOutput{diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.goindex a2f819f5f..cfacf5801 100644--- a/backend/api/handlers/users.go+++ b/backend/api/handlers/users.go@@ -2,13 +2,13 @@ package handlersimport ("context"- "errors""strings""time"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -169,7 +169,7 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Liusers, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list users").Error())}return &ListUsersOutput{@@ -191,7 +191,7 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*hashedPassword, err := h.userService.HashPassword(input.Body.Password)if err != nil {- return nil, huma.Error500InternalServerError((&common.PasswordHashError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to hash password")}userModel := &models.User{@@ -211,12 +211,12 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*createdUser, err := h.userService.CreateUser(ctx, userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to create user")}out, err := h.userService.ToUserResponseDto(ctx, *createdUser)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &CreateUserOutput{@@ -231,12 +231,12 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUserOutput, error) {userModel, err := h.userService.GetUserByID(ctx, input.UserID)if err != nil {- return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())+ return nil, huma.Error404NotFound("User not found")}out, err := h.userService.ToUserResponseDto(ctx, *userModel)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &GetUserOutput{@@ -251,7 +251,7 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUsefunc (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*UpdateUserOutput, error) {userModel, err := h.userService.GetUserByID(ctx, input.UserID)if err != nil {- return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())+ return nil, huma.Error404NotFound("User not found")}normalizedEmail, err := normalizeOptionalEmailInternal(input.Body.Email)@@ -279,7 +279,7 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*if input.Body.Password != nil && *input.Body.Password != "" {hashedPassword, err := h.userService.HashPassword(*input.Body.Password)if err != nil {- return nil, huma.Error500InternalServerError((&common.PasswordHashError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to hash password")}userModel.PasswordHash = hashedPassword}@@ -292,9 +292,9 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())}if errors.Is(err, services.ErrUserNotFound) {- return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())+ return nil, huma.Error404NotFound("User not found")}- return nil, huma.Error500InternalServerError((&common.UserUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to update user")}if h.authService != nil {@@ -303,7 +303,7 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*out, err := h.userService.ToUserResponseDto(ctx, *updatedUser)if err != nil {- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to map user")}return &UpdateUserOutput{@@ -321,9 +321,9 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())}if errors.Is(err, services.ErrUserNotFound) {- return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())+ return nil, huma.Error404NotFound("User not found")}- return nil, huma.Error500InternalServerError((&common.UserDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError("Failed to delete user")}if h.authService != nil {@@ -345,7 +345,7 @@ func (h *UserHandler) GetUserAvatar(ctx context.Context, input *GetUserAvatarInpdata, mimeType, err := h.userService.GetAvatar(ctx, input.UserID)if err != nil {if errors.Is(err, services.ErrUserNotFound) {- return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())+ return nil, huma.Error404NotFound("User not found")}return nil, huma.Error500InternalServerError("failed to retrieve avatar")}diff --git a/backend/api/handlers/variables.go b/backend/api/handlers/variables.goindex 9544617c6..586a514c1 100644--- a/backend/api/handlers/variables.go+++ b/backend/api/handlers/variables.go@@ -4,6 +4,7 @@ import ("context""net/http"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -279,7 +280,7 @@ func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *Gvars, err := h.variableService.ReadLocalEnvFile(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.GlobalVariablesRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve global variables").Error())}return &GetGlobalVariablesOutput{@@ -302,10 +303,10 @@ func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input}if err := h.variableService.WriteLocalEnvFile(ctx, input.Body.Variables); err != nil {- if common.IsInvalidEnvKeyError(err) {+ if errors.Is(err, common.ErrInvalidEnvKey) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError((&common.GlobalVariablesUpdateError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update global variables").Error())}return &UpdateGlobalVariablesOutput{@@ -320,11 +321,11 @@ func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, inputfunc variableMutationHTTPErrorInternal(err error) error {switch {- case common.IsInvalidEnvKeyError(err), common.IsGlobalVariableSecretValueRequiredError(err), common.IsGlobalVariableScopeRequiredError(err):+ case errors.Is(err, common.ErrInvalidEnvKey), errors.Is(err, common.ErrGlobalVariableSecretValueRequired), errors.Is(err, common.ErrGlobalVariableScopeRequired):return huma.Error400BadRequest(err.Error())- case common.IsGlobalVariableNotFoundError(err):+ case errors.Is(err, common.ErrGlobalVariableNotFound):return huma.Error404NotFound(err.Error())- case common.IsGlobalVariableConflictError(err):+ case errors.Is(err, common.ErrGlobalVariableConflict):return huma.Error409Conflict(err.Error())default:return huma.Error500InternalServerError(err.Error())diff --git a/backend/api/handlers/volumes.go b/backend/api/handlers/volumes.goindex a527fddfc..c9c63b963 100644--- a/backend/api/handlers/volumes.go+++ b/backend/api/handlers/volumes.go@@ -9,9 +9,9 @@ import ("strconv""strings"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -569,7 +569,7 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInputvolumes, paginationResp, counts, err := h.volumeService.ListVolumesPaginated(ctx, params, input.IncludeInternal)if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumeListError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list volumes").Error())}if volumes == nil {@@ -594,7 +594,7 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInputfunc (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*GetVolumeOutput, error) {vol, err := h.volumeService.GetVolumeByName(ctx, input.VolumeName)if err != nil {- return nil, huma.Error404NotFound((&common.VolumeNotFoundError{Err: err}).Error())+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Volume not found").Error())}return &GetVolumeOutput{@@ -641,7 +641,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInpreturn createErr})if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumeCreationError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create volume").Error())}response.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -679,7 +679,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInpreturn h.volumeService.DeleteVolume(runtimeCtx, input.VolumeName, input.Force, *user)})if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumeDeletionError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete volume").Error())}return &RemoveVolumeOutput{@@ -711,7 +711,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInpreturn pruneErr})if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumePruneError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune volumes").Error())}return &PruneVolumesOutput{@@ -730,7 +730,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInpfunc (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*GetVolumeUsageOutput, error) {inUse, containers, err := h.volumeService.GetVolumeUsage(ctx, input.VolumeName)if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumeUsageError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume usage").Error())}return &GetVolumeUsageOutput{@@ -748,7 +748,7 @@ func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsagfunc (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*GetVolumeUsageCountsOutput, error) {_, _, counts, err := h.volumeService.ListVolumesPaginated(ctx, pagination.QueryParams{}, input.IncludeInternal)if err != nil {- return nil, huma.Error500InternalServerError((&common.VolumeCountsError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume counts").Error())}return &GetVolumeUsageCountsOutput{diff --git a/backend/api/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.goindex 20200b9af..e3ed72bd6 100644--- a/backend/api/handlers/vulnerabilities.go+++ b/backend/api/handlers/vulnerabilities.go@@ -4,9 +4,9 @@ import ("context""net/http"+ "emperror.dev/errors""github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -261,7 +261,7 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.vulnerabilityService.ScanImage(runtimeCtx, input.EnvironmentID, input.ImageID, *user)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())}return &ScanImageOutput{@@ -288,7 +288,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetSsummaries, err := h.vulnerabilityService.GetScanSummariesByImageIDs(ctx, imageIDs)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())}return &GetScanSummariesOutput{@@ -305,11 +305,11 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetSfunc (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*GetScanResultOutput, error) {result, err := h.vulnerabilityService.GetScanResult(ctx, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if result == nil {- return nil, huma.Error404NotFound((&common.VulnerabilityScanNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Vulnerability scan not found")}return &GetScanResultOutput{@@ -324,11 +324,11 @@ func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanfunc (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*GetScanSummaryOutput, error) {summary, err := h.vulnerabilityService.GetScanSummary(ctx, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if summary == nil {- return nil, huma.Error404NotFound((&common.VulnerabilityScanNotFoundError{}).Error())+ return nil, huma.Error404NotFound("Vulnerability scan not found")}return &GetScanSummaryOutput{@@ -351,7 +351,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inpitems, paginationResp, err := h.vulnerabilityService.ListVulnerabilities(ctx, input.ImageID, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if items == nil {@@ -371,7 +371,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inpfunc (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*GetEnvironmentSummaryOutput, error) {summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if summary == nil {@@ -401,7 +401,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, inputitems, paginationResp, err := h.vulnerabilityService.ListAllVulnerabilities(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if items == nil {@@ -421,7 +421,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, inputfunc (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*ListAllVulnerabilityImageOptionsOutput, error) {items, err := h.vulnerabilityService.ListAllVulnerabilityImageOptions(ctx, input.Severity)if err != nil {- return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}if items == nil {diff --git a/backend/api/handlers/webhooks.go b/backend/api/handlers/webhooks.goindex 7ea79c70d..91e7366f6 100644--- a/backend/api/handlers/webhooks.go+++ b/backend/api/handlers/webhooks.go@@ -2,9 +2,10 @@ package handlersimport ("context"- "errors""net/http"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2"humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/models"diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.goindex ba59170c5..0e3dc41f0 100644--- a/backend/api/json_serializer.go+++ b/backend/api/json_serializer.go@@ -4,10 +4,11 @@ import (jsonv1 "encoding/json""encoding/json/jsontext"json "encoding/json/v2"- "errors""fmt""net/http"+ "emperror.dev/errors"+"github.com/labstack/echo/v4")diff --git a/backend/api/middleware/auth.go b/backend/api/middleware/auth.goindex 0a8df7726..9ea8b3792 100644--- a/backend/api/middleware/auth.go+++ b/backend/api/middleware/auth.go@@ -2,11 +2,12 @@ package middlewareimport ("context"- "errors""log/slog""net/http""strings"+ "emperror.dev/errors"+"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -338,7 +339,7 @@ func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *servi_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Application has been updated. Refreshing session.")return nil, true}- if common.IsSessionRevokedError(err) || common.IsTokenValidationError(err) {+ if errors.Is(err, common.ErrSessionRevoked) || errors.Is(err, common.ErrTokenValidation) {for _, cookieHeader := range cookie.BuildClearTokenCookieStringsFor(cookie.SecureCookieFromContext(ctx.Context())) {ctx.AppendHeader("Set-Cookie", cookieHeader)}diff --git a/backend/api/middleware/auth_test.go b/backend/api/middleware/auth_test.goindex bbb5a70e8..941e3f0ef 100644--- a/backend/api/middleware/auth_test.go+++ b/backend/api/middleware/auth_test.go@@ -142,7 +142,7 @@ func TestNewAuthBridge_UsesBearerWhenLoopbackProxySendsEnvironmentAccessToken(tsessionSvc := services.NewSessionService(db)jwtSecret := "test-secret-please-do-not-use-in-prod"- authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, &config.Config{JWTRefreshExpiry: 24 * time.Hour})+ authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, &config.Config{JWTRefreshExpiry: 24 * time.Hour}, nil)bearerToken := mintAuthBridgeTestTokenInternal(t, userSvc, sessionSvc, jwtSecret, "u-loopback")ps := authz.NewPermissionSet()@@ -321,7 +321,7 @@ func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {jwtSecret := "test-secret-please-do-not-use-in-prod"cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}- authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg)+ authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg, nil)_, err := userSvc.CreateUser(context.Background(), &models.User{BaseModel: models.BaseModel{ID: "u-logout"},@@ -409,7 +409,7 @@ func TestNewAuthBridge_VersionMismatchIsRecoverable(t *testing.T) {jwtSecret := "test-secret-please-do-not-use-in-prod"cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}- authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg)+ authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg, nil)_, err := userSvc.CreateUser(context.Background(), &models.User{BaseModel: models.BaseModel{ID: "u-ver"},diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.goindex 4eaf39b93..22efee02c 100644--- a/backend/api/webhooks_trigger.go+++ b/backend/api/webhooks_trigger.go@@ -1,9 +1,10 @@package apiimport (- "errors""net/http"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/api/handlers""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.goindex e3d1b5ce3..c244dac31 100644--- a/backend/api/ws/handler.go+++ b/backend/api/ws/handler.go@@ -3,7 +3,6 @@ package wsimport ("context"json "encoding/json/v2"- "errors""io""log/slog""net/http"@@ -14,6 +13,8 @@ import ("sync/atomic""time"+ "emperror.dev/errors"+"github.com/gorilla/websocket""github.com/labstack/echo/v4""github.com/samber/hot"@@ -22,7 +23,6 @@ import ("github.com/shirou/gopsutil/v4/host""github.com/shirou/gopsutil/v4/mem"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -361,7 +361,7 @@ func broadcastLogStreamErrorInternal(resourceLabel, errorPrefix string, resourcefunc (h *WebSocketHandler) ProjectLogs(c echo.Context) error {projectID := c.Param("projectId")if strings.TrimSpace(projectID) == "" {- return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": "Project ID is required"})}params := parseLogStreamParamsInternal(c)@@ -569,7 +569,7 @@ func mapLogLinesInternal[T any](ctx context.Context, lines <-chan string, transffunc (h *WebSocketHandler) ContainerLogs(c echo.Context) error {containerID := c.Param("containerId")if strings.TrimSpace(containerID) == "" {- return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": "Container ID is required"})}params := parseLogStreamParamsInternal(c)@@ -639,7 +639,7 @@ func (h *WebSocketHandler) ServiceLogs(c echo.Context) error {func (h *WebSocketHandler) ContainerStats(c echo.Context) error {containerID := c.Param("containerId")if strings.TrimSpace(containerID) == "" {- return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": "Container ID is required"})}conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)@@ -754,7 +754,7 @@ func (h *WebSocketHandler) runContainerStatsHubInternal(containerID string, hubfunc (h *WebSocketHandler) ContainerExec(c echo.Context) error {containerID := c.Param("containerId")if strings.TrimSpace(containerID) == "" {- return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": "Container ID is required"})}shell := queryParamWithDefaultInternal(c, "shell", "/bin/sh")@@ -808,14 +808,14 @@ func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancel// Create exec instanceexecID, err := h.containerService.CreateExec(ctx, containerID, []string{shell})if err != nil {- h.writeExecErrorInternal(conn, &common.ExecCreationError{Err: err})+ h.writeExecErrorInternal(conn, errors.WithMessage(err, "Error creating exec"))return}// Attach to execexecSession, err := h.containerService.AttachExec(ctx, containerID, execID)if err != nil {- h.writeExecErrorInternal(conn, &common.ExecAttachError{Err: err})+ h.writeExecErrorInternal(conn, errors.WithMessage(err, "Error attaching to exec"))return}cleanup := h.execCleanupFuncInternal(ctx, execSession, execID, containerID)diff --git a/backend/buildables/buildables.go b/backend/buildables/buildables.goindex 899d542f1..9f93aea82 100644--- a/backend/buildables/buildables.go+++ b/backend/buildables/buildables.go@@ -12,7 +12,7 @@ func HasBuildFeature(feature string) bool {if feature == "" || EnabledFeatures == "" {return false}- for _, value := range strings.Split(EnabledFeatures, ",") {+ for value := range strings.SplitSeq(EnabledFeatures, ",") {if strings.EqualFold(strings.TrimSpace(value), feature) {return true}diff --git a/backend/cli/health.go b/backend/cli/health.goindex a65cf42f4..fde7ccfa8 100644--- a/backend/cli/health.go+++ b/backend/cli/health.go@@ -2,8 +2,6 @@ package cliimport ("context"- "errors"- "fmt""net""net/http""net/url"@@ -11,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/spf13/cobra")@@ -52,7 +52,7 @@ func buildHealthURLInternal(cfg *config.Config) (string, error) {port = defaultHealthPort}if _, err := strconv.Atoi(port); err != nil {- return "", fmt.Errorf("invalid health port %q: %w", port, err)+ return "", errors.WrapIff(err, "invalid health port %q", port)}hostPort := net.JoinHostPort(healthHost, port)@@ -78,20 +78,20 @@ func runHealthCommandInternal(ctx context.Context, cfg *config.Config, timeout trequest, err := http.NewRequestWithContext(ctx, http.MethodHead, healthURL, nil)if err != nil {- return fmt.Errorf("health check request creation failed: %w", err)+ return errors.WrapIf(err, "health check request creation failed")}client := &http.Client{Timeout: timeout}resp, err := client.Do(request)if err != nil {- return fmt.Errorf("health check request failed: %w", err)+ return errors.WrapIf(err, "health check request failed")}defer func() {_ = resp.Body.Close()}()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("health check failed with status %d", resp.StatusCode)+ return errors.Errorf("health check failed with status %d", resp.StatusCode)}return nildiff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.goindex bc819d50c..71f657ff0 100644--- a/backend/cli/upgrade/upgrade.go+++ b/backend/cli/upgrade/upgrade.go@@ -2,13 +2,14 @@ package upgradeimport ("context"- "errors""fmt""log/slog""maps""strings""time"+ "emperror.dev/errors"+"github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/client"@@ -73,7 +74,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {// Connect to DockerdockerClient, err := client.New(client.FromEnv)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}defer func() { _ = dockerClient.Close() }()@@ -83,7 +84,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {slog.Info("Auto-detecting Arcane container...")targetContainer, err = findArcaneContainer(ctx, dockerClient)if err != nil {- return fmt.Errorf("failed to find Arcane container: %w", err)+ return errors.WrapIf(err, "failed to find Arcane container")}containerName = strings.TrimPrefix(targetContainer.Name, "/")slog.Info("Found Arcane container", "name", containerName, "id", targetContainer.ID[:12])@@ -92,7 +93,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {targetContainer = inspectResult.Containererr = inspectErrif err != nil {- return fmt.Errorf("failed to inspect container %s: %w", containerName, err)+ return errors.WrapIff(err, "failed to inspect container %s", containerName)}}@@ -106,13 +107,13 @@ func runUpgrade(cmd *cobra.Command, args []string) error {// Pull the new imageslog.Info("Pulling new image", "image", imageToPull)if err := pullImage(ctx, dockerClient, imageToPull); err != nil {- return fmt.Errorf("failed to pull image: %w", err)+ return errors.WrapIf(err, "failed to pull image")}// Perform the upgradeslog.Info("Starting container upgrade", "container", containerName)if err := upgradeContainer(ctx, dockerClient, targetContainer, imageToPull); err != nil {- return fmt.Errorf("failed to upgrade container: %w", err)+ return errors.WrapIf(err, "failed to upgrade container")}slog.Info("Upgrade completed successfully", "container", containerName, "image", imageToPull)@@ -363,7 +364,7 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldContahostConfig, sanitizedMemorySwappiness, engineInfo, err := libarcane.PrepareRecreateHostConfigForEngine(ctx, dockerClient, oldContainer.HostConfig)if err != nil {- return fmt.Errorf("prepare host config: %w", err)+ return errors.WrapIf(err, "prepare host config")}if sanitizedMemorySwappiness {slog.Info("Stripped unsupported host config field for recreate",@@ -430,14 +431,14 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldContafmt.Println("PROGRESS:65:Renaming old container")slog.Info("Renaming old container", "from", originalName, "to", oldName)if _, err := dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: oldName}); err != nil {- return fmt.Errorf("rename old container: %w", err)+ return errors.WrapIf(err, "rename old container")}fmt.Println("PROGRESS:70:Stopping old container")slog.Info("Stopping old container", "name", oldName)if _, err := dockerClient.ContainerStop(ctx, oldContainer.ID, client.ContainerStopOptions{Timeout: new(10)}); err != nil {_, _ = dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: originalName})- return fmt.Errorf("stop old container: %w", err)+ return errors.WrapIf(err, "stop old container")}fmt.Println("PROGRESS:75:Creating new container")@@ -452,7 +453,7 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta// Try to restart and restore old container on failure_, _ = dockerClient.ContainerStart(ctx, oldContainer.ID, client.ContainerStartOptions{})_, _ = dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: originalName})- return fmt.Errorf("create new container: %w", err)+ return errors.WrapIf(err, "create new container")}fmt.Println("PROGRESS:80:Starting new container")@@ -462,7 +463,7 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})_, _ = dockerClient.ContainerStart(ctx, oldContainer.ID, client.ContainerStartOptions{})_, _ = dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: originalName})- return fmt.Errorf("start new container: %w", err)+ return errors.WrapIf(err, "start new container")}// Wait a moment for the new container to initializediff --git a/backend/frontend/frontend.go b/backend/frontend/frontend.goindex 95184dd13..e4d7a9f2b 100644--- a/backend/frontend/frontend.go+++ b/backend/frontend/frontend.go@@ -4,7 +4,6 @@ package frontendimport ("embed"- "errors""fmt""io/fs""net/http"@@ -12,6 +11,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/labstack/echo/v4")@@ -26,7 +27,7 @@ const indexHtmlFileConstant = "index.html"func RegisterFrontend(e *echo.Echo) error {distFS, err := fs.Sub(frontendFS, "dist")if err != nil {- return fmt.Errorf("failed to create sub FS: %w", err)+ return errors.WrapIf(err, "failed to create sub FS")}cacheMaxAge := time.Hour * 24diff --git a/backend/frontend/shared.go b/backend/frontend/shared.goindex d3ebfc1b9..c3eebb4d4 100644--- a/backend/frontend/shared.go+++ b/backend/frontend/shared.go@@ -1,5 +1,5 @@package frontend-import "errors"+import "emperror.dev/errors"-var ErrFrontendNotIncluded = errors.New("frontend is not included")+const ErrFrontendNotIncluded = errors.Sentinel("frontend is not included")diff --git a/backend/go.mod b/backend/go.modindex 30c335360..16cf16be5 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -8,6 +8,8 @@ replace ()require (+ emperror.dev/emperror v0.33.0+ emperror.dev/errors v0.8.1github.com/aws/aws-sdk-go-v2/config v1.32.30github.com/aws/aws-sdk-go-v2/credentials v1.19.29github.com/aws/aws-sdk-go-v2/service/ecr v1.59.1diff --git a/backend/go.sum b/backend/go.sumindex e64df11ff..119dcba1c 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -2,6 +2,11 @@ connectrpc.com/connect v1.19.2 h1:McQ83FGdzL+t60peksi0gXC7MQ/iLKgLduAnThbM0mo=connectrpc.com/connect v1.19.2/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=+emperror.dev/emperror v0.33.0 h1:urYop6KLYxKVpZbt9ADC4eVG3WDnJFE6Ye3j07wUu/I=+emperror.dev/emperror v0.33.0/go.mod h1:CeOIKPcppTE8wn+3xBNcdzdHMMIP77sLOHS0Ik56m+w=+emperror.dev/errors v0.8.0/go.mod h1:YcRvLPh626Ubn2xqtoprejnA5nFha+TJ+2vew48kWuE=+emperror.dev/errors v0.8.1 h1:UavXZ5cSX/4u9iyvH6aDcuGkVjeexUGJ7Ij7G4VfQT0=+emperror.dev/errors v0.8.1/go.mod h1:YcRvLPh626Ubn2xqtoprejnA5nFha+TJ+2vew48kWuE=github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=@@ -586,6 +591,7 @@ go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=+go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=@@ -594,6 +600,7 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=+go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 9f09e1c6a..3ef5fd471 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -2,8 +2,6 @@ package bootstrapimport ("context"- "errors"- "fmt""io""log/slog""net/http"@@ -11,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/moby/moby/client""github.com/subosito/gotenv"@@ -32,7 +32,7 @@ import (func Bootstrap(ctx context.Context) error {if err := gotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("load .env: %w", err)+ return errors.WrapIf(err, "load .env")}cfg := config.Load()runtimeIdentityCfg := &startup.RuntimeIdentityConfig{@@ -44,7 +44,7 @@ func Bootstrap(ctx context.Context) error {ProjectsDirectory: cfg.ProjectsDirectory,}if err := startup.ApplyRequestedRuntimeIdentity(ctx, runtimeIdentityCfg); err != nil {- return fmt.Errorf("apply runtime identity: %w", err)+ return errors.WrapIf(err, "apply runtime identity")}cfg.DockerConfig = runtimeIdentityCfg.DockerConfig@@ -62,7 +62,7 @@ func Bootstrap(ctx context.Context) error {db, err := initializeDBAndMigrate(appCtx, cfg)if err != nil {cancelApp()- return fmt.Errorf("failed to initialize database: %w", err)+ return errors.WrapIf(err, "failed to initialize database")}defer func() {cancelApp()@@ -76,7 +76,7 @@ func Bootstrap(ctx context.Context) error {startCtx, cancelStart := context.WithTimeout(ctx, 5*time.Minute)defer cancelStart()if err := app.Start(startCtx); err != nil {- return fmt.Errorf("start application: %w", err)+ return errors.WrapIf(err, "start application")}select {@@ -89,7 +89,7 @@ func Bootstrap(ctx context.Context) error {stopCtx, cancelStop := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)defer cancelStop()if err := app.Stop(stopCtx); err != nil {- return fmt.Errorf("stop application: %w", err)+ return errors.WrapIf(err, "stop application")}slog.InfoContext(context.WithoutCancel(appCtx), "Arcane shutdown complete")@@ -405,7 +405,7 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClreq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pairURL, nil)if err != nil {- return fmt.Errorf("failed to create pairing request: %w", err)+ return errors.WrapIf(err, "failed to create pairing request")}req.Header.Set("X-Api-Key", cfg.AgentToken)@@ -421,14 +421,14 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClEdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,}, 10*time.Second)if edgeErr != nil {- return fmt.Errorf("failed to configure edge pairing client: %w", edgeErr)+ return errors.WrapIf(edgeErr, "failed to configure edge pairing client")}httpClient = edgeClient}resp, err := httpClient.Do(req)if err != nil {- return fmt.Errorf("pairing request failed: %w", err)+ return errors.WrapIf(err, "pairing request failed")}defer func() { _ = resp.Body.Close() }()@@ -444,13 +444,13 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClslog.InfoContext(ctx, "Agent already paired with manager", "managerUrl", cfg.ManagerApiUrl)return nil}- return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))+ return errors.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))case http.StatusUnauthorized:// Invalid API key - could be already paired with a different key, or key was deleted// This is not fatal; the agent can still function if it has a valid token configuredslog.DebugContext(ctx, "Pairing skipped - API key not recognized (agent may already be paired)", "managerUrl", cfg.ManagerApiUrl)return nildefault:- return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))+ return errors.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))}}diff --git a/backend/internal/bootstrap/db_bootstrap.go b/backend/internal/bootstrap/db_bootstrap.goindex c29269d79..fa23ff7f6 100644--- a/backend/internal/bootstrap/db_bootstrap.go+++ b/backend/internal/bootstrap/db_bootstrap.go@@ -2,9 +2,9 @@ package bootstrapimport ("context"- "fmt""log/slog"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database")@@ -14,7 +14,7 @@ func initializeDBAndMigrate(ctx context.Context, cfg *config.Config) (*database.AllowDowngrade: cfg.AllowDowngrade,})if err != nil {- return nil, fmt.Errorf("failed to initialize database: %w", err)+ return nil, errors.WrapIf(err, "failed to initialize database")}slog.Info("Database initialized successfully")diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex b6a5397ec..4c3b7bb44 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -3,10 +3,11 @@ package bootstrapimport ("context"json "encoding/json/v2"- "errors""fmt""log/slog"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -60,7 +61,7 @@ func registerEdgeTunnelRoutes(if len(evt.MetadataJSON) > 0 {metadata = models.JSON{}if err := json.Unmarshal(evt.MetadataJSON, &metadata); err != nil {- return fmt.Errorf("failed to decode event metadata: %w", err)+ return errors.WrapIf(err, "failed to decode event metadata")}}@@ -79,7 +80,7 @@ func registerEdgeTunnelRoutes(}_, err := eventService.CreateEvent(ctx, req)if err != nil {- return fmt.Errorf("failed to persist synced event: %w", err)+ return errors.WrapIf(err, "failed to persist synced event")}return nil}@@ -221,7 +222,7 @@ func createEdgeConnectionEvent(ctx context.Context, eventService *services.EventEnvironmentID: &envID,})if err != nil {- return fmt.Errorf("failed to create edge lifecycle event: %w", err)+ return errors.WrapIf(err, "failed to create edge lifecycle event")}return nildiff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.goindex 2725623f3..da188e45b 100644--- a/backend/internal/bootstrap/logger_bootstrap.go+++ b/backend/internal/bootstrap/logger_bootstrap.go@@ -8,6 +8,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/lmittmann/tint"slogGorm "github.com/orandin/slog-gorm"@@ -25,6 +26,51 @@ type attrFilterHandler struct {dropKeys map[string]struct{}}+type stackAttrHandler struct {+ handler slog.Handler+ attrs []slog.Attr+}++func (h *stackAttrHandler) Enabled(ctx context.Context, level slog.Level) bool {+ return h.handler.Enabled(ctx, level)+}++func (h *stackAttrHandler) Handle(ctx context.Context, r slog.Record) error {+ if r.Level < slog.LevelError {+ return h.handler.Handle(ctx, r)+ }++ attrs := append([]slog.Attr(nil), h.attrs...)+ r.Attrs(func(attr slog.Attr) bool {+ attrs = append(attrs, attr)+ return true+ })++ var stackTracer interface{ StackTrace() errors.StackTrace }+ for _, attr := range attrs {+ attr.Value = attr.Value.Resolve()+ if attr.Value.Kind() != slog.KindAny {+ continue+ }+ err, ok := attr.Value.Any().(error)+ if ok && errors.As(err, &stackTracer) {+ r.AddAttrs(slog.String("stack", fmt.Sprintf("%+v", stackTracer.StackTrace())))+ break+ }+ }++ return h.handler.Handle(ctx, r)+}++func (h *stackAttrHandler) WithAttrs(attrs []slog.Attr) slog.Handler {+ boundAttrs := append(append([]slog.Attr(nil), h.attrs...), attrs...)+ return &stackAttrHandler{handler: h.handler.WithAttrs(attrs), attrs: boundAttrs}+}++func (h *stackAttrHandler) WithGroup(name string) slog.Handler {+ return &stackAttrHandler{handler: h.handler.WithGroup(name), attrs: h.attrs}+}+func (h *requestLogHandler) Enabled(ctx context.Context, level slog.Level) bool {return h.handler.Enabled(ctx, level)}@@ -178,6 +224,7 @@ func SetupSlogLogger(cfg *config.Config) {}h = &requestLogHandler{handler: h}+ h = &stackAttrHandler{handler: h}slog.SetDefault(slog.New(h))}diff --git a/backend/internal/bootstrap/logger_bootstrap_test.go b/backend/internal/bootstrap/logger_bootstrap_test.goindex ceb102bdb..4898c906d 100644--- a/backend/internal/bootstrap/logger_bootstrap_test.go+++ b/backend/internal/bootstrap/logger_bootstrap_test.go@@ -6,6 +6,7 @@ import ("testing""time"+ "emperror.dev/errors""github.com/stretchr/testify/assert")@@ -62,3 +63,17 @@ func TestRequestLogHandler(t *testing.T) {assert.Contains(t, buf.String(), "msg=\"plain record\" component=scheduler")})}++func TestStackAttrHandlerAddsStackToErrorRecords(t *testing.T) {+ var buf bytes.Buffer+ logger := slog.New(&stackAttrHandler{+ handler: slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}),+ })+ err := errors.New("boom")++ logger.InfoContext(t.Context(), "info", "error", err)+ assert.NotContains(t, buf.String(), "stack=")++ logger.ErrorContext(t.Context(), "failed", "err", err)+ assert.Contains(t, buf.String(), "stack=")+}diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex b9d511fee..aa7992ccf 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -2,13 +2,14 @@ package bootstrapimport ("context"- "errors""log/slog""net""net/http""path""strings"+ "emperror.dev/errors"+"github.com/labstack/echo/v4"echomiddleware "github.com/labstack/echo/v4/middleware"slogecho "github.com/samber/slog-echo"diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.goindex b7c3b5527..4298bc6a1 100644--- a/backend/internal/bootstrap/server_bootstrap.go+++ b/backend/internal/bootstrap/server_bootstrap.go@@ -3,13 +3,14 @@ package bootstrapimport ("context""crypto/tls"- "errors""log/slog""net""net/http""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1"diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 528473682..a5a281e1a 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1,2105 +1,99 @@package commonimport (- "errors""fmt"-)--type AuthSettingsCheckError struct {- Err error-}--func (e *AuthSettingsCheckError) Error() string {- return "Failed to check authentication settings"-}--type LocalAuthDisabledError struct{}--func (e *LocalAuthDisabledError) Error() string {- return "Local authentication is disabled"-}--type InvalidCredentialsError struct{}--func (e *InvalidCredentialsError) Error() string {- return "Invalid username or password"-}--type AuthFailedError struct {- Err error-}--func (e *AuthFailedError) Error() string {- return "Authentication failed"-}--type UserMappingError struct {- Err error-}--func (e *UserMappingError) Error() string {- return "Failed to map user"-}--type NotAuthenticatedError struct{}--func (e *NotAuthenticatedError) Error() string {- return "Not authenticated"-}--type UserRetrievalError struct {- Err error-}--func (e *UserRetrievalError) Error() string {- return "Failed to get user information"-}--type InvalidTokenError struct{}--func (e *InvalidTokenError) Error() string {- return "Invalid or expired refresh token"-}--type InvalidTokenClaimsError struct{}--func (e *InvalidTokenClaimsError) Error() string {- return "Invalid token claims"-}--type AccessTokenSubjectError struct{}--func (e *AccessTokenSubjectError) Error() string {- return "Not an access token"-}--type RefreshTokenSubjectError struct{}--func (e *RefreshTokenSubjectError) Error() string {- return "Not a refresh token"-}--type MissingTokenUserIDError struct{}--func (e *MissingTokenUserIDError) Error() string {- return "Missing user ID in token"-}--type MissingRefreshTokenIDError struct{}--func (e *MissingRefreshTokenIDError) Error() string {- return "Missing refresh token ID"-}--type MissingTokenSessionIDError struct{}--func (e *MissingTokenSessionIDError) Error() string {- return "Missing session ID in token"-}--type SessionServiceUnavailableError struct{}--func (e *SessionServiceUnavailableError) Error() string {- return "Session service is not configured"-}--func IsTokenValidationError(err error) bool {- return isErrorTypeInternal[*InvalidTokenClaimsError](err) ||- isErrorTypeInternal[*AccessTokenSubjectError](err) ||- isErrorTypeInternal[*RefreshTokenSubjectError](err) ||- isErrorTypeInternal[*MissingTokenUserIDError](err) ||- isErrorTypeInternal[*MissingRefreshTokenIDError](err) ||- isErrorTypeInternal[*MissingTokenSessionIDError](err)-}--type TokenRefreshError struct {- Err error-}--func (e *TokenRefreshError) Error() string {- return "Failed to refresh token"-}--type SessionRevokedError struct{}--func (e *SessionRevokedError) Error() string {- return "Session has been revoked"-}--func IsSessionRevokedError(err error) bool {- return isErrorTypeInternal[*SessionRevokedError](err)-}--func isErrorTypeInternal[T error](err error) bool {- var target T- return errors.As(err, &target)-}--type PasswordRequiredError struct{}--func (e *PasswordRequiredError) Error() string {- return "Current password is required"-}--type IncorrectPasswordError struct{}--func (e *IncorrectPasswordError) Error() string {- return "Current password is incorrect"-}--type PasswordChangeError struct {- Err error-}--func (e *PasswordChangeError) Error() string {- return "Failed to change password"-}--type ImageRetrievalError struct {- Err error-}--func (e *ImageRetrievalError) Error() string {- return "Failed to retrieve image"-}--type BuildHistoryListError struct {- Err error-}--func (e *BuildHistoryListError) Error() string {- return "Failed to list build history"-}--type BuildHistoryRetrievalError struct {- Err error-}--func (e *BuildHistoryRetrievalError) Error() string {- return "Failed to retrieve build history"-}--type ContainerIDRequiredError struct{}--func (e *ContainerIDRequiredError) Error() string {- return "Container ID is required"-}--type ExecCreationError struct {- Err error-}--func (e *ExecCreationError) Error() string {- return fmt.Sprintf("Error creating exec: %v", e.Err)-}--type ExecAttachError struct {- Err error-}--func (e *ExecAttachError) Error() string {- return fmt.Sprintf("Error attaching to exec: %v", e.Err)-}--type ContainerListError struct {- Err error-}--func (e *ContainerListError) Error() string {- return fmt.Sprintf("Failed to list containers: %v", e.Err)-}--type ContainerRetrievalError struct {- Err error-}--func (e *ContainerRetrievalError) Error() string {- return fmt.Sprintf("Failed to retrieve container: %v", e.Err)-}--type ContainerStartError struct {- Err error-}--func (e *ContainerStartError) Error() string {- return fmt.Sprintf("Failed to start container: %v", e.Err)-}--type ContainerStopError struct {- Err error-}--func (e *ContainerStopError) Error() string {- return fmt.Sprintf("Failed to stop container: %v", e.Err)-}--type ContainerRestartError struct {- Err error-}--func (e *ContainerRestartError) Error() string {- return fmt.Sprintf("Failed to restart container: %v", e.Err)-}--type ContainerKillError struct {- Err error-}--func (e *ContainerKillError) Error() string {- return fmt.Sprintf("Failed to kill container: %v", e.Err)-}--type ContainerPauseError struct {- Err error-}--func (e *ContainerPauseError) Error() string {- return fmt.Sprintf("Failed to pause container: %v", e.Err)-}--type ContainerUnpauseError struct {- Err error-}--func (e *ContainerUnpauseError) Error() string {- return fmt.Sprintf("Failed to unpause container: %v", e.Err)-}--type ContainerRedeployError struct {- Err error-}--func (e *ContainerRedeployError) Error() string {- return fmt.Sprintf("Failed to redeploy container: %v", e.Err)-}--type ArcaneSelfRedeployError struct{}--func (e *ArcaneSelfRedeployError) Error() string {- return "arcane cannot redeploy itself; use the system upgrade flow (Settings -> Updates) instead"-}--type ContainerDeleteError struct {- Err error-}--func (e *ContainerDeleteError) Error() string {- return fmt.Sprintf("Failed to delete container: %v", e.Err)-}--type ContainerStatusCountsError struct {- Err error-}--func (e *ContainerStatusCountsError) Error() string {- return fmt.Sprintf("Failed to get container counts: %v", e.Err)-}--type InvalidPortFormatError struct {- Err error-}--func (e *InvalidPortFormatError) Error() string {- return fmt.Sprintf("Invalid port format: %v", e.Err)-}--type ContainerCreationError struct {- Err error-}--func (e *ContainerCreationError) Error() string {- return fmt.Sprintf("Failed to create container: %v", e.Err)-}--type RegistryListError struct {- Err error-}--func (e *RegistryListError) Error() string {- return fmt.Sprintf("Failed to list registries: %v", e.Err)-}--type RegistryMappingError struct {- Err error-}--func (e *RegistryMappingError) Error() string {- return fmt.Sprintf("Failed to map registry: %v", e.Err)-}--type RegistryRetrievalError struct {- Err error-}--func (e *RegistryRetrievalError) Error() string {- return fmt.Sprintf("Failed to retrieve registry: %v", e.Err)-}--type RegistryCreationError struct {- Err error-}--func (e *RegistryCreationError) Error() string {- return fmt.Sprintf("Failed to create registry: %v", e.Err)-}--type RegistryUpdateError struct {- Err error-}--func (e *RegistryUpdateError) Error() string {- return fmt.Sprintf("Failed to update registry: %v", e.Err)-}--type RegistryDeletionError struct {- Err error-}--func (e *RegistryDeletionError) Error() string {- return fmt.Sprintf("Failed to delete registry: %v", e.Err)-}--type TokenDecryptionError struct {- Err error-}--func (e *TokenDecryptionError) Error() string {- return fmt.Sprintf("Failed to decrypt token: %v", e.Err)-}--type RegistryTestError struct {- Err error-}--func (e *RegistryTestError) Error() string {- return fmt.Sprintf("Registry test failed: %v", e.Err)-}--type RegistrySyncError struct {- Err error-}--func (e *RegistrySyncError) Error() string {- return fmt.Sprintf("Failed to sync registries: %v", e.Err)-}--type QueryParameterRequiredError struct{}--func (e *QueryParameterRequiredError) Error() string {- return "Query parameter is required"-}--type EnvironmentNotFoundError struct{}--func (e *EnvironmentNotFoundError) Error() string {- return "Environment not found"-}--type EnvironmentDisabledError struct{}--func (e *EnvironmentDisabledError) Error() string {- return "Environment is disabled"-}--type EnvironmentUnauthorizedError struct{}--func (e *EnvironmentUnauthorizedError) Error() string {- return "Authentication required to access remote environments"-}--type EnvironmentForbiddenError struct{}--func (e *EnvironmentForbiddenError) Error() string {- return "You don't have permission to perform this action on this environment"-}--type EnvironmentInvalidProxyTargetError struct {- Err error-}--func (e *EnvironmentInvalidProxyTargetError) Error() string {- return fmt.Sprintf("Invalid proxy target URL: %v", e.Err)-}--func (e *EnvironmentInvalidProxyTargetError) Unwrap() error { return e.Err }--type EnvironmentProxyRequestCreationError struct {- Err error-}--func (e *EnvironmentProxyRequestCreationError) Error() string {- return fmt.Sprintf("Failed to create proxy request: %v", e.Err)-}--type EnvironmentProxyRequestFailedError struct {- Err error-}--func (e *EnvironmentProxyRequestFailedError) Error() string {- return fmt.Sprintf("Proxy request failed: %v", e.Err)-}--type EdgeAgentNotConnectedError struct{}--func (e *EdgeAgentNotConnectedError) Error() string {- return "Edge agent is not connected"-}--type AgentTokenPersistenceError struct {- Err error-}--func (e *AgentTokenPersistenceError) Error() string {- return "Failed to persist agent token"-}--type EnvironmentCreationError struct {- Err error-}--func (e *EnvironmentCreationError) Error() string {- return fmt.Sprintf("Failed to create environment: %v", e.Err)-}--type EnvironmentMappingError struct {- Err error-}--func (e *EnvironmentMappingError) Error() string {- return "Failed to map environment"-}--type EnvironmentListError struct {- Err error-}--func (e *EnvironmentListError) Error() string {- return "Failed to fetch environments"-}--type EnvironmentUpdateError struct {- Err error-}--func (e *EnvironmentUpdateError) Error() string {- return "Failed to update environment"-}--type LocalEnvironmentDeletionError struct{}--func (e *LocalEnvironmentDeletionError) Error() string {- return "Cannot delete local environment"-}--type EnvironmentDeletionError struct {- Err error-}--func (e *EnvironmentDeletionError) Error() string {- return fmt.Sprintf("Failed to delete environment: %v", e.Err)-}--type HeartbeatUpdateError struct {- Err error-}--func (e *HeartbeatUpdateError) Error() string {- return "Failed to update heartbeat"-}--type EventListError struct {- Err error-}--func (e *EventListError) Error() string {- return fmt.Sprintf("Failed to list events: %v", e.Err)-}--type EventStatsError struct {- Err error-}--func (e *EventStatsError) Error() string {- return fmt.Sprintf("Failed to load event statistics: %v", e.Err)-}--type EnvironmentIDRequiredError struct{}--func (e *EnvironmentIDRequiredError) Error() string {- return "Environment ID is required"-}--type EventCreationError struct {- Err error-}--func (e *EventCreationError) Error() string {- return fmt.Sprintf("Failed to create event: %v", e.Err)-}--type EventIDRequiredError struct{}--func (e *EventIDRequiredError) Error() string {- return "Event ID is required"-}--type EventDeletionError struct {- Err error-}--func (e *EventDeletionError) Error() string {- return fmt.Sprintf("Failed to delete event: %v", e.Err)-}--type ImageListError struct {- Err error-}--func (e *ImageListError) Error() string {- return fmt.Sprintf("Failed to list images: %v", e.Err)-}--type ImageNotFoundError struct {- Err error-}--func (e *ImageNotFoundError) Error() string {- return fmt.Sprintf("Image not found: %v", e.Err)-}--type ImageRemovalError struct {- Err error-}--func (e *ImageRemovalError) Error() string {- return fmt.Sprintf("Failed to remove image: %v", e.Err)-}--type ImagePruneError struct {- Err error-}--func (e *ImagePruneError) Error() string {- return fmt.Sprintf("Failed to prune images: %v", e.Err)-}--type ImageUsageCountsError struct {- Err error-}--func (e *ImageUsageCountsError) Error() string {- return fmt.Sprintf("Failed to get image usage counts: %v", e.Err)-}--type FileUploadReadError struct {- Err error-}--func (e *FileUploadReadError) Error() string {- return fmt.Sprintf("Failed to read upload: %v", e.Err)-}--type NoFileUploadedError struct{}--func (e *NoFileUploadedError) Error() string {- return "No file uploaded"-}--type InvalidFileFormatError struct{}--func (e *InvalidFileFormatError) Error() string {- return "Invalid file format. Only Docker image tar archives are allowed (.tar, .tar.gz, .tgz, .tar.xz)"-}--type ImageLoadError struct {- Err error-}--func (e *ImageLoadError) Error() string {- return fmt.Sprintf("Failed to load image: %v", e.Err)-}--type ImageRefRequiredError struct{}--func (e *ImageRefRequiredError) Error() string {- return "imageRef query parameter is required"-}--type ImageUpdateCheckError struct {- Err error-}--func (e *ImageUpdateCheckError) Error() string {- return fmt.Sprintf("Failed to check image update: %v", e.Err)-}--type ImageIDRequiredError struct{}--func (e *ImageIDRequiredError) Error() string {- return "imageId parameter is required"-}--type BatchImageUpdateCheckError struct {- Err error-}--func (e *BatchImageUpdateCheckError) Error() string {- return fmt.Sprintf("Failed to check image updates: %v", e.Err)-}--type AllImageUpdateCheckError struct {- Err error-}--func (e *AllImageUpdateCheckError) Error() string {- return fmt.Sprintf("Failed to check all images: %v", e.Err)-}--type UpdateSummaryError struct {- Err error-}--func (e *UpdateSummaryError) Error() string {- return fmt.Sprintf("Failed to get update summary: %v", e.Err)-}--type NetworkListError struct {- Err error-}--func (e *NetworkListError) Error() string {- return fmt.Sprintf("Failed to list networks: %v", e.Err)-}--type NetworkNotFoundError struct {- Err error-}--func (e *NetworkNotFoundError) Error() string {- return fmt.Sprintf("Network not found: %v", e.Err)-}--type NetworkMappingError struct {- Err error-}--func (e *NetworkMappingError) Error() string {- return fmt.Sprintf("Failed to map network: %v", e.Err)-}--type NetworkCreationError struct {- Err error-}--func (e *NetworkCreationError) Error() string {- return fmt.Sprintf("Failed to create network: %v", e.Err)-}--type NetworkRemovalError struct {- Err error-}--func (e *NetworkRemovalError) Error() string {- return fmt.Sprintf("Failed to remove network: %v", e.Err)-}--type NetworkUsageCountsError struct {- Err error-}--func (e *NetworkUsageCountsError) Error() string {- return fmt.Sprintf("Failed to get network counts: %v", e.Err)-}--type NetworkPruneError struct {- Err error-}--func (e *NetworkPruneError) Error() string {- return fmt.Sprintf("Failed to prune networks: %v", e.Err)-}--type NotificationSettingsListError struct {- Err error-}--func (e *NotificationSettingsListError) Error() string {- return fmt.Sprintf("Failed to list notification settings: %v", e.Err)-}--type InvalidNotificationProviderError struct{}--func (e *InvalidNotificationProviderError) Error() string {- return "invalid provider"-}--type NotificationSettingsNotFoundError struct{}--func (e *NotificationSettingsNotFoundError) Error() string {- return "Settings not found"-}--type NotificationSettingsUpdateError struct {- Err error-}--func (e *NotificationSettingsUpdateError) Error() string {- return fmt.Sprintf("Failed to update notification settings: %v", e.Err)-}--type NotificationSettingsDeletionError struct {- Err error-}--func (e *NotificationSettingsDeletionError) Error() string {- return fmt.Sprintf("Failed to delete notification settings: %v", e.Err)-}--type NotificationTestError struct {- Err error-}--func (e *NotificationTestError) Error() string {- return fmt.Sprintf("Failed to send test notification: %v", e.Err)-}--type OidcStatusError struct {- Err error-}--func (e *OidcStatusError) Error() string {- return fmt.Sprintf("Failed to retrieve OIDC status: %v", e.Err)-}--type OidcStatusCheckError struct{}--func (e *OidcStatusCheckError) Error() string {- return "Failed to check OIDC status"-}--type OidcDisabledError struct{}--func (e *OidcDisabledError) Error() string {- return "OIDC authentication is disabled"-}--type OidcAuthUrlGenerationError struct {- Err error-}--func (e *OidcAuthUrlGenerationError) Error() string {- return fmt.Sprintf("Failed to generate OIDC auth URL: %v", e.Err)-}--type OidcStateCookieError struct{}--func (e *OidcStateCookieError) Error() string {- return "Missing or invalid OIDC state cookie"-}--type OidcCallbackError struct {- Err error-}--func (e *OidcCallbackError) Error() string {- return fmt.Sprintf("OIDC callback failed: %v", e.Err)-}--type OidcConfigError struct{}--func (e *OidcConfigError) Error() string {- return "Failed to get OIDC configuration"-}--type ProjectListError struct {- Err error-}--func (e *ProjectListError) Error() string {- return fmt.Sprintf("Failed to list projects: %v", e.Err)-}--type ProjectIDRequiredError struct{}--func (e *ProjectIDRequiredError) Error() string {- return "Project ID is required"-}--type ProjectDownError struct {- Err error-}--func (e *ProjectDownError) Error() string {- return fmt.Sprintf("Failed to bring down project: %v", e.Err)-}--type ProjectCreationError struct {- Err error-}--func (e *ProjectCreationError) Error() string {- return fmt.Sprintf("Failed to create project: %v", e.Err)-}--type ProjectDetailsError struct {- Err error-}--func (e *ProjectDetailsError) Error() string {- return fmt.Sprintf("Failed to get project details: %v", e.Err)-}--type ProjectFileBadRequestError struct {- Err error-}--func (e *ProjectFileBadRequestError) Error() string {- return fmt.Sprintf("Invalid project file request: %v", e.Err)-}--type ProjectFileForbiddenError struct {- Err error-}--func (e *ProjectFileForbiddenError) Error() string {- return fmt.Sprintf("Forbidden project file path: %v", e.Err)-}--type ProjectFileNotFoundError struct{}--func (e *ProjectFileNotFoundError) Error() string {- return "Project file not found"-}--type ProjectFileConflictError struct {- Err error-}--func (e *ProjectFileConflictError) Error() string {- if e.Err == nil {- return "Project files changed; refresh the project and try again"- }- return e.Err.Error()-}--type ProjectComposeFileNotFoundError struct {- Err error-}--func (e *ProjectComposeFileNotFoundError) Error() string {- return fmt.Sprintf("Project compose file not found: %v", e.Err)-}--func (e *ProjectComposeFileNotFoundError) Unwrap() error {- return e.Err-}--// ComposeFileNotFoundError indicates a directory contains no recognizable-// compose file at all (zero candidates).-type ComposeFileNotFoundError struct {- Dir string-}--func (e *ComposeFileNotFoundError) Error() string {- return fmt.Sprintf("no compose file found in %q", e.Dir)-}--// AmbiguousComposeFileError indicates a directory contains multiple custom-named-// compose candidates that cannot be disambiguated. The directory still holds-// compose content, so callers must not treat this as "no project here" (e.g. by-// deleting the project record).-type AmbiguousComposeFileError struct {- Dir string-}--func (e *AmbiguousComposeFileError) Error() string {- return fmt.Sprintf("multiple custom compose files found in %q", e.Dir)-}--type ProjectDiscoveryError struct {- Dir string- Err error-}--func (e *ProjectDiscoveryError) Error() string {- return fmt.Sprintf("Failed to discover projects in %q: %v", e.Dir, e.Err)-}--func (e *ProjectDiscoveryError) Unwrap() error {- return e.Err-}--type ProjectRedeploymentError struct {- Err error-}--func (e *ProjectRedeploymentError) Error() string {- return fmt.Sprintf("Failed to redeploy project: %v", e.Err)-}--type ProjectDestroyError struct {- Err error-}--func (e *ProjectDestroyError) Error() string {- return fmt.Sprintf("Failed to destroy project: %v", e.Err)-}--type ProjectUpdateError struct {- Err error-}--func (e *ProjectUpdateError) Error() string {- return fmt.Sprintf("Failed to update project: %v", e.Err)-}--type ProjectRestartError struct {- Err error-}--func (e *ProjectRestartError) Error() string {- return fmt.Sprintf("Failed to restart project: %v", e.Err)-}--type ProjectArchiveError struct {- Err error-}--func (e *ProjectArchiveError) Error() string {- return fmt.Sprintf("Failed to archive project: %v", e.Err)-}--type ProjectUnarchiveError struct {- Err error-}--func (e *ProjectUnarchiveError) Error() string {- return fmt.Sprintf("Failed to unarchive project: %v", e.Err)-}--type ProjectMustBeStoppedError struct{}--func (e *ProjectMustBeStoppedError) Error() string {- return "project must be stopped before archiving"-}--type ProjectArchivedError struct{}--func (e *ProjectArchivedError) Error() string {- return "project is archived and must be unarchived before this action"-}--type ProjectStatusCountsError struct {- Err error-}--func (e *ProjectStatusCountsError) Error() string {- return fmt.Sprintf("Failed to get project status counts: %v", e.Err)-}--type SettingsMappingError struct {- Err error-}--func (e *SettingsMappingError) Error() string {- return "Failed to map settings"-}--type AuthSettingsUpdateError struct{}--func (e *AuthSettingsUpdateError) Error() string {- return "Authentication settings can only be updated from the main environment"-}--type SettingsUpdateError struct {- Err error-}--func (e *SettingsUpdateError) Error() string {- return "Failed to update settings"-}--type DockerConnectionError struct {- Err error-}--func (e *DockerConnectionError) Error() string {- return fmt.Sprintf("Failed to connect to Docker: %v", e.Err)-}--type DockerPingError struct {- Err error-}--func (e *DockerPingError) Error() string {- return fmt.Sprintf("Docker is not responsive: %v", e.Err)-}--type DockerVersionError struct {- Err error-}--func (e *DockerVersionError) Error() string {- return fmt.Sprintf("Failed to get Docker version: %v", e.Err)-}--type DockerInfoError struct {- Err error-}--func (e *DockerInfoError) Error() string {- return fmt.Sprintf("Failed to get Docker info: %v", e.Err)-}--type ContainerStartAllError struct {- Err error-}--func (e *ContainerStartAllError) Error() string {- return fmt.Sprintf("Failed to start containers: %v", e.Err)-}--type ContainerStartStoppedError struct {- Err error-}--func (e *ContainerStartStoppedError) Error() string {- return fmt.Sprintf("Failed to start stopped containers: %v", e.Err)-}--type ContainerStopAllError struct {- Err error-}--func (e *ContainerStopAllError) Error() string {- return fmt.Sprintf("Failed to stop containers: %v", e.Err)-}--type DockerRunParseError struct {- Err error-}--func (e *DockerRunParseError) Error() string {- return "Failed to parse docker run command. Please check the syntax."-}--type DockerComposeConversionError struct {- Err error-}--func (e *DockerComposeConversionError) Error() string {- return "Failed to convert to Docker Compose format."-}--type UpgradeCheckError struct {- Err error-}--func (e *UpgradeCheckError) Error() string {- return fmt.Sprintf("Failed to check for updates: %v", e.Err)-}--type UpgradeTriggerError struct {- Err error-}--func (e *UpgradeTriggerError) Error() string {- return fmt.Sprintf("Failed to initiate upgrade: %v", e.Err)-}--type NotRunningInDockerError struct{}--func (e *NotRunningInDockerError) Error() string {- return "arcane is not running in a Docker container"-}--type ArcaneContainerNotFoundError struct{}--func (e *ArcaneContainerNotFoundError) Error() string {- return "could not find Arcane container"-}--type UpgradeInProgressError struct{}--func (e *UpgradeInProgressError) Error() string {- return "an upgrade is already in progress"-}--func IsUpgradeInProgressError(err error) bool {- return isErrorTypeInternal[*UpgradeInProgressError](err)-}--type UpdateAllInProgressError struct{}--func (e *UpdateAllInProgressError) Error() string {- return "an update-all job is already in progress"-}--func IsUpdateAllInProgressError(err error) bool {- return isErrorTypeInternal[*UpdateAllInProgressError](err)-}--type DockerSocketAccessError struct{}--func (e *DockerSocketAccessError) Error() string {- return "docker socket is not accessible"-}--type TemplateListError struct {- Err error-}--func (e *TemplateListError) Error() string {- return fmt.Sprintf("Failed to get templates: %v", e.Err)-}--type TemplateMappingError struct {- Err error-}--func (e *TemplateMappingError) Error() string {- return fmt.Sprintf("Failed to map templates: %v", e.Err)-}--type TemplateIDRequiredError struct{}--func (e *TemplateIDRequiredError) Error() string {- return "Template ID is required"-}--type TemplateNotFoundError struct {- Err error-}--func (e *TemplateNotFoundError) Error() string {- if e.Err != nil {- return fmt.Sprintf("Template not found: %v", e.Err)- }- return "Template not found"-}--func IsTemplateNotFoundError(err error) bool {- return isErrorTypeInternal[*TemplateNotFoundError](err)-}--type TemplateRetrievalError struct {- Err error-}--func (e *TemplateRetrievalError) Error() string {- return fmt.Sprintf("Failed to get template: %v", e.Err)-}--type TemplateContentError struct {- Err error-}--func (e *TemplateContentError) Error() string {- return fmt.Sprintf("Failed to get template content: %v", e.Err)-}--type TemplateCreationError struct {- Err error-}--func (e *TemplateCreationError) Error() string {- return fmt.Sprintf("Failed to create template: %v", e.Err)-}--type TemplateUpdateError struct {- Err error-}--func (e *TemplateUpdateError) Error() string {- return fmt.Sprintf("Failed to update template: %v", e.Err)-}--type TemplateDeletionError struct {- Err error-}--func (e *TemplateDeletionError) Error() string {- return fmt.Sprintf("Failed to delete template: %v", e.Err)-}--type DefaultTemplateSaveError struct {- Err error-}--func (e *DefaultTemplateSaveError) Error() string {- return fmt.Sprintf("Failed to save default template: %v", e.Err)-}--type RegistryIDRequiredError struct{}--func (e *RegistryIDRequiredError) Error() string {- return "Registry ID is required"-}--type RegistryNotFoundError struct {- Err error-}--func (e *RegistryNotFoundError) Error() string {- if e.Err != nil {- return fmt.Sprintf("Registry not found: %v", e.Err)- }- return "Registry not found"-}--type RegistryFetchError struct {- Err error-}--func (e *RegistryFetchError) Error() string {- return "Failed to fetch registry"-}--type InvalidJSONResponseError struct {- Err error-}--func (e *InvalidJSONResponseError) Error() string {- return "Invalid JSON response"-}--type UnsafeRemoteURLError struct {- Err error-}--func (e *UnsafeRemoteURLError) Error() string {- return fmt.Sprintf("Remote URL is not allowed: %v", e.Err)-}--type TemplateAlreadyLocalError struct{}--func (e *TemplateAlreadyLocalError) Error() string {- return "Template is already local"-}--type TemplateDownloadError struct {- Err error-}--func (e *TemplateDownloadError) Error() string {- return fmt.Sprintf("Failed to download template: %v", e.Err)-}--type GlobalVariablesRetrievalError struct {- Err error-}--func (e *GlobalVariablesRetrievalError) Error() string {- return fmt.Sprintf("Failed to retrieve global variables: %v", e.Err)-}--type GlobalVariablesUpdateError struct {- Err error-}--func (e *GlobalVariablesUpdateError) Error() string {- return fmt.Sprintf("Failed to update global variables: %v", e.Err)-}--type InvalidEnvKeyError struct {- Key string-}--func (e *InvalidEnvKeyError) Error() string {- return fmt.Sprintf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", e.Key)-}--func IsInvalidEnvKeyError(err error) bool {- return isErrorTypeInternal[*InvalidEnvKeyError](err)-}--type GlobalVariableNotFoundError struct{}--func (e *GlobalVariableNotFoundError) Error() string {- return "Global variable not found"-}--func IsGlobalVariableNotFoundError(err error) bool {- return isErrorTypeInternal[*GlobalVariableNotFoundError](err)-}--type GlobalVariableConflictError struct {- Key string-}--func (e *GlobalVariableConflictError) Error() string {- return fmt.Sprintf("A variable named %q already exists for an overlapping environment scope", e.Key)-}--func IsGlobalVariableConflictError(err error) bool {- return isErrorTypeInternal[*GlobalVariableConflictError](err)-}--// GlobalVariableScopeRequiredError is returned when a variable is scoped to-// specific environments but no environment IDs were provided.-type GlobalVariableScopeRequiredError struct{}--func (e *GlobalVariableScopeRequiredError) Error() string {- return "At least one environment is required when a variable is not scoped to all environments"-}--func IsGlobalVariableScopeRequiredError(err error) bool {- return isErrorTypeInternal[*GlobalVariableScopeRequiredError](err)-}--// GlobalVariableSecretValueRequiredError is returned when a secret variable is-// switched to readable without providing a replacement value.-type GlobalVariableSecretValueRequiredError struct{}--func (e *GlobalVariableSecretValueRequiredError) Error() string {- return "A new value is required when making a secret variable readable"-}--func IsGlobalVariableSecretValueRequiredError(err error) bool {- return isErrorTypeInternal[*GlobalVariableSecretValueRequiredError](err)-}--type UpdaterRunError struct {- Err error-}--func (e *UpdaterRunError) Error() string {- return fmt.Sprintf("Failed to run updater: %v", e.Err)-}--type UpdaterHistoryError struct {- Err error-}--func (e *UpdaterHistoryError) Error() string {- return fmt.Sprintf("Failed to get updater history: %v", e.Err)-}--type UpdaterDockerServiceUnavailableError struct{}--func (e *UpdaterDockerServiceUnavailableError) Error() string {- return "docker service unavailable"-}--type UpdaterDockerClientUnavailableError struct{}--func (e *UpdaterDockerClientUnavailableError) Error() string {- return "docker client unavailable"-}--type UpdaterImageServiceUnavailableError struct{}--func (e *UpdaterImageServiceUnavailableError) Error() string {- return "image service unavailable"-}--type UpdaterDatabaseUnavailableError struct{}--func (e *UpdaterDatabaseUnavailableError) Error() string {- return "database unavailable"-}--type UpdaterServiceUnavailableError struct{}--func (e *UpdaterServiceUnavailableError) Error() string {- return "updater service unavailable"-}--type UpdaterProjectServiceUnavailableError struct{}--func (e *UpdaterProjectServiceUnavailableError) Error() string {- return "project service unavailable"-}--type UserListError struct {- Err error-}--func (e *UserListError) Error() string {- return fmt.Sprintf("Failed to list users: %v", e.Err)-}--type PasswordHashError struct {- Err error-}--func (e *PasswordHashError) Error() string {- return "Failed to hash password"-}--type UserCreationError struct {- Err error-}--func (e *UserCreationError) Error() string {- return "Failed to create user"-}--type UserNotFoundError struct{}--func (e *UserNotFoundError) Error() string {- return "User not found"-}--type UserUpdateError struct {- Err error-}--func (e *UserUpdateError) Error() string {- return "Failed to update user"-}--type UserDeletionError struct {- Err error-}--func (e *UserDeletionError) Error() string {- return "Failed to delete user"-}--type VolumeListError struct {- Err error-}--func (e *VolumeListError) Error() string {- return fmt.Sprintf("Failed to list volumes: %v", e.Err)-}--type VolumeNotFoundError struct {- Err error-}--func (e *VolumeNotFoundError) Error() string {- if e.Err != nil {- return fmt.Sprintf("Volume not found: %v", e.Err)- }- return "Volume not found"-}--type VolumeCreationError struct {- Err error-}--func (e *VolumeCreationError) Error() string {- return fmt.Sprintf("Failed to create volume: %v", e.Err)-}--type VolumeDeletionError struct {- Err error-}--func (e *VolumeDeletionError) Error() string {- return fmt.Sprintf("Failed to delete volume: %v", e.Err)-}--type VolumePruneError struct {- Err error-}--func (e *VolumePruneError) Error() string {- return fmt.Sprintf("Failed to prune volumes: %v", e.Err)-}--type VolumeUsageError struct {- Err error-}--func (e *VolumeUsageError) Error() string {- return fmt.Sprintf("Failed to get volume usage: %v", e.Err)-}--type VolumeCountsError struct {- Err error-}--func (e *VolumeCountsError) Error() string {- return fmt.Sprintf("Failed to get volume counts: %v", e.Err)-}--type ApiKeyListError struct {- Err error-}--func (e *ApiKeyListError) Error() string {- return fmt.Sprintf("Failed to list API keys: %v", e.Err)-}--type ApiKeyCreationError struct {- Err error-}--func (e *ApiKeyCreationError) Error() string {- return "Failed to create API key"-}--type ApiKeyNotFoundError struct{}--func (e *ApiKeyNotFoundError) Error() string {- return "API key not found"-}--type ApiKeyUpdateError struct {- Err error-}--func (e *ApiKeyUpdateError) Error() string {- return "Failed to update API key"-}--type ApiKeyDeletionError struct {- Err error-}--func (e *ApiKeyDeletionError) Error() string {- return "Failed to delete API key"-}--type GitRepositoryListError struct {- Err error-}--func (e *GitRepositoryListError) Error() string {- return fmt.Sprintf("Failed to list git repositories: %v", e.Err)-}--type GitRepositoryCreationError struct {- Err error-}--func (e *GitRepositoryCreationError) Error() string {- return "Failed to create git repository"-}--type GitRepositoryRetrievalError struct {- Err error-}--func (e *GitRepositoryRetrievalError) Error() string {- return "Failed to retrieve git repository"-}--type GitRepositoryUpdateError struct {- Err error-}--func (e *GitRepositoryUpdateError) Error() string {- return "Failed to update git repository"-}--type GitRepositoryDeletionError struct {- Err error-}--func (e *GitRepositoryDeletionError) Error() string {- return "Failed to delete git repository"-}--type GitRepositoryTestError struct {- Err error-}--func (e *GitRepositoryTestError) Error() string {- return fmt.Sprintf("Failed to test git repository connection: %v", e.Err)-}--type GitRepositoryMappingError struct {- Err error-}--func (e *GitRepositoryMappingError) Error() string {- return "Failed to map git repository"-}--type GitRepositorySyncError struct {- Err error-}--func (e *GitRepositorySyncError) Error() string {- return fmt.Sprintf("Failed to sync git repositories: %v", e.Err)-}--type GitOpsSyncListError struct {- Err error-}--func (e *GitOpsSyncListError) Error() string {- return fmt.Sprintf("Failed to list GitOps syncs: %v", e.Err)-}--type GitOpsSyncCreationError struct {- Err error-}--func (e *GitOpsSyncCreationError) Error() string {- return fmt.Sprintf("Failed to create GitOps sync: %v", e.Err)-}--type GitOpsSyncRetrievalError struct {- Err error-}--func (e *GitOpsSyncRetrievalError) Error() string {- return "Failed to retrieve GitOps sync"-}--type GitOpsSyncUpdateError struct {- Err error-}--func (e *GitOpsSyncUpdateError) Error() string {- return fmt.Sprintf("Failed to update GitOps sync: %v", e.Err)-}--type GitOpsSyncDeletionError struct {- Err error-}--func (e *GitOpsSyncDeletionError) Error() string {- return "Failed to delete GitOps sync"-}--type GitOpsSyncPerformError struct {- Err error-}--func (e *GitOpsSyncPerformError) Error() string {- return "Failed to perform GitOps sync"-}--type GitOpsSyncProjectBindingBrokenError struct {- Err error-}--func (e *GitOpsSyncProjectBindingBrokenError) Error() string {- if e.Err != nil {- return fmt.Sprintf("GitOps sync project binding broken: %v", e.Err)- }- return "GitOps sync project binding broken"-}--func (e *GitOpsSyncProjectBindingBrokenError) Unwrap() error {- return e.Err-}--type GitOpsSyncStatusError struct {- Err error-}--func (e *GitOpsSyncStatusError) Error() string {- return "Failed to get GitOps sync status"-}--type GitOpsSyncBrowseError struct {- Err error-}--func (e *GitOpsSyncBrowseError) Error() string {- return "Failed to browse GitOps sync files"-}+ "io"-type GitOpsSyncMappingError struct {- Err error-}--func (e *GitOpsSyncMappingError) Error() string {- return "Failed to map GitOps sync"-}--// RedeployAfterSyncFailedError is returned by the internal GitOps sync flow-// when the file sync succeeded but the auto-redeploy that follows it failed-// (e.g. a pre-deploy lifecycle hook returned non-zero). Callers surface this on-// the sync row's LastSyncError so the failure is visible from the GitOps UI-// rather than only in the logs.-type RedeployAfterSyncFailedError struct {- Err error-}+ "emperror.dev/errors"+)-func (e *RedeployAfterSyncFailedError) Error() string {- if e == nil || e.Err == nil {- return "redeploy failed"- }+const (+ ErrBadRequest = errors.Sentinel("kind: bad request")+ ErrValidation = errors.Sentinel("kind: validation failed")+ ErrUnauthorized = errors.Sentinel("kind: unauthorized")+ ErrForbidden = errors.Sentinel("kind: forbidden")+ ErrNotFound = errors.Sentinel("kind: not found")+ ErrConflict = errors.Sentinel("kind: conflict")+ ErrTimeout = errors.Sentinel("kind: timeout")+ ErrUnavailable = errors.Sentinel("kind: service unavailable")+)- return "redeploy failed: " + e.Err.Error()+type classified struct {+ kind error+ err error}-func (e *RedeployAfterSyncFailedError) Unwrap() error {- if e == nil {+// Classify gives err a stable semantic identity without changing its message.+func Classify(kind, err error) error {+ if err == nil {return nil}-- return e.Err-}--type VulnerabilityScanError struct {- Err error-}--func (e *VulnerabilityScanError) Error() string {- return fmt.Sprintf("Failed to scan image for vulnerabilities: %v", e.Err)-}--type VulnerabilityScanNotFoundError struct{}--func (e *VulnerabilityScanNotFoundError) Error() string {- return "Vulnerability scan not found"-}--type VulnerabilityScanRetrievalError struct {- Err error-}--func (e *VulnerabilityScanRetrievalError) Error() string {- return fmt.Sprintf("Failed to retrieve vulnerability scan: %v", e.Err)-}--type SwarmNotEnabledError struct{}--func (e *SwarmNotEnabledError) Error() string {- return "Swarm mode is not enabled"-}--type SwarmManagerRequiredError struct{}--func (e *SwarmManagerRequiredError) Error() string {- return "Swarm manager access required"-}--func IsSwarmNotEnabledError(err error) bool {- return isErrorTypeInternal[*SwarmNotEnabledError](err)-}--func IsSwarmManagerRequiredError(err error) bool {- return isErrorTypeInternal[*SwarmManagerRequiredError](err)-}--type SwarmConfigImmutableError struct{}--func (e *SwarmConfigImmutableError) Error() string {- return "Swarm configs are immutable; create a new config and update services to use it"-}--type SwarmSecretImmutableError struct{}--func (e *SwarmSecretImmutableError) Error() string {- return "Swarm secrets are immutable; create a new secret and update services to use it"-}--func IsSwarmConfigImmutableError(err error) bool {- return isErrorTypeInternal[*SwarmConfigImmutableError](err)-}--func IsSwarmSecretImmutableError(err error) bool {- return isErrorTypeInternal[*SwarmSecretImmutableError](err)-}--type SwarmServiceListError struct {- Err error-}--func (e *SwarmServiceListError) Error() string {- return fmt.Sprintf("Failed to list swarm services: %v", e.Err)-}--type SwarmServiceNotFoundError struct {- Err error-}--func (e *SwarmServiceNotFoundError) Error() string {- return fmt.Sprintf("Swarm service not found: %v", e.Err)-}--type SwarmServiceCreateError struct {- Err error-}--func (e *SwarmServiceCreateError) Error() string {- return fmt.Sprintf("Failed to create swarm service: %v", e.Err)-}--type SwarmServiceUpdateError struct {- Err error-}--func (e *SwarmServiceUpdateError) Error() string {- return fmt.Sprintf("Failed to update swarm service: %v", e.Err)-}--type SwarmServiceRemoveError struct {- Err error-}--func (e *SwarmServiceRemoveError) Error() string {- return fmt.Sprintf("Failed to remove swarm service: %v", e.Err)-}--type SwarmNodeListError struct {- Err error-}--func (e *SwarmNodeListError) Error() string {- return fmt.Sprintf("Failed to list swarm nodes: %v", e.Err)-}--type SwarmNodeNotFoundError struct {- Err error-}--func (e *SwarmNodeNotFoundError) Error() string {- return fmt.Sprintf("Swarm node not found: %v", e.Err)-}--type SwarmTaskListError struct {- Err error-}--func (e *SwarmTaskListError) Error() string {- return fmt.Sprintf("Failed to list swarm tasks: %v", e.Err)-}--type SwarmStackListError struct {- Err error-}--func (e *SwarmStackListError) Error() string {- return fmt.Sprintf("Failed to list swarm stacks: %v", e.Err)-}--type SwarmStackDeployError struct {- Err error-}--func (e *SwarmStackDeployError) Error() string {- return fmt.Sprintf("Failed to deploy swarm stack: %v", e.Err)-}--type SwarmInspectError struct {- Err error-}--func (e *SwarmInspectError) Error() string {- return fmt.Sprintf("Failed to inspect swarm: %v", e.Err)-}--// ----- RBAC / role service errors -------type RoleNotFoundError struct{}--func (e *RoleNotFoundError) Error() string {- return "Role not found"-}--func IsRoleNotFoundError(err error) bool {- return isErrorTypeInternal[*RoleNotFoundError](err)-}--type RoleBuiltInError struct{}--func (e *RoleBuiltInError) Error() string {- return "Built-in role cannot be modified"-}--func IsRoleBuiltInError(err error) bool {- return isErrorTypeInternal[*RoleBuiltInError](err)-}--type RoleNameTakenError struct{}--func (e *RoleNameTakenError) Error() string {- return "Role name already in use"-}--func IsRoleNameTakenError(err error) bool {- return isErrorTypeInternal[*RoleNameTakenError](err)-}--type UnknownPermissionError struct {- Perm string-}--func (e *UnknownPermissionError) Error() string {- return "Unknown permission: " + e.Perm-}--func IsUnknownPermissionError(err error) bool {- return isErrorTypeInternal[*UnknownPermissionError](err)-}--// RolePermissionEscalationError is returned when a caller attempts to author a-// role containing a permission they do not themselves hold at global scope.-// Used by the CreateRole and UpdateRole handlers as defense-in-depth alongside-// the RequireGlobalAdmin middleware.-type RolePermissionEscalationError struct {- Perm string-}--func (e *RolePermissionEscalationError) Error() string {- return "cannot grant a permission you do not hold: " + e.Perm-}--func IsRolePermissionEscalationError(err error) bool {- return isErrorTypeInternal[*RolePermissionEscalationError](err)-}--// InvalidRoleAssignmentError is returned when SetUserAssignments is called with-// a RoleID or EnvironmentID that doesn't exist in the database. Surfaces as a-// 400 Bad Request so callers see a descriptive message instead of an opaque-// FK-violation 500 from the underlying tx.Create.-type InvalidRoleAssignmentError struct {- RoleID string- EnvironmentID string-}--func (e *InvalidRoleAssignmentError) Error() string {- if e.RoleID != "" {- return fmt.Sprintf("invalid role assignment: role %q does not exist", e.RoleID)- }- if e.EnvironmentID != "" {- return fmt.Sprintf("invalid role assignment: environment %q does not exist", e.EnvironmentID)+ if kind == nil {+ return err}- return "invalid role assignment"-}--func IsInvalidRoleAssignmentError(err error) bool {- return isErrorTypeInternal[*InvalidRoleAssignmentError](err)-}--type FederatedCredentialNotFoundError struct{}--func (e *FederatedCredentialNotFoundError) Error() string {- return "federated credential not found"-}--func IsErrorFederatedCredentialNotFound(err error) bool {- return isErrorTypeInternal[*FederatedCredentialNotFoundError](err)-}--type FederatedCredentialInvalidError struct{}--func (e *FederatedCredentialInvalidError) Error() string {- return "invalid federated credential"-}--func IsErrorFederatedCredentialInvalid(err error) bool {- return isErrorTypeInternal[*FederatedCredentialInvalidError](err)-}--// DefaultTransportTypeError is returned when http.DefaultTransport is not the-// expected *http.Transport concrete type and therefore cannot be cloned.-type DefaultTransportTypeError struct{}--func (e *DefaultTransportTypeError) Error() string {- return "http.DefaultTransport is not *http.Transport"-}--// ManagerCALockTypeError is returned when a cached manager CA lock value is not-// the expected *sync.Mutex.-type ManagerCALockTypeError struct{}--func (e *ManagerCALockTypeError) Error() string {- return "manager CA lock value is not *sync.Mutex"-}--// ECRTokenResultTypeError is returned when a deduplicated ECR token refresh-// yields a value that is not the expected *ecrTokenResult.-type ECRTokenResultTypeError struct{}--func (e *ECRTokenResultTypeError) Error() string {- return "unexpected ECR token result type"-}--type FederatedCredentialInvalidRequestError struct{}--func (e *FederatedCredentialInvalidRequestError) Error() string {- return "invalid federated token exchange request"-}--func IsErrorFederatedCredentialInvalidRequest(err error) bool {- return isErrorTypeInternal[*FederatedCredentialInvalidRequestError](err)-}--type FederatedCredentialInvalidGrantError struct{}--func (e *FederatedCredentialInvalidGrantError) Error() string {- return "invalid federated token grant"-}--func IsErrorFederatedCredentialInvalidGrant(err error) bool {- return isErrorTypeInternal[*FederatedCredentialInvalidGrantError](err)-}--type FederatedCredentialPermissionEscalationError struct{}--func (e *FederatedCredentialPermissionEscalationError) Error() string {- return "cannot map a federated credential to a role you do not hold"-}--func IsErrorFederatedCredentialPermissionEscalation(err error) bool {- return isErrorTypeInternal[*FederatedCredentialPermissionEscalationError](err)-}--type OidcMappingNotFoundError struct{}--func (e *OidcMappingNotFoundError) Error() string {- return "OIDC role mapping not found"-}--func IsOidcMappingNotFoundError(err error) bool {- return isErrorTypeInternal[*OidcMappingNotFoundError](err)-}--// OidcMappingEnvManagedError is returned when an API caller attempts to mutate-// an OIDC role mapping that was declared via OIDC_ROLE_MAPPINGS. Env-managed-// rows can only be changed by editing the env var and restarting.-type OidcMappingEnvManagedError struct{}--func (e *OidcMappingEnvManagedError) Error() string {- return "OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"-}--func IsOidcMappingEnvManagedError(err error) bool {- return isErrorTypeInternal[*OidcMappingEnvManagedError](err)-}--type NoGlobalAdminRemainsError struct{}--func (e *NoGlobalAdminRemainsError) Error() string {- return "At least one user must retain a global Admin role assignment"-}--func IsNoGlobalAdminRemainsError(err error) bool {- return isErrorTypeInternal[*NoGlobalAdminRemainsError](err)+ return &classified{kind: kind, err: err}}-// AgentDashboardUnsupportedError is emitted on the aggregated dashboard stream-// when a remote agent does not expose the dashboard snapshot endpoint, which-// typically means the agent runs an older Arcane version than the manager.-type AgentDashboardUnsupportedError struct{}+func (e *classified) Error() string { return e.err.Error() }-func (e *AgentDashboardUnsupportedError) Error() string {- return "Agent does not provide the dashboard endpoint — the agent is likely running an older Arcane version and should be upgraded"-}--// DashboardSnapshotUnavailableError is returned when a dashboard snapshot-// request completes without producing a usable snapshot payload.-type DashboardSnapshotUnavailableError struct{}+func (e *classified) Unwrap() error { return e.err }-func (e *DashboardSnapshotUnavailableError) Error() string {- return "dashboard snapshot not available"-}+func (e *classified) Is(target error) bool { return errors.Is(e.kind, target) }-// ActivitySlotWaitTimeoutError is returned when a queued activity gave up-// waiting for a per-environment concurrency slot, typically because-// long-running work (e.g. an auto-update run) is holding every slot.-type ActivitySlotWaitTimeoutError struct{}+func (e *classified) Format(s fmt.State, verb rune) {+ if verb == 'v' && s.Flag('+') {+ _, _ = fmt.Fprintf(s, "%+v", e.err)+ return+ }-func (e *ActivitySlotWaitTimeoutError) Error() string {- return "timed out waiting for a free activity slot; other long-running activities are holding all slots"+ switch verb {+ case 'q':+ _, _ = fmt.Fprintf(s, "%q", e.err)+ case 's', 'v':+ _, _ = io.WriteString(s, e.err.Error())+ }}-// ImageScanInProgressError is returned when a manual image update check is-// requested while another scan is already running.-type ImageScanInProgressError struct{}--func (e *ImageScanInProgressError) Error() string {- return "an image update check is already in progress"-}+var (+ ErrTokenValidation = Classify(ErrUnauthorized, errors.Sentinel("Invalid token claims"))+ ErrSessionRevoked = Classify(ErrUnauthorized, errors.Sentinel("Session has been revoked"))+ ErrUpgradeInProgress = Classify(ErrConflict, errors.Sentinel("an upgrade is already in progress"))+ ErrUpdateAllInProgress = Classify(ErrConflict, errors.Sentinel("an update-all job is already in progress"))+ ErrTemplateNotFound = Classify(ErrNotFound, errors.Sentinel("Template not found"))+ ErrInvalidEnvKey = Classify(ErrValidation, errors.Sentinel("Invalid environment key"))+ ErrGlobalVariableNotFound = Classify(ErrNotFound, errors.Sentinel("Global variable not found"))+ ErrGlobalVariableConflict = Classify(ErrConflict, errors.Sentinel("Global variable already exists"))+ ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.Sentinel("At least one environment is required when a variable is not scoped to all environments"))+ ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.Sentinel("A new value is required when making a secret variable readable"))+ ErrSwarmNotEnabled = Classify(ErrBadRequest, errors.Sentinel("Swarm mode is not enabled"))+ ErrSwarmManagerRequired = Classify(ErrForbidden, errors.Sentinel("Swarm manager access required"))+ ErrSwarmConfigImmutable = Classify(ErrConflict, errors.Sentinel("Swarm configs are immutable; create a new config and update services to use it"))+ ErrSwarmSecretImmutable = Classify(ErrConflict, errors.Sentinel("Swarm secrets are immutable; create a new secret and update services to use it"))+ ErrRoleNotFound = Classify(ErrNotFound, errors.Sentinel("Role not found"))+ ErrRoleBuiltIn = Classify(ErrForbidden, errors.Sentinel("Built-in role cannot be modified"))+ ErrRoleNameTaken = Classify(ErrConflict, errors.Sentinel("Role name already in use"))+ ErrUnknownPermission = Classify(ErrValidation, errors.Sentinel("Unknown permission"))+ ErrRolePermissionEscalation = Classify(ErrForbidden, errors.Sentinel("cannot grant a permission you do not hold"))+ ErrInvalidRoleAssignment = Classify(ErrBadRequest, errors.Sentinel("invalid role assignment"))+ ErrFederatedCredentialNotFound = Classify(ErrNotFound, errors.Sentinel("federated credential not found"))+ ErrFederatedCredentialInvalid = Classify(ErrValidation, errors.Sentinel("invalid federated credential"))+ ErrFederatedCredentialInvalidRequest = Classify(ErrBadRequest, errors.Sentinel("invalid federated token exchange request"))+ ErrFederatedCredentialInvalidGrant = Classify(ErrUnauthorized, errors.Sentinel("invalid federated token grant"))+ ErrFederatedCredentialPermissionEscalation = Classify(ErrForbidden, errors.Sentinel("cannot map a federated credential to a role you do not hold"))+ ErrOidcMappingNotFound = Classify(ErrNotFound, errors.Sentinel("OIDC role mapping not found"))+ ErrOidcMappingEnvManaged = Classify(ErrConflict, errors.Sentinel("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))+ ErrNoGlobalAdminRemains = Classify(ErrConflict, errors.Sentinel("At least one user must retain a global Admin role assignment"))+ ErrProjectArchived = Classify(ErrConflict, errors.Sentinel("project is archived and must be unarchived before this action"))+ ErrProjectMustBeStopped = Classify(ErrConflict, errors.Sentinel("project must be stopped before archiving"))+ ErrProjectFileConflict = Classify(ErrConflict, errors.Sentinel("Project files changed; refresh the project and try again"))+ ErrProjectFileForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden project file path"))+ ErrProjectFileBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid project file request"))+ ErrProjectFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project file not found"))+ ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project compose file not found"))+ ErrComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("no compose file found"))+ ErrEnvironmentInvalidProxyTarget = Classify(ErrBadRequest, errors.Sentinel("Invalid proxy target URL"))+ ErrUnsafeRemoteURL = Classify(ErrBadRequest, errors.Sentinel("Remote URL is not allowed"))+ ErrImageScanInProgress = Classify(ErrConflict, errors.Sentinel("an image update check is already in progress"))+ ErrRedeployAfterSyncFailed = errors.Sentinel("redeploy failed")+ ErrGitOpsSyncProjectBindingBroken = errors.Sentinel("GitOps sync project binding broken")+)diff --git a/backend/internal/common/errors_test.go b/backend/internal/common/errors_test.goindex 92450b4d0..5bb3fb440 100644--- a/backend/internal/common/errors_test.go+++ b/backend/internal/common/errors_test.go@@ -1,44 +1,30 @@package commonimport (- "errors"- "io"+ stderrors "errors""testing"-)--func TestRedeployAfterSyncFailedErrorZeroValue(t *testing.T) {- err := &RedeployAfterSyncFailedError{}-- if got := err.Error(); got != "redeploy failed" {- t.Fatalf("Error() = %q, want %q", got, "redeploy failed")- }-- if errors.Is(err, io.EOF) {- t.Fatal("errors.Is matched an unrelated error")- }-}--func TestRedeployAfterSyncFailedErrorNilReceiver(t *testing.T) {- var err *RedeployAfterSyncFailedError- if got := err.Error(); got != "redeploy failed" {- t.Fatalf("Error() = %q, want %q", got, "redeploy failed")- }-- if got := err.Unwrap(); got != nil {- t.Fatalf("Unwrap() = %v, want nil", got)- }-}--func TestRedeployAfterSyncFailedErrorWrapsErr(t *testing.T) {- cause := io.EOF- err := &RedeployAfterSyncFailedError{Err: cause}-- if got := err.Error(); got != "redeploy failed: EOF" {- t.Fatalf("Error() = %q, want %q", got, "redeploy failed: EOF")- }+ "emperror.dev/errors"+ "github.com/stretchr/testify/require"+)- if !errors.Is(err, cause) {- t.Fatal("errors.Is did not match wrapped error")+func TestClassifyPreservesChainDetailsAndSingleStack(t *testing.T) {+ cause := errors.New("root cause")+ err := errors.WithDetails(cause, "field", "name")+ err = Classify(ErrInvalidEnvKey, err)+ err = errors.WrapIf(err, "validate input")++ require.EqualError(t, err, "validate input: root cause")+ require.ErrorIs(t, err, ErrInvalidEnvKey)+ require.ErrorIs(t, err, ErrValidation)+ require.ErrorIs(t, err, cause)+ require.Equal(t, []any{"field", "name"}, errors.GetDetails(err))++ stackCount := 0+ for current := err; current != nil; current = stderrors.Unwrap(current) {+ if _, ok := current.(interface{ StackTrace() errors.StackTrace }); ok {+ stackCount+++ }}+ require.Equal(t, 1, stackCount)}diff --git a/backend/internal/configschema/schema.go b/backend/internal/configschema/schema.goindex 4d0317ea2..a7de45cc1 100644--- a/backend/internal/configschema/schema.go+++ b/backend/internal/configschema/schema.go@@ -4,8 +4,6 @@ import ("bytes""encoding/json/jsontext"json "encoding/json/v2"- "errors"- "fmt""go/ast""go/format""go/parser"@@ -18,6 +16,8 @@ import ("strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -147,12 +147,12 @@ var overrideDocRules = map[string]overrideDocRule{func GenerateWithSourceRoot(sourceRoot string) (*SchemaDocument, error) {envConfig, err := collectEnvConfigInternal(sourceRoot)if err != nil {- return nil, fmt.Errorf("collect env config: %w", err)+ return nil, errors.WrapIf(err, "collect env config")}settingOverrides, err := collectSettingEnvOverridesInternal()if err != nil {- return nil, fmt.Errorf("collect setting env overrides: %w", err)+ return nil, errors.WrapIf(err, "collect setting env overrides")}doc := &SchemaDocument{@@ -169,7 +169,7 @@ func GenerateWithSourceRoot(sourceRoot string) (*SchemaDocument, error) {func MarshalJSON(doc *SchemaDocument) ([]byte, error) {output, err := json.Marshal(doc, json.Deterministic(true), jsontext.WithIndent(" "))if err != nil {- return nil, fmt.Errorf("marshal schema document: %w", err)+ return nil, errors.WrapIf(err, "marshal schema document")}output = append(output, '\n')@@ -220,7 +220,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptifset := token.NewFileSet()file, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)if err != nil {- return nil, fmt.Errorf("parse %s: %w", filename, err)+ return nil, errors.WrapIff(err, "parse %s", filename)}structType, err := findStructTypeInternal(file, structName)@@ -236,7 +236,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptitagValue, err := strconv.Unquote(field.Tag.Value)if err != nil {- return nil, fmt.Errorf("unquote struct tag for %s: %w", structName, err)+ return nil, errors.WrapIff(err, "unquote struct tag for %s", structName)}structTag := reflect.StructTag(tagValue)@@ -248,7 +248,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptioptions := splitTagListInternal(structTag.Get("options"))typeName, err := exprStringInternal(field.Type)if err != nil {- return nil, fmt.Errorf("render type for %s.%s: %w", structName, field.Names[0].Name, err)+ return nil, errors.WrapIff(err, "render type for %s.%s", structName, field.Names[0].Name)}description := normalizeCommentInternal(field.Doc.Text())@@ -303,7 +303,7 @@ func collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {defaultValue, isPublic, isSensitive, err := defaults.FieldByKey(key)if err != nil {- return nil, fmt.Errorf("lookup default value for %q: %w", key, err)+ return nil, errors.WrapIff(err, "lookup default value for %q", key)}if isSensitive {defaultValue = ""@@ -362,14 +362,14 @@ func findStructTypeInternal(file *ast.File, structName string) (*ast.StructType,structType, ok := typeSpec.Type.(*ast.StructType)if !ok {- return nil, fmt.Errorf("%s is not a struct", structName)+ return nil, errors.Errorf("%s is not a struct", structName)}return structType, nil}}- return nil, fmt.Errorf("struct %s not found", structName)+ return nil, errors.Errorf("struct %s not found", structName)}func exprStringInternal(expr ast.Expr) (string, error) {@@ -429,7 +429,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {} else {wd, err := os.Getwd()if err != nil {- return "", fmt.Errorf("get working directory: %w", err)+ return "", errors.WrapIf(err, "get working directory")}candidates = append(candidates, wd)}@@ -442,7 +442,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {}if strings.TrimSpace(sourceRoot) != "" {- return "", fmt.Errorf("resolve source root from %q: expected backend/internal/config/config.go", sourceRoot)+ return "", errors.Errorf("resolve source root from %q: expected backend/internal/config/config.go", sourceRoot)}return "", errors.New("resolve source root: run from the repository root/backend directory or pass --source-root")@@ -451,7 +451,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {func resolveSourceRootCandidateInternal(candidate string) (string, error) {candidate, err := filepath.Abs(candidate)if err != nil {- return "", fmt.Errorf("abs path for %q: %w", candidate, err)+ return "", errors.WrapIff(err, "abs path for %q", candidate)}for current := candidate; ; current = filepath.Dir(current) {@@ -470,7 +470,7 @@ func resolveSourceRootCandidateInternal(candidate string) (string, error) {}}- return "", fmt.Errorf("schema sources not found from %q", candidate)+ return "", errors.Errorf("schema sources not found from %q", candidate)}func hasSchemaSourceFilesInternal(root string) bool {diff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex fae380e35..ee107ace9 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -3,7 +3,6 @@ package databaseimport ("context""database/sql"- "errors""fmt""io/fs""log/slog"@@ -15,6 +14,8 @@ import ("strings""time"+ "emperror.dev/errors"+sqlite "github.com/libtnb/sqlite"goose "github.com/pressly/goose/v3""gorm.io/driver/postgres"@@ -61,7 +62,7 @@ func SetGormLogger(l logger.Interface) {func Initialize(ctx context.Context, databaseURL string, options MigrationOptions) (*DB, error) {db, err := connectDatabaseInternal(ctx, databaseURL)if err != nil {- return nil, fmt.Errorf("failed to connect to database: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to database")}if err := ctx.Err(); err != nil {@@ -71,7 +72,7 @@ func Initialize(ctx context.Context, databaseURL string, options MigrationOption// Get underlying sql.DB for migrationssqlDB, err := db.DB.DB()if err != nil {- return nil, fmt.Errorf("failed to get sql.DB: %w", err)+ return nil, errors.WrapIf(err, "failed to get sql.DB")}var dbProvider string@@ -81,12 +82,12 @@ func Initialize(ctx context.Context, databaseURL string, options MigrationOptioncase strings.HasPrefix(databaseURL, "postgres"):dbProvider = dbProviderPostgresdefault:- return nil, fmt.Errorf("unsupported database type in URL: %s", databaseURL)+ return nil, errors.Errorf("unsupported database type in URL: %s", databaseURL)}if err := migrateDatabaseInternal(ctx, sqlDB, dbProvider, options); err != nil {slog.Error("Failed to run migrations", "error", err)- return nil, fmt.Errorf("failed to run migrations: %w", err)+ return nil, errors.WrapIf(err, "failed to run migrations")}// Set connection pool settings@@ -110,16 +111,16 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, errocase strings.HasPrefix(databaseURL, "file:"):connString, err := parseSqliteConnectionStringInternal(databaseURL)if err != nil {- return nil, fmt.Errorf("failed to parse SQLite connection string: %w", err)+ return nil, errors.WrapIf(err, "failed to parse SQLite connection string")}if err := ensureSQLiteDirectoryInternal(connString); err != nil {- return nil, fmt.Errorf("failed to prepare SQLite directory: %w", err)+ return nil, errors.WrapIf(err, "failed to prepare SQLite directory")}dialector = sqlite.Open(connString)case strings.HasPrefix(databaseURL, "postgres"):dialector = postgres.Open(databaseURL)default:- return nil, fmt.Errorf("unsupported database type in URL: %s", databaseURL)+ return nil, errors.Errorf("unsupported database type in URL: %s", databaseURL)}// Retry connection up to 3 times@@ -159,7 +160,7 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, errofunc migrateDatabaseInternal(ctx context.Context, db *sql.DB, dbProvider string, options MigrationOptions) error {requiredVersion, err := getHighestEmbeddedMigrationVersionInternal(dbProvider)if err != nil {- return fmt.Errorf("failed to determine target migration version for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to determine target migration version for %s", dbProvider)}return migrateDatabaseToVersionInternal(ctx, db, dbProvider, options, requiredVersion)@@ -172,19 +173,19 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvideprovider, err := newGooseProviderInternal(db, dbProvider)if err != nil {- return fmt.Errorf("failed to create goose provider for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to create goose provider for %s", dbProvider)}currentVersion, err := provider.GetDBVersion(ctx)if err != nil {- return fmt.Errorf("failed to determine current migration version for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to determine current migration version for %s", dbProvider)}logMigrationStateInternal(dbProvider, currentVersion, requiredVersion)if currentVersion > requiredVersion {if !options.AllowDowngrade {- return fmt.Errorf("database schema version %d is newer than this Arcane binary supports (target %d for %s); downgrade requires ALLOW_DOWNGRADE=true and a database backup before startup", currentVersion, requiredVersion, dbProvider)+ return errors.Errorf("database schema version %d is newer than this Arcane binary supports (target %d for %s); downgrade requires ALLOW_DOWNGRADE=true and a database backup before startup", currentVersion, requiredVersion, dbProvider)}missingVersions, err := missingEmbeddedDowngradeMigrationsInternal(ctx, db, dbProvider, requiredVersion)@@ -192,11 +193,11 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvidereturn err}if len(missingVersions) > 0 {- return fmt.Errorf("cannot downgrade database from version %d to %d for %s: embedded Goose migrations are missing for applied version(s) %v, so the rollback SQL is unavailable in this Arcane binary; ALLOW_DOWNGRADE=true is not sufficient, restore the database from a backup taken before the newer schema was applied", currentVersion, requiredVersion, dbProvider, missingVersions)+ return errors.Errorf("cannot downgrade database from version %d to %d for %s: embedded Goose migrations are missing for applied version(s) %v, so the rollback SQL is unavailable in this Arcane binary; ALLOW_DOWNGRADE=true is not sufficient, restore the database from a backup taken before the newer schema was applied", currentVersion, requiredVersion, dbProvider, missingVersions)}if _, err := provider.DownTo(ctx, requiredVersion); err != nil {- return fmt.Errorf("failed to downgrade database from version %d to %d for %s using embedded Goose migrations: %w", currentVersion, requiredVersion, dbProvider, err)+ return errors.WrapIff(err, "failed to downgrade database from version %d to %d for %s using embedded Goose migrations", currentVersion, requiredVersion, dbProvider)}slog.Info("Database downgrade completed successfully", "provider", dbProvider, "fromVersion", currentVersion, "toVersion", requiredVersion)@@ -209,7 +210,7 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvide}if _, err := provider.UpTo(ctx, requiredVersion); err != nil {- return fmt.Errorf("failed to apply embedded Goose migrations for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to apply embedded Goose migrations for %s", dbProvider)}slog.Info("Database migrations completed successfully", "provider", dbProvider, "targetVersion", requiredVersion)@@ -233,7 +234,7 @@ func newGooseProviderInternal(db *sql.DB, dbProvider string) (*goose.Provider, efunc embeddedMigrationFSInternal(dbProvider string) (fs.FS, error) {migrationsFS, err := fs.Sub(resources.FS, "migrations/"+dbProvider)if err != nil {- return nil, fmt.Errorf("failed to load embedded migrations for %s: %w", dbProvider, err)+ return nil, errors.WrapIff(err, "failed to load embedded migrations for %s", dbProvider)}return migrationsFS, nil@@ -246,7 +247,7 @@ func gooseDialectInternal(dbProvider string) (goose.Dialect, error) {case dbProviderPostgres:return goose.DialectPostgres, nildefault:- return "", fmt.Errorf("unsupported database provider: %s", dbProvider)+ return "", errors.Errorf("unsupported database provider: %s", dbProvider)}}@@ -261,7 +262,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvidif legacyState.dirty {if !options.AllowDowngrade {- return fmt.Errorf("database schema version %d is dirty in legacy %s table; resolve it manually or set ALLOW_DOWNGRADE=true after verifying the database state", legacyState.version, legacyVersionTable)+ return errors.Errorf("database schema version %d is dirty in legacy %s table; resolve it manually or set ALLOW_DOWNGRADE=true after verifying the database state", legacyState.version, legacyVersionTable)}if err := clearLegacyMigrationDirtyInternal(ctx, db, dbProvider, legacyState.version); err != nil {@@ -285,7 +286,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvidtx, err := db.BeginTx(ctx, nil)if err != nil {- return fmt.Errorf("failed to start legacy migration adoption transaction for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to start legacy migration adoption transaction for %s", dbProvider)}defer func() {_ = tx.Rollback()@@ -321,7 +322,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvid}if err := tx.Commit(); err != nil {- return fmt.Errorf("failed to commit legacy migration adoption for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to commit legacy migration adoption for %s", dbProvider)}slog.Info("Adopted legacy migration state into Goose", "provider", dbProvider, "legacyVersion", legacyState.version)@@ -348,7 +349,7 @@ func legacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvider streturn legacyMigrationState{}, false, nil}if err != nil {- return legacyMigrationState{}, false, fmt.Errorf("failed to read legacy migration state for %s: %w", dbProvider, err)+ return legacyMigrationState{}, false, errors.WrapIff(err, "failed to read legacy migration state for %s", dbProvider)}return state, true, nil@@ -359,17 +360,17 @@ func legacyVersionTableExistsInternal(ctx context.Context, db *sql.DB, dbProvidecase dbProviderSQLite:var count intif err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?`, legacyVersionTable).Scan(&count); err != nil {- return false, fmt.Errorf("failed to check legacy migration table for sqlite: %w", err)+ return false, errors.WrapIf(err, "failed to check legacy migration table for sqlite")}return count > 0, nilcase dbProviderPostgres:var exists boolif err := db.QueryRowContext(ctx, `SELECT to_regclass($1) IS NOT NULL`, legacyVersionTable).Scan(&exists); err != nil {- return false, fmt.Errorf("failed to check legacy migration table for postgres: %w", err)+ return false, errors.WrapIf(err, "failed to check legacy migration table for postgres")}return exists, nildefault:- return false, fmt.Errorf("unsupported database provider: %s", dbProvider)+ return false, errors.Errorf("unsupported database provider: %s", dbProvider)}}@@ -380,7 +381,7 @@ func clearLegacyMigrationDirtyInternal(ctx context.Context, db *sql.DB, dbProvidreturn err}if _, err := db.ExecContext(ctx, query, args...); err != nil {- return fmt.Errorf("failed to clear legacy dirty migration state for %s version %d: %w", dbProvider, version, err)+ return errors.WrapIff(err, "failed to clear legacy dirty migration state for %s version %d", dbProvider, version)}return nil}@@ -393,7 +394,7 @@ func gooseVersionTableHasAppliedMigrationsInternal(ctx context.Context, db *sql.var version int64if err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, appliedLiteralInternal(dbProvider))).Scan(&version); err != nil {- return false, fmt.Errorf("failed to read Goose migration state for %s: %w", dbProvider, err)+ return false, errors.WrapIff(err, "failed to read Goose migration state for %s", dbProvider)}return version > 0, nil}@@ -403,17 +404,17 @@ func gooseVersionTableExistsInternal(ctx context.Context, db *sql.DB, dbProvidercase dbProviderSQLite:var count intif err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?`, gooseVersionTable).Scan(&count); err != nil {- return false, fmt.Errorf("failed to check Goose version table for sqlite: %w", err)+ return false, errors.WrapIf(err, "failed to check Goose version table for sqlite")}return count > 0, nilcase dbProviderPostgres:var exists boolif err := db.QueryRowContext(ctx, `SELECT to_regclass($1) IS NOT NULL`, gooseVersionTable).Scan(&exists); err != nil {- return false, fmt.Errorf("failed to check Goose version table for postgres: %w", err)+ return false, errors.WrapIf(err, "failed to check Goose version table for postgres")}return exists, nildefault:- return false, fmt.Errorf("unsupported database provider: %s", dbProvider)+ return false, errors.Errorf("unsupported database provider: %s", dbProvider)}}@@ -439,18 +440,18 @@ func createGooseVersionTableInternal(ctx context.Context, execer sqlExecerInterntstamp timestamp NOT NULL DEFAULT now())`, gooseVersionTable)default:- return fmt.Errorf("unsupported database provider: %s", dbProvider)+ return errors.Errorf("unsupported database provider: %s", dbProvider)}if _, err := execer.ExecContext(ctx, query); err != nil {- return fmt.Errorf("failed to create Goose version table for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to create Goose version table for %s", dbProvider)}return nil}func clearGooseVersionTableInternal(ctx context.Context, execer sqlExecerInternal, dbProvider string) error {if _, err := execer.ExecContext(ctx, "DELETE FROM "+gooseVersionTable); err != nil {- return fmt.Errorf("failed to clear Goose version table for %s: %w", dbProvider, err)+ return errors.WrapIff(err, "failed to clear Goose version table for %s", dbProvider)}return nil}@@ -459,14 +460,14 @@ func insertGooseMigrationVersionInternal(ctx context.Context, execer sqlExecerInswitch dbProvider {case dbProviderSQLite:if _, err := execer.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s (version_id, is_applied) VALUES (?, ?)", gooseVersionTable), version, true); err != nil {- return fmt.Errorf("failed to insert Goose migration version %d for sqlite: %w", version, err)+ return errors.WrapIff(err, "failed to insert Goose migration version %d for sqlite", version)}case dbProviderPostgres:if _, err := execer.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s (version_id, is_applied) VALUES ($1, $2)", gooseVersionTable), version, true); err != nil {- return fmt.Errorf("failed to insert Goose migration version %d for postgres: %w", version, err)+ return errors.WrapIff(err, "failed to insert Goose migration version %d for postgres", version)}default:- return fmt.Errorf("unsupported database provider: %s", dbProvider)+ return errors.Errorf("unsupported database provider: %s", dbProvider)}return nil}@@ -478,7 +479,7 @@ func sqlWithProviderPlaceholderInternal(dbProvider, queryFormat string, arg any)case dbProviderPostgres:return fmt.Sprintf(queryFormat, "$1"), []any{arg}, nildefault:- return "", nil, fmt.Errorf("unsupported database provider: %s", dbProvider)+ return "", nil, errors.Errorf("unsupported database provider: %s", dbProvider)}}@@ -499,7 +500,7 @@ func getHighestEmbeddedMigrationVersionInternal(dbProvider string) (int64, errorreturn 0, err}if len(versions) == 0 {- return 0, fmt.Errorf("no embedded migrations found for %s", dbProvider)+ return 0, errors.Errorf("no embedded migrations found for %s", dbProvider)}return versions[len(versions)-1], nil@@ -508,7 +509,7 @@ func getHighestEmbeddedMigrationVersionInternal(dbProvider string) (int64, errorfunc getEmbeddedMigrationVersionsInternal(dbProvider string) ([]int64, error) {entries, err := resources.FS.ReadDir("migrations/" + dbProvider)if err != nil {- return nil, fmt.Errorf("failed to read embedded migrations for %s: %w", dbProvider, err)+ return nil, errors.WrapIff(err, "failed to read embedded migrations for %s", dbProvider)}versionsMap := make(map[int64]struct{})@@ -564,7 +565,7 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,rows, err := db.QueryContext(ctx, query, args...)if err != nil {- return nil, fmt.Errorf("failed to read applied migration versions for %s: %w", dbProvider, err)+ return nil, errors.WrapIff(err, "failed to read applied migration versions for %s", dbProvider)}defer func() {_ = rows.Close()@@ -574,14 +575,14 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,for rows.Next() {var version int64if err := rows.Scan(&version); err != nil {- return nil, fmt.Errorf("failed to scan applied migration version for %s: %w", dbProvider, err)+ return nil, errors.WrapIff(err, "failed to scan applied migration version for %s", dbProvider)}if _, ok := embeddedSet[version]; !ok {missing = append(missing, version)}}if err := rows.Err(); err != nil {- return nil, fmt.Errorf("failed to iterate applied migration versions for %s: %w", dbProvider, err)+ return nil, errors.WrapIff(err, "failed to iterate applied migration versions for %s", dbProvider)}return missing, nil@@ -598,7 +599,7 @@ func parseSqliteConnectionStringInternal(connString string) (string, error) {connStringUrl, err := url.Parse(connString)if err != nil {- return "", fmt.Errorf("failed to parse SQLite connection string: %w", err)+ return "", errors.WrapIf(err, "failed to parse SQLite connection string")}qs := make(url.Values, len(connStringUrl.Query()))@@ -668,7 +669,7 @@ func ensureSQLiteDirectoryInternal(connString string) error {}u, err := url.Parse(connString)if err != nil {- return fmt.Errorf("failed to parse SQLite DSN: %w", err)+ return errors.WrapIf(err, "failed to parse SQLite DSN")}// For "file:data/arcane.db?...", path is in Opaque; for "file:/abs/path.db", it's in Path.diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex b73851b7f..71ac676fe 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -2,6 +2,7 @@package diimport (+ arcanelogging "github.com/getarcaneapp/arcane/backend/v2/internal/logging""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""go.uber.org/fx"@@ -12,6 +13,7 @@ var ServiceOptions = fx.Options(fx.Provide(// Infrastructure values consumed by services.provideResourcesFSInternal,+ arcanelogging.NewSlogErrorHandler,// Services constructed directly through their public constructors.services.NewEventService,diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex 6f9241cef..9ce51511c 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -8,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ arcanelogging "github.com/getarcaneapp/arcane/backend/v2/internal/logging""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"@@ -53,8 +54,8 @@ func provideVolumeServiceInternal(lc fx.Lifecycle, db *database.DB, docker *servreturn service}-func provideAuthServiceInternal(user *services.UserService, settings *services.SettingsService, event *services.EventService, session *services.SessionService, role *services.RoleService, cfg *config.Config) *services.AuthService {- return services.NewAuthService(user, settings, event, session, role, cfg.JWTSecret, cfg)+func provideAuthServiceInternal(user *services.UserService, settings *services.SettingsService, event *services.EventService, session *services.SessionService, role *services.RoleService, cfg *config.Config, errorHandler *arcanelogging.SlogErrorHandler) *services.AuthService {+ return services.NewAuthService(user, settings, event, session, role, cfg.JWTSecret, cfg, errorHandler)}func provideContainerRegistryServiceInternal(db *database.DB, docker *services.DockerClientService, kv *services.KVService) *services.ContainerRegistryService {diff --git a/backend/internal/logging/error_handler.go b/backend/internal/logging/error_handler.gonew file mode 100644index 000000000..d8af575db--- /dev/null+++ b/backend/internal/logging/error_handler.go@@ -0,0 +1,37 @@+package logging++import (+ "context"+ "log/slog"++ "emperror.dev/emperror"+ "emperror.dev/errors"+)++var _ emperror.ErrorHandler = (*SlogErrorHandler)(nil)+var _ emperror.ErrorHandlerContext = (*SlogErrorHandler)(nil)++// SlogErrorHandler reports handled errors through the process slog logger.+type SlogErrorHandler struct{}++func (SlogErrorHandler) Handle(err error) {+ SlogErrorHandler{}.HandleContext(context.Background(), err)+}++func (SlogErrorHandler) HandleContext(ctx context.Context, err error) {+ if err == nil {+ return+ }++ attrs := []any{"error", err}+ details := errors.GetDetails(err)+ for i := 0; i+1 < len(details); i += 2 {+ attrs = append(attrs, details[i], details[i+1])+ }+ slog.ErrorContext(ctx, "Unhandled error", attrs...)+}++// NewSlogErrorHandler creates the application error handler.+func NewSlogErrorHandler() *SlogErrorHandler {+ return &SlogErrorHandler{}+}diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.goindex 9ba4287f9..5f2040e9d 100644--- a/backend/internal/middleware/auth_middleware.go+++ b/backend/internal/middleware/auth_middleware.go@@ -5,11 +5,12 @@ import ("context""crypto/subtle"- "errors""log/slog""net/http""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -215,7 +216,7 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next e})}- if common.IsSessionRevokedError(err) || common.IsTokenValidationError(err) {+ if errors.Is(err, common.ErrSessionRevoked) || errors.Is(err, common.ErrTokenValidation) {cookie.ClearTokenCookie(c.Response().Writer, req)return c.JSON(http.StatusUnauthorized, models.APIError{Code: models.APIErrorCodeUnauthorized,diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 6caa47f81..009c567d5 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -5,8 +5,6 @@ import ("bytes""context"- "errors"- "fmt""io""log/slog""net/http"@@ -14,6 +12,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -121,7 +120,7 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) erif !ok {return c.JSON(http.StatusUnauthorized, map[string]any{"success": false,- "data": map[string]any{"error": (&common.EnvironmentUnauthorizedError{}).Error()},+ "data": map[string]any{"error": "Authentication required to access remote environments"},})}perms = ps@@ -131,14 +130,14 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) erif err != nil || apiURL == "" {return c.JSON(http.StatusNotFound, map[string]any{"success": false,- "data": map[string]any{"error": (&common.EnvironmentNotFoundError{}).Error()},+ "data": map[string]any{"error": "Environment not found"},})}if !enabled {return c.JSON(http.StatusBadRequest, map[string]any{"success": false,- "data": map[string]any{"error": (&common.EnvironmentDisabledError{}).Error()},+ "data": map[string]any{"error": (errors.New("Environment is disabled")).Error()},})}@@ -150,7 +149,7 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) erif m.proxyPermissionDenied(c, perms, envID) {return c.JSON(http.StatusForbidden, map[string]any{"success": false,- "data": map[string]any{"error": (&common.EnvironmentForbiddenError{}).Error()},+ "data": map[string]any{"error": "You don't have permission to perform this action on this environment"},})}@@ -417,7 +416,7 @@ func (m *EnvironmentMiddleware) abortEdgeTunnelUnavailable(c echo.Context) errorreturn c.JSON(http.StatusBadGateway, map[string]any{"success": false,"data": map[string]any{- "error": (&common.EdgeAgentNotConnectedError{}).Error(),+ "error": "Edge agent is not connected",},})}@@ -447,9 +446,9 @@ func (m *EnvironmentMiddleware) proxyHTTP(c echo.Context, target string, accessTreq, err := m.createProxyRequest(c, target, accessToken)if err != nil {- errMessage := (&common.EnvironmentProxyRequestCreationError{Err: err}).Error()- if invalidTargetErr, ok := errors.AsType[*common.EnvironmentInvalidProxyTargetError](err); ok {- errMessage = invalidTargetErr.Error()+ errMessage := errors.WithMessage(err, "Failed to create proxy request").Error()+ if errors.Is(err, common.ErrEnvironmentInvalidProxyTarget) {+ errMessage = err.Error()}return c.JSON(http.StatusInternalServerError, map[string]any{"success": false,@@ -461,7 +460,7 @@ func (m *EnvironmentMiddleware) proxyHTTP(c echo.Context, target string, accessTif err != nil {return c.JSON(http.StatusBadGateway, map[string]any{"success": false,- "data": map[string]any{"error": (&common.EnvironmentProxyRequestFailedError{Err: err}).Error()},+ "data": map[string]any{"error": errors.WithMessage(err, "Proxy request failed").Error()},})}defer func() { _ = resp.Body.Close() }()@@ -475,7 +474,7 @@ func (m *EnvironmentMiddleware) createProxyRequest(c echo.Context, target stringsrcReq := c.Request()validatedTarget, err := httputils.ValidateOutboundHTTPURL(target)if err != nil {- return nil, &common.EnvironmentInvalidProxyTargetError{Err: err}+ return nil, common.Classify(common.ErrEnvironmentInvalidProxyTarget, errors.WrapIf(err, "Invalid proxy target URL"))}var bodyBytes []byte@@ -484,7 +483,7 @@ func (m *EnvironmentMiddleware) createProxyRequest(c echo.Context, target stringbodyBytes, err = io.ReadAll(srcReq.Body)_ = srcReq.Body.Close()if err != nil {- return nil, fmt.Errorf("failed to read request body: %w", err)+ return nil, errors.WrapIf(err, "failed to read request body")}}diff --git a/backend/internal/models/environment_update_job.go b/backend/internal/models/environment_update_job.goindex 40f092943..dc28d9634 100644--- a/backend/internal/models/environment_update_job.go+++ b/backend/internal/models/environment_update_job.go@@ -3,8 +3,9 @@ package modelsimport ("database/sql/driver"json "encoding/json/v2"- "fmt""time"++ "emperror.dev/errors")// EnvironmentUpdateJobStatus is the lifecycle status of a fleet-wide "update all@@ -82,7 +83,7 @@ func (r *EnvironmentUpdateResults) Scan(value any) error {case string:return json.Unmarshal([]byte(v), r)default:- return fmt.Errorf("unsupported scan type for EnvironmentUpdateResults: %T", value)+ return errors.Errorf("unsupported scan type for EnvironmentUpdateResults: %T", value)}}diff --git a/backend/internal/models/errors.go b/backend/internal/models/errors.goindex 75a2d0f84..c19a5454d 100644--- a/backend/internal/models/errors.go+++ b/backend/internal/models/errors.go@@ -1,8 +1,12 @@package modelsimport (- "errors"+ stderrors "errors""net/http"++ "emperror.dev/errors"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common")type APIErrorCode string@@ -84,22 +88,6 @@ func NewValidationError(message string, details any) *APIError {return NewAPIErrorWithDetails(message, APIErrorCodeValidationError, http.StatusBadRequest, details)}-type NotFoundError struct {- Message string-}--func (e *NotFoundError) Error() string {- return e.Message-}--type ConflictError struct {- Message string-}--func (e *ConflictError) Error() string {- return e.Message-}-type DockerAPIError struct {Message stringStatusCode int@@ -117,30 +105,43 @@ func (e *DockerAPIError) HTTPStatus() int {return http.StatusInternalServerError}-type ValidationError struct {- Message string- Field string-}--func (e *ValidationError) Error() string {- return e.Message-}-func ToAPIError(err error) *APIError {- if apiErr, ok := errors.AsType[*APIError](err); ok {+ if apiErr, ok := stderrors.AsType[*APIError](err); ok {return apiErr}- if notFoundErr, ok := errors.AsType[*NotFoundError](err); ok {- return NewNotFoundError(notFoundErr.Message)- }- if conflictErr, ok := errors.AsType[*ConflictError](err); ok {- return NewConflictError(conflictErr.Message)- }- if validationErr, ok := errors.AsType[*ValidationError](err); ok {- return NewValidationError(validationErr.Message, map[string]string{"field": validationErr.Field})- }- if dockerAPIErr, ok := errors.AsType[*DockerAPIError](err); ok {+ if dockerAPIErr, ok := stderrors.AsType[*DockerAPIError](err); ok {return NewAPIErrorWithDetails(dockerAPIErr.Message, APIErrorCodeDockerAPIError, dockerAPIErr.HTTPStatus(), dockerAPIErr.Details)}++ switch {+ case errors.Is(err, common.ErrValidation):+ details := make(map[string]any)+ keyValues := errors.GetDetails(err)+ for i := 0; i+1 < len(keyValues); i += 2 {+ key, ok := keyValues[i].(string)+ if ok {+ details[key] = keyValues[i+1]+ }+ }+ if len(details) == 0 {+ details = nil+ }+ return NewValidationError(err.Error(), details)+ case errors.Is(err, common.ErrBadRequest):+ return NewAPIError(err.Error(), APIErrorCodeBadRequest, http.StatusBadRequest)+ case errors.Is(err, common.ErrUnauthorized):+ return NewAPIError(err.Error(), APIErrorCodeUnauthorized, http.StatusUnauthorized)+ case errors.Is(err, common.ErrForbidden):+ return NewAPIError(err.Error(), APIErrorCodeForbidden, http.StatusForbidden)+ case errors.Is(err, common.ErrNotFound):+ return NewNotFoundError(err.Error())+ case errors.Is(err, common.ErrConflict):+ return NewConflictError(err.Error())+ case errors.Is(err, common.ErrTimeout):+ return NewAPIError(err.Error(), APIErrorCodeTimeout, http.StatusGatewayTimeout)+ case errors.Is(err, common.ErrUnavailable):+ return NewAPIError(err.Error(), APIErrorCodeInternalServerError, http.StatusServiceUnavailable)+ }+return NewInternalServerError(err.Error())}diff --git a/backend/internal/models/errors_test.go b/backend/internal/models/errors_test.gonew file mode 100644index 000000000..7d31c248f--- /dev/null+++ b/backend/internal/models/errors_test.go@@ -0,0 +1,22 @@+package models++import (+ "net/http"+ "testing"++ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/stretchr/testify/require"+)++func TestToAPIErrorMapsClassifiedValidationDetails(t *testing.T) {+ err := errors.WithDetails(errors.New("Name is required"), "field", "name")+ err = common.Classify(common.ErrValidation, err)++ apiErr := ToAPIError(err)++ require.Equal(t, http.StatusBadRequest, apiErr.HTTPStatus())+ require.Equal(t, APIErrorCodeValidationError, apiErr.Code)+ require.Equal(t, "Name is required", apiErr.Message)+ require.Equal(t, map[string]any{"field": "name"}, apiErr.Details)+}diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex fb97df6e9..39ec6c0a8 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -1,14 +1,14 @@package modelsimport (- "errors"- "fmt""reflect""slices""strconv""strings""sync""time"++ "emperror.dev/errors")const (@@ -331,7 +331,7 @@ func (s *Settings) UpdateField(key string, value string, noSensitive bool) errorvalueField := rv.Field(field.index).FieldByName("Value")if !valueField.CanSet() {- return fmt.Errorf("field Value in SettingVariable is not settable for config key '%s'", key)+ return errors.Errorf("field Value in SettingVariable is not settable for config key '%s'", key)}valueField.SetString(value)diff --git a/backend/internal/services/activity_service.go b/backend/internal/services/activity_service.goindex 8d5d81333..5fef0a781 100644--- a/backend/internal/services/activity_service.go+++ b/backend/internal/services/activity_service.go@@ -2,8 +2,7 @@ package servicesimport ("context"- "errors"- "fmt"+ stderrors "errors""log/slog""maps""slices"@@ -11,6 +10,7 @@ import ("sync""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -57,7 +57,7 @@ type ActivityService struct {// ErrActivityNotCancelable indicates the activity has already reached a terminal// state and can no longer be cancelled.-var ErrActivityNotCancelable = errors.New("activity is not cancelable")+const ErrActivityNotCancelable = errors.Sentinel("activity is not cancelable")// subscriberMessageQueueLimit bounds the per-subscriber backlog of "message"// events; the oldest message is dropped (and flagged as missed) on overflow.@@ -331,7 +331,7 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityReif slotRelease != nil {slotRelease()}- return nil, fmt.Errorf("failed to create activity: %w", err)+ return nil, errors.WrapIf(err, "failed to create activity")}if slotRelease != nil {s.registerSlotReleaseInternal(model.ID, slotRelease)@@ -412,7 +412,7 @@ func (s *ActivityService) AwaitActivitySlotBounded(ctx context.Context, activitydefer cancel()if err := s.AwaitActivitySlot(slotCtx, activityID, environmentID); err != nil {if ctx.Err() == nil && errors.Is(err, context.DeadlineExceeded) {- return &common.ActivitySlotWaitTimeoutError{}+ return common.Classify(common.ErrTimeout, errors.New("timed out waiting for a free activity slot; other long-running activities are holding all slots"))}return err}@@ -454,13 +454,13 @@ func (s *ActivityService) UpdateActivity(ctx context.Context, activityID string,if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {- return fmt.Errorf("failed to update activity: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to update activity")}if result.RowsAffected == 0 {return errors.New("activity not found")}if err := tx.First(&model, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("failed to load updated activity: %w", err)+ return errors.WrapIf(err, "failed to load updated activity")}return nil}); err != nil {@@ -508,7 +508,7 @@ func (s *ActivityService) AppendMessage(ctx context.Context, activityID string,var updated models.Activityif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(message).Error; err != nil {- return fmt.Errorf("failed to append activity message: %w", err)+ return errors.WrapIf(err, "failed to append activity message")}updates := map[string]any{@@ -524,13 +524,13 @@ func (s *ActivityService) AppendMessage(ctx context.Context, activityID string,result := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {- return fmt.Errorf("failed to update activity latest message: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to update activity latest message")}if result.RowsAffected == 0 {return errors.New("activity not found")}if err := tx.First(&updated, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("failed to load updated activity: %w", err)+ return errors.WrapIf(err, "failed to load updated activity")}return nil}); err != nil {@@ -578,15 +578,15 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strinfor attempt := 1; attempt <= completeWriteAttempts; attempt++ {writeErr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.First(&model, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("failed to load activity: %w", err)+ return errors.WrapIf(err, "failed to load activity")}updates := completeActivityUpdatesInternal(model.StartedAt, status, finalMessage, errMessage, finalStep, now)if err := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to complete activity: %w", err)+ return errors.WrapIf(err, "failed to complete activity")}if err := tx.First(&model, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("failed to load completed activity: %w", err)+ return errors.WrapIf(err, "failed to load completed activity")}return nil})@@ -692,13 +692,13 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, actWhere("id = ? AND status IN ?", activityID, []models.ActivityStatus{models.ActivityStatusQueued, models.ActivityStatusRunning}).Updates(updates)if result.Error != nil {- return fmt.Errorf("failed to cancel activity: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to cancel activity")}if result.RowsAffected == 0 {return ErrActivityNotCancelable}if err := tx.First(&finalized, "id = ? AND environment_id = ?", activityID, environmentID).Error; err != nil {- return fmt.Errorf("failed to load cancelled activity: %w", err)+ return errors.WrapIf(err, "failed to load cancelled activity")}return nil}); err != nil {@@ -725,7 +725,7 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64if err := s.db.WithContext(ctx).Where("type = ? AND status = ? AND started_at < ?", models.ActivityTypeImageUpdateCheck, models.ActivityStatusRunning, cutoff).Find(&staleChecks).Error; err != nil {- return 0, fmt.Errorf("find stale image update checks: %w", err)+ return 0, errors.WrapIf(err, "find stale image update checks")}const message = "Image update check failed because it was stale after Arcane restarted"@@ -734,13 +734,13 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64var failErrs []errorfor i := range staleChecks {if _, err := s.CompleteActivity(ctx, staleChecks[i].ID, models.ActivityStatusFailed, message, &errMessage, "Image update check failed"); err != nil {- failErrs = append(failErrs, fmt.Errorf("fail stale image update check %s: %w", staleChecks[i].ID, err))+ failErrs = append(failErrs, errors.WrapIff(err, "fail stale image update check %s", staleChecks[i].ID))continue}failed++}- return failed, errors.Join(failErrs...)+ return failed, stderrors.Join(failErrs...)}// isTrackedInternal reports whether activityID has a live work registration in@@ -775,7 +775,7 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eif err := s.db.WithContext(ctx).Where("status IN ? AND started_at < ?", activeStatuses, cutoff).Find(&candidates).Error; err != nil {- return 0, fmt.Errorf("find abandoned activities: %w", err)+ return 0, errors.WrapIf(err, "find abandoned activities")}const message = "Activity was marked failed because its worker is no longer running"@@ -797,18 +797,18 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eWhere("id = ? AND status IN ?", activityID, activeStatuses).Updates(updates)if result.Error != nil {- return fmt.Errorf("fail abandoned activity: %w", result.Error)+ return errors.WrapIf(result.Error, "fail abandoned activity")}if result.RowsAffected == 0 {lostRace = truereturn nil}if err := tx.First(&finalized, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("load failed abandoned activity: %w", err)+ return errors.WrapIf(err, "load failed abandoned activity")}return nil}); err != nil {- sweepErrs = append(sweepErrs, fmt.Errorf("sweep activity %s: %w", activityID, err))+ sweepErrs = append(sweepErrs, errors.WrapIff(err, "sweep activity %s", activityID))continue}if lostRace {@@ -820,7 +820,7 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eswept++}- return swept, errors.Join(sweepErrs...)+ return swept, stderrors.Join(sweepErrs...)}// ResolveOrphanedQueuedActivities fails any activity still queued at startup.@@ -835,7 +835,7 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context) (if err := s.db.WithContext(ctx).Where("status = ?", models.ActivityStatusQueued).Find(&queued).Error; err != nil {- return 0, fmt.Errorf("find orphaned queued activities: %w", err)+ return 0, errors.WrapIf(err, "find orphaned queued activities")}const message = "Queued activity was interrupted by an Arcane restart"@@ -844,13 +844,13 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context) (var failErrs []errorfor i := range queued {if _, err := s.CompleteActivity(ctx, queued[i].ID, models.ActivityStatusFailed, message, &errMessage); err != nil {- failErrs = append(failErrs, fmt.Errorf("fail orphaned queued activity %s: %w", queued[i].ID, err))+ failErrs = append(failErrs, errors.WrapIff(err, "fail orphaned queued activity %s", queued[i].ID))continue}failed++}- return failed, errors.Join(failErrs...)+ return failed, stderrors.Join(failErrs...)}// PatchActivityMetadata merges patch into the activity's existing metadata,@@ -870,7 +870,7 @@ func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityIDreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var activity models.Activityif err := tx.First(&activity, "id = ?", activityID).Error; err != nil {- return fmt.Errorf("failed to load activity: %w", err)+ return errors.WrapIf(err, "failed to load activity")}merged := cloneJSONInternal(activity.Metadata)if merged == nil {@@ -879,7 +879,7 @@ func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityIDmaps.Copy(merged, patch)if err := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(map[string]any{"metadata": merged, "updated_at": time.Now()}).Error; err != nil {- return fmt.Errorf("failed to patch activity metadata: %w", err)+ return errors.WrapIf(err, "failed to patch activity metadata")}return nil})@@ -898,7 +898,7 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context)if err := s.db.WithContext(ctx).Where("type = ? AND status = ?", models.ActivityTypeAutoUpdate, models.ActivityStatusRunning).Find(&stale).Error; err != nil {- return 0, fmt.Errorf("find stale auto-update activities: %w", err)+ return 0, errors.WrapIf(err, "find stale auto-update activities")}var resolved int64@@ -914,13 +914,13 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context)errMessage = new(message)}if _, err := s.CompleteActivity(ctx, stale[i].ID, status, message, errMessage); err != nil {- resolveErrs = append(resolveErrs, fmt.Errorf("resolve stale auto-update activity %s: %w", stale[i].ID, err))+ resolveErrs = append(resolveErrs, errors.WrapIff(err, "resolve stale auto-update activity %s", stale[i].ID))continue}resolved++}- return resolved, errors.Join(resolveErrs...)+ return resolved, stderrors.Join(resolveErrs...)}func completeActivityUpdatesInternal(startedAt time.Time, status models.ActivityStatus, finalMessage string, errMessage *string, finalStep []string, now time.Time) map[string]any {@@ -984,7 +984,7 @@ func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environmepaginationResp, err := pagination.PaginateAndSortDB(params, q, &activities)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate activities: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate activities")}out := make([]activitytypes.Activity, 0, len(activities))@@ -1006,7 +1006,7 @@ func (s *ActivityService) GetActivityDetail(ctx context.Context, environmentID,if err := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", activityID, environmentID).First(&model).Error; err != nil {- return nil, fmt.Errorf("failed to load activity: %w", err)+ return nil, errors.WrapIf(err, "failed to load activity")}var messages []models.ActivityMessage@@ -1015,7 +1015,7 @@ func (s *ActivityService) GetActivityDetail(ctx context.Context, environmentID,Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {- return nil, fmt.Errorf("failed to load activity messages: %w", err)+ return nil, errors.WrapIf(err, "failed to load activity messages")}outMessages := make([]activitytypes.Message, 0, len(messages))@@ -1047,7 +1047,7 @@ func (s *ActivityService) PruneHistory(ctx context.Context, retentionDays, maxEnids, err := findTerminalActivityIDsInternal(tx.Where("COALESCE(ended_at, updated_at, created_at) < ?", cutoff))if err != nil {- return fmt.Errorf("failed to find activities older than retention window: %w", err)+ return errors.WrapIf(err, "failed to find activities older than retention window")}count, err := deleteActivitiesByIDInternal(tx, ids)if err != nil {@@ -1090,7 +1090,7 @@ func (s *ActivityService) DeleteHistory(ctx context.Context, environmentID strinif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {ids, err := findTerminalActivityIDsInternal(tx.Where("environment_id = ?", environmentID))if err != nil {- return fmt.Errorf("failed to find activity history: %w", err)+ return errors.WrapIf(err, "failed to find activity history")}count, err := deleteActivitiesByIDInternal(tx, ids)if err != nil {@@ -1301,7 +1301,7 @@ func findActivityIDsBeyondHistoryLimitInternal(tx *gorm.DB, maxEntries int) ([]s) rankedWHERE ranked.activity_rank > ?`, terminalActivityStatusesInternal(), maxEntries).Scan(&activityIDs).Error; err != nil {- return nil, fmt.Errorf("failed to find excess activities: %w", err)+ return nil, errors.WrapIf(err, "failed to find excess activities")}return activityIDs, nil}@@ -1319,11 +1319,11 @@ func deleteActivitiesByIDInternal(tx *gorm.DB, activityIDs []string) (int64, errbatch := activityIDs[i:end]if err := tx.Where("activity_id IN ?", batch).Delete(&models.ActivityMessage{}).Error; err != nil {- return totalDeleted, fmt.Errorf("failed to delete activity messages: %w", err)+ return totalDeleted, errors.WrapIf(err, "failed to delete activity messages")}result := tx.Where("id IN ?", batch).Delete(&models.Activity{})if result.Error != nil {- return totalDeleted, fmt.Errorf("failed to delete activities: %w", result.Error)+ return totalDeleted, errors.WrapIf(result.Error, "failed to delete activities")}totalDeleted += result.RowsAffected}diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.goindex 00a6987ab..079a5622e 100644--- a/backend/internal/services/api_key_service.go+++ b/backend/internal/services/api_key_service.go@@ -4,12 +4,12 @@ import ("context""crypto/rand""encoding/hex"- "errors"- "fmt""log/slog""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -19,11 +19,11 @@ import ("gorm.io/gorm")-var (- ErrApiKeyNotFound = errors.New("API key not found")- ErrApiKeyExpired = errors.New("API key has expired")- ErrApiKeyInvalid = errors.New("invalid API key")- ErrApiKeyProtected = errors.New("API key is protected")+const (+ ErrApiKeyNotFound = errors.Sentinel("API key not found")+ ErrApiKeyExpired = errors.Sentinel("API key has expired")+ ErrApiKeyInvalid = errors.Sentinel("invalid API key")+ ErrApiKeyProtected = errors.Sentinel("API key is protected"))const (@@ -69,7 +69,7 @@ func (s *ApiKeyService) WithRoleService(roleService *RoleService) *ApiKeyServicefunc (s *ApiKeyService) generateApiKey() (string, error) {bytes := make([]byte, apiKeyLength)if _, err := rand.Read(bytes); err != nil {- return "", fmt.Errorf("failed to generate API key: %w", err)+ return "", errors.WrapIf(err, "failed to generate API key")}return apiKeyPrefix + hex.EncodeToString(bytes), nil}@@ -107,7 +107,7 @@ func (s *ApiKeyService) markApiKeyUsedInternal(ctx context.Context, keyID stringModel(&models.ApiKey{}).Where("id = ? AND (last_used_at IS NULL OR last_used_at < ?)", keyID, cutoff).Update("last_used_at", now).Error; err != nil {- return fmt.Errorf("failed to update API key last-used timestamp: %w", err)+ return errors.WrapIf(err, "failed to update API key last-used timestamp")}return nil}@@ -131,7 +131,7 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPif s.roleService != nil {grants := toApiKeyPermissionRowsInternal(created.ID, req.Permissions)if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {- return nil, fmt.Errorf("failed to persist api key permissions: %w", err)+ return nil, errors.WrapIf(err, "failed to persist api key permissions")}// Re-load the just-persisted grants into the response DTO so the// frontend doesn't see `"permissions": null` on a successful create.@@ -142,12 +142,12 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerP// ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an// API key permissions they themselves do not hold.-var ErrApiKeyPermissionEscalation = errors.New("cannot grant a permission you do not have")+const ErrApiKeyPermissionEscalation = errors.Sentinel("cannot grant a permission you do not have")// ErrApiKeyPersonalNoGrants is returned when a caller attempts to attach// permission grants to a personal key, which has none of its own — it inherits// the owner's role permissions at authentication time.-var ErrApiKeyPersonalNoGrants = errors.New("personal API keys inherit the owner's permissions and cannot carry grants")+const ErrApiKeyPersonalNoGrants = errors.Sentinel("personal API keys inherit the owner's permissions and cannot carry grants")// validateGrantsAgainstOwnerInternal caps grants at the key owner's role// permissions, so no holder of apikeys:create/update — sudo included — can@@ -161,14 +161,14 @@ func (s *ApiKeyService) validateGrantsAgainstOwnerInternal(ctx context.Context,}user, err := s.userService.GetUserByID(ctx, ownerID)if err != nil {- return fmt.Errorf("load owner for permission validation: %w", err)+ return errors.WrapIf(err, "load owner for permission validation")}ps, err := s.roleService.ResolvePermissions(ctx, user)if err != nil {- return fmt.Errorf("resolve owner permissions: %w", err)+ return errors.WrapIf(err, "resolve owner permissions")}if err := validateGrantsAgainstPermissionSetInternal(ps, grants); err != nil {- return fmt.Errorf("owner's roles do not allow this grant: %w", err)+ return errors.WrapIf(err, "owner's roles do not allow this grant")}return nil}@@ -184,7 +184,7 @@ func validateGrantsAgainstPermissionSetInternal(callerPerms *authz.PermissionSetenvID = *g.EnvironmentID}if !callerPerms.Allows(g.Permission, envID) {- return fmt.Errorf("%w: %s (env=%q)", ErrApiKeyPermissionEscalation, g.Permission, envID)+ return errors.WrapIff(ErrApiKeyPermissionEscalation, "%s (env=%q)", g.Permission, envID)}}return nil@@ -240,7 +240,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(keyHash, err := s.hashApiKey(rawKey)if err != nil {- return nil, fmt.Errorf("failed to hash API key: %w", err)+ return nil, errors.WrapIf(err, "failed to hash API key")}ak := &models.ApiKey{@@ -256,7 +256,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(}if err := s.db.WithContext(ctx).Create(ak).Error; err != nil {- return nil, fmt.Errorf("failed to create API key: %w", err)+ return nil, errors.WrapIf(err, "failed to create API key")}return &apikey.ApiKeyCreatedDto{@@ -325,7 +325,7 @@ func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*models.User,slog.WarnContext(ctx, "Default admin user not found, skipping default admin API key reconciliation", "username", defaultAdminUsername)return nil, nil}- return nil, fmt.Errorf("failed to load default admin user: %w", err)+ return nil, errors.WrapIf(err, "failed to load default admin user")}return adminUser, nil@@ -336,7 +336,7 @@ func (s *ApiKeyService) listManagedAPIKeys(tx *gorm.DB, userID string) ([]modelsif err := tx.Where("user_id = ? AND managed_by = ?", userID, managedByAdminBootstrap).Order("created_at asc, id asc").Find(&managedKeys).Error; err != nil {- return nil, fmt.Errorf("failed to load managed API keys: %w", err)+ return nil, errors.WrapIf(err, "failed to load managed API keys")}return managedKeys, nil@@ -347,7 +347,7 @@ func (s *ApiKeyService) deleteManagedAPIKeysByIDs(tx *gorm.DB, ids []string) errreturn nil}if err := tx.Delete(&models.ApiKey{}, "id IN ?", ids).Error; err != nil {- return fmt.Errorf("failed to delete managed API keys: %w", err)+ return errors.WrapIf(err, "failed to delete managed API keys")}return nil}@@ -380,7 +380,7 @@ func (s *ApiKeyService) updateMatchingManagedAPIKey(tx *gorm.DB, apiKeyID string"description": defaultAdminAPIKeyDescription,"managed_by": managedByAdminBootstrap,}).Error; err != nil {- return fmt.Errorf("failed to update managed API key metadata: %w", err)+ return errors.WrapIf(err, "failed to update managed API key metadata")}return nil}@@ -393,7 +393,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, rawkeyHash, err := s.hashApiKey(rawKey)if err != nil {- return fmt.Errorf("failed to hash API key: %w", err)+ return errors.WrapIf(err, "failed to hash API key")}ak := &models.ApiKey{@@ -406,7 +406,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, raw}if err := tx.Create(ak).Error; err != nil {- return fmt.Errorf("failed to create managed API key: %w", err)+ return errors.WrapIf(err, "failed to create managed API key")}return nil}@@ -483,7 +483,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment}}if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {- return nil, fmt.Errorf("failed to persist environment bootstrap key permissions: %w", err)+ return nil, errors.WrapIf(err, "failed to persist environment bootstrap key permissions")}// Re-load grants into the response DTO so callers see the seeded// permissions immediately, not null.@@ -502,7 +502,7 @@ func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKeif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrApiKeyNotFound}- return nil, fmt.Errorf("failed to get API key: %w", err)+ return nil, errors.WrapIf(err, "failed to get API key")}return new(toAPIKeyDTOWithPermissionsInternal(&ak)), nil}@@ -524,7 +524,7 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QuerypaginationResp, err := pagination.PaginateAndSortDB(params, query, &apiKeys)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate API keys: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate API keys")}result := make([]apikey.ApiKey, len(apiKeys))@@ -550,7 +550,7 @@ func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([Where("user_id = ?", userID).Order("created_at DESC").Find(&apiKeys).Error; err != nil {- return nil, fmt.Errorf("failed to list user api keys: %w", err)+ return nil, errors.WrapIf(err, "failed to list user api keys")}result := make([]apikey.ApiKey, 0, len(apiKeys))@@ -569,7 +569,7 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Perif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrApiKeyNotFound}- return nil, fmt.Errorf("failed to get API key: %w", err)+ return nil, errors.WrapIf(err, "failed to get API key")}if isStaticAPIKeyInternal(ak) || isEnvironmentBootstrapKeyInternal(ak) {return nil, ErrApiKeyProtected@@ -612,11 +612,11 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.PerpermissionsUpdated := falseif err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Save(&ak).Error; err != nil {- return fmt.Errorf("failed to update API key: %w", err)+ return errors.WrapIf(err, "failed to update API key")}if req.Permissions != nil && s.roleService != nil {if err := s.roleService.setApiKeyPermissionsInternal(ctx, tx, ak.ID, toApiKeyPermissionRowsInternal(ak.ID, req.Permissions)); err != nil {- return fmt.Errorf("failed to update api key permissions: %w", err)+ return errors.WrapIf(err, "failed to update api key permissions")}permissionsUpdated = true}@@ -673,7 +673,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {if errors.Is(err, gorm.ErrRecordNotFound) {return ErrApiKeyNotFound}- return fmt.Errorf("failed to load API key: %w", err)+ return errors.WrapIf(err, "failed to load API key")}if isStaticAPIKeyInternal(apiKey) || isEnvironmentBootstrapKeyInternal(apiKey) {return ErrApiKeyProtected@@ -681,7 +681,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {result := s.db.WithContext(ctx).Delete(&models.ApiKey{}, "id = ?", id)if result.Error != nil {- return fmt.Errorf("failed to delete API key: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete API key")}if result.RowsAffected == 0 {return ErrApiKeyNotFound@@ -704,7 +704,7 @@ func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string)var apiKeys []models.ApiKeyif err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {- return nil, nil, fmt.Errorf("failed to find API keys: %w", err)+ return nil, nil, errors.WrapIf(err, "failed to find API keys")}rawKey = normalizeAPIKeyInputInternal(rawKey)@@ -724,7 +724,7 @@ func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string)user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)if err != nil {- return nil, nil, fmt.Errorf("failed to get user for API key: %w", err)+ return nil, nil, errors.WrapIf(err, "failed to get user for API key")}return user, &apiKey, nil@@ -742,7 +742,7 @@ func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey strinvar apiKeys []models.ApiKeyif err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {- return nil, fmt.Errorf("failed to find API keys: %w", err)+ return nil, errors.WrapIf(err, "failed to find API keys")}rawKey = normalizeAPIKeyInputInternal(rawKey)diff --git a/backend/internal/services/app_images_service.go b/backend/internal/services/app_images_service.goindex 949a1ee4d..9f26897e8 100644--- a/backend/internal/services/app_images_service.go+++ b/backend/internal/services/app_images_service.go@@ -2,12 +2,12 @@ package servicesimport ("embed"- "fmt""io/fs""path/filepath""strings""sync"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/image""github.com/getarcaneapp/arcane/types/v2/settings")@@ -66,7 +66,7 @@ func (s *ApplicationImagesService) GetImageWithColor(name string, colorOverrides.mu.RUnlock()if !ok {- return nil, "", fmt.Errorf("image '%s' not found", name)+ return nil, "", errors.Errorf("image '%s' not found", name)}// Apply dynamic color replacement for logo SVGsdiff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex 0dd97dbdc..d1d371962 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -4,12 +4,14 @@ import ("context""crypto/sha256""encoding/hex"- "errors""fmt""log/slog""strings""time"+ "emperror.dev/emperror"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -20,14 +22,14 @@ import ("github.com/samber/hot")-var (- ErrInvalidCredentials = errors.New("invalid credentials")- ErrUserNotFound = errors.New("user not found")- ErrInvalidToken = errors.New("invalid token")- ErrExpiredToken = errors.New("token expired")- ErrTokenVersionMismatch = errors.New("token version mismatch")- ErrLocalAuthDisabled = errors.New("local authentication is disabled")- ErrOidcAuthDisabled = errors.New("OIDC authentication is disabled")+const (+ ErrInvalidCredentials = errors.Sentinel("invalid credentials")+ ErrUserNotFound = errors.Sentinel("user not found")+ ErrInvalidToken = errors.Sentinel("invalid token")+ ErrExpiredToken = errors.Sentinel("token expired")+ ErrTokenVersionMismatch = errors.Sentinel("token version mismatch")+ ErrLocalAuthDisabled = errors.Sentinel("local authentication is disabled")+ ErrOidcAuthDisabled = errors.Sentinel("OIDC authentication is disabled"))type TokenPair struct {@@ -78,6 +80,7 @@ type AuthService struct {jwtSecret []byterefreshExpiry time.Durationconfig *config.Config+ errorHandler emperror.ErrorHandler// tokenCache is a per-process in-memory cache. In horizontally-scaled// deployments, RevokeSession / ChangePassword / InvalidateUserTokenCache// only purge the local instance; peers continue to accept the token until@@ -85,10 +88,13 @@ type AuthService struct {tokenCache *hot.HotCache[string, verifiedTokenEntry]}-func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, roleService *RoleService, jwtSecret string, cfg *config.Config) *AuthService {+func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, roleService *RoleService, jwtSecret string, cfg *config.Config, errorHandler emperror.ErrorHandler) *AuthService {// Production managers must supply an explicit, non-default JWT_SECRET (fail// closed, mirroring the ENCRYPTION_KEY guard). Dev and agent mode auto-generate.requireExplicitSecret := cfg.Environment == config.AppEnvironmentProduction && !cfg.AgentMode+ if errorHandler == nil {+ errorHandler = emperror.NoopHandler{}+ }return &AuthService{userService: userService,settingsService: settingsService,@@ -98,6 +104,7 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,jwtSecret: jwtclaims.CheckOrGenerateJwtSecret(jwtSecret, requireExplicitSecret),refreshExpiry: cfg.JWTRefreshExpiry,config: cfg,+ errorHandler: errorHandler,tokenCache: hot.NewHotCache[string, verifiedTokenEntry](hot.LRU, 4096).WithTTL(15 * time.Second).WithJanitor().@@ -108,7 +115,7 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {settings, err := s.settingsService.GetSettings(ctx)if err != nil {- return nil, fmt.Errorf("failed to get settings: %w", err)+ return nil, errors.WrapIf(err, "failed to get settings")}timeoutMinutes, _ := s.GetSessionTimeout(ctx)@@ -254,7 +261,7 @@ func (s *AuthService) Login(ctx context.Context, username, password string, metaif s.userService.NeedsPasswordUpgrade(user.PasswordHash) {s.runInBackground(ctx, "upgrade_password_hash", func(ctx context.Context) error {if err := s.userService.UpgradePasswordHash(ctx, user.ID, password); err != nil {- return fmt.Errorf("failed to upgrade password hash for user %s: %w", user.ID, err)+ return errors.WrapIff(err, "failed to upgrade password hash for user %s", user.ID)}slog.InfoContext(ctx, "Successfully upgraded password hash from bcrypt to Argon2", "user", user.Username)return nil@@ -268,7 +275,7 @@ func (s *AuthService) Login(ctx context.Context, username, password string, metauserCopy := new(*user)s.runInBackground(ctx, "update_last_login", func(ctx context.Context) error {if _, err := s.userService.UpdateUser(ctx, userCopy); err != nil {- return fmt.Errorf("failed to update user's last login time: %w", err)+ return errors.WrapIf(err, "failed to update user's last login time")}return nil})@@ -510,7 +517,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *models.groups := s.extractOidcGroups(ctx, userInfo, tokenResp)mappings, err := s.roleService.ListOidcMappings(ctx)if err != nil {- return fmt.Errorf("list oidc mappings: %w", err)+ return errors.WrapIf(err, "list oidc mappings")}groupSet := make(map[string]struct{}, len(groups))@@ -625,7 +632,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, mettoken, err := jwt.ParseWithClaims(refreshToken, &refreshClaims{},func(t *jwt.Token) (any, error) {if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {- return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])+ return nil, errors.Errorf("unexpected signing method: %v", t.Header["alg"])}return s.jwtSecret, nil})@@ -639,11 +646,11 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, metclaims, ok := token.Claims.(*refreshClaims)if !ok {- return nil, &common.InvalidTokenClaimsError{}+ return nil, common.Classify(common.ErrTokenValidation, errors.New("Invalid token claims"))}if claims.Subject != "refresh" {- return nil, &common.RefreshTokenSubjectError{}+ return nil, common.Classify(common.ErrTokenValidation, errors.New("Not a refresh token"))}if claims.AppVersion != "" && claims.AppVersion != config.Version {@@ -651,16 +658,16 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, met}if claims.UserID == "" {- return nil, &common.MissingTokenUserIDError{}+ return nil, common.Classify(common.ErrTokenValidation, errors.New("Missing user ID in token"))}if claims.ID == "" {- return nil, &common.MissingRefreshTokenIDError{}+ return nil, common.Classify(common.ErrTokenValidation, errors.New("Missing refresh token ID"))}if claims.SessionID == "" {- return nil, &common.MissingTokenSessionIDError{}+ return nil, common.Classify(common.ErrTokenValidation, errors.New("Missing session ID in token"))}if s.sessionService == nil {- return nil, &common.SessionServiceUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}session, err := s.sessionService.GetSessionByID(ctx, claims.SessionID)@@ -691,7 +698,7 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modtoken, err := jwt.ParseWithClaims(accessToken, &userClaims{},func(t *jwt.Token) (any, error) {if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {- return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])+ return nil, errors.Errorf("unexpected signing method: %v", t.Header["alg"])}return s.jwtSecret, nil})@@ -708,15 +715,15 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modclaims, ok := token.Claims.(*userClaims)if !ok {- return nil, "", &common.InvalidTokenClaimsError{}+ return nil, "", common.Classify(common.ErrTokenValidation, errors.New("Invalid token claims"))}if claims.Subject != "access" {- return nil, "", &common.AccessTokenSubjectError{}+ return nil, "", common.Classify(common.ErrTokenValidation, errors.New("Not an access token"))}if claims.ID == "" {- return nil, "", &common.MissingTokenUserIDError{}+ return nil, "", common.Classify(common.ErrTokenValidation, errors.New("Missing user ID in token"))}if claims.AppVersion != "" && claims.AppVersion != config.Version {@@ -724,10 +731,10 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modreturn nil, "", ErrTokenVersionMismatch}if claims.SessionID == "" {- return nil, "", &common.MissingTokenSessionIDError{}+ return nil, "", common.Classify(common.ErrTokenValidation, errors.New("Missing session ID in token"))}if s.sessionService == nil {- return nil, "", &common.SessionServiceUnavailableError{}+ return nil, "", common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}tokenHash := hashTokenInternal(accessToken)@@ -769,7 +776,7 @@ func hashTokenInternal(token string) string {func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword, currentSessionID string) error {if s.sessionService == nil {- return &common.SessionServiceUnavailableError{}+ return common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}user, err := s.userService.GetUserByID(ctx, userID)@@ -785,7 +792,7 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassworhashedPassword, err := s.userService.hashPassword(newPassword)if err != nil {- return fmt.Errorf("failed to hash password: %w", err)+ return errors.WrapIf(err, "failed to hash password")}user.PasswordHash = hashedPassword@@ -855,7 +862,7 @@ func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, currenfunc (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *models.User, meta auth.SessionMeta) (*TokenPair, error) {if s.sessionService == nil {- return nil, &common.SessionServiceUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}refreshExpiry := time.Now().Add(s.refreshExpiry)session, refreshJTI, err := s.sessionService.CreateSession(ctx, user.ID, refreshExpiry, meta)@@ -924,7 +931,7 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *models.Ufunc (s *AuthService) IssueFederatedToken(ctx context.Context, user *models.User, credentialID string, ttlSeconds int) (*TokenPair, error) {if s.sessionService == nil {- return nil, &common.SessionServiceUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}if user == nil {return nil, ErrUserNotFound@@ -991,7 +998,7 @@ func validateSessionActiveInternal(session *models.UserSession) error {return ErrInvalidToken}if session.RevokedAt != nil {- return &common.SessionRevokedError{}+ return common.Classify(common.ErrSessionRevoked, errors.New("Session has been revoked"))}if time.Now().After(session.ExpiresAt) {return ErrExpiredToken@@ -1019,8 +1026,13 @@ func (s *AuthService) runInBackground(ctx context.Context, name string, fn func(go func() {defer func() {- if r := recover(); r != nil {- slog.ErrorContext(bgCtx, "Background task panicked", "task", name, "panic", r)+ if panicErr := emperror.Recover(recover()); panicErr != nil {+ panicErr = errors.WithDetails(errors.WrapIf(panicErr, "Background task panicked"), "task", name)+ if contextHandler, ok := s.errorHandler.(emperror.ErrorHandlerContext); ok {+ contextHandler.HandleContext(bgCtx, panicErr)+ } else {+ s.errorHandler.Handle(panicErr)+ }}}()diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.goindex d7918ab6e..492b66274 100644--- a/backend/internal/services/auth_service_test.go+++ b/backend/internal/services/auth_service_test.go@@ -233,7 +233,7 @@ func TestVerifyToken_InvalidSubject(t *testing.T) {token := makeAccessToken(t, s.jwtSecret, "refresh", "u1", "bob", []string{"user"}, "", "", exp)_, _, err := s.VerifyToken(context.Background(), token)- require.ErrorAs(t, err, new(*common.AccessTokenSubjectError))+ require.ErrorIs(t, err, common.ErrTokenValidation)}func TestVerifyToken_InvalidSignature(t *testing.T) {@@ -257,7 +257,7 @@ func TestVerifyToken_MissingUserID(t *testing.T) {token := makeAccessToken(t, s.jwtSecret, "access", "", "bob", []string{"user"}, "", "", exp)_, _, err := s.VerifyToken(context.Background(), token)- require.ErrorAs(t, err, new(*common.MissingTokenUserIDError))+ require.ErrorIs(t, err, common.ErrTokenValidation)}func TestGenerateUsernameFromEmail(t *testing.T) {@@ -421,7 +421,7 @@ func TestVerifyToken_RejectsRevokedSession(t *testing.T) {token := makeAccessToken(t, s.jwtSecret, "access", user.ID, user.Username, []string{"user"}, "", "", exp, session.ID)_, _, err = s.VerifyToken(context.Background(), token)- require.True(t, common.IsSessionRevokedError(err))+ require.True(t, errors.Is(err, common.ErrSessionRevoked))}func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {@@ -441,7 +441,7 @@ func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {token := makeAccessToken(t, s.jwtSecret, "access", user.ID, user.Username, []string{"user"}, "", "", time.Now().Add(5*time.Minute))_, _, err = s.VerifyToken(context.Background(), token)- require.ErrorAs(t, err, new(*common.MissingTokenSessionIDError))+ require.ErrorIs(t, err, common.ErrTokenValidation)}func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {@@ -464,7 +464,7 @@ func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {require.NoError(t, s.RevokeSession(context.Background(), session.ID))_, _, err = s.VerifyToken(context.Background(), token)- require.True(t, common.IsSessionRevokedError(err))+ require.True(t, errors.Is(err, common.ErrSessionRevoked))}func TestRefreshToken_RotatesJTI(t *testing.T) {@@ -519,7 +519,7 @@ func TestRefreshToken_RejectsRevokedSession(t *testing.T) {token := makeRefreshToken(t, s.jwtSecret, "refresh", refreshJTI, exp, user.ID, session.ID)_, err = s.RefreshToken(context.Background(), token, auth.SessionMeta{})- require.True(t, common.IsSessionRevokedError(err))+ require.True(t, errors.Is(err, common.ErrSessionRevoked))}func TestChangePassword_RevokesAllSessions(t *testing.T) {diff --git a/backend/internal/services/build_service.go b/backend/internal/services/build_service.goindex 36fe78949..2b7a5ed5a 100644--- a/backend/internal/services/build_service.go+++ b/backend/internal/services/build_service.go@@ -3,7 +3,6 @@ package servicesimport ("context"json "encoding/json/v2"- "errors""fmt""io""log/slog"@@ -13,6 +12,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"buildgit "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil"@@ -258,7 +259,7 @@ func (s *BuildService) resolveBuildRequestInternal(}if !ok || source == nil {if contextsource.IsPotentialRemoteBuildContextSource(req.ContextDir) {- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("unsupported remote build context source %q: only git repository URLs are supported", req.ContextDir)+ return buildtypes.BuildRequest{}, func() error { return nil }, errors.Errorf("unsupported remote build context source %q: only git repository URLs are supported", req.ContextDir)}return req, func() error { return nil }, nil}@@ -275,7 +276,7 @@ func (s *BuildService) resolveBuildRequestInternal(if contextsource.RequiresGitRemoteProbe(source.RepositoryURL) {writeBuildProgressStatusInternal(progressWriter, serviceName, "verifying remote git repository "+source.RepositoryURL)if err := s.probeGitContextInternal(ctx, source.RepositoryURL, authConfig); err != nil {- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to verify remote git repository %q: %w", source.RepositoryURL, err)+ return buildtypes.BuildRequest{}, func() error { return nil }, errors.WrapIff(err, "failed to verify remote git repository %q", source.RepositoryURL)}}@@ -288,7 +289,7 @@ func (s *BuildService) resolveBuildRequestInternal(if source.Subdir != "" {if err := buildgit.ValidatePath(repoPath, filepath.FromSlash(source.Subdir)); err != nil {_ = s.cleanupGitContextInternal(repoPath)- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("invalid git build context subdir: %w", err)+ return buildtypes.BuildRequest{}, func() error { return nil }, errors.WrapIf(err, "invalid git build context subdir")}contextDir = filepath.Join(repoPath, filepath.FromSlash(source.Subdir))}@@ -296,7 +297,7 @@ func (s *BuildService) resolveBuildRequestInternal(info, err := os.Stat(contextDir)if err != nil {_ = s.cleanupGitContextInternal(repoPath)- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to stat resolved git build context: %w", err)+ return buildtypes.BuildRequest{}, func() error { return nil }, errors.WrapIf(err, "failed to stat resolved git build context")}if !info.IsDir() {_ = s.cleanupGitContextInternal(repoPath)@@ -318,7 +319,7 @@ func (s *BuildService) resolveGitBuildAuthInternal(ctx context.Context, rawURL srepository, err := s.gitRepository.FindEnabledRepositoryByURL(ctx, rawURL)if err != nil {- return buildgit.AuthConfig{}, false, fmt.Errorf("failed to resolve git repository credentials: %w", err)+ return buildgit.AuthConfig{}, false, errors.WrapIf(err, "failed to resolve git repository credentials")}if repository == nil {return buildgit.AuthConfig{}, false, nil@@ -326,7 +327,7 @@ func (s *BuildService) resolveGitBuildAuthInternal(ctx context.Context, rawURL sauthConfig, err := s.gitRepository.GetAuthConfig(ctx, repository)if err != nil {- return buildgit.AuthConfig{}, true, fmt.Errorf("failed to load git repository credentials: %w", err)+ return buildgit.AuthConfig{}, true, errors.WrapIf(err, "failed to load git repository credentials")}return authConfig, true, nil@@ -412,7 +413,7 @@ func (s *BuildService) ListImageBuildsByEnvironmentPaginated(ctx context.ContextpaginationResp, err := pagination.PaginateAndSortDB(params, q, &builds)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate builds: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate builds")}records := make([]imagetypes.BuildRecord, 0, len(builds))@@ -480,7 +481,7 @@ func (s *BuildService) createBuildRecord(ctx context.Context, environmentID stri}if err := s.db.WithContext(ctx).Create(record).Error; err != nil {- return nil, fmt.Errorf("failed to create build record: %w", err)+ return nil, errors.WrapIf(err, "failed to create build record")}return record, nil@@ -516,7 +517,7 @@ func (s *BuildService) completeBuildRecord(return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Model(&models.ImageBuild{}).Where("id = ?", buildID).Updates(updates)if result.Error != nil {- return fmt.Errorf("failed to update build record: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to update build record")}if result.RowsAffected == 0 {return errors.New("build record not found")diff --git a/backend/internal/services/build_workspace_service.go b/backend/internal/services/build_workspace_service.goindex 6d9fb117b..6ac3ec108 100644--- a/backend/internal/services/build_workspace_service.go+++ b/backend/internal/services/build_workspace_service.go@@ -2,8 +2,6 @@ package servicesimport ("context"- "errors"- "fmt""io""net/http""os"@@ -11,6 +9,8 @@ import ("path/filepath""strings"+ "emperror.dev/errors"+"log/slog""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -37,7 +37,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strincleaned, err := utils.SanitizeBrowsePath(dirPath)if err != nil {- return nil, fmt.Errorf("invalid path: %w", err)+ return nil, errors.WrapIf(err, "invalid path")}targetPath, err := joinBuildRoot(root, cleaned)@@ -47,7 +47,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strinentries, err := os.ReadDir(targetPath)if err != nil {- return nil, fmt.Errorf("failed to list directory: %w", err)+ return nil, errors.WrapIf(err, "failed to list directory")}results := make([]volumetypes.FileEntry, 0, len(entries))@@ -97,7 +97,7 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strcleaned, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return nil, "", fmt.Errorf("invalid path: %w", err)+ return nil, "", errors.WrapIf(err, "invalid path")}fullPath, err := joinBuildRoot(root, cleaned)@@ -107,7 +107,7 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strinfo, err := os.Stat(fullPath)if err != nil {- return nil, "", fmt.Errorf("failed to stat file: %w", err)+ return nil, "", errors.WrapIf(err, "failed to stat file")}if info.IsDir() {return nil, "", errors.New("path is a directory")@@ -119,13 +119,13 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strfile, err := os.Open(fullPath)if err != nil {- return nil, "", fmt.Errorf("failed to open file: %w", err)+ return nil, "", errors.WrapIf(err, "failed to open file")}defer func() { _ = file.Close() }()content, err := io.ReadAll(io.LimitReader(file, maxBytes))if err != nil {- return nil, "", fmt.Errorf("failed to read file: %w", err)+ return nil, "", errors.WrapIf(err, "failed to read file")}mimeType := http.DetectContentType(content)@@ -141,7 +141,7 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strincleaned, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return nil, 0, fmt.Errorf("invalid path: %w", err)+ return nil, 0, errors.WrapIf(err, "invalid path")}fullPath, err := joinBuildRoot(root, cleaned)@@ -151,7 +151,7 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strininfo, err := os.Stat(fullPath)if err != nil {- return nil, 0, fmt.Errorf("failed to stat file: %w", err)+ return nil, 0, errors.WrapIf(err, "failed to stat file")}if info.IsDir() {return nil, 0, errors.New("path is a directory")@@ -159,7 +159,7 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strinfile, err := os.Open(fullPath)if err != nil {- return nil, 0, fmt.Errorf("failed to open file: %w", err)+ return nil, 0, errors.WrapIf(err, "failed to open file")}return file, info.Size(), nil@@ -179,7 +179,7 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,cleaned, err := utils.SanitizeBrowsePath(destPath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}dirPath, err := joinBuildRoot(root, cleaned)@@ -188,18 +188,18 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,}if err := os.MkdirAll(dirPath, 0o755); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}targetFile := filepath.Join(dirPath, safeFilename)file, err := os.Create(targetFile)if err != nil {- return fmt.Errorf("failed to create file: %w", err)+ return errors.WrapIf(err, "failed to create file")}defer func() { _ = file.Close() }()if _, err := io.Copy(file, content); err != nil {- return fmt.Errorf("failed to write file: %w", err)+ return errors.WrapIf(err, "failed to write file")}return nil@@ -214,7 +214,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath strcleaned, err := utils.SanitizeBrowsePath(dirPath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}fullPath, err := joinBuildRoot(root, cleaned)@@ -227,7 +227,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath str}if err := os.MkdirAll(fullPath, 0o755); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}return nil@@ -242,7 +242,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)cleaned, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}if cleaned == "/" {@@ -255,7 +255,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)}if err := os.RemoveAll(fullPath); err != nil {- return fmt.Errorf("failed to delete path: %w", err)+ return errors.WrapIf(err, "failed to delete path")}return nil@@ -277,7 +277,7 @@ func (s *BuildWorkspaceService) resolveRoot() (string, error) {cleaned := filepath.Clean(root)if err := os.MkdirAll(cleaned, 0o755); err != nil {- return "", fmt.Errorf("failed to ensure builds directory: %w", err)+ return "", errors.WrapIf(err, "failed to ensure builds directory")}return cleaned, nildiff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.goindex dc200b985..059c28d4d 100644--- a/backend/internal/services/container_registry_service.go+++ b/backend/internal/services/container_registry_service.go@@ -3,8 +3,7 @@ package servicesimport ("context"json "encoding/json/v2"- "errors"- "fmt"+ stderrors "errors""log/slog""net/http""strings"@@ -15,7 +14,9 @@ import ("github.com/samber/mo""golang.org/x/sync/singleflight"+ "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"@@ -117,7 +118,7 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetfunc (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]models.ContainerRegistry, error) {var registries []models.ContainerRegistryif err := s.db.WithContext(ctx).Find(®istries).Error; err != nil {- return nil, fmt.Errorf("failed to get container registries: %w", err)+ return nil, errors.WrapIf(err, "failed to get container registries")}return registries, nil}@@ -133,7 +134,7 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, pout, paginationResp, err := pagination.PaginateSortAndMapDB[models.ContainerRegistry, containerregistry.ContainerRegistry](params, q, ®istries)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list container registries: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list container registries")}return out, paginationResp, nil@@ -142,7 +143,7 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, pfunc (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id string) (*models.ContainerRegistry, error) {var registry models.ContainerRegistryif err := s.db.WithContext(ctx).Where("id = ?", id).First(®istry).Error; err != nil {- return nil, fmt.Errorf("failed to get container registry: %w", err)+ return nil, errors.WrapIf(err, "failed to get container registry")}return ®istry, nil}@@ -165,38 +166,38 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req modelif registryType == registryTypeECR {if strings.TrimSpace(req.AWSAccessKeyID) == "" {- return nil, &models.ValidationError{Field: "awsAccessKeyId", Message: "AWS Access Key ID is required"}+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Access Key ID is required"), "field", "awsAccessKeyId"))}if strings.TrimSpace(req.AWSRegion) == "" {- return nil, &models.ValidationError{Field: "awsRegion", Message: "AWS Region is required"}+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Region is required"), "field", "awsRegion"))}if strings.TrimSpace(req.AWSSecretAccessKey) == "" {- return nil, &models.ValidationError{Field: "awsSecretAccessKey", Message: "AWS Secret Access Key is required"}+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Secret Access Key is required"), "field", "awsSecretAccessKey"))}encryptedSecret, err := crypto.Encrypt(req.AWSSecretAccessKey)if err != nil {- return nil, fmt.Errorf("failed to encrypt AWS secret access key: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt AWS secret access key")}registry.AWSAccessKeyID = req.AWSAccessKeyIDregistry.AWSSecretAccessKey = encryptedSecretregistry.AWSRegion = req.AWSRegion} else {if strings.TrimSpace(req.Username) == "" {- return nil, &models.ValidationError{Field: "username", Message: "Username is required"}+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Username is required"), "field", "username"))}if strings.TrimSpace(req.Token) == "" {- return nil, &models.ValidationError{Field: "token", Message: "Token is required"}+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Token is required"), "field", "token"))}encryptedToken, err := crypto.Encrypt(req.Token)if err != nil {- return nil, fmt.Errorf("failed to encrypt token: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt token")}registry.Username = req.Usernameregistry.Token = encryptedToken}if err := s.db.WithContext(ctx).Create(registry).Error; err != nil {- return nil, fmt.Errorf("failed to create registry: %w", err)+ return nil, errors.WrapIf(err, "failed to create registry")}return registry, nil@@ -242,7 +243,7 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id stringregistry.UpdatedAt = time.Now()if err := s.db.WithContext(ctx).Save(registry).Error; err != nil {- return nil, fmt.Errorf("failed to update registry: %w", err)+ return nil, errors.WrapIf(err, "failed to update registry")}return registry, nil@@ -259,7 +260,7 @@ func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *mod}if nextType != registry.RegistryType {- return &models.ValidationError{Field: "registryType", Message: "Registry type cannot be changed after creation"}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Registry type cannot be changed after creation"), "field", "registryType"))}return nil@@ -272,19 +273,19 @@ func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *modif req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "" {encryptedSecret, err := crypto.Encrypt(*req.AWSSecretAccessKey)if err != nil {- return fmt.Errorf("failed to encrypt AWS secret access key: %w", err)+ return errors.WrapIf(err, "failed to encrypt AWS secret access key")}utils.ApplyChanged(®istry.AWSSecretAccessKey, mo.Some(encryptedSecret))}if strings.TrimSpace(registry.AWSAccessKeyID) == "" {- return &models.ValidationError{Field: "awsAccessKeyId", Message: "AWS Access Key ID is required"}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Access Key ID is required"), "field", "awsAccessKeyId"))}if strings.TrimSpace(registry.AWSRegion) == "" {- return &models.ValidationError{Field: "awsRegion", Message: "AWS Region is required"}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Region is required"), "field", "awsRegion"))}if strings.TrimSpace(registry.AWSSecretAccessKey) == "" {- return &models.ValidationError{Field: "awsSecretAccessKey", Message: "AWS Secret Access Key is required"}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Secret Access Key is required"), "field", "awsSecretAccessKey"))}if req.AWSAccessKeyID != nil || req.AWSSecretAccessKey != nil || req.AWSRegion != nil {@@ -301,13 +302,13 @@ func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registryif req.Token != nil && *req.Token != "" {encryptedToken, err := crypto.Encrypt(*req.Token)if err != nil {- return fmt.Errorf("failed to encrypt token: %w", err)+ return errors.WrapIf(err, "failed to encrypt token")}utils.ApplyChanged(®istry.Token, mo.Some(encryptedToken))}if strings.TrimSpace(registry.Username) == "" {- return &models.ValidationError{Field: "username", Message: "Username is required"}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Username is required"), "field", "username"))}return nil@@ -315,7 +316,7 @@ func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registryfunc (s *ContainerRegistryService) DeleteRegistry(ctx context.Context, id string) error {if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.ContainerRegistry{}).Error; err != nil {- return fmt.Errorf("failed to delete container registry: %w", err)+ return errors.WrapIf(err, "failed to delete container registry")}return nil}@@ -329,7 +330,7 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id strdecryptedToken, err := crypto.Decrypt(registry.Token)if err != nil {- return "", fmt.Errorf("failed to decrypt token: %w", err)+ return "", errors.WrapIf(err, "failed to decrypt token")}return decryptedToken, nil@@ -339,7 +340,7 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id strfunc (s *ContainerRegistryService) GetEnabledRegistries(ctx context.Context) ([]models.ContainerRegistry, error) {var registries []models.ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {- return nil, fmt.Errorf("failed to get enabled container registries: %w", err)+ return nil, errors.WrapIf(err, "failed to get enabled container registries")}return registries, nil}@@ -581,7 +582,7 @@ func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg motoken, err := crypto.Decrypt(reg.Token)if err != nil {- return nil, "credential", username, fmt.Errorf("failed to decrypt Docker Hub credential: %w", err)+ return nil, "credential", username, errors.WrapIf(err, "failed to decrypt Docker Hub credential")}token = strings.TrimSpace(token)@@ -672,7 +673,7 @@ func (s *ContainerRegistryService) setCachedRateLimitInternal(ctx context.Contexfunc normalizePullRegistryHostInternal(imageRef string) (string, error) {registryHost, err := utilsregistry.GetRegistryAddress(imageRef)if err != nil {- return "", fmt.Errorf("parse image registry for %q: %w", imageRef, err)+ return "", errors.WrapIff(err, "parse image registry for %q", imageRef)}return utilsregistry.NormalizeRegistryForComparison(registryHost), nil@@ -731,7 +732,7 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURLServerAddress: normalizeRegistryServerAddressInternal(registryURL),})if err != nil {- return fmt.Errorf("registry login failed: %w", err)+ return errors.WrapIf(err, "registry login failed")}return nil@@ -742,7 +743,7 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURLfunc (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *models.ContainerRegistry) error {ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)if err != nil {- return fmt.Errorf("failed to obtain ECR token: %w", err)+ return errors.WrapIf(err, "failed to obtain ECR token")}dockerClient, err := s.getDockerClientInternal(ctx)@@ -756,7 +757,7 @@ func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *modServerAddress: normalizeRegistryServerAddressInternal(reg.URL),})if err != nil {- return fmt.Errorf("ECR registry login failed: %w", err)+ return errors.WrapIf(err, "ECR registry login failed")}return nil@@ -850,7 +851,7 @@ func (s *ContainerRegistryService) inspectImageDigestInternal(ctx context.Contex}lastResult = fallbackResult- lastErr = fmt.Errorf("daemon digest lookup failed; registry fallback failed: %w", errors.Join(err, fallbackErr))+ lastErr = errors.WrapIf(stderrors.Join(err, fallbackErr), "daemon digest lookup failed; registry fallback failed")return nil, backoff.Permanent(lastErr)}, backoff.WithBackOff(bo), backoff.WithMaxTries(5))@@ -881,7 +882,7 @@ func (s *ContainerRegistryService) inspectImageDigestViaDaemonInternal(ctx conteif err == nil {digest, normalizeErr := updaterdigest.Normalize(inspectResult.Descriptor.Digest.String())if normalizeErr != nil {- return nil, fmt.Errorf("distribution inspect returned invalid digest for %s: %w", normalizedRef, normalizeErr)+ return nil, errors.WrapIff(normalizeErr, "distribution inspect returned invalid digest for %s", normalizedRef)}return ®istryDigestResult{Digest: digest,@@ -890,14 +891,14 @@ func (s *ContainerRegistryService) inspectImageDigestViaDaemonInternal(ctx conte}, nil}if !isUnauthorizedRegistryErrorInternal(err) {- return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost},- fmt.Errorf("distribution inspect failed for %s: %w", normalizedRef, err)+ return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost}, errors.+ WrapIff(err, "distribution inspect failed for %s", normalizedRef)}credentials, credErr := s.getMatchingRegistryCredentialsInternal(ctx, registryHost, externalCreds)if credErr != nil {- return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost},- fmt.Errorf("distribution inspect: anonymous access unauthorized; credential lookup failed: %w", errors.Join(err, credErr))+ return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost}, errors.+ WrapIf(stderrors.Join(err, credErr), "distribution inspect: anonymous access unauthorized; credential lookup failed")}return s.inspectImageDigestWithCredentialsInternal(ctx, dockerClient, normalizedRef, registryHost, credentials, err)@@ -910,7 +911,7 @@ func (s *ContainerRegistryService) inspectImageDigestWithCredentialsInternal(ctxlastCred = credentialauthHeader, encodeErr := utilsregistry.EncodeAuthHeader(credential.Username, credential.Token, credential.ServerAddress)if encodeErr != nil {- return nil, fmt.Errorf("encode registry auth header for %s: %w", registryHost, encodeErr)+ return nil, errors.WrapIff(encodeErr, "encode registry auth header for %s", registryHost)}inspectResult, err := dockerClient.DistributionInspect(ctx, normalizedRef, client.DistributionInspectOptions{@@ -919,7 +920,7 @@ func (s *ContainerRegistryService) inspectImageDigestWithCredentialsInternal(ctxif err == nil {digest, normalizeErr := updaterdigest.Normalize(inspectResult.Descriptor.Digest.String())if normalizeErr != nil {- return nil, fmt.Errorf("distribution inspect returned invalid digest for %s: %w", normalizedRef, normalizeErr)+ return nil, errors.WrapIff(normalizeErr, "distribution inspect returned invalid digest for %s", normalizedRef)}return ®istryDigestResult{Digest: digest,@@ -936,7 +937,7 @@ func (s *ContainerRegistryService) inspectImageDigestWithCredentialsInternal(ctxAuthUsername: credential.Username,AuthRegistry: registryHost,UsedCredential: true,- }, fmt.Errorf("distribution inspect failed for %s with credentials: %w", normalizedRef, err)+ }, errors.WrapIff(err, "distribution inspect failed for %s with credentials", normalizedRef)}}@@ -947,9 +948,9 @@ func (s *ContainerRegistryService) inspectImageDigestWithCredentialsInternal(ctxpartial.UsedCredential = true}if lastErr == nil {- return partial, fmt.Errorf("distribution inspect failed for %s: no credentials available", normalizedRef)+ return partial, errors.Errorf("distribution inspect failed for %s: no credentials available", normalizedRef)}- return partial, fmt.Errorf("distribution inspect failed for %s: %w", normalizedRef, lastErr)+ return partial, errors.WrapIff(lastErr, "distribution inspect failed for %s", normalizedRef)}func (s *ContainerRegistryService) inspectImageDigestViaRegistryInternal(ctx context.Context, registryHost, repository, tag string, externalCreds []containerregistry.Credential) (*registryDigestResult, error) {@@ -962,14 +963,14 @@ func (s *ContainerRegistryService) inspectImageDigestViaRegistryInternal(ctx con}, nil}if !isUnauthorizedRegistryErrorInternal(err) {- return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost},- fmt.Errorf("registry manifest inspect failed for %s/%s:%s: %w", registryHost, repository, tag, err)+ return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost}, errors.+ WrapIff(err, "registry manifest inspect failed for %s/%s:%s", registryHost, repository, tag)}credentials, credErr := s.getMatchingRegistryCredentialsInternal(ctx, registryHost, externalCreds)if credErr != nil {- return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost},- fmt.Errorf("registry manifest inspect: anonymous access unauthorized; credential lookup failed: %w", errors.Join(err, credErr))+ return ®istryDigestResult{AuthMethod: "anonymous", AuthRegistry: registryHost}, errors.+ WrapIf(stderrors.Join(err, credErr), "registry manifest inspect: anonymous access unauthorized; credential lookup failed")}lastErr := err@@ -998,7 +999,7 @@ func (s *ContainerRegistryService) inspectImageDigestViaRegistryInternal(ctx conpartial.UsedCredential = true}- return partial, fmt.Errorf("registry manifest inspect failed for %s/%s:%s: %w", registryHost, repository, tag, lastErr)+ return partial, errors.WrapIff(lastErr, "registry manifest inspect failed for %s/%s:%s", registryHost, repository, tag)}func (s *ContainerRegistryService) getDockerClientInternal(ctx context.Context) (RegistryDaemonClient, error) {@@ -1008,7 +1009,7 @@ func (s *ContainerRegistryService) getDockerClientInternal(ctx context.Context)dockerClient, err := s.dockerClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to get docker client: %w", err)+ return nil, errors.WrapIf(err, "failed to get docker client")}if dockerClient == nil {return nil, errors.New("docker client unavailable")@@ -1039,7 +1040,7 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx coregistries, err := s.GetEnabledRegistries(ctx)if err != nil {- return nil, fmt.Errorf("failed to load enabled registries: %w", err)+ return nil, errors.WrapIf(err, "failed to load enabled registries")}creds := make([]resolvedRegistryCredential, 0, len(registries))@@ -1114,7 +1115,7 @@ func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItemsfunc (s *ContainerRegistryService) getExistingRegistriesMapInternal(ctx context.Context) (map[string]*models.ContainerRegistry, error) {var existingRegistries []models.ContainerRegistryif err := s.db.WithContext(ctx).Find(&existingRegistries).Error; err != nil {- return nil, fmt.Errorf("failed to get existing registries: %w", err)+ return nil, errors.WrapIf(err, "failed to get existing registries")}existingMap := make(map[string]*models.ContainerRegistry)@@ -1142,7 +1143,7 @@ func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Coif needsUpdate {existing.UpdatedAt = time.Now()if err := s.db.WithContext(ctx).Save(existing).Error; err != nil {- return fmt.Errorf("failed to update registry %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to update registry %s", item.ID)}}@@ -1239,19 +1240,19 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.ContextencryptedToken, err := crypto.Encrypt(item.Token)if err != nil {- return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to encrypt token for new registry %s", item.ID)}newRegistry.Token = encryptedToken} else if item.AWSSecretAccessKey != "" {encryptedSecret, err := crypto.Encrypt(item.AWSSecretAccessKey)if err != nil {- return fmt.Errorf("failed to encrypt AWS secret for new registry %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to encrypt AWS secret for new registry %s", item.ID)}newRegistry.AWSSecretAccessKey = encryptedSecret}if err := s.db.WithContext(ctx).Create(newRegistry).Error; err != nil {- return fmt.Errorf("failed to create registry %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to create registry %s", item.ID)}return nil@@ -1267,10 +1268,7 @@ func normalizeRegistryTypeInternal(value string) (string, error) {case registryTypeGeneric, registryTypeECR:return registryType, nildefault:- return "", &models.ValidationError{- Field: "registryType",- Message: "Registry type must be one of: generic, ecr",- }+ return "", common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Registry type must be one of: generic, ecr"), "field", "registryType"))}}@@ -1278,7 +1276,7 @@ func (s *ContainerRegistryService) deleteUnsyncedInternal(ctx context.Context, efor id := range existingMap {if !syncedIDs[id] {if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.ContainerRegistry{}).Error; err != nil {- return fmt.Errorf("failed to delete registry %s: %w", id, err)+ return errors.WrapIff(err, "failed to delete registry %s", id)}}}diff --git a/backend/internal/services/container_registry_service_test.go b/backend/internal/services/container_registry_service_test.goindex 97a05df0a..f0ee60264 100644--- a/backend/internal/services/container_registry_service_test.go+++ b/backend/internal/services/container_registry_service_test.go@@ -3,7 +3,6 @@ package servicesimport ("context""encoding/json"- "errors""net/http""net/http/httptest""net/url"@@ -11,6 +10,8 @@ import ("testing""time"+ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2/containerregistry"dockerregistry "github.com/moby/moby/api/types/registry"@@ -342,9 +343,8 @@ func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "registryType", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "registryType")}func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(t *testing.T) {@@ -358,9 +358,8 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "username", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "username")}func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *testing.T) {@@ -374,9 +373,8 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "token", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "token")}func TestContainerRegistryService_CreateRegistry_AcceptsValidGenericCredentials(t *testing.T) {@@ -409,9 +407,8 @@ func TestContainerRegistryService_UpdateRegistry_RejectsBlankingUsername(t *test})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "username", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "username")}func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvided(t *testing.T) {@@ -462,9 +459,8 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "token", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "token")stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)require.NoError(t, loadErr)@@ -533,9 +529,8 @@ func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "registryType", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "registryType")}func TestContainerRegistryService_UpdateRegistry_AllowsSameRegistryType(t *testing.T) {diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex e893fdf70..3af80c062 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -4,7 +4,6 @@ import ("context""encoding/json/jsontext"json "encoding/json/v2"- "errors""fmt""io""log/slog"@@ -13,13 +12,14 @@ import ("sync""time"+ "emperror.dev/errors"+composetypes "github.com/compose-spec/compose-go/v2/types""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/events""github.com/moby/moby/api/types/network""github.com/moby/moby/client"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -196,7 +196,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "pull_image_timeout","image": imageName,})- return fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageName)+ return errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageName)}s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, models.JSON{@@ -204,7 +204,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "pull_image","image": imageName,})- return fmt.Errorf("failed to pull image %s: %w", imageName, pullErr)+ return errors.WrapIff(pullErr, "failed to pull image %s", imageName)}defer func() { _ = reader.Close() }()@@ -215,7 +215,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "complete_pull","image": imageName,})- return fmt.Errorf("failed to complete image pull: %w", streamErr)+ return errors.WrapIf(streamErr, "failed to complete image pull")}return nil@@ -229,7 +229,7 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conte"step": "rename_old","backupName": backupName,})- return fmt.Errorf("failed to rename existing container: %w", err)+ return errors.WrapIf(err, "failed to rename existing container")}}@@ -255,7 +255,7 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conte"action": "redeploy","step": "stop",})- return fmt.Errorf("failed to stop container: %w", err)+ return errors.WrapIf(err, "failed to stop container")}func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName, failedStep string, wasRunning bool, user models.User) {@@ -294,7 +294,7 @@ func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.ContedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": cfg.action})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}metadata := models.JSON{@@ -306,7 +306,7 @@ func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.Conteerr = s.eventService.LogContainerEvent(ctx, cfg.eventType, containerID, "name", user.ID, user.Username, "0", metadata)if err != nil {if !cfg.warnOnLogError {- return fmt.Errorf("failed to log action: %w", err)+ return errors.WrapIf(err, "failed to log action")}slog.WarnContext(ctx, "could not log container action", "action", cfg.action, "error", err)}@@ -403,7 +403,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "commit"})- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}repository := strings.TrimSpace(req.Repository)@@ -422,7 +422,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stri})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "container", containerID, reference, user.ID, user.Username, "0", err, models.JSON{"action": "commit", "reference": reference})- return nil, fmt.Errorf("failed to commit container: %w", err)+ return nil, errors.WrapIf(err, "failed to commit container")}metadata := models.JSON{@@ -480,7 +480,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont)return "", false, nil}- return "", true, fmt.Errorf("failed to look up compose project %s: %w", projectName, err)+ return "", true, errors.WrapIff(err, "failed to look up compose project %s", projectName)}if proj == nil {slog.WarnContext(ctx, "RedeployContainer: compose project not registered, falling back to standalone redeploy",@@ -506,7 +506,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont"projectId": proj.ID,"projectName": proj.Name,})- return "", true, fmt.Errorf("compose redeploy failed for %s/%s: %w", projectName, serviceName, err)+ return "", true, errors.WrapIff(err, "compose redeploy failed for %s/%s", projectName, serviceName)}newID := s.findComposeServiceContainerIDInternal(ctx, projectName, serviceName)@@ -569,7 +569,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "get_client",})- return "", fmt.Errorf("failed to connect to Docker: %w", err)+ return "", errors.WrapIf(err, "failed to connect to Docker")}containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})@@ -578,7 +578,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "inspect",})- return "", fmt.Errorf("failed to inspect container: %w", err)+ return "", errors.WrapIf(err, "failed to inspect container")}containerInfo := containerJSON.Container@@ -588,7 +588,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "validate_config",})- return "", fmt.Errorf("failed to redeploy container: %w", err)+ return "", errors.WrapIf(err, "failed to redeploy container")}containerName := strings.TrimPrefix(containerInfo.Name, "/")@@ -598,7 +598,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcurrentContainerID, currentContainerErr := cgroup.CurrentContainerID()if libupdater.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {- err = &common.ArcaneSelfRedeployError{}+ err = errors.New("arcane cannot redeploy itself; use the system upgrade flow (Settings -> Updates) instead")s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{"action": "redeploy","step": "self_redeploy_blocked",@@ -659,7 +659,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"step": "create","image": imageName,})- return "", fmt.Errorf("failed to recreate container: %w", err)+ return "", errors.WrapIf(err, "failed to recreate container")}if shouldStartRedeployedContainerInternal(containerInfo, wasRunning) {@@ -678,7 +678,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"step": "start","image": imageName,})- return "", fmt.Errorf("failed to start new container: %w", err)+ return "", errors.WrapIf(err, "failed to start new container")}}@@ -712,12 +712,12 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stfunc (s *ContainerService) GetContainerByReference(ctx context.Context, ref string) (*container.InspectResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, ref, client.ContainerInspectOptions{})if err != nil {- return nil, fmt.Errorf("container not found: %w", err)+ return nil, errors.WrapIf(err, "container not found")}return new(containerInspect.Container), nil@@ -759,7 +759,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}// Get container mounts before deletion if we need to remove volumes@@ -783,7 +783,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})- return fmt.Errorf("failed to delete container: %w", err)+ return errors.WrapIf(err, "failed to delete container")}// Remove named volumes if requested@@ -803,7 +803,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID strierr = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDelete, containerID, "name", user.ID, user.Username, "0", metadata)if err != nil {- return fmt.Errorf("failed to log action: %w", err)+ return errors.WrapIf(err, "failed to log action")}return nil@@ -813,7 +813,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image})- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.ImageInspect(ctx, config.Image)@@ -835,17 +835,17 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containeif pullErr != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, models.JSON{"action": "create", "image": config.Image, "step": "pull_image_timeout"})- return nil, fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)+ return nil, errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)}s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, models.JSON{"action": "create", "image": config.Image, "step": "pull_image"})- return nil, fmt.Errorf("failed to pull image %s: %w", config.Image, pullErr)+ return nil, errors.WrapIff(pullErr, "failed to pull image %s", config.Image)}defer func() { _ = reader.Close() }()streamErr := dockerutils.ConsumeJSONMessageStream(reader, nil)if streamErr != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "create", "image": config.Image, "step": "complete_pull"})- return nil, fmt.Errorf("failed to complete image pull: %w", streamErr)+ return nil, errors.WrapIf(streamErr, "failed to complete image pull")}}@@ -857,7 +857,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "create"})- return nil, fmt.Errorf("failed to create container: %w", err)+ return nil, errors.WrapIf(err, "failed to create container")}metadata := models.JSON{@@ -872,13 +872,13 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containeif _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "start"})- return nil, fmt.Errorf("failed to start container: %w", err)+ return nil, errors.WrapIf(err, "failed to start container")}containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "inspect"})- return nil, fmt.Errorf("failed to inspect created container: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect created container")}return new(containerJSON.Container), nil@@ -887,12 +887,12 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containefunc (s *ContainerService) StreamStats(ctx context.Context, containerID string, statsChan chan<- any) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}stats, err := dockerClient.ContainerStats(ctx, containerID, client.ContainerStatsOptions{Stream: true})if err != nil {- return fmt.Errorf("failed to start stats stream: %w", err)+ return errors.WrapIf(err, "failed to start stats stream")}defer func() { _ = stats.Body.Close() }()@@ -912,7 +912,7 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,if errors.Is(err, io.EOF) {return nil}- return fmt.Errorf("failed to decode stats: %w", err)+ return errors.WrapIf(err, "failed to decode stats")}recordedAt := statsData.Read@@ -943,12 +943,12 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,func (s *ContainerService) StreamLogs(ctx context.Context, containerID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {- return fmt.Errorf("failed to inspect container for logs: %w", err)+ return errors.WrapIf(err, "failed to inspect container for logs")}options := client.ContainerLogsOptions{@@ -962,7 +962,7 @@ func (s *ContainerService) StreamLogs(ctx context.Context, containerID string, llogs, err := dockerClient.ContainerLogs(ctx, containerID, options)if err != nil {- return fmt.Errorf("failed to get container logs: %w", err)+ return errors.WrapIf(err, "failed to get container logs")}defer func() { _ = logs.Close() }()@@ -987,12 +987,12 @@ func (s *ContainerService) ListContainersPaginated(} else {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return ContainerListResult{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return ContainerListResult{}, errors.WrapIf(err, "failed to connect to Docker")}containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: false})if err != nil {- return ContainerListResult{}, fmt.Errorf("failed to list Docker containers: %w", err)+ return ContainerListResult{}, errors.WrapIf(err, "failed to list Docker containers")}dockerContainers = containerList.Items}@@ -1515,7 +1515,7 @@ func (s *ContainerService) calculateContainerStatusCounts(items []containertypesfunc (s *ContainerService) CreateExec(ctx context.Context, containerID string, cmd []string) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", fmt.Errorf("failed to connect to Docker: %w", err)+ return "", errors.WrapIf(err, "failed to connect to Docker")}execConfig := client.ExecCreateOptions{@@ -1528,7 +1528,7 @@ func (s *ContainerService) CreateExec(ctx context.Context, containerID string, cexecResp, err := dockerClient.ExecCreate(ctx, containerID, execConfig)if err != nil {- return "", fmt.Errorf("failed to create exec: %w", err)+ return "", errors.WrapIf(err, "failed to create exec")}return execResp.ID, nil@@ -1568,14 +1568,14 @@ func (e *ExecSession) Close(ctx context.Context) error {func (s *ContainerService) AttachExec(ctx context.Context, containerID, execID string) (*ExecSession, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}execAttach, err := dockerClient.ExecAttach(ctx, execID, client.ExecAttachOptions{TTY: true,})if err != nil {- return nil, fmt.Errorf("failed to attach to exec: %w", err)+ return nil, errors.WrapIf(err, "failed to attach to exec")}return &ExecSession{diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.goindex 8df25e26a..c92a7d86f 100644--- a/backend/internal/services/dashboard_service.go+++ b/backend/internal/services/dashboard_service.go@@ -2,11 +2,11 @@ package servicesimport ("context"- "errors"- "fmt""sort""time"+ "emperror.dev/errors"+dockercontainer "github.com/moby/moby/api/types/container""golang.org/x/sync/errgroup"@@ -273,7 +273,7 @@ func (s *DashboardService) getPendingResourceUpdatesCountInternal(ctx context.Cocontainers, _, _, _, err := s.dockerService.GetAllContainers(ctx)if err != nil {- return 0, fmt.Errorf("failed to load containers for update counts: %w", err)+ return 0, errors.WrapIf(err, "failed to load containers for update counts")}filteredContainers := filterInternalContainers(containers, false)@@ -313,7 +313,7 @@ func (s *DashboardService) getPendingContainerUpdatesCountForImageIDsInternal(ctWhere("id IN ? AND has_update = ?", imageIDs, true).Count(&count).Errorif err != nil {- return 0, fmt.Errorf("failed to count pending container updates: %w", err)+ return 0, errors.WrapIf(err, "failed to count pending container updates")}return int(count), nil@@ -326,7 +326,7 @@ func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Concount, err := s.projectService.countProjectsByUpdateStatusInternal(ctx, "has_update")if err != nil {- return 0, fmt.Errorf("failed to count projects with updates: %w", err)+ return 0, errors.WrapIf(err, "failed to count projects with updates")}return count, nil@@ -351,7 +351,7 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)Where("expires_at <= ?", time.Now().Add(defaultDashboardAPIKeyExpiryWindow)).Count(&count).Errorif err != nil {- return 0, fmt.Errorf("failed to count expiring API keys: %w", err)+ return 0, errors.WrapIf(err, "failed to count expiring API keys")}return int(count), nildiff --git a/backend/internal/services/docker_client_service.go b/backend/internal/services/docker_client_service.goindex ea4f9a912..a426413e0 100644--- a/backend/internal/services/docker_client_service.go+++ b/backend/internal/services/docker_client_service.go@@ -2,14 +2,14 @@ package servicesimport ("context"- "errors"- "fmt""io""log/slog""strings""sync""time"+ "emperror.dev/errors"+"github.com/cenkalti/backoff/v5""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -70,7 +70,7 @@ func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, eclient.WithHost(host),)if err != nil {- return "", fmt.Errorf("failed to create Docker probe client: %w", err)+ return "", errors.WrapIf(err, "failed to create Docker probe client")}defer closeDockerClientInternal(probeClient, "failed to close probe Docker client")@@ -79,7 +79,7 @@ func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, epingResult, err := probeClient.Ping(ctx, client.PingOptions{})if err != nil {- return "", fmt.Errorf("failed to negotiate Docker API version: %w", err)+ return "", errors.WrapIf(err, "failed to negotiate Docker API version")}apiVersion := strings.TrimSpace(pingResult.APIVersion)@@ -97,7 +97,7 @@ func newDockerClientWithAPIVersionInternal(host string, apiVersion string) (*cliclient.WithAPIVersion(apiVersion),)if err != nil {- return nil, fmt.Errorf("failed to configure Docker client API version %s: %w", apiVersion, err)+ return nil, errors.WrapIff(err, "failed to configure Docker client API version %s", apiVersion)}return configuredClient, nil@@ -126,7 +126,7 @@ func (s *DockerClientService) GetClient(ctx context.Context) (*client.Client, ercli, err := newDockerClientInternal(ctx, s.config.DockerHost)if err != nil {- return nil, fmt.Errorf("failed to create Docker client: %w", err)+ return nil, errors.WrapIf(err, "failed to create Docker client")}s.mu.Lock()@@ -150,7 +150,7 @@ func (s *DockerClientService) GetClient(ctx context.Context) (*client.Client, erfunc (s *DockerClientService) RefreshClient(ctx context.Context) error {apiVersion, err := detectDockerAPIVersionInternal(ctx, s.config.DockerHost)if err != nil {- return fmt.Errorf("failed to refresh Docker client: %w", err)+ return errors.WrapIf(err, "failed to refresh Docker client")}s.mu.Lock()@@ -163,7 +163,7 @@ func (s *DockerClientService) RefreshClient(ctx context.Context) error {cli, err := newDockerClientWithAPIVersionInternal(s.config.DockerHost, apiVersion)if err != nil {- return fmt.Errorf("failed to refresh Docker client: %w", err)+ return errors.WrapIf(err, "failed to refresh Docker client")}s.mu.Lock()@@ -278,7 +278,7 @@ func sleepDockerEventBackoffInternal(ctx context.Context, eventBackoff *backoff.func (s *DockerClientService) listContainersInternal(ctx context.Context) ([]container.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}settings := s.settingsService.GetSettingsConfig()@@ -287,7 +287,7 @@ func (s *DockerClientService) listContainersInternal(ctx context.Context) ([]concontainerList, err := dockerClient.ContainerList(apiCtx, client.ContainerListOptions{All: true})if err != nil {- return nil, fmt.Errorf("failed to list Docker containers: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker containers")}return containerList.Items, nil}@@ -295,7 +295,7 @@ func (s *DockerClientService) listContainersInternal(ctx context.Context) ([]confunc (s *DockerClientService) listImagesInternal(ctx context.Context) ([]image.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}settings := s.settingsService.GetSettingsConfig()@@ -304,7 +304,7 @@ func (s *DockerClientService) listImagesInternal(ctx context.Context) ([]image.SimageList, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{All: true})if err != nil {- return nil, fmt.Errorf("failed to list Docker images: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker images")}return imageList.Items, nil}@@ -312,7 +312,7 @@ func (s *DockerClientService) listImagesInternal(ctx context.Context) ([]image.Sfunc (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]network.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}settings := s.settingsService.GetSettingsConfig()@@ -321,7 +321,7 @@ func (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]netwonetworkList, err := libarcane.NetworkListWithCompatibility(apiCtx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list Docker networks: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker networks")}return networkList.Items, nil}@@ -329,7 +329,7 @@ func (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]netwofunc (s *DockerClientService) listVolumesInternal(ctx context.Context) (*client.VolumeListResult, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}settings := s.settingsService.GetSettingsConfig()@@ -338,7 +338,7 @@ func (s *DockerClientService) listVolumesInternal(ctx context.Context) (*client.volResp, err := dockerClient.VolumeList(apiCtx, client.VolumeListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list Docker volumes: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker volumes")}return &volResp, nil}diff --git a/backend/internal/services/ecr_token_service.go b/backend/internal/services/ecr_token_service.goindex 22d370973..a8cda20b7 100644--- a/backend/internal/services/ecr_token_service.go+++ b/backend/internal/services/ecr_token_service.go@@ -3,15 +3,14 @@ package servicesimport ("context""encoding/base64"- "fmt""log/slog""strings""time"+ "emperror.dev/errors""github.com/aws/aws-sdk-go-v2/config""github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/service/ecr"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""go.getarcane.app/sys/crypto")@@ -51,7 +50,7 @@ func (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, reg}r, ok := result.(*ecrTokenResult)if !ok {- return "", "", &common.ECRTokenResultTypeError{}+ return "", "", errors.New("unexpected ECR token result type")}return r.username, r.password, nil}@@ -60,11 +59,11 @@ func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context,// Decrypt the stored AWS secret access key.secretKey, decErr := crypto.Decrypt(reg.AWSSecretAccessKey)if decErr != nil {- return nil, fmt.Errorf("failed to decrypt AWS secret key for registry %s: %w", reg.URL, decErr)+ return nil, errors.WrapIff(decErr, "failed to decrypt AWS secret key for registry %s", reg.URL)}secretKey = strings.TrimSpace(secretKey)if secretKey == "" {- return nil, fmt.Errorf("AWS secret access key is empty for registry %s", reg.URL)+ return nil, errors.Errorf("AWS secret access key is empty for registry %s", reg.URL)}// Call AWS ECR GetAuthorizationToken.@@ -77,33 +76,33 @@ func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context,)),)if cfgErr != nil {- return nil, fmt.Errorf("failed to load AWS config for registry %s: %w", reg.URL, cfgErr)+ return nil, errors.WrapIff(cfgErr, "failed to load AWS config for registry %s", reg.URL)}ecrClient := ecr.NewFromConfig(cfg)result, ecrErr := ecrClient.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})if ecrErr != nil {- return nil, fmt.Errorf("failed to get ECR authorization token for registry %s: %w", reg.URL, ecrErr)+ return nil, errors.WrapIff(ecrErr, "failed to get ECR authorization token for registry %s", reg.URL)}if len(result.AuthorizationData) == 0 || result.AuthorizationData[0].AuthorizationToken == nil {- return nil, fmt.Errorf("ECR returned empty authorization data for registry %s", reg.URL)+ return nil, errors.Errorf("ECR returned empty authorization data for registry %s", reg.URL)}// Decode base64 token → "AWS:<password>".decoded, decodeErr := base64.StdEncoding.DecodeString(*result.AuthorizationData[0].AuthorizationToken)if decodeErr != nil {- return nil, fmt.Errorf("failed to decode ECR token for registry %s: %w", reg.URL, decodeErr)+ return nil, errors.WrapIff(decodeErr, "failed to decode ECR token for registry %s", reg.URL)}parts := strings.SplitN(string(decoded), ":", 2)if len(parts) != 2 || parts[1] == "" {- return nil, fmt.Errorf("unexpected ECR token format for registry %s", reg.URL)+ return nil, errors.Errorf("unexpected ECR token format for registry %s", reg.URL)}ecrPassword := parts[1]// Persist the new token (encrypted) and generation timestamp.encryptedToken, encErr := crypto.Encrypt(ecrPassword)if encErr != nil {- return nil, fmt.Errorf("failed to encrypt ECR token for registry %s: %w", reg.URL, encErr)+ return nil, errors.WrapIff(encErr, "failed to encrypt ECR token for registry %s", reg.URL)}now := time.Now().UTC()reg.ECRToken = encryptedTokendiff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.goindex ee529d0eb..94e1dda16 100644--- a/backend/internal/services/environment_service.go+++ b/backend/internal/services/environment_service.go@@ -5,7 +5,6 @@ import ("context"json "encoding/json/v2"- "errors""fmt""log/slog""maps"@@ -14,6 +13,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -75,9 +76,9 @@ const (const edgeTokenCacheTTL = time.Minute-var (- ErrEnvironmentAccessTokenRequired = errors.New("environment access token required")- ErrInvalidEnvironmentAccessToken = errors.New("invalid environment access token")+const (+ ErrEnvironmentAccessTokenRequired = errors.Sentinel("environment access token required")+ ErrInvalidEnvironmentAccessToken = errors.Sentinel("invalid environment access token"))func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, apiKeyService *ApiKeyService) *EnvironmentService {@@ -178,7 +179,7 @@ func (s *EnvironmentService) listEnabledEnvironmentIDsInternal(ctx context.ConteTable("environments").Where("enabled = ?", true).Pluck("id", &ids).Error; err != nil {- return nil, fmt.Errorf("failed to list enabled environments: %w", err)+ return nil, errors.WrapIf(err, "failed to list enabled environments")}return ids, nil}@@ -293,7 +294,7 @@ func (s *EnvironmentService) ResolveEdgeEnvironmentByToken(ctx context.Context,s.logEdgeTokenResolveMissInternal(ctx, token)return "", errors.New("invalid agent token")}- return "", fmt.Errorf("failed to resolve edge environment by token: %w", err)+ return "", errors.WrapIf(err, "failed to resolve edge environment by token")}s.cacheEnvironmentTokenInternal(env.ID, token)@@ -494,7 +495,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl// Local environment already exists, ensure ApiUrl matches current appUrlif existingEnv.ApiUrl != appUrl {if err := s.db.WithContext(ctx).Model(&existingEnv).Update("api_url", appUrl).Error; err != nil {- return fmt.Errorf("failed to update local environment api url: %w", err)+ return errors.WrapIf(err, "failed to update local environment api url")}slog.InfoContext(ctx, "updated local environment api url", "id", localEnvID, "url", appUrl)}@@ -502,7 +503,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl}if !errors.Is(err, gorm.ErrRecordNotFound) {- return fmt.Errorf("failed to check for local environment: %w", err)+ return errors.WrapIf(err, "failed to check for local environment")}// Create the local environment@@ -520,7 +521,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl}if err := s.db.WithContext(ctx).Create(localEnv).Error; err != nil {- return fmt.Errorf("failed to create local environment: %w", err)+ return errors.WrapIf(err, "failed to create local environment")}slog.InfoContext(ctx, "created local environment record", "id", localEnvID)@@ -540,7 +541,7 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environmentenvironment.UpdatedAt = new(now)if err := s.db.WithContext(ctx).Create(environment).Error; err != nil {- return nil, fmt.Errorf("failed to create environment: %w", err)+ return nil, errors.WrapIf(err, "failed to create environment")}// Create event in background@@ -560,7 +561,7 @@ func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context,Model(&models.Environment{}).Where("parent_environment_id = ?", parentEnvironmentID).Find(&envs).Error; err != nil {- return nil, fmt.Errorf("failed to list swarm node agent environments: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm node agent environments")}return envs, nil@@ -577,7 +578,7 @@ func (s *EnvironmentService) ListSwarmNodeCandidateEnvironments(ctx context.ContWhere("id <> ?", "0").Order("name ASC").Find(&envs).Error; err != nil {- return nil, fmt.Errorf("failed to list swarm node candidate environments: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm node candidate environments")}return envs, nil@@ -593,7 +594,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(var environment models.Environmenterr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Where("id = ?", environmentID).First(&environment).Error; err != nil {- return fmt.Errorf("failed to load environment for swarm node binding: %w", err)+ return errors.WrapIf(err, "failed to load environment for swarm node binding")}if environment.Hidden {return errors.New("dedicated agent environments cannot be attached as visible environments")@@ -612,7 +613,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(if err := tx.Model(&models.Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).Count(&existingVisibleBindings).Error; err != nil {- return fmt.Errorf("failed to inspect existing swarm node binding: %w", err)+ return errors.WrapIf(err, "failed to inspect existing swarm node binding")}if existingVisibleBindings > 0 && !rebind {return errors.New("swarm node already has a visible environment binding; explicit rebinding is required")@@ -621,7 +622,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(if err := tx.Model(&models.Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": new(time.Now())}).Error; err != nil {- return fmt.Errorf("failed to clear previous swarm node binding: %w", err)+ return errors.WrapIf(err, "failed to clear previous swarm node binding")}}@@ -630,7 +631,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment("swarm_node_id": nodeID,"updated_at": new(time.Now()),}).Error; err != nil {- return fmt.Errorf("failed to bind environment to swarm node: %w", err)+ return errors.WrapIf(err, "failed to bind environment to swarm node")}return tx.Where("id = ?", environmentID).First(&environment).Error@@ -649,7 +650,7 @@ func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, parif err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ?", false, parentEnvironmentID, nodeID).Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": &now}).Error; err != nil {- return fmt.Errorf("failed to detach swarm node environment: %w", err)+ return errors.WrapIf(err, "failed to detach swarm node environment")}return nil@@ -665,7 +666,7 @@ func (s *EnvironmentService) DeleteSwarmNodeAgentDeployment(ctx context.Context,if errors.Is(err, gorm.ErrRecordNotFound) {return nil}- return fmt.Errorf("failed to load swarm node agent deployment: %w", err)+ return errors.WrapIf(err, "failed to load swarm node agent deployment")}return s.DeleteEnvironment(ctx, environment.ID, userID, username)@@ -710,7 +711,7 @@ func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(apiKeyDto, err := s.apiKeyService.CreateEnvironmentApiKey(ctx, env.ID, userID)if err != nil {- return "", fmt.Errorf("failed to create environment API key: %w", err)+ return "", errors.WrapIf(err, "failed to create environment API key")}if err := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); err != nil {@@ -742,7 +743,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(Order("hidden ASC").First(&env).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, "", fmt.Errorf("failed to load swarm node agent environment: %w", err)+ return nil, "", errors.WrapIf(err, "failed to load swarm node agent environment")}if errors.Is(err, gorm.ErrRecordNotFound) {@@ -758,7 +759,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(}if _, createErr := s.CreateEnvironment(ctx, createdEnv, new(userID), new(username)); createErr != nil {- return nil, "", fmt.Errorf("failed to create swarm node agent environment: %w", createErr)+ return nil, "", errors.WrapIf(createErr, "failed to create swarm node agent environment")}env = *createdEnv}@@ -770,7 +771,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(refreshedEnv, err := s.GetEnvironmentByID(ctx, env.ID)if err != nil {- return nil, "", fmt.Errorf("failed to refresh swarm node agent environment: %w", err)+ return nil, "", errors.WrapIf(err, "failed to refresh swarm node agent environment")}return refreshedEnv, apiKey, nil@@ -783,7 +784,7 @@ func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID,}if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update swarm node identity: %w", err)+ return errors.WrapIf(err, "failed to update swarm node identity")}return nil@@ -795,7 +796,7 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)if errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("environment not found")}- return nil, fmt.Errorf("failed to get environment: %w", err)+ return nil, errors.WrapIf(err, "failed to get environment")}return &environment, nil}@@ -831,12 +832,12 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parapaginationResp, err := pagination.PaginateAndSortDB(params, q, &envs)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate environments: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate environments")}out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)if mapErr != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)+ return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}return out, paginationResp, nil@@ -865,12 +866,12 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternalModel(&models.Environment{}).Where("hidden = ?", false).Find(&envs).Error; err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list environments: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list environments")}items, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)if mapErr != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)+ return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}// nil = no restriction; non-nil restricts to the caller's accessible envs.@@ -991,12 +992,12 @@ func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]envWhere("hidden = ?", false).Order("created_at asc, id asc").Find(&envs).Error; err != nil {- return nil, fmt.Errorf("failed to list visible environments: %w", err)+ return nil, errors.WrapIf(err, "failed to list visible environments")}out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)if mapErr != nil {- return nil, fmt.Errorf("failed to map environments: %w", mapErr)+ return nil, errors.WrapIf(mapErr, "failed to map environments")}for i := range out {@@ -1030,7 +1031,7 @@ func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]modeWhere("hidden = ?", false).Find(&envs).Errorif err != nil {- return nil, fmt.Errorf("failed to list remote environments: %w", err)+ return nil, errors.WrapIf(err, "failed to list remote environments")}s.syncRemoteEnvironmentSnapshotsInternal(envs)return envs, nil@@ -1041,7 +1042,7 @@ func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]modefunc (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Context) error {envs, err := s.ListRemoteEnvironments(ctx)if err != nil {- return fmt.Errorf("failed to list remote environments for registry sync: %w", err)+ return errors.WrapIf(err, "failed to list remote environments for registry sync")}if len(envs) == 0 {@@ -1067,7 +1068,7 @@ func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Cont}if failedCount > 0 {- return fmt.Errorf("failed to sync registries to %d remote environment(s)", failedCount)+ return errors.Errorf("failed to sync registries to %d remote environment(s)", failedCount)}return nil@@ -1077,7 +1078,7 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, uupdates["updated_at"] = new(time.Now())if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return nil, fmt.Errorf("failed to update environment: %w", err)+ return nil, errors.WrapIf(err, "failed to update environment")}updated, err := s.GetEnvironmentByID(ctx, id)@@ -1125,22 +1126,22 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, uif err := tx.Model(&models.GitOpsSync{}).Where("environment_id = ?", id).Pluck("id", &syncIDs).Error; err != nil {- return fmt.Errorf("failed to list environment gitops syncs: %w", err)+ return errors.WrapIf(err, "failed to list environment gitops syncs")}if len(syncIDs) > 0 {if err := tx.Model(&models.Project{}).Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {- return fmt.Errorf("failed to clear environment gitops project references: %w", err)+ return errors.WrapIf(err, "failed to clear environment gitops project references")}if err := tx.Where("environment_id = ?", id).Delete(&models.GitOpsSync{}).Error; err != nil {- return fmt.Errorf("failed to delete environment gitops syncs: %w", err)+ return errors.WrapIf(err, "failed to delete environment gitops syncs")}}if err := tx.Delete(&models.Environment{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete environment: %w", err)+ return errors.WrapIf(err, "failed to delete environment")}return nil@@ -1193,7 +1194,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))}- return "offline", fmt.Errorf("invalid environment API URL: %w", err)+ return "offline", errors.WrapIf(err, "invalid environment API URL")}reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)@@ -1203,14 +1204,14 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))}- return "offline", fmt.Errorf("failed to create request: %w", err)+ return "offline", errors.WrapIf(err, "failed to create request")}resp, err := s.httpClient.Do(req)if err != nil {if customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))}- return "offline", fmt.Errorf("connection failed: %w", err)+ return "offline", errors.WrapIf(err, "connection failed")}defer func() { _ = resp.Body.Close() }()@@ -1224,7 +1225,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))}- return "error", fmt.Errorf("unexpected status code: %d", resp.StatusCode)+ return "error", errors.Errorf("unexpected status code: %d", resp.StatusCode)}// testEdgeConnection tests connection to an edge agent via its tunnel@@ -1242,7 +1243,7 @@ func (s *EnvironmentService) testEdgeConnection(ctx context.Context, id string)statusCode, _, err := edge.DoRequest(reqCtx, id, http.MethodGet, "/api/health", nil)if err != nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))- return "offline", fmt.Errorf("health check via tunnel failed: %w", err)+ return "offline", errors.WrapIf(err, "health check via tunnel failed")}if statusCode == http.StatusOK {@@ -1251,7 +1252,7 @@ func (s *EnvironmentService) testEdgeConnection(ctx context.Context, id string)}_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))- return "error", fmt.Errorf("unexpected status code: %d", statusCode)+ return "error", errors.Errorf("unexpected status code: %d", statusCode)}func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id string) (string, error) {@@ -1262,13 +1263,13 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id sdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))- return "offline", fmt.Errorf("failed to connect to Docker: %w", err)+ return "offline", errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.Ping(reqCtx, client.PingOptions{})if err != nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))- return "offline", fmt.Errorf("docker ping failed: %w", err)+ return "offline", errors.WrapIf(err, "docker ping failed")}_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))@@ -1278,7 +1279,7 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id sfunc (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {var currentEnv models.Environmentif err := s.db.WithContext(ctx).Select("status", "is_edge").Where("id = ?", id).First(¤tEnv).Error; err != nil {- return fmt.Errorf("failed to check environment status: %w", err)+ return errors.WrapIf(err, "failed to check environment status")}if currentEnv.Status == string(models.EnvironmentStatusPending) {@@ -1301,7 +1302,7 @@ func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context"updated_at": &now,}if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update environment status: %w", err)+ return errors.WrapIf(err, "failed to update environment status")}return nil}@@ -1319,7 +1320,7 @@ func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id`, new(now), string(models.EnvironmentStatusOnline), new(now), id, now.Add(-30*time.Second))if result.Error != nil {- return fmt.Errorf("failed to update environment heartbeat: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to update environment heartbeat")}return nil@@ -1346,7 +1347,7 @@ func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Contex}if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update environment connection state: %w", err)+ return errors.WrapIf(err, "failed to update environment connection state")}return nil@@ -1365,7 +1366,7 @@ func (s *EnvironmentService) ReconcileEdgeStatusesOnStartup(ctx context.Context)"updated_at": new(time.Now()),})if result.Error != nil {- return fmt.Errorf("failed to reconcile edge environment statuses: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to reconcile edge environment statuses")}if result.RowsAffected > 0 {@@ -1409,7 +1410,7 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, en}if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update environment with new API key: %w", err)+ return errors.WrapIf(err, "failed to update environment with new API key")}s.syncEnvironmentTokenCacheInternal(envID, encryptedKey)@@ -1445,7 +1446,7 @@ func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Contextif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrInvalidEnvironmentAccessToken}- return nil, fmt.Errorf("failed to resolve environment by access token: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve environment by access token")}return &env, nil@@ -1454,7 +1455,7 @@ func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Contextfunc (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context) ([]containerregistry.Credential, error) {var registries []models.ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {- return nil, fmt.Errorf("failed to get enabled container registries: %w", err)+ return nil, errors.WrapIf(err, "failed to get enabled container registries")}var creds []containerregistry.Credential@@ -1722,7 +1723,7 @@ type remoteEnvironmentTargetInternal struct {func (s *EnvironmentService) resolveRemoteEnvironmentTargetInternal(ctx context.Context, envID string) (*remoteEnvironmentTargetInternal, error) {environment, err := s.GetEnvironmentByID(ctx, envID)if err != nil {- return nil, fmt.Errorf("failed to get environment: %w", err)+ return nil, errors.WrapIf(err, "failed to get environment")}return s.remoteEnvironmentTargetFromModelInternal(*environment)@@ -1737,7 +1738,7 @@ func (s *EnvironmentService) remoteEnvironmentTargetFromModelInternal(environmenif !environment.IsEdge {validatedTargetURL, err := normalizeEnvironmentBaseURLInternal(environment.ApiUrl)if err != nil {- return nil, fmt.Errorf("invalid environment API URL: %w", err)+ return nil, errors.WrapIf(err, "invalid environment API URL")}targetURL = validatedTargetURL}@@ -1839,7 +1840,7 @@ func (s *EnvironmentService) executeRemoteRequestForTargetInternal(resp, err := s.remoteClient.Do(ctx, request)if err != nil {- return nil, fmt.Errorf("failed to send request to environment %s: %w", target.Name, err)+ return nil, errors.WrapIff(err, "failed to send request to environment %s", target.Name)}return resp, nil@@ -1915,15 +1916,15 @@ func doRemoteEnvironmentTunnelRequestInternal() (*remenv.Response, error) {tunnel, ok := edge.GetRegistry().Get(envID).Get()if !ok {- return nil, fmt.Errorf("no active tunnel for environment %s", envID)+ return nil, errors.Errorf("no active tunnel for environment %s", envID)}if tunnel.Conn.IsClosed() {- return nil, fmt.Errorf("tunnel for environment %s is closed", envID)+ return nil, errors.Errorf("tunnel for environment %s is closed", envID)}statusCode, respHeaders, respBody, err := edge.ProxyRequest(ctx, tunnel, method, path, "", headers, body)if err != nil {- return nil, fmt.Errorf("tunnel request failed: %w", err)+ return nil, errors.WrapIf(err, "tunnel request failed")}return &remenv.Response{@@ -1945,7 +1946,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en// Get all registries from this managervar registries []models.ContainerRegistryif err := s.db.WithContext(ctx).Find(®istries).Error; err != nil {- return fmt.Errorf("failed to get registries: %w", err)+ return errors.WrapIf(err, "failed to get registries")}slog.InfoContext(ctx, "Found registries to sync", "count", len(registries))@@ -1955,7 +1956,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, enfor _, reg := range registries {registryType, typeErr := normalizeRegistryTypeInternal(reg.RegistryType)if typeErr != nil {- return fmt.Errorf("normalize registry type for sync %s: %w", reg.ID, typeErr)+ return errors.WrapIff(typeErr, "normalize registry type for sync %s", reg.ID)}syncItem := containerregistry.Sync{@@ -2001,7 +2002,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en// Marshal the requestreqBody, err := json.Marshal(syncReq)if err != nil {- return fmt.Errorf("failed to marshal sync request: %w", err)+ return errors.WrapIf(err, "failed to marshal sync request")}reqCtx, cancel := context.WithTimeout(ctx, 30*time.Second)@@ -2016,11 +2017,11 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en} `json:"data"`}if err := s.proxyJSONRequestForTargetInternal(reqCtx, target, http.MethodPost, "/api/container-registries/sync", reqBody, &result); err != nil {- return fmt.Errorf("failed to send sync request: %w", err)+ return errors.WrapIf(err, "failed to send sync request")}if !result.Success {- return fmt.Errorf("sync failed: %s", result.Data.Message)+ return errors.Errorf("sync failed: %s", result.Data.Message)}slog.InfoContext(ctx, "Successfully synced registries to environment", "environmentID", environmentID, "environmentName", target.Name)@@ -2040,7 +2041,7 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,// Get all git repositories from this managervar repositories []models.GitRepositoryif err := s.db.WithContext(ctx).Find(&repositories).Error; err != nil {- return fmt.Errorf("failed to get git repositories: %w", err)+ return errors.WrapIf(err, "failed to get git repositories")}slog.InfoContext(ctx, "Found git repositories to sync", "count", len(repositories))@@ -2093,7 +2094,7 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,// Marshal the requestreqBody, err := json.Marshal(syncReq)if err != nil {- return fmt.Errorf("failed to marshal sync request: %w", err)+ return errors.WrapIf(err, "failed to marshal sync request")}reqCtx, cancel := context.WithTimeout(ctx, 30*time.Second)@@ -2108,11 +2109,11 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,} `json:"data"`}if err := s.proxyJSONRequestForTargetInternal(reqCtx, target, http.MethodPost, "/api/git-repositories/sync", reqBody, &result); err != nil {- return fmt.Errorf("failed to send sync request: %w", err)+ return errors.WrapIf(err, "failed to send sync request")}if !result.Success {- return fmt.Errorf("sync failed: %s", result.Data.Message)+ return errors.Errorf("sync failed: %s", result.Data.Message)}slog.InfoContext(ctx, "Successfully synced git repositories to environment", "environmentID", environmentID, "environmentName", target.Name)diff --git a/backend/internal/services/event_service.go b/backend/internal/services/event_service.goindex 1ab7ecec2..4aef347dd 100644--- a/backend/internal/services/event_service.go+++ b/backend/internal/services/event_service.go@@ -4,7 +4,6 @@ import ("bytes""context"json "encoding/json/v2"- "errors""fmt""io""log/slog"@@ -13,6 +12,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -88,7 +89,7 @@ func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest)err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(event).Error; err != nil {- return fmt.Errorf("failed to create event: %w", err)+ return errors.WrapIf(err, "failed to create event")}return nil})@@ -176,7 +177,7 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelmanagerEventsURL, err := managerEventEndpointURL(s.cfg.GetManagerBaseURL())if err != nil {- return fmt.Errorf("manager API URL is invalid for manager event sync: %w", err)+ return errors.WrapIf(err, "manager API URL is invalid for manager event sync")}payload := CreateEventRequest{@@ -198,19 +199,19 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelbody, err := json.Marshal(payload)if err != nil {- return fmt.Errorf("failed to marshal event payload: %w", err)+ return errors.WrapIf(err, "failed to marshal event payload")}req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerEventsURL, bytes.NewReader(body))if err != nil {- return fmt.Errorf("failed to create manager event request: %w", err)+ return errors.WrapIf(err, "failed to create manager event request")}req.Header.Set("Content-Type", "application/json")req.Header.Set(pkgutils.HeaderAgentToken, s.cfg.AgentToken)resp, err := s.httpClient.Do(req)if err != nil {- return fmt.Errorf("failed to send event to manager: %w", err)+ return errors.WrapIf(err, "failed to send event to manager")}defer func() { _ = resp.Body.Close() }()@@ -220,9 +221,9 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelbodyBytes, readErr := io.ReadAll(io.LimitReader(resp.Body, 8192))if readErr != nil {- return fmt.Errorf("manager event sync failed with status %d", resp.StatusCode)+ return errors.Errorf("manager event sync failed with status %d", resp.StatusCode)}- return fmt.Errorf("manager event sync failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return errors.Errorf("manager event sync failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))}func managerEventEndpointURL(rawBaseURL string) (string, error) {@@ -233,10 +234,10 @@ func managerEventEndpointURL(rawBaseURL string) (string, error) {baseURL, err := url.Parse(trimmed)if err != nil {- return "", fmt.Errorf("failed to parse manager API URL: %w", err)+ return "", errors.WrapIf(err, "failed to parse manager API URL")}if baseURL.Scheme != "http" && baseURL.Scheme != "https" {- return "", fmt.Errorf("unsupported scheme %q", baseURL.Scheme)+ return "", errors.Errorf("unsupported scheme %q", baseURL.Scheme)}if baseURL.Host == "" {return "", errors.New("manager API URL host is required")@@ -304,12 +305,12 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatiopaginationResp, err := pagination.PaginateAndSortDB(params, q, &events)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}eventDtos, mapErr := mapper.MapSlice[models.Event, event.Event](events)if mapErr != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)+ return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}return eventDtos, paginationResp, nil@@ -334,12 +335,12 @@ func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, envipaginationResp, err := pagination.PaginateAndSortDB(params, q, &events)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}eventDtos, mapErr := mapper.MapSlice[models.Event, event.Event](events)if mapErr != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)+ return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}return eventDtos, paginationResp, nil@@ -398,7 +399,7 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeveritSelect("severity, COUNT(*) AS count").Group("severity").Scan(&rows).Error; err != nil {- return EventSeverityCounts{}, fmt.Errorf("failed to count events by severity: %w", err)+ return EventSeverityCounts{}, errors.WrapIf(err, "failed to count events by severity")}var counts EventSeverityCounts@@ -425,7 +426,7 @@ func (s *EventService) DeleteEvent(ctx context.Context, eventID string) error {return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Delete(&models.Event{}, "id = ?", eventID)if result.Error != nil {- return fmt.Errorf("failed to delete event: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete event")}if result.RowsAffected == 0 {return errors.New("event not found")@@ -439,7 +440,7 @@ func (s *EventService) DeleteOldEvents(ctx context.Context, olderThan time.Duratreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Where("timestamp < ?", cutoff).Delete(&models.Event{})if result.Error != nil {- return fmt.Errorf("failed to delete old events: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete old events")}return nil})diff --git a/backend/internal/services/federated_credential_service.go b/backend/internal/services/federated_credential_service.goindex 0923ee334..0378d1257 100644--- a/backend/internal/services/federated_credential_service.go+++ b/backend/internal/services/federated_credential_service.go@@ -4,8 +4,6 @@ import ("context""crypto/sha256""encoding/hex"- "errors"- "fmt""log/slog""net/http""net/url"@@ -14,6 +12,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/coreos/go-oidc/v3/oidc""github.com/google/uuid""github.com/samber/mo"@@ -93,7 +93,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fede}if issuer == "" {logReason = "missing_issuer"- return nil, &common.FederatedCredentialInvalidGrantError{}+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}credentials, err := s.listEnabledCredentialsForIssuerInternal(ctx, issuer)@@ -103,13 +103,13 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fede}if len(credentials) == 0 {logReason = "issuer_not_allowed"- return nil, &common.FederatedCredentialInvalidGrantError{}+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}verifiedToken, verifiedClaims, err := s.verifySubjectTokenInternal(ctx, issuer, req.SubjectToken)if err != nil {logReason = "token_verification_failed"- return nil, fmt.Errorf("%w: %w", &common.FederatedCredentialInvalidGrantError{}, err)+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.WrapIf(err, "invalid federated token grant"))}if subject == "" {subject = stringClaimByPathInternal(verifiedClaims, defaultFederatedSubjectClaim)@@ -121,7 +121,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedecredential := selectMatchingCredentialInternal(credentials, verifiedToken.Audience, verifiedClaims)if credential == nil {logReason = "no_matching_credential"- return nil, &common.FederatedCredentialInvalidGrantError{}+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}matchedCredential = credentialif err := s.recordTokenReplayGuardInternal(ctx, issuer, req.SubjectToken, verifiedClaims, verifiedToken.Expiry); err != nil {@@ -132,7 +132,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedeuser, err := s.userService.GetUserByID(ctx, credential.IdentityUserID)if err != nil {logReason = "identity_user_missing"- return nil, fmt.Errorf("%w: %w", &common.FederatedCredentialInvalidGrantError{}, err)+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.WrapIf(err, "invalid federated token grant"))}matchedUser = user@@ -171,7 +171,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stIsServiceAccount: true,}if err := tx.Create(&serviceUser).Error; err != nil {- return fmt.Errorf("failed to create federated service user: %w", err)+ return errors.WrapIf(err, "failed to create federated service user")}created = models.FederatedCredential{@@ -190,7 +190,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stExpiresAt: normalized.ExpiresAt,}if err := tx.Create(&created).Error; err != nil {- return fmt.Errorf("failed to create federated credential: %w", err)+ return errors.WrapIf(err, "failed to create federated credential")}assignment := models.UserRoleAssignment{@@ -200,7 +200,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stSource: models.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return fmt.Errorf("failed to create federated role assignment: %w", err)+ return errors.WrapIf(err, "failed to create federated role assignment")}return nil@@ -234,7 +234,7 @@ func (s *FederatedCredentialService) List(ctx context.Context, params paginationresp, err := pagination.PaginateAndSortDB(params, query, &credentials)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate federated credentials: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate federated credentials")}result := make([]federatedtypes.FederatedCredential, len(credentials))@@ -253,9 +253,9 @@ func (s *FederatedCredentialService) Get(ctx context.Context, id string) (*federWhere("id = ?", id).First(&credential).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, &common.FederatedCredentialNotFoundError{}+ return nil, common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return nil, fmt.Errorf("failed to get federated credential: %w", err)+ return nil, errors.WrapIf(err, "failed to get federated credential")}return new(toFederatedCredentialDTOInternal(&credential)), nil}@@ -264,9 +264,9 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID stvar credential models.FederatedCredentialif err := s.db.WithContext(ctx).Where("id = ?", id).First(&credential).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, &common.FederatedCredentialNotFoundError{}+ return nil, common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return nil, fmt.Errorf("failed to load federated credential: %w", err)+ return nil, errors.WrapIf(err, "failed to load federated credential")}updated, roleChanged, err := applyFederatedCredentialUpdateInternal(credential, req)@@ -282,7 +282,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID sterr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Save(&updated).Error; err != nil {- return fmt.Errorf("failed to update federated credential: %w", err)+ return errors.WrapIf(err, "failed to update federated credential")}if revokeActiveSessions {if err := revokeFederatedCredentialSessionsInternal(tx, updated.ID); err != nil {@@ -292,7 +292,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID stif roleChanged {if err := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, models.RoleAssignmentSourceManual).Delete(&models.UserRoleAssignment{}).Error; err != nil {- return fmt.Errorf("failed to clear federated role assignment: %w", err)+ return errors.WrapIf(err, "failed to clear federated role assignment")}assignment := models.UserRoleAssignment{UserID: updated.IdentityUserID,@@ -301,7 +301,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID stSource: models.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return fmt.Errorf("failed to update federated role assignment: %w", err)+ return errors.WrapIf(err, "failed to update federated role assignment")}}return nil@@ -320,17 +320,17 @@ func (s *FederatedCredentialService) Delete(ctx context.Context, id string) errovar credential models.FederatedCredentialif err := s.db.WithContext(ctx).Where("id = ?", id).First(&credential).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.FederatedCredentialNotFoundError{}+ return common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return fmt.Errorf("failed to load federated credential: %w", err)+ return errors.WrapIf(err, "failed to load federated credential")}err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Delete(&models.FederatedCredential{}, "id = ?", credential.ID).Error; err != nil {- return fmt.Errorf("failed to delete federated credential: %w", err)+ return errors.WrapIf(err, "failed to delete federated credential")}if err := tx.Delete(&models.User{}, "id = ?", credential.IdentityUserID).Error; err != nil {- return fmt.Errorf("failed to delete federated service user: %w", err)+ return errors.WrapIf(err, "failed to delete federated service user")}return nil})@@ -345,18 +345,18 @@ func (s *FederatedCredentialService) Delete(ctx context.Context, id string) errofunc validateTokenExchangeRequestInternal(req federatedtypes.TokenExchangeRequest) error {if req.GrantType != federatedtypes.TokenExchangeGrantType {- return &common.FederatedCredentialInvalidRequestError{}+ return common.Classify(common.ErrFederatedCredentialInvalidRequest, errors.New("invalid federated token exchange request"))}if strings.TrimSpace(req.SubjectToken) == "" {- return &common.FederatedCredentialInvalidRequestError{}+ return common.Classify(common.ErrFederatedCredentialInvalidRequest, errors.New("invalid federated token exchange request"))}switch req.SubjectTokenType {case federatedtypes.SubjectTokenTypeJWT, federatedtypes.SubjectTokenTypeIDToken:default:- return &common.FederatedCredentialInvalidRequestError{}+ return common.Classify(common.ErrFederatedCredentialInvalidRequest, errors.New("invalid federated token exchange request"))}if req.RequestedTokenType != "" && req.RequestedTokenType != federatedtypes.RequestedTokenTypeAccessJWT {- return &common.FederatedCredentialInvalidRequestError{}+ return common.Classify(common.ErrFederatedCredentialInvalidRequest, errors.New("invalid federated token exchange request"))}return nil}@@ -368,7 +368,7 @@ func (s *FederatedCredentialService) listEnabledCredentialsForIssuerInternal(ctxOrder("created_at ASC").Order("id ASC").Find(&credentials).Error; err != nil {- return nil, fmt.Errorf("failed to list federated credentials for issuer: %w", err)+ return nil, errors.WrapIf(err, "failed to list federated credentials for issuer")}now := time.Now()@@ -404,14 +404,14 @@ func (s *FederatedCredentialService) verifySubjectTokenInternal(ctx context.Contfunc (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.Context, issuer string, rawToken string, claims map[string]any, expiresAt time.Time) error {if expiresAt.IsZero() || time.Now().After(expiresAt) {- return &common.FederatedCredentialInvalidGrantError{}+ return common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}now := time.Now()if err := s.db.WithContext(ctx).Where("expires_at < ?", now).Delete(&models.FederatedTokenReplay{}).Error; err != nil {- return fmt.Errorf("failed to prune federated token replay records: %w", err)+ return errors.WrapIf(err, "failed to prune federated token replay records")}replay := models.FederatedTokenReplay{@@ -421,9 +421,9 @@ func (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.}if err := s.db.WithContext(ctx).Create(&replay).Error; err != nil {if isUniqueConstraintErrorInternal(err) {- return &common.FederatedCredentialInvalidGrantError{}+ return common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}- return fmt.Errorf("failed to record federated token replay guard: %w", err)+ return errors.WrapIf(err, "failed to record federated token replay guard")}return nil}@@ -460,7 +460,7 @@ func (s *FederatedCredentialService) providerForIssuerInternal(ctx context.ConteproviderCtx := oidc.ClientContext(context.WithoutCancel(ctx), s.httpClient)provider, err := oidc.NewProvider(providerCtx, issuer)if err != nil {- return nil, fmt.Errorf("failed to discover federated issuer: %w", err)+ return nil, errors.WrapIf(err, "failed to discover federated issuer")}s.providerMu.Lock()@@ -600,7 +600,7 @@ func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatreq.SubjectClaim = defaultFederatedSubjectClaim}if req.Name == "" || req.SubjectMatch == "" || req.RoleID == "" || len(req.Audiences) == 0 {- return req, &common.FederatedCredentialInvalidError{}+ return req, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}if err := validateIssuerURLInternal(req.IssuerURL); err != nil {return req, err@@ -615,7 +615,7 @@ func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential,if req.Name != nil {name := strings.TrimSpace(*req.Name)if name == "" {- return existing, false, &common.FederatedCredentialInvalidError{}+ return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}existing.Name = name}@@ -635,7 +635,7 @@ func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential,if req.Audiences != nil {audiences := pkgutils.UniqueNonEmptyStrings(req.Audiences)if len(audiences) == 0 {- return existing, false, &common.FederatedCredentialInvalidError{}+ return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}existing.Audiences = models.StringSlice(audiences)}@@ -649,7 +649,7 @@ func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential,if req.SubjectMatch != nil {subjectMatch := strings.TrimSpace(*req.SubjectMatch)if subjectMatch == "" {- return existing, false, &common.FederatedCredentialInvalidError{}+ return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}existing.SubjectMatch = subjectMatch}@@ -674,14 +674,14 @@ func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential,func applyFederatedRoleScopeUpdateInternal(existing *models.FederatedCredential, roleID *string, environmentID *string) (bool, error) {if existing == nil {- return false, &common.FederatedCredentialInvalidError{}+ return false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}roleChanged := falseif roleID != nil {normalizedRoleID := strings.TrimSpace(*roleID)if normalizedRoleID == "" {- return false, &common.FederatedCredentialInvalidError{}+ return false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}roleChanged = roleChanged || normalizedRoleID != existing.RoleIDexisting.RoleID = normalizedRoleID@@ -706,17 +706,17 @@ func normalizeMatchTypeInternal(matchType string) string {func validateIssuerURLInternal(rawURL string) error {parsed, err := url.Parse(rawURL)if err != nil || parsed == nil || parsed.Host == "" || parsed.Scheme != "https" {- return fmt.Errorf("%w: issuerUrl must be an HTTPS URL", &common.FederatedCredentialInvalidError{})+ return common.Classify(common.ErrFederatedCredentialInvalid, errors.WithStackIf(errors.New("invalid federated credential: issuerUrl must be an HTTPS URL")))}return nil}func validateSubjectMatchInternal(matchType, subjectMatch string) error {if strings.TrimSpace(subjectMatch) == "" {- return &common.FederatedCredentialInvalidError{}+ return common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}if normalizeMatchTypeInternal(matchType) == federatedtypes.MatchTypeGlob && strings.TrimSpace(subjectMatch) == "*" {- return &common.FederatedCredentialInvalidError{}+ return common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}return nil}@@ -728,19 +728,19 @@ func (s *FederatedCredentialService) validateRoleGrantAgainstUserInternal(ctx couser, err := s.userService.GetUserByID(ctx, userID)if err != nil {- return fmt.Errorf("load user for federated role validation: %w", err)+ return errors.WrapIf(err, "load user for federated role validation")}ps, err := s.roleService.ResolvePermissions(ctx, user)if err != nil {- return fmt.Errorf("resolve user permissions: %w", err)+ return errors.WrapIf(err, "resolve user permissions")}if err := s.roleService.ValidateRoleAssignmentAgainstCaller(ctx, ps, roleID, environmentID); err != nil {- if common.IsRolePermissionEscalationError(err) {- return fmt.Errorf("%w: %w", &common.FederatedCredentialPermissionEscalationError{}, err)+ if errors.Is(err, common.ErrRolePermissionEscalation) {+ return common.Classify(common.ErrFederatedCredentialPermissionEscalation, errors.WrapIf(err, "cannot map a federated credential to a role you do not hold"))}- return fmt.Errorf("%w: %w", &common.FederatedCredentialInvalidError{}, err)+ return common.Classify(common.ErrFederatedCredentialInvalid, errors.WrapIf(err, "invalid federated credential"))}return nil}@@ -754,7 +754,7 @@ func revokeFederatedCredentialSessionsInternal(tx *gorm.DB, credentialID string)if err := tx.Model(&models.UserSession{}).Where("federated_credential_id = ? AND revoked_at IS NULL", credentialID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return fmt.Errorf("failed to revoke federated credential sessions: %w", err)+ return errors.WrapIf(err, "failed to revoke federated credential sessions")}return nil}diff --git a/backend/internal/services/federated_credential_service_test.go b/backend/internal/services/federated_credential_service_test.goindex 84c6a7c32..a6a388aa1 100644--- a/backend/internal/services/federated_credential_service_test.go+++ b/backend/internal/services/federated_credential_service_test.go@@ -14,6 +14,7 @@ import ("testing""time"+ "emperror.dev/errors""github.com/golang-jwt/jwt/v5"sqlite "github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -137,7 +138,7 @@ func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTesteventSvc := NewEventService(db, &config.Config{}, nil)authSvc := NewAuthService(userSvc, settingsSvc, eventSvc, sessionSvc, roleSvc, "test-federated-secret", &config.Config{JWTRefreshExpiry: 24 * time.Hour,- })+ }, nil)service := NewFederatedCredentialService(db, authSvc, userSvc, settingsSvc, eventSvc, issuer.server.Client()).WithRoleService(roleSvc)@@ -195,14 +196,14 @@ func TestFederatedCredentialServiceExchangeToken(t *testing.T) {name: "rejects audience mismatch",token: issuer.tokenInternal(t, "repo:getarcaneapp/arcane:ref:refs/heads/main", []string{"other-audience"}),wantError: func(err error) bool {- return common.IsErrorFederatedCredentialInvalidGrant(err)+ return errors.Is(err, common.ErrFederatedCredentialInvalidGrant)},},{name: "rejects subject mismatch",token: issuer.tokenInternal(t, "repo:other/repo:ref:refs/heads/main", []string{"arcane-ci"}),wantError: func(err error) bool {- return common.IsErrorFederatedCredentialInvalidGrant(err)+ return errors.Is(err, common.ErrFederatedCredentialInvalidGrant)},},}@@ -255,7 +256,7 @@ func TestFederatedCredentialServiceExchangeTokenRejectsIssuerWithoutCredentialIn})require.Error(t, err)- require.True(t, common.IsErrorFederatedCredentialInvalidGrant(err), "unexpected error: %v", err)+ require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)require.Nil(t, resp)}@@ -293,7 +294,7 @@ func TestFederatedCredentialServiceExchangeTokenRejectsExpiredCredentialInternal})require.Error(t, err)- require.True(t, common.IsErrorFederatedCredentialInvalidGrant(err), "unexpected error: %v", err)+ require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)require.Nil(t, resp)}@@ -318,7 +319,7 @@ func TestFederatedCredentialServiceUpdateDisableRevokesIssuedSessionsInternal(t_, _, err = authSvc.VerifyToken(ctx, resp.AccessToken)require.Error(t, err)- require.True(t, common.IsSessionRevokedError(err), "unexpected error: %v", err)+ require.True(t, errors.Is(err, common.ErrSessionRevoked), "unexpected error: %v", err)}func TestFederatedCredentialServiceRejectsReplayedSubjectTokenInternal(t *testing.T) {@@ -339,7 +340,7 @@ func TestFederatedCredentialServiceRejectsReplayedSubjectTokenInternal(t *testinsecond, err := service.ExchangeToken(ctx, req)require.Error(t, err)- require.True(t, common.IsErrorFederatedCredentialInvalidGrant(err), "unexpected error: %v", err)+ require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)require.Nil(t, second)}@@ -358,5 +359,5 @@ func TestFederatedCredentialServiceCreateRejectsBareWildcardGlob(t *testing.T) {})require.Error(t, err)- require.True(t, common.IsErrorFederatedCredentialInvalid(err), "unexpected error: %v", err)+ require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalid), "unexpected error: %v", err)}diff --git a/backend/internal/services/git_repository_service.go b/backend/internal/services/git_repository_service.goindex ee61f62d0..ab3224c73 100644--- a/backend/internal/services/git_repository_service.go+++ b/backend/internal/services/git_repository_service.go@@ -2,10 +2,11 @@ package servicesimport ("context"- "errors""fmt""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil"@@ -47,7 +48,7 @@ func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, parout, paginationResp, err := pagination.PaginateSortAndMapDB[models.GitRepository, gitops.GitRepository](params, q, &repositories)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list git repositories: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list git repositories")}return out, paginationResp, nil@@ -59,7 +60,7 @@ func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string)if errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("repository not found")}- return nil, fmt.Errorf("failed to get repository: %w", err)+ return nil, errors.WrapIf(err, "failed to get repository")}return &repository, nil}@@ -70,7 +71,7 @@ func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name strif errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("repository not found")}- return nil, fmt.Errorf("failed to get repository: %w", err)+ return nil, errors.WrapIf(err, "failed to get repository")}return &repository, nil}@@ -97,7 +98,7 @@ func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, rquery = query.Where("url = ? OR url = ? OR url LIKE ? OR url LIKE ?", rawURL, normalizedURL, likePrefix+"%", likePrefix+"/%")}if err := query.Find(&repositories).Error; err != nil {- return nil, fmt.Errorf("failed to list repositories: %w", err)+ return nil, errors.WrapIf(err, "failed to list repositories")}for i := range repositories {@@ -133,7 +134,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.if req.Token != "" {encrypted, err := crypto.Encrypt(req.Token)if err != nil {- return nil, fmt.Errorf("failed to encrypt token: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt token")}repository.Token = encrypted}@@ -141,13 +142,13 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.if req.SSHKey != "" {encrypted, err := crypto.Encrypt(req.SSHKey)if err != nil {- return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt SSH key")}repository.SSHKey = encrypted}if err := s.db.WithContext(ctx).Create(&repository).Error; err != nil {- return nil, fmt.Errorf("failed to create repository: %w", err)+ return nil, errors.WrapIf(err, "failed to create repository")}// Log event@@ -219,7 +220,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,} else {encrypted, err := crypto.Encrypt(*req.Token)if err != nil {- return nil, fmt.Errorf("failed to encrypt token: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt token")}updates["token"] = encrypted}@@ -231,7 +232,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,} else {encrypted, err := crypto.Encrypt(*req.SSHKey)if err != nil {- return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)+ return nil, errors.WrapIf(err, "failed to encrypt SSH key")}updates["ssh_key"] = encrypted}@@ -239,7 +240,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,if len(updates) > 0 {if err := s.db.WithContext(ctx).Model(repository).Updates(updates).Error; err != nil {- return nil, fmt.Errorf("failed to update repository: %w", err)+ return nil, errors.WrapIf(err, "failed to update repository")}// Log event@@ -263,11 +264,11 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,// Check if repository is used by any syncsvar count int64if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("repository_id = ?", id).Count(&count).Error; err != nil {- return fmt.Errorf("failed to check repository usage: %w", err)+ return errors.WrapIf(err, "failed to check repository usage")}if count > 0 {- return fmt.Errorf("repository is used by %d sync configuration(s)", count)+ return errors.Errorf("repository is used by %d sync configuration(s)", count)}// Get repository info before deleting@@ -277,7 +278,7 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,}if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.GitRepository{}).Error; err != nil {- return fmt.Errorf("failed to delete repository: %w", err)+ return errors.WrapIf(err, "failed to delete repository")}// Log event@@ -354,7 +355,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *moif repository.Token != "" {token, err := crypto.Decrypt(repository.Token)if err != nil {- return authConfig, fmt.Errorf("failed to decrypt token: %w", err)+ return authConfig, errors.WrapIf(err, "failed to decrypt token")}authConfig.Token = token}@@ -362,7 +363,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *moif repository.SSHKey != "" {sshKey, err := crypto.Decrypt(repository.SSHKey)if err != nil {- return authConfig, fmt.Errorf("failed to decrypt SSH key: %w", err)+ return authConfig, errors.WrapIf(err, "failed to decrypt SSH key")}authConfig.SSHKey = sshKey}@@ -387,7 +388,7 @@ func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]gbranches, err := s.gitClient.ListBranches(listCtx, repository.URL, authConfig)if err != nil {- return nil, fmt.Errorf("failed to list branches: %w", err)+ return nil, errors.WrapIf(err, "failed to list branches")}var result []gitops.BranchInfo@@ -419,7 +420,7 @@ func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path// Clone the repositoryrepoPath, err := s.gitClient.Clone(ctx, repository.URL, branch, authConfig)if err != nil {- return nil, fmt.Errorf("failed to clone repository: %w", err)+ return nil, errors.WrapIf(err, "failed to clone repository")}defer func() {if cleanupErr := s.gitClient.Cleanup(repoPath); cleanupErr != nil {@@ -466,7 +467,7 @@ func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems [func (s *GitRepositoryService) getExistingRepositoriesMap(ctx context.Context) (map[string]*models.GitRepository, error) {var existing []models.GitRepositoryif err := s.db.WithContext(ctx).Find(&existing).Error; err != nil {- return nil, fmt.Errorf("failed to get existing repositories: %w", err)+ return nil, errors.WrapIf(err, "failed to get existing repositories")}existingMap := make(map[string]*models.GitRepository)@@ -490,7 +491,7 @@ func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, iteif needsUpdate {// Use Save to trigger GORM callbacks including UpdatedAtif err := s.db.WithContext(ctx).Save(existing).Error; err != nil {- return fmt.Errorf("failed to update repository %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to update repository %s", item.ID)}}@@ -538,14 +539,14 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitif item.Token != "" {encryptedToken, err = crypto.Encrypt(item.Token)if err != nil {- return fmt.Errorf("failed to encrypt token for repository %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to encrypt token for repository %s", item.ID)}}if item.SSHKey != "" {encryptedSSHKey, err = crypto.Encrypt(item.SSHKey)if err != nil {- return fmt.Errorf("failed to encrypt SSH key for repository %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to encrypt SSH key for repository %s", item.ID)}}@@ -568,7 +569,7 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitrepo.ID = item.IDif err := s.db.WithContext(ctx).Create(&repo).Error; err != nil {- return fmt.Errorf("failed to create repository %s: %w", item.ID, err)+ return errors.WrapIff(err, "failed to create repository %s", item.ID)}return nil@@ -578,7 +579,7 @@ func (s *GitRepositoryService) deleteUnsynced(ctx context.Context, existingMap mfor id := range existingMap {if !syncedIDs[id] {if err := s.db.WithContext(ctx).Delete(&models.GitRepository{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete repository %s: %w", id, err)+ return errors.WrapIff(err, "failed to delete repository %s", id)}}}diff --git a/backend/internal/services/git_repository_service_test.go b/backend/internal/services/git_repository_service_test.goindex 872196dc8..8fc3b79a7 100644--- a/backend/internal/services/git_repository_service_test.go+++ b/backend/internal/services/git_repository_service_test.go@@ -6,11 +6,13 @@ import ("strings""testing"+ "emperror.dev/errors"sqlite "github.com/libtnb/sqlite""github.com/stretchr/testify/assert""github.com/stretchr/testify/require""gorm.io/gorm"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -75,10 +77,9 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWo}, models.User{})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "token", validationErr.Field)- assert.Contains(t, validationErr.Message, "repository URL")+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "token")+ assert.Contains(t, err.Error(), "repository URL")stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)require.NoError(t, loadErr)@@ -100,10 +101,9 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyW}, models.User{})require.Error(t, err)- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, "sshKey", validationErr.Field)- assert.Contains(t, validationErr.Message, "repository URL")+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), "sshKey")+ assert.Contains(t, err.Error(), "repository URL")stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)require.NoError(t, loadErr)diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.goindex 2893d353b..5aef45f0b 100644--- a/backend/internal/services/gitops_sync_service.go+++ b/backend/internal/services/gitops_sync_service.go@@ -3,7 +3,6 @@ package servicesimport ("context"json "encoding/json/v2"- "errors""fmt""log/slog""maps"@@ -15,6 +14,7 @@ import ("sync""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -144,7 +144,8 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,// toggling unrelated fields on an existing config shouldn't be rejected// just because the global setting was turned off afterwards.if lifecycleFieldSet && !s.settingsService.GetBoolSetting(ctx, "lifecycleEnabled", false) {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Pre-deploy lifecycle hooks are disabled. An admin must enable lifecycleEnabled in settings before they can be configured."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Pre-deploy lifecycle hooks are disabled. An admin must enable lifecycleEnabled in settings before they can be configured."), "field", "preDeployScriptPath"))}if effectiveScriptPath != "" {@@ -155,19 +156,21 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,if in.timeoutSec != nil {if *in.timeoutSec < 1 {- return &models.ValidationError{Field: "preDeployTimeoutSec", Message: "Timeout must be at least 1 second."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Timeout must be at least 1 second."), "field", "preDeployTimeoutSec"))}maxTimeoutSec := s.settingsService.GetIntSetting(ctx, "lifecycleMaxTimeoutSec", lifecycleDefaultMaxTimeoutSec)if maxTimeoutSec > 0 && *in.timeoutSec > maxTimeoutSec {- return &models.ValidationError{Field: "preDeployTimeoutSec", Message: fmt.Sprintf("Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).", *in.timeoutSec, maxTimeoutSec)}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).", *in.timeoutSec, maxTimeoutSec), "field", "preDeployTimeoutSec"))}}if _, err := parseLifecycleEnvTextInternal(in.env); err != nil {- return &models.ValidationError{Field: "preDeployEnv", Message: err.Error()}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployEnv"))}if _, err := parseLifecycleExtraMountsTextInternal(in.extraMounts); err != nil {- return &models.ValidationError{Field: "preDeployExtraMounts", Message: err.Error()}+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployExtraMounts"))}return nil@@ -175,30 +178,36 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Context, current *models.GitOpsSync, in lifecycleConfigInputInternal, scriptPath string) error {if resolveLifecycleEffectiveTargetTypeInternal(current, in.targetType) == "swarm_stack" {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Pre-deploy lifecycle hooks are only supported for project syncs."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Pre-deploy lifecycle hooks are only supported for project syncs."), "field", "preDeployScriptPath"))}if len(scriptPath) > 256 {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Script path must be 256 characters or fewer."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Script path must be 256 characters or fewer."), "field", "preDeployScriptPath"))}// scriptPath is a POSIX repo path, not a host path; use path.IsAbs so the// check behaves the same on Windows-based contributor machines.if path.IsAbs(filepath.ToSlash(scriptPath)) {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Script path must be relative to the project directory."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Script path must be relative to the project directory."), "field", "preDeployScriptPath"))}cleaned := filepath.ToSlash(filepath.Clean(scriptPath))if cleaned == ".." || strings.HasPrefix(cleaned, "../") {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Script path must not escape the project directory."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Script path must not escape the project directory."), "field", "preDeployScriptPath"))}effectiveRunnerImage := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *models.GitOpsSync) *string { return c.PreDeployRunnerImage }), in.runnerImage)defaultRunnerImage := strings.TrimSpace(s.settingsService.GetStringSetting(ctx, "lifecycleDefaultRunnerImage", ""))if effectiveRunnerImage == "" && defaultRunnerImage == "" {- return &models.ValidationError{Field: "preDeployRunnerImage", Message: "Runner image is required when a script path is set."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Runner image is required when a script path is set."), "field", "preDeployRunnerImage"))}if !resolveEffectiveSyncDirectoryInternal(current, in.syncDirectory) {- return &models.ValidationError{Field: "preDeployScriptPath", Message: "Pre-deploy script requires \"Sync entire directory\" so the script is included in the synced files."}+ //nolint:revive // Preserve the existing API validation message.+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Pre-deploy script requires \"Sync entire directory\" so the script is included in the synced files."), "field", "preDeployScriptPath"))}return nil@@ -407,7 +416,7 @@ func (s *GitOpsSyncService) buildSyncJobInternal(syncID, environmentID string, ifunc (s *GitOpsSyncService) runScheduledSyncInternal(ctx context.Context, environmentID, syncID string) {sync, err := s.getSyncRecordByIDInternal(ctx, environmentID, syncID)if err != nil {- if _, ok := errors.AsType[*models.NotFoundError](err); ok {+ if errors.Is(err, common.ErrNotFound) {slog.InfoContext(ctx, "gitops auto-sync job unregistering; sync no longer exists", "syncId", syncID)s.unregisterSyncJobInternal(ctx, syncID)return@@ -554,17 +563,17 @@ func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentIDcounts, err := s.getFilteredSyncCounts(q)if err != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to get sync counts: %w", err)+ return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to get sync counts")}paginationResp, err := pagination.PaginateAndSortDB(params, q.Preload("Repository").Preload("Project"), &syncs)if err != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to paginate gitops syncs: %w", err)+ return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to paginate gitops syncs")}out, mapErr := mapper.MapSlice[models.GitOpsSync, gitops.GitOpsSync](syncs)if mapErr != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to map syncs: %w", mapErr)+ return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(mapErr, "failed to map syncs")}return out, paginationResp, counts, nil@@ -596,8 +605,7 @@ func (s *GitOpsSyncService) getFilteredSyncCounts(query *gorm.DB) (gitops.SyncCofunc (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id string) (*models.GitOpsSync, error) {sync, err := s.getSyncByIDInternal(ctx, environmentID, id, true)if err != nil {- var notFound *models.NotFoundError- if errors.As(err, ¬Found) {+ if errors.Is(err, common.ErrNotFound) {slog.WarnContext(ctx, "GitOps sync not found", "syncID", id, "environmentID", environmentID)return nil, err}@@ -618,9 +626,9 @@ func (s *GitOpsSyncService) getSyncByIDInternal(ctx context.Context, environment}if err := q.First(&sync).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, &models.NotFoundError{Message: "GitOps sync not found"}+ return nil, common.Classify(common.ErrNotFound, errors.New("GitOps sync not found"))}- return nil, fmt.Errorf("failed to get sync: %w", err)+ return nil, errors.WrapIf(err, "failed to get sync")}return &sync, nil}@@ -636,7 +644,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringrepo, err := s.repoService.GetRepositoryByID(ctx, req.RepositoryID)if err != nil {slog.ErrorContext(ctx, "Repository not found for GitOps sync", "repositoryID", req.RepositoryID, "error", err)- return nil, fmt.Errorf("repository not found: %w", err)+ return nil, errors.WrapIf(err, "repository not found")}slog.InfoContext(ctx, "Found repository for GitOps sync", "repositoryID", req.RepositoryID, "repositoryName", repo.Name)@@ -706,7 +714,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string// unset pre-deploy fields) to persist instead of GORM substituting column defaults.if err := s.db.WithContext(ctx).Select("*").Omit("Environment", "Repository", "Project").Create(&sync).Error; err != nil { //nolint:unqueryvet // intentional Select("*"); see comment aboveslog.ErrorContext(ctx, "Failed to create GitOps sync in database", "name", req.Name, "repositoryID", req.RepositoryID, "environmentID", environmentID, "error", err)- return nil, fmt.Errorf("failed to create sync: %w", err)+ return nil, errors.WrapIf(err, "failed to create sync")}slog.InfoContext(ctx, "GitOps sync created successfully", "syncID", sync.ID, "name", sync.Name)@@ -764,7 +772,7 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st// Validate repository exists_, err := s.repoService.GetRepositoryByID(ctx, *req.RepositoryID)if err != nil {- return nil, fmt.Errorf("repository not found: %w", err)+ return nil, errors.WrapIf(err, "repository not found")}updates["repository_id"] = *req.RepositoryID}@@ -819,7 +827,7 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id stif len(updates) > 0 {if err := s.db.WithContext(ctx).Model(sync).Updates(updates).Error; err != nil {- return nil, fmt.Errorf("failed to update sync: %w", err)+ return nil, errors.WrapIf(err, "failed to update sync")}// Log event@@ -870,14 +878,14 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id stif err := tx.Model(&models.Project{}).Where("gitops_managed_by = ?", id).Update("gitops_managed_by", nil).Error; err != nil {- return fmt.Errorf("failed to clear gitops_managed_by: %w", err)+ return errors.WrapIf(err, "failed to clear gitops_managed_by")}// Delete by id only (no environment scoping). The handler already enforced the// delete permission; env scoping is precisely what made env-mismatched corrupt// rows undeletable. A zero-row delete is treated as success (idempotent).if err := tx.Where("id = ?", id).Delete(&models.GitOpsSync{}).Error; err != nil {- return fmt.Errorf("failed to delete sync: %w", err)+ return errors.WrapIf(err, "failed to delete sync")}return nil}); err != nil {@@ -1048,22 +1056,19 @@ func (s *GitOpsSyncService) performDirectorySync(ctx context.Context, sync *modeproject, syncedFiles, _, contentsChanged, err := s.syncProjectDirectoryInternal(ctx, sync, syncFiles, actor)if err != nil {- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- if errors.As(err, &bindingErr) {- errMsg := bindingErr.Error()+ if errors.Is(err, common.ErrGitOpsSyncProjectBindingBroken) {+ errMsg := err.Error()result.Message = "GitOps project binding broken"result.Error = new(errMsg)- return result, bindingErr+ return result, err}return result, s.failSync(ctx, id, result, sync, actor, "Failed to sync project directory", err.Error())}if contentsChanged {if redeployErr := s.redeployIfRunningAfterSync(ctx, project, actor, "directory"); redeployErr != nil {- // redeployIfRunningAfterSync only ever returns *common.RedeployAfterSyncFailedError;- // AsType remains as a defensive guard against future contract drift.- if typed, ok := errors.AsType[*common.RedeployAfterSyncFailedError](redeployErr); ok {- s.markSyncRedeployFailedInternal(ctx, sync, id, source.commitHash, syncedFiles, typed, actor, result)+ if errors.Is(redeployErr, common.ErrRedeployAfterSyncFailed) {+ s.markSyncRedeployFailedInternal(ctx, sync, id, source.commitHash, syncedFiles, redeployErr, actor, result)}return result, redeployErr}@@ -1098,12 +1103,8 @@ func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, sproject, err := s.getOrCreateProjectInternal(ctx, sync, id, source.composeContent, source.envContent, source.overrideContent, source.overrideFileName, result, actor)if err != nil {- // err may be a *common.RedeployAfterSyncFailedError (from updateProjectForSyncInternal)- // or a plain failSync error (from CreateProject / ApplyGitSyncProjectFiles).- // Only the typed case warrants the redeploy-failure marker; the rest just- // surface through the caller.- if redeployErr, ok := errors.AsType[*common.RedeployAfterSyncFailedError](err); ok {- s.markSyncRedeployFailedInternal(ctx, sync, id, source.commitHash, syncedFiles, redeployErr, actor, result)+ if errors.Is(err, common.ErrRedeployAfterSyncFailed) {+ s.markSyncRedeployFailedInternal(ctx, sync, id, source.commitHash, syncedFiles, err, actor, result)}return result, err}@@ -1195,7 +1196,7 @@ func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, s// redeployIfRunningAfterSync redeploys a project only when it is already// running and the latest sync actually changed managed content. Returns a-// *common.RedeployAfterSyncFailedError when the redeploy itself fails; callers+// common.ErrRedeployAfterSyncFailed when the redeploy itself fails; callers// surface that on the sync row's LastSyncError.func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, project *models.Project, actor models.User, syncMode string) error {details, err := s.projectService.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{})@@ -1209,7 +1210,7 @@ func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, projslog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "syncMode", syncMode, "projectName", project.Name, "projectId", project.ID)if err := s.projectService.RedeployProject(ctx, project.ID, actor, nil); err != nil {slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "syncMode", syncMode, "error", err, "projectId", project.ID)- return &common.RedeployAfterSyncFailedError{Err: err}+ return common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(err, "redeploy failed"))}return nil}@@ -1285,7 +1286,7 @@ func (s *GitOpsSyncService) GetSyncStatus(ctx context.Context, environmentID, idfunc (s *GitOpsSyncService) CleanupLeakedScratchDirsOnStartup(ctx context.Context) error {projectsDir, err := s.projectService.getProjectsDirectoryInternal(ctx)if err != nil {- return fmt.Errorf("failed to resolve projects directory for gitops scratch cleanup: %w", err)+ return errors.WrapIf(err, "failed to resolve projects directory for gitops scratch cleanup")}entries, err := os.ReadDir(projectsDir)@@ -1293,7 +1294,7 @@ func (s *GitOpsSyncService) CleanupLeakedScratchDirsOnStartup(ctx context.Contexif errors.Is(err, os.ErrNotExist) {return nil}- return fmt.Errorf("failed to list projects directory %s for gitops scratch cleanup: %w", projectsDir, err)+ return errors.WrapIff(err, "failed to list projects directory %s for gitops scratch cleanup", projectsDir)}removed := 0@@ -1320,7 +1321,7 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) eif err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("environment_id NOT IN (SELECT id FROM environments)").Pluck("id", &syncIDs).Error; err != nil {- return fmt.Errorf("failed to list orphaned gitops syncs: %w", err)+ return errors.WrapIf(err, "failed to list orphaned gitops syncs")}if len(syncIDs) == 0 {return nil@@ -1330,10 +1331,10 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) eif err := tx.Model(&models.Project{}).Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {- return fmt.Errorf("failed to clear orphaned gitops project references: %w", err)+ return errors.WrapIf(err, "failed to clear orphaned gitops project references")}if err := tx.Where("id IN ?", syncIDs).Delete(&models.GitOpsSync{}).Error; err != nil {- return fmt.Errorf("failed to delete orphaned gitops syncs: %w", err)+ return errors.WrapIf(err, "failed to delete orphaned gitops syncs")}return nil}); err != nil {@@ -1349,7 +1350,7 @@ func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.if err := s.db.WithContext(ctx).Where("sync_directory = ?", true).Find(&syncs).Error; err != nil {- return fmt.Errorf("failed to list directory syncs for startup reconciliation: %w", err)+ return errors.WrapIf(err, "failed to list directory syncs for startup reconciliation")}for i := range syncs {@@ -1397,7 +1398,7 @@ func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id s// Clone the repositoryrepoPath, err := s.repoService.gitClient.Clone(browseCtx, repository.URL, sync.Branch, authConfig)if err != nil {- return nil, fmt.Errorf("failed to clone repository: %w", err)+ return nil, errors.WrapIf(err, "failed to clone repository")}defer func() {if cleanupErr := s.repoService.gitClient.Cleanup(repoPath); cleanupErr != nil {@@ -1479,7 +1480,7 @@ func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *gitresult.Error = new(errMsg)s.updateSyncStatus(ctx, id, "failed", errMsg, "")s.logSyncError(ctx, sync, actor, errMsg)- return fmt.Errorf("%s", errMsg)+ return errors.Errorf("%s", errMsg)}// markSyncRedeployFailedInternal records a sync where the file sync wrote@@ -1487,7 +1488,7 @@ func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *git// lifecycle hook returning non-zero). The synced-files list and commit hash// are preserved on the row so operators can see what reached disk; the// error message surfaces the redeploy failure on LastSyncError.-func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context, sync *models.GitOpsSync, id, commitHash string, syncedFiles []string, redeployErr *common.RedeployAfterSyncFailedError, actor models.User, result *gitops.SyncResult) {+func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context, sync *models.GitOpsSync, id, commitHash string, syncedFiles []string, redeployErr error, actor models.User, result *gitops.SyncResult) {errMsg := redeployErr.Error()result.Success = falseresult.Message = "Sync wrote files but redeploy failed"@@ -1518,11 +1519,10 @@ func (s *GitOpsSyncService) failSyncAndDisableAutoSyncInternal(ctx context.Conte}func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Context, sync *models.GitOpsSync, actor models.User, err error) {- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- if !errors.As(err, &bindingErr) || sync == nil {+ if !errors.Is(err, common.ErrGitOpsSyncProjectBindingBroken) || sync == nil {return}- errMsg := bindingErr.Error()+ errMsg := err.Error()s.updateSyncStatus(ctx, sync.ID, "failed", errMsg, "")s.logSyncError(ctx, sync, actor, errMsg)s.disableAutoSyncForBrokenBindingInternal(ctx, sync)@@ -1535,9 +1535,8 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, syproject, err := s.projectService.createProjectInternal(ctx, sync.ProjectName, composeContent, envContent, nil, actor, false)if err != nil {if errors.Is(err, projects.ErrProjectDirExists) {- bindingErr := &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)),- }+ bindingErr := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)), "GitOps sync project binding broken"))+return nil, s.failSyncAndDisableAutoSyncInternal(ctx, id, result, sync, actor, "GitOps project binding broken", bindingErr)}return nil, s.failSync(ctx, id, result, sync, actor, "Failed to create project", err.Error())@@ -1575,9 +1574,8 @@ func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, syncreturn nil, s.failSync(ctx, id, result, sync, actor, "Failed to load existing project", lookupErr.Error())}if !found {- err := &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s references missing project %s", sync.ID, *sync.ProjectID),- }+ err := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s references missing project %s", sync.ID, *sync.ProjectID), "GitOps sync project binding broken"))+slog.WarnContext(ctx, "Existing project not found; GitOps project binding is broken", "projectId", *sync.ProjectID, "syncId", sync.ID)return nil, s.failSyncAndDisableAutoSyncInternal(ctx, id, result, sync, actor, "GitOps project binding broken", err)}@@ -1608,7 +1606,7 @@ func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sycontentChanged := oldCompose != newCompose || envContentChangedInternal(oldEnv, newEnv) || oldOverride != newOverride// If content changed and project is running, redeploy. A redeploy failure- // is bubbled up as a *common.RedeployAfterSyncFailedError so the parent flow+ // is classified as common.ErrRedeployAfterSyncFailed so the parent flow// can reflect it on the sync row's LastSyncError.if contentChanged {details, err := s.projectService.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{})@@ -1616,7 +1614,7 @@ func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, syslog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "projectName", project.Name, "projectId", project.ID)if err := s.projectService.RedeployProject(ctx, project.ID, actor, nil); err != nil {slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "error", err, "projectId", project.ID)- return &common.RedeployAfterSyncFailedError{Err: err}+ return common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(err, "redeploy failed"))}}}@@ -1668,7 +1666,7 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, syncwalkResult, err := s.repoService.gitClient.WalkDirectory(ctx, repoPath, sync.ComposePath, maxFiles, maxTotalSize, maxBinarySize)if err != nil {- return nil, fmt.Errorf("failed to walk directory: %w", err)+ return nil, errors.WrapIf(err, "failed to walk directory")}slog.InfoContext(ctx, "Directory walk complete",@@ -1696,7 +1694,7 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync}if !composeFound {- return nil, fmt.Errorf("compose file %s not found in walked directory", composeFileName)+ return nil, errors.Errorf("compose file %s not found in walked directory", composeFileName)}return syncFiles, nil@@ -1739,7 +1737,7 @@ func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, syfunc (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync *models.GitOpsSync, syncFiles []projects.SyncFile) (*stagedDirectorySync, error) {projectsDir, err := s.projectService.getProjectsDirectoryInternal(ctx)if err != nil {- return nil, fmt.Errorf("failed to get projects directory: %w", err)+ return nil, errors.WrapIf(err, "failed to get projects directory")}// The project-root env files are reserved for the three-file override@@ -1750,7 +1748,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncstagePath, err := os.MkdirTemp(projectsDir, ".gitops-sync-stage-*")if err != nil {- return nil, fmt.Errorf("failed to create staging directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create staging directory")}project, err := s.getDirectorySyncProjectInternal(ctx, sync)@@ -1769,7 +1767,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, synccopySkipped, err = projects.CopyDirectoryContentsTolerant(project.Path, stagePath)if err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("failed to stage current project files: %w", err)+ return nil, errors.WrapIf(err, "failed to stage current project files")}if len(copySkipped) > 0 {slog.WarnContext(ctx, "skipped unreadable files while staging project sync; they will be left untouched on promotion", "projectPath", project.Path, "skipped", copySkipped)@@ -1792,14 +1790,14 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncif len(oldSyncedFiles) > 0 {if err := projects.CleanupRemovedFiles(projectsDir, stagePath, oldSyncedFiles, syncedFiles); err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("failed to clean removed synced files: %w", err)+ return nil, errors.WrapIf(err, "failed to clean removed synced files")}}composeFileName := filepath.Base(sync.ComposePath)if err := projects.RemoveStaleComposeFiles(stagePath, composeFileName, syncedFiles); err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("failed to remove stale compose files: %w", err)+ return nil, errors.WrapIf(err, "failed to remove stale compose files")}contentsChanged := true@@ -1807,7 +1805,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, synccontentsChanged, err = projects.DirectorySyncContentsChanged(project.Path, filteredSyncFiles, oldSyncedFiles, composeFileName)if err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("failed to compare staged directory changes: %w", err)+ return nil, errors.WrapIf(err, "failed to compare staged directory changes")}}@@ -1816,7 +1814,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync// will exist in the managed project.if _, err := projects.WriteSyncedDirectory(projectsDir, stagePath, filteredSyncFiles); err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("failed to write staged sync files: %w", err)+ return nil, errors.WrapIf(err, "failed to write staged sync files")}// Route the project-root .env through the same three-file override merge@@ -1834,7 +1832,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncserviceCount, err := s.validateDirectorySyncStageInternal(ctx, sync.ProjectName, stagePath, composeFileName)if err != nil {_ = os.RemoveAll(stagePath)- return nil, fmt.Errorf("invalid compose file: %w", err)+ return nil, errors.WrapIf(err, "invalid compose file")}return &stagedDirectorySync{@@ -1922,7 +1920,7 @@ func partitionReservedRootEnvFilesInternal(ctx context.Context, syncFiles []projfunc (s *GitOpsSyncService) applyGitSyncEnvToDirInternal(dirPath, projectsDir string, gitEnvContent *string) (before, after string, err error) {update, err := s.projectService.prepareGitSyncEnvUpdateInternal(dirPath, gitEnvContent)if err != nil {- return "", "", fmt.Errorf("failed to resolve git env state: %w", err)+ return "", "", errors.WrapIf(err, "failed to resolve git env state")}before = update.state.DirectContentif update.effectiveContent != nil {@@ -1930,7 +1928,7 @@ func (s *GitOpsSyncService) applyGitSyncEnvToDirInternal(dirPath, projectsDir st}if err := s.projectService.persistGitSyncEnvFilesInternal(dirPath, projectsDir, update); err != nil {- return "", "", fmt.Errorf("failed to sync git env files: %w", err)+ return "", "", errors.WrapIf(err, "failed to sync git env files")}return before, after, nil@@ -1950,7 +1948,7 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Conif errors.Is(err, os.ErrNotExist) {return nil}- return fmt.Errorf("inspect pre-existing project directory %s: %w", candidatePath, err)+ return errors.WrapIff(err, "inspect pre-existing project directory %s", candidatePath)}if !info.IsDir() {return nil@@ -1971,7 +1969,7 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Conslog.WarnContext(ctx, "skipping permission-locked project env file while seeding GitOps stage", "path", filepath.Join(candidatePath, name))return "", false, nil}- return "", false, fmt.Errorf("read %s from %s: %w", name, candidatePath, readErr)+ return "", false, errors.WrapIff(readErr, "read %s from %s", name, candidatePath)}effective, hasEffective, err := readOptional(projects.EffectiveEnvFileName)@@ -1992,27 +1990,27 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Conif hasGit {if err := projects.WriteProjectFile(projectsDir, stagePath, projects.GitSourceEnvFileName, gitSource); err != nil {- return fmt.Errorf("seed stage .env.git: %w", err)+ return errors.WrapIf(err, "seed stage .env.git")}}if hasOverride {if err := projects.WriteProjectFile(projectsDir, stagePath, projects.OverrideEnvFileName, override); err != nil {- return fmt.Errorf("seed stage project.env: %w", err)+ return errors.WrapIf(err, "seed stage project.env")}}switch {case hasEffective:if err := projects.WriteEnvFile(projectsDir, stagePath, effective); err != nil {- return fmt.Errorf("seed stage .env: %w", err)+ return errors.WrapIf(err, "seed stage .env")}case hasGit || hasOverride:merged, mergeErr := projects.BuildEffectiveEnvContent(gitSource, override)if mergeErr != nil {- return fmt.Errorf("build effective env from pre-existing project: %w", mergeErr)+ return errors.WrapIf(mergeErr, "build effective env from pre-existing project")}if err := projects.WriteEnvFile(projectsDir, stagePath, merged); err != nil {- return fmt.Errorf("seed stage .env: %w", err)+ return errors.WrapIf(err, "seed stage .env")}}@@ -2031,7 +2029,7 @@ func (s *GitOpsSyncService) lookupProjectByIDInternal(ctx context.Context, projeif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, fmt.Errorf("failed to get project %s: %w", projectID, err)+ return nil, false, errors.WrapIff(err, "failed to get project %s", projectID)}return &project, true, nil@@ -2043,7 +2041,7 @@ func (s *GitOpsSyncService) lookupProjectByPathInternal(ctx context.Context, proif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, fmt.Errorf("failed to get project by path %s: %w", projectPath, err)+ return nil, false, errors.WrapIff(err, "failed to get project by path %s", projectPath)}return &project, true, nil@@ -2055,7 +2053,7 @@ func (s *GitOpsSyncService) ensureDirectorySyncProjectLinkedInternal(ctx context}if project.GitOpsManagedBy != nil && *project.GitOpsManagedBy != "" && *project.GitOpsManagedBy != sync.ID {- return fmt.Errorf("project %s is already managed by a different GitOps sync", project.ID)+ return errors.Errorf("project %s is already managed by a different GitOps sync", project.ID)}if sync.ProjectID != nil && *sync.ProjectID == project.ID && project.GitOpsManagedBy != nil && *project.GitOpsManagedBy == sync.ID {@@ -2080,12 +2078,12 @@ func (s *GitOpsSyncService) ensureDirectorySyncProjectLinkedInternal(ctx contextif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if len(updatesSync) > 0 {if err := tx.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Updates(updatesSync).Error; err != nil {- return fmt.Errorf("failed to relink GitOps sync %s: %w", sync.ID, err)+ return errors.WrapIff(err, "failed to relink GitOps sync %s", sync.ID)}}if len(updatesProject) > 0 {if err := tx.Model(&models.Project{}).Where("id = ?", project.ID).Updates(updatesProject).Error; err != nil {- return fmt.Errorf("failed to relink project %s to GitOps sync %s: %w", project.ID, sync.ID, err)+ return errors.WrapIff(err, "failed to relink project %s to GitOps sync %s", project.ID, sync.ID)}}return nil@@ -2105,7 +2103,7 @@ func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Coif err := s.db.WithContext(ctx).Where("gitops_managed_by = ?", sync.ID).Find(&managedProjects).Error; err != nil {- return nil, fmt.Errorf("failed to list GitOps-managed projects for sync %s: %w", sync.ID, err)+ return nil, errors.WrapIff(err, "failed to list GitOps-managed projects for sync %s", sync.ID)}matches := make([]models.Project, 0, len(managedProjects))@@ -2115,7 +2113,7 @@ func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Coreturn nil, err}if _, err := s.projectService.resolveProjectComposeFileInternal(ctx, &project); err != nil {- if _, ok := errors.AsType[*common.ProjectComposeFileNotFoundError](err); ok {+ if errors.Is(err, common.ErrProjectComposeFileNotFound) {continue}return nil, err@@ -2129,7 +2127,7 @@ func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Cocase 1:return &matches[0], nildefault:- return nil, fmt.Errorf("multiple GitOps-managed projects match sync %s; refusing automatic relink", sync.ID)+ return nil, errors.Errorf("multiple GitOps-managed projects match sync %s; refusing automatic relink", sync.ID)}}@@ -2141,7 +2139,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contentries, err := os.ReadDir(projectsDir)if err != nil {- return "", fmt.Errorf("failed to list projects directory %s: %w", projectsDir, err)+ return "", errors.WrapIff(err, "failed to list projects directory %s", projectsDir)}composeFileName := strings.TrimSpace(filepath.Base(sync.ComposePath))@@ -2170,7 +2168,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contmatches = append(matches, candidatePath)}} else if !os.IsNotExist(statErr) {- return "", fmt.Errorf("failed to inspect recovery candidate %s: %w", composePath, statErr)+ return "", errors.WrapIff(statErr, "failed to inspect recovery candidate %s", composePath)}}@@ -2180,7 +2178,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contcase 1:return matches[0], nildefault:- return "", fmt.Errorf("multiple candidate project directories match sync %s; refusing automatic relink", sync.ID)+ return "", errors.Errorf("multiple candidate project directories match sync %s; refusing automatic relink", sync.ID)}}@@ -2204,11 +2202,11 @@ func (s *GitOpsSyncService) createRecoveredProjectFromDirectoryInternal(ctx contif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(project).Error; err != nil {- return fmt.Errorf("failed to create recovered project for sync %s: %w", sync.ID, err)+ return errors.WrapIff(err, "failed to create recovered project for sync %s", sync.ID)}if err := tx.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {- return fmt.Errorf("failed to relink sync %s to recovered project %s: %w", sync.ID, project.ID, err)+ return errors.WrapIff(err, "failed to relink sync %s to recovered project %s", sync.ID, project.ID)}return nil@@ -2274,9 +2272,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,project, err := s.findRecoverableManagedProjectInternal(ctx, sync)if err != nil {if establishedBinding {- return nil, &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err),- }+ return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.WrapIff(err, "sync %s references missing project %s", sync.ID, *sync.ProjectID), "GitOps sync project binding broken"))}return nil, err}@@ -2290,9 +2286,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,project, err = s.recoverProjectFromDirectoryCandidateInternal(ctx, sync)if err != nil {if establishedBinding {- return nil, &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err),- }+ return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.WrapIff(err, "sync %s references missing project %s", sync.ID, *sync.ProjectID), "GitOps sync project binding broken"))}return nil, err}@@ -2301,9 +2295,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,}if establishedBinding {- return nil, &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s references missing project %s: no unique recovery candidate was found", sync.ID, *sync.ProjectID),- }+ return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s references missing project %s: no unique recovery candidate was found", sync.ID, *sync.ProjectID), "GitOps sync project binding broken"))}return nil, nil@@ -2341,7 +2333,7 @@ func (s *GitOpsSyncService) validateDirectorySyncStageInternal(ctx context.Contefunc (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Context, sync *models.GitOpsSync, stage *stagedDirectorySync, actor models.User) (*models.Project, error) {projectsDir, err := s.projectService.getProjectsDirectoryInternal(ctx)if err != nil {- return nil, fmt.Errorf("failed to get projects directory: %w", err)+ return nil, errors.WrapIf(err, "failed to get projects directory")}// Non-suffixing create: a GitOps sync must never mint a "-N" duplicate. Any@@ -2352,19 +2344,17 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.ConteprojectPath, folderName, err := projects.CreateExactDir(projectsDir, basePath, sync.ProjectName, 0o755)if err != nil {if errors.Is(err, projects.ErrProjectDirExists) {- return nil, &common.GitOpsSyncProjectBindingBrokenError{- Err: fmt.Errorf("sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)),- }+ return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)), "GitOps sync project binding broken"))}- return nil, fmt.Errorf("failed to create project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create project directory")}if err := os.Remove(projectPath); err != nil {- return nil, fmt.Errorf("failed to prepare project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to prepare project directory")}if err := os.Rename(stage.stagePath, projectPath); err != nil {- return nil, fmt.Errorf("failed to promote staged project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to promote staged project directory")}stage.stagePath = ""@@ -2379,15 +2369,15 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conteif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(project).Error; err != nil {- return fmt.Errorf("failed to create project: %w", err)+ return errors.WrapIf(err, "failed to create project")}if err := tx.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {- return fmt.Errorf("failed to update sync with project ID: %w", err)+ return errors.WrapIf(err, "failed to update sync with project ID")}if err := tx.Model(&models.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", sync.ID).Error; err != nil {- return fmt.Errorf("failed to mark project as GitOps-managed: %w", err)+ return errors.WrapIf(err, "failed to mark project as GitOps-managed")}return nil@@ -2420,26 +2410,26 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conteif info, err := os.Stat(projectPath); err == nil {if !info.IsDir() {- return nil, fmt.Errorf("project path is not a directory: %s", projectPath)+ return nil, errors.Errorf("project path is not a directory: %s", projectPath)}} else if errors.Is(err, os.ErrNotExist) {existed = falseif err := os.MkdirAll(projectPath, 0o755); err != nil {- return nil, fmt.Errorf("failed to recreate project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to recreate project directory")}} else {- return nil, fmt.Errorf("failed to inspect current project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect current project directory")}var backupSkipped []stringif existed {projectsDir, err := s.projectService.getProjectsDirectoryInternal(ctx)if err != nil {- return nil, fmt.Errorf("failed to get projects directory: %w", err)+ return nil, errors.WrapIf(err, "failed to get projects directory")}backupPath, err = os.MkdirTemp(projectsDir, ".gitops-backup-*")if err != nil {- return nil, fmt.Errorf("failed to create backup directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create backup directory")}defer func() { _ = os.RemoveAll(backupPath) }()// Tolerate unreadable files (e.g. foreign-owned bind-mount data) so an@@ -2447,7 +2437,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte// the backup and must be preserved, not pruned, when restoring.backupSkipped, err = projects.CopyDirectoryContentsTolerant(projectPath, backupPath)if err != nil {- return nil, fmt.Errorf("failed to back up current project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to back up current project directory")}if len(backupSkipped) > 0 {slog.WarnContext(ctx, "skipped unreadable files while backing up project for sync; they will be left untouched on rollback", "projectPath", projectPath, "skipped", backupSkipped)@@ -2470,7 +2460,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte// absent from the stage, so a plain mirror would prune them.if err := projects.MirrorDirectoryContentsPreserving(stage.stagePath, projectPath, stage.copySkipped); err != nil {restore()- return nil, fmt.Errorf("failed to promote staged project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to promote staged project directory")}if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", project.ID).Updates(map[string]any{@@ -2479,7 +2469,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte"updated_at": time.Now(),}).Error; err != nil {restore()- return nil, fmt.Errorf("failed to update project metadata after directory sync: %w", err)+ return nil, errors.WrapIf(err, "failed to update project metadata after directory sync")}return project, nildiff --git a/backend/internal/services/gitops_sync_service_test.go b/backend/internal/services/gitops_sync_service_test.goindex 9a3d3ec2e..13a7653de 100644--- a/backend/internal/services/gitops_sync_service_test.go+++ b/backend/internal/services/gitops_sync_service_test.go@@ -3,12 +3,12 @@ package servicesimport ("context""encoding/json"- "errors""os""path/filepath""testing""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -90,8 +90,7 @@ func TestGitOpsSyncService_GetSyncByID_ReturnsNotFoundError(t *testing.T) {_, err := svc.GetSyncByID(ctx, "0", "missing-sync")- var notFound *models.NotFoundError- require.ErrorAs(t, err, ¬Found)+ require.ErrorIs(t, err, common.ErrNotFound)}func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *testing.T) {@@ -340,8 +339,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision(}_, _, _, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- require.ErrorAs(t, err, &bindingErr)+ require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))assert.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")@@ -374,8 +372,7 @@ func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(tresult := &gitops.SyncResult{}_, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, models.User{})- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- require.ErrorAs(t, err, &bindingErr)+ require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))assert.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")@@ -1148,8 +1145,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})require.Error(t, err)- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- require.ErrorAs(t, err, &bindingErr)+ require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)assert.Nil(t, syncedFiles)assert.False(t, created)@@ -1207,8 +1203,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProjectproject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})require.Error(t, err)- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- require.ErrorAs(t, err, &bindingErr)+ require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)assert.Nil(t, syncedFiles)assert.False(t, created)@@ -1250,8 +1245,7 @@ func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissiresult := &gitops.SyncResult{}project, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, models.User{})require.Error(t, err)- var bindingErr *common.GitOpsSyncProjectBindingBrokenError- require.ErrorAs(t, err, &bindingErr)+ require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)var projectCount int64@@ -1573,9 +1567,8 @@ func TestValidateLifecycleConfig_RejectsScriptWithoutSyncDirectoryOnCreate(t *tesyncDirectory: new(false),})require.Error(t, err)- validationErr, ok := errors.AsType[*models.ValidationError](err)- require.True(t, ok, "expected *models.ValidationError, got %T", err)- require.Equal(t, "preDeployScriptPath", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")}func TestValidateLifecycleConfig_AcceptsScriptWithSyncDirectoryOnCreate(t *testing.T) {@@ -1597,9 +1590,8 @@ func TestValidateLifecycleConfig_RejectsLifecycleHookForSwarmStack(t *testing.T)syncDirectory: new(true),})require.Error(t, err)- validationErr, ok := errors.AsType[*models.ValidationError](err)- require.True(t, ok, "expected *models.ValidationError, got %T", err)- require.Equal(t, "preDeployScriptPath", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")require.Contains(t, err.Error(), "project syncs")}@@ -1612,9 +1604,8 @@ func TestValidateLifecycleConfig_RejectsSwarmTargetChangeWithExistingLifecycleHotargetType: new("swarm_stack"),})require.Error(t, err)- validationErr, ok := errors.AsType[*models.ValidationError](err)- require.True(t, ok, "expected *models.ValidationError, got %T", err)- require.Equal(t, "preDeployScriptPath", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")require.Contains(t, err.Error(), "project syncs")}@@ -1637,21 +1628,18 @@ func TestValidateLifecycleConfig_RejectsSyncDirectoryToggleOffWhileScriptStillSesyncDirectory: new(false),})require.Error(t, err)- validationErr, ok := errors.AsType[*models.ValidationError](err)- require.True(t, ok, "expected *models.ValidationError, got %T", err)- require.Equal(t, "preDeployScriptPath", validationErr.Field)+ require.ErrorIs(t, err, common.ErrValidation)+ require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")}func TestRedeployAfterSyncFailedError_FormatAndUnwrap(t *testing.T) {cause := errors.New("pre-deploy hook bombed")- err := &common.RedeployAfterSyncFailedError{Err: cause}+ err := common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(cause, "redeploy failed"))require.Equal(t, "redeploy failed: pre-deploy hook bombed", err.Error())require.True(t, errors.Is(err, cause), "Unwrap should expose the cause for errors.Is")- typed, ok := errors.AsType[*common.RedeployAfterSyncFailedError](err)- require.True(t, ok)- require.Equal(t, cause, typed.Err)+ require.ErrorIs(t, err, common.ErrRedeployAfterSyncFailed)}func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {@@ -1675,7 +1663,7 @@ func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {result := &gitops.SyncResult{Success: true}syncedFiles := []string{"compose.yml", "scripts/pre-deploy.sh"}- hookErr := &common.RedeployAfterSyncFailedError{Err: errors.New("pre-deploy hook failed: exit 1")}+ hookErr := common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(errors.New("pre-deploy hook failed: exit 1"), "redeploy failed"))svc.markSyncRedeployFailedInternal(ctx, sync, sync.ID, "abc123", syncedFiles, hookErr, models.User{BaseModel: models.BaseModel{ID: "user"}, Username: "tester"}, result)diff --git a/backend/internal/services/image_attestations_service.go b/backend/internal/services/image_attestations_service.goindex c984e08db..b5205c210 100644--- a/backend/internal/services/image_attestations_service.go+++ b/backend/internal/services/image_attestations_service.go@@ -5,13 +5,13 @@ import ("compress/gzip""context"json "encoding/json/v2"- "errors"- "fmt""io""log/slog""net/http""strings"+ "emperror.dev/errors"+"github.com/containerd/platforms"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"@@ -80,13 +80,13 @@ func (s *ImageService) GetImageAttestations(ctx context.Context, imageName strinref, err := name.ParseReference(resolution.ImageRef, name.WeakValidation)if err != nil {- return nil, fmt.Errorf("parse image reference %q: %w", resolution.ImageRef, err)+ return nil, errors.WrapIff(err, "parse image reference %q", resolution.ImageRef)}remoteOptions := s.remoteOptionsForImageRefInternal(ctx, resolution.ImageRef)remoteDescriptor, err := remote.Get(ref, remoteOptions...)if err != nil {- return nil, fmt.Errorf("get image manifest %q: %w", resolution.ImageRef, err)+ return nil, errors.WrapIff(err, "get image manifest %q", resolution.ImageRef)}if out.SubjectDigest == "" {@@ -147,10 +147,10 @@ func (s *ImageService) resolveImageAttestationReferenceInternal(ctx context.Cont}if isLikelyLocalImageIDInternal(imageName) {- return imageAttestationReferenceInternal{}, fmt.Errorf("image %q does not have a registry reference", imageName)+ return imageAttestationReferenceInternal{}, errors.Errorf("image %q does not have a registry reference", imageName)}if _, err := name.ParseReference(imageName, name.WeakValidation); err != nil {- return imageAttestationReferenceInternal{}, fmt.Errorf("image %q does not have a registry reference: %w", imageName, err)+ return imageAttestationReferenceInternal{}, errors.WrapIff(err, "image %q does not have a registry reference", imageName)}return imageAttestationReferenceInternal{ImageRef: imageName,@@ -208,7 +208,7 @@ func parseAttestationPlatformInternal(value string) (ocispec.Platform, bool, errplatform, err := platforms.Parse(value)if err != nil {- return ocispec.Platform{}, false, fmt.Errorf("invalid platform %q: %w", value, err)+ return ocispec.Platform{}, false, errors.WrapIff(err, "invalid platform %q", value)}return platform, true, nil}@@ -265,12 +265,12 @@ func imageAttestationSubjectsInternal(descriptor *remote.Descriptor, platform ocindex, err := descriptor.ImageIndex()if err != nil {- return nil, nil, fmt.Errorf("read image index %s: %w", descriptor.Digest.String(), err)+ return nil, nil, errors.WrapIff(err, "read image index %s", descriptor.Digest.String())}indexManifest, err := index.IndexManifest()if err != nil {- return nil, nil, fmt.Errorf("read image index manifest %s: %w", descriptor.Digest.String(), err)+ return nil, nil, errors.WrapIff(err, "read image index manifest %s", descriptor.Digest.String())}subjects := make([]imageAttestationSubjectInternal, 0, len(indexManifest.Manifests)+1)@@ -348,19 +348,19 @@ func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, repif shouldIgnoreReferrersErrorInternal(err) {return nil, nil}- return nil, fmt.Errorf("query image referrers for %s: %w", subject.Digest, err)+ return nil, errors.WrapIff(err, "query image referrers for %s", subject.Digest)}manifest, err := referrers.IndexManifest()if err != nil {- return nil, fmt.Errorf("read image referrers for %s: %w", subject.Digest, err)+ return nil, errors.WrapIff(err, "read image referrers for %s", subject.Digest)}attestations := make([]imagetypes.Attestation, 0, len(manifest.Manifests))for _, referrer := range manifest.Manifests {referrerDescriptor, err := remote.Get(repository.Digest(referrer.Digest.String()), remoteOptions...)if err != nil {- return nil, fmt.Errorf("get image referrer %s: %w", referrer.Digest.String(), err)+ return nil, errors.WrapIff(err, "get image referrer %s", referrer.Digest.String())}referrerImage, err := referrerDescriptor.Image()@@ -399,7 +399,7 @@ func readInlineAttestationsInternal(ctx context.Context, index v1.ImageIndex, suindexManifest, err := index.IndexManifest()if err != nil {- return nil, fmt.Errorf("read image index manifest for inline attestations: %w", err)+ return nil, errors.WrapIf(err, "read image index manifest for inline attestations")}subjectByDigest := make(map[string]imageAttestationSubjectInternal, len(subjects))@@ -424,7 +424,7 @@ func readInlineAttestationsInternal(ctx context.Context, index v1.ImageIndex, suattestationImage, err := index.Image(descriptor.Digest)if err != nil {- return nil, fmt.Errorf("read inline attestation image %s: %w", descriptor.Digest.String(), err)+ return nil, errors.WrapIff(err, "read inline attestation image %s", descriptor.Digest.String())}items, err := readAttestationImageInternal(ctx, attestationImage, descriptor, subject.Platform, query)@@ -453,7 +453,7 @@ func isInlineAttestationDescriptorInternal(descriptor v1.Descriptor) bool {func readAttestationImageInternal(ctx context.Context, attestationImage v1.Image, artifactDescriptor v1.Descriptor, platform string, query ImageAttestationQuery) ([]imagetypes.Attestation, error) {manifest, err := attestationImage.Manifest()if err != nil {- return nil, fmt.Errorf("read attestation manifest %s: %w", artifactDescriptor.Digest.String(), err)+ return nil, errors.WrapIff(err, "read attestation manifest %s", artifactDescriptor.Digest.String())}artifactType := artifactDescriptor.ArtifactType@@ -489,7 +489,7 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imagelayer, err := attestationImage.LayerByDigest(layerDescriptor.Digest)if err != nil {- return imagetypes.Attestation{}, false, fmt.Errorf("read attestation layer %s: %w", layerDescriptor.Digest.String(), err)+ return imagetypes.Attestation{}, false, errors.WrapIff(err, "read attestation layer %s", layerDescriptor.Digest.String())}rawStatement, err := readAttestationLayerBytesInternal(layer, layerDescriptor.Digest.String())@@ -499,7 +499,7 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imagestatement, err := parseAttestationStatementInternal(rawStatement)if err != nil {- return imagetypes.Attestation{}, false, fmt.Errorf("parse attestation statement %s: %w", layerDescriptor.Digest.String(), err)+ return imagetypes.Attestation{}, false, errors.WrapIff(err, "parse attestation statement %s", layerDescriptor.Digest.String())}if statement.PredicateType == "" {statement.PredicateType = annotationPredicate@@ -535,20 +535,20 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imagefunc readAttestationLayerBytesInternal(layer v1.Layer, digest string) ([]byte, error) {reader, err := layer.Compressed()if err != nil {- return nil, fmt.Errorf("open attestation layer %s: %w", digest, err)+ return nil, errors.WrapIff(err, "open attestation layer %s", digest)}rawStatement, readErr := io.ReadAll(reader)closeErr := reader.Close()if readErr != nil {- return nil, fmt.Errorf("read attestation layer %s: %w", digest, readErr)+ return nil, errors.WrapIff(readErr, "read attestation layer %s", digest)}if closeErr != nil {- return nil, fmt.Errorf("close attestation layer %s: %w", digest, closeErr)+ return nil, errors.WrapIff(closeErr, "close attestation layer %s", digest)}statement, err := decompressAttestationStatementInternal(rawStatement)if err != nil {- return nil, fmt.Errorf("decompress attestation layer %s: %w", digest, err)+ return nil, errors.WrapIff(err, "decompress attestation layer %s", digest)}return statement, nil}diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.goindex 8003915c2..34b3cc401 100644--- a/backend/internal/services/image_service.go+++ b/backend/internal/services/image_service.go@@ -2,7 +2,6 @@ package servicesimport ("context"- "errors""fmt""io""log/slog"@@ -10,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -60,7 +61,7 @@ func NewImageService(db *database.DB, dockerService *DockerClientService, registfunc (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypes.DetailSummary, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}var (@@ -74,7 +75,7 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypvar err errorinspectResult, err := dockerClient.ImageInspect(gctx, id)if err != nil {- return fmt.Errorf("inspect not found: %w", err)+ return errors.WrapIf(err, "inspect not found")}inspect = inspectResult.InspectResponsereturn nil@@ -83,7 +84,7 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypg.Go(func() error {imageList, err := dockerClient.ImageList(gctx, client.ImageListOptions{})if err != nil {- return fmt.Errorf("failed to list images: %w", err)+ return errors.WrapIf(err, "failed to list images")}for _, img := range imageList.Items {if img.ID == id {@@ -110,7 +111,7 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, udockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", id, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}imageDetails, inspectErr := dockerClient.ImageInspect(ctx, id)@@ -129,7 +130,7 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u_, err = dockerClient.ImageRemove(ctx, id, options)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", id, imageName, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})- return fmt.Errorf("failed to remove image: %w", err)+ return errors.WrapIf(err, "failed to remove image")}if s.db != nil {@@ -169,7 +170,7 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, models.JSON{"action": "pull"})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}slog.DebugContext(ctx, "Attempting to pull image", "image", imageName, "externalCredCount", len(externalCreds))@@ -193,7 +194,7 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressif err != nil {slog.ErrorContext(ctx, "Docker ImagePull failed", "image", imageName, "hasAuth", pullOptions.RegistryAuth != "", "initialHasAuth", initialHasAuth, "retriedWithoutAuth", retriedWithoutAuth, "error", err.Error())s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, models.JSON{"action": "pull"})- return fmt.Errorf("failed to initiate image pull for %s: %w", imageName, err)+ return errors.WrapIff(err, "failed to initiate image pull for %s", imageName)}defer func() { _ = reader.Close() }()@@ -219,10 +220,10 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressif errors.Is(streamErr, context.Canceled) || strings.Contains(streamErr.Error(), "context canceled") {slog.Debug("image pull stream canceled", "image", imageName, "err", streamErr)s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "pull", "step": "canceled"})- return fmt.Errorf("image pull stream canceled for %s: %w", imageName, streamErr)+ return errors.WrapIff(streamErr, "image pull stream canceled for %s", imageName)}s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "pull", "step": "read_stream"})- return fmt.Errorf("error reading image pull stream for %s: %w", imageName, streamErr)+ return errors.WrapIff(streamErr, "error reading image pull stream for %s", imageName)}slog.Debug("image pull stream completed", "image", imageName)@@ -271,13 +272,13 @@ func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, models.JSON{"action": "tag", "target": target})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.ImageTag(ctx, client.ImageTagOptions{Source: source, Target: target})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, models.JSON{"action": "tag", "target": target})- return fmt.Errorf("failed to tag image: %w", err)+ return errors.WrapIf(err, "failed to tag image")}metadata := models.JSON{@@ -303,12 +304,12 @@ func (s *ImageService) GetImageHistory(ctx context.Context, imageName string) ([dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}result, err := dockerClient.ImageHistory(ctx, imageName)if err != nil {- return nil, fmt.Errorf("failed to get image history: %w", err)+ return nil, errors.WrapIf(err, "failed to get image history")}items := make([]imagetypes.HistoryItem, 0, len(result.Items))@@ -334,12 +335,12 @@ func (s *ImageService) SearchImages(ctx context.Context, term string) ([]imagetydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}result, err := dockerClient.ImageSearch(ctx, term, client.ImageSearchOptions{})if err != nil {- return nil, fmt.Errorf("failed to search images: %w", err)+ return nil, errors.WrapIf(err, "failed to search images")}items := make([]imagetypes.SearchResult, 0, len(result.Items))@@ -363,12 +364,12 @@ func (s *ImageService) ExportImage(ctx context.Context, imageName string) (io.RedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}reader, err := dockerClient.ImageSave(ctx, []string{imageName})if err != nil {- return nil, fmt.Errorf("failed to export image: %w", err)+ return nil, errors.WrapIf(err, "failed to export image")}return reader, nil}@@ -380,7 +381,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.ReaderdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, models.JSON{"action": "load"})- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}// ImageLoad accepts a tar archive reader and optional load options@@ -388,10 +389,10 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Readerif err != nil {// Check if error is due to size limit being exceededif err.Error() == "unexpected EOF" || strings.Contains(err.Error(), "unexpected EOF") {- return nil, fmt.Errorf("file size exceeds maximum allowed size of %d MB", maxSizeBytes/(1024*1024))+ return nil, errors.Errorf("file size exceeds maximum allowed size of %d MB", maxSizeBytes/(1024*1024))}s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, models.JSON{"action": "load", "file": fileName})- return nil, fmt.Errorf("failed to load image from tar: %w", err)+ return nil, errors.WrapIf(err, "failed to load image from tar")}defer func() { _ = loadResp.Close() }()@@ -408,7 +409,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Reader})if streamErr != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "load", "file": fileName, "step": "read_response"})- return nil, fmt.Errorf("failed to read load response: %w", streamErr)+ return nil, errors.WrapIf(streamErr, "failed to read load response")}result.Stream = responseBuilder.String()@@ -427,7 +428,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Readerfunc (s *ImageService) ImageExistsLocally(ctx context.Context, imageName string) (bool, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return false, fmt.Errorf("failed to connect to Docker: %w", err)+ return false, errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.ImageInspect(ctx, imageName)@@ -439,7 +440,7 @@ func (s *ImageService) ImageExistsLocally(ctx context.Context, imageName string)if strings.Contains(errLower, "no such image") || strings.Contains(errLower, "not found") {return false, nil}- return false, fmt.Errorf("failed to inspect image %s: %w", imageName, err)+ return false, errors.WrapIff(err, "failed to inspect image %s", imageName)}func (s *ImageService) getPullOptionsWithAuth(ctx context.Context, imageRef string, externalCreds []containerregistry.Credential) (client.ImagePullOptions, error) {@@ -456,7 +457,7 @@ func (s *ImageService) getPullOptionsWithAuth(ctx context.Context, imageRef striif utilsregistry.IsRegistryMatch(cred.URL, registryHost) {authStr, err := utilsregistry.EncodeAuthHeader(cred.Username, cred.Token, utilsregistry.NormalizeRegistryURL(cred.URL))if err != nil {- return pullOptions, fmt.Errorf("failed to create auth header: %w", err)+ return pullOptions, errors.WrapIf(err, "failed to create auth header")}pullOptions.RegistryAuth = authStr@@ -471,7 +472,7 @@ func (s *ImageService) getPullOptionsWithAuth(ctx context.Context, imageRef striauthStr, err := s.registryService.GetRegistryAuthForHost(ctx, registryHost)if err != nil {- return pullOptions, fmt.Errorf("failed to get registry credentials: %w", err)+ return pullOptions, errors.WrapIf(err, "failed to get registry credentials")}if authStr != "" {pullOptions.RegistryAuth = authStr@@ -513,7 +514,7 @@ func isUnauthorizedPullErrorInternal(err error) bool {func (s *ImageService) PruneImages(ctx context.Context, options systemtypes.PruneImagesOptions) (*image.PruneReport, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}filterArgs := make(client.Filters)@@ -530,12 +531,12 @@ func (s *ImageService) PruneImages(ctx context.Context, options systemtypes.Prun}filterArgs = filterArgs.Add("until", options.Until)default:- return nil, fmt.Errorf("unsupported image prune mode: %s", options.Mode)+ return nil, errors.Errorf("unsupported image prune mode: %s", options.Mode)}report, err := dockerClient.ImagePrune(ctx, client.ImagePruneOptions{Filters: filterArgs})if err != nil {- return nil, fmt.Errorf("failed to prune images: %w", err)+ return nil, errors.WrapIf(err, "failed to prune images")}pruneReport := report.Report@@ -617,7 +618,7 @@ func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []svar updateRecords []models.ImageUpdateRecordif err := s.db.WithContext(ctx).Where("id IN ?", imageIDs).Find(&updateRecords).Error; err != nil {- return nil, fmt.Errorf("failed to fetch update records: %w", err)+ return nil, errors.WrapIf(err, "failed to fetch update records")}result := make(map[string]*imagetypes.UpdateInfo, len(updateRecords))@@ -675,7 +676,7 @@ func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs [Where("tag IN ? AND repository IN ?", tags, repositoryCandidates).Order("check_time DESC").Find(&updateRecords).Error; err != nil {- return nil, fmt.Errorf("failed to fetch update records by image refs: %w", err)+ return nil, errors.WrapIf(err, "failed to fetch update records by image refs")}for _, lookup := range lookups {@@ -701,7 +702,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatiovar err errorimageList, err := s.dockerService.listImagesInternal(groupCtx)if err != nil {- return fmt.Errorf("failed to list Docker images: %w", err)+ return errors.WrapIf(err, "failed to list Docker images")}dockerImages = imageListreturn nil@@ -712,7 +713,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatiovar err errorcontainerList, err := s.dockerService.listContainersInternal(groupCtx)if err != nil {- return fmt.Errorf("failed to list containers: %w", err)+ return errors.WrapIf(err, "failed to list containers")}containers = containerListreturn nil@@ -729,7 +730,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatioif s.db != nil && len(imageIDs) > 0 {if err := s.db.WithContext(ctx).Where("id IN ?", imageIDs).Find(&updateRecords).Error; err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to fetch image update records: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to fetch image update records")}}@@ -859,7 +860,7 @@ func convertLabels(labels map[string]string) map[string]any {func (s *ImageService) GetTotalImageSize(ctx context.Context) (int64, error) {images, err := s.dockerService.listImagesInternal(ctx)if err != nil {- return 0, fmt.Errorf("failed to list images: %w", err)+ return 0, errors.WrapIf(err, "failed to list images")}var total int64diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.goindex a738f5391..4fbdb5dae 100644--- a/backend/internal/services/image_update_service.go+++ b/backend/internal/services/image_update_service.go@@ -2,15 +2,16 @@ package servicesimport ("context"- "errors""fmt""log/slog""maps"- "runtime/debug""strings""sync""time"+ "emperror.dev/emperror"+ "emperror.dev/errors"+ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -94,7 +95,7 @@ func (s *ImageUpdateService) dockerClientInternal(ctx context.Context) (*client.}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}return dockerClient, nil}@@ -110,7 +111,7 @@ func (s *ImageUpdateService) composeBuildImageRefsInternal(ctx context.Context)Select("id", "build_image_refs_json").Where("build_image_refs_json IS NOT NULL AND build_image_refs_json <> ''").Find(&projectRows).Error; err != nil {- return nil, fmt.Errorf("load project build image references: %w", err)+ return nil, errors.WrapIf(err, "load project build image references")}for i := range projectRows {@@ -390,7 +391,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.Cif err != nil {partial := digestResult // may contain auth metadata even on errorif partial == nil {- return nil, nil, fmt.Errorf("failed to get remote digest: %w", err)+ return nil, nil, errors.WrapIf(err, "failed to get remote digest")}return &imageupdate.Response{Error: err.Error(),@@ -400,13 +401,13 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.CAuthUsername: partial.AuthUsername,AuthRegistry: partial.AuthRegistry,UsedCredential: partial.UsedCredential,- }, nil, fmt.Errorf("failed to get remote digest: %w", err)+ }, nil, errors.WrapIf(err, "failed to get remote digest")}if snapshot == nil {snapshot, err = s.inspectLocalImageSnapshotInternal(ctx, imageRef, composeBuildRefs)if err != nil {- return nil, nil, fmt.Errorf("failed to get local digest: %w", err)+ return nil, nil, errors.WrapIf(err, "failed to get local digest")}}@@ -560,7 +561,7 @@ func (s *ImageUpdateService) getImageRefByIDInternal(ctx context.Context, imageIreturn ref, nil}- return "", fmt.Errorf("image not found: no local image or running container found for %s", imageID)+ return "", errors.Errorf("image not found: no local image or running container found for %s", imageID)}func (s *ImageUpdateService) resolveImageRefFromInspect(ctx context.Context, dockerClient client.APIClient, imageID string) (string, error) {@@ -603,7 +604,7 @@ func (s *ImageUpdateService) resolveImageRefFromContainers(ctx context.Context,return c.Image, nil}}- return "", fmt.Errorf("no container found using image %s", imageID)+ return "", errors.Errorf("no container found using image %s", imageID)}func (s *ImageUpdateService) getAllImageRefsInternal(ctx context.Context, limit int) ([]string, error) {@@ -617,7 +618,7 @@ func (s *ImageUpdateService) getAllImageRefsInternal(ctx context.Context, limitimageList, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list Docker images: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker images")}return dedupeImageRefsFromSummariesInternal(imageList.Items, limit), nil@@ -654,7 +655,7 @@ func (s *ImageUpdateService) inspectLocalImageSnapshotInternal(ctx context.ConteinspectResponse, err := dockerClient.ImageInspect(apiCtx, imageRef)if err != nil {- return nil, fmt.Errorf("failed to inspect image: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect image")}var allDigests []string@@ -720,7 +721,7 @@ func (s *ImageUpdateService) CheckImageUpdateByID(ctx context.Context, imageID sif logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, imageID, "", systemUser.ID, systemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "Failed to log image update check by ID error event", "imageID", imageID, "error", logErr.Error())}- return nil, fmt.Errorf("failed to get image reference: %w", err)+ return nil, errors.WrapIf(err, "failed to get image reference")}result, err := s.CheckImageUpdate(ctx, imageRef)if err != nil {@@ -948,7 +949,7 @@ func (s *ImageUpdateService) saveUpdateResultByIDInternal(ctx context.Context, idockerImage, err := dockerClient.ImageInspect(apiCtx, imageID)if err != nil {- return fmt.Errorf("failed to inspect image: %w", err)+ return errors.WrapIf(err, "failed to inspect image")}repo, tag := extractRepoAndTagFromImage(dockerImage.InspectResponse)@@ -980,7 +981,7 @@ func (s *ImageUpdateService) getImageIDByRef(ctx context.Context, imageRef strininspectResponse, err := dockerClient.ImageInspect(apiCtx, imageRef)if err != nil {- return "", fmt.Errorf("image not found: %w", err)+ return "", errors.WrapIf(err, "image not found")}return inspectResponse.ID, nil}@@ -992,7 +993,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,snapshot, err := s.inspectLocalImageSnapshotInternal(ctx, imageRef, nil)if err != nil {- return fmt.Errorf("inspect pulled image: %w", err)+ return errors.WrapIf(err, "inspect pulled image")}checkTime := time.Now().UTC()@@ -1018,13 +1019,13 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,if err := tx.Model(&models.ImageUpdateRecord{}).Where("id LIKE 'ref::%' AND tag = ? AND repository IN ?", lookup.tag, repositories).Update("has_update", false).Error; err != nil {- return fmt.Errorf("clear stale image updates: %w", err)+ return errors.WrapIf(err, "clear stale image updates")}}}if err := savePreparedUpdateResultWithTxInternal(tx, snapshot.ImageID, snapshot.Repository, snapshot.Tag, result); err != nil {- return fmt.Errorf("save pulled image update state: %w", err)+ return errors.WrapIf(err, "save pulled image update state")}return nil@@ -1042,7 +1043,7 @@ func (s *ImageUpdateService) getStoredUpdateByImageIDInternal(ctx context.Contexif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, fmt.Errorf("get stored image update by image id: %w", err)+ return nil, false, errors.WrapIf(err, "get stored image update by image id")}return &record, true, nil@@ -1054,7 +1055,7 @@ func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[striif err := s.db.WithContext(ctx).Where("has_update = ? AND notification_sent = ?", true, false).Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to get unnotified updates: %w", err)+ return nil, errors.WrapIf(err, "failed to get unnotified updates")}result := make(map[string]*models.ImageUpdateRecord)@@ -1354,10 +1355,10 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs// completion would strand the row in running forever. It reads the Track// ctx so a user cancellation still records a cancelled status.defer func() {- if r := recover(); r != nil {+ if panicErr := emperror.Recover(recover()); panicErr != nil {// Don't re-panic: the caller is the long-lived watcher goroutine.- err = fmt.Errorf("image update check panicked: %v", r)- slog.ErrorContext(ctx, "image update check panicked", "activityId", activityID, "panic", r, "stack", string(debug.Stack()))+ err = errors.WrapIf(panicErr, "image update check panicked")+ slog.ErrorContext(ctx, "image update check panicked", "activityId", activityID, "error", err)}if err != nil {s.completeImageUpdateActivityInternal(ctx, activityID, false, "Image update check failed: "+err.Error())@@ -1392,7 +1393,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefscomposeBuildRefs, composeErr := s.composeBuildImageRefsInternal(scanCtx)if composeErr != nil {- err = fmt.Errorf("prepare compose build image references: %w", composeErr)+ err = errors.WrapIf(composeErr, "prepare compose build image references")return results, err}@@ -1413,9 +1414,9 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs// the process), so convert them to errors here; the deferred// finalizer then records the failed terminal status.defer func() {- if r := recover(); r != nil {- checkErr = fmt.Errorf("image update check panicked: %v", r)- slog.ErrorContext(groupCtx, "image update check worker panicked", "activityId", activityID, "imageRef", img.canonicalRef, "panic", r, "stack", string(debug.Stack()))+ if panicErr := emperror.Recover(recover()); panicErr != nil {+ checkErr = errors.WrapIf(panicErr, "image update check panicked")+ slog.ErrorContext(groupCtx, "image update check worker panicked", "activityId", activityID, "imageRef", img.canonicalRef, "error", checkErr)}}()return s.checkBatchImageInternal(groupCtx, activityID, resolvedCreds, img, composeBuildRefs, recorder)@@ -1424,7 +1425,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefsif err = g.Wait(); err != nil {if ctx.Err() == nil && errors.Is(scanCtx.Err(), context.DeadlineExceeded) {- err = fmt.Errorf("image update check timed out after %s: %w", timeouts.DefaultImageUpdateScan, err)+ err = errors.WrapIff(err, "image update check timed out after %s", timeouts.DefaultImageUpdateScan)}slog.ErrorContext(ctx, "Batch check error", "error", err)return results, err@@ -1518,7 +1519,7 @@ func (s *ImageUpdateService) sendBatchImageUpdateNotificationsInternal(ctx contefunc (s *ImageUpdateService) CheckAllImages(ctx context.Context, limit int, externalCreds []containerregistry.Credential) (map[string]*imageupdate.Response, error) {imageRefs, err := s.getAllImageRefsInternal(ctx, limit)if err != nil {- return nil, fmt.Errorf("failed to get image references: %w", err)+ return nil, errors.WrapIf(err, "failed to get image references")}if len(imageRefs) == 0 {@@ -1553,7 +1554,7 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {dockerImagesResult, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{})if err != nil {- return fmt.Errorf("failed to list Docker images: %w", err)+ return errors.WrapIf(err, "failed to list Docker images")}dockerImages := dockerImagesResult.Items@@ -1569,7 +1570,7 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {result = s.db.WithContext(ctx).Where("id NOT IN ?", dockerImageIDs).Delete(&models.ImageUpdateRecord{})}if result.Error != nil {- return fmt.Errorf("failed to delete orphaned records: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete orphaned records")}if result.RowsAffected > 0 {diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.goindex 0c8e2713f..c9a8b7c42 100644--- a/backend/internal/services/job_service.go+++ b/backend/internal/services/job_service.go@@ -2,12 +2,12 @@ package servicesimport ("context"- "errors"- "fmt"+ stderrors "errors""log/slog""sort""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -117,7 +117,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedulecontinue}if _, err := parser.Parse(*field.update); err != nil {- return jobschedule.Config{}, fmt.Errorf("invalid cron expression for %s: %w", field.key, err)+ return jobschedule.Config{}, errors.WrapIff(err, "invalid cron expression for %s", field.key)}}@@ -146,24 +146,22 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedulereturn nil})if err != nil {- return jobschedule.Config{}, fmt.Errorf("failed to update job schedules: %w", err)+ return jobschedule.Config{}, errors.WrapIf(err, "failed to update job schedules")}// Refresh settings cache so jobs reading from SettingsService see new values.if changed {if err := s.settings.LoadDatabaseSettings(ctx); err != nil {restoreErr := s.restoreJobSchedulesInternal(ctx, previousValues, changedKeys)- return jobschedule.Config{}, errors.Join(- fmt.Errorf("failed to reload settings after job schedule update: %w", err),- restoreErr,+ return jobschedule.Config{}, stderrors.Join(errors.+ WrapIf(err, "failed to reload settings after job schedule update"), restoreErr,)}if err := s.RescheduleJobsForSettingKeys(ctx, changedKeys); err != nil {restoreErr := s.restoreJobSchedulesInternal(ctx, previousValues, changedKeys)- return jobschedule.Config{}, errors.Join(- fmt.Errorf("failed to apply job schedule update: %w", err),- restoreErr,+ return jobschedule.Config{}, stderrors.Join(errors.+ WrapIf(err, "failed to apply job schedule update"), restoreErr,)}}@@ -198,7 +196,7 @@ func (s *JobService) RescheduleJobsForSettingKeys(ctx context.Context, changedKe}}- return errors.Join(rescheduleErrors...)+ return stderrors.Join(rescheduleErrors...)}// jobRescheduleContextInternal prefers the app lifecycle context so cron jobs@@ -235,23 +233,23 @@ func (s *JobService) rescheduleAffectedJobInternal(ctx context.Context, jobID stjob, ok := s.scheduler.GetJob(jobID).Get()if !ok {- return fmt.Errorf("job %s not found in scheduler", jobID)+ return errors.Errorf("job %s not found in scheduler", jobID)}slog.DebugContext(ctx, "Processing job setting change", "job", jobID, "settingsKey", jobMeta.SettingsKey, "enabledKey", jobMeta.EnabledKey)rescheduleCtx := s.jobRescheduleContextInternal(ctx)if err := s.scheduler.RescheduleJob(rescheduleCtx, job); err != nil {- return fmt.Errorf("reschedule job %s: %w", jobID, err)+ return errors.WrapIff(err, "reschedule job %s", jobID)}runtimeState, ok := s.scheduler.GetJobRuntimeState(jobID).Get()if !ok {- return fmt.Errorf("job %s has no runtime scheduler state", jobID)+ return errors.Errorf("job %s has no runtime scheduler state", jobID)}expectedSchedule := job.Schedule(rescheduleCtx)if runtimeState.Schedule != expectedSchedule {- return fmt.Errorf("job %s runtime schedule %q does not match requested schedule %q", jobID, runtimeState.Schedule, expectedSchedule)+ return errors.Errorf("job %s runtime schedule %q does not match requested schedule %q", jobID, runtimeState.Schedule, expectedSchedule)}return nil}@@ -269,15 +267,15 @@ func (s *JobService) restoreJobSchedulesInternal(ctx context.Context, previousVa}return nil}); err != nil {- return fmt.Errorf("failed to restore previous job schedules: %w", err)+ return errors.WrapIf(err, "failed to restore previous job schedules")}if err := s.settings.LoadDatabaseSettings(ctx); err != nil {- return fmt.Errorf("failed to reload restored job schedules: %w", err)+ return errors.WrapIf(err, "failed to reload restored job schedules")}if err := s.RescheduleJobsForSettingKeys(ctx, changedKeys); err != nil {- return fmt.Errorf("failed to restore runtime job schedules: %w", err)+ return errors.WrapIf(err, "failed to restore runtime job schedules")}return nil@@ -367,20 +365,20 @@ func (s *JobService) getRunnableJobInternal(jobID string) (schedulertypes.Job, emeta, ok := meta.GetJobMetadata(jobID)if !ok {- return nil, fmt.Errorf("unknown job: %s", jobID)+ return nil, errors.Errorf("unknown job: %s", jobID)}if !meta.CanRunManually {- return nil, fmt.Errorf("job %s cannot be run manually", jobID)+ return nil, errors.Errorf("job %s cannot be run manually", jobID)}if s.cfg != nil && s.cfg.AgentMode && meta.ManagerOnly {- return nil, fmt.Errorf("job %s is manager-only and cannot run in agent mode", jobID)+ return nil, errors.Errorf("job %s is manager-only and cannot run in agent mode", jobID)}job, ok := s.scheduler.GetJob(jobID).Get()if !ok {- return nil, fmt.Errorf("job %s not found in scheduler", jobID)+ return nil, errors.Errorf("job %s not found in scheduler", jobID)}return job, nildiff --git a/backend/internal/services/kv_service.go b/backend/internal/services/kv_service.goindex 424a7adfc..ff8c284ae 100644--- a/backend/internal/services/kv_service.go+++ b/backend/internal/services/kv_service.go@@ -2,11 +2,11 @@ package servicesimport ("context"- "errors"- "fmt""strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models""gorm.io/gorm"@@ -29,7 +29,7 @@ func (s *KVService) Get(ctx context.Context, key string) (string, bool, error) {return "", false, nil}if err != nil {- return "", false, fmt.Errorf("failed to load kv entry %q: %w", key, err)+ return "", false, errors.WrapIff(err, "failed to load kv entry %q", key)}return entry.Value, true, nil@@ -44,7 +44,7 @@ func (s *KVService) Set(ctx context.Context, key, value string) error {}).Create(&entry).Errorif err != nil {- return fmt.Errorf("failed to upsert kv entry %q: %w", key, err)+ return errors.WrapIff(err, "failed to upsert kv entry %q", key)}return nil@@ -52,7 +52,7 @@ func (s *KVService) Set(ctx context.Context, key, value string) error {func (s *KVService) Delete(ctx context.Context, key string) error {if err := s.db.WithContext(ctx).Delete(&models.KVEntry{}, "key = ?", key).Error; err != nil {- return fmt.Errorf("failed to delete kv entry %q: %w", key, err)+ return errors.WrapIff(err, "failed to delete kv entry %q", key)}return nil}@@ -61,7 +61,7 @@ func (s *KVService) ListByPrefix(ctx context.Context, prefix string) ([]models.Kvar entries []models.KVEntryescapedPrefix := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(prefix)if err := s.db.WithContext(ctx).Where("key LIKE ? ESCAPE '\\'", escapedPrefix+"%").Find(&entries).Error; err != nil {- return nil, fmt.Errorf("failed to list kv entries with prefix %q: %w", prefix, err)+ return nil, errors.WrapIff(err, "failed to list kv entries with prefix %q", prefix)}return entries, nil}@@ -77,7 +77,7 @@ func (s *KVService) GetBool(ctx context.Context, key string, defaultValue bool)parsedValue, err := strconv.ParseBool(rawValue)if err != nil {- return defaultValue, fmt.Errorf("failed to parse kv entry %q as bool: %w", key, err)+ return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as bool", key)}return parsedValue, nil@@ -98,7 +98,7 @@ func (s *KVService) GetInt64(ctx context.Context, key string, defaultValue int64parsedValue, err := strconv.ParseInt(rawValue, 10, 64)if err != nil {- return defaultValue, fmt.Errorf("failed to parse kv entry %q as int64: %w", key, err)+ return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as int64", key)}return parsedValue, nil@@ -122,7 +122,7 @@ func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64)currentValue, parseErr := strconv.ParseInt(entry.Value, 10, 64)if parseErr != nil {- return fmt.Errorf("failed to parse kv entry %q as int64: %w", key, parseErr)+ return errors.WrapIff(parseErr, "failed to parse kv entry %q as int64", key)}nextValue = currentValue + delta@@ -130,7 +130,7 @@ func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64)return tx.Save(&entry).Error})if err != nil {- return 0, fmt.Errorf("failed to increment kv entry %q: %w", key, err)+ return 0, errors.WrapIff(err, "failed to increment kv entry %q", key)}return nextValue, nildiff --git a/backend/internal/services/lifecycle_service.go b/backend/internal/services/lifecycle_service.goindex 5b2abc421..54261f182 100644--- a/backend/internal/services/lifecycle_service.go+++ b/backend/internal/services/lifecycle_service.go@@ -3,7 +3,6 @@ package servicesimport ("bufio""context"- "errors""fmt""io""log/slog"@@ -14,6 +13,8 @@ import ("strings""time"+ "emperror.dev/errors"+cerrdefs "github.com/containerd/errdefs""github.com/moby/moby/api/pkg/stdcopy"containertypes "github.com/moby/moby/api/types/container"@@ -120,7 +121,7 @@ func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *models.Prosync, err := s.loadGitOpsSyncForProjectInternal(ctx, project.ID)if err != nil {- return fmt.Errorf("failed to load gitops sync for lifecycle hook: %w", err)+ return errors.WrapIf(err, "failed to load gitops sync for lifecycle hook")}if sync == nil || sync.PreDeployScriptPath == nil || strings.TrimSpace(*sync.PreDeployScriptPath) == "" {return nil@@ -132,21 +133,21 @@ func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *models.Profunc (s *LifecycleService) executePreDeployInternal(ctx context.Context, project *models.Project, sync *models.GitOpsSync, actor models.User) error {runnerImage := s.resolveRunnerImageInternal(ctx, sync)if runnerImage == "" {- return fmt.Errorf("pre-deploy script %q is configured but no runner image is set on the GitOps sync or lifecycleDefaultRunnerImage setting", *sync.PreDeployScriptPath)+ return errors.Errorf("pre-deploy script %q is configured but no runner image is set on the GitOps sync or lifecycleDefaultRunnerImage setting", *sync.PreDeployScriptPath)}scriptPath := strings.TrimSpace(*sync.PreDeployScriptPath)if err := validateScriptPathInternal(project.Path, scriptPath); err != nil {- return fmt.Errorf("invalid pre-deploy script path: %w", err)+ return errors.WrapIf(err, "invalid pre-deploy script path")}hookEnv, err := parseLifecycleEnvTextInternal(sync.PreDeployEnv)if err != nil {- return fmt.Errorf("invalid lifecycle env config: %w", err)+ return errors.WrapIf(err, "invalid lifecycle env config")}extraMounts, err := parseLifecycleExtraMountsTextInternal(sync.PreDeployExtraMounts)if err != nil {- return fmt.Errorf("invalid lifecycle extra mounts config: %w", err)+ return errors.WrapIf(err, "invalid lifecycle extra mounts config")}timeout := s.resolveTimeoutInternal(ctx, sync.PreDeployTimeoutSec)@@ -185,7 +186,7 @@ func (s *LifecycleService) executePreDeployInternal(ctx context.Context, projectreturn runErr}if exitCode != 0 {- return fmt.Errorf("pre-deploy script exited with status %d", exitCode)+ return errors.Errorf("pre-deploy script exited with status %d", exitCode)}return nil}@@ -217,11 +218,11 @@ func (s *LifecycleService) runScriptInContainerInternal() (stdoutContent string, stderrContent string, exitCode int64, err error) {dockerClient, dErr := s.dockerService.GetClient(ctx)if dErr != nil {- return "", "", 0, fmt.Errorf("failed to connect to Docker: %w", dErr)+ return "", "", 0, errors.WrapIf(dErr, "failed to connect to Docker")}if err := s.ensureRunnerImageInternal(ctx, dockerClient, runnerImage); err != nil {- return "", "", 0, fmt.Errorf("failed to ensure runner image %s: %w", runnerImage, err)+ return "", "", 0, errors.WrapIff(err, "failed to ensure runner image %s", runnerImage)}// Resolve the workspace mount. When Arcane runs inside a container whose@@ -289,7 +290,7 @@ func (s *LifecycleService) runScriptInContainerInternal(HostConfig: hostConfig,})if err != nil {- return "", "", 0, fmt.Errorf("create lifecycle container: %w", err)+ return "", "", 0, errors.WrapIf(err, "create lifecycle container")}containerID := resp.IDdefer removeLifecycleContainerInternal(ctx, dockerClient, containerID, apiTimeoutSec)@@ -297,7 +298,7 @@ func (s *LifecycleService) runScriptInContainerInternal(startCtx, startCancel := timeouts.WithTimeout(ctx, apiTimeoutSec, timeouts.DefaultDockerAPI)defer startCancel()if _, err := dockerClient.ContainerStart(startCtx, containerID, client.ContainerStartOptions{}); err != nil {- return "", "", 0, fmt.Errorf("start lifecycle container: %w", err)+ return "", "", 0, errors.WrapIf(err, "start lifecycle container")}logsCtx, logsCancel := context.WithCancel(ctx)@@ -308,7 +309,7 @@ func (s *LifecycleService) runScriptInContainerInternal(Follow: true,})if err != nil {- return "", "", 0, fmt.Errorf("stream lifecycle container logs: %w", err)+ return "", "", 0, errors.WrapIf(err, "stream lifecycle container logs")}stdoutBuf := buildapi.NewLogCapture(lifecycleMaxOutputBytes)@@ -330,17 +331,17 @@ func (s *LifecycleService) runScriptInContainerInternal(exitCode = result.StatusCodeif result.Error != nil && result.Error.Message != "" {drainLifecycleLogsInternal(ctx, logsCancel, logs, logDone)- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), exitCode, fmt.Errorf("lifecycle container reported error: %s", result.Error.Message)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), exitCode, errors.Errorf("lifecycle container reported error: %s", result.Error.Message)}case waitErr := <-waitResp.Error:drainLifecycleLogsInternal(ctx, logsCancel, logs, logDone)if errors.Is(waitErr, context.DeadlineExceeded) || errors.Is(waitCtx.Err(), context.DeadlineExceeded) {- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("pre-deploy script timed out after %s: %w", timeout, context.DeadlineExceeded)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, errors.WrapIff(context.DeadlineExceeded, "pre-deploy script timed out after %s", timeout)}if errors.Is(waitErr, context.Canceled) {- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("pre-deploy script cancelled: %w", waitErr)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, errors.WrapIf(waitErr, "pre-deploy script cancelled")}- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("lifecycle container wait failed: %w", waitErr)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, errors.WrapIf(waitErr, "lifecycle container wait failed")}drainLifecycleLogsInternal(ctx, logsCancel, logs, logDone)@@ -364,14 +365,14 @@ func (s *LifecycleService) ensureRunnerImageInternal(ctx context.Context, dockerpullReader, err := dockerClient.ImagePull(pullCtx, image, client.ImagePullOptions{})if err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return fmt.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", image)+ return errors.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", image)}- return fmt.Errorf("pull runner image %s: %w", image, err)+ return errors.WrapIff(err, "pull runner image %s", image)}defer func() { _ = pullReader.Close() }()if err := dockerutils.ConsumeJSONMessageStream(pullReader, nil); err != nil {- return fmt.Errorf("failed to complete runner image pull: %w", err)+ return errors.WrapIf(err, "failed to complete runner image pull")}return nil}@@ -483,30 +484,30 @@ func validateScriptPathInternal(projectPath, scriptPath string) error {// scriptPath is a POSIX repo path, not a host path; use path.IsAbs so the// check behaves the same on Windows-based contributor machines.if path.IsAbs(filepath.ToSlash(scriptPath)) {- return fmt.Errorf("script path %q must be relative to the project directory", scriptPath)+ return errors.Errorf("script path %q must be relative to the project directory", scriptPath)}absProject, err := filepath.Abs(projectPath)if err != nil {- return fmt.Errorf("resolve project path: %w", err)+ return errors.WrapIf(err, "resolve project path")}absScript, err := filepath.Abs(filepath.Join(absProject, scriptPath))if err != nil {- return fmt.Errorf("resolve script path: %w", err)+ return errors.WrapIf(err, "resolve script path")}if !projects.IsSafeSubdirectory(absProject, absScript) {- return fmt.Errorf("script path %q escapes project directory", scriptPath)+ return errors.Errorf("script path %q escapes project directory", scriptPath)}info, err := os.Lstat(absScript)if err != nil {- return fmt.Errorf("stat script %q: %w", scriptPath, err)+ return errors.WrapIff(err, "stat script %q", scriptPath)}if info.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("script path %q is a symlink; symlinks are not allowed", scriptPath)+ return errors.Errorf("script path %q is a symlink; symlinks are not allowed", scriptPath)}if info.IsDir() {- return fmt.Errorf("script path %q refers to a directory", scriptPath)+ return errors.Errorf("script path %q refers to a directory", scriptPath)}return nil}@@ -521,7 +522,7 @@ func parseLifecycleEnvTextInternal(raw *string) (map[string]string, error) {}env, err := parseKeyValueEnvInternal(*raw)if err != nil {- return nil, fmt.Errorf("invalid env entry: %w", err)+ return nil, errors.WrapIf(err, "invalid env entry")}return env, nil}@@ -549,7 +550,7 @@ func parseLifecycleExtraMountsTextInternal(raw *string) ([]lifecycleExtraMount,parts := strings.Split(line, ":")if len(parts) < 2 || len(parts) > 3 {- return nil, fmt.Errorf("line %d: expected src:tgt[:ro|:rw], got %q", lineNum, line)+ return nil, errors.Errorf("line %d: expected src:tgt[:ro|:rw], got %q", lineNum, line)}mount := lifecycleExtraMount{Source: parts[0], Target: parts[1]}@@ -560,7 +561,7 @@ func parseLifecycleExtraMountsTextInternal(raw *string) ([]lifecycleExtraMount,case "rw":mount.Readonly = falsedefault:- return nil, fmt.Errorf("line %d: invalid mode %q (expected \"ro\" or \"rw\")", lineNum, parts[2])+ return nil, errors.Errorf("line %d: invalid mode %q (expected \"ro\" or \"rw\")", lineNum, parts[2])}}@@ -568,16 +569,16 @@ func parseLifecycleExtraMountsTextInternal(raw *string) ([]lifecycleExtraMount,// host/container paths, so use path.IsAbs to avoid host-OS quirks// (filepath.IsAbs("/x") returns false on Windows).if !path.IsAbs(filepath.ToSlash(mount.Source)) {- return nil, fmt.Errorf("line %d: source %q must be an absolute path", lineNum, mount.Source)+ return nil, errors.Errorf("line %d: source %q must be an absolute path", lineNum, mount.Source)}if !path.IsAbs(filepath.ToSlash(mount.Target)) {- return nil, fmt.Errorf("line %d: target %q must be an absolute path", lineNum, mount.Target)+ return nil, errors.Errorf("line %d: target %q must be an absolute path", lineNum, mount.Target)}mounts = append(mounts, mount)}if err := scanner.Err(); err != nil {- return nil, fmt.Errorf("read extra mounts config: %w", err)+ return nil, errors.WrapIf(err, "read extra mounts config")}return mounts, nil}@@ -602,17 +603,17 @@ func parseKeyValueEnvInternal(stdout string) (map[string]string, error) {}idx := strings.IndexByte(line, '=')if idx <= 0 {- return nil, fmt.Errorf("line %d: expected KEY=VALUE, got %q", lineNum, line)+ return nil, errors.Errorf("line %d: expected KEY=VALUE, got %q", lineNum, line)}key := line[:idx]value := line[idx+1:]if !lifecycleEnvKeyRegex.MatchString(key) {- return nil, fmt.Errorf("line %d: invalid env key %q", lineNum, key)+ return nil, errors.Errorf("line %d: invalid env key %q", lineNum, key)}env[key] = value}if err := scanner.Err(); err != nil {- return nil, fmt.Errorf("read stdout: %w", err)+ return nil, errors.WrapIf(err, "read stdout")}return env, nil}diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.goindex af4453c13..fdb1651cd 100644--- a/backend/internal/services/network_service.go+++ b/backend/internal/services/network_service.go@@ -7,6 +7,7 @@ import ("sort""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -36,12 +37,12 @@ func NewNetworkService(db *database.DB, dockerService *DockerClientService, evenfunc (s *NetworkService) GetNetworkByID(ctx context.Context, id string) (*network.Inspect, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}networkInspect, err := libarcane.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})if err != nil {- return nil, fmt.Errorf("network not found: %w", err)+ return nil, errors.WrapIf(err, "network not found")}return new(networkInspect.Network), nil@@ -50,19 +51,19 @@ func (s *NetworkService) GetNetworkByID(ctx context.Context, id string) (*networfunc (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.Topology, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return nil, fmt.Errorf("failed to list containers: %w", err)+ return nil, errors.WrapIf(err, "failed to list containers")}containerInfoByID := buildTopologyContainerInfoInternal(containerList.Items)networkList, err := libarcane.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list Docker networks: %w", err)+ return nil, errors.WrapIf(err, "failed to list Docker networks")}topology := &networktypes.Topology{@@ -83,7 +84,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.g.Go(func() error {inspected, err := libarcane.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})if err != nil {- return fmt.Errorf("failed to inspect network %s: %w", rawNetwork.Name, err)+ return errors.WrapIff(err, "failed to inspect network %s", rawNetwork.Name)}inspectedNetworks[i] = struct {@@ -174,13 +175,13 @@ func (s *NetworkService) CreateNetwork(ctx context.Context, name string, optionsdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}response, err := dockerClient.NetworkCreate(ctx, name, options)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})- return nil, fmt.Errorf("failed to create network: %w", err)+ return nil, errors.WrapIf(err, "failed to create network")}metadata := models.JSON{@@ -209,7 +210,7 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user modedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", id, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete"})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}networkInfo, err := libarcane.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})@@ -222,7 +223,7 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user modeif _, err := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", err, models.JSON{"action": "delete"})- return fmt.Errorf("failed to remove network: %w", err)+ return errors.WrapIf(err, "failed to remove network")}metadata := models.JSON{@@ -239,14 +240,14 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user modefunc (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneReport, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}filterArgs := make(client.Filters)report, err := dockerClient.NetworkPrune(ctx, client.NetworkPruneOptions{Filters: filterArgs})if err != nil {- return nil, fmt.Errorf("failed to prune networks: %w", err)+ return nil, errors.WrapIf(err, "failed to prune networks")}pruneReport := report.Report@@ -264,12 +265,12 @@ func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneReporfunc (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagination.QueryParams) ([]networktypes.Summary, pagination.Response, networktypes.UsageCounts, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to connect to Docker")}containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list containers: %w", err)+ return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to list containers")}containers := containerList.Items@@ -277,7 +278,7 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params paginnetworkList, err := libarcane.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list Docker networks: %w", err)+ return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to list Docker networks")}rawNets := networkList.Itemsdiff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.goindex 69ea2c31e..bff469eb7 100644--- a/backend/internal/services/notification_service.go+++ b/backend/internal/services/notification_service.go@@ -4,7 +4,6 @@ import ("bytes""context"json "encoding/json/v2"- "errors""fmt""html""html/template"@@ -16,6 +15,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -39,8 +40,8 @@ var notificationCredentialFieldsByProviderInternal = map[models.NotificationProvmodels.NotificationProviderMatrix: {"password"},}-var ErrUnauthorizedNotificationDispatch = errors.New("unauthorized notification dispatch")-var ErrUnsupportedDispatchKind = errors.New("unsupported notification dispatch kind")+const ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")+const ErrUnsupportedDispatchKind = errors.Sentinel("unsupported notification dispatch kind")type NotificationService struct {db *database.DB@@ -97,7 +98,7 @@ func (s *NotificationService) resolveNotificationTargetInternal(ctx context.Cont}, nil}if trimmedEnvironmentID != "0" {- return NotificationTarget{}, fmt.Errorf("failed to resolve notification environment: %w", err)+ return NotificationTarget{}, errors.WrapIf(err, "failed to resolve notification environment")}if err != nil {slog.WarnContext(ctx, "Failed to resolve local environment, falling back to 'Local Docker'", "error", err)@@ -118,7 +119,7 @@ func (s *NotificationService) resolveNotificationTargetForAccessTokenInternal(ctenv, err := s.environmentSvc.ResolveEnvironmentByAccessToken(ctx, accessToken)if err != nil {if errors.Is(err, ErrEnvironmentAccessTokenRequired) || errors.Is(err, ErrInvalidEnvironmentAccessToken) {- return NotificationTarget{}, fmt.Errorf("%w", ErrUnauthorizedNotificationDispatch)+ return NotificationTarget{}, errors.WithStackIf(ErrUnauthorizedNotificationDispatch)}return NotificationTarget{}, err}@@ -144,20 +145,20 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.body, err := json.Marshal(payload)if err != nil {- return notificationdto.DispatchResponse{}, fmt.Errorf("failed to marshal notification dispatch payload: %w", err)+ return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to marshal notification dispatch payload")}dispatchURL := strings.TrimRight(s.config.GetManagerBaseURL(), "/") + "/api/notifications/dispatch"req, err := http.NewRequestWithContext(ctx, http.MethodPost, dispatchURL, bytes.NewReader(body))if err != nil {- return notificationdto.DispatchResponse{}, fmt.Errorf("failed to create notification dispatch request: %w", err)+ return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to create notification dispatch request")}req.Header.Set("Content-Type", "application/json")req.Header.Set("X-Api-Key", s.config.AgentToken)resp, err := s.httpClient.Do(req)if err != nil {- return notificationdto.DispatchResponse{}, fmt.Errorf("failed to dispatch notification to manager: %w", err)+ return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to dispatch notification to manager")}defer func() { _ = resp.Body.Close() }()@@ -166,13 +167,13 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.Data notificationdto.DispatchResponse `json:"data"`}if err := json.UnmarshalRead(resp.Body, &apiResponse); err != nil {- return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", err)+ return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to decode manager notification dispatch response")}return apiResponse.Data, nil}responseBody, _ := io.ReadAll(resp.Body)- return notificationdto.DispatchResponse{}, fmt.Errorf("manager notification dispatch failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))+ return notificationdto.DispatchResponse{}, errors.Errorf("manager notification dispatch failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))}func (s *NotificationService) DispatchNotification(ctx context.Context, accessToken string, payload notificationdto.DispatchRequest) (notificationdto.DispatchResponse, error) {@@ -234,14 +235,14 @@ func (s *NotificationService) DispatchNotification(ctx context.Context, accessTologManagerDispatchNotificationInternal(ctx, target, payload.Kind)return dispatchResponse, s.sendAutoHealNotificationForTargetInternal(ctx, target, payload.AutoHeal.ContainerName, payload.AutoHeal.ContainerID)default:- return notificationdto.DispatchResponse{}, fmt.Errorf("%w: %s", ErrUnsupportedDispatchKind, payload.Kind)+ return notificationdto.DispatchResponse{}, errors.WrapIff(ErrUnsupportedDispatchKind, "%s", payload.Kind)}}func (s *NotificationService) GetAllSettings(ctx context.Context) ([]models.NotificationSettings, error) {var settings []models.NotificationSettingsif err := s.db.WithContext(ctx).Find(&settings).Error; err != nil {- return nil, fmt.Errorf("failed to get notification settings: %w", err)+ return nil, errors.WrapIf(err, "failed to get notification settings")}return settings, nil}@@ -276,13 +277,13 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, providConfig: config,}if err := s.db.WithContext(ctx).Create(&setting).Error; err != nil {- return nil, fmt.Errorf("failed to create notification settings: %w", err)+ return nil, errors.WrapIf(err, "failed to create notification settings")}} else {setting.Enabled = enabledsetting.Config = configif err := s.db.WithContext(ctx).Save(&setting).Error; err != nil {- return nil, fmt.Errorf("failed to update notification settings: %w", err)+ return nil, errors.WrapIf(err, "failed to update notification settings")}}@@ -326,7 +327,7 @@ func encryptNotificationConfigCredentialsInternal(provider models.NotificationPrencrypted, err := encryptNotificationCredentialInternal(value)if err != nil {- return nil, fmt.Errorf("failed to encrypt notification credential %q: %w", field, err)+ return nil, errors.WrapIff(err, "failed to encrypt notification credential %q", field)}encryptedConfig[field] = encrypted}@@ -378,7 +379,7 @@ func cloneNotificationConfigInternal(config models.JSON) models.JSON {func (s *NotificationService) DeleteSettings(ctx context.Context, provider models.NotificationProvider) error {if err := s.db.WithContext(ctx).Where("provider = ?", provider).Delete(&models.NotificationSettings{}).Error; err != nil {- return fmt.Errorf("failed to delete notification settings: %w", err)+ return errors.WrapIf(err, "failed to delete notification settings")}return nil}@@ -453,7 +454,7 @@ func (s *NotificationService) notifyEnabledProvidersInternal() (int, error) {settings, err := s.GetAllSettings(ctx)if err != nil {- return 0, fmt.Errorf("failed to get notification settings: %w", err)+ return 0, errors.WrapIf(err, "failed to get notification settings")}delivered := 0@@ -481,7 +482,7 @@ func (s *NotificationService) notifyEnabledProvidersInternal(}if len(errs) > 0 {- return delivered, fmt.Errorf("notification errors: %s", strings.Join(errs, "; "))+ return delivered, errors.Errorf("notification errors: %s", strings.Join(errs, "; "))}return delivered, nil}@@ -497,7 +498,7 @@ func collectNotificationSendResultInternal(errors *[]string, provider models.Not}func unknownNotificationProviderErrorInternal(provider models.NotificationProvider) error {- return fmt.Errorf("unknown provider: %s", provider)+ return errors.Errorf("unknown provider: %s", provider)}const (@@ -541,7 +542,7 @@ func (s *NotificationService) imageUpdateNotificationContentInternal(environmentRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderEmailTemplate(environmentName, imageRef, updateInfo)if err != nil {- return "", "", fmt.Errorf("failed to render email template: %w", err)+ return "", "", errors.WrapIf(err, "failed to render email template")}subject := notifications.BuildEmailSubject(environmentName, "Container Update Available: "+notifications.SanitizeForEmail(imageRef))return subject, htmlBody, nil@@ -560,7 +561,7 @@ func (s *NotificationService) containerUpdateNotificationContentInternal(environRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderContainerUpdateEmailTemplate(environmentName, containerName, imageRef, oldDigest, newDigest)if err != nil {- return "", "", fmt.Errorf("failed to render email template: %w", err)+ return "", "", errors.WrapIf(err, "failed to render email template")}subject := notifications.BuildEmailSubject(environmentName, "Container Updated: "+notifications.SanitizeForEmail(containerName))return subject, htmlBody, nil@@ -589,7 +590,7 @@ func (s *NotificationService) vulnerabilityNotificationContentInternal(environmeRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderVulnerabilitySummaryEmailTemplate(environmentName, payload)if err != nil {- return "", "", fmt.Errorf("failed to render summary email template: %w", err)+ return "", "", errors.WrapIf(err, "failed to render summary email template")}subject := notifications.BuildEmailSubject(environmentName, "Daily Vulnerability Summary: "+notifications.SanitizeForEmail(payload.CVEID))return subject, htmlBody, nil@@ -608,7 +609,7 @@ func (s *NotificationService) batchImageUpdateNotificationContentInternal(enviroRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderBatchEmailTemplate(environmentName, updates)if err != nil {- return "", "", fmt.Errorf("failed to render email template: %w", err)+ return "", "", errors.WrapIf(err, "failed to render email template")}updateCount := len(updates)plural := ""@@ -632,7 +633,7 @@ func (s *NotificationService) pruneReportNotificationContentInternal(environmentRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderPruneReportEmailTemplate(environmentName, result)if err != nil {- return "", "", fmt.Errorf("failed to render email template: %w", err)+ return "", "", errors.WrapIf(err, "failed to render email template")}subject := notifications.BuildEmailSubject(environmentName, fmt.Sprintf("System Prune Report: %s Reclaimed", notifications.FormatBytes(result.SpaceReclaimed)))return subject, htmlBody, nil@@ -1058,14 +1059,14 @@ func (s *NotificationService) testNotificationContentInternal(environmentName, tfunc (s *NotificationService) TestNotification(ctx context.Context, environmentID string, provider models.NotificationProvider, testType string) (string, error) {setting, err := s.GetSettingsByProvider(ctx, provider)if err != nil {- return "", fmt.Errorf("please save your %s settings before testing", provider)+ return "", errors.Errorf("please save your %s settings before testing", provider)}testType = strings.TrimSpace(testType)if testType == "" {testType = notificationTestTypeSimple}if _, ok := supportedNotificationTestTypes[testType]; !ok {- return "", fmt.Errorf("unsupported notification test type: %s", testType)+ return "", errors.Errorf("unsupported notification test type: %s", testType)}warning := s.testNotificationWarningInternal(setting, testType)@@ -1105,32 +1106,32 @@ func (s *NotificationService) renderEmailTemplate(environmentName, imageRef strihtmlContent, err := resources.FS.ReadFile("email-templates/image-update_html.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile("email-templates/image-update_text.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read text template")}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {- return "", "", fmt.Errorf("failed to parse text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse text template")}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute text template")}return htmlBuf.String(), textBuf.String(), nil@@ -1152,32 +1153,32 @@ func (s *NotificationService) renderContainerUpdateEmailTemplate(environmentNamehtmlContent, err := resources.FS.ReadFile("email-templates/container-update_html.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile("email-templates/container-update_text.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read text template")}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {- return "", "", fmt.Errorf("failed to parse text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse text template")}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute text template")}return htmlBuf.String(), textBuf.String(), nil@@ -1187,10 +1188,10 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, environmentNamevar emailConfig models.EmailConfigconfigBytes, err := json.Marshal(config)if err != nil {- return fmt.Errorf("failed to marshal email config: %w", err)+ return errors.WrapIf(err, "failed to marshal email config")}if err := json.Unmarshal(configBytes, &emailConfig); err != nil {- return fmt.Errorf("failed to unmarshal email config: %w", err)+ return errors.WrapIf(err, "failed to unmarshal email config")}if emailConfig.SMTPHost == "" || emailConfig.SMTPPort == 0 {@@ -1201,11 +1202,11 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, environmentName}if _, err := mail.ParseAddress(emailConfig.FromAddress); err != nil {- return fmt.Errorf("invalid from address: %w", err)+ return errors.WrapIf(err, "invalid from address")}for _, addr := range emailConfig.ToAddresses {if _, err := mail.ParseAddress(addr); err != nil {- return fmt.Errorf("invalid to address %s: %w", addr, err)+ return errors.WrapIff(err, "invalid to address %s", addr)}}@@ -1215,12 +1216,12 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, environmentNamehtmlBody, _, err := s.renderTestEmailTemplate(environmentName)if err != nil {- return fmt.Errorf("failed to render test email template: %w", err)+ return errors.WrapIf(err, "failed to render test email template")}subject := notifications.BuildEmailSubject(environmentName, "Test Email from Arcane")if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {- return fmt.Errorf("failed to send email: %w", err)+ return errors.WrapIf(err, "failed to send email")}return nil@@ -1237,32 +1238,32 @@ func (s *NotificationService) renderTestEmailTemplate(environmentName string) (shtmlContent, err := resources.FS.ReadFile("email-templates/test_html.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile("email-templates/test_text.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read text template")}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {- return "", "", fmt.Errorf("failed to parse text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse text template")}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute text template")}return htmlBuf.String(), textBuf.String(), nil@@ -1288,32 +1289,32 @@ func (s *NotificationService) renderBatchEmailTemplate(environmentName string, uhtmlContent, err := resources.FS.ReadFile("email-templates/batch-image-updates_html.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile("email-templates/batch-image-updates_text.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read text template")}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {- return "", "", fmt.Errorf("failed to parse text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse text template")}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute text template")}return htmlBuf.String(), textBuf.String(), nil@@ -1335,28 +1336,28 @@ func (s *NotificationService) renderVulnerabilitySummaryEmailTemplate(environmenhtmlContent, err := resources.FS.ReadFile("email-templates/vulnerability-summary_html.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile("email-templates/vulnerability-summary_text.tmpl")if err != nil {- return "", "", fmt.Errorf("failed to read text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read text template")}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {- return "", "", fmt.Errorf("failed to parse text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse text template")}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute text template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute text template")}return htmlBuf.String(), textBuf.String(), nil}@@ -1382,17 +1383,17 @@ func (s *NotificationService) renderPruneReportEmailTemplate(environmentName strfunc (s *NotificationService) renderTemplatesInternal(name string, data any) (string, string, error) {htmlContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_html.tmpl", name))if err != nil {- return "", "", fmt.Errorf("failed to read HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to read HTML template")}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", fmt.Errorf("failed to parse HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse HTML template")}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)+ return "", "", errors.WrapIf(err, "failed to execute HTML template")}textContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_text.tmpl", name))diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.goindex 69f86bd5e..3351f5967 100644--- a/backend/internal/services/oidc_service.go+++ b/backend/internal/services/oidc_service.go@@ -5,7 +5,6 @@ import ("crypto/tls""encoding/base64"json "encoding/json/v2"- "errors""fmt""log/slog""net/http"@@ -15,6 +14,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/coreos/go-oidc/v3/oidc""github.com/samber/hot""golang.org/x/net/http2"@@ -73,7 +74,7 @@ func NewOidcService(authService *AuthService, settingsService *SettingsService,func (s *OidcService) getEffectiveConfigInternal(ctx context.Context) (*models.OidcConfig, error) {config, err := s.authService.GetOidcConfig(ctx)if err != nil {- return nil, fmt.Errorf("failed to get OIDC config: %w", err)+ return nil, errors.WrapIf(err, "failed to get OIDC config")}if config.IssuerURL == "" {return nil, errors.New("issuer URL must be configured")@@ -213,7 +214,7 @@ func (s *OidcService) ValidateMobileRedirectURI(ctx context.Context, uri string)if slices.Contains(s.GetMobileRedirectAllowlist(ctx), uri) {return nil}- return fmt.Errorf("mobile redirect URI %q is not in the configured allowlist", uri)+ return errors.Errorf("mobile redirect URI %q is not in the configured allowlist", uri)}func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, origin string, mobileRedirectURI string) (string, string, error) {@@ -229,7 +230,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, orprovider, err = s.getOrDiscoverProviderInternal(ctx, config)if err != nil {slog.Error("GenerateAuthURL: provider discovery failed", "issuer", config.IssuerURL, "error", err)- return "", "", fmt.Errorf("failed to discover provider: %w", err)+ return "", "", errors.WrapIf(err, "failed to discover provider")}}@@ -259,7 +260,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, orstateJSON, err := json.Marshal(stateData)if err != nil {slog.Error("GenerateAuthURL: failed to marshal state", "error", err)- return "", "", fmt.Errorf("failed to encode state: %w", err)+ return "", "", errors.WrapIf(err, "failed to encode state")}encodedState := base64.URLEncoding.EncodeToString(stateJSON)@@ -289,7 +290,7 @@ func (s *OidcService) getOrDiscoverProviderInternal(ctx context.Context, cfg *mocancel()if discoverErr != nil {slog.ErrorContext(ctx, "getOrDiscoverProviderInternal: discovery failed", "issuer", providerKey.issuer, "skipTls", providerKey.skipTLS, "error", discoverErr)- return nil, fmt.Errorf("failed to discover provider at %s: %w", providerKey.issuer, discoverErr)+ return nil, errors.WrapIff(discoverErr, "failed to discover provider at %s", providerKey.issuer)}providers[providerKey] = discoveredslog.DebugContext(ctx, "getOrDiscoverProviderInternal: provider cached", "issuer", providerKey.issuer, "effectiveIssuer", discoveredIssuer, "skipTls", providerKey.skipTLS)@@ -336,7 +337,7 @@ func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *models.Oidtoken, err := oauth2Config.Exchange(providerCtx, code, oauth2.VerifierOption(verifier))if err != nil {slog.Error("exchangeTokenInternal: token exchange failed", "token_endpoint", oauth2Config.Endpoint.TokenURL, "error", err)- return nil, fmt.Errorf("failed to exchange authorization code: %w", err)+ return nil, errors.WrapIf(err, "failed to exchange authorization code")}slog.Debug("exchangeTokenInternal: token exchange successful", "has_access_token", token.AccessToken != "", "has_refresh_token", token.RefreshToken != "")@@ -364,14 +365,14 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *models.OidcCif claims != nil {return claims, nil}- return nil, fmt.Errorf("failed to fetch userinfo: %w", err)+ return nil, errors.WrapIf(err, "failed to fetch userinfo")}if err := userInfo.Claims(&userInfoClaims); err != nil {slog.Warn("fetchClaimsInternal: failed to decode userinfo claims", "error", err)if claims != nil {return claims, nil}- return nil, fmt.Errorf("failed to decode userinfo claims: %w", err)+ return nil, errors.WrapIf(err, "failed to decode userinfo claims")}slog.Debug("fetchClaimsInternal: fetched userinfo claims successfully")case cfg.UserinfoEndpoint != "":@@ -381,7 +382,7 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *models.OidcCif claims != nil {return claims, nil}- return nil, fmt.Errorf("failed to fetch userinfo: %w", err)+ return nil, errors.WrapIf(err, "failed to fetch userinfo")}userInfoClaims = manualClaimsslog.Debug("fetchClaimsInternal: fetched userinfo claims successfully")@@ -431,7 +432,7 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *modedefer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, fmt.Errorf("userinfo endpoint returned status %d", resp.StatusCode)+ return nil, errors.Errorf("userinfo endpoint returned status %d", resp.StatusCode)}var claims map[string]any@@ -481,7 +482,7 @@ func (s *OidcService) validateStateInternal(state, storedState string) (*OidcStastateData, err := s.decodeStateInternal(storedState)if err != nil {slog.Error("HandleCallback: failed to decode stored state", "error", err)- return nil, fmt.Errorf("invalid state parameter: %w", err)+ return nil, errors.WrapIf(err, "invalid state parameter")}if state != stateData.State {@@ -532,7 +533,7 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.idToken, err := verifier.Verify(providerCtx, rawIDToken)if err != nil {slog.Error("HandleCallback: ID token verification failed", "error", err)- return nil, "", fmt.Errorf("failed to verify ID token: %w", err)+ return nil, "", errors.WrapIf(err, "failed to verify ID token")}if nonce != "" {@@ -541,7 +542,7 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.}if err := idToken.Claims(&claims); err != nil {slog.Error("HandleCallback: failed to extract nonce from ID token", "error", err)- return nil, "", fmt.Errorf("failed to verify nonce: %w", err)+ return nil, "", errors.WrapIf(err, "failed to verify nonce")}if claims.Nonce != nonce {slog.Error("HandleCallback: nonce mismatch", "expected", nonce, "got", claims.Nonce)@@ -557,7 +558,7 @@ func (s *OidcService) buildUserInfoInternal(ctx context.Context, provider *oidc.claims, err := s.fetchClaimsInternal(ctx, cfg, provider, token, idToken)if err != nil {slog.Error("HandleCallback: failed to fetch claims", "error", err)- return nil, nil, fmt.Errorf("failed to fetch user claims: %w", err)+ return nil, nil, errors.WrapIf(err, "failed to fetch user claims")}subject := jwtclaims.GetStringClaim(claims, "sub")@@ -693,14 +694,14 @@ func (s *OidcService) getDeviceAuthorizationEndpointInternal(ctx context.Contextprovider, err := s.getOrDiscoverProviderInternal(ctx, cfg)if err != nil {- return "", fmt.Errorf("failed to discover provider: %w", err)+ return "", errors.WrapIf(err, "failed to discover provider")}var claims struct {DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`}if err := provider.Claims(&claims); err != nil {- return "", fmt.Errorf("failed to get device authorization endpoint from provider: %w", err)+ return "", errors.WrapIf(err, "failed to get device authorization endpoint from provider")}if claims.DeviceAuthorizationEndpoint == "" {@@ -725,7 +726,7 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoinresp, err := client.Do(req)if err != nil {slog.Error("makeDeviceAuthRequestInternal: request failed", "error", err)- return nil, fmt.Errorf("device authorization request failed: %w", err)+ return nil, errors.WrapIf(err, "device authorization request failed")}defer func() { _ = resp.Body.Close() }()@@ -733,15 +734,15 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoinvar errorResp map[string]anyif err := json.UnmarshalRead(resp.Body, &errorResp); err == nil {if errMsg, ok := errorResp["error"].(string); ok {- return nil, fmt.Errorf("device authorization failed: %s", errMsg)+ return nil, errors.Errorf("device authorization failed: %s", errMsg)}}- return nil, fmt.Errorf("device authorization endpoint returned status %d", resp.StatusCode)+ return nil, errors.Errorf("device authorization endpoint returned status %d", resp.StatusCode)}var respData map[string]anyif err := json.UnmarshalRead(resp.Body, &respData); err != nil {- return nil, fmt.Errorf("failed to decode device authorization response: %w", err)+ return nil, errors.WrapIf(err, "failed to decode device authorization response")}return respData, nil@@ -834,13 +835,13 @@ func (s *OidcService) makeTokenRequestInternal(ctx context.Context, endpoint strresp, err := client.Do(req)if err != nil {slog.Error("makeTokenRequestInternal: request failed", "error", err)- return nil, fmt.Errorf("token request failed: %w", err)+ return nil, errors.WrapIf(err, "token request failed")}defer func() { _ = resp.Body.Close() }()var tokenResp map[string]anyif err := json.UnmarshalRead(resp.Body, &tokenResp); err != nil {- return nil, fmt.Errorf("failed to decode token response: %w", err)+ return nil, errors.WrapIf(err, "failed to decode token response")}if resp.StatusCode < 200 || resp.StatusCode >= 300 {@@ -855,10 +856,10 @@ func (s *OidcService) makeTokenRequestInternal(ctx context.Context, endpoint strcase "access_denied":return nil, errors.New("access_denied")default:- return nil, fmt.Errorf("token exchange failed: %s", errMsg)+ return nil, errors.Errorf("token exchange failed: %s", errMsg)}}- return nil, fmt.Errorf("token endpoint returned status %d", resp.StatusCode)+ return nil, errors.Errorf("token endpoint returned status %d", resp.StatusCode)}return tokenResp, nildiff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.goindex 7265b1957..6e9bd9a0e 100644--- a/backend/internal/services/playwright_service.go+++ b/backend/internal/services/playwright_service.go@@ -8,6 +8,7 @@ import ("log/slog""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -36,7 +37,7 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (// Get the arcane user to associate the API keys withuser, err := ps.userService.GetUserByUsername(ctx, "arcane")if err != nil {- return nil, fmt.Errorf("failed to get arcane user: %w", err)+ return nil, errors.WrapIf(err, "failed to get arcane user")}// Grant every recognized permission globally so the test key behaves like@@ -59,7 +60,7 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), req)if err != nil {- return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, err)+ return nil, errors.WrapIff(err, "failed to create test API key %d", i+1)}createdKeys = append(createdKeys, apiKey)@@ -85,7 +86,7 @@ func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {apiKeys, _, err := ps.apiKeyService.ListApiKeys(ctx, params)if err != nil {- return fmt.Errorf("failed to list API keys: %w", err)+ return errors.WrapIf(err, "failed to list API keys")}for _, apiKey := range apiKeys {@@ -100,10 +101,10 @@ func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {func (ps *PlaywrightService) CreateTestFederatedCredential(ctx context.Context, issuerURL string, audiences []string, subject string, roleID string, tokenTTLSeconds int) (string, error) {if ps.federatedCredentialService == nil || ps.federatedCredentialService.db == nil {- return "", fmt.Errorf("federated credential service is not available")+ return "", errors.Errorf("federated credential service is not available")}if strings.TrimSpace(issuerURL) == "" || strings.TrimSpace(subject) == "" || strings.TrimSpace(roleID) == "" || len(audiences) == 0 {- return "", fmt.Errorf("issuerUrl, subject, roleId, and audiences are required")+ return "", errors.Errorf("issuerUrl, subject, roleId, and audiences are required")}if tokenTTLSeconds <= 0 {tokenTTLSeconds = 600@@ -116,7 +117,7 @@ func (ps *PlaywrightService) CreateTestFederatedCredential(ctx context.Context,IsServiceAccount: true,}if err := tx.Create(&serviceUser).Error; err != nil {- return fmt.Errorf("failed to create federated e2e user: %w", err)+ return errors.WrapIf(err, "failed to create federated e2e user")}credential := models.FederatedCredential{@@ -132,7 +133,7 @@ func (ps *PlaywrightService) CreateTestFederatedCredential(ctx context.Context,TokenTTLSeconds: tokenTTLSeconds,}if err := tx.Create(&credential).Error; err != nil {- return fmt.Errorf("failed to create federated e2e credential: %w", err)+ return errors.WrapIf(err, "failed to create federated e2e credential")}assignment := models.UserRoleAssignment{@@ -141,7 +142,7 @@ func (ps *PlaywrightService) CreateTestFederatedCredential(ctx context.Context,Source: models.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return fmt.Errorf("failed to create federated e2e role assignment: %w", err)+ return errors.WrapIf(err, "failed to create federated e2e role assignment")}credentialID = credential.IDdiff --git a/backend/internal/services/port_service.go b/backend/internal/services/port_service.goindex c611077ba..821dfe62f 100644--- a/backend/internal/services/port_service.go+++ b/backend/internal/services/port_service.go@@ -6,6 +6,7 @@ import ("strconv""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"containertypes "github.com/getarcaneapp/arcane/types/v2/container"porttypes "github.com/getarcaneapp/arcane/types/v2/port"@@ -23,12 +24,12 @@ func NewPortService(dockerService *DockerClientService) *PortService {func (s *PortService) ListPortsPaginated(ctx context.Context, params pagination.QueryParams) ([]porttypes.PortMapping, pagination.Response, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list containers: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list containers")}items := make([]porttypes.PortMapping, 0)diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.goindex 10a76480f..97022b38a 100644--- a/backend/internal/services/project_service.go+++ b/backend/internal/services/project_service.go@@ -4,7 +4,7 @@ import ("bufio""context"json "encoding/json/v2"- "errors"+ stderrors "errors""fmt""io""log/slog"@@ -17,16 +17,13 @@ import ("sync""time"+ "emperror.dev/emperror"+ "emperror.dev/errors"+"github.com/compose-spec/compose-go/v2/dotenv""github.com/compose-spec/compose-go/v2/loader"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/compose/v5/pkg/api"- "github.com/moby/moby/api/types/container"- dockerregistry "github.com/moby/moby/api/types/registry"- "github.com/moby/moby/client"- "github.com/samber/mo"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -43,10 +40,15 @@ import ("github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/project"+ "github.com/moby/moby/api/types/container"+ dockerregistry "github.com/moby/moby/api/types/registry"+ "github.com/moby/moby/client""github.com/samber/hot"+ "github.com/samber/mo"buildtypes "go.getarcane.app/builds/types""go.getarcane.app/sys/cgroup"libupdater "go.getarcane.app/updater/pkg/labels"+ "gorm.io/gorm")type ProjectService struct {@@ -114,7 +116,7 @@ func (s *ProjectService) resolveRegistryCredentialsInternal(ctx context.Context)credentials, err := s.registryCredentialsProvider(ctx)if err != nil {- return nil, fmt.Errorf("get enabled registry credentials: %w", err)+ return nil, errors.WrapIf(err, "get enabled registry credentials")}return credentials, nil@@ -362,9 +364,9 @@ func (s *ProjectService) lookupProjectByCachedComposeNameInternal(ctx context.Coreturn nil, false, nil}if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {- return nil, false, fmt.Errorf("request canceled or timed out: %w", err)+ return nil, false, errors.WrapIf(err, "request canceled or timed out")}- return nil, false, fmt.Errorf("failed to get project by cached compose name: %w", err)+ return nil, false, errors.WrapIf(err, "failed to get project by cached compose name")}if projects.NormalizeProjectName(project.Name) != normalizedName {s.invalidateCachedComposeProjectIDInternal(normalizedName)@@ -407,7 +409,7 @@ func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id striif errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("project not found")}- return nil, fmt.Errorf("failed to get project: %w", err)+ return nil, errors.WrapIf(err, "failed to get project")}return &project, nil}@@ -425,7 +427,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strinreturn &proj, nil}if !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, fmt.Errorf("failed to get project by name: %w", err)+ return nil, errors.WrapIf(err, "failed to get project by name")}if cachedProject, found, cacheErr := s.lookupProjectByCachedComposeNameInternal(ctx, normalized); cacheErr != nil {@@ -435,7 +437,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strin}if err := s.rebuildComposeNameCacheInternal(ctx); err != nil {- return nil, fmt.Errorf("failed to list projects by compose name: %w", err)+ return nil, errors.WrapIf(err, "failed to list projects by compose name")}if cachedProject, found, cacheErr := s.lookupProjectByCachedComposeNameInternal(ctx, normalized); cacheErr != nil {@@ -444,7 +446,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strinreturn cachedProject, nil}- return nil, fmt.Errorf("project not found: %s", name)+ return nil, errors.Errorf("project not found: %s", name)}func (s *ProjectService) resolveProjectComposeFileInternal(ctx context.Context, proj *models.Project) (string, error) {@@ -466,17 +468,17 @@ func (s *ProjectService) resolveProjectComposeFileInternal(ctx context.Context,return candidate, nil}} else if !os.IsNotExist(statErr) {- return "", fmt.Errorf("failed to inspect GitOps compose file %s: %w", candidate, statErr)+ return "", errors.WrapIff(statErr, "failed to inspect GitOps compose file %s", candidate)}}} else if !errors.Is(err, gorm.ErrRecordNotFound) {- return "", fmt.Errorf("failed to resolve GitOps compose path for project %s: %w", proj.ID, err)+ return "", errors.WrapIff(err, "failed to resolve GitOps compose path for project %s", proj.ID)}}composeFile, err := projects.DetectComposeFile(proj.Path)if err != nil {- return "", &common.ProjectComposeFileNotFoundError{Err: err}+ return "", common.Classify(common.ErrProjectComposeFileNotFound, errors.WrapIf(err, "Project compose file not found"))}return composeFile, nil@@ -532,7 +534,7 @@ func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, prif info, statErr := os.Stat(composePath); statErr == nil {entry.composeMtime = info.ModTime()} else {- return nil, fmt.Errorf("stat compose file: %w", statErr)+ return nil, errors.WrapIf(statErr, "stat compose file")}if composeProject != nil {for _, composeFile := range composeProject.ComposeFiles {@@ -541,7 +543,7 @@ func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, pr}info, statErr := os.Stat(composeFile)if statErr != nil {- return nil, fmt.Errorf("stat compose include %s: %w", composeFile, statErr)+ return nil, errors.WrapIff(statErr, "stat compose include %s", composeFile)}entry.includeMtimes[composeFile] = info.ModTime()}@@ -650,7 +652,7 @@ func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context) (int, errif err := s.db.WithContext(ctx).Where("build_image_refs_json IS NULL").Find(&projectsList).Error; err != nil {- return 0, fmt.Errorf("list projects for image ref backfill: %w", err)+ return 0, errors.WrapIf(err, "list projects for image ref backfill")}for i := range projectsList {if err := ctx.Err(); err != nil {@@ -664,7 +666,7 @@ func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context) (int, errfunc (s *ProjectService) resolveProjectsByChangedPathsInternal(ctx context.Context, paths []string) ([]models.Project, error) {var projectsList []models.Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {- return nil, fmt.Errorf("list projects for changed paths: %w", err)+ return nil, errors.WrapIf(err, "list projects for changed paths")}seen := make(map[string]struct{})@@ -771,9 +773,9 @@ func (s *ProjectService) pullAndReconcileImageInternal(if err := s.imageService.PullImage(pullCtx, imageRef, progressWriter, user, credentials); err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageRef)+ return errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageRef)}- return fmt.Errorf("failed to pull image %s: %w", imageRef, err)+ return errors.WrapIff(err, "failed to pull image %s", imageRef)}s.reconcilePulledImageRefsInternal(ctx, []string{imageRef})@@ -810,7 +812,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID st// 1. Load projectcompProj, _, err := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if err != nil {- return fmt.Errorf("failed to load compose project: %w", err)+ return errors.WrapIf(err, "failed to load compose project")}// 2. Set status to deploying/restarting@@ -823,7 +825,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID stif statusErr := s.updateProjectStatusInternal(ctx, projectID, previousStatus); statusErr != nil {slog.ErrorContext(ctx, "UpdateProjectServices: failed to restore project status after credential lookup failure", "projectID", projectID, "error", statusErr)}- return fmt.Errorf("resolve registry credentials: %w", err)+ return errors.WrapIf(err, "resolve registry credentials")}// 3. Pull images for specific services@@ -832,7 +834,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID stif statusErr := s.updateProjectStatusInternal(ctx, projectID, previousStatus); statusErr != nil {slog.ErrorContext(ctx, "UpdateProjectServices: failed to restore project status after compose pull failure", "projectID", projectID, "error", statusErr)}- return fmt.Errorf("pull updated service images: %w", err)+ return errors.WrapIf(err, "pull updated service images")}// 4. Stop specific services@@ -845,7 +847,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID stwriteProjectProgressInternal(ctx, "Starting selected services", 70, "up")if err := composeUpProjectServicesInternal(ctx, compProj, servicesToUpdate, false, true, s.composeRegistryAuthConfigsInternal(ctx)); err != nil {s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID)- return fmt.Errorf("failed to up services: %w", err)+ return errors.WrapIf(err, "failed to up services")}// 6. Finalize status@@ -892,7 +894,7 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contex"running_count": runningCount,"updated_at": time.Now(),}).Error; err != nil {- return fmt.Errorf("failed to update project status and counts: %w", err)+ return errors.WrapIf(err, "failed to update project status and counts")}return nil@@ -906,7 +908,7 @@ func (s *ProjectService) updateProjectStatusInternal(ctx context.Context, id str})if res.Error != nil {- return fmt.Errorf("failed to update project status: %w", res.Error)+ return errors.WrapIf(res.Error, "failed to update project status")}return nil@@ -920,7 +922,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strincomposeProject, composeFileFullPath, derr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if derr != nil {- return []ProjectServiceInfo{}, fmt.Errorf("failed to load compose project in %s: %w", projectFromDb.Path, derr)+ return []ProjectServiceInfo{}, errors.WrapIff(derr, "failed to load compose project in %s", projectFromDb.Path)}projectsDirectory, projectsDirErr := s.getProjectsDirectoryInternal(ctx)@@ -937,7 +939,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strincontainers, err := projects.ComposePs(ctx, composeProject, nil, true)if err != nil {slog.Error("compose ps error", "projectName", composeProject.Name, "error", err)- return nil, fmt.Errorf("failed to get compose services status: %w", err)+ return nil, errors.WrapIf(err, "failed to get compose services status")}currentContainerID, currentContainerErr := cgroup.CurrentContainerID()@@ -1032,7 +1034,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringvar resp project.Detailsif err := mapper.MapStruct(proj, &resp); err != nil {- return project.Details{}, fmt.Errorf("failed to map project: %w", err)+ return project.Details{}, errors.WrapIf(err, "failed to map project")}resp.CreatedAt = proj.CreatedAt.Format(time.RFC3339)@@ -1063,7 +1065,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringif opts.IncludeEnvState {envState, err := projects.ReadProjectEnvState(proj.Path)if err != nil {- return project.Details{}, fmt.Errorf("failed to read project env state: %w", err)+ return project.Details{}, errors.WrapIf(err, "failed to read project env state")}effectiveEnvContent, err := s.resolveStoredEffectiveEnvContentInternal(envState)if err != nil {@@ -1145,11 +1147,11 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, rreturn project.IncludeFile{}, err}if strings.TrimSpace(relativePath) == "" {- return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("relative path is required")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: relative path is required"))}normalizedRelativePath, err := projects.NormalizeProjectRelativePath(relativePath)if err != nil {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: err}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))}composeFile, detectErr := s.resolveProjectComposeFileInternal(ctx, proj)@@ -1166,7 +1168,7 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, rcontinue}if !projects.IsSafeSubdirectory(proj.Path, inc.Path) {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("file path is outside project directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: include resolves outside project directory"))}return readProjectIncludeFileContentInternal(proj.Path, inc)}@@ -1175,32 +1177,32 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, rabsFilePath, err := projects.ValidateIncludePathForWrite(proj.Path, normalizedRelativePath)if err != nil {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("file path is outside project directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))}info, err := os.Lstat(absFilePath)if err != nil {if os.IsNotExist(err) {- return project.IncludeFile{}, &common.ProjectFileNotFoundError{}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))}- return project.IncludeFile{}, fmt.Errorf("failed to stat file: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to stat file")}if info.IsDir() {- return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("path refers to a directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: path is a directory"))}if info.Mode()&os.ModeSymlink != 0 {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("symlink files are not supported")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: symlinks are not allowed"))}content, err := os.ReadFile(absFilePath)if err != nil {if os.IsNotExist(err) {- return project.IncludeFile{}, &common.ProjectFileNotFoundError{}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))}- return project.IncludeFile{}, fmt.Errorf("failed to read file: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to read file")}if projects.IsBinaryProjectFileContent(content) {- return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("binary files are not supported")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: binary files are not supported"))}return project.IncludeFile{@@ -1213,12 +1215,12 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, rfunc readProjectIncludeFileContentInternal(projectPath string, inc projects.IncludeFile) (project.IncludeFile, error) {validatedPath, err := projects.ValidateIncludePathForWrite(projectPath, inc.Path)if err != nil {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("file path is outside project directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))}resolvedProjectPath, err := filepath.EvalSymlinks(projectPath)if err != nil {- return project.IncludeFile{}, fmt.Errorf("failed to resolve project path: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to resolve project path")}resolvedPath, err := filepath.EvalSymlinks(validatedPath)if err != nil {@@ -1229,32 +1231,32 @@ func readProjectIncludeFileContentInternal(projectPath string, inc projects.InclContent: "# This file will be created when you save changes\nservices:\n",}, nil}- return project.IncludeFile{}, fmt.Errorf("failed to resolve include file: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to resolve include file")}if !projects.IsSafeSubdirectory(resolvedProjectPath, resolvedPath) {- return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("file path is outside project directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: include resolves outside project directory"))}info, err := os.Stat(resolvedPath)if err != nil {if os.IsNotExist(err) {- return project.IncludeFile{}, &common.ProjectFileNotFoundError{}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))}- return project.IncludeFile{}, fmt.Errorf("failed to stat include file: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to stat include file")}if info.IsDir() {- return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("path refers to a directory")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: path is a directory"))}content, err := os.ReadFile(resolvedPath)if err != nil {if os.IsNotExist(err) {- return project.IncludeFile{}, &common.ProjectFileNotFoundError{}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))}- return project.IncludeFile{}, fmt.Errorf("failed to read include file: %w", err)+ return project.IncludeFile{}, errors.WrapIf(err, "failed to read include file")}if projects.IsBinaryProjectFileContent(content) {- return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("binary files are not supported")}+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: binary files are not supported"))}return project.IncludeFile{@@ -1390,7 +1392,7 @@ func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(func (s *ProjectService) getProjectImageRefsFromComposeInternal(ctx context.Context, proj models.Project, cfg *models.Settings) ([]string, []string, error) {composeProject, err := s.getCachedComposeProjectInternal(ctx, &proj, cfg)if err != nil {- return nil, nil, fmt.Errorf("load compose project: %w", err)+ return nil, nil, errors.WrapIf(err, "load compose project")}return projects.ImageRefsFromComposeServices(composeProject.Services), projects.BuildImageRefsFromComposeProject(composeProject), nil@@ -1545,7 +1547,7 @@ func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {if os.IsNotExist(discoveryErr) {return nil}- return &common.ProjectDiscoveryError{Dir: projectsDir, Err: discoveryErr}+ return errors.WrapIff(discoveryErr, "Failed to discover projects in %q", projectsDir)}renameSyncState := s.activeProjectRenameSyncStateInternal(ctx)@@ -1598,13 +1600,13 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaslog.WarnContext(ctx, "failed to read compose service count during project discovery", "project", dirName, "path", dirPath, "error", serviceCountErr)}if cerr := s.db.WithContext(ctx).Create(proj).Error; cerr != nil {- return fmt.Errorf("create project for %q failed: %w", dirPath, cerr)+ return errors.WrapIff(cerr, "create project for %q failed", dirPath)}s.warnDuplicateComposeNameForPathInternal(ctx, composeMetadata.resolvedProjectName, dirPath, proj.ID)return nil}if err != nil {- return fmt.Errorf("query existing project for %q failed: %w", dirPath, err)+ return errors.WrapIff(err, "query existing project for %q failed", dirPath)}updates := map[string]any{}@@ -1640,7 +1642,7 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaModel(&models.Project{}).Where("id = ?", existing.ID).Updates(updates).Error; uerr != nil {- return fmt.Errorf("update project %s failed: %w", existing.ID, uerr)+ return errors.WrapIff(uerr, "update project %s failed", existing.ID)}if serviceCountErr == nil {s.warnDuplicateComposeNameForPathInternal(ctx, composeMetadata.resolvedProjectName, dirPath, existing.ID)@@ -1727,7 +1729,7 @@ func (s activeProjectRenameSyncStateInternal) markProtectedPathsSeenInternal(seefunc (s *ProjectService) cleanupDBProjectsInternal(ctx context.Context, seen map[string]struct{}, followProjectSymlinks bool, projectsDir string, maxDepth int) error {var all []models.Projectif err := s.db.WithContext(ctx).Find(&all).Error; err != nil {- return fmt.Errorf("list projects for cleanup failed: %w", err)+ return errors.WrapIf(err, "list projects for cleanup failed")}// Decide deletions without performing them. Collecting decisions up front lets@@ -1875,7 +1877,7 @@ func (s *ProjectService) evaluateProjectComposeFileInternal(ctx context.Context,// means the project still has compose content on disk and may be deployable.// Deleting it would silently destroy a live project whose files are intact, so// keep the record and warn instead.- if _, ok := errors.AsType[*common.ComposeFileNotFoundError](err); !ok {+ if !errors.Is(err, common.ErrComposeFileNotFound) {slog.WarnContext(ctx, "project directory present but compose file unresolved during cleanup; keeping DB record","projectID", p.ID, "path", p.Path, "error", err)return mo.None[projectCleanupDecision]()@@ -1905,7 +1907,7 @@ func (s *ProjectService) deleteProjectDuringCleanupInternal(ctx context.Context,func (s *ProjectService) ListAllProjects(ctx context.Context) ([]models.Project, error) {var items []models.Projectif err := s.db.WithContext(ctx).Find(&items).Error; err != nil {- return nil, fmt.Errorf("list projects: %w", err)+ return nil, errors.WrapIf(err, "list projects")}return items, nil}@@ -1938,7 +1940,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {followProjectSymlinks := s.settingsService.GetBoolSetting(ctx, "followProjectSymlinks", false)projectsDir, err := s.getProjectsDirectoryInternal(ctx)if err != nil {- return 0, fmt.Errorf("could not determine projects directory: %w", err)+ return 0, errors.WrapIf(err, "could not determine projects directory")}info, statErr := os.Stat(projectsDir)@@ -1947,7 +1949,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {return 0, nil}if statErr != nil {- return 0, fmt.Errorf("unable to access projects directory %s: %w", projectsDir, statErr)+ return 0, errors.WrapIff(statErr, "unable to access projects directory %s", projectsDir)}if !info.IsDir() {return 0, nil@@ -1955,7 +1957,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {discoveredProjects, discoveryErr := projects.DiscoverProjectDirectories(projectsDir, followProjectSymlinks, s.config.ProjectScanMaxDepth)if discoveryErr != nil {- return 0, fmt.Errorf("failed to discover project directories in %s: %w", projectsDir, discoveryErr)+ return 0, errors.WrapIff(discoveryErr, "failed to discover project directories in %s", projectsDir)}return len(discoveredProjects), nil@@ -1977,7 +1979,7 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCounvar projectsList []models.Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {- return folderCount, 0, 0, 0, 0, fmt.Errorf("failed to list projects: %w", err)+ return folderCount, 0, 0, 0, 0, errors.WrapIf(err, "failed to list projects")}totalProjects = len(projectsList)@@ -2037,7 +2039,7 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCounfunc ensureProjectMutableInternal(proj *models.Project) error {if proj != nil && proj.IsArchived {- return &common.ProjectArchivedError{}+ return common.Classify(common.ErrProjectArchived, errors.New("project is archived and must be unarchived before this action"))}return nil}@@ -2068,7 +2070,7 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, ureturn nil}if isProjectArchiveBlockedInternal(proj) {- return &common.ProjectMustBeStoppedError{}+ return common.Classify(common.ErrProjectMustBeStopped, errors.New("project must be stopped before archiving"))}now := time.Now()@@ -2076,7 +2078,7 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, u"is_archived": true,"archived_at": now,}).Error; err != nil {- return fmt.Errorf("failed to archive project: %w", err)+ return errors.WrapIf(err, "failed to archive project")}metadata := models.JSON{"action": "archived", "projectID": projectID, "projectName": proj.Name}@@ -2098,7 +2100,7 @@ func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string,"is_archived": false,"archived_at": gorm.Expr("NULL"),}).Error; err != nil {- return fmt.Errorf("failed to unarchive project: %w", err)+ return errors.WrapIf(err, "failed to unarchive project")}metadata := models.JSON{"action": "unarchived", "projectID": projectID, "projectName": proj.Name}@@ -2117,7 +2119,7 @@ func resolveRemoveOrphansInternal(gitOpsManaged bool, options *project.DeployOptfunc (s *ProjectService) DeployProject(ctx context.Context, projectID string, user models.User, options *project.DeployOptions) error {projectFromDb, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {- return fmt.Errorf("failed to get project: %w", err)+ return errors.WrapIf(err, "failed to get project")}if err := ensureProjectMutableInternal(projectFromDb); err != nil {return err@@ -2137,7 +2139,7 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us}if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusDeploying); err != nil {- return fmt.Errorf("failed to update project status to deploying: %w", err)+ return errors.WrapIf(err, "failed to update project status to deploying")}// Run any configured pre-deploy lifecycle hook before loading the compose@@ -2147,26 +2149,26 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, usif s.lifecycleService != nil {if lerr := s.lifecycleService.RunPreDeploy(ctx, projectFromDb, user); lerr != nil {s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID)- return fmt.Errorf("pre-deploy lifecycle hook failed: %w", lerr)+ return errors.WrapIf(lerr, "pre-deploy lifecycle hook failed")}}project, _, derr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if derr != nil {s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID)- return fmt.Errorf("failed to load compose project in %s: %w", projectFromDb.Path, derr)+ return errors.WrapIff(derr, "failed to load compose project in %s", projectFromDb.Path)}credentials, cerr := s.resolveRegistryCredentialsInternal(ctx)if cerr != nil {s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID)- return fmt.Errorf("resolve registry credentials: %w", cerr)+ return errors.WrapIf(cerr, "resolve registry credentials")}progressWriter, _ := ctx.Value(projects.ProgressWriterKey{}).(io.Writer)if perr := s.prepareProjectImagesForDeploy(ctx, projectID, project, progressWriter, credentials, &user, resolvedPullPolicy); perr != nil {s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID)- return fmt.Errorf("failed to prepare project images for deploy: %w", perr)+ return errors.WrapIf(perr, "failed to prepare project images for deploy")}gitOpsManaged := projectFromDb.GitOpsManagedBy != nil && *projectFromDb.GitOpsManagedBy != ""@@ -2184,9 +2186,9 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us// Provide more helpful error messageserrMsg := err.Error()if strings.Contains(errMsg, "timeout") || strings.Contains(errMsg, "context deadline exceeded") {- return fmt.Errorf("deployment timed out - check if services with 'condition: service_healthy' have healthchecks defined: %w", err)+ return errors.WrapIf(err, "deployment timed out - check if services with 'condition: service_healthy' have healthchecks defined")}- return fmt.Errorf("failed to deploy project: %w", err)+ return errors.WrapIf(err, "failed to deploy project")}slog.Info("compose up completed successfully", "projectID", projectID, "projectName", project.Name)@@ -2209,17 +2211,17 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, userproj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if lerr != nil {_ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)- return fmt.Errorf("failed to load compose project: %w", lerr)+ return errors.WrapIf(lerr, "failed to load compose project")}if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusStopped); err != nil {- return fmt.Errorf("failed to update project status to stopping: %w", err)+ return errors.WrapIf(err, "failed to update project status to stopping")}writeProjectProgressInternal(ctx, "Stopping project services", 45, "down")if err := projects.ComposeDown(ctx, proj, false); err != nil {_ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)- return fmt.Errorf("failed to bring down project: %w", err)+ return errors.WrapIf(err, "failed to bring down project")}metadata := models.JSON{@@ -2256,7 +2258,7 @@ func (s *ProjectService) createProjectInternal(ctx context.Context, name, composprojectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return nil, fmt.Errorf("failed to get projects directory: %w", err)+ return nil, errors.WrapIf(err, "failed to get projects directory")}basePath := filepath.Join(projectsDirectory, sanitized)@@ -2267,7 +2269,7 @@ func (s *ProjectService) createProjectInternal(ctx context.Context, name, composprojectPath, folderName, err = projects.CreateExactDir(projectsDirectory, basePath, name, common.DirPerm)}if err != nil {- return nil, fmt.Errorf("failed to create project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create project directory")}proj := &models.Project{@@ -2293,18 +2295,18 @@ func (s *ProjectService) createProjectInternal(ctx context.Context, name, compos// creates (allowNameSuffix=true) stay strict.if err := s.validateComposeContentForUpdate(ctx, projectsDirectory, projectPath, name, composeContent, envContent, nil, "", !allowNameSuffix); err != nil {_ = os.RemoveAll(projectPath)- return nil, fmt.Errorf("invalid compose file: %w", err)+ return nil, errors.WrapIf(err, "invalid compose file")}if err := projects.SaveOrUpdateProjectFiles(projectsDirectory, projectPath, composeContent, envContent); err != nil {// Best-effort cleanup to restore pre-transaction behavior._ = os.RemoveAll(projectPath)- return nil, fmt.Errorf("failed to save project files: %w", err)+ return nil, errors.WrapIf(err, "failed to save project files")}if err := s.db.WithContext(ctx).Create(proj).Error; err != nil {_ = os.RemoveAll(projectPath)- return nil, fmt.Errorf("failed to create project: %w", err)+ return nil, errors.WrapIf(err, "failed to create project")}s.refreshComposeProjectNameInternal(ctx, proj)s.refreshProjectImageRefsInternal(ctx, proj)@@ -2353,13 +2355,13 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, rslog.DebugContext(ctx, "Removing project files", "path", proj.Path)if err := os.RemoveAll(proj.Path); err != nil {slog.ErrorContext(ctx, "Failed to remove project files", "path", proj.Path, "error", err)- return fmt.Errorf("failed to remove project files: %w", err)+ return errors.WrapIf(err, "failed to remove project files")}slog.InfoContext(ctx, "Project files removed successfully", "path", proj.Path)}if err := s.db.WithContext(ctx).Delete(proj).Error; err != nil {- return fmt.Errorf("failed to delete project from database: %w", err)+ return errors.WrapIf(err, "failed to delete project from database")}if !removeFiles {@@ -2391,7 +2393,7 @@ func (s *ProjectService) RedeployProject(ctx context.Context, projectID string,disabled := s.projectRedeployDisabledInternal(ctx, *proj)if disabled {- return &common.ArcaneSelfRedeployError{}+ return errors.New("arcane cannot redeploy itself; use the system upgrade flow (Settings -> Updates) instead")}progressWriter, _ := ctx.Value(projects.ProgressWriterKey{}).(io.Writer)@@ -2447,7 +2449,7 @@ func (s *ProjectService) PullProjectImages(ctx context.Context, projectID stringcompProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if lerr != nil {- return fmt.Errorf("failed to load compose project: %w", lerr)+ return errors.WrapIf(lerr, "failed to load compose project")}images := map[string]struct{}{}@@ -2478,7 +2480,7 @@ func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID strproject, _, derr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if derr != nil {- return fmt.Errorf("failed to load compose project in %s: %w", projectFromDb.Path, derr)+ return errors.WrapIff(derr, "failed to load compose project in %s", projectFromDb.Path)}return s.buildProjectServicesInternal(ctx, projectID, project, options, progressWriter, user)@@ -2497,7 +2499,7 @@ func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectcompProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if lerr != nil {- return fmt.Errorf("failed to load compose project: %w", lerr)+ return errors.WrapIf(lerr, "failed to load compose project")}pullPlan := projects.BuildImagePullPlan(compProj.Services)@@ -2519,7 +2521,7 @@ func (s *ProjectService) ensureImagesPresent(ctx context.Context, pullPlan map[scontinue}if !exists {- return fmt.Errorf("image %s is not available locally and pull_policy is 'never'", img)+ return errors.Errorf("image %s is not available locally and pull_policy is 'never'", img)}slog.DebugContext(ctx, "pull_policy is 'never'; using local image without pull", "image", img)continue@@ -2608,7 +2610,7 @@ func (s *ProjectService) ensureDeployServiceImageReady(if decision.RequireLocalOnly {if !exists {- return fmt.Errorf("image %s is not available locally and pull_policy is set to never", imageName)+ return errors.Errorf("image %s is not available locally and pull_policy is set to never", imageName)}return nil}@@ -2625,7 +2627,7 @@ func (s *ProjectService) ensureDeployServiceImageReady(slog.WarnContext(ctx, "image pull failed, falling back to build", "service", serviceName, "image", imageName, "error", err)return s.buildServiceImageForDeploy(ctx, projectID, project, serviceName, svc, progressWriter, user)}- return fmt.Errorf("failed to pull image %s: %w", imageName, err)+ return errors.WrapIff(err, "failed to pull image %s", imageName)}func (s *ProjectService) buildServiceImageForDeploy(@@ -2638,7 +2640,7 @@ func (s *ProjectService) buildServiceImageForDeploy(user *models.User,) error {if s.buildService == nil {- return fmt.Errorf("build service not available for service %s", serviceName)+ return errors.Errorf("build service not available for service %s", serviceName)}buildReq, updatedSvc, updated, err := s.prepareServiceBuildRequest(ctx, projectID, project, serviceName, svc, ProjectBuildOptions{})@@ -2716,10 +2718,10 @@ func (s *ProjectService) prepareServiceBuildRequest(effectiveProvider := s.resolveEffectiveBuildProvider(options.Provider)if updated && effectiveProvider == "depot" {- return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.Errorf("service %s must define an image when using depot build provider", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, errors.Errorf("service %s must define an image when using depot build provider", serviceName)}if updated && options.Push != nil && *options.Push {- return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.Errorf("service %s must define an image when push is enabled", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, errors.Errorf("service %s must define an image when push is enabled", serviceName)}// The build context (and any absolute Dockerfile path) is read locally by@@ -2737,7 +2739,7 @@ func (s *ProjectService) prepareServiceBuildRequest(dockerfileInline := updatedSvc.Build.DockerfileInlineif strings.TrimSpace(updatedSvc.Build.Dockerfile) != "" && strings.TrimSpace(dockerfileInline) != "" {- return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.Errorf("service %s cannot define both dockerfile and dockerfile_inline", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, errors.Errorf("service %s cannot define both dockerfile and dockerfile_inline", serviceName)}dockerfilePath := ""@@ -2838,7 +2840,7 @@ func (s *ProjectService) buildProjectServicesInternal(ctx context.Context, proje}if buildCount == 0 && len(selected) > 0 {- return fmt.Errorf("no build-enabled services matched: %s", strings.Join(options.Services, ", "))+ return errors.Errorf("no build-enabled services matched: %s", strings.Join(options.Services, ", "))}return nil@@ -2851,7 +2853,7 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, s}if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRestarting); err != nil {- return fmt.Errorf("failed to update project status to restarting: %w", err)+ return errors.WrapIf(err, "failed to update project status to restarting")}// Get configured projects directory from settings@@ -2863,13 +2865,13 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, scompProj, _, lerr := projects.LoadComposeProjectFromDir(ctx, proj.Path, projects.NormalizeProjectName(proj.Name), projectsDirectory, utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false), pathMapper)if lerr != nil {_ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)- return fmt.Errorf("failed to load compose project: %w", lerr)+ return errors.WrapIf(lerr, "failed to load compose project")}writeProjectProgressInternal(ctx, "Restarting project services", 55, "restart")if err := projects.ComposeRestart(ctx, compProj, services); err != nil {_ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)- return fmt.Errorf("failed to restart project: %w", err)+ return errors.WrapIf(err, "failed to restart project")}metadata := models.JSON{@@ -2915,7 +2917,7 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, nareturn nil, err}if len(fileChanges) > 0 && isGitOpsManagedProjectInternal(&proj) {- return nil, &common.ProjectFileForbiddenError{Err: errors.New("git-managed project files are read-only")}+ return nil, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: GitOps-managed project files cannot be edited"))}if err := s.ensureProjectStoppedForRenameInternal(ctx, &proj, name); err != nil {@@ -3010,7 +3012,7 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx contextstateCommitted := projectStateCommitted != nil && *projectStateCommittedif err != nil && volumeMigrationApplied && !stateCommitted {if rollbackErr := volumeMigration.Rollback(ctx); rollbackErr != nil {- err = errors.Join(err, fmt.Errorf("failed to rollback project volume rename: %w", rollbackErr))+ err = stderrors.Join(err, errors.WrapIf(rollbackErr, "failed to rollback project volume rename"))}}}()@@ -3042,7 +3044,7 @@ func (s *ProjectService) applyProjectVolumeMigrationForUpdateInternal(ctx contexreturn nil}if err := volumeMigration.Apply(ctx); err != nil {- return fmt.Errorf("failed to rename project volumes: %w", err)+ return errors.WrapIf(err, "failed to rename project volumes")}*applied = truereturn s.writeProjectRenameJournalInternal(ctx, renameJournal, projectRenameJournalPhaseTargetsCopiedInternal)@@ -3051,7 +3053,7 @@ func (s *ProjectService) applyProjectVolumeMigrationForUpdateInternal(ctx contexfunc (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *models.Project) error {tx := s.db.WithContext(ctx).Begin()if tx.Error != nil {- return fmt.Errorf("failed to start project update transaction: %w", tx.Error)+ return errors.WrapIf(tx.Error, "failed to start project update transaction")}txCommitted := false@@ -3062,10 +3064,10 @@ func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *mo}()if err := tx.Save(proj).Error; err != nil {- return fmt.Errorf("failed to update project: %w", err)+ return errors.WrapIf(err, "failed to update project")}if err := tx.Commit().Error; err != nil {- return fmt.Errorf("failed to commit project update: %w", err)+ return errors.WrapIf(err, "failed to commit project update")}txCommitted = truereturn nil@@ -3114,12 +3116,12 @@ func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context,if backup != nil {if restoreErr := s.restoreProjectDirectoryBackupInternal(ctx, projectsDirectory, proj.Path, backup); restoreErr != nil {- err = errors.Join(err, fmt.Errorf("failed to restore project files after update failure: %w", restoreErr))+ err = stderrors.Join(err, errors.WrapIf(restoreErr, "failed to restore project files after update failure"))}}if *journalActive {if recoverErr := s.recoverProjectRenameJournalForProjectInternal(ctx, projectID); recoverErr != nil {- err = errors.Join(err, fmt.Errorf("project rename recovery failed: %w", recoverErr))+ err = stderrors.Join(err, errors.WrapIf(recoverErr, "project rename recovery failed"))} else {*journalActive = false}@@ -3172,24 +3174,24 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectIDenvUpdate, err := s.prepareGitSyncEnvUpdateInternal(proj.Path, gitEnvContent)if err != nil {- return nil, fmt.Errorf("failed to resolve git env state: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve git env state")}if err := s.validateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, composeContent, envUpdate.effectiveContent, gitOverrideContent, gitOverrideFileName, true); err != nil {- return nil, fmt.Errorf("invalid compose file: %w", err)+ return nil, errors.WrapIf(err, "invalid compose file")}if err := projects.WriteComposeFile(projectsDirectory, proj.Path, composeContent); err != nil {- return nil, fmt.Errorf("failed to save compose file: %w", err)+ return nil, errors.WrapIf(err, "failed to save compose file")}if err := s.persistGitSyncEnvFilesInternal(proj.Path, projectsDirectory, envUpdate); err != nil {- return nil, fmt.Errorf("failed to sync git env files: %w", err)+ return nil, errors.WrapIf(err, "failed to sync git env files")}if err := projects.WriteComposeOverrideFile(projectsDirectory, proj.Path, gitOverrideContent, gitOverrideFileName); err != nil {- return nil, fmt.Errorf("failed to sync git override file: %w", err)+ return nil, errors.WrapIf(err, "failed to sync git override file")}if err := s.db.WithContext(ctx).Save(&proj).Error; err != nil {- return nil, fmt.Errorf("failed to update project: %w", err)+ return nil, errors.WrapIf(err, "failed to update project")}s.refreshComposeProjectNameInternal(ctx, &proj)s.refreshProjectImageRefsInternal(ctx, &proj)@@ -3221,12 +3223,12 @@ func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID striif errors.Is(err, gorm.ErrRecordNotFound) {return models.Project{}, "", errors.New("project not found")}- return models.Project{}, "", fmt.Errorf("failed to get project: %w", err)+ return models.Project{}, "", errors.WrapIf(err, "failed to get project")}projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return models.Project{}, "", fmt.Errorf("failed to get projects directory: %w", err)+ return models.Project{}, "", errors.WrapIf(err, "failed to get projects directory")}if err := s.ensureProjectPathUnderRoot(ctx, &proj, false); err != nil {@@ -3250,7 +3252,7 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctpreviewPath, err := os.MkdirTemp(projectsDirectory, ".project-update-preview-*")if err != nil {- return nil, fmt.Errorf("failed to create project update preview: %w", err)+ return nil, errors.WrapIf(err, "failed to create project update preview")}defer func() {if removeErr := os.RemoveAll(previewPath); removeErr != nil {@@ -3259,16 +3261,16 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ct}()if err := projects.CopyDirectoryContents(proj.Path, previewPath); err != nil {- return nil, fmt.Errorf("failed to prepare project update preview: %w", err)+ return nil, errors.WrapIf(err, "failed to prepare project update preview")}previewProject := *projpreviewProject.Path = previewPathif err := s.applyProjectFileChangesInternal(ctx, &previewProject, "", fileChanges); err != nil {- return nil, fmt.Errorf("failed to prepare project update preview: %w", err)+ return nil, errors.WrapIf(err, "failed to prepare project update preview")}if err := s.persistUpdatedProjectFiles(ctx, &previewProject, projectsDirectory, composeContent, envContent, overrideContent); err != nil {- return nil, fmt.Errorf("failed to prepare project update preview: %w", err)+ return nil, errors.WrapIf(err, "failed to prepare project update preview")}return s.prepareProjectRenameVolumeMigrationInternal(ctx, &previewProject, name)@@ -3282,16 +3284,15 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationInternal(ctx contextcomposeProject, _, err := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if err != nil {- var notFound *common.ProjectComposeFileNotFoundError- if errors.As(err, ¬Found) {+ if errors.Is(err, common.ErrProjectComposeFileNotFound) {return nil, nil}- return nil, fmt.Errorf("failed to load compose project for volume rename: %w", err)+ return nil, errors.WrapIf(err, "failed to load compose project for volume rename")}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker for volume rename: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker for volume rename")}return volumes.PlanMigration(ctx, dockerClient, composeProject, oldComposeName, newComposeName)@@ -3333,7 +3334,7 @@ func requireProjectFileRevisionInternal(fileTreeRevision *string, fileChanges []return nil}if fileTreeRevision == nil || strings.TrimSpace(*fileTreeRevision) == "" {- return &common.ProjectFileBadRequestError{Err: errors.New("file tree revision is required")}+ return common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: file tree revision is required"))}return nil}@@ -3380,20 +3381,23 @@ func (s *ProjectService) projectFileApplyOptionsInternal(ctx context.Context, prfunc wrapProjectFileErrorInternal(err error) error {switch {case errors.Is(err, projects.ErrProjectFileRevisionConflict):- return &common.ProjectFileConflictError{Err: err}+ return common.Classify(common.ErrProjectFileConflict, errors.WithStackIf(err))case errors.Is(err, projects.ErrProjectFileOutsideProjectDirectory),errors.Is(err, projects.ErrProjectFileProtectedPath),errors.Is(err, projects.ErrProjectFileSymlinkPath):- return &common.ProjectFileForbiddenError{Err: err}+ return common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))+default:- return &common.ProjectFileBadRequestError{Err: err}+ return common.Classify(common.ErrProjectFileBadRequest, errors.++ // projectUpdateBackupScopeInternal derives the exact set of paths an update+ // can mutate so the backup never copies out-of-scope data directories.+ // Changes that fail normalization are skipped: the apply step rejects them+ // before mutating anything, so there is nothing to roll back for them.+ WrapIf(err, "Invalid project file request"))}}-// projectUpdateBackupScopeInternal derives the exact set of paths an update-// can mutate so the backup never copies out-of-scope data directories.-// Changes that fail normalization are skipped: the apply step rejects them-// before mutating anything, so there is nothing to roll back for them.func projectUpdateBackupScopeInternal(projectPath string, composeContent, envContent, overrideContent *string, fileChanges []project.ProjectFileChange) projects.ProjectUpdateBackupScope {scope := projects.ProjectUpdateBackupScope{TopLevelFiles: composeContent != nil || envContent != nil || overrideContent != nil,@@ -3476,13 +3480,13 @@ func demoteInterferingRenamedDirsInternal(scope *projects.ProjectUpdateBackupScofunc (s *ProjectService) backupProjectDirectoryInternal(ctx context.Context, projectsDirectory, projectPath string, scope projects.ProjectUpdateBackupScope) (*projects.ProjectUpdateBackup, error) {projectAbs, err := filepath.Abs(projectPath)if err != nil {- return nil, fmt.Errorf("failed to resolve project path: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve project path")}projectAbs = filepath.Clean(projectAbs)rootAbs, err := filepath.Abs(projectsDirectory)if err != nil {- return nil, fmt.Errorf("failed to resolve projects directory: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve projects directory")}rootAbs = filepath.Clean(rootAbs)if !projects.IsSafeSubdirectory(rootAbs, projectAbs) || projectAbs == rootAbs {@@ -3491,7 +3495,7 @@ func (s *ProjectService) backupProjectDirectoryInternal(ctx context.Context, probackupPath, err := os.MkdirTemp(projectsDirectory, ".project-update-backup-*")if err != nil {- return nil, fmt.Errorf("failed to create project backup directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create project backup directory")}// Tolerate files Arcane cannot read (e.g. foreign-owned secrets): skip them// in the backup so an unrelated unreadable file can't block the whole save.@@ -3499,7 +3503,7 @@ func (s *ProjectService) backupProjectDirectoryInternal(ctx context.Context, probackup, err := projects.BackupProjectUpdateScope(projectAbs, backupPath, scope)if err != nil {_ = os.RemoveAll(backupPath)- return nil, fmt.Errorf("failed to backup project files: %w", err)+ return nil, errors.WrapIf(err, "failed to backup project files")}if len(backup.Skipped) > 0 {slog.WarnContext(ctx, "skipped unreadable files while backing up project; they will be left untouched on rollback", "projectPath", projectAbs, "skipped", backup.Skipped)@@ -3510,13 +3514,13 @@ func (s *ProjectService) backupProjectDirectoryInternal(ctx context.Context, profunc (s *ProjectService) restoreProjectDirectoryBackupInternal(ctx context.Context, projectsDirectory, projectPath string, backup *projects.ProjectUpdateBackup) error {projectAbs, err := filepath.Abs(projectPath)if err != nil {- return fmt.Errorf("failed to resolve project path: %w", err)+ return errors.WrapIf(err, "failed to resolve project path")}projectAbs = filepath.Clean(projectAbs)rootAbs, err := filepath.Abs(projectsDirectory)if err != nil {- return fmt.Errorf("failed to resolve projects directory: %w", err)+ return errors.WrapIf(err, "failed to resolve projects directory")}rootAbs = filepath.Clean(rootAbs)if !projects.IsSafeSubdirectory(rootAbs, projectAbs) || projectAbs == rootAbs {@@ -3525,13 +3529,13 @@ func (s *ProjectService) restoreProjectDirectoryBackupInternal(ctx context.Conteslog.DebugContext(ctx, "restoring project directory backup", "path", projectAbs, "backup", backup.BackupDir)if err := os.MkdirAll(projectAbs, common.DirPerm); err != nil {- return fmt.Errorf("failed to recreate project directory: %w", err)+ return errors.WrapIf(err, "failed to recreate project directory")}// Restore only the paths the update could have mutated, in place: files// that were skipped during backup (unreadable, e.g. foreign-owned secrets)// are preserved, and out-of-scope files are never touched.if err := projects.RestoreProjectUpdateBackup(projectAbs, backup); err != nil {- return fmt.Errorf("failed to restore project backup: %w", err)+ return errors.WrapIf(err, "failed to restore project backup")}return nil}@@ -3609,24 +3613,24 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *mcase composeContent != nil:effectiveEnvContent, err := s.resolveEffectiveEnvContentForUpdateInternal(proj.Path, envContent)if err != nil {- return fmt.Errorf("invalid compose file: %w", err)+ return errors.WrapIf(err, "invalid compose file")}valOverride, valOverrideName := resolveEffectiveOverrideForValidationInternal(proj.Path, overrideContent)if err := s.validateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, *composeContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {- return fmt.Errorf("invalid compose file: %w", err)+ return errors.WrapIf(err, "invalid compose file")}if err := projects.WriteComposeFile(projectsDirectory, proj.Path, *composeContent); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}if envContent != nil {if err := s.persistEffectiveEnvContentInternal(proj.Path, projectsDirectory, *envContent); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}} else if err := s.ensureEffectiveEnvFileInternal(proj.Path, projectsDirectory); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}if err := applyOverrideFileChangeInternal(projectsDirectory, proj.Path, overrideContent); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}case overrideContent != nil:if err := s.persistOverrideOnlyUpdateInternal(ctx, proj, projectsDirectory, envContent, overrideContent); err != nil {@@ -3649,31 +3653,31 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *mfunc (s *ProjectService) persistOverrideOnlyUpdateInternal(ctx context.Context, proj *models.Project, projectsDirectory string, envContent, overrideContent *string) error {baseContent, _, err := projects.ReadProjectFiles(proj.Path, "")if err != nil {- return fmt.Errorf("failed to read project files: %w", err)+ return errors.WrapIf(err, "failed to read project files")}effectiveEnvContent, err := s.resolveEffectiveEnvContentForUpdateInternal(proj.Path, envContent)if err != nil {- return fmt.Errorf("invalid compose file: %w", err)+ return errors.WrapIf(err, "invalid compose file")}valOverride, valOverrideName := resolveEffectiveOverrideForValidationInternal(proj.Path, overrideContent)if err := s.validateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, baseContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {- return fmt.Errorf("invalid compose file: %w", err)+ return errors.WrapIf(err, "invalid compose file")}if envContent != nil {if err := s.persistEffectiveEnvContentInternal(proj.Path, projectsDirectory, *envContent); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}}if err := applyOverrideFileChangeInternal(projectsDirectory, proj.Path, overrideContent); err != nil {- return fmt.Errorf("failed to save project files: %w", err)+ return errors.WrapIf(err, "failed to save project files")}return nil}func (s *ProjectService) validateComposeContentForUpdate(ctx context.Context, projectsDirectory, projectPath, projectName, composeContent string, effectiveEnvContent *string, overrideContent *string, overrideFileName string, lenient bool) (err error) {defer func() {- if recovered := recover(); recovered != nil {- err = fmt.Errorf("compose file contains invalid syntax: %v", recovered)+ if panicErr := emperror.Recover(recover()); panicErr != nil {+ err = errors.WrapIf(panicErr, "compose file contains invalid syntax")}}()@@ -3741,7 +3745,7 @@ func validateComposeIncludePathsForProjectInternal(projectPath, composeContent s}for _, inc := range includes {if _, err := projects.ValidateIncludePathForWrite(projectPath, inc.Path); err != nil {- return fmt.Errorf("include path %q is outside project directory: %w", inc.RelativePath, err)+ return errors.WrapIff(err, "include path %q is outside project directory", inc.RelativePath)}}return nil@@ -3760,14 +3764,14 @@ func buildComposeValidationEnvironment(projectsDirectory, projectPath string, efglobalEnvPath := filepath.Join(projectsDirectory, projects.GlobalEnvFileName)globalEnv, err := parseComposeValidationEnvFile(globalEnvPath, fullEnvMap)if err != nil {- return nil, fmt.Errorf("parse global env file: %w", err)+ return nil, errors.WrapIf(err, "parse global env file")}maps.Copy(fullEnvMap, globalEnv)if effectiveEnvContent != nil {projectEnv, err := parseComposeValidationEnvContent(*effectiveEnvContent, fullEnvMap)if err != nil {- return nil, fmt.Errorf("parse provided env content: %w", err)+ return nil, errors.WrapIf(err, "parse provided env content")}maps.Copy(fullEnvMap, projectEnv)return fullEnvMap, nil@@ -3776,7 +3780,7 @@ func buildComposeValidationEnvironment(projectsDirectory, projectPath string, efprojectEnvPath := filepath.Join(projectPath, ".env")projectEnv, err := parseComposeValidationEnvFile(projectEnvPath, fullEnvMap)if err != nil {- return nil, fmt.Errorf("parse project env file: %w", err)+ return nil, errors.WrapIf(err, "parse project env file")}maps.Copy(fullEnvMap, projectEnv)@@ -3788,12 +3792,12 @@ func parseComposeValidationEnvFile(path string, contextEnv projects.EnvMap) (proif os.IsNotExist(err) {return nil, nil}- return nil, fmt.Errorf("stat file: %w", err)+ return nil, errors.WrapIf(err, "stat file")}content, err := os.ReadFile(path)if err != nil {- return nil, fmt.Errorf("read file: %w", err)+ return nil, errors.WrapIf(err, "read file")}return parseComposeValidationEnvContent(string(content), contextEnv)@@ -3807,7 +3811,7 @@ func parseComposeValidationEnvContent(content string, contextEnv projects.EnvMapenvMap, err := dotenv.ParseWithLookup(strings.NewReader(content), lookupFn)if err != nil {- return nil, fmt.Errorf("parse env: %w", err)+ return nil, errors.WrapIf(err, "parse env")}return envMap, nil@@ -3820,7 +3824,7 @@ func (s *ProjectService) resolveEffectiveEnvContentForUpdateInternal(projectPathstate, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return nil, fmt.Errorf("read project env state: %w", err)+ return nil, errors.WrapIf(err, "read project env state")}effectiveContent, err := s.resolveStoredEffectiveEnvContentInternal(state)@@ -3841,7 +3845,7 @@ func (s *ProjectService) resolveStoredEffectiveEnvContentInternal(state projectsif state.HasGitSource || state.HasOverride {effectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return "", fmt.Errorf("build effective env content: %w", err)+ return "", errors.WrapIf(err, "build effective env content")}return effectiveContent, nil}@@ -3851,7 +3855,7 @@ func (s *ProjectService) resolveStoredEffectiveEnvContentInternal(state projectsfunc (s *ProjectService) persistEffectiveEnvContentInternal(projectPath, projectsDirectory, envContent string) error {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return fmt.Errorf("read project env state: %w", err)+ return errors.WrapIf(err, "read project env state")}if state.HasGitSource && state.HasEffective && envContent == state.EffectiveContent {@@ -3872,12 +3876,12 @@ func (s *ProjectService) persistEffectiveEnvContentInternal(projectPath, projectoverrideContent, err := projects.BuildOverrideEnvContent(state.GitContent, envContent)if err != nil {- return fmt.Errorf("build override env content: %w", err)+ return errors.WrapIf(err, "build override env content")}effectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, overrideContent)if err != nil {- return fmt.Errorf("build effective env content: %w", err)+ return errors.WrapIf(err, "build effective env content")}if err := projects.WriteManagedEnvFile(projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent); err != nil {@@ -3890,7 +3894,7 @@ func (s *ProjectService) persistEffectiveEnvContentInternal(projectPath, projectfunc (s *ProjectService) ensureEffectiveEnvFileInternal(projectPath, projectsDirectory string) error {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return fmt.Errorf("read project env state: %w", err)+ return errors.WrapIf(err, "read project env state")}if !state.HasGitSource {@@ -3909,7 +3913,7 @@ func (s *ProjectService) ensureEffectiveEnvFileInternal(projectPath, projectsDireffectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return fmt.Errorf("build effective env content: %w", err)+ return errors.WrapIf(err, "build effective env content")}return projects.WriteManagedEnvFile(projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent)@@ -3925,7 +3929,7 @@ type gitSyncEnvUpdateInternal struct {func (s *ProjectService) prepareGitSyncEnvUpdateInternal(projectPath string, gitEnvContent *string) (gitSyncEnvUpdateInternal, error) {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return gitSyncEnvUpdateInternal{}, fmt.Errorf("read project env state: %w", err)+ return gitSyncEnvUpdateInternal{}, errors.WrapIf(err, "read project env state")}update := gitSyncEnvUpdateInternal{@@ -3953,7 +3957,7 @@ func (s *ProjectService) prepareGitSyncEnvUpdateInternal(projectPath string, giteffectiveContent, err := projects.BuildEffectiveEnvContent(*gitEnvContent, overrideContent)if err != nil {- return gitSyncEnvUpdateInternal{}, fmt.Errorf("build effective env content: %w", err)+ return gitSyncEnvUpdateInternal{}, errors.WrapIf(err, "build effective env content")}update.effectiveContent = &effectiveContent@@ -3965,7 +3969,7 @@ func (s *ProjectService) resolveOverrideContentForGitSyncInternal(state projectscase state.HasGitSource:overrideContent, err := projects.BuildOverrideEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return "", fmt.Errorf("build override env content: %w", err)+ return "", errors.WrapIf(err, "build override env content")}return overrideContent, nilcase state.HasOverride:@@ -3975,13 +3979,13 @@ func (s *ProjectService) resolveOverrideContentForGitSyncInternal(state projects}overrideContent, err := projects.BuildOverrideEnvContent(gitEnvContent, effectiveContent)if err != nil {- return "", fmt.Errorf("build override env content: %w", err)+ return "", errors.WrapIf(err, "build override env content")}return overrideContent, nilcase strings.TrimSpace(state.DirectContent) != "":overrideContent, err := projects.BuildAdditiveOverrideEnvContent(gitEnvContent, state.DirectContent)if err != nil {- return "", fmt.Errorf("build override env content: %w", err)+ return "", errors.WrapIf(err, "build override env content")}return overrideContent, nildefault:@@ -4033,18 +4037,18 @@ func (s *ProjectService) ensureProjectStoppedForRenameInternal(ctx context.Contereturn nil}if proj.Status != models.ProjectStatusStopped && proj.Status != models.ProjectStatusUnknown {- return fmt.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)+ return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)}services, err := s.GetProjectServices(ctx, proj.ID)if err != nil {slog.WarnContext(ctx, "failed to resolve project status before rename", "projectID", proj.ID, "error", err)- return fmt.Errorf("project must be stopped before renaming (current status: %s): failed to verify live status: %w", proj.Status, err)+ return errors.WrapIff(err, "project must be stopped before renaming (current status: %s): failed to verify live status", proj.Status)}status := s.calculateProjectStatus(services)if status != models.ProjectStatusStopped {- return fmt.Errorf("project must be stopped before renaming (current status: %s)", status)+ return errors.Errorf("project must be stopped before renaming (current status: %s)", status)}serviceCount, runningCount := s.getServiceCounts(services)@@ -4066,7 +4070,7 @@ func (s *ProjectService) applyProjectRenameIfNeeded(proj *models.Project, name *}if proj.Status != models.ProjectStatusStopped {- return fmt.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)+ return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)}newDirName := projects.SanitizeProjectName(newName)@@ -4078,13 +4082,13 @@ func (s *ProjectService) applyProjectRenameIfNeeded(proj *models.Project, name *targetPath := filepath.Clean(filepath.Join(projectsDirectory, newDirName))if currentPath != targetPath {if _, statErr := os.Stat(targetPath); statErr == nil {- return fmt.Errorf("project directory already exists: %s", targetPath)+ return errors.Errorf("project directory already exists: %s", targetPath)} else if !os.IsNotExist(statErr) {- return fmt.Errorf("failed to check project directory rename target: %w", statErr)+ return errors.WrapIf(statErr, "failed to check project directory rename target")}if err := os.Rename(currentPath, targetPath); err != nil {- return fmt.Errorf("failed to rename project directory: %w", err)+ return errors.WrapIf(err, "failed to rename project directory")}proj.Path = targetPath@@ -4107,7 +4111,7 @@ func (s *ProjectService) UpdateProjectIncludeFile(ctx context.Context, projectID}if err := projects.WriteIncludeFile(proj.Path, relativePath, content); err != nil {- return fmt.Errorf("failed to update include file: %w", err)+ return errors.WrapIf(err, "failed to update include file")}s.refreshProjectImageRefsInternal(ctx, proj)@@ -4134,7 +4138,7 @@ func (s *ProjectService) UpdateProjectIncludeFile(ctx context.Context, projectIDfunc (s *ProjectService) ensureProjectPathUnderRoot(ctx context.Context, proj *models.Project, persist bool) error {projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return fmt.Errorf("failed to get projects directory: %w", err)+ return errors.WrapIf(err, "failed to get projects directory")}rootAbs, _ := filepath.Abs(projectsDirectory)@@ -4245,7 +4249,7 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Quevar projectsArray []models.ProjectpaginationResp, err := pagination.PaginateAndSortDB(params, query, &projectsArray)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate projects: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate projects")}slog.DebugContext(ctx, "Retrieved projects from database",@@ -4311,7 +4315,7 @@ func (s *ProjectService) filterProjectsWithDerivedFiltersInternal()}if err := query.Find(&projectsArray).Error; err != nil {- return pagination.FilterResult[project.Details]{}, fmt.Errorf("failed to list projects: %w", err)+ return pagination.FilterResult[project.Details]{}, errors.WrapIf(err, "failed to list projects")}items := s.fetchProjectStatusConcurrently(ctx, projectsArray)@@ -5140,11 +5144,11 @@ func (s *ProjectService) writeProjectRenameJournalInternal(ctx context.Context,payload, err := json.Marshal(journal)if err != nil {- return fmt.Errorf("marshal project rename journal: %w", err)+ return errors.WrapIf(err, "marshal project rename journal")}if err := s.kvService.Set(ctx, projectRenameJournalKeyInternal(journal.ProjectID), string(payload)); err != nil {- return fmt.Errorf("write project rename journal: %w", err)+ return errors.WrapIf(err, "write project rename journal")}return nil}@@ -5172,10 +5176,10 @@ func (s *ProjectService) writeProjectRenameRollbackCleanupInternal(ctx context.C}payload, err := json.Marshal(cleanup)if err != nil {- return fmt.Errorf("marshal project rename rollback cleanup: %w", err)+ return errors.WrapIf(err, "marshal project rename rollback cleanup")}if err := s.kvService.Set(ctx, projectRenameRollbackCleanupKeyInternal(journal.ProjectID), string(payload)); err != nil {- return fmt.Errorf("write project rename rollback cleanup: %w", err)+ return errors.WrapIf(err, "write project rename rollback cleanup")}return nil}@@ -5223,15 +5227,15 @@ func (s *ProjectService) RecoverProjectRenameJournals(ctx context.Context) errorfor _, entry := range entries {var journal projectRenameJournalInternalif err := json.Unmarshal([]byte(entry.Value), &journal); err != nil {- recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename journal %s: %w", entry.Key, err))+ recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "decode project rename journal %s", entry.Key))continue}if err := s.recoverProjectRenameJournalInternal(ctx, &journal); err != nil {- recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename journal %s: %w", entry.Key, err))+ recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "recover project rename journal %s", entry.Key))continue}}- return errors.Join(recoverErr, s.recoverProjectRenameRollbackCleanupsInternal(ctx))+ return stderrors.Join(recoverErr, s.recoverProjectRenameRollbackCleanupsInternal(ctx))}func (s *ProjectService) recoverProjectRenameJournalForProjectInternal(ctx context.Context, projectID string) error {@@ -5246,7 +5250,7 @@ func (s *ProjectService) recoverProjectRenameJournalForProjectInternal(ctx contevar journal projectRenameJournalInternalif err := json.Unmarshal([]byte(raw), &journal); err != nil {- return fmt.Errorf("decode project rename journal: %w", err)+ return errors.WrapIf(err, "decode project rename journal")}return s.recoverProjectRenameJournalInternal(ctx, &journal)}@@ -5259,7 +5263,7 @@ func (s *ProjectService) recoverProjectRenameJournalInternal(ctx context.Contextvar proj models.ProjectdbErr := s.db.WithContext(ctx).First(&proj, "id = ?", journal.ProjectID).Errorif dbErr != nil && !errors.Is(dbErr, gorm.ErrRecordNotFound) {- return fmt.Errorf("load project for rename recovery: %w", dbErr)+ return errors.WrapIf(dbErr, "load project for rename recovery")}projectCommitted := dbErr == nil && (proj.Name == journal.NewName || filepath.Clean(proj.Path) == filepath.Clean(journal.NewPath))@@ -5274,7 +5278,7 @@ func (s *ProjectService) recoverProjectRenameJournalInternal(ctx context.Contextvar cleanupErr *volumes.SourceCleanupErrorif errors.As(err, &cleanupErr) {if writeErr := s.writeProjectRenameJournalInternal(ctx, journal, projectRenameJournalPhaseSourceCleanupPendingInternal); writeErr != nil {- return errors.Join(err, writeErr)+ return stderrors.Join(err, writeErr)}}return err@@ -5326,7 +5330,7 @@ func (s *ProjectService) rollbackProjectRenameJournalInternal(ctx context.Contex"path": journal.OldPath,"dir_name": journal.OldDirName,}).Error; err != nil {- return errors.Join(directoryErr, volumeErr, fmt.Errorf("restore project database state: %w", err))+ return stderrors.Join(directoryErr, volumeErr, errors.WrapIf(err, "restore project database state"))}if directoryErr != nil {@@ -5338,7 +5342,7 @@ func (s *ProjectService) rollbackProjectRenameJournalInternal(ctx context.Contexslog.WarnContext(ctx, "clearing project rename journal after preserving target volume data", "projectID", journal.ProjectID, "pathsMissing", pathsMissing, "error", volumeErr)} else {if cleanupErr := s.writeProjectRenameRollbackCleanupInternal(ctx, journal); cleanupErr != nil {- return errors.Join(directoryErr, volumeErr, cleanupErr)+ return stderrors.Join(directoryErr, volumeErr, cleanupErr)}slog.WarnContext(ctx, "queued project rename target volume cleanup after restoring database state despite volume rollback failure", "projectID", journal.ProjectID, "pathsMissing", pathsMissing, "error", volumeErr)}@@ -5361,11 +5365,11 @@ func (s *ProjectService) recoverProjectRenameRollbackCleanupsInternal(ctx contexfor _, entry := range entries {var cleanup projectRenameRollbackCleanupInternalif err := json.Unmarshal([]byte(entry.Value), &cleanup); err != nil {- recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename rollback cleanup %s: %w", entry.Key, err))+ recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "decode project rename rollback cleanup %s", entry.Key))continue}if err := s.recoverProjectRenameRollbackCleanupInternal(ctx, &cleanup); err != nil {- recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename rollback cleanup %s: %w", entry.Key, err))+ recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "recover project rename rollback cleanup %s", entry.Key))continue}}@@ -5387,7 +5391,7 @@ func (s *ProjectService) recoverProjectRenameRollbackCleanupInternal(ctx contextslog.WarnContext(ctx, "clearing project rename rollback cleanup because project no longer exists", "projectID", cleanup.ProjectID)return s.clearProjectRenameRollbackCleanupInternal(ctx, cleanup.ProjectID)}- return fmt.Errorf("load project for rename rollback cleanup: %w", dbErr)+ return errors.WrapIf(dbErr, "load project for rename rollback cleanup")}if proj.Name != cleanup.OldName || filepath.Clean(proj.Path) != filepath.Clean(cleanup.OldPath) {@@ -5435,7 +5439,7 @@ func (s *ProjectService) projectRenameRecoveryDockerInternal(ctx context.ContextdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}return dockerClient, nildiff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.goindex d4a50f615..66b93d083 100644--- a/backend/internal/services/project_service_test.go+++ b/backend/internal/services/project_service_test.go@@ -2379,9 +2379,7 @@ func TestProjectService_UpdateProject_RejectsStaleProjectFileRevision(t *testing})require.Error(t, err)-- var conflictErr *common.ProjectFileConflictError- assert.ErrorAs(t, err, &conflictErr)+ assert.ErrorIs(t, err, common.ErrProjectFileConflict)assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))}@@ -2422,9 +2420,7 @@ func TestProjectService_UpdateProject_RejectsStaleDeepProjectFileRevision(t *tes})require.Error(t, err)-- var conflictErr *common.ProjectFileConflictError- assert.ErrorAs(t, err, &conflictErr)+ assert.ErrorIs(t, err, common.ErrProjectFileConflict)assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))}@@ -2466,9 +2462,7 @@ services:includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "../metadata.yaml")require.Error(t, err)assert.Empty(t, includeFile)-- var forbiddenErr *common.ProjectFileForbiddenError- assert.ErrorAs(t, err, &forbiddenErr)+ assert.ErrorIs(t, err, common.ErrProjectFileForbidden)}func TestProjectService_GetProjectFileContent_RejectsSymlinkInclude(t *testing.T) {@@ -2512,9 +2506,7 @@ services:includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "evil-link")require.Error(t, err)assert.Empty(t, includeFile)-- var forbiddenErr *common.ProjectFileForbiddenError- assert.ErrorAs(t, err, &forbiddenErr)+ assert.ErrorIs(t, err, common.ErrProjectFileForbidden)}func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkInclude(t *testing.T) {@@ -2558,9 +2550,7 @@ services:includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "subdir/secret.yaml")require.Error(t, err)assert.Empty(t, includeFile)-- var forbiddenErr *common.ProjectFileForbiddenError- assert.ErrorAs(t, err, &forbiddenErr)+ assert.ErrorIs(t, err, common.ErrProjectFileForbidden)}func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkProjectFile(t *testing.T) {@@ -2597,9 +2587,7 @@ func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkProjectFincludeFile, err := svc.GetProjectFileContent(ctx, project.ID, "subdir/secret.yaml")require.Error(t, err)assert.Empty(t, includeFile)-- var forbiddenErr *common.ProjectFileForbiddenError- assert.ErrorAs(t, err, &forbiddenErr)+ assert.ErrorIs(t, err, common.ErrProjectFileForbidden)}func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation(t *testing.T) {@@ -4184,8 +4172,7 @@ func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())err = svc.ArchiveProject(ctx, "project-running", models.User{BaseModel: models.BaseModel{ID: "user-1"}, Username: "tester"})require.Error(t, err)- var stoppedErr *common.ProjectMustBeStoppedError- assert.ErrorAs(t, err, &stoppedErr)+ assert.ErrorIs(t, err, common.ErrProjectMustBeStopped)var stored models.Projectrequire.NoError(t, db.First(&stored, "id = ?", "project-running").Error)@@ -4989,7 +4976,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectWithAmbiguous// Replace the standard compose.yaml with two custom-named compose files. The// directory still holds compose content, but DetectComposeFile can't pick one- // and returns common.AmbiguousComposeFileError. The reconcile must NOT delete the+ // and returns common.ErrComposeFileNotFound. The reconcile must NOT delete the// record: the project's files are intact on disk and it may be deployable.require.NoError(t, os.Remove(filepath.Join(projectPath, "compose.yaml")))composeBody := []byte("services:\n app:\n image: nginx:alpine\n")@@ -5747,8 +5734,7 @@ func TestProjectService_UpdateProject_RenameRollsBackWhenFileRevisionIsStale(t *})require.Error(t, err)- var conflictErr *common.ProjectFileConflictError- require.ErrorAs(t, err, &conflictErr)+ require.ErrorIs(t, err, common.ErrProjectFileConflict)require.DirExists(t, originalPath)require.NoDirExists(t, filepath.Join(projectsDir, "bar"))require.FileExists(t, filepath.Join(originalPath, "external.txt"))diff --git a/backend/internal/services/role_service.go b/backend/internal/services/role_service.goindex 68eea32fc..dadc41321 100644--- a/backend/internal/services/role_service.go+++ b/backend/internal/services/role_service.go@@ -3,12 +3,12 @@ package servicesimport ("context"json "encoding/json/v2"- "errors"- "fmt""log/slog""strings""time"+ "emperror.dev/errors"+"gorm.io/gorm""gorm.io/gorm/clause"@@ -80,7 +80,7 @@ func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {BuiltIn: true,}if err := tx.Save(&role).Error; err != nil {- return fmt.Errorf("failed to upsert built-in role %s: %w", id, err)+ return errors.WrapIff(err, "failed to upsert built-in role %s", id)}}return nil@@ -116,7 +116,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var rows []legacyUserif err := tx.Table("users").Select("id, roles").Scan(&rows).Error; err != nil {- return fmt.Errorf("failed to read legacy users.roles for backfill: %w", err)+ return errors.WrapIf(err, "failed to read legacy users.roles for backfill")}for _, u := range rows {roleID := authz.BuiltInRoleViewer@@ -129,7 +129,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {Source: models.RoleAssignmentSourceManual,}if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&assignment).Error; err != nil {- return fmt.Errorf("failed to backfill assignment for user %s: %w", u.ID, err)+ return errors.WrapIff(err, "failed to backfill assignment for user %s", u.ID)}}slog.InfoContext(ctx, "Backfilled legacy users.roles into user_role_assignments", "userCount", len(rows))@@ -157,7 +157,7 @@ func legacyRolesContainsAdminInternal(raw string) bool {return false}-// AssertGlobalAdminExists returns a *common.NoGlobalAdminRemainsError if zero+// AssertGlobalAdminExists returns common.ErrNoGlobalAdminRemains if zero// non-service users resolve to global administrator permissions. Called at boot// after the backfill migration; also called from inside mutation paths.func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {@@ -166,28 +166,30 @@ func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {return err}if count == 0 {- return &common.NoGlobalAdminRemainsError{}+ return common.Classify(common.ErrNoGlobalAdminRemains, errors.++ // BackfillApiKeyPermissions populates api_key_permissions for every existing+ // API key whose row has no permissions yet. Each key inherits a snapshot of+ // its owner's current effective permissions (scoped per the key's+ // environment_id when set). Idempotent: skips if the table is non-empty.+ // BackfillApiKeyPermissions ensures every ownerless (bootstrap) API key has+ // its expected permission grants. Called once per boot.+ //+ // Per-key, not all-or-nothing: a single bootstrap key with zero grants is+ // repaired even if other keys are already populated. This recovers env-+ // bootstrap keys that pre-date the per-key permission feature, or that were+ // created on a deployment where the original SetApiKeyPermissions call failed+ // (e.g., the api_key_permissions table didn't exist yet).+ //+ // User-owned keys are deliberately skipped. A user-owned key with zero grants+ // is an intentional "no access" state; rehydrating from the owner's effective+ // permissions on every boot would clobber that. User keys are seeded at+ // creation time by CreateApiKey instead.+ New("At least one user must retain a global Admin role assignment"))}return nil}-// BackfillApiKeyPermissions populates api_key_permissions for every existing-// API key whose row has no permissions yet. Each key inherits a snapshot of-// its owner's current effective permissions (scoped per the key's-// environment_id when set). Idempotent: skips if the table is non-empty.-// BackfillApiKeyPermissions ensures every ownerless (bootstrap) API key has-// its expected permission grants. Called once per boot.-//-// Per-key, not all-or-nothing: a single bootstrap key with zero grants is-// repaired even if other keys are already populated. This recovers env--// bootstrap keys that pre-date the per-key permission feature, or that were-// created on a deployment where the original SetApiKeyPermissions call failed-// (e.g., the api_key_permissions table didn't exist yet).-//-// User-owned keys are deliberately skipped. A user-owned key with zero grants-// is an intentional "no access" state; rehydrating from the owner's effective-// permissions on every boot would clobber that. User keys are seeded at-// creation time by CreateApiKey instead.func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {// Bootstrap-class keys we'll repair if they have zero grants:// - user_id IS NULL → env-bootstrap keys.@@ -198,7 +200,7 @@ func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {// those are an intentional "no access" state we must not overwrite.var keys []models.ApiKeyif err := s.db.WithContext(ctx).Where("user_id IS NULL OR managed_by IS NOT NULL").Find(&keys).Error; err != nil {- return fmt.Errorf("failed to list bootstrap api keys for backfill: %w", err)+ return errors.WrapIf(err, "failed to list bootstrap api keys for backfill")}if len(keys) == 0 {return nil@@ -208,7 +210,7 @@ func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {for _, key := range keys {var existing int64if err := tx.Model(&models.ApiKeyPermission{}).Where("api_key_id = ?", key.ID).Count(&existing).Error; err != nil {- return fmt.Errorf("failed to count permissions for api key %s: %w", key.ID, err)+ return errors.WrapIff(err, "failed to count permissions for api key %s", key.ID)}if existing > 0 {continue@@ -223,7 +225,7 @@ func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {Permission: p,EnvironmentID: key.EnvironmentID,}).Error; err != nil {- return fmt.Errorf("failed to seed api key permission: %w", err)+ return errors.WrapIf(err, "failed to seed api key permission")}}slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)@@ -251,7 +253,7 @@ func (s *RoleService) backfillPermsForKeyInternal(ctx context.Context, tx *gorm.if errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, fmt.Errorf("failed to load api key owner: %w", err)+ return nil, errors.WrapIf(err, "failed to load api key owner")}ps, err := s.resolveUserPermissionsInternal(ctx, tx, owner.ID)if err != nil {@@ -289,7 +291,7 @@ func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryPararesp, err := pagination.PaginateAndSortDB(params, query, &roles)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate roles: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate roles")}return roles, resp, nil}@@ -297,13 +299,13 @@ func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParafunc (s *RoleService) ListAllRoles(ctx context.Context) ([]models.Role, error) {var roles []models.Roleif err := s.db.WithContext(ctx).Order("name").Find(&roles).Error; err != nil {- return nil, fmt.Errorf("failed to list roles: %w", err)+ return nil, errors.WrapIf(err, "failed to list roles")}return roles, nil}func (s *RoleService) GetRole(ctx context.Context, id string) (*models.Role, error) {- return dbutil.FirstWhere[models.Role](ctx, s.db.DB, &common.RoleNotFoundError{}, "id = ?", id)+ return dbutil.FirstWhere[models.Role](ctx, s.db.DB, common.Classify(common.ErrRoleNotFound, errors.New("Role not found")), "id = ?", id)}func (s *RoleService) CreateRole(ctx context.Context, name string, description *string, permissions []string) (*models.Role, error) {@@ -322,10 +324,10 @@ func (s *RoleService) CreateRole(ctx context.Context, name string, description *err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var conflict int64if err := tx.Model(&models.Role{}).Where("name = ?", name).Count(&conflict).Error; err != nil {- return fmt.Errorf("failed to check role name uniqueness: %w", err)+ return errors.WrapIf(err, "failed to check role name uniqueness")}if conflict > 0 {- return &common.RoleNameTakenError{}+ return common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))}return tx.Create(role).Error})@@ -344,27 +346,27 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptivar existing models.Roleif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.RoleNotFoundError{}+ return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))}- return fmt.Errorf("failed to load role: %w", err)+ return errors.WrapIf(err, "failed to load role")}if existing.BuiltIn {- return &common.RoleBuiltInError{}+ return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified"))}if name != existing.Name {var conflict int64if err := tx.Model(&models.Role{}).Where("name = ? AND id <> ?", name, id).Count(&conflict).Error; err != nil {- return fmt.Errorf("failed to check role name uniqueness: %w", err)+ return errors.WrapIf(err, "failed to check role name uniqueness")}if conflict > 0 {- return &common.RoleNameTakenError{}+ return common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))}}existing.Name = nameexisting.Description = descriptionexisting.Permissions = models.StringSlice(permissions)if err := tx.Save(&existing).Error; err != nil {- return fmt.Errorf("failed to update role: %w", err)+ return errors.WrapIf(err, "failed to update role")}out = existingreturn nil@@ -382,22 +384,25 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {var existing models.Roleif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.RoleNotFoundError{}+ return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))}- return fmt.Errorf("failed to load role: %w", err)+ return errors.WrapIf(err, "failed to load role")}if existing.BuiltIn {- return &common.RoleBuiltInError{}+ return common.Classify(common.ErrRoleBuiltIn,++ // Collect users affected before the delete so we can invalidate their caches.+ errors.New("Built-in role cannot be modified"))}- // Collect users affected before the delete so we can invalidate their caches.+if err := tx.Model(&models.UserRoleAssignment{}).Where("role_id = ?", id).Distinct("user_id").Pluck("user_id", &affected).Error; err != nil {- return fmt.Errorf("failed to list affected users: %w", err)+ return errors.WrapIf(err, "failed to list affected users")}if err := tx.Delete(&models.Role{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete role: %w", err)+ return errors.WrapIf(err, "failed to delete role")}return nil})@@ -422,7 +427,7 @@ func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID strinDistinct("user_id").Where("role_id = ?", roleID).Count(&count).Error; err != nil {- return 0, fmt.Errorf("failed to count users assigned to role: %w", err)+ return 0, errors.WrapIf(err, "failed to count users assigned to role")}return int(count), nil}@@ -435,7 +440,7 @@ func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([Where("user_id = ?", userID).Order("source ASC, role_id ASC").Find(&out).Error; err != nil {- return nil, fmt.Errorf("failed to list user assignments: %w", err)+ return nil, errors.WrapIf(err, "failed to list user assignments")}return out, nil}@@ -457,11 +462,11 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contex}if err := tx.Where("user_id = ? AND source = ?", userID, source).Delete(&models.UserRoleAssignment{}).Error; err != nil {- return fmt.Errorf("failed to clear %s assignments: %w", source, err)+ return errors.WrapIff(err, "failed to clear %s assignments", source)}if len(desired) > 0 {if err := tx.Create(&desired).Error; err != nil {- return fmt.Errorf("failed to insert %s assignments: %w", source, err)+ return errors.WrapIff(err, "failed to insert %s assignments", source)}}count, err := s.countEffectiveGlobalAdminsInternal(ctx, tx, "")@@ -469,7 +474,7 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contexreturn err}if count == 0 {- return &common.NoGlobalAdminRemainsError{}+ return common.Classify(common.ErrNoGlobalAdminRemains, errors.New("At least one user must retain a global Admin role assignment"))}return nil})@@ -508,7 +513,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi}var found []stringif err := tx.Model(&models.Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {- return fmt.Errorf("failed to verify role ids: %w", err)+ return errors.WrapIf(err, "failed to verify role ids")}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -516,7 +521,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi}for id := range roleIDSet {if _, ok := foundSet[id]; !ok {- return &common.InvalidRoleAssignmentError{RoleID: id}+ return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: role %q does not exist", id))}}}@@ -528,7 +533,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi}var found []stringif err := tx.Model(&models.Environment{}).Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {- return fmt.Errorf("failed to verify environment ids: %w", err)+ return errors.WrapIf(err, "failed to verify environment ids")}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -536,7 +541,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi}for id := range envIDSet {if _, ok := foundSet[id]; !ok {- return &common.InvalidRoleAssignmentError{EnvironmentID: id}+ return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: environment %q does not exist", id))}}}@@ -577,7 +582,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, txquery = query.Where("u.id <> ?", excludedUserID)}if err := query.Scan(&rows).Error; err != nil {- return 0, fmt.Errorf("failed to list global role permissions for admin count: %w", err)+ return 0, errors.WrapIf(err, "failed to list global role permissions for admin count")}permissionsByUser := make(map[string]*authz.PermissionSet, len(rows))@@ -589,7 +594,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, tx}perms, err := decodePermissionsJSONInternal(r.Permissions)if err != nil {- return 0, fmt.Errorf("failed to decode role permissions: %w", err)+ return 0, errors.WrapIf(err, "failed to decode role permissions")}ps.AddGlobal(perms...)}@@ -636,13 +641,13 @@ func (s *RoleService) resolveUserPermissionsInternal(_ context.Context, tx *gormJoins("INNER JOIN roles r ON r.id = ura.role_id").Where("ura.user_id = ?", userID).Scan(&rows).Error; err != nil {- return nil, fmt.Errorf("failed to resolve user permissions: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve user permissions")}ps := authz.NewPermissionSet()for _, r := range rows {perms, err := decodePermissionsJSONInternal(r.Permissions)if err != nil {- return nil, fmt.Errorf("failed to decode role permissions: %w", err)+ return nil, errors.WrapIf(err, "failed to decode role permissions")}if r.EnvironmentID == nil {ps.AddGlobal(perms...)@@ -674,7 +679,7 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID str}var perms []models.ApiKeyPermissionif err := s.db.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Find(&perms).Error; err != nil {- return nil, fmt.Errorf("failed to resolve api key permissions: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve api key permissions")}ps := authz.NewPermissionSet()for _, p := range perms {@@ -707,11 +712,11 @@ func (s *RoleService) setApiKeyPermissionsInternal(ctx context.Context, tx *gormgrants[i].ApiKeyID = apiKeyID}if err := tx.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Delete(&models.ApiKeyPermission{}).Error; err != nil {- return fmt.Errorf("failed to clear api key permissions: %w", err)+ return errors.WrapIf(err, "failed to clear api key permissions")}if len(grants) > 0 {if err := tx.WithContext(ctx).Create(&grants).Error; err != nil {- return fmt.Errorf("failed to insert api key permissions: %w", err)+ return errors.WrapIf(err, "failed to insert api key permissions")}}return nil@@ -722,13 +727,13 @@ func (s *RoleService) setApiKeyPermissionsInternal(ctx context.Context, tx *gormfunc (s *RoleService) ListOidcMappings(ctx context.Context) ([]models.OidcRoleMapping, error) {var out []models.OidcRoleMappingif err := s.db.WithContext(ctx).Order("claim_value, role_id").Find(&out).Error; err != nil {- return nil, fmt.Errorf("failed to list oidc mappings: %w", err)+ return nil, errors.WrapIf(err, "failed to list oidc mappings")}return out, nil}func (s *RoleService) GetOidcMapping(ctx context.Context, id string) (*models.OidcRoleMapping, error) {- return dbutil.FirstWhere[models.OidcRoleMapping](ctx, s.db.DB, &common.OidcMappingNotFoundError{}, "id = ?", id)+ return dbutil.FirstWhere[models.OidcRoleMapping](ctx, s.db.DB, common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found")), "id = ?", id)}func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error) {@@ -752,7 +757,7 @@ func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleIDSource: models.OidcMappingSourceManual,}if err := tx.Create(&mapping).Error; err != nil {- return fmt.Errorf("failed to create oidc mapping: %w", err)+ return errors.WrapIf(err, "failed to create oidc mapping")}return nil})@@ -776,12 +781,12 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolvar existing models.OidcRoleMappingif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.OidcMappingNotFoundError{}+ return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}- return fmt.Errorf("failed to load mapping: %w", err)+ return errors.WrapIf(err, "failed to load mapping")}if existing.Source == models.OidcMappingSourceEnv {- return &common.OidcMappingEnvManagedError{}+ return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))}if err := validateRoleIDsExistInternal(tx, []string{roleID}); err != nil {return err@@ -790,7 +795,7 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolexisting.RoleID = roleIDexisting.EnvironmentID = environmentIDif err := tx.Save(&existing).Error; err != nil {- return fmt.Errorf("failed to update mapping: %w", err)+ return errors.WrapIf(err, "failed to update mapping")}out = existingreturn nil@@ -819,7 +824,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {}var found []stringif err := tx.Model(&models.Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {- return fmt.Errorf("failed to verify role ids: %w", err)+ return errors.WrapIf(err, "failed to verify role ids")}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -827,7 +832,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {}for _, id := range normalized {if _, ok := foundSet[id]; !ok {- return &common.InvalidRoleAssignmentError{RoleID: id}+ return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: role %q does not exist", id))}}return nil@@ -838,15 +843,15 @@ func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {var existing models.OidcRoleMappingif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.OidcMappingNotFoundError{}+ return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}- return fmt.Errorf("failed to load mapping: %w", err)+ return errors.WrapIf(err, "failed to load mapping")}if existing.Source == models.OidcMappingSourceEnv {- return &common.OidcMappingEnvManagedError{}+ return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))}if err := tx.Delete(&models.OidcRoleMapping{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete mapping: %w", err)+ return errors.WrapIf(err, "failed to delete mapping")}return nil})@@ -870,14 +875,14 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri}var specs []roletypes.OidcRoleMappingSpecif err := json.Unmarshal([]byte(rawSpec), &specs); err != nil {- return fmt.Errorf("invalid OIDC_ROLE_MAPPINGS JSON: %w", err)+ return errors.WrapIf(err, "invalid OIDC_ROLE_MAPPINGS JSON")}for i, sp := range specs {if strings.TrimSpace(sp.ClaimValue) == "" {- return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: claimValue is required", i)+ return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: claimValue is required", i)}if strings.TrimSpace(sp.RoleID) == "" {- return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: roleId is required", i)+ return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: roleId is required", i)}}@@ -887,17 +892,17 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec strifor i, sp := range specs {var count int64if err := tx.Model(&models.Role{}).Where("id = ?", sp.RoleID).Count(&count).Error; err != nil {- return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: failed to verify role: %w", i, err)+ return errors.WrapIff(err, "OIDC_ROLE_MAPPINGS[%d]: failed to verify role", i)}if count == 0 {- return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: role %q does not exist", i, sp.RoleID)+ return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: role %q does not exist", i, sp.RoleID)}}// Declarative replace: drop every env-managed row, then insert the new// set. Manual rows are untouched.if err := tx.Where("source = ?", models.OidcMappingSourceEnv).Delete(&models.OidcRoleMapping{}).Error; err != nil {- return fmt.Errorf("failed to clear env-managed mappings: %w", err)+ return errors.WrapIf(err, "failed to clear env-managed mappings")}if len(specs) == 0 {slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled (empty)", "envManagedCount", 0)@@ -913,7 +918,7 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri}}if err := tx.Create(&rows).Error; err != nil {- return fmt.Errorf("failed to insert env-managed mappings: %w", err)+ return errors.WrapIf(err, "failed to insert env-managed mappings")}slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled", "envManagedCount", len(rows))return nil@@ -956,7 +961,9 @@ func (s *RoleService) invalidateUsersAssignedToInternal(ctx context.Context, rolfunc validatePermissionsInternal(perms []string) error {for _, p := range perms {if !authz.IsKnownPermission(p) {- return &common.UnknownPermissionError{Perm: p}+ return common.Classify(common.ErrUnknownPermission, errors.New("Unknown permission: "+++ p))}}return nil@@ -1006,14 +1013,18 @@ func validatePermissionSetAgainstCallerInternal(caller *authz.PermissionSet, desif len(desired) == 0 {return nil}- return &common.RolePermissionEscalationError{Perm: desired[0]}+ return common.Classify(common.ErrRolePermissionEscalation, errors.New("cannot grant a permission you do not hold: "+++ desired[0]))}if caller.Sudo {return nil}for _, p := range desired {if !caller.Allows(p, environmentID) {- return &common.RolePermissionEscalationError{Perm: p}+ return common.Classify(common.ErrRolePermissionEscalation, errors.New("cannot grant a permission you do not hold: "+++ p))}}return nildiff --git a/backend/internal/services/role_service_test.go b/backend/internal/services/role_service_test.goindex 6006b4d37..84385bcae 100644--- a/backend/internal/services/role_service_test.go+++ b/backend/internal/services/role_service_test.go@@ -5,6 +5,7 @@ import ("slices""testing"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -51,7 +52,7 @@ func TestValidatePermissionsAgainstCallerRejectsEscalation(t *testing.T) {authz.PermUsersDelete,})require.Error(t, err)- require.True(t, common.IsRolePermissionEscalationError(err))+ require.True(t, errors.Is(err, common.ErrRolePermissionEscalation))require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermRolesRead}))require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{authz.PermUsersDelete}))@@ -65,7 +66,7 @@ func TestValidatePermissionsAgainstCallerRejectsEnvOnlyGrantForGlobalRole(t *teserr := roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermContainersStart})require.Error(t, err)- require.True(t, common.IsRolePermissionEscalationError(err))+ require.True(t, errors.Is(err, common.ErrRolePermissionEscalation))}func TestValidatePermissionsAgainstCallerRejectsUnknownPermissionBeforeEscalation(t *testing.T) {@@ -76,8 +77,8 @@ func TestValidatePermissionsAgainstCallerRejectsUnknownPermissionBeforeEscalatio// not as an opaque escalation 403 or a silent pass.err := roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{"containrs:start"})require.Error(t, err)- require.True(t, common.IsUnknownPermissionError(err))- require.False(t, common.IsRolePermissionEscalationError(err))+ require.True(t, errors.Is(err, common.ErrUnknownPermission))+ require.False(t, errors.Is(err, common.ErrRolePermissionEscalation))}func TestBackfillLegacyRoleAssignmentsIsNoOpWhenColumnAbsent(t *testing.T) {@@ -174,7 +175,7 @@ func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {{RoleID: "role_does_not_exist"},})require.Error(t, err)- require.True(t, common.IsInvalidRoleAssignmentError(err))+ require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))}func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {@@ -186,7 +187,7 @@ func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {{RoleID: "role_does_not_exist"},})require.Error(t, err)- require.True(t, common.IsInvalidRoleAssignmentError(err))+ require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))}func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {@@ -201,7 +202,7 @@ func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &missingEnv},})require.Error(t, err)- require.True(t, common.IsInvalidRoleAssignmentError(err))+ require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))}func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T) {@@ -222,7 +223,7 @@ func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T)err = roleSvc.SetUserAssignments(ctx, user.ID, nil)require.Error(t, err)- require.True(t, common.IsNoGlobalAdminRemainsError(err))+ require.True(t, errors.Is(err, common.ErrNoGlobalAdminRemains))}func TestEffectiveGlobalAdminCountIgnoresEnvScopedAndServiceAccounts(t *testing.T) {diff --git a/backend/internal/services/session_service.go b/backend/internal/services/session_service.goindex 27b948d9a..7042fb13b 100644--- a/backend/internal/services/session_service.go+++ b/backend/internal/services/session_service.go@@ -5,11 +5,11 @@ import ("crypto/sha256""crypto/subtle""encoding/hex"- "errors"- "fmt""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"@@ -43,7 +43,7 @@ func (s *SessionService) CreateSession(ctx context.Context, userID string, expir}if err := s.db.WithContext(ctx).Create(session).Error; err != nil {- return nil, "", fmt.Errorf("failed to create user session: %w", err)+ return nil, "", errors.WrapIf(err, "failed to create user session")}return session, refreshJTI, nil@@ -63,7 +63,7 @@ func (s *SessionService) CreateFederatedSession(ctx context.Context, userID stri}if err := s.db.WithContext(ctx).Create(session).Error; err != nil {- return nil, fmt.Errorf("failed to create federated user session: %w", err)+ return nil, errors.WrapIf(err, "failed to create federated user session")}return session, nil@@ -79,7 +79,7 @@ func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrInvalidToken}- return nil, fmt.Errorf("failed to get user session: %w", err)+ return nil, errors.WrapIf(err, "failed to get user session")}return &session, nil}@@ -101,7 +101,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID strinif errors.Is(err, gorm.ErrRecordNotFound) {return ErrInvalidToken}- return fmt.Errorf("failed to get user session for rotation: %w", err)+ return errors.WrapIf(err, "failed to get user session for rotation")}if err := validateSessionActiveInternal(&session); err != nil {return err@@ -121,7 +121,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID strinWhere("id = ? AND refresh_token_hash = ? AND revoked_at IS NULL", session.ID, session.RefreshTokenHash).Updates(updates)if result.Error != nil {- return fmt.Errorf("failed to rotate refresh token: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to rotate refresh token")}if result.RowsAffected != 1 {return ErrInvalidToken@@ -151,7 +151,7 @@ func (s *SessionService) RevokeSession(ctx context.Context, sessionID string) erif err := s.db.WithContext(ctx).Model(&models.UserSession{}).Where("id = ? AND revoked_at IS NULL", sessionID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return fmt.Errorf("failed to revoke user session: %w", err)+ return errors.WrapIf(err, "failed to revoke user session")}return nil}@@ -163,7 +163,7 @@ func (s *SessionService) DeleteExpiredSessions(ctx context.Context, revokedRetenWhere("expires_at < ? OR (revoked_at IS NOT NULL AND revoked_at < ?)", now, revokedCutoff).Delete(&models.UserSession{})if result.Error != nil {- return 0, fmt.Errorf("failed to delete expired user sessions: %w", result.Error)+ return 0, errors.WrapIf(result.Error, "failed to delete expired user sessions")}return result.RowsAffected, nil}@@ -187,7 +187,7 @@ func (s *SessionService) RevokeAllUserSessionsExcept(ctx context.Context, userIDquery = query.Where("id <> ?", exceptSessionID)}if err := query.Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return fmt.Errorf("failed to revoke user sessions: %w", err)+ return errors.WrapIf(err, "failed to revoke user sessions")}return nil}diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.goindex 186656d3b..ce4595b43 100644--- a/backend/internal/services/settings_service.go+++ b/backend/internal/services/settings_service.go@@ -4,7 +4,6 @@ import ("context""crypto/sha256""encoding/base64"- "errors""fmt""log/slog""os"@@ -16,6 +15,8 @@ import ("sync/atomic""time"+ "emperror.dev/errors"+"github.com/google/uuid""github.com/samber/mo""gorm.io/gorm"@@ -62,12 +63,12 @@ func NewSettingsService(ctx context.Context, db *database.DB) (*SettingsService,err := svc.LoadDatabaseSettings(ctx)if err != nil {- return nil, fmt.Errorf("failed to load settings: %w", err)+ return nil, errors.WrapIf(err, "failed to load settings")}err = svc.setupInstanceID(ctx)if err != nil {- return nil, fmt.Errorf("failed to setup instance ID: %w", err)+ return nil, errors.WrapIf(err, "failed to setup instance ID")}return svc, nil@@ -95,7 +96,7 @@ func (s *SettingsService) LoadDatabaseSettings(ctx context.Context) (err error)func (s *SettingsService) refreshSettingsCacheInternal(ctx context.Context) error {if err := s.LoadDatabaseSettings(ctx); err != nil {- return fmt.Errorf("failed to refresh settings cache: %w", err)+ return errors.WrapIf(err, "failed to refresh settings cache")}return nil@@ -233,14 +234,14 @@ func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *WithContext(queryCtx).Find(&loaded).Errorif err != nil {- return nil, fmt.Errorf("failed to load configuration from the database: %w", err)+ return nil, errors.WrapIf(err, "failed to load configuration from the database")}for _, v := range loaded {err = dest.UpdateField(v.Key, v.Value, false)if err != nil && !errors.Is(err, models.SettingKeyNotFoundError{}) {- return nil, fmt.Errorf("failed to process settings for key '%s': %w", v.Key, err)+ return nil, errors.WrapIff(err, "failed to process settings for key '%s'", v.Key)}}@@ -256,7 +257,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat// Fetch all settings once to avoid N+1 queries for internal keysvar allSettings []models.SettingVariableif err := db.WithContext(ctx).Find(&allSettings).Error; err != nil {- return nil, fmt.Errorf("failed to load settings for env config: %w", err)+ return nil, errors.WrapIf(err, "failed to load settings for env config")}settingsMap := make(map[string]string, len(allSettings))for _, s := range allSettings {@@ -496,7 +497,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa}if err := cfg.UpdateField(key, value, false); err != nil {- return nil, false, false, false, false, false, nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)+ return nil, false, false, false, false, false, nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)}valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: key, Value: value})@@ -508,7 +509,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa}if err := libarcane.ValidateCronSetting(key, value); err != nil {- return nil, false, false, false, false, false, nil, fmt.Errorf("invalid cron expression for %s: %w", key, err)+ return nil, false, false, false, false, false, nil, errors.WrapIff(err, "invalid cron expression for %s", key)}if key == "accentColor" && value != "" && value != "default" && !settings.SafeAccentColor.MatchString(value) {@@ -531,7 +532,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defacontinue}if err != nil {- return nil, false, false, false, false, false, nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)+ return nil, false, false, false, false, false, nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)}valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: key, Value: valueToSave})@@ -580,7 +581,7 @@ func (s *SettingsService) persistSettings(ctx context.Context, values []models.Sreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {for _, setting := range values {if err := tx.Save(&setting).Error; err != nil {- return fmt.Errorf("failed to update setting %s: %w", setting.Key, err)+ return errors.WrapIff(err, "failed to update setting %s", setting.Key)}}return nil@@ -596,7 +597,7 @@ func (s *SettingsService) handleOidcConfigUpdate(ctx context.Context, updates seif secret == "" {current, err := s.GetSettings(ctx)if err != nil {- return fmt.Errorf("failed to load current settings for secret: %w", err)+ return errors.WrapIf(err, "failed to load current settings for secret")}if current.OidcClientSecret.Value != "" {// Keep existing secret, don't update@@ -605,7 +606,7 @@ func (s *SettingsService) handleOidcConfigUpdate(ctx context.Context, updates se}if err := s.updateSettingValueNoRefreshInternal(ctx, "oidcClientSecret", secret); err != nil {- return fmt.Errorf("failed to update oidcClientSecret: %w", err)+ return errors.WrapIf(err, "failed to update oidcClientSecret")}}@@ -624,13 +625,13 @@ func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {switch {case errors.Is(err, gorm.ErrRecordNotFound):if err := tx.Create(&defaultSetting).Error; err != nil {- return fmt.Errorf("failed to create default setting %s: %w", defaultSetting.Key, err)+ return errors.WrapIff(err, "failed to create default setting %s", defaultSetting.Key)}case err != nil:- return fmt.Errorf("failed to check for existing setting %s: %w", defaultSetting.Key, err)+ return errors.WrapIff(err, "failed to check for existing setting %s", defaultSetting.Key)case defaultSetting.Key == "trivyImage" && existing.Value != defaultSetting.Value:if err := tx.Model(&existing).Update("value", defaultSetting.Value).Error; err != nil {- return fmt.Errorf("failed to enforce default setting %s: %w", defaultSetting.Key, err)+ return errors.WrapIff(err, "failed to enforce default setting %s", defaultSetting.Key)}}}@@ -655,7 +656,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {result := s.db.WithContext(ctx).Where("key NOT IN ?", keys).Delete(&models.SettingVariable{})if result.Error != nil {- return fmt.Errorf("failed to prune unknown settings: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to prune unknown settings")}if result.RowsAffected > 0 {@@ -745,15 +746,15 @@ func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, keycase errors.Is(err, gorm.ErrRecordNotFound):newVar := models.SettingVariable{Key: key, Value: envVal}if err := tx.Create(&newVar).Error; err != nil {- return fmt.Errorf("persist env setting %s: %w", key, err)+ return errors.WrapIff(err, "persist env setting %s", key)}slog.DebugContext(ctx, "Created setting from environment", "key", key)case err != nil:- return fmt.Errorf("check setting %s: %w", key, err)+ return errors.WrapIff(err, "check setting %s", key)default:if existing.Value != envVal {if err := tx.Model(&existing).Update("value", envVal).Error; err != nil {- return fmt.Errorf("update env setting %s: %w", key, err)+ return errors.WrapIff(err, "update env setting %s", key)}slog.DebugContext(ctx, "Updated setting from environment", "key", key)}@@ -794,12 +795,12 @@ func (s *SettingsService) setupInstanceID(ctx context.Context) error {createdInstanceID, err := uuid.NewRandom()if err != nil {- return fmt.Errorf("failed to created a new instance ID: %w", err)+ return errors.WrapIf(err, "failed to created a new instance ID")}err = s.UpdateSetting(ctx, "instanceId", createdInstanceID.String())if err != nil {- return fmt.Errorf("failed to set instance ID in database: %w", err)+ return errors.WrapIf(err, "failed to set instance ID in database")}return nil@@ -887,7 +888,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erroerr := tx.Where("key = ?", keyName).First(&sv).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return fmt.Errorf("failed to load encryption key: %w", err)+ return errors.WrapIf(err, "failed to load encryption key")}// If already present and non-empty, return it@@ -901,7 +902,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erro// Generate uuid -> sha256 -> base64 key (32 bytes raw -> 44 chars base64)u, genErr := uuid.NewRandom()if genErr != nil {- return fmt.Errorf("failed to generate encryption key: %w", genErr)+ return errors.WrapIf(genErr, "failed to generate encryption key")}sum := sha256.Sum256([]byte(u.String()))generatedKey := base64.StdEncoding.EncodeToString(sum[:])@@ -909,7 +910,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erroif notFound {if createErr := tx.Create(&models.SettingVariable{Key: keyName, Value: generatedKey}).Error; createErr != nil {- return fmt.Errorf("failed to persist encryption key: %w", createErr)+ return errors.WrapIf(createErr, "failed to persist encryption key")}return nil}@@ -918,7 +919,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erroif updErr := tx.Model(&models.SettingVariable{}).Where("key = ?", keyName).Update("value", generatedKey).Error; updErr != nil {- return fmt.Errorf("failed to update encryption key: %w", updErr)+ return errors.WrapIf(updErr, "failed to update encryption key")}return nil})@@ -944,7 +945,7 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projec}if err != nil {- return fmt.Errorf("failed to load projectsDirectory setting: %w", err)+ return errors.WrapIf(err, "failed to load projectsDirectory setting")}value := strings.TrimSpace(projectsDirSetting.Value)@@ -965,12 +966,12 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projeccwd, _ := os.Getwd()absPath, absErr := filepath.Abs(value)if absErr != nil {- return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)+ return errors.WrapIf(absErr, "failed to resolve relative path to absolute")}slog.InfoContext(ctx, "Normalizing projects directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)if err := s.UpdateSetting(ctx, "projectsDirectory", absPath); err != nil {- return fmt.Errorf("failed to update projectsDirectory: %w", err)+ return errors.WrapIf(err, "failed to update projectsDirectory")}slog.InfoContext(ctx, "Successfully normalized projects directory")@@ -998,7 +999,7 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {}if err != nil {- return fmt.Errorf("failed to load buildsDirectory setting: %w", err)+ return errors.WrapIf(err, "failed to load buildsDirectory setting")}value := strings.TrimSpace(buildsDirSetting.Value)@@ -1011,12 +1012,12 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {cwd, _ := os.Getwd()absPath, absErr := filepath.Abs(value)if absErr != nil {- return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)+ return errors.WrapIf(absErr, "failed to resolve relative path to absolute")}slog.InfoContext(ctx, "Normalizing builds directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)if err := s.UpdateSetting(ctx, buildsKey, absPath); err != nil {- return fmt.Errorf("failed to update buildsDirectory: %w", err)+ return errors.WrapIf(err, "failed to update buildsDirectory")}slog.InfoContext(ctx, "Successfully normalized builds directory")diff --git a/backend/internal/services/swarm_service.go b/backend/internal/services/swarm_service.goindex 67fd43e53..418fb20e1 100644--- a/backend/internal/services/swarm_service.go+++ b/backend/internal/services/swarm_service.go@@ -5,7 +5,7 @@ import ("context"stdjson "encoding/json"json "encoding/json/v2"- "errors"+ stderrors "errors""fmt""io/fs""log/slog"@@ -19,6 +19,7 @@ import ("syscall""time"+ "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -103,7 +104,7 @@ func (s *SwarmService) IsEnabled(ctx context.Context) (bool, error) {enabled, err := s.kvService.GetBool(ctx, KVKeySwarmEnabled, false)if err != nil {- return false, fmt.Errorf("failed to read swarm enabled state: %w", err)+ return false, errors.WrapIf(err, "failed to read swarm enabled state")}return enabled, nil@@ -116,19 +117,19 @@ func (s *SwarmService) ListServicesPaginated(ctx context.Context, params paginatdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{Status: true})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")}services := servicesResult.Items// Fetch nodes to resolve node IDs to hostnamesnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")}nodes := nodesResult.ItemsnodeNameByID := make(map[string]string, len(nodes))@@ -139,7 +140,7 @@ func (s *SwarmService) ListServicesPaginated(ctx context.Context, params paginat// Fetch networks to resolve network IDs to namesnetworksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list networks: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list networks")}networks := networksResult.ItemsnetworkNameByID := make(map[string]string, len(networks))@@ -150,7 +151,7 @@ func (s *SwarmService) ListServicesPaginated(ctx context.Context, params paginat// Fetch tasks and group running tasks by service IDtasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm tasks")}tasks := tasksResult.ItemsserviceNodes := make(map[string]map[string]struct{})@@ -193,12 +194,12 @@ func (s *SwarmService) GetService(ctx context.Context, serviceID string) (*swarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm service")}service := serviceResult.Service@@ -352,13 +353,13 @@ func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.ServicedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}// Unmarshal spec from JSONvar spec swarm.ServiceSpecif err := json.Unmarshal(req.Spec, &spec); err != nil {- return nil, fmt.Errorf("failed to parse service spec: %w", err)+ return nil, errors.WrapIf(err, "failed to parse service spec")}optionsPayload := swarmtypes.ServiceCreateOptions{}@@ -375,7 +376,7 @@ func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.ServiceQueryRegistry: optionsPayload.QueryRegistry,})if err != nil {- return nil, fmt.Errorf("failed to create swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to create swarm service")}return &swarmtypes.ServiceCreateResponse{@@ -391,14 +392,14 @@ func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, reqdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}versionIndex := req.Versionif versionIndex == 0 {serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm service")}versionIndex = serviceResult.Service.Version.Index}@@ -420,7 +421,7 @@ func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, reqQueryRegistry: optionsPayload.QueryRegistry,})if err != nil {- return nil, fmt.Errorf("failed to update swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to update swarm service")}return &swarmtypes.ServiceUpdateResponse{@@ -435,11 +436,11 @@ func (s *SwarmService) RemoveService(ctx context.Context, serviceID string) errodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.ServiceRemove(ctx, serviceID, dockerclient.ServiceRemoveOptions{}); err != nil {- return fmt.Errorf("failed to remove swarm service: %w", err)+ return errors.WrapIf(err, "failed to remove swarm service")}return nil@@ -452,7 +453,7 @@ func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}options := dockerclient.ServiceLogsOptions{@@ -467,7 +468,7 @@ func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string,logs, err := dockerClient.ServiceLogs(ctx, serviceID, options)if err != nil {- return fmt.Errorf("failed to get service logs: %w", err)+ return errors.WrapIf(err, "failed to get service logs")}defer func() { _ = logs.Close() }()@@ -485,7 +486,7 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID strData []swarmtypes.NodeSummary `json:"data"`}if err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/swarm/nodes?limit=-1", nil, &remote); err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list remote swarm nodes: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list remote swarm nodes")}if !remote.Success {return nil, pagination.Response{}, errors.New("remote swarm node listing failed")@@ -502,12 +503,12 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID strdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")}nodes := nodesResult.Items@@ -533,7 +534,7 @@ func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID string}remotePath := "/api/environments/0/swarm/nodes/" + nodeIDif err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, remotePath, nil, &remote); err != nil {- return nil, fmt.Errorf("failed to inspect remote swarm node: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect remote swarm node")}if !remote.Success {return nil, errors.New("remote swarm node inspection failed")@@ -549,12 +550,12 @@ func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID stringdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm node: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm node")}items := []swarmtypes.NodeSummary{swarmtypes.NewNodeSummary(nodeResult.Node)}@@ -616,7 +617,7 @@ func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nreturn nil, errors.New("environment did not report an active swarm identity")}if strings.TrimSpace(runtime.identity.SwarmNodeID) != strings.TrimSpace(nodeID) {- return nil, fmt.Errorf("environment reports swarm node %s instead of %s", runtime.identity.SwarmNodeID, nodeID)+ return nil, errors.Errorf("environment reports swarm node %s instead of %s", runtime.identity.SwarmNodeID, nodeID)}bound, err := s.environmentService.BindSwarmNodeEnvironment(ctx, parentEnvironmentID, nodeID, request.EnvironmentID, request.Rebind)@@ -629,12 +630,12 @@ func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nfunc (s *SwarmService) GetLocalNodeIdentity(ctx context.Context) (*SwarmNodeIdentity, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect local Docker engine: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect local Docker engine")}swarmInfo := infoResult.Info@@ -932,7 +933,7 @@ func (s *SwarmService) getSwarmJoinTokensForEnvironmentInternal(ctx context.ContData swarmtypes.SwarmJoinTokensResponse `json:"data"`}if err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/swarm/join-tokens", nil, &response); err != nil {- return nil, fmt.Errorf("failed to get remote swarm join tokens: %w", err)+ return nil, errors.WrapIf(err, "failed to get remote swarm join tokens")}if !response.Success {return nil, errors.New("remote swarm join-token request failed")@@ -1131,12 +1132,12 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")}services := servicesResult.Items@@ -1147,7 +1148,7 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")}nodes := nodesResult.Items@@ -1158,7 +1159,7 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationtasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm tasks")}tasks := tasksResult.Items@@ -1181,12 +1182,12 @@ func (s *SwarmService) ListStacksPaginated(ctx context.Context, environmentID stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")}services := servicesResult.Items@@ -1254,7 +1255,7 @@ func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, redockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}_, stackSourceDir, err := s.resolveSwarmStackSourceDirInternal(ctx, environmentID, stackName)@@ -1303,12 +1304,12 @@ func (s *SwarmService) GetSwarmInfo(ctx context.Context) (*swarmtypes.SwarmInfo,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm")}return new(swarmtypes.NewSwarmInfo(infoResult.Swarm)), nil@@ -1317,7 +1318,7 @@ func (s *SwarmService) GetSwarmInfo(ctx context.Context) (*swarmtypes.SwarmInfo,func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitRequest) (*swarmtypes.SwarmInitResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}spec, err := decodeSwarmSpecInternal(req.Spec)@@ -1329,7 +1330,7 @@ func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitRefor _, raw := range req.DefaultAddrPool {prefix, err := netip.ParsePrefix(raw)if err != nil {- return nil, fmt.Errorf("failed to parse default address pool %q: %w", raw, err)+ return nil, errors.WrapIff(err, "failed to parse default address pool %q", raw)}defaultAddrPool = append(defaultAddrPool, prefix.Masked())}@@ -1347,7 +1348,7 @@ func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitReSubnetSize: req.SubnetSize,})if err != nil {- return nil, fmt.Errorf("failed to initialize swarm: %w", err)+ return nil, errors.WrapIf(err, "failed to initialize swarm")}s.persistSwarmEnabledStateInternal(ctx, true)@@ -1358,7 +1359,7 @@ func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitRefunc (s *SwarmService) JoinSwarm(ctx context.Context, req swarmtypes.SwarmJoinRequest) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.SwarmJoin(ctx, dockerclient.SwarmJoinOptions{@@ -1369,7 +1370,7 @@ func (s *SwarmService) JoinSwarm(ctx context.Context, req swarmtypes.SwarmJoinReJoinToken: req.JoinToken,Availability: req.Availability,}); err != nil {- return fmt.Errorf("failed to join swarm: %w", err)+ return errors.WrapIf(err, "failed to join swarm")}s.persistSwarmEnabledStateInternal(ctx, true)@@ -1384,11 +1385,11 @@ func (s *SwarmService) LeaveSwarm(ctx context.Context, req swarmtypes.SwarmLeavedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.SwarmLeave(ctx, dockerclient.SwarmLeaveOptions{Force: req.Force}); err != nil {- return fmt.Errorf("failed to leave swarm: %w", err)+ return errors.WrapIf(err, "failed to leave swarm")}s.persistSwarmEnabledStateInternal(ctx, false)@@ -1403,11 +1404,11 @@ func (s *SwarmService) UnlockSwarm(ctx context.Context, req swarmtypes.SwarmUnlodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.SwarmUnlock(ctx, dockerclient.SwarmUnlockOptions{Key: req.Key}); err != nil {- return fmt.Errorf("failed to unlock swarm: %w", err)+ return errors.WrapIf(err, "failed to unlock swarm")}return nil@@ -1420,12 +1421,12 @@ func (s *SwarmService) GetSwarmUnlockKey(ctx context.Context) (*swarmtypes.SwarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}unlockResult, err := dockerClient.SwarmGetUnlockKey(ctx)if err != nil {- return nil, fmt.Errorf("failed to get swarm unlock key: %w", err)+ return nil, errors.WrapIf(err, "failed to get swarm unlock key")}return &swarmtypes.SwarmUnlockKeyResponse{UnlockKey: unlockResult.Key}, nil@@ -1438,12 +1439,12 @@ func (s *SwarmService) GetSwarmJoinTokens(ctx context.Context) (*swarmtypes.SwardockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm")}return &swarmtypes.SwarmJoinTokensResponse{@@ -1459,12 +1460,12 @@ func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypesdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return fmt.Errorf("failed to inspect swarm: %w", err)+ return errors.WrapIf(err, "failed to inspect swarm")}rotateWorker := req.RotateWorkerToken@@ -1480,7 +1481,7 @@ func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypesRotateWorkerToken: rotateWorker,RotateManagerToken: rotateManager,}); err != nil {- return fmt.Errorf("failed to rotate swarm join tokens: %w", err)+ return errors.WrapIf(err, "failed to rotate swarm join tokens")}return nil@@ -1493,14 +1494,14 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}version := req.Versionif version == 0 {infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return fmt.Errorf("failed to inspect swarm: %w", err)+ return errors.WrapIf(err, "failed to inspect swarm")}version = infoResult.Swarm.Version.Index}@@ -1517,7 +1518,7 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmRotateManagerToken: req.RotateManagerToken,RotateManagerUnlockKey: req.RotateManagerUnlockKey,}); err != nil {- return fmt.Errorf("failed to update swarm spec: %w", err)+ return errors.WrapIf(err, "failed to update swarm spec")}return nil@@ -1540,12 +1541,12 @@ func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm service")}updateResult, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{@@ -1554,7 +1555,7 @@ func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*Rollback: "previous",})if err != nil {- return nil, fmt.Errorf("failed to rollback swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to rollback swarm service")}return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil@@ -1567,12 +1568,12 @@ func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, replidockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm service")}service := serviceResult.Service@@ -1585,7 +1586,7 @@ func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, repliSpec: service.Spec,})if err != nil {- return nil, fmt.Errorf("failed to scale swarm service: %w", err)+ return nil, errors.WrapIf(err, "failed to scale swarm service")}return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil@@ -1598,7 +1599,7 @@ func applySwarmServiceScaleInternal(mode *swarm.ServiceMode, replicas uint64) ercase mode.ReplicatedJob != nil:mode.ReplicatedJob.TotalCompletions = &replicasdefault:- return fmt.Errorf("scale can only be used with replicated or replicated-job mode: %w", cerrdefs.ErrInvalidArgument)+ return errors.WrapIf(cerrdefs.ErrInvalidArgument, "scale can only be used with replicated or replicated-job mode")}return nil@@ -1611,12 +1612,12 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})if err != nil {- return fmt.Errorf("failed to inspect swarm node: %w", err)+ return errors.WrapIf(err, "failed to inspect swarm node")}version := req.Version@@ -1642,7 +1643,7 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtVersion: swarm.Version{Index: version},Spec: spec,}); err != nil {- return fmt.Errorf("failed to update swarm node: %w", err)+ return errors.WrapIf(err, "failed to update swarm node")}return nil@@ -1655,11 +1656,11 @@ func (s *SwarmService) RemoveNode(ctx context.Context, nodeID string, force booldockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.NodeRemove(ctx, nodeID, dockerclient.NodeRemoveOptions{Force: force}); err != nil {- return fmt.Errorf("failed to remove swarm node: %w", err)+ return errors.WrapIf(err, "failed to remove swarm node")}return nil@@ -1690,7 +1691,7 @@ func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -1751,7 +1752,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif errors.Is(err, os.ErrNotExist) {return nil, cerrdefs.ErrNotFound}- return nil, fmt.Errorf("failed to read swarm stack compose source: %w", err)+ return nil, errors.WrapIf(err, "failed to read swarm stack compose source")}overrideContent := ""@@ -1759,7 +1760,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif err == nil {overrideContent = string(overrideBytes)} else if !errors.Is(err, os.ErrNotExist) {- return nil, fmt.Errorf("failed to read swarm stack override source: %w", err)+ return nil, errors.WrapIf(err, "failed to read swarm stack override source")}envContent := ""@@ -1767,7 +1768,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif err == nil {envContent = string(envBytes)} else if !errors.Is(err, os.ErrNotExist) {- return nil, fmt.Errorf("failed to read swarm stack env source: %w", err)+ return nil, errors.WrapIf(err, "failed to read swarm stack env source")}var files []swarmtypes.SyncFile@@ -1799,7 +1800,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackN})}if err != nil && !errors.Is(err, os.ErrNotExist) {- return nil, fmt.Errorf("failed to read additional swarm stack source files: %w", err)+ return nil, errors.WrapIf(err, "failed to read additional swarm stack source files")}return &swarmtypes.StackSource{@@ -1844,7 +1845,7 @@ func (s *SwarmService) listPersistedStackSourcesInternal(ctx context.Context, enif errors.Is(err, os.ErrNotExist) {return map[string]swarmtypes.StackSummary{}, nil}- return nil, fmt.Errorf("failed to list swarm stack source directories: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm stack source directories")}stacks := make(map[string]swarmtypes.StackSummary, len(entries))@@ -1882,7 +1883,7 @@ func (s *SwarmService) buildPersistedStackSourceSummaryInternal(stackSourceDir,if errors.Is(err, os.ErrNotExist) {return nil, cerrdefs.ErrNotFound}- return nil, fmt.Errorf("failed to stat swarm stack compose source: %w", err)+ return nil, errors.WrapIf(err, "failed to stat swarm stack compose source")}createdAt := composeInfo.ModTime()@@ -1897,7 +1898,7 @@ func (s *SwarmService) buildPersistedStackSourceSummaryInternal(stackSourceDir,updatedAt = envInfo.ModTime()}} else if !errors.Is(err, os.ErrNotExist) {- return nil, fmt.Errorf("failed to stat swarm stack env source: %w", err)+ return nil, errors.WrapIf(err, "failed to stat swarm stack env source")}return &swarmtypes.StackSummary{@@ -1922,7 +1923,7 @@ func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackNamedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -1971,7 +1972,7 @@ func (s *SwarmService) removeStackServicesInternal(ctx context.Context, dockerClfor _, service := range services {serviceIDs[service.ID] = struct{}{}if _, err := dockerClient.ServiceRemove(ctx, service.ID, dockerclient.ServiceRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {- return fmt.Errorf("failed to remove swarm service %s: %w", service.Spec.Name, err)+ return errors.WrapIff(err, "failed to remove swarm service %s", service.Spec.Name)}}@@ -1986,11 +1987,11 @@ func (s *SwarmService) removeStackConfigsInternal(ctx context.Context, dockerCliconfigFilter := make(dockerclient.Filters).Add("label", stackLabel)configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{Filters: configFilter})if err != nil {- return fmt.Errorf("failed to list stack configs: %w", err)+ return errors.WrapIf(err, "failed to list stack configs")}for _, cfg := range configsResult.Items {if _, err := dockerClient.ConfigRemove(ctx, cfg.ID, dockerclient.ConfigRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {- return fmt.Errorf("failed to remove stack config %s: %w", cfg.Spec.Name, err)+ return errors.WrapIff(err, "failed to remove stack config %s", cfg.Spec.Name)}}@@ -2001,11 +2002,11 @@ func (s *SwarmService) removeStackSecretsInternal(ctx context.Context, dockerClisecretFilter := make(dockerclient.Filters).Add("label", stackLabel)secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{Filters: secretFilter})if err != nil {- return fmt.Errorf("failed to list stack secrets: %w", err)+ return errors.WrapIf(err, "failed to list stack secrets")}for _, secret := range secretsResult.Items {if _, err := dockerClient.SecretRemove(ctx, secret.ID, dockerclient.SecretRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {- return fmt.Errorf("failed to remove stack secret %s: %w", secret.Spec.Name, err)+ return errors.WrapIff(err, "failed to remove stack secret %s", secret.Spec.Name)}}@@ -2016,14 +2017,14 @@ func (s *SwarmService) removeStackNetworksInternal(ctx context.Context, dockerClnetworkFilter := make(dockerclient.Filters).Add("label", stackLabel)networksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{Filters: networkFilter})if err != nil {- return fmt.Errorf("failed to list stack networks: %w", err)+ return errors.WrapIf(err, "failed to list stack networks")}for _, network := range networksResult.Items {if network.Ingress {continue}if _, err := dockerClient.NetworkRemove(ctx, network.ID, dockerclient.NetworkRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {- return fmt.Errorf("failed to remove stack network %s: %w", network.Name, err)+ return errors.WrapIff(err, "failed to remove stack network %s", network.Name)}}@@ -2037,7 +2038,7 @@ func (s *SwarmService) ListStackServicesPaginated(ctx context.Context, stackNamedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -2066,7 +2067,7 @@ func (s *SwarmService) ListStackTasksPaginated(ctx context.Context, stackName stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -2121,12 +2122,12 @@ func (s *SwarmService) ListConfigs(ctx context.Context) ([]swarmtypes.ConfigSummdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list swarm configs: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm configs")}items := make([]swarmtypes.ConfigSummary, 0, len(configsResult.Items))@@ -2143,12 +2144,12 @@ func (s *SwarmService) GetConfig(ctx context.Context, configID string) (*swarmtydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}cfgResult, err := dockerClient.ConfigInspect(ctx, configID, dockerclient.ConfigInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm config: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm config")}return new(swarmtypes.NewConfigSummary(cfgResult.Config)), nil@@ -2166,12 +2167,12 @@ func (s *SwarmService) CreateConfig(ctx context.Context, req swarmtypes.ConfigCrdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}createResult, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})if err != nil {- return nil, fmt.Errorf("failed to create swarm config: %w", err)+ return nil, errors.WrapIf(err, "failed to create swarm config")}return s.GetConfig(ctx, createResult.ID)@@ -2180,7 +2181,7 @@ func (s *SwarmService) CreateConfig(ctx context.Context, req swarmtypes.ConfigCrfunc (s *SwarmService) UpdateConfig(ctx context.Context, configID string, req swarmtypes.ConfigUpdateRequest) error {_ = configID_ = req- return &common.SwarmConfigImmutableError{}+ return common.Classify(common.ErrSwarmConfigImmutable, errors.New("Swarm configs are immutable; create a new config and update services to use it"))}func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) error {@@ -2190,11 +2191,11 @@ func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.ConfigRemove(ctx, configID, dockerclient.ConfigRemoveOptions{}); err != nil {- return fmt.Errorf("failed to remove swarm config: %w", err)+ return errors.WrapIf(err, "failed to remove swarm config")}return nil@@ -2207,12 +2208,12 @@ func (s *SwarmService) ListSecrets(ctx context.Context) ([]swarmtypes.SecretSummdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list swarm secrets: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm secrets")}items := make([]swarmtypes.SecretSummary, 0, len(secretsResult.Items))@@ -2229,12 +2230,12 @@ func (s *SwarmService) GetSecret(ctx context.Context, secretID string) (*swarmtydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}secretResult, err := dockerClient.SecretInspect(ctx, secretID, dockerclient.SecretInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect swarm secret: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect swarm secret")}return new(swarmtypes.NewSecretSummary(secretResult.Secret)), nil@@ -2252,12 +2253,12 @@ func (s *SwarmService) CreateSecret(ctx context.Context, req swarmtypes.SecretCrdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}createResult, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})if err != nil {- return nil, fmt.Errorf("failed to create swarm secret: %w", err)+ return nil, errors.WrapIf(err, "failed to create swarm secret")}return s.GetSecret(ctx, createResult.ID)@@ -2266,7 +2267,7 @@ func (s *SwarmService) CreateSecret(ctx context.Context, req swarmtypes.SecretCrfunc (s *SwarmService) UpdateSecret(ctx context.Context, secretID string, req swarmtypes.SecretUpdateRequest) error {_ = secretID_ = req- return &common.SwarmSecretImmutableError{}+ return common.Classify(common.ErrSwarmSecretImmutable, errors.New("Swarm secrets are immutable; create a new secret and update services to use it"))}func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) error {@@ -2276,11 +2277,11 @@ func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}if _, err := dockerClient.SecretRemove(ctx, secretID, dockerclient.SecretRemoveOptions{}); err != nil {- return fmt.Errorf("failed to remove swarm secret: %w", err)+ return errors.WrapIf(err, "failed to remove swarm secret")}return nil@@ -2289,12 +2290,12 @@ func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) errorfunc (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Context, filters dockerclient.Filters, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")}serviceNameByID := make(map[string]string, len(servicesResult.Items))@@ -2304,7 +2305,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.ContextnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")}nodeNameByID := make(map[string]string, len(nodesResult.Items))@@ -2317,7 +2318,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Context}tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{Filters: filters})if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm tasks")}items := make([]swarmtypes.TaskSummary, 0, len(tasksResult.Items))@@ -2334,7 +2335,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Contextfunc (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClient *dockerclient.Client, services []swarm.Service) ([]swarmtypes.ServiceSummary, error) {nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list swarm nodes: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm nodes")}nodeNameByID := make(map[string]string, len(nodesResult.Items))@@ -2344,7 +2345,7 @@ func (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClienetworksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list networks: %w", err)+ return nil, errors.WrapIf(err, "failed to list networks")}networkNameByID := make(map[string]string, len(networksResult.Items))@@ -2359,7 +2360,7 @@ func (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClietasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})if err != nil {- return nil, fmt.Errorf("failed to list swarm tasks: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm tasks")}serviceNodes := make(map[string]map[string]struct{})@@ -2406,7 +2407,7 @@ func (s *SwarmService) listStackServicesRawInternal(ctx context.Context, dockerCStatus: true,})if err != nil {- return nil, fmt.Errorf("failed to list stack services: %w", err)+ return nil, errors.WrapIf(err, "failed to list stack services")}return servicesResult.Items, nil@@ -2431,7 +2432,7 @@ func (s *SwarmService) waitForRemovedServiceTasksInternal(ctx context.Context, dfor {tasksResult, err := dockerClient.TaskList(waitCtx, dockerclient.TaskListOptions{Filters: taskFilters})if err != nil {- return fmt.Errorf("failed to list tasks while waiting for stack removal: %w", err)+ return errors.WrapIf(err, "failed to list tasks while waiting for stack removal")}hasActiveTasks := false@@ -2447,7 +2448,7 @@ func (s *SwarmService) waitForRemovedServiceTasksInternal(ctx context.Context, dselect {case <-waitCtx.Done():- return fmt.Errorf("timed out waiting for stack task convergence: %w", waitCtx.Err())+ return errors.WrapIf(waitCtx.Err(), "timed out waiting for stack task convergence")case <-ticker.C:}}@@ -2484,7 +2485,7 @@ func decodeConfigSpecInternal(raw stdjson.RawMessage) (swarm.ConfigSpec, error)var spec swarm.ConfigSpecif err := json.Unmarshal(raw, &spec); err != nil {- return swarm.ConfigSpec{}, fmt.Errorf("failed to parse config spec: %w", err)+ return swarm.ConfigSpec{}, errors.WrapIf(err, "failed to parse config spec")}if strings.TrimSpace(spec.Name) == "" {@@ -2502,7 +2503,7 @@ func decodeSwarmSpecInternal(raw stdjson.RawMessage) (swarm.Spec, error) {var spec swarm.Specif err := json.Unmarshal(trimmed, &spec); err != nil {- return swarm.Spec{}, fmt.Errorf("failed to parse swarm spec: %w", err)+ return swarm.Spec{}, errors.WrapIf(err, "failed to parse swarm spec")}if spec.Labels == nil {@@ -2528,7 +2529,7 @@ func decodeSecretSpecInternal(raw stdjson.RawMessage) (swarm.SecretSpec, error)var spec swarm.SecretSpecif err := json.Unmarshal(raw, &spec); err != nil {- return swarm.SecretSpec{}, fmt.Errorf("failed to parse secret spec: %w", err)+ return swarm.SecretSpec{}, errors.WrapIf(err, "failed to parse secret spec")}if strings.TrimSpace(spec.Name) == "" {@@ -2550,32 +2551,32 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmen}if err := os.MkdirAll(stackSourceDir, common.DirPerm); err != nil {- return fmt.Errorf("failed to create swarm stack source directory: %w", err)+ return errors.WrapIf(err, "failed to create swarm stack source directory")}if err := atomic.WriteFile(filepath.Join(stackSourceDir, swarmStackComposeFilename), []byte(composeContent), common.FilePerm); err != nil {- return fmt.Errorf("failed to write swarm stack compose source: %w", err)+ return errors.WrapIf(err, "failed to write swarm stack compose source")}overridePath := filepath.Join(stackSourceDir, swarmStackOverrideFilename)if overrideContent != "" {if err := atomic.WriteFile(overridePath, []byte(overrideContent), common.FilePerm); err != nil {- return fmt.Errorf("failed to write swarm stack override source: %w", err)+ return errors.WrapIf(err, "failed to write swarm stack override source")}} else {if err := os.Remove(overridePath); err != nil && !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("failed to clear swarm stack override source: %w", err)+ return errors.WrapIf(err, "failed to clear swarm stack override source")}}envPath := filepath.Join(stackSourceDir, swarmStackEnvFilename)if envContent != "" {if err := atomic.WriteFile(envPath, []byte(envContent), common.FilePerm); err != nil {- return fmt.Errorf("failed to write swarm stack env source: %w", err)+ return errors.WrapIf(err, "failed to write swarm stack env source")}} else {if err := os.Remove(envPath); err != nil && !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("failed to clear swarm stack env source: %w", err)+ return errors.WrapIf(err, "failed to clear swarm stack env source")}}@@ -2587,13 +2588,13 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmenfPath := filepath.Join(stackSourceDir, f.RelativePath)// Prevent path traversalif !appfs.IsSafeSubdirectory(stackSourceDir, fPath) {- return fmt.Errorf("invalid file path %q: must be inside stack directory", f.RelativePath)+ return errors.Errorf("invalid file path %q: must be inside stack directory", f.RelativePath)}if err := os.MkdirAll(filepath.Dir(fPath), common.DirPerm); err != nil {- return fmt.Errorf("failed to create directory for %s: %w", f.RelativePath, err)+ return errors.WrapIff(err, "failed to create directory for %s", f.RelativePath)}if err := atomic.WriteFile(fPath, f.Content, common.FilePerm); err != nil {- return fmt.Errorf("failed to write %s: %w", f.RelativePath, err)+ return errors.WrapIff(err, "failed to write %s", f.RelativePath)}}@@ -2611,14 +2612,14 @@ func (s *SwarmService) deleteStackSourceInternal(ctx context.Context, environmen}if err := os.RemoveAll(stackSourceDir); err != nil {- return fmt.Errorf("failed to remove swarm stack source directory: %w", err)+ return errors.WrapIf(err, "failed to remove swarm stack source directory")}// Best-effort cleanup of now-empty environment directory.environmentDir := filepath.Dir(stackSourceDir)if environmentDir != rootDir {if err := os.Remove(environmentDir); err != nil && !errors.Is(err, os.ErrNotExist) {- if errno, ok := errors.AsType[syscall.Errno](err); ok && (errno == syscall.ENOTEMPTY || errno == syscall.EACCES) {+ if errno, ok := stderrors.AsType[syscall.Errno](err); ok && (errno == syscall.ENOTEMPTY || errno == syscall.EACCES) {slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", err)return nil}@@ -2748,10 +2749,10 @@ func (s *SwarmService) ensureSwarmManagerInternal(ctx context.Context) error {}if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {- return &common.SwarmNotEnabledError{}+ return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled"))}if !info.Swarm.ControlAvailable {- return &common.SwarmManagerRequiredError{}+ return common.Classify(common.ErrSwarmManagerRequired, errors.New("Swarm manager access required"))}return nil@@ -2764,7 +2765,7 @@ func (s *SwarmService) ensureSwarmActiveInternal(ctx context.Context) error {}if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {- return &common.SwarmNotEnabledError{}+ return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled"))}return nil@@ -2773,12 +2774,12 @@ func (s *SwarmService) ensureSwarmActiveInternal(ctx context.Context) error {func (s *SwarmService) getDockerInfoInternal(ctx context.Context) (system.Info, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return system.Info{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return system.Info{}, errors.WrapIf(err, "failed to connect to Docker")}infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})if err != nil {- return system.Info{}, fmt.Errorf("failed to get Docker info: %w", err)+ return system.Info{}, errors.WrapIf(err, "failed to get Docker info")}return infoResult.Info, nil@@ -2796,7 +2797,7 @@ func (s *SwarmService) SyncSwarmEnabledState(ctx context.Context) error {}if err := s.kvService.SetBool(ctx, KVKeySwarmEnabled, enabled); err != nil {- return fmt.Errorf("persist swarm enabled state: %w", err)+ return errors.WrapIf(err, "persist swarm enabled state")}return nildiff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.goindex a4419e06d..4e22894fe 100644--- a/backend/internal/services/system_service.go+++ b/backend/internal/services/system_service.go@@ -2,12 +2,13 @@ package servicesimport ("context"- "errors""fmt""log/slog""strings""sync"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"@@ -461,7 +462,7 @@ func (s *SystemService) completeSystemContainerActivityInternal(ctx context.Contfunc (s *SystemService) pruneContainersInternal(ctx context.Context, options system.PruneContainersOptions, result *system.PruneAllResult) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}filterArgs := make(client.Filters)@@ -474,7 +475,7 @@ func (s *SystemService) pruneContainersInternal(ctx context.Context, options sysreport, err := dockerClient.ContainerPrune(ctx, client.ContainerPruneOptions{Filters: filterArgs})if err != nil {- return fmt.Errorf("failed to prune containers: %w", err)+ return errors.WrapIf(err, "failed to prune containers")}result.ContainersPruned = report.Report.ContainersDeleted@@ -486,7 +487,7 @@ func (s *SystemService) pruneContainersInternal(ctx context.Context, options sysfunc (s *SystemService) pruneImagesInternal(ctx context.Context, options system.PruneImagesOptions, result *system.PruneAllResult) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}filterArgs := make(client.Filters)@@ -504,12 +505,12 @@ func (s *SystemService) pruneImagesInternal(ctx context.Context, options system.filterArgs = filterArgs.Add("dangling", "false")filterArgs = filterArgs.Add("until", options.Until)default:- return fmt.Errorf("unsupported image prune mode: %s", options.Mode)+ return errors.Errorf("unsupported image prune mode: %s", options.Mode)}report, err := dockerClient.ImagePrune(ctx, client.ImagePruneOptions{Filters: filterArgs})if err != nil {- return fmt.Errorf("failed to prune images: %w", err)+ return errors.WrapIf(err, "failed to prune images")}slog.InfoContext(ctx, "Image pruning completed", "images_deleted", len(report.Report.ImagesDeleted), "bytes_reclaimed", report.Report.SpaceReclaimed)@@ -540,9 +541,9 @@ func (s *SystemService) pruneImagesInternal(ctx context.Context, options system.func (s *SystemService) pruneBuildCacheInternal(ctx context.Context, options system.PruneBuildCacheOptions, result *system.PruneAllResult) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed (connection): %w", err).Error())+ result.Errors = append(result.Errors, errors.WrapIf(err, "build cache pruning failed (connection)").Error())slog.ErrorContext(ctx, "Error connecting to Docker for build cache prune", "error", err.Error())- return fmt.Errorf("failed to connect to Docker for build cache prune: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker for build cache prune")}pruneOptions := client.BuildCachePruneOptions{@@ -559,9 +560,9 @@ func (s *SystemService) pruneBuildCacheInternal(ctx context.Context, options sysslog.DebugContext(ctx, "starting build cache pruning", "mode", options.Mode, "until", options.Until)report, err := dockerClient.BuildCachePrune(ctx, pruneOptions)if err != nil {- result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed: %w", err).Error())+ result.Errors = append(result.Errors, errors.WrapIf(err, "build cache pruning failed").Error())slog.ErrorContext(ctx, "Error pruning build cache", "error", err.Error())- return fmt.Errorf("failed to prune build cache: %w", err)+ return errors.WrapIf(err, "failed to prune build cache")}slog.InfoContext(ctx, "build cache pruning completed", "cache_entries_deleted", len(report.Report.CachesDeleted), "bytes_reclaimed", report.Report.SpaceReclaimed)@@ -589,7 +590,7 @@ func (s *SystemService) pruneVolumesInternal(ctx context.Context, options systemfunc (s *SystemService) pruneNetworksInternal(ctx context.Context, options system.PruneNetworksOptions, result *system.PruneAllResult) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}filterArgs := make(client.Filters)@@ -602,7 +603,7 @@ func (s *SystemService) pruneNetworksInternal(ctx context.Context, options systereport, err := dockerClient.NetworkPrune(ctx, client.NetworkPruneOptions{Filters: filterArgs})if err != nil {- return fmt.Errorf("failed to prune networks: %w", err)+ return errors.WrapIf(err, "failed to prune networks")}slog.InfoContext(ctx, "Network prune completed", "networks_deleted", len(report.Report.NetworksDeleted))diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.goindex 357c938e5..96c7f0fc2 100644--- a/backend/internal/services/system_upgrade_service.go+++ b/backend/internal/services/system_upgrade_service.go@@ -2,7 +2,7 @@ package servicesimport ("context"- "errors"+ stderrors "errors""fmt""log/slog""net/http"@@ -12,9 +12,7 @@ import ("sync/atomic""time"- containertypes "github.com/moby/moby/api/types/container"- mounttypes "github.com/moby/moby/api/types/mount"- "github.com/moby/moby/client"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -26,6 +24,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/getarcaneapp/arcane/types/v2/version"+ containertypes "github.com/moby/moby/api/types/container"+ mounttypes "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/client""go.getarcane.app/sys/cgroup"libupdater "go.getarcane.app/updater/pkg/labels"updatertypes "go.getarcane.app/updater/types"@@ -76,7 +77,7 @@ func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {// Verify we can access Docker_, err = s.dockerService.GetClient(ctx)if err != nil {- return false, &common.DockerSocketAccessError{}+ return false, errors.New("docker socket is not accessible")}// Verify we can find our container@@ -94,7 +95,7 @@ func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {// the updater engine passes an explicit target with the resolved new image.func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User, target updatertypes.SelfUpdateTarget) error {if !s.upgrading.CompareAndSwap(false, true) {- return &common.UpgradeInProgressError{}+ return common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))}defer s.upgrading.Store(false)@@ -104,13 +105,13 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user movar err errorcontainerId, err = s.getCurrentContainerIDInternal()if err != nil {- return fmt.Errorf("get current container: %w", err)+ return errors.WrapIf(err, "get current container")}}currentContainer, err := s.findArcaneContainerInternal(ctx, containerId)if err != nil {- return fmt.Errorf("inspect container: %w", err)+ return errors.WrapIf(err, "inspect container")}containerName := strings.TrimPrefix(currentContainer.Name, "/")@@ -155,7 +156,7 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo// This will run independently of the current containerdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}// Pull the upgrader image first to ensure it exists@@ -168,14 +169,14 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mopullReader, err := dockerClient.ImagePull(pullCtx, upgraderImage, client.ImagePullOptions{})if err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return fmt.Errorf("upgrader image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", upgraderImage)+ return errors.Errorf("upgrader image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", upgraderImage)}- return fmt.Errorf("pull upgrader image: %w", err)+ return errors.WrapIf(err, "pull upgrader image")}// Drain and validate the JSON stream to complete the pull.if err := dockerutils.ConsumeJSONMessageStream(pullReader, nil); err != nil {_ = pullReader.Close()- return fmt.Errorf("failed to complete upgrader image pull: %w", err)+ return errors.WrapIf(err, "failed to complete upgrader image pull")}if closeErr := pullReader.Close(); closeErr != nil {slog.Warn("Failed to close upgrader image pull reader", "error", closeErr)@@ -204,7 +205,7 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo},)if err != nil {- return fmt.Errorf("resolve upgrader docker runtime: %w", err)+ return errors.WrapIf(err, "resolve upgrader docker runtime")}upgradeCmd := []string{binaryPath, "upgrade", "--container", containerName}@@ -263,13 +264,13 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user moName: containerName,})if err != nil {- return fmt.Errorf("create upgrader container: %w", err)+ return errors.WrapIf(err, "create upgrader container")}// Start the upgrader container - it will run the upgrade and auto-removeif _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})- return fmt.Errorf("start upgrader container: %w", err)+ return errors.WrapIf(err, "start upgrader container")}slog.Info("Upgrade container started", "upgraderId", resp.ID[:12], "upgraderName", containerName)@@ -318,7 +319,7 @@ func resolveSystemUpgraderRuntimeOptionsInternal(scheme, socketPath, err := vuln.ParseDockerHost(dockerHost)if err != nil {- return upgraderRuntimeOptionsInternal{}, fmt.Errorf("resolve docker host %q: %w", dockerHost, err)+ return upgraderRuntimeOptionsInternal{}, errors.WrapIff(err, "resolve docker host %q", dockerHost)}if scheme != "unix" {@@ -333,7 +334,7 @@ func resolveSystemUpgraderRuntimeOptionsInternal(isRunningInDocker,)if err != nil {- return upgraderRuntimeOptionsInternal{}, fmt.Errorf("resolve unix socket source: %w", err)+ return upgraderRuntimeOptionsInternal{}, errors.WrapIf(err, "resolve unix socket source")}options.Mounts = append(options.Mounts, mounttypes.Mount{@@ -349,7 +350,7 @@ func resolveSystemUpgraderRuntimeOptionsInternal(func (s *SystemUpgradeService) getCurrentContainerIDInternal() (string, error) {id, err := cgroup.CurrentContainerID()if err != nil {- return "", &common.NotRunningInDockerError{}+ return "", errors.New("arcane is not running in a Docker container")}return id, nil}@@ -405,19 +406,20 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,}}- return containertypes.InspectResponse{}, &common.ArcaneContainerNotFoundError{}-}+ return containertypes.InspectResponse{}, common.Classify(common.ErrNotFound, errors.-// --- Fleet-wide "update all environments" orchestration ----//-// Remote agents upgrade first, while the manager is still up and can orchestrate-// and report live progress. The manager upgrades itself LAST, which recreates its-// own container. Updates are unconditional: every environment pulls the latest-// image whether or not it reports an update available. Because the browser loses-// the backend across that final restart, the orchestration is a persisted-// EnvironmentUpdateJob: StartUpdateAll runs the agents phase, triggers the manager-// self-upgrade as the last step and leaves the job in pending_restart; on the next-// boot ResumeUpdateAllOnStartup finalizes the manager result and closes the job.+ // --- Fleet-wide "update all environments" orchestration ---+ //+ // Remote agents upgrade first, while the manager is still up and can orchestrate+ // and report live progress. The manager upgrades itself LAST, which recreates its+ // own container. Updates are unconditional: every environment pulls the latest+ // image whether or not it reports an update available. Because the browser loses+ // the backend across that final restart, the orchestration is a persisted+ // EnvironmentUpdateJob: StartUpdateAll runs the agents phase, triggers the manager+ // self-upgrade as the last step and leaves the job in pending_restart; on the next+ // boot ResumeUpdateAllOnStartup finalizes the manager result and closes the job.+ New("could not find Arcane container"))+}const (localEnvironmentIDInternal = "0"@@ -442,16 +444,16 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.U// job row is the durable guard once committed; this only closes the in-process// window before that row exists.if !s.updatingAll.CompareAndSwap(false, true) {- return nil, &common.UpdateAllInProgressError{}+ return nil, common.Classify(common.ErrUpdateAllInProgress, errors.New("an update-all job is already in progress"))}defer s.updatingAll.Store(false)active, err := s.activeUpdateAllJobInternal(ctx)if err != nil {- return nil, fmt.Errorf("check for active update-all job: %w", err)+ return nil, errors.WrapIf(err, "check for active update-all job")}if active != nil {- return nil, &common.UpdateAllInProgressError{}+ return nil, common.Classify(common.ErrUpdateAllInProgress, errors.New("an update-all job is already in progress"))}info := s.versionService.GetAppVersionInfo(ctx)@@ -487,7 +489,7 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.Ujob.Results = append(models.EnvironmentUpdateResults{managerResult}, remoteResults...)if err := s.db.WithContext(ctx).Create(job).Error; err != nil {- return nil, fmt.Errorf("create update-all job: %w", err)+ return nil, errors.WrapIf(err, "create update-all job")}slog.InfoContext(ctx, "Update-all started; upgrading agents first", "jobId", job.ID, "user", user.Username)@@ -716,7 +718,7 @@ func updateAllAgentFailureStatusInternal(err error) models.EnvironmentUpdateResureturn models.EnvironmentUpdateResultStatusFailed}// The environment answered with a non-success status — reached, not offline.- if _, ok := errors.AsType[*remenv.StatusError](err); ok {+ if _, ok := stderrors.AsType[*remenv.StatusError](err); ok {return models.EnvironmentUpdateResultStatusFailed}return models.EnvironmentUpdateResultStatusSkippedOfflinediff --git a/backend/internal/services/system_upgrade_service_test.go b/backend/internal/services/system_upgrade_service_test.goindex 1c46eb278..147d31e11 100644--- a/backend/internal/services/system_upgrade_service_test.go+++ b/backend/internal/services/system_upgrade_service_test.go@@ -2,10 +2,11 @@ package servicesimport ("context"- "errors""fmt""testing"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -44,16 +45,16 @@ func TestSystemUpgradeService_Initialization(t *testing.T) {// TestSystemUpgradeService_ErrorVariables tests that error variables are properly definedfunc TestSystemUpgradeService_ErrorVariables(t *testing.T) {// Test that all expected errors exist and are not nil- require.Error(t, &common.NotRunningInDockerError{})- require.Error(t, &common.ArcaneContainerNotFoundError{})- require.Error(t, &common.UpgradeInProgressError{})- require.Error(t, &common.DockerSocketAccessError{})+ require.Error(t, errors.New("arcane is not running in a Docker container"))+ require.Error(t, common.Classify(common.ErrNotFound, errors.New("could not find Arcane container")))+ require.Error(t, common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress")))+ require.Error(t, errors.New("docker socket is not accessible"))// Test error messages- require.Equal(t, "arcane is not running in a Docker container", (&common.NotRunningInDockerError{}).Error())- require.Equal(t, "could not find Arcane container", (&common.ArcaneContainerNotFoundError{}).Error())- require.Equal(t, "an upgrade is already in progress", (&common.UpgradeInProgressError{}).Error())- require.Equal(t, "docker socket is not accessible", (&common.DockerSocketAccessError{}).Error())+ require.Equal(t, "arcane is not running in a Docker container", (errors.New("arcane is not running in a Docker container")).Error())+ require.Equal(t, "could not find Arcane container", (common.Classify(common.ErrNotFound, errors.New("could not find Arcane container"))).Error())+ require.Equal(t, "an upgrade is already in progress", (common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))).Error())+ require.Equal(t, "docker socket is not accessible", (errors.New("docker socket is not accessible")).Error())}// TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess tests upgrading flag@@ -125,12 +126,12 @@ func TestSystemUpgradeService_ConcurrentUpgradeAttempts(t *testing.T) {// TestSystemUpgradeService_UpgradeInProgressError tests the upgrade in progress sentinel errorfunc TestSystemUpgradeService_UpgradeInProgressError(t *testing.T) {// This tests the specific error that the handler checks for- // The handler uses common.IsUpgradeInProgressError for conflict detection.+ // The handler uses errors.Is with common.ErrUpgradeInProgress for conflict detection.- err := &common.UpgradeInProgressError{}+ err := common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))require.Equal(t, "an upgrade is already in progress", err.Error())- require.True(t, common.IsUpgradeInProgressError(err))+ require.True(t, errors.Is(err, common.ErrUpgradeInProgress))}// TestSystemUpgradeService_AtomicOperations tests atomic.Bool operationsdiff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.goindex ead53bf8b..fa5fa6a7a 100644--- a/backend/internal/services/template_service.go+++ b/backend/internal/services/template_service.go@@ -3,7 +3,6 @@ package servicesimport ("context"json "encoding/json/v2"- "errors""fmt""io""log/slog"@@ -15,6 +14,8 @@ import ("sync""time"+ "emperror.dev/errors"+composeloader "github.com/compose-spec/compose-go/v2/loader"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -137,7 +138,7 @@ func (s *TemplateService) ensureRemoteTemplatesLoaded(_ context.Context) error {}templates, found, err := s.remoteCache.Get(struct{}{})if err != nil {- return fmt.Errorf("failed to load remote templates: %w", err)+ return errors.WrapIf(err, "failed to load remote templates")}if !found || len(templates) == 0 {return errNoRemoteTemplates@@ -148,7 +149,7 @@ func (s *TemplateService) ensureRemoteTemplatesLoaded(_ context.Context) error {func (s *TemplateService) refreshRemoteTemplates(ctx context.Context) error {templates, err := s.loadRemoteTemplates(ctx)if err != nil {- return fmt.Errorf("failed to load remote templates: %w", err)+ return errors.WrapIf(err, "failed to load remote templates")}if len(templates) == 0 {@@ -249,11 +250,11 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.Cif err := s.db.WithContext(ctx).Preload("Registry").Where("id = ?", id).First(&template).Error; err == nil {return &template, nil} else if !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, fmt.Errorf("failed to query local template: %w", err)+ return nil, errors.WrapIf(err, "failed to query local template")}if err := s.ensureRemoteTemplatesLoaded(ctx); err != nil && !errors.Is(err, errNoRemoteTemplates) {- return nil, fmt.Errorf("template %q lookup failed: registry refresh error: %w", id, err)+ return nil, errors.WrapIff(err, "template %q lookup failed: registry refresh error", id)}if found := s.lookupRemoteFromCacheInternal(id); found != nil {@@ -266,17 +267,15 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.Cif strings.HasPrefix(id, remoteIDPrefix+":") {slog.InfoContext(ctx, "remote template not in cache, forcing registry refresh", "templateID", id, "cacheSize", s.remoteCacheSizeInternal())if refreshErr := s.refreshRemoteTemplates(ctx); refreshErr != nil && !errors.Is(refreshErr, errNoRemoteTemplates) {- return nil, fmt.Errorf("template %q not found and registry refresh failed: %w", id, refreshErr)+ return nil, errors.WrapIff(refreshErr, "template %q not found and registry refresh failed", id)}if found := s.lookupRemoteFromCacheInternal(id); found != nil {return found, nil}- return nil, &common.TemplateNotFoundError{- Err: fmt.Errorf("template %q not found in any registered registry (cache size=%d after refresh)", id, s.remoteCacheSizeInternal()),- }+ return nil, common.Classify(common.ErrTemplateNotFound, errors.WrapIf(errors.Errorf("template %q not found in any registered registry (cache size=%d after refresh)", id, s.remoteCacheSizeInternal()), "Template not found"))}- return nil, &common.TemplateNotFoundError{}+ return nil, common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))}func (s *TemplateService) lookupRemoteFromCacheInternal(id string) *models.ComposeTemplate {@@ -313,7 +312,7 @@ func (s *TemplateService) CreateTemplate(ctx context.Context, template *models.CsetTemplateIconURL(template, s.resolveTemplateIconURL(ctx, template.Content, mo.PointerToOption(template.EnvContent).OrEmpty()))return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(template).Error; err != nil {- return fmt.Errorf("failed to create template: %w", err)+ return errors.WrapIf(err, "failed to create template")}return nil})@@ -324,9 +323,9 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updatesvar existing models.ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.TemplateNotFoundError{}+ return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))}- return fmt.Errorf("failed to find template: %w", err)+ return errors.WrapIf(err, "failed to find template")}if existing.IsRemote {@@ -340,7 +339,7 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updatessetTemplateIconURL(&existing, s.resolveTemplateIconURL(ctx, existing.Content, mo.PointerToOption(existing.EnvContent).OrEmpty()))if err := tx.Save(&existing).Error; err != nil {- return fmt.Errorf("failed to update template: %w", err)+ return errors.WrapIf(err, "failed to update template")}return nil@@ -352,9 +351,9 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {var existing models.ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return &common.TemplateNotFoundError{}+ return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))}- return fmt.Errorf("failed to find template: %w", err)+ return errors.WrapIf(err, "failed to find template")}if existing.IsRemote {@@ -363,20 +362,20 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {baseDir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return fmt.Errorf("failed to get templates directory: %w", err)+ return errors.WrapIf(err, "failed to get templates directory")}templatePath := filepath.Join(baseDir, existing.Name)if stat, err := os.Stat(templatePath); err == nil && stat.IsDir() {if _, err := projects.DetectComposeFile(templatePath); err == nil {if err := os.RemoveAll(templatePath); err != nil {- return fmt.Errorf("failed to delete template directory: %w", err)+ return errors.WrapIf(err, "failed to delete template directory")}}}if err := tx.Delete(&existing).Error; err != nil {- return fmt.Errorf("failed to delete template: %w", err)+ return errors.WrapIf(err, "failed to delete template")}return nil})@@ -438,7 +437,7 @@ func (s *TemplateService) GetRegistries(ctx context.Context) ([]models.TemplateRvar registries []models.TemplateRegistryerr := s.db.WithContext(ctx).Find(®istries).Errorif err != nil {- return nil, fmt.Errorf("failed to get registries: %w", err)+ return nil, errors.WrapIf(err, "failed to get registries")}return registries, nil}@@ -467,7 +466,7 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.Tregistry.Description = manifest.Description}} else if registry.Name == "" || registry.Description == "" {- return fmt.Errorf("failed to fetch registry manifest: %w", err)+ return errors.WrapIf(err, "failed to fetch registry manifest")}}@@ -477,7 +476,7 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.Terr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(registry).Error; err != nil {- return fmt.Errorf("failed to create registry: %w", err)+ return errors.WrapIf(err, "failed to create registry")}return nil})@@ -496,7 +495,7 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updatesif errors.Is(err, gorm.ErrRecordNotFound) {return errors.New("registry not found")}- return fmt.Errorf("failed to find registry: %w", err)+ return errors.WrapIf(err, "failed to find registry")}if err := s.hydrateRegistryUpdates(ctx, updates, &existing); err != nil {@@ -535,7 +534,7 @@ func (s *TemplateService) hydrateRegistryUpdates(ctx context.Context, updates, eupdates.Description = manifest.Description}} else if urlChanged && (updates.Name == "" || updates.Description == "") {- return fmt.Errorf("failed to fetch registry manifest: %w", err)+ return errors.WrapIf(err, "failed to fetch registry manifest")}}return nil@@ -622,17 +621,17 @@ func (s *TemplateService) doGET(ctx context.Context, url string) ([]byte, error)}resp, err := client.Do(req)if err != nil {- return nil, fmt.Errorf("failed to fetch %s: %w", url, err)+ return nil, errors.WrapIff(err, "failed to fetch %s", url)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)+ return nil, errors.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read response body from %s: %w", url, err)+ return nil, errors.WrapIff(err, "failed to read response body from %s", url)}return body, nil}@@ -646,7 +645,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *modelclient, req, err := s.newSafeRequestInternal(ctx, http.MethodGet, reg.URL)if err != nil {- return nil, fmt.Errorf("create request: %w", err)+ return nil, errors.WrapIf(err, "create request")}if fetchMeta != nil && fetchMeta.LastModified != "" {req.Header.Set("If-Modified-Since", fetchMeta.LastModified)@@ -654,7 +653,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *modelresp, err := client.Do(req)if err != nil {- return nil, fmt.Errorf("request failed: %w", err)+ return nil, errors.WrapIf(err, "request failed")}defer func() { _ = resp.Body.Close() }()@@ -665,17 +664,17 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *modelreturn nil, errors.New("received 304 without cached data")}if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("unexpected status %d", resp.StatusCode)+ return nil, errors.Errorf("unexpected status %d", resp.StatusCode)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("read body: %w", err)+ return nil, errors.WrapIf(err, "read body")}var regDTO tmpl.RemoteRegistryif err := json.Unmarshal(body, ®DTO); err != nil {- return nil, fmt.Errorf("parse registry JSON: %w", err)+ return nil, errors.WrapIf(err, "parse registry JSON")}templates := make([]models.ComposeTemplate, 0, len(regDTO.Templates))@@ -703,7 +702,7 @@ func (s *TemplateService) fetchRegistryManifest(ctx context.Context, url string)}var reg tmpl.RemoteRegistryif err := json.Unmarshal(body, ®); err != nil {- return nil, fmt.Errorf("failed to parse registry JSON: %w", err)+ return nil, errors.WrapIf(err, "failed to parse registry JSON")}if reg.Name == "" || len(reg.Templates) == 0 {return nil, errors.New("invalid registry manifest: missing required fields (name, templates)")@@ -744,7 +743,7 @@ func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *moreturn template.Content, envContent, nil}if template.Metadata == nil || template.Metadata.RemoteURL == nil || strings.TrimSpace(*template.Metadata.RemoteURL) == "" {- return "", "", fmt.Errorf("remote template %q is missing compose_url in registry metadata", template.ID)+ return "", "", errors.Errorf("remote template %q is missing compose_url in registry metadata", template.ID)}return s.fetchRemoteTemplateFiles(ctx, template)@@ -757,7 +756,7 @@ func (s *TemplateService) fetchRemoteTemplateFiles(ctx context.Context, templatecomposeContent, err := s.fetchURL(ctx, *template.Metadata.RemoteURL)if err != nil {- return "", "", fmt.Errorf("failed to fetch compose content from %s: %w", *template.Metadata.RemoteURL, err)+ return "", "", errors.WrapIff(err, "failed to fetch compose content from %s", *template.Metadata.RemoteURL)}var envContent string@@ -832,7 +831,7 @@ func (s *TemplateService) newSafeRequestInternal(ctx context.Context, method, rareq, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), nil)if err != nil {- return nil, nil, fmt.Errorf("failed to create request for %s: %w", rawURL, err)+ return nil, nil, errors.WrapIff(err, "failed to create request for %s", rawURL)}return client, req, nil@@ -862,12 +861,12 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remotif err := tx.Where("is_remote = ? AND registry_id IS NULL AND (description = ? OR name = ?)", false, srcDesc, base).First(&existing).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return fmt.Errorf("failed to check existing template: %w", err)+ return errors.WrapIf(err, "failed to check existing template")} else if err == nil {// Existing template foundcomposeContent, envContent, err := s.FetchTemplateContent(ctx, remoteTemplate)if err != nil {- return fmt.Errorf("failed to fetch template content for existing local template: %w", err)+ return errors.WrapIf(err, "failed to fetch template content for existing local template")}envPtr, werr := projects.WriteTemplateFiles(composePath, envPath, composeContent, envContent)@@ -880,7 +879,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remotexisting.Metadata = cloneTemplateMetadata(remoteTemplate.Metadata)if err := tx.Save(&existing).Error; err != nil {- return fmt.Errorf("failed to update existing local template: %w", err)+ return errors.WrapIf(err, "failed to update existing local template")}resultTemplate = &existingreturn nil@@ -889,7 +888,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot// New templatecomposeContent, envContent, err := s.FetchTemplateContent(ctx, remoteTemplate)if err != nil {- return fmt.Errorf("failed to fetch template content for download: %w", err)+ return errors.WrapIf(err, "failed to fetch template content for download")}envPtr, werr := projects.WriteTemplateFiles(composePath, envPath, composeContent, envContent)@@ -911,7 +910,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot}if err := tx.Create(localTemplate).Error; err != nil {- return fmt.Errorf("failed to save local template: %w", err)+ return errors.WrapIf(err, "failed to save local template")}resultTemplate = localTemplatereturn nil@@ -1011,12 +1010,12 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, deexisting.IsRemote = falsesetTemplateIconURL(&existing, iconURL)if err := tx.Save(&existing).Error; err != nil {- return fmt.Errorf("update template %s: %w", existing.ID, err)+ return errors.WrapIff(err, "update template %s", existing.ID)}return nil}if !errors.Is(q.Error, gorm.ErrRecordNotFound) {- return fmt.Errorf("query existing template: %w", q.Error)+ return errors.WrapIf(q.Error, "query existing template")}tpl := &models.ComposeTemplate{@@ -1033,7 +1032,7 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, de}setTemplateIconURL(tpl, iconURL)if err := tx.Create(tpl).Error; err != nil {- return fmt.Errorf("insert template %s: %w", name, err)+ return errors.WrapIff(err, "insert template %s", name)}return nil})@@ -1057,7 +1056,7 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) edir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return fmt.Errorf("ensure templates dir: %w", err)+ return errors.WrapIf(err, "ensure templates dir")}entries, err := os.ReadDir(dir)@@ -1065,7 +1064,7 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) eif os.IsNotExist(err) {return nil}- return fmt.Errorf("read dir %s: %w", dir, err)+ return errors.WrapIff(err, "read dir %s", dir)}for _, ent := range entries {@@ -1227,7 +1226,7 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,if composeTemplate.IsRemote {composeContent, envContent, err = s.FetchTemplateContent(ctx, composeTemplate)if err != nil {- return nil, fmt.Errorf("failed to fetch template content: %w", err)+ return nil, errors.WrapIf(err, "failed to fetch template content")}} else {composeContent = composeTemplate.Content@@ -1240,7 +1239,7 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,var outTemplate tmpl.Templateif mapErr := mapper.MapStruct(composeTemplate, &outTemplate); mapErr != nil {- return nil, fmt.Errorf("failed to map template: %w", mapErr)+ return nil, errors.WrapIf(mapErr, "failed to map template")}// Parse services from compose content using compose-go library@@ -1270,7 +1269,7 @@ func (s *TemplateService) getMergedTemplates(ctx context.Context) ([]models.Compvar templates []models.ComposeTemplate// Use Omit to avoid fetching heavy content fields which are not needed for listingif err := s.db.WithContext(ctx).Omit("Content", "EnvContent").Preload("Registry").Find(&templates).Error; err != nil {- return nil, fmt.Errorf("failed to get local templates: %w", err)+ return nil, errors.WrapIf(err, "failed to get local templates")}if err := s.ensureRemoteTemplatesLoaded(ctx); err != nil {diff --git a/backend/internal/services/template_service_test.go b/backend/internal/services/template_service_test.goindex dd09e8377..5e87cc2b6 100644--- a/backend/internal/services/template_service_test.go+++ b/backend/internal/services/template_service_test.go@@ -375,8 +375,7 @@ func TestFetchRaw_BlocksUnsafeRemoteURL(t *testing.T) {_, err := service.FetchRaw(context.Background(), "http://127.0.0.1:8080/registry.json")require.Error(t, err)- var unsafeErr *common.UnsafeRemoteURLError- require.ErrorAs(t, err, &unsafeErr)+ require.ErrorIs(t, err, common.ErrUnsafeRemoteURL)}func TestSyncFilesystemTemplatesInternal_PopulatesIconURL(t *testing.T) {diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.goindex 0a68f0caf..6c98f0dc4 100644--- a/backend/internal/services/updater_service.go+++ b/backend/internal/services/updater_service.go@@ -2,7 +2,7 @@ package servicesimport ("context"- "errors"+ stderrors "errors""fmt""io""log/slog"@@ -11,11 +11,9 @@ import ("strings""time"- "github.com/compose-spec/compose-go/v2/loader"- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/client"- "github.com/samber/mo"+ "emperror.dev/errors"+ "github.com/compose-spec/compose-go/v2/loader""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -26,6 +24,9 @@ import (projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/updater"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"+ "github.com/samber/mo""go.getarcane.app/sys/cgroup"moduleapi "go.getarcane.app/updater/api"updaterdigest "go.getarcane.app/updater/pkg/digest"@@ -236,7 +237,7 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, optionsreturn err}if len(containerIDs) == 0 {- return fmt.Errorf("no containers matched the requested %s resources", strings.TrimSpace(options.Type))+ return errors.Errorf("no containers matched the requested %s resources", strings.TrimSpace(options.Type))}engineOpts := moduletypes.Options{Force: options.ForceUpdate, DryRun: options.DryRun}@@ -260,14 +261,14 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, optionsStatus: updater.StatusFailed,Error: engineErr.Error(),})- engineErrs = append(engineErrs, fmt.Errorf("%s: %w", containerID, engineErr))+ engineErrs = append(engineErrs, errors.WrapIff(engineErr, "%s", containerID))}}s.logResultItemsInternal(ctx, out)out.Success = out.Failed == 0// Engine errors propagate like the unscoped path's engine error does —// the remaining containers were still attempted and recorded above.- return errors.Join(engineErrs...)+ return stderrors.Join(engineErrs...)}// resolveScopedContainerIDsInternal maps a scoped options payload to the@@ -291,7 +292,7 @@ func (s *UpdaterService) resolveScopedContainerIDsInternal(ctx context.Context,case "image":return s.containerIDsForImagesInternal(ctx, requested)default:- return nil, fmt.Errorf("unsupported scoped update type %q", options.Type)+ return nil, errors.Errorf("unsupported scoped update type %q", options.Type)}}@@ -320,7 +321,7 @@ func (s *UpdaterService) containerIDsForProjectsInternal(ctx context.Context, prcontainers, _, _, _, err := s.deps.Docker.GetAllContainers(ctx)if err != nil {- return nil, fmt.Errorf("list containers: %w", err)+ return nil, errors.WrapIf(err, "list containers")}var ids []string@@ -357,7 +358,7 @@ func (s *UpdaterService) containerIDsForImagesInternal(ctx context.Context, imagcontainers, _, _, _, err := s.deps.Docker.GetAllContainers(ctx)if err != nil {- return nil, fmt.Errorf("list containers: %w", err)+ return nil, errors.WrapIf(err, "list containers")}var ids []string@@ -421,7 +422,7 @@ func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.Auquery = query.Limit(limit)}if err := query.Find(&records).Error; err != nil {- return nil, fmt.Errorf("get history: %w", err)+ return nil, errors.WrapIf(err, "get history")}return records, nil}@@ -435,7 +436,7 @@ func (s *UpdaterService) RestartContainersUsingOldIDs(ctx context.Context, oldID// TriggerSelfUpdateViaCLI triggers Arcane's detached CLI self-update path.func (s *UpdaterService) TriggerSelfUpdateViaCLI(ctx context.Context, source, containerID, containerName string, labelMap map[string]string) error {if !labels.IsArcaneContainer(labelMap) {- return fmt.Errorf("%s: container is not an Arcane self-update target", source)+ return errors.Errorf("%s: container is not an Arcane self-update target", source)}return s.TriggerSelfUpdate(ctx, moduletypes.SelfUpdateTarget{ContainerID: containerID,@@ -534,7 +535,7 @@ func autoUpdateEventTitleInternal(phase string, metadata models.JSON) string {// DockerClient returns Arcane's configured Docker client for the updater engine.func (s *UpdaterService) DockerClient(ctx context.Context) (*client.Client, error) {if s == nil || s.deps.Docker == nil {- return nil, &common.UpdaterDockerServiceUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("docker service unavailable"))}return s.deps.Docker.GetClient(ctx)}@@ -545,7 +546,7 @@ func (s *UpdaterService) DockerClient(ctx context.Context) (*client.Client, erro// run (and its activity slot) indefinitely.func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progress io.Writer) error {if s == nil || s.deps.ImagePuller == nil {- return &common.UpdaterImageServiceUnavailableError{}+ return common.Classify(common.ErrUnavailable, errors.New("image service unavailable"))}activityID := activityIDFromContextInternal(ctx)writer := activitylib.NewWriter(ctx, s.deps.Activity, activityID, progress, "Pulling updated images")@@ -561,7 +562,7 @@ func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progresif s.deps.Projects != nil {resolved, err := s.deps.Projects.resolveRegistryCredentialsInternal(pullCtx)if err != nil {- return fmt.Errorf("resolve registry credentials: %w", err)+ return errors.WrapIf(err, "resolve registry credentials")}return s.deps.ImagePuller.PullImage(pullCtx, imageRef, writer, s.deps.SystemUser, resolved)}@@ -572,12 +573,12 @@ func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progres// PendingImageUpdates returns pending image update records from Arcane's database.func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]moduletypes.ImageUpdateRecord, error) {if s == nil || s.deps.DB == nil {- return nil, &common.UpdaterDatabaseUnavailableError{}+ return nil, common.Classify(common.ErrUnavailable, errors.New("database unavailable"))}var records []models.ImageUpdateRecordif err := s.deps.DB.WithContext(ctx).Where("has_update = ?", true).Find(&records).Error; err != nil {- return nil, fmt.Errorf("query pending image updates: %w", err)+ return nil, errors.WrapIf(err, "query pending image updates")}// Flush pending "Updates Available" notifications before the engine@@ -604,7 +605,7 @@ func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]moduletypes// ClearImageUpdateRecord clears a pending image update record after it is handled.func (s *UpdaterService) ClearImageUpdateRecord(ctx context.Context, record moduletypes.ImageUpdateRecord) error {if s == nil {- return &common.UpdaterServiceUnavailableError{}+ return common.Classify(common.ErrUnavailable, errors.New("updater service unavailable"))}return s.clearImageUpdateRecordForModuleInternal(ctx, record)}@@ -636,14 +637,14 @@ func (s *UpdaterService) ExcludedContainers(ctx context.Context) ([]string, erro// ProjectByComposeName resolves an Arcane project from a Docker Compose project name.func (s *UpdaterService) ProjectByComposeName(ctx context.Context, composeName string) (moduletypes.ComposeProject, error) {if s == nil || s.deps.Projects == nil {- return moduletypes.ComposeProject{}, &common.UpdaterProjectServiceUnavailableError{}+ return moduletypes.ComposeProject{}, common.Classify(common.ErrUnavailable, errors.New("project service unavailable"))}project, err := s.deps.Projects.GetProjectByComposeName(ctx, composeName)if err != nil {return moduletypes.ComposeProject{}, err}if project == nil {- return moduletypes.ComposeProject{}, fmt.Errorf("compose project not found: %s", composeName)+ return moduletypes.ComposeProject{}, errors.Errorf("compose project not found: %s", composeName)}return moduletypes.ComposeProject{ID: project.ID, Name: project.Name}, nil}@@ -651,7 +652,7 @@ func (s *UpdaterService) ProjectByComposeName(ctx context.Context, composeName s// UpdateServices redeploys selected services through Arcane's project service.func (s *UpdaterService) UpdateServices(ctx context.Context, projectID string, services []string) error {if s == nil || s.deps.Projects == nil {- return &common.UpdaterProjectServiceUnavailableError{}+ return common.Classify(common.ErrUnavailable, errors.New("project service unavailable"))}return s.deps.Projects.UpdateProjectServices(ctx, projectID, services, s.deps.SystemUser)}@@ -663,7 +664,7 @@ func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target moduletypif instanceType == "" {instanceType = "server"}- return fmt.Errorf("%s self-update requires CLI upgrade service", instanceType)+ return errors.Errorf("%s self-update requires CLI upgrade service", instanceType)}// A server self-update stops this process before the run can complete its@@ -674,7 +675,7 @@ func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target moduletyp}if err := s.deps.SelfUpgrade.TriggerUpgradeViaCLI(ctx, s.deps.SystemUser, target); err != nil {- return fmt.Errorf("CLI upgrade failed: %w", err)+ return errors.WrapIf(err, "CLI upgrade failed")}return nil}@@ -1039,12 +1040,12 @@ func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]strusuccessfulSources := 0if s.deps.Docker == nil {- errs = append(errs, &common.UpdaterDockerServiceUnavailableError{})+ errs = append(errs, common.Classify(common.ErrUnavailable, errors.New("docker service unavailable")))} else {dcli, err := s.deps.Docker.GetClient(ctx)if err != nil || dcli == nil {if err == nil {- err = &common.UpdaterDockerClientUnavailableError{}+ err = common.Classify(common.ErrUnavailable, errors.New("docker client unavailable"))}errs = append(errs, err)s.loggerInternal().DebugContext(ctx, "collectUsedImages: docker connection unavailable", "error", err)@@ -1066,7 +1067,7 @@ func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]stru}if successfulSources == 0 {- return nil, errors.Join(errs...)+ return nil, stderrors.Join(errs...)}s.loggerInternal().DebugContext(ctx, "collectUsedImages: collected used images", "count", len(out))diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.goindex f206dd951..322d4c65f 100644--- a/backend/internal/services/user_service.go+++ b/backend/internal/services/user_service.go@@ -5,11 +5,12 @@ import ("crypto/rand""crypto/subtle""encoding/base64"- "errors""fmt""log/slog""strings"+ "emperror.dev/errors"+"golang.org/x/crypto/argon2""golang.org/x/crypto/bcrypt""gorm.io/gorm"@@ -47,7 +48,7 @@ type UserService struct {argon2Params *Argon2Params}-var ErrCannotRemoveLastAdmin = errors.New("cannot remove the last admin user")+const ErrCannotRemoveLastAdmin = errors.Sentinel("cannot remove the last admin user")func NewUserService(db *database.DB) *UserService {return &UserService{@@ -145,7 +146,7 @@ func (s *UserService) validateArgon2Password(encodedHash, password string) errorfunc (s *UserService) CreateUser(ctx context.Context, user *models.User) (*models.User, error) {err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Create(user).Error; err != nil {- return fmt.Errorf("failed to create user: %w", err)+ return errors.WrapIf(err, "failed to create user")}return nil})@@ -180,10 +181,10 @@ func (s *UserService) UpdateUser(ctx context.Context, user *models.User) (*modelif errors.Is(err, gorm.ErrRecordNotFound) {return ErrUserNotFound}- return fmt.Errorf("failed to load user: %w", err)+ return errors.WrapIf(err, "failed to load user")}if err := tx.Save(user).Error; err != nil {- return fmt.Errorf("failed to update user: %w", err)+ return errors.WrapIf(err, "failed to update user")}return nil})@@ -211,7 +212,7 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userIDif errors.Is(err, gorm.ErrRecordNotFound) {return ErrUserNotFound}- return fmt.Errorf("failed to load user for OIDC merge: %w", err)+ return errors.WrapIf(err, "failed to load user for OIDC merge")}// If already linked to a different subject, abort@@ -229,9 +230,9 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userIDif err := tx.Save(&u).Error; err != nil {// Bubble up uniqueness violations with a clearer messageif strings.Contains(strings.ToLower(err.Error()), "unique") || strings.Contains(strings.ToLower(err.Error()), "duplicate key") {- return fmt.Errorf("oidc subject is already linked to another user: %w", err)+ return errors.WrapIf(err, "oidc subject is already linked to another user")}- return fmt.Errorf("failed to persist OIDC merge: %w", err)+ return errors.WrapIf(err, "failed to persist OIDC merge")}out = &ureturn nil@@ -246,7 +247,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {// Hash password outside transaction to minimize lock timehashedPassword, err := s.hashPassword("arcane-admin")if err != nil {- return fmt.Errorf("failed to hash default admin password: %w", err)+ return errors.WrapIf(err, "failed to hash default admin password")}// Step 1: ensure the default admin user row exists. If the users table is@@ -257,7 +258,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var count int64if err := tx.Model(&models.User{}).Count(&count).Error; err != nil {- return fmt.Errorf("failed to count users: %w", err)+ return errors.WrapIf(err, "failed to count users")}if count == 0 {@@ -271,7 +272,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {RequiresPasswordChange: true,}if err := tx.Create(userModel).Error; err != nil {- return fmt.Errorf("failed to create default admin user: %w", err)+ return errors.WrapIf(err, "failed to create default admin user")}adminUserID = userModel.IDslog.InfoContext(ctx, "👑 Default admin user created!")@@ -289,7 +290,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {if errors.Is(err, gorm.ErrRecordNotFound) {return nil}- return fmt.Errorf("failed to look up default admin user: %w", err)+ return errors.WrapIf(err, "failed to look up default admin user")}adminUserID = existing.IDreturn nil@@ -309,7 +310,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {// wired up.assignments, err := s.roleService.ListUserAssignments(ctx, adminUserID)if err != nil {- return fmt.Errorf("failed to list default admin assignments: %w", err)+ return errors.WrapIf(err, "failed to list default admin assignments")}for _, a := range assignments {if a.RoleID == authz.BuiltInRoleAdmin && a.EnvironmentID == nil {@@ -327,7 +328,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {manual = append(manual, models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID})}if err := s.roleService.SetUserAssignments(ctx, adminUserID, manual); err != nil {- return fmt.Errorf("failed to grant default admin global role: %w", err)+ return errors.WrapIf(err, "failed to grant default admin global role")}slog.InfoContext(ctx, "Default admin granted global Admin role assignment", "user_id", adminUserID)return nil@@ -360,11 +361,11 @@ func (s *UserService) DeleteUser(ctx context.Context, id string) error {if errors.Is(err, gorm.ErrRecordNotFound) {return ErrUserNotFound}- return fmt.Errorf("failed to load user: %w", err)+ return errors.WrapIf(err, "failed to load user")}if err := tx.Delete(&models.User{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete user: %w", err)+ return errors.WrapIf(err, "failed to delete user")}return nil})@@ -381,14 +382,14 @@ func (s *UserService) NeedsPasswordUpgrade(hash string) bool {func (s *UserService) UpgradePasswordHash(ctx context.Context, userID, password string) error {newHash, err := s.hashPassword(password)if err != nil {- return fmt.Errorf("failed to create new hash: %w", err)+ return errors.WrapIf(err, "failed to create new hash")}return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Model(&models.User{}).Where("id = ?", userID).Update("password_hash", newHash).Error; err != nil {- return fmt.Errorf("failed to update password hash: %w", err)+ return errors.WrapIf(err, "failed to update password hash")}return nil})@@ -410,7 +411,7 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.paginationResp, err := pagination.PaginateAndSortDB(params, query, &users)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to paginate users: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate users")}result := s.toUserResponseDtosInternal(ctx, users)@@ -534,7 +535,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []byMimeType: mimeType,}if err := tx.Save(&avatar).Error; err != nil {- return fmt.Errorf("failed to save avatar data: %w", err)+ return errors.WrapIf(err, "failed to save avatar data")}err := tx.Model(&models.User{}).@@ -543,7 +544,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []by"has_avatar": true,}).Errorif err != nil {- return fmt.Errorf("failed to update user avatar flag: %w", err)+ return errors.WrapIf(err, "failed to update user avatar flag")}return nil})@@ -553,7 +554,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []byfunc (s *UserService) DeleteAvatar(ctx context.Context, userID string) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Where("user_id = ?", userID).Delete(&models.UserAvatar{}).Error; err != nil {- return fmt.Errorf("failed to delete avatar data: %w", err)+ return errors.WrapIf(err, "failed to delete avatar data")}err := tx.Model(&models.User{}).@@ -562,7 +563,7 @@ func (s *UserService) DeleteAvatar(ctx context.Context, userID string) error {"has_avatar": false,}).Errorif err != nil {- return fmt.Errorf("failed to update user avatar flag: %w", err)+ return errors.WrapIf(err, "failed to update user avatar flag")}return nil})diff --git a/backend/internal/services/variable_service.go b/backend/internal/services/variable_service.goindex 1a1b5ffc3..f677ce6a7 100644--- a/backend/internal/services/variable_service.go+++ b/backend/internal/services/variable_service.go@@ -4,7 +4,6 @@ import ("bufio""context"json "encoding/json/v2"- "errors""fmt""log/slog""net/http"@@ -16,6 +15,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -27,7 +28,7 @@ import (// envKeyPattern is the POSIX env-name shape used to validate variable keys// before they are persisted to .env.global. Keys that do not match are-// rejected with a common.InvalidEnvKeyError.+// rejected with common.ErrInvalidEnvKey.var envKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)const (@@ -67,7 +68,7 @@ func NewVariableService(db *database.DB, environmentService *EnvironmentService,func (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariable, error) {variables, err := s.loadVariablesInternal(ctx)if err != nil {- return nil, &common.GlobalVariablesRetrievalError{Err: err}+ return nil, errors.WrapIf(err, "Failed to retrieve global variables")}result := make([]env.GlobalVariable, 0, len(variables))@@ -80,7 +81,7 @@ func (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariabfunc (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobalVariableRequest) (*env.GlobalVariable, error) {key := strings.TrimSpace(req.Key)if !envKeyPattern.MatchString(key) {- return nil, &common.InvalidEnvKeyError{Key: req.Key}+ return nil, common.Classify(common.ErrInvalidEnvKey, errors.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))}envIDs, err := s.normalizeScopeInternal(ctx, req.AllEnvironments, req.EnvironmentIDs)@@ -92,7 +93,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobvalue := req.Valueif req.IsSecret {if value, err = crypto.Encrypt(value); err != nil {- return nil, &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}+ return nil, errors.WrapIf(err, "Failed to update global variables")}}@@ -108,7 +109,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobreturn err}if err := tx.Omit("Environments").Create(&variable).Error; err != nil {- return fmt.Errorf("failed to create global variable: %w", err)+ return errors.WrapIf(err, "failed to create global variable")}return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)})@@ -125,16 +126,16 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req envvar variable models.GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").First(&variable, "id = ?", id).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, &common.GlobalVariableNotFoundError{}+ return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found"))}- return nil, &common.GlobalVariablesRetrievalError{Err: err}+ return nil, errors.WrapIf(err, "Failed to retrieve global variables")}key := variable.Keyif req.Key != nil {key = strings.TrimSpace(*req.Key)if !envKeyPattern.MatchString(key) {- return nil, &common.InvalidEnvKeyError{Key: *req.Key}+ return nil, common.Classify(common.ErrInvalidEnvKey, errors.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))}}@@ -163,7 +164,7 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req envreturn err}if err := tx.Omit("Environments").Save(&variable).Error; err != nil {- return fmt.Errorf("failed to update global variable: %w", err)+ return errors.WrapIf(err, "failed to update global variable")}return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)})@@ -181,7 +182,7 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env// made readable without a replacement value (revealing the stored one).func resolveUpdatedValueInternal(variable *models.GlobalVariable, reqValue *string, isSecret bool) (string, error) {if variable.IsSecret && !isSecret && reqValue == nil {- return "", &common.GlobalVariableSecretValueRequiredError{}+ return "", common.Classify(common.ErrGlobalVariableSecretValueRequired, errors.New("A new value is required when making a secret variable readable"))}switch {@@ -191,14 +192,14 @@ func resolveUpdatedValueInternal(variable *models.GlobalVariable, reqValue *stri}encrypted, err := crypto.Encrypt(*reqValue)if err != nil {- return "", &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}+ return "", errors.WrapIf(err, "Failed to update global variables")}return encrypted, nilcase isSecret && !variable.IsSecret:// Readable value becoming secret keeps its current plaintext, encrypted.encrypted, err := crypto.Encrypt(variable.Value)if err != nil {- return "", &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}+ return "", errors.WrapIf(err, "Failed to update global variables")}return encrypted, nildefault:@@ -234,10 +235,10 @@ func (s *VariableService) DeleteVariable(ctx context.Context, id string) error {err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Delete(&models.GlobalVariable{}, "id = ?", id)if result.Error != nil {- return fmt.Errorf("failed to delete global variable: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete global variable")}if result.RowsAffected == 0 {- return &common.GlobalVariableNotFoundError{}+ return common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found"))}return tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", id).Error})@@ -308,7 +309,7 @@ func (s *VariableService) SyncEnvironment(ctx context.Context, envID string) errfunc (s *VariableService) syncEnvironmentInternal(ctx context.Context, envID string) error {if envID != localEnvironmentID {if err := s.importRemoteLegacyVarsOnceInternal(ctx, envID); err != nil {- return fmt.Errorf("failed to import existing variables from environment %s: %w", envID, err)+ return errors.WrapIff(err, "failed to import existing variables from environment %s", envID)}}@@ -323,7 +324,7 @@ func (s *VariableService) syncEnvironmentInternal(ctx context.Context, envID strbody, err := json.Marshal(env.Summary{Variables: vars})if err != nil {- return fmt.Errorf("failed to marshal variables for sync: %w", err)+ return errors.WrapIf(err, "failed to marshal variables for sync")}var out struct {@@ -440,7 +441,7 @@ func (s *VariableService) recordSyncStatusInternal(envID string, err error) {func (s *VariableService) localEnvFilePathInternal(ctx context.Context) (string, error) {projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return "", fmt.Errorf("failed to get projects directory: %w", err)+ return "", errors.WrapIf(err, "failed to get projects directory")}return filepath.Join(projectsDirectory, projects.GlobalEnvFileName), nil@@ -459,7 +460,7 @@ func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable,file, err := os.Open(envPath)if err != nil {- return nil, fmt.Errorf("failed to open global variables file: %w", err)+ return nil, errors.WrapIf(err, "failed to open global variables file")}defer func() { _ = file.Close() }()@@ -500,7 +501,7 @@ func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable,}if err := scanner.Err(); err != nil {- return nil, fmt.Errorf("error reading global variables file: %w", err)+ return nil, errors.WrapIf(err, "error reading global variables file")}return vars, nil@@ -514,7 +515,7 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.VariprojectsDirectory := filepath.Dir(envPath)if err := os.MkdirAll(projectsDirectory, common.DirPerm); err != nil {- return fmt.Errorf("failed to create projects directory: %w", err)+ return errors.WrapIf(err, "failed to create projects directory")}var builder strings.Builder@@ -531,10 +532,13 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Varikey := strings.TrimSpace(v.Key)if !envKeyPattern.MatchString(key) {- return &common.InvalidEnvKeyError{Key: v.Key}+ return common.Classify(common.ErrInvalidEnvKey, errors.++ // The value is written verbatim: leading/trailing whitespace is+ // intentional and survives inside the quoted form below.+ Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))}- // The value is written verbatim: leading/trailing whitespace is- // intentional and survives inside the quoted form below.+value := v.Valueif strings.ContainsAny(value, " \t\n\r#") {@@ -545,7 +549,7 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Vari}if err := projects.WriteFileWithPerm(envPath, builder.String(), common.FilePerm); err != nil {- return fmt.Errorf("failed to write global variables file: %w", err)+ return errors.WrapIf(err, "failed to write global variables file")}slog.InfoContext(ctx, "Updated global variables",@@ -653,7 +657,7 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []enreturn replaceVariableScopeRowsInternal(tx, variable.ID, []string{scopeEnvID})})if err != nil {- return fmt.Errorf("failed to import legacy variable %q: %w", key, err)+ return errors.WrapIff(err, "failed to import legacy variable %q", key)}covered[key] = trueslog.InfoContext(ctx, "Imported legacy global variable", "key", key, "environment_id", scopeEnvID)@@ -669,7 +673,7 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []enfunc (s *VariableService) loadVariablesInternal(ctx context.Context) ([]models.GlobalVariable, error) {var variables []models.GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").Order("key").Find(&variables).Error; err != nil {- return nil, fmt.Errorf("failed to load global variables: %w", err)+ return nil, errors.WrapIf(err, "failed to load global variables")}return variables, nil}@@ -691,15 +695,15 @@ func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnviron// An explicitly specific scope with no environments must not silently// widen to all environments.if len(unique) == 0 {- return nil, &common.GlobalVariableScopeRequiredError{}+ return nil, common.Classify(common.ErrGlobalVariableScopeRequired, errors.New("At least one environment is required when a variable is not scoped to all environments"))}var count int64if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {- return nil, &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to validate environment scope: %w", err)}+ return nil, errors.WrapIf(err, "Failed to update global variables")}if count != int64(len(unique)) {- return nil, &common.GlobalVariablesUpdateError{Err: errors.New("scope references unknown environments")}+ return nil, errors.New("Failed to update global variables: one or more environments do not exist")}return unique, nil}@@ -714,7 +718,7 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string,query = query.Where("id <> ?", excludeID)}if err := query.Find(&others).Error; err != nil {- return fmt.Errorf("failed to check for conflicting variables: %w", err)+ return errors.WrapIf(err, "failed to check for conflicting variables")}for _, other := range others {@@ -722,12 +726,12 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string,continue}if allEnvironments {- return &common.GlobalVariableConflictError{Key: key}+ return common.Classify(common.ErrGlobalVariableConflict, errors.Errorf("A variable named %q already exists for an overlapping environment scope", key))}otherIDs := scopedEnvironmentIDsInternal(other.Environments)for _, id := range envIDs {if slices.Contains(otherIDs, id) {- return &common.GlobalVariableConflictError{Key: key}+ return common.Classify(common.ErrGlobalVariableConflict, errors.Errorf("A variable named %q already exists for an overlapping environment scope", key))}}}@@ -738,11 +742,11 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string,// of relying on FK cascades (the sqlite FK pragma is DSN-dependent).func replaceVariableScopeRowsInternal(tx *gorm.DB, variableID string, envIDs []string) error {if err := tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", variableID).Error; err != nil {- return fmt.Errorf("failed to clear variable scope: %w", err)+ return errors.WrapIf(err, "failed to clear variable scope")}for _, envID := range envIDs {if err := tx.Exec("INSERT INTO global_variable_environments (global_variable_id, environment_id) VALUES (?, ?)", variableID, envID).Error; err != nil {- return fmt.Errorf("failed to set variable scope: %w", err)+ return errors.WrapIf(err, "failed to set variable scope")}}return nil@@ -750,12 +754,12 @@ func replaceVariableScopeRowsInternal(tx *gorm.DB, variableID string, envIDs []sfunc wrapVariableMutationErrorInternal(err error) error {if err == nil ||- common.IsGlobalVariableConflictError(err) ||- common.IsGlobalVariableNotFoundError(err) ||- common.IsInvalidEnvKeyError(err) {+ errors.Is(err, common.ErrGlobalVariableConflict) ||+ errors.Is(err, common.ErrGlobalVariableNotFound) ||+ errors.Is(err, common.ErrInvalidEnvKey) {return err}- return &common.GlobalVariablesUpdateError{Err: err}+ return errors.WrapIf(err, "Failed to update global variables")}func scopedEnvironmentIDsInternal(environments []models.Environment) []string {diff --git a/backend/internal/services/variable_service_test.go b/backend/internal/services/variable_service_test.goindex 157530fa7..6d9561bbe 100644--- a/backend/internal/services/variable_service_test.go+++ b/backend/internal/services/variable_service_test.go@@ -13,6 +13,7 @@ import ("sync""testing"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -129,7 +130,7 @@ func TestUpdateVariable_SecretToPlainRequiresReplacementValue(t *testing.T) {plain := false_, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{IsSecret: &plain})require.Error(t, err)- require.True(t, common.IsGlobalVariableSecretValueRequiredError(err))+ require.True(t, errors.Is(err, common.ErrGlobalVariableSecretValueRequired))replacement := "public-value"updated, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{@@ -171,7 +172,7 @@ func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {_, err = service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{Key: "NO_SCOPE", Value: "x", AllEnvironments: false, EnvironmentIDs: []string{},})- require.True(t, common.IsGlobalVariableScopeRequiredError(err), "expected GlobalVariableScopeRequiredError, got %v", err)+ require.True(t, errors.Is(err, common.ErrGlobalVariableScopeRequired), "expected GlobalVariableScopeRequiredError, got %v", err)forA, err := service.resolveEffectiveVariablesInternal(ctx, "env-a")require.NoError(t, err)@@ -188,7 +189,7 @@ func TestWriteLocalEnvFile_RejectsNewlineInjectionKey(t *testing.T) {err := service.WriteLocalEnvFile(context.Background(), []envtypes.Variable{{Key: "BENIGN\nINJECTED", Value: "x"},})- require.True(t, common.IsInvalidEnvKeyError(err), "expected InvalidEnvKeyError, got %v", err)+ require.True(t, errors.Is(err, common.ErrInvalidEnvKey), "expected InvalidEnvKeyError, got %v", err)_, statErr := os.Stat(filepath.Join(projectsDir, ".env.global"))require.True(t, os.IsNotExist(statErr), ".env.global must not be written on validation failure")diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.goindex b691f516a..617ab5033 100644--- a/backend/internal/services/version_service.go+++ b/backend/internal/services/version_service.go@@ -3,13 +3,14 @@ package servicesimport ("context"json "encoding/json/v2"- "errors""fmt""log/slog""net/http""strings""time"+ "emperror.dev/errors"+ref "github.com/distribution/reference"containertypes "github.com/moby/moby/api/types/container""github.com/moby/moby/client"@@ -93,17 +94,17 @@ func (s *VersionService) getLatestReleaseInternal(_ context.Context) (latestRelefunc (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latestRelease, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, versionCheckURL, nil)if err != nil {- return latestRelease{}, fmt.Errorf("create GitHub request: %w", err)+ return latestRelease{}, errors.WrapIf(err, "create GitHub request")}resp, err := s.httpClient.Do(req)if err != nil {- return latestRelease{}, fmt.Errorf("get latest release: %w", err)+ return latestRelease{}, errors.WrapIf(err, "get latest release")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return latestRelease{}, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)+ return latestRelease{}, errors.Errorf("GitHub API returned status %d", resp.StatusCode)}var payload struct {@@ -112,7 +113,7 @@ func (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latestPublishedAt string `json:"published_at"`}if err := json.UnmarshalRead(resp.Body, &payload); err != nil {- return latestRelease{}, fmt.Errorf("decode payload: %w", err)+ return latestRelease{}, errors.WrapIf(err, "decode payload")}if payload.TagName == "" {return latestRelease{}, errors.New("GitHub API returned empty tag name")diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.goindex 427119625..a482feed2 100644--- a/backend/internal/services/volume_service.go+++ b/backend/internal/services/volume_service.go@@ -5,7 +5,6 @@ import ("bytes""compress/gzip""context"- "errors""fmt""io""log/slog"@@ -17,6 +16,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -98,13 +99,13 @@ func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*voluslog.DebugContext(ctx, "volume service: get volume", "volume", name)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}volResult, err := dockerClient.VolumeInspect(ctx, name, client.VolumeInspectOptions{})vol := volResult.Volumeif err != nil {- return nil, fmt.Errorf("volume not found: %w", err)+ return nil, errors.WrapIf(err, "volume not found")}settings := s.settingsService.GetSettingsConfig()@@ -140,19 +141,19 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}created, err := dockerClient.VolumeCreate(ctx, options)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})- return nil, fmt.Errorf("failed to create volume: %w", err)+ return nil, errors.WrapIf(err, "failed to create volume")}vol, err := dockerClient.VolumeInspect(ctx, created.Volume.Name, client.VolumeInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", created.Volume.Name, created.Volume.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver, "step": "inspect"})- return nil, fmt.Errorf("failed to inspect created volume: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect created volume")}metadata := models.JSON{@@ -174,7 +175,7 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})- return fmt.Errorf("failed to connect to Docker: %w", err)+ return errors.WrapIf(err, "failed to connect to Docker")}// Stop any read-only browse helper first; a helper mounting the volume would@@ -187,7 +188,7 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force booForce: force,}); err != nil {s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})- return fmt.Errorf("failed to remove volume: %w", err)+ return errors.WrapIf(err, "failed to remove volume")}metadata := models.JSON{@@ -212,7 +213,7 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (slog.DebugContext(ctx, "volume service: prune volumes with options", "all", all)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}// Stop all read-only browse helpers first; a helper mounting a volume marks it@@ -229,7 +230,7 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (volumePruneOptions := buildVolumePruneOptionsInternal(all, preserveTrivyCache)volumePruneResult, err := dockerClient.VolumePrune(ctx, volumePruneOptions)if err != nil {- return nil, fmt.Errorf("failed to prune volumes: %w", err)+ return nil, errors.WrapIf(err, "failed to prune volumes")}metadata := buildVolumePruneMetadataInternal(all, len(volumePruneResult.Report.VolumesDeleted), volumePruneResult.Report.SpaceReclaimed, preserveTrivyCache)@@ -291,10 +292,10 @@ func buildVolumePruneMetadataInternal(all bool, volumesDeleted int, spaceReclaimfunc (s *VolumeService) isBrowsableVolumeInternal(ctx context.Context, volumeName string) error {vol, err := s.GetVolumeByName(ctx, volumeName)if err != nil {- return fmt.Errorf("failed to inspect volume: %w", err)+ return errors.WrapIf(err, "failed to inspect volume")}if vol.Options["type"] == "none" || strings.Contains(vol.Options["o"], "bind") {- return fmt.Errorf("volume %q uses a custom mount configuration and cannot be browsed", volumeName)+ return errors.Errorf("volume %q uses a custom mount configuration and cannot be browsed", volumeName)}return nil}@@ -308,7 +309,7 @@ func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath ssanitizedPath, err := utils.SanitizeBrowsePath(dirPath)if err != nil {- return nil, fmt.Errorf("invalid path: %w", err)+ return nil, errors.WrapIf(err, "invalid path")}containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, true)@@ -322,7 +323,7 @@ func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath scmd := []string{"sh", "-c", fmt.Sprintf("find %s -mindepth 1 -maxdepth 1 | while IFS= read -r f; do out=$(stat -c \"%%s %%Y %%f %%A\" -- \"$f\" 2>/dev/null) || continue; printf \"%%s\\0%%s\\0\" \"$f\" \"$out\"; done", quotedPath)}stdout, _, err := s.execInContainerInternal(ctx, containerID, cmd)if err != nil {- return nil, fmt.Errorf("failed to list directory: %w", err)+ return nil, errors.WrapIf(err, "failed to list directory")}lines := strings.Split(stdout, "\x00")@@ -395,7 +396,7 @@ func (s *VolumeService) GetFileContent(ctx context.Context, volumeName, filePathsanitizedPath, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return nil, "", fmt.Errorf("invalid path: %w", err)+ return nil, "", errors.WrapIf(err, "invalid path")}containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, true)@@ -408,7 +409,7 @@ func (s *VolumeService) GetFileContent(ctx context.Context, volumeName, filePathcmd := []string{"head", "-c", strconv.FormatInt(maxBytes, 10), targetPath}stdout, _, err := s.execInContainerInternal(ctx, containerID, cmd)if err != nil {- return nil, "", fmt.Errorf("failed to read file: %w", err)+ return nil, "", errors.WrapIf(err, "failed to read file")}content := []byte(stdout)@@ -426,7 +427,7 @@ func (s *VolumeService) DownloadFile(ctx context.Context, volumeName, filePath ssanitizedPath, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return nil, 0, fmt.Errorf("invalid path: %w", err)+ return nil, 0, errors.WrapIf(err, "invalid path")}dockerClient, err := s.dockerService.GetClient(ctx)@@ -452,7 +453,7 @@ func getVolumeHelperImageInternal(ctx context.Context, dockerService *DockerClie}dockerClient, err = dockerService.GetClient(ctx)if err != nil {- return "", fmt.Errorf("failed to get docker client: %w", err)+ return "", errors.WrapIf(err, "failed to get docker client")}}@@ -480,7 +481,7 @@ func getVolumeHelperImageInternal(ctx context.Context, dockerService *DockerCliereturn fallback.Image, nil}- return "", fmt.Errorf("failed to resolve helper image: tools image unavailable and arcane fallback not found (pull error: %w)", pullErr)+ return "", errors.WrapIf(pullErr, "failed to resolve helper image: tools image unavailable and arcane fallback not found")}func resolveBackupStorageMountFromMountsInternal(mounts []container.MountPoint, target string, readOnly bool) mo.Option[backupStorageMountInternal] {@@ -634,12 +635,12 @@ func (s *VolumeService) createBackupTempContainerWithMountInternal(ctx context.CHostConfig: hostConfig,})if err != nil {- return "", nil, fmt.Errorf("failed to create backup temp container: %w", err)+ return "", nil, errors.WrapIf(err, "failed to create backup temp container")}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return "", nil, fmt.Errorf("failed to start backup temp container: %w", err)+ return "", nil, errors.WrapIf(err, "failed to start backup temp container")}cleanup := func() {@@ -749,12 +750,12 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeNHostConfig: hostConfig,})if err != nil {- return "", nil, fmt.Errorf("failed to create temp container: %w", err)+ return "", nil, errors.WrapIf(err, "failed to create temp container")}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return "", nil, fmt.Errorf("failed to start temp container: %w", err)+ return "", nil, errors.WrapIf(err, "failed to start temp container")}cleanup := func() {@@ -838,7 +839,7 @@ func (s *VolumeService) ReapIdleHelpers(ctx context.Context, idleTimeout time.DudockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, fmt.Errorf("failed to get docker client for idle helper reap: %w", err)+ return 0, errors.WrapIf(err, "failed to get docker client for idle helper reap")}staleIDs := s.collectStaleHelperIDsInternal(time.Now(), idleTimeout)@@ -887,7 +888,7 @@ func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return fmt.Errorf("failed to get docker client for helper stop: %w", err)+ return errors.WrapIf(err, "failed to get docker client for helper stop")}containerID := s.takeHelperIDInternal(volumeName)@@ -896,7 +897,7 @@ func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error}if _, err := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); err != nil {- return fmt.Errorf("failed to remove helper container: %w", err)+ return errors.WrapIf(err, "failed to remove helper container")}return nil@@ -920,12 +921,12 @@ func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, fmt.Errorf("failed to get docker client for orphan helper cleanup: %w", err)+ return 0, errors.WrapIf(err, "failed to get docker client for orphan helper cleanup")}containers, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return 0, fmt.Errorf("failed to list containers for orphan helper cleanup: %w", err)+ return 0, errors.WrapIf(err, "failed to list containers for orphan helper cleanup")}removedCount := 0@@ -991,7 +992,7 @@ func (s *VolumeService) execInContainerInternal(ctx context.Context, containerIDinspect, err := dockerClient.ExecInspect(ctx, execResp.ID, client.ExecInspectOptions{})if err != nil {- return stdout.String(), stderr.String(), fmt.Errorf("failed to inspect exec result: %w", err)+ return stdout.String(), stderr.String(), errors.WrapIf(err, "failed to inspect exec result")}if inspect.ExitCode != 0 {@@ -1000,9 +1001,9 @@ func (s *VolumeService) execInContainerInternal(ctx context.Context, containerIDexecErr = strings.TrimSpace(stdout.String())}if execErr != "" {- return stdout.String(), stderr.String(), fmt.Errorf("command exited with code %d: %s", inspect.ExitCode, execErr)+ return stdout.String(), stderr.String(), errors.Errorf("command exited with code %d: %s", inspect.ExitCode, execErr)}- return stdout.String(), stderr.String(), fmt.Errorf("command exited with code %d", inspect.ExitCode)+ return stdout.String(), stderr.String(), errors.Errorf("command exited with code %d", inspect.ExitCode)}return stdout.String(), stderr.String(), nil@@ -1013,7 +1014,7 @@ func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath strsanitizedPath, err := utils.SanitizeBrowsePath(filePath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}// Prevent deleting rootif sanitizedPath == "/" {@@ -1032,7 +1033,7 @@ func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath strreturn err}if stderr != "" {- return fmt.Errorf("delete failed: %s", stderr)+ return errors.Errorf("delete failed: %s", stderr)}actingUser := user@@ -1054,7 +1055,7 @@ func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPathsanitizedPath, err := utils.SanitizeBrowsePath(dirPath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, false)@@ -1069,7 +1070,7 @@ func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPathreturn err}if stderr != "" {- return fmt.Errorf("mkdir failed: %s", stderr)+ return errors.Errorf("mkdir failed: %s", stderr)}actingUser := user@@ -1091,7 +1092,7 @@ func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath strsanitizedPath, err := utils.SanitizeBrowsePath(destPath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}dockerClient, err := s.dockerService.GetClient(ctx)@@ -1135,7 +1136,7 @@ func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath strContent: &buf,})if err != nil {- return fmt.Errorf("failed to upload: %w", err)+ return errors.WrapIf(err, "failed to upload")}actingUser := user@@ -1167,7 +1168,7 @@ func (s *VolumeService) ensureBackupVolumeInternal(ctx context.Context) error {Name: s.backupVolumeName,})if err != nil {- return fmt.Errorf("failed to create backup volume: %w", err)+ return errors.WrapIf(err, "failed to create backup volume")}}return nil@@ -1211,12 +1212,12 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, useHostConfig: hostConfig,})if err != nil {- return nil, fmt.Errorf("failed to create backup container: %w", err)+ return nil, errors.WrapIf(err, "failed to create backup container")}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return nil, fmt.Errorf("failed to start backup container: %w", err)+ return nil, errors.WrapIf(err, "failed to start backup container")}waitResult := dockerClient.ContainerWait(ctx, resp.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})@@ -1227,7 +1228,7 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, use}case status := <-waitResult.Result:if status.StatusCode != 0 {- return nil, fmt.Errorf("backup container exited with status %d", status.StatusCode)+ return nil, errors.Errorf("backup container exited with status %d", status.StatusCode)}}@@ -1403,7 +1404,7 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID// Validate backup belongs to volumeif backup.VolumeName != volumeName {- return fmt.Errorf("backup does not belong to volume %s", volumeName)+ return errors.Errorf("backup does not belong to volume %s", volumeName)}// Check if volume is in use by running containers@@ -1411,12 +1412,12 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupIDif err != nil {slog.WarnContext(ctx, "could not check volume usage", "volume", volumeName, "error", err.Error())} else if inUse {- return fmt.Errorf("volume is in use by %d container(s): restoring while containers are running may cause data corruption. Stop the containers first or use selective file restore", len(containerIDs))+ return errors.Errorf("volume is in use by %d container(s): restoring while containers are running may cause data corruption. Stop the containers first or use selective file restore", len(containerIDs))}preBackup, err := s.CreateBackup(ctx, volumeName, user)if err != nil {- return fmt.Errorf("failed to create pre-restore backup: %w", err)+ return errors.WrapIf(err, "failed to create pre-restore backup")}dockerClient, err := s.dockerService.GetClient(ctx)@@ -1458,12 +1459,12 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupIDHostConfig: hostConfig,})if err != nil {- return fmt.Errorf("failed to create restore container: %w", err)+ return errors.WrapIf(err, "failed to create restore container")}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return fmt.Errorf("failed to start restore container: %w", err)+ return errors.WrapIf(err, "failed to start restore container")}waitResult := dockerClient.ContainerWait(ctx, resp.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})@@ -1477,7 +1478,7 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID}if waitBody.StatusCode != 0 {- return fmt.Errorf("restore container exited with code %d (volume may be partially wiped)", waitBody.StatusCode)+ return errors.Errorf("restore container exited with code %d (volume may be partially wiped)", waitBody.StatusCode)}metadata := models.JSON{@@ -1499,13 +1500,13 @@ func (s *VolumeService) sanitizeBackupPathInternal(input string) (string, error)}cleaned := path.Clean(trimmed)if cleaned == "." || cleaned == "/" {- return "", fmt.Errorf("invalid path: %s", input)+ return "", errors.Errorf("invalid path: %s", input)}if path.IsAbs(cleaned) {cleaned = strings.TrimPrefix(cleaned, "/")}if cleaned == "" || cleaned == "." || cleaned == "/" || strings.HasPrefix(cleaned, "..") || strings.Contains(cleaned, "/../") {- return "", fmt.Errorf("invalid path: %s", input)+ return "", errors.Errorf("invalid path: %s", input)}return cleaned, nil}@@ -1513,7 +1514,7 @@ func (s *VolumeService) sanitizeBackupPathInternal(input string) (string, error)func (s *VolumeService) sanitizeBackupIDInternal(backupID string) (string, error) {cleaned, err := s.sanitizeBackupPathInternal(backupID)if err != nil {- return "", fmt.Errorf("invalid backup id: %w", err)+ return "", errors.WrapIf(err, "invalid backup id")}if strings.Contains(cleaned, "/") {return "", errors.New("invalid backup id: path separators not allowed")@@ -1574,7 +1575,7 @@ func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, filereturn false, err}if strings.TrimSpace(stderr) != "" {- return false, fmt.Errorf("failed to list backup contents: %s", strings.TrimSpace(stderr))+ return false, errors.Errorf("failed to list backup contents: %s", strings.TrimSpace(stderr))}for line := range strings.SplitSeq(stdout, "\n") {@@ -1674,7 +1675,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, back// Create pre-restore backup for safety (consistent with RestoreBackup behavior)preBackup, err := s.CreateBackup(ctx, volumeName, user)if err != nil {- return fmt.Errorf("failed to create pre-restore backup: %w", err)+ return errors.WrapIf(err, "failed to create pre-restore backup")}slog.DebugContext(ctx, "created pre-restore backup", "volume", volumeName, "pre_backup_id", preBackup.ID)@@ -1726,12 +1727,12 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backHostConfig: hostConfig,})if err != nil {- return fmt.Errorf("failed to create restore container: %w", err)+ return errors.WrapIf(err, "failed to create restore container")}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return fmt.Errorf("failed to start restore container: %w", err)+ return errors.WrapIf(err, "failed to start restore container")}cleanup := func() {@@ -1742,7 +1743,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backcmd := append([]string{"tar", "-xzf", path.Join("/backups", filename), "-C", "/volume", "--"}, tarPaths...)_, stderr, err := s.execInContainerInternal(ctx, resp.ID, cmd)if err != nil {- return fmt.Errorf("failed to restore files: %w", err)+ return errors.WrapIf(err, "failed to restore files")}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore files stderr", "backup_id", backupID, "stderr", strings.TrimSpace(stderr))@@ -1814,31 +1815,31 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,tmpFile, err := os.CreateTemp("", "arcane-restore-*.tar.gz")if err != nil {- return fmt.Errorf("failed to buffer upload: %w", err)+ return errors.WrapIf(err, "failed to buffer upload")}defer func() {_ = tmpFile.Close()_ = os.Remove(tmpFile.Name())}()if _, err := io.Copy(tmpFile, archive); err != nil {- return fmt.Errorf("failed to buffer upload: %w", err)+ return errors.WrapIf(err, "failed to buffer upload")}if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {- return fmt.Errorf("failed to read buffered upload: %w", err)+ return errors.WrapIf(err, "failed to read buffered upload")}gzr, err := gzip.NewReader(tmpFile)if err != nil {- return fmt.Errorf("invalid archive: %w", err)+ return errors.WrapIf(err, "invalid archive")}if _, err := tar.NewReader(gzr).Next(); err != nil {_ = gzr.Close()- return fmt.Errorf("invalid archive: %w", err)+ return errors.WrapIf(err, "invalid archive")}_ = gzr.Close()preBackup, err := s.CreateBackup(ctx, volumeName, user)if err != nil {- return fmt.Errorf("failed to create pre-restore backup: %w", err)+ return errors.WrapIf(err, "failed to create pre-restore backup")}dockerClient, err := s.dockerService.GetClient(ctx)@@ -1855,26 +1856,26 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,tmpDir := fmt.Sprintf("/volume/.restore_tmp_%d", time.Now().UnixNano())_, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"mkdir", "-p", tmpDir})if err != nil {- return fmt.Errorf("failed to create temp restore dir: %w", err)+ return errors.WrapIf(err, "failed to create temp restore dir")}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore temp dir stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))}if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {- return fmt.Errorf("failed to read buffered upload: %w", err)+ return errors.WrapIf(err, "failed to read buffered upload")}_, err = dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{DestinationPath: tmpDir,Content: tmpFile,})if err != nil {- return fmt.Errorf("failed to restore from uploaded archive: %w", err)+ return errors.WrapIf(err, "failed to restore from uploaded archive")}_, stderr, err = s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", fmt.Sprintf("test -n \"$(find %s -mindepth 1 -maxdepth 1 -print -quit)\"", tmpDir)})if err != nil {- return fmt.Errorf("uploaded archive appears empty or invalid: %w", err)+ return errors.WrapIf(err, "uploaded archive appears empty or invalid")}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore validate stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1882,7 +1883,7 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,_, stderr, err = s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", "rm -rf /volume/* /volume/.[!.]* /volume/..?* 2>/dev/null || true"})if err != nil {- return fmt.Errorf("failed to clear volume before restore: %w", err)+ return errors.WrapIf(err, "failed to clear volume before restore")}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore clear stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1891,7 +1892,7 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,moveCmd := fmt.Sprintf("find %s -mindepth 1 -maxdepth 1 -exec mv -- {} /volume/ \\; && rmdir %s", tmpDir, tmpDir)_, stderr, err = s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", moveCmd})if err != nil {- return fmt.Errorf("failed to move restored files into place: %w", err)+ return errors.WrapIf(err, "failed to move restored files into place")}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore move stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1913,17 +1914,17 @@ func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool,slog.DebugContext(ctx, "volume service: get volume usage", "volume", name)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return false, nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return false, nil, errors.WrapIf(err, "failed to connect to Docker")}vol, err := dockerClient.VolumeInspect(ctx, name, client.VolumeInspectOptions{})if err != nil {- return false, nil, fmt.Errorf("volume not found: %w", err)+ return false, nil, errors.WrapIf(err, "volume not found")}containerIDs, err := docker.GetContainersUsingVolume(ctx, dockerClient, vol.Volume.Name)if err != nil {- return false, nil, fmt.Errorf("failed to get containers using volume: %w", err)+ return false, nil, errors.WrapIf(err, "failed to get containers using volume")}inUse := len(containerIDs) > 0@@ -1946,12 +1947,12 @@ func (s *VolumeService) GetVolumeSizes(ctx context.Context) (map[string]VolumeSidockerClient, err := s.dockerService.GetClient(apiCtx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}usageVolumes, err := docker.GetVolumeUsageData(apiCtx, dockerClient)if err != nil {- return nil, fmt.Errorf("failed to get volume usage data: %w", err)+ return nil, errors.WrapIf(err, "failed to get volume usage data")}result := make(map[string]VolumeSizeData, len(usageVolumes))@@ -1993,7 +1994,7 @@ func (s *VolumeService) enrichVolumesWithUsageDataInternal(volumes []volume.Volufunc (s *VolumeService) buildVolumeContainerMapInternal(ctx context.Context, dockerClient *client.Client) (map[string][]string, error) {containers, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return nil, fmt.Errorf("failed to list containers: %w", err)+ return nil, errors.WrapIf(err, "failed to list containers")}volumeContainerMap := make(map[string][]string)@@ -2160,7 +2161,7 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginatslog.DebugContext(ctx, "volume service: list volumes paginated", "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit, "include_internal", includeInternal)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, pagination.Response{}, volumetypes.UsageCounts{}, errors.WrapIf(err, "failed to connect to Docker")}// Run volume list and container list in parallel for better performance@@ -2193,7 +2194,7 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginat// Wait for both resultsvolResult := <-volChanif volResult.err != nil {- return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to list Docker volumes: %w", volResult.err)+ return nil, pagination.Response{}, volumetypes.UsageCounts{}, errors.WrapIf(volResult.err, "failed to list Docker volumes")}containerResult := <-containerChan@@ -2275,7 +2276,7 @@ func (s *VolumeService) downloadFileFromContainerInternal(})if err != nil {cleanup()- return nil, 0, fmt.Errorf("failed to download: %w", err)+ return nil, 0, errors.WrapIf(err, "failed to download")}reader := copyResult.Content@@ -2284,7 +2285,7 @@ func (s *VolumeService) downloadFileFromContainerInternal(if err != nil {_ = reader.Close()cleanup()- return nil, 0, fmt.Errorf("failed to read tar stream: %w", err)+ return nil, 0, errors.WrapIf(err, "failed to read tar stream")}if hdr.FileInfo().IsDir() {_ = reader.Close()diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.goindex 736e00400..cb9ba3c40 100644--- a/backend/internal/services/vulnerability_service.go+++ b/backend/internal/services/vulnerability_service.go@@ -6,7 +6,6 @@ import ("context""encoding/json/jsontext"json "encoding/json/v2"- "errors""fmt""io""log/slog"@@ -20,6 +19,8 @@ import ("sync""time"+ "emperror.dev/errors"+cerrdefs "github.com/containerd/errdefs""github.com/moby/moby/api/pkg/stdcopy"containertypes "github.com/moby/moby/api/types/container"@@ -285,13 +286,13 @@ func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imag// Get Docker client to inspect the imagedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}// Inspect the image to get detailsimageInspect, err := dockerClient.ImageInspect(scanCtx, imageID)if err != nil {- return nil, fmt.Errorf("failed to inspect image: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect image")}// Determine image name to scan@@ -551,7 +552,7 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, imageID stringif errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, fmt.Errorf("failed to get scan result: %w", err)+ return nil, errors.WrapIf(err, "failed to get scan result")}s.markStaleScanIfNeeded(ctx, &record)@@ -574,7 +575,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strinif errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, fmt.Errorf("failed to get scan summary: %w", err)+ return nil, errors.WrapIf(err, "failed to get scan summary")}s.markStaleScanIfNeeded(ctx, &record)@@ -602,7 +603,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strinfunc (s *VulnerabilityService) ListVulnerabilities(ctx context.Context, imageID string, params pagination.QueryParams) ([]vulnerability.Vulnerability, pagination.Response, error) {result, err := s.GetScanResult(ctx, imageID)if err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to get scan result: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to get scan result")}if result == nil {limit := params.Limit@@ -722,7 +723,7 @@ func (s *VulnerabilityService) GetEnvironmentSummary(ctx context.Context) (*vulnWhere("status = ?", models.ScanStatusCompleted).Scan(&agg).Errorif err != nil {- return nil, fmt.Errorf("failed to aggregate vulnerability summary: %w", err)+ return nil, errors.WrapIf(err, "failed to aggregate vulnerability summary")}summary.ScannedImages = agg.Scanned@@ -753,7 +754,7 @@ func (s *VulnerabilityService) getActionableCountExcludingIgnoredInternal(ctx coWhere("critical_count + high_count > 0").Find(&records).Errorif err != nil {- return 0, fmt.Errorf("failed to list vulnerability scans: %w", err)+ return 0, errors.WrapIf(err, "failed to list vulnerability scans")}if len(records) == 0 {@@ -765,7 +766,7 @@ func (s *VulnerabilityService) getActionableCountExcludingIgnoredInternal(ctx co// an environment ID through the service layer today).var ignores []models.VulnerabilityIgnoreif err := s.db.WithContext(ctx).Find(&ignores).Error; err != nil {- return 0, fmt.Errorf("failed to get ignore records: %w", err)+ return 0, errors.WrapIf(err, "failed to get ignore records")}ignoredKeys := make(map[string]struct{}, len(ignores))@@ -835,7 +836,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envIDvar records []models.VulnerabilityScanRecordif err := recordsQuery.Find(&records).Error; err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list vulnerability scans: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list vulnerability scans")}ignoredKeys, err := s.getIgnoredVulnerabilityKeySetByEnvironmentInternal(ctx, envID)@@ -968,7 +969,7 @@ func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Contvar records []models.VulnerabilityScanRecordif err := query.Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to list vulnerability image options: %w", err)+ return nil, errors.WrapIf(err, "failed to list vulnerability image options")}seen := make(map[string]struct{}, len(records))@@ -1110,7 +1111,7 @@ func (s *VulnerabilityService) getIgnoredVulnerabilityKeySetByEnvironmentInternavar ignores []models.VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("environment_id = ?", envID).Find(&ignores).Error; err != nil {- return nil, fmt.Errorf("failed to get ignore records: %w", err)+ return nil, errors.WrapIf(err, "failed to get ignore records")}if len(ignores) == 0 {@@ -1155,7 +1156,7 @@ func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, iWhere("id IN ?", imageIDs).Find(&records).Errorif err != nil {- return nil, fmt.Errorf("failed to get scan summaries: %w", err)+ return nil, errors.WrapIf(err, "failed to get scan summaries")}result := make(map[string]*vulnerability.ScanSummary, len(records))@@ -1349,12 +1350,12 @@ func (s *VulnerabilityService) sendScheduledVulnerabilitySummaryInternal(func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user models.User) (scanned, failed int, err error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, 0, fmt.Errorf("failed to connect to Docker: %w", err)+ return 0, 0, errors.WrapIf(err, "failed to connect to Docker")}imageList, err := dockerClient.ImageList(ctx, client.ImageListOptions{})if err != nil {- return 0, 0, fmt.Errorf("failed to list images: %w", err)+ return 0, 0, errors.WrapIf(err, "failed to list images")}images := imageList.Items@@ -1398,12 +1399,12 @@ const (func (s *VulnerabilityService) setupTrivyBatchContainer(ctx context.Context) (string, func(), error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return "", nil, errors.WrapIf(err, "failed to connect to Docker")}trivyImage, err := s.ensureTrivyImageInternal(ctx)if err != nil {- return "", nil, fmt.Errorf("trivy scanner not available: %w", err)+ return "", nil, errors.WrapIf(err, "trivy scanner not available")}serverURL, _ := s.getTrivyServerConfig()@@ -1411,13 +1412,13 @@ func (s *VulnerabilityService) setupTrivyBatchContainer(ctx context.Context) (stif serverURL == "" {cacheVolume, err = s.ensureTrivyCacheVolumeInternal(ctx)if err != nil {- return "", nil, fmt.Errorf("failed to ensure trivy cache volume: %w", err)+ return "", nil, errors.WrapIf(err, "failed to ensure trivy cache volume")}}containerID, err := s.createBatchTrivyContainer(ctx, trivyImage, cacheVolume)if err != nil {- return "", nil, fmt.Errorf("failed to create batch trivy container: %w", err)+ return "", nil, errors.WrapIf(err, "failed to create batch trivy container")}cleanup := func() {@@ -1459,7 +1460,7 @@ func (s *VulnerabilityService) scanSingleImage(func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, trivyImage, cacheVolume string) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", fmt.Errorf("failed to connect to Docker: %w", err)+ return "", errors.WrapIf(err, "failed to connect to Docker")}runtimeOptions, err := s.resolveTrivyRuntimeOptionsInternal(ctx, dockerClient)@@ -1506,18 +1507,18 @@ func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, trfunc (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, containerID, imageName, imageID, scannerVersion string) (*vulnerability.ScanResult, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}stdoutFile, err := createTrivyLogTempFileInternal("trivy-exec-stdout-*")if err != nil {- return nil, fmt.Errorf("failed to create trivy exec stdout temp file: %w", err)+ return nil, errors.WrapIf(err, "failed to create trivy exec stdout temp file")}stderrFile, err := createTrivyLogTempFileInternal("trivy-exec-stderr-*")if err != nil {cleanupTrivyLogTempFilesInternal(ctx, stdoutFile)- return nil, fmt.Errorf("failed to create trivy exec stderr temp file: %w", err)+ return nil, errors.WrapIf(err, "failed to create trivy exec stderr temp file")}defer cleanupTrivyLogTempFilesInternal(ctx, stdoutFile, stderrFile)@@ -1541,24 +1542,24 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, conexecResp, err := dockerClient.ExecCreate(ctx, containerID, execCfg)if err != nil {- return nil, fmt.Errorf("failed to create exec: %w", err)+ return nil, errors.WrapIf(err, "failed to create exec")}attachResp, err := dockerClient.ExecAttach(ctx, execResp.ID, client.ExecAttachOptions{})if err != nil {- return nil, fmt.Errorf("failed to attach to exec: %w", err)+ return nil, errors.WrapIf(err, "failed to attach to exec")}defer attachResp.Close()logDone := startDockerLogCopyInternal(attachResp.Reader, stdoutFile, stderrFile)if err := waitForDockerLogCopyInternal(logDone); err != nil {- return nil, fmt.Errorf("failed to read exec output: %w", err)+ return nil, errors.WrapIf(err, "failed to read exec output")}// Check exit codeexecInspect, err := dockerClient.ExecInspect(ctx, execResp.ID, client.ExecInspectOptions{})if err != nil {- return nil, fmt.Errorf("failed to inspect exec: %w", err)+ return nil, errors.WrapIf(err, "failed to inspect exec")}if execInspect.ExitCode != 0 {@@ -1597,11 +1598,11 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, conerrMsg = "trivy scan produced no output"}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, int64(execInspect.ExitCode), stdoutFile, stderrFile, "exec empty output")- return nil, fmt.Errorf("trivy scan failed: %s", errMsg)+ return nil, errors.Errorf("trivy scan failed: %s", errMsg)}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, int64(execInspect.ExitCode), stdoutFile, stderrFile, "exec parse error")- return nil, fmt.Errorf("failed to parse trivy output: %w", err)+ return nil, errors.WrapIf(err, "failed to parse trivy output")}if trivyReport == nil {@@ -1610,7 +1611,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, conerrMsg = "trivy scan produced no output"}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, int64(execInspect.ExitCode), stdoutFile, stderrFile, "exec nil report")- return nil, fmt.Errorf("trivy scan failed: %s", errMsg)+ return nil, errors.Errorf("trivy scan failed: %s", errMsg)}result := vulnerability.ConvertTrivyReportToScanResult(trivyReport, imageID, time.Now(), 0)@@ -1648,12 +1649,12 @@ func (s *VulnerabilityService) CleanupOrphanedScanRecords(ctx context.Context) (dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, fmt.Errorf("failed to connect to Docker: %w", err)+ return 0, errors.WrapIf(err, "failed to connect to Docker")}imageList, err := dockerClient.ImageList(ctx, client.ImageListOptions{})if err != nil {- return 0, fmt.Errorf("failed to list images: %w", err)+ return 0, errors.WrapIf(err, "failed to list images")}images := imageList.Items@@ -1830,12 +1831,12 @@ func resolveTrivyUnixSocketSourceInternal(return strings.TrimSpace(hostPath), nil}if err != nil && (isRunningInDocker == nil || isRunningInDocker()) {- return "", fmt.Errorf("failed to resolve socket path %q: %w", socketPath, err)+ return "", errors.WrapIff(err, "failed to resolve socket path %q", socketPath)}}if isRunningInDocker != nil && isRunningInDocker() {- return "", fmt.Errorf("failed to resolve socket path %q to a daemon-visible host path", socketPath)+ return "", errors.Errorf("failed to resolve socket path %q to a daemon-visible host path", socketPath)}return socketPath, nil@@ -1906,7 +1907,7 @@ func (s *VulnerabilityService) inspectCurrentArcaneContainerInternal(client.ContainerInspectOptions{},)if err != nil {- return nil, fmt.Errorf("inspect Arcane container: %w", err)+ return nil, errors.WrapIf(err, "inspect Arcane container")}return &inspect.Container, nil@@ -1983,7 +1984,7 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.CodockerHost := s.getEffectiveDockerHostInternal()scheme, socketPath, err := vuln.ParseDockerHost(dockerHost)if err != nil {- return trivyRuntimeOptions{}, fmt.Errorf("failed to resolve trivy docker host: %w", err)+ return trivyRuntimeOptions{}, errors.WrapIf(err, "failed to resolve trivy docker host")}options.ContainerEnv = vuln.BuildDockerHostEnv(dockerHost)@@ -2003,7 +2004,7 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.Co},)if err != nil {- return trivyRuntimeOptions{}, fmt.Errorf("failed to resolve trivy docker host: %w", err)+ return trivyRuntimeOptions{}, errors.WrapIf(err, "failed to resolve trivy docker host")}options.Mounts = append(options.Mounts, mounttypes.Mount{@@ -2058,7 +2059,7 @@ func (s *VulnerabilityService) getTrivySingleScanCacheDirForSlotInternal(slotIDfunc (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", fmt.Errorf("failed to connect to Docker: %w", err)+ return "", errors.WrapIf(err, "failed to connect to Docker")}trivyImage := s.getTrivyImageRef()@@ -2077,13 +2078,13 @@ func (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (stpullReader, err := dockerClient.ImagePull(pullCtx, trivyImage, client.ImagePullOptions{})if err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return "", fmt.Errorf("scanner image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", trivyImage)+ return "", errors.Errorf("scanner image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", trivyImage)}- return "", fmt.Errorf("pull scanner image %s: %w", trivyImage, err)+ return "", errors.WrapIff(err, "pull scanner image %s", trivyImage)}if err := dockerutils.ConsumeJSONMessageStream(pullReader, nil); err != nil {_ = pullReader.Close()- return "", fmt.Errorf("failed to complete scanner image pull: %w", err)+ return "", errors.WrapIf(err, "failed to complete scanner image pull")}_ = pullReader.Close()@@ -2107,7 +2108,7 @@ func (s *VulnerabilityService) ensureTrivyCacheVolumeInternal(ctx context.Contex},})if err != nil {- return "", fmt.Errorf("failed to create trivy cache volume: %w", err)+ return "", errors.WrapIf(err, "failed to create trivy cache volume")}return trivyCacheVolumeName, nil@@ -2357,15 +2358,15 @@ func createTrivyLogTempFileInternal(prefix string) (*os.File, error) {// per-user cache directory so Trivy scans can still run.cacheDir, err := os.UserCacheDir()if err != nil {- return nil, fmt.Errorf("failed to create trivy temp file (primary: %s) and user cache dir unavailable: %w", primaryErr.Error(), err)+ return nil, errors.WrapIff(err, "failed to create trivy temp file (primary: %s) and user cache dir unavailable", primaryErr.Error())}fallbackDir := filepath.Join(cacheDir, "arcane", "trivy-tmp")if err := os.MkdirAll(fallbackDir, 0o700); err != nil {- return nil, fmt.Errorf("failed to create trivy fallback temp dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), err)+ return nil, errors.WrapIff(err, "failed to create trivy fallback temp dir %s (primary: %s)", fallbackDir, primaryErr.Error())}fallbackFile, err := os.CreateTemp(fallbackDir, prefix)if err != nil {- return nil, fmt.Errorf("failed to create trivy temp file in fallback dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), err)+ return nil, errors.WrapIff(err, "failed to create trivy temp file in fallback dir %s (primary: %s)", fallbackDir, primaryErr.Error())}return fallbackFile, nil}@@ -2577,7 +2578,7 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal(})if err != nil {slog.WarnContext(ctx, "failed to create trivy container", "scope", scope, "error", err)- return "", fmt.Errorf("failed to create container: %w", err)+ return "", errors.WrapIf(err, "failed to create container")}if len(registryConfigJSON) > 0 {@@ -2608,7 +2609,7 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal()removeDockerContainerInternal(ctx, dockerClient, resp.ID, "failed to cleanup trivy container after start failure")- return "", fmt.Errorf("failed to start container: %w", err)+ return "", errors.WrapIf(err, "failed to start container")}return resp.ID, nil@@ -2819,7 +2820,7 @@ func readTrivyOutputFromContainerFileInternal(ctx context.Context, dockerClientcopyResult, err := dockerClient.CopyFromContainer(copyCtx, containerID, client.CopyFromContainerOptions{SourcePath: outputPath})if err != nil {- return nil, fmt.Errorf("copy trivy output file: %w", err)+ return nil, errors.WrapIf(err, "copy trivy output file")}archiveReader := copyResult.Contentdefer func() {@@ -2835,7 +2836,7 @@ func readTrivyOutputFromContainerFileInternal(ctx context.Context, dockerClientrawOutput, err := extractFileFromContainerArchiveInternal(archiveReader)if err != nil {- return nil, fmt.Errorf("extract trivy output file: %w", err)+ return nil, errors.WrapIf(err, "extract trivy output file")}if len(bytes.TrimSpace(rawOutput)) == 0 {@@ -2889,7 +2890,7 @@ func extractFileFromContainerArchiveInternal(archiveReader io.Reader) ([]byte, ebreak}if err != nil {- return nil, fmt.Errorf("read tar header: %w", err)+ return nil, errors.WrapIf(err, "read tar header")}if header == nil || header.Typeflag == tar.TypeDir {@@ -2902,7 +2903,7 @@ func extractFileFromContainerArchiveInternal(archiveReader io.Reader) ([]byte, edata, err := io.ReadAll(tarReader)if err != nil {- return nil, fmt.Errorf("read tar file content: %w", err)+ return nil, errors.WrapIf(err, "read tar file content")}return data, nil@@ -2917,12 +2918,12 @@ func decodeTrivyReportFromFileInternal(file *os.File) (*vulnerability.TrivyRepor}if _, err := file.Seek(0, io.SeekStart); err != nil {- return nil, fmt.Errorf("failed to seek trivy output file: %w", err)+ return nil, errors.WrapIf(err, "failed to seek trivy output file")}rawOutput, err := io.ReadAll(file)if err != nil {- return nil, fmt.Errorf("failed to read trivy output file: %w", err)+ return nil, errors.WrapIf(err, "failed to read trivy output file")}return decodeTrivyReportFromBytesInternal(rawOutput)@@ -3079,16 +3080,16 @@ func formatTrivyExitErrorInternal(exitCode int64, errMsg, imageName string) erroif exitCode == 137 {if errMsg == "" || errMsg == fmt.Sprintf("exit status %d", exitCode) {- return fmt.Errorf("trivy scan failed: process killed with exit status 137 (likely out of memory while scanning %s)", imageName)+ return errors.Errorf("trivy scan failed: process killed with exit status 137 (likely out of memory while scanning %s)", imageName)}- return fmt.Errorf("trivy scan failed: %s (process killed with exit status 137; likely out of memory)", errMsg)+ return errors.Errorf("trivy scan failed: %s (process killed with exit status 137; likely out of memory)", errMsg)}if strings.Contains(strings.ToLower(errMsg), "deadline exceeded") {- return fmt.Errorf("trivy scan timed out for %s (increase TRIVY_SCAN_TIMEOUT or trivyScanTimeout setting)", imageName)+ return errors.Errorf("trivy scan timed out for %s (increase TRIVY_SCAN_TIMEOUT or trivyScanTimeout setting)", imageName)}- return fmt.Errorf("trivy scan failed: %s", errMsg)+ return errors.Errorf("trivy scan failed: %s", errMsg)}func buildTrivyContainerResourcesInternal(cfg *models.Settings) mo.Option[containertypes.Resources] {@@ -3130,13 +3131,13 @@ func (s *VulnerabilityService) runTrivyContainer() (*os.File, *os.File, int64, int64, string, error) {stdoutFile, err := createTrivyLogTempFileInternal("trivy-stdout-*")if err != nil {- return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stdout temp file: %w", err)+ return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to create trivy stdout temp file")}stderrFile, err := createTrivyLogTempFileInternal("trivy-stderr-*")if err != nil {cleanupTrivyLogTempFilesInternal(ctx, stdoutFile)- return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stderr temp file: %w", err)+ return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to create trivy stderr temp file")}success := false@@ -3150,7 +3151,7 @@ func (s *VulnerabilityService) runTrivyContainer(containerID, err = s.createAndStartTrivyContainerInternal(ctx, dockerClient, "single-scan", config, hostConfig, registryConfigJSON)if err != nil {- return nil, nil, 0, 0, "", fmt.Errorf("failed to prepare trivy scan container: %w", err)+ return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to prepare trivy scan container")}slog.DebugContext(ctx, "started trivy scan container", "containerId", containerID)@@ -3164,7 +3165,7 @@ func (s *VulnerabilityService) runTrivyContainer(})if err != nil {logsCancel()- return nil, nil, 0, 0, "", fmt.Errorf("failed to stream trivy logs: %w", err)+ return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to stream trivy logs")}var closeLogsOnce sync.Once@@ -3211,14 +3212,14 @@ func (s *VulnerabilityService) runTrivyContainer(case logErr := <-logDone:closeLogs() // clean up context / connectionif logErr != nil && !isExpectedDockerStreamEndErrorInternal(logErr) {- return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)+ return nil, nil, 0, 0, "", errors.WrapIf(logErr, "failed to read trivy logs")}case <-logDrainTimer.C:// Stream did not close on its own; force-close so the goroutine exits.slog.DebugContext(ctx, "trivy log stream did not close after container exit; force-closing", "containerId", containerID)closeLogs()if logErr := waitForDockerLogCopyInternal(logDone); logErr != nil {- return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)+ return nil, nil, 0, 0, "", errors.WrapIf(logErr, "failed to read trivy logs")}}@@ -3237,12 +3238,12 @@ func (s *VulnerabilityService) waitForTrivyContainer(statusCode, err := awaitContainerWaitResponseInternal(ctx, waitResult.Result, waitResult.Error)if err != nil {if errors.Is(err, context.DeadlineExceeded) {- return 0, fmt.Errorf("trivy container wait timed out: %w", err)+ return 0, errors.WrapIf(err, "trivy container wait timed out")}if errors.Is(err, context.Canceled) {- return 0, fmt.Errorf("scan cancelled: %w", err)+ return 0, errors.WrapIf(err, "scan cancelled")}- return 0, fmt.Errorf("trivy container wait failed: %w", err)+ return 0, errors.WrapIf(err, "trivy container wait failed")}return statusCode, nil@@ -3298,7 +3299,7 @@ func (s *VulnerabilityService) runTrivyScan(ctx context.Context, trivyImage stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, errors.WrapIf(err, "failed to connect to Docker")}serverURL, serverToken := s.getTrivyServerConfig()@@ -3403,11 +3404,11 @@ func (s *VulnerabilityService) runTrivyScan(ctx context.Context, trivyImage strierrMsg = "trivy scan produced no output"}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, statusCode, stdoutFile, stderrFile, "container empty output")- return nil, fmt.Errorf("trivy scan failed: %s", errMsg)+ return nil, errors.Errorf("trivy scan failed: %s", errMsg)}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, statusCode, stdoutFile, stderrFile, "container parse error")- return nil, fmt.Errorf("failed to parse trivy output: %w", err)+ return nil, errors.WrapIf(err, "failed to parse trivy output")}if trivyReport == nil {@@ -3416,7 +3417,7 @@ func (s *VulnerabilityService) runTrivyScan(ctx context.Context, trivyImage strierrMsg = "trivy scan produced no output"}logTrivyScanFailureDiagnosticsInternal(ctx, imageName, imageID, statusCode, stdoutFile, stderrFile, "container nil report")- return nil, fmt.Errorf("trivy scan failed: %s", errMsg)+ return nil, errors.Errorf("trivy scan failed: %s", errMsg)}// Convert Trivy report to our ScanResult format@@ -3575,7 +3576,7 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulneif len(result.Vulnerabilities) > 0 {vulnBytes, err := json.Marshal(result.Vulnerabilities)if err != nil {- return fmt.Errorf("failed to marshal vulnerabilities: %w", err)+ return errors.WrapIf(err, "failed to marshal vulnerabilities")}vulnJSON = models.StringSlice{string(vulnBytes)}}@@ -3822,7 +3823,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st}if !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, fmt.Errorf("failed to check existing ignore: %w", err)+ return nil, errors.WrapIf(err, "failed to check existing ignore")}ignore := &models.VulnerabilityIgnore{@@ -3836,7 +3837,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st}if err := s.db.WithContext(ctx).Create(ignore).Error; err != nil {- return nil, fmt.Errorf("failed to create ignore record: %w", err)+ return nil, errors.WrapIf(err, "failed to create ignore record")}slog.InfoContext(ctx, "vulnerability ignored",@@ -3856,7 +3857,7 @@ func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envIDresult := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", ignoreID, envID).Delete(&models.VulnerabilityIgnore{})if result.Error != nil {- return fmt.Errorf("failed to delete ignore record: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete ignore record")}if result.RowsAffected == 0 {@@ -3959,13 +3960,13 @@ func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, e// Count totalvar total int64if err := query.Model(&models.VulnerabilityIgnore{}).Count(&total).Error; err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to count ignored vulnerabilities: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to count ignored vulnerabilities")}// Apply paginationoffset := params.Startif err := query.Offset(offset).Limit(params.Limit).Find(&ignores).Error; err != nil {- return nil, pagination.Response{}, fmt.Errorf("failed to list ignored vulnerabilities: %w", err)+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to list ignored vulnerabilities")}result := mapIgnoredVulnerabilities(ignores)@@ -3982,7 +3983,7 @@ func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envvar ignores []models.VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ?", envID, imageID).Find(&ignores).Error; err != nil {- return nil, fmt.Errorf("failed to get ignore records: %w", err)+ return nil, errors.WrapIf(err, "failed to get ignore records")}return ignores, nildiff --git a/backend/internal/services/webhook_service.go b/backend/internal/services/webhook_service.goindex 25311004c..661a04e11 100644--- a/backend/internal/services/webhook_service.go+++ b/backend/internal/services/webhook_service.go@@ -6,13 +6,14 @@ import ("crypto/sha256""encoding/base64""encoding/hex"- "errors""fmt""net/http""net/url""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2"@@ -23,13 +24,13 @@ import ("gorm.io/gorm")-var (- ErrWebhookNotFound = errors.New("webhook not found")- ErrWebhookInvalid = errors.New("invalid webhook token")- ErrWebhookDisabled = errors.New("webhook is disabled")- ErrWebhookInvalidType = errors.New("invalid webhook target type")- ErrWebhookInvalidAction = errors.New("invalid webhook action type")- ErrWebhookMissingTarget = errors.New("target ID is required for container, project, and gitops webhook types")+const (+ ErrWebhookNotFound = errors.Sentinel("webhook not found")+ ErrWebhookInvalid = errors.Sentinel("invalid webhook token")+ ErrWebhookDisabled = errors.Sentinel("webhook is disabled")+ ErrWebhookInvalidType = errors.Sentinel("invalid webhook target type")+ ErrWebhookInvalidAction = errors.Sentinel("invalid webhook action type")+ ErrWebhookMissingTarget = errors.Sentinel("target ID is required for container, project, and gitops webhook types"))const (@@ -71,16 +72,16 @@ func isRemoteWebhookEnvironmentInternal(environmentID string) bool {func generateWebhookTokenInternal() (raw, hash, prefix string, err error) {b := make([]byte, webhookTokenLength)if _, err = crand.Read(b); err != nil {- return "", "", "", fmt.Errorf("failed to generate webhook token: %w", err)+ return "", "", "", errors.WrapIf(err, "failed to generate webhook token")}secretHex := hex.EncodeToString(b)encrypted, err := libcrypto.Encrypt(secretHex)if err != nil {- return "", "", "", fmt.Errorf("failed to encrypt webhook token: %w", err)+ return "", "", "", errors.WrapIf(err, "failed to encrypt webhook token")}encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)if err != nil {- return "", "", "", fmt.Errorf("failed to decode encrypted webhook token: %w", err)+ return "", "", "", errors.WrapIf(err, "failed to decode encrypted webhook token")}tokenHex := hex.EncodeToString(encryptedBytes)raw = webhookTokenPrefix + tokenHex@@ -209,7 +210,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, ac}if err := s.db.WithContext(ctx).Create(wh).Error; err != nil {- return nil, "", fmt.Errorf("failed to create webhook: %w", err)+ return nil, "", errors.WrapIf(err, "failed to create webhook")}if s.eventService != nil {@@ -237,7 +238,7 @@ func (s *WebhookService) ListWebhooks(ctx context.Context, environmentID string)Where("environment_id = ?", environmentID).Order("created_at DESC").Find(&webhooks).Error; err != nil {- return nil, fmt.Errorf("failed to list webhooks: %w", err)+ return nil, errors.WrapIf(err, "failed to list webhooks")}return webhooks, nil}@@ -332,7 +333,7 @@ func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID sreturn nil, ErrWebhookNotFound}if err != nil {- return nil, fmt.Errorf("failed to get webhook: %w", err)+ return nil, errors.WrapIf(err, "failed to get webhook")}return &wh, nil}@@ -348,7 +349,7 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID stWhere("id = ? AND environment_id = ?", id, environmentID).Delete(&models.Webhook{})if result.Error != nil {- return fmt.Errorf("failed to delete webhook: %w", result.Error)+ return errors.WrapIf(result.Error, "failed to delete webhook")}if result.RowsAffected == 0 {return ErrWebhookNotFound@@ -382,11 +383,11 @@ func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID streturn nil, ErrWebhookNotFound}if err != nil {- return nil, fmt.Errorf("failed to get webhook: %w", err)+ return nil, errors.WrapIf(err, "failed to get webhook")}if err := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; err != nil {- return nil, fmt.Errorf("failed to update webhook: %w", err)+ return nil, errors.WrapIf(err, "failed to update webhook")}if s.eventService != nil {@@ -420,7 +421,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) (*if err := s.db.WithContext(ctx).Where("token_prefix = ?", prefix).Find(&candidates).Error; err != nil {- return nil, fmt.Errorf("failed to look up webhook: %w", err)+ return nil, errors.WrapIf(err, "failed to look up webhook")}hash := hashWebhookTokenInternal(rawToken)@@ -599,7 +600,7 @@ func (s *WebhookService) resolveContainerWebhookTargetRefInternal(ctx context.CocontainerName, err := s.containerService.GetContainerNameByReference(ctx, targetID)if err != nil {- return "", fmt.Errorf("failed to resolve container target reference: %w", err)+ return "", errors.WrapIf(err, "failed to resolve container target reference")}return containerName, nil@@ -715,7 +716,7 @@ func (s *WebhookService) executeGitOpsWebhookActionInternal(ctx context.Context,func (s *WebhookService) wrapWebhookActionErrorInternal(ctx context.Context, wh *models.Webhook, targetKind, actionType string, err error) error {msg := fmt.Sprintf("%s %s failed: %s", targetKind, actionType, err)s.logWebhookEventInternal(ctx, wh, actionType, models.EventSeverityError, msg)- return fmt.Errorf("%s %s failed: %w", targetKind, actionType, err)+ return errors.WrapIff(err, "%s %s failed", targetKind, actionType)}func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *models.Webhook, actionType string, severity models.EventSeverity, errMsg string) {diff --git a/backend/pkg/dockerutil/log_stream.go b/backend/pkg/dockerutil/log_stream.goindex 2d74e6b06..6595f4f89 100644--- a/backend/pkg/dockerutil/log_stream.go+++ b/backend/pkg/dockerutil/log_stream.go@@ -3,13 +3,13 @@ package dockerimport ("bufio""context"- "errors"- "fmt""io""log/slog""strings""sync"+ "emperror.dev/errors"+"github.com/moby/moby/api/pkg/stdcopy")@@ -115,7 +115,7 @@ func ReadAllLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- stringif ctxErr := ctx.Err(); ctxErr != nil {return ctxErr}- return fmt.Errorf("failed to demultiplex logs: %w", err)+ return errors.WrapIf(err, "failed to demultiplex logs")}if ctxErr := ctx.Err(); ctxErr != nil {return ctxErrdiff --git a/backend/pkg/dockerutil/volume_utils.go b/backend/pkg/dockerutil/volume_utils.goindex 5e38c4fd8..4d4526632 100644--- a/backend/pkg/dockerutil/volume_utils.go+++ b/backend/pkg/dockerutil/volume_utils.go@@ -2,11 +2,12 @@ package dockerimport ("context"- "errors""fmt""log/slog""time"+ "emperror.dev/errors"+"github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/volume"@@ -165,7 +166,7 @@ func fetchVolumeUsageDataInternal(ctx context.Context, dockerClient *client.ClieVerbose: true,})if err != nil {- return nil, fmt.Errorf("failed to get disk usage: %w", err)+ return nil, errors.WrapIf(err, "failed to get disk usage")}slog.DebugContext(ctx, "disk usage returned volumes", "volume_count", len(diskUsage.Volumes.Items))@@ -193,7 +194,7 @@ func FilterContainersUsingVolume(containers []container.Summary, volumeName strifunc GetContainersUsingVolume(ctx context.Context, dockerClient *client.Client, volumeName string) ([]string, error) {containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return nil, fmt.Errorf("failed to list containers: %w", err)+ return nil, errors.WrapIf(err, "failed to list containers")}containerIDs := FilterContainersUsingVolume(containerList.Items, volumeName)diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.goindex 44fa3b5cb..5b7111f2f 100644--- a/backend/pkg/fswatch/watcher.go+++ b/backend/pkg/fswatch/watcher.go@@ -2,7 +2,6 @@ package fswatchimport ("context"- "errors""log/slog""os""path/filepath"@@ -11,6 +10,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/fsnotify/fsnotify""github.com/getarcaneapp/arcane/backend/v2/pkg/projects")diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.goindex b2dff5370..f77c29f32 100644--- a/backend/pkg/gitutil/git.go+++ b/backend/pkg/gitutil/git.go@@ -2,7 +2,7 @@ package gitimport ("context"- "errors"+ stderrors "errors""fmt""io""io/fs"@@ -16,6 +16,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/types/v2/gitops""github.com/go-git/go-git/v5""github.com/go-git/go-git/v5/config"@@ -123,13 +124,13 @@ func (c *Client) getAuth(config AuthConfig) (transport.AuthMethod, error) {if config.SSHKey != "" {publicKeys, err := ssh.NewPublicKeys("git", []byte(config.SSHKey), "")if err != nil {- return nil, fmt.Errorf("failed to create ssh auth: %w", err)+ return nil, errors.WrapIf(err, "failed to create ssh auth")}// Configure host key verification based on modehostKeyCallback, err := c.getSSHHostKeyCallback(config.SSHHostKeyVerification)if err != nil {- return nil, fmt.Errorf("failed to configure SSH host key verification: %w", err)+ return nil, errors.WrapIf(err, "failed to configure SSH host key verification")}publicKeys.HostKeyCallbackHelper = ssh.HostKeyCallbackHelper{HostKeyCallback: hostKeyCallback,@@ -170,14 +171,14 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)// Ensure the directory existsdir := filepath.Dir(knownHostsPath)if err := os.MkdirAll(dir, 0o700); err != nil {- return nil, fmt.Errorf("failed to create known_hosts directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create known_hosts directory")}// Create the file if it doesn't existif _, err := os.Stat(knownHostsPath); os.IsNotExist(err) {file, err := os.OpenFile(knownHostsPath, os.O_CREATE|os.O_WRONLY, 0o600)if err != nil {- return nil, fmt.Errorf("failed to create known_hosts file: %w", err)+ return nil, errors.WrapIf(err, "failed to create known_hosts file")}if err := file.Close(); err != nil {fmt.Fprintf(os.Stderr, "Warning: failed to close known_hosts file %s: %v\n", knownHostsPath, err)@@ -198,9 +199,9 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)return nil // Host key matches}// Check if it's a "key mismatch" error vs "unknown host"- if keyErr, ok := errors.AsType[*knownhosts.KeyError](err); ok && len(keyErr.Want) > 0 {+ if keyErr, ok := stderrors.AsType[*knownhosts.KeyError](err); ok && len(keyErr.Want) > 0 {// Host is known but key doesn't match - this is a security concern- return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, err)+ return errors.WrapIff(err, "host key mismatch for %s (possible MITM attack)", hostname)}// Otherwise, host is unknown - we'll add it}@@ -251,23 +252,23 @@ func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error// Acquire exclusive lock to prevent concurrent writesfileLock := flock.New(knownHostsPath)if err := fileLock.Lock(); err != nil {- return fmt.Errorf("failed to acquire lock on known_hosts file: %w", err)+ return errors.WrapIf(err, "failed to acquire lock on known_hosts file")}defer fileLock.Unlock() //nolint:errcheck// Append to the filefile, err := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)if err != nil {- return fmt.Errorf("failed to open known_hosts file: %w", err)+ return errors.WrapIf(err, "failed to open known_hosts file")}defer func() {if cerr := file.Close(); cerr != nil && err == nil {- err = fmt.Errorf("failed to close known_hosts file: %w", cerr)+ err = errors.WrapIf(cerr, "failed to close known_hosts file")}}()if _, err := file.WriteString(line + "\n"); err != nil {- return fmt.Errorf("failed to write to known_hosts file: %w", err)+ return errors.WrapIf(err, "failed to write to known_hosts file")}return nil@@ -292,11 +293,11 @@ func (c *Client) Clone(ctx context.Context, url, branch string, auth AuthConfig)}// Ensure the work directory existsif err := os.MkdirAll(workDir, 0o755); err != nil {- return "", fmt.Errorf("failed to create work dir: %w", err)+ return "", errors.WrapIf(err, "failed to create work dir")}tmpDir, err := os.MkdirTemp(workDir, "gitops-*")if err != nil {- return "", fmt.Errorf("failed to create temp dir: %w", err)+ return "", errors.WrapIf(err, "failed to create temp dir")}authMethod, err := c.getAuth(auth)@@ -328,7 +329,7 @@ func (c *Client) Clone(ctx context.Context, url, branch string, auth AuthConfig)_, err = git.PlainCloneContext(ctx, tmpDir, false, cloneOptions)if err != nil {_ = os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to clone repository: %w", err)+ return "", errors.WrapIf(err, "failed to clone repository")}return tmpDir, nil@@ -341,12 +342,12 @@ func (c *Client) GetCurrentCommit(ctx context.Context, repoPath string) (string,}repo, err := git.PlainOpen(repoPath)if err != nil {- return "", fmt.Errorf("failed to open repository: %w", err)+ return "", errors.WrapIf(err, "failed to open repository")}ref, err := repo.Head()if err != nil {- return "", fmt.Errorf("failed to get HEAD: %w", err)+ return "", errors.WrapIf(err, "failed to get HEAD")}return ref.Hash().String(), nil@@ -454,7 +455,7 @@ func (c *Client) listRemoteReferences(ctx context.Context, url string, auth Authrefs, err := rem.ListContext(listCtx, listOptions)if err != nil {- return nil, fmt.Errorf("failed to list remote references: %w", err)+ return nil, errors.WrapIf(err, "failed to list remote references")}return refs, nil@@ -469,7 +470,7 @@ func ValidatePath(repoPath, requestedPath string) error {// Check if the requested path is within the repo using relative path validationrel, err := filepath.Rel(cleanRepoPath, cleanRequestedPath)if err != nil {- return fmt.Errorf("invalid path: %w", err)+ return errors.WrapIf(err, "invalid path")}if strings.HasPrefix(rel, "..") || strings.Contains(rel, string(filepath.Separator)+".."+string(filepath.Separator)) {return errors.New("path traversal attempt detected")@@ -493,7 +494,7 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([// Check if path existsinfo, err := os.Stat(fullPath)if err != nil {- return nil, fmt.Errorf("path not found: %w", err)+ return nil, errors.WrapIf(err, "path not found")}if !info.IsDir() {@@ -502,7 +503,7 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([entries, err := os.ReadDir(fullPath)if err != nil {- return nil, fmt.Errorf("failed to read directory: %w", err)+ return nil, errors.WrapIf(err, "failed to read directory")}var nodes []gitops.FileTreeNode@@ -596,7 +597,7 @@ func (c *Client) ReadFile(ctx context.Context, repoPath, filePath string) (strinfullPath := filepath.Join(repoPath, filePath)content, err := os.ReadFile(fullPath)if err != nil {- return "", fmt.Errorf("failed to read file: %w", err)+ return "", errors.WrapIf(err, "failed to read file")}return string(content), nil}@@ -640,7 +641,7 @@ func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath string// Validate compose pathif err := ValidatePath(repoPath, composePath); err != nil {- return nil, fmt.Errorf("invalid compose path: %w", err)+ return nil, errors.WrapIf(err, "invalid compose path")}// Get the directory containing the compose file@@ -648,7 +649,7 @@ func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath stringroot, err := os.OpenRoot(syncDir)if err != nil {- return nil, fmt.Errorf("sync directory not found: %w", err)+ return nil, errors.WrapIf(err, "sync directory not found")}defer func() { _ = root.Close() }()@@ -710,14 +711,14 @@ func (c *Client) walkSyncEntry(func (c *Client) appendSyncFile(root *os.Root, path string, d fs.DirEntry, result *DirectoryWalkResult, limits syncWalkLimits) error {if limits.maxFiles > 0 && result.TotalFiles >= limits.maxFiles {- return fmt.Errorf("file count limit exceeded (max %d files)", limits.maxFiles)+ return errors.Errorf("file count limit exceeded (max %d files)", limits.maxFiles)}if limits.maxBinarySize > 0 {if info, err := d.Info(); err == nil && info.Size() > limits.maxBinarySize {isBinary, err := c.isBinarySyncFile(root, path)if err != nil {- return fmt.Errorf("failed to inspect file %s: %w", path, err)+ return errors.WrapIff(err, "failed to inspect file %s", path)}if isBinary {result.SkippedBinaries++@@ -728,7 +729,7 @@ func (c *Client) appendSyncFile(root *os.Root, path string, d fs.DirEntry, resulcontent, err := root.ReadFile(path)if err != nil {- return fmt.Errorf("failed to read file %s: %w", path, err)+ return errors.WrapIff(err, "failed to read file %s", path)}fileSize := int64(len(content))@@ -740,7 +741,7 @@ func (c *Client) appendSyncFile(root *os.Root, path string, d fs.DirEntry, resul}if limits.maxTotalSize > 0 && result.TotalSize+fileSize > limits.maxTotalSize {- return fmt.Errorf("total size limit exceeded (max %d bytes)", limits.maxTotalSize)+ return errors.Errorf("total size limit exceeded (max %d bytes)", limits.maxTotalSize)}executable := falsediff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.goindex ecfe61ec4..cee520733 100644--- a/backend/pkg/libarcane/activity/handler.go+++ b/backend/pkg/libarcane/activity/handler.go@@ -3,12 +3,13 @@ package activityimport ("context"json "encoding/json/v2"- "errors""fmt""io""log/slog""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo"@@ -17,7 +18,7 @@ import (// ErrCanceled is the cancellation cause set on an activity's work context when a// user requests cancellation. Completion paths read context.Cause to record a// cancelled (rather than failed) terminal status.-var ErrCanceled = errors.New("activity cancelled by user")+const ErrCanceled = errors.Sentinel("activity cancelled by user")// cancelledMessage is the latest-message recorded when work is cancelled.const cancelledMessage = "Cancelled by user"diff --git a/backend/pkg/libarcane/docker_compat.go b/backend/pkg/libarcane/docker_compat.goindex a0f17f518..f2bd90a0e 100644--- a/backend/pkg/libarcane/docker_compat.go+++ b/backend/pkg/libarcane/docker_compat.go@@ -2,12 +2,12 @@ package libarcaneimport ("context"- "errors"- "fmt""slices""strconv""strings"+ "emperror.dev/errors"+"github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/client"@@ -205,7 +205,7 @@ func ConnectContainerExtraNetworksForDockerAPI(ctx context.Context, dockerClientEndpointConfig: copyEndpointSettingsInternal(endpoints[networkName]),})if err != nil {- return fmt.Errorf("connect network %s: %w", networkName, err)+ return errors.WrapIff(err, "connect network %s", networkName)}}diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.goindex 9e2b8dec7..a93b53844 100644--- a/backend/pkg/libarcane/edge/client.go+++ b/backend/pkg/libarcane/edge/client.go@@ -3,7 +3,6 @@ package edgeimport ("bytes""context"- "errors""fmt""io""log/slog"@@ -12,6 +11,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/google/uuid""github.com/gorilla/websocket""github.com/samber/mo"@@ -208,6 +209,7 @@ func (c *TunnelClient) connectAndServeManagedTunnelInternal(ctx context.Context)"manager_ws_url", managerWSURL,)if wsErr := c.connectAndServeWebSocket(ctx); wsErr != nil {+ // Keep both transport failures in the chain for errors.Is/errors.As traversal.return fmt.Errorf("gRPC edge tunnel failed: %w; websocket fallback failed: %w", err, wsErr)}return nil@@ -382,19 +384,19 @@ func (c *TunnelClient) awaitRegistrationInternal(ctx context.Context) (*TunnelMereturn nil, ctx.Err()case <-timer.C:_ = conn.Close()- return nil, fmt.Errorf("timed out waiting for tunnel registration response after %s", timeout)+ return nil, errors.Errorf("timed out waiting for tunnel registration response after %s", timeout)case result := <-recvCh:if result.err != nil {- return nil, fmt.Errorf("failed to receive tunnel registration response: %w", result.err)+ return nil, errors.WrapIf(result.err, "failed to receive tunnel registration response")}if result.msg == nil {return nil, errors.New("received empty tunnel registration response")}if result.msg.Type != MessageTypeRegisterResponse {- return nil, fmt.Errorf("unexpected first tunnel message: %s", result.msg.Type)+ return nil, errors.Errorf("unexpected first tunnel message: %s", result.msg.Type)}if !result.msg.Accepted {- return nil, fmt.Errorf("manager rejected tunnel registration: %s", result.msg.Error)+ return nil, errors.Errorf("manager rejected tunnel registration: %s", result.msg.Error)}c.sessionID = result.msg.SessionIDreturn result.msg, nil@@ -449,7 +451,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {default:msg, err := conn.Receive()if err != nil {- return fmt.Errorf("failed to receive message: %w", err)+ return errors.WrapIf(err, "failed to receive message")}switch msg.Type {@@ -483,7 +485,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {slog.DebugContext(ctx, "Received heartbeat ack")case MessageTypeRegisterResponse:if !msg.Accepted {- return fmt.Errorf("manager rejected tunnel registration: %s", msg.Error)+ return errors.Errorf("manager rejected tunnel registration: %s", msg.Error)}slog.InfoContext(ctx, "Edge gRPC tunnel connected to manager","manager_addr", c.managerGRPCAddr,diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.goindex 93ef791aa..aab0e4444 100644--- a/backend/pkg/libarcane/edge/client_transport_grpc.go+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go@@ -3,13 +3,13 @@ package edgeimport ("context""crypto/tls"- "errors"- "fmt""log/slog""net/url""strings""time"+ "emperror.dev/errors"+tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1""google.golang.org/grpc""google.golang.org/grpc/backoff"@@ -50,7 +50,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {if c.useTLSForManagerGRPC() {tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)if err != nil {- return fmt.Errorf("failed to configure edge gRPC TLS: %w", err)+ return errors.WrapIf(err, "failed to configure edge gRPC TLS")}if tlsConfig == nil {tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}@@ -64,12 +64,12 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {conn, err := grpc.NewClient(managerAddr, dialOpts...)if err != nil {- return fmt.Errorf("failed to dial manager gRPC endpoint: %w", err)+ return errors.WrapIf(err, "failed to dial manager gRPC endpoint")}defer func() { _ = conn.Close() }()if err := c.waitForGRPCReadyInternal(ctx, conn); err != nil {- return fmt.Errorf("manager gRPC endpoint is not ready: %w", err)+ return errors.WrapIf(err, "manager gRPC endpoint is not ready")}streamCtx, streamCancel := context.WithCancel(metadata.NewOutgoingContext(ctx, metadata.Pairs(@@ -82,7 +82,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {method := c.grpcConnectMethodInternal()stream, err := c.openTunnelConnectStreamInternal(streamCtx, conn, method)if err != nil {- return fmt.Errorf("failed to open tunnel stream: %w", err)+ return errors.WrapIf(err, "failed to open tunnel stream")}tunnelConn := NewGRPCAgentTunnelConn(stream, streamCancel)@@ -90,7 +90,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {setActiveAgentTunnelConn(tunnelConn)defer clearActiveAgentTunnelConn(tunnelConn)if err := tunnelConn.Send(c.registerMessageInternal()); err != nil {- return fmt.Errorf("failed to send register message: %w", err)+ return errors.WrapIf(err, "failed to send register message")}registerMsg, err := c.awaitGRPCRegistrationInternal(ctx)@@ -132,7 +132,7 @@ func (c *TunnelClient) waitForGRPCReadyInternal(ctx context.Context, conn *grpc.if !conn.WaitForStateChange(readyCtx, state) {if errors.Is(readyCtx.Err(), context.DeadlineExceeded) {- return fmt.Errorf("timed out waiting for manager gRPC endpoint after %s", timeout)+ return errors.Errorf("timed out waiting for manager gRPC endpoint after %s", timeout)}return readyCtx.Err()}diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.goindex 150508322..1728d4b54 100644--- a/backend/pkg/libarcane/edge/client_transport_poll.go+++ b/backend/pkg/libarcane/edge/client_transport_poll.go@@ -4,13 +4,13 @@ import ("bytes""context"json "encoding/json/v2"- "errors"- "fmt""io""log/slog""net/http""strings""time"++ "emperror.dev/errors")const defaultTunnelPollRequestTimeout = 15 * time.Second@@ -24,7 +24,7 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {}httpClient, err := NewManagerHTTPClient(c.cfg, 0)if err != nil {- return fmt.Errorf("failed to configure edge poll client: %w", err)+ return errors.WrapIf(err, "failed to configure edge poll client")}c.httpClient = httpClient@@ -93,7 +93,7 @@ func consumePollManagedSessionInternal(session *pollManagedTunnelSession) (*pollselect {case err := <-session.done:if err != nil {- return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)+ return nil, errors.WrapIf(err, "poll-managed websocket session ended")}return nil, nildefault:@@ -147,7 +147,7 @@ func waitForNextPollCycleInternal(ctx context.Context, session *pollManagedTunnereturn session, ctx.Err()case err := <-sessionDone:if err != nil {- return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)+ return nil, errors.WrapIf(err, "poll-managed websocket session ended")}return nil, nilcase <-waitTimer.C:@@ -163,7 +163,7 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, pollURL stbody, err := json.Marshal(pollReq)if err != nil {- return nil, fmt.Errorf("failed to marshal poll request: %w", err)+ return nil, errors.WrapIf(err, "failed to marshal poll request")}reqCtx, cancel := context.WithTimeout(ctx, defaultTunnelPollRequestTimeout)@@ -171,7 +171,7 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, pollURL streq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pollURL, bytes.NewReader(body))if err != nil {- return nil, fmt.Errorf("failed to create poll request: %w", err)+ return nil, errors.WrapIf(err, "failed to create poll request")}req.Header.Set("Content-Type", "application/json")req.Header.Set(HeaderAgentToken, c.cfg.AgentToken)@@ -180,18 +180,18 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, pollURL stresp, err := c.httpClient.Do(req)if err != nil {- return nil, fmt.Errorf("poll request failed: %w", err)+ return nil, errors.WrapIf(err, "poll request failed")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {respBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("poll request failed with status %d: %s", resp.StatusCode, string(respBody))+ return nil, errors.Errorf("poll request failed with status %d: %s", resp.StatusCode, string(respBody))}var pollResp TunnelPollResponseif err := json.UnmarshalRead(resp.Body, &pollResp); err != nil {- return nil, fmt.Errorf("failed to decode poll response: %w", err)+ return nil, errors.WrapIf(err, "failed to decode poll response")}return &pollResp, nil}diff --git a/backend/pkg/libarcane/edge/client_transport_websocket.go b/backend/pkg/libarcane/edge/client_transport_websocket.goindex f116d88c4..aa7450dfd 100644--- a/backend/pkg/libarcane/edge/client_transport_websocket.go+++ b/backend/pkg/libarcane/edge/client_transport_websocket.go@@ -2,14 +2,14 @@ package edgeimport ("context"- "errors"- "fmt""io""log/slog""net/http""strings""time"+ "emperror.dev/errors"+"github.com/gorilla/websocket")@@ -27,7 +27,7 @@ func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {if strings.HasPrefix(strings.ToLower(managerWSURL), "wss://") {tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)if err != nil {- return fmt.Errorf("failed to configure edge websocket TLS: %w", err)+ return errors.WrapIf(err, "failed to configure edge websocket TLS")}dialer.TLSClientConfig = tlsConfig}@@ -44,9 +44,9 @@ func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {if resp != nil {defer func() { _ = resp.Body.Close() }()body, _ := io.ReadAll(resp.Body)- return fmt.Errorf("failed to connect to manager websocket endpoint: %w, status: %d, body: %s", err, resp.StatusCode, string(body))+ return errors.WrapIff(err, "failed to connect to manager websocket endpoint (status: %d, body: %s)", resp.StatusCode, string(body))}- return fmt.Errorf("failed to connect to manager websocket endpoint: %w", err)+ return errors.WrapIf(err, "failed to connect to manager websocket endpoint")}defer func() { _ = conn.Close() }()@@ -55,7 +55,7 @@ func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {setActiveAgentTunnelConn(tunnelConn)defer clearActiveAgentTunnelConn(tunnelConn)if err := tunnelConn.Send(c.registerMessageInternal()); err != nil {- return fmt.Errorf("failed to send websocket register message: %w", err)+ return errors.WrapIf(err, "failed to send websocket register message")}registerMsg, err := c.awaitRegistrationInternal(ctx)if err != nil {diff --git a/backend/pkg/libarcane/edge/command_client.go b/backend/pkg/libarcane/edge/command_client.goindex f0abe9754..f36e4d3ea 100644--- a/backend/pkg/libarcane/edge/command_client.go+++ b/backend/pkg/libarcane/edge/command_client.go@@ -2,12 +2,12 @@ package edgeimport ("context"- "errors"- "fmt""net/http""slices""time"+ "emperror.dev/errors"+"github.com/google/uuid")@@ -35,7 +35,7 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *Cif commandName == "" {resolved, ok := ResolveEdgeCommandName(req.Method, req.Path, false).Get()if !ok {- return nil, fmt.Errorf("unsupported edge command for %s %s", req.Method, req.Path)+ return nil, errors.Errorf("unsupported edge command for %s %s", req.Method, req.Path)}commandName = resolved}@@ -78,7 +78,7 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *C}if err := tunnel.Conn.Send(msg); err != nil {- return nil, fmt.Errorf("tunnel request failed: %w", err)+ return nil, errors.WrapIf(err, "tunnel request failed")}if chunkRequestBody {transferID := msg.Metadata[bodyTransferMetadataKey]@@ -91,7 +91,7 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *CSequence: sequence,EOF: end == len(req.Body),}); err != nil {- return nil, fmt.Errorf("tunnel request body transfer failed: %w", err)+ return nil, errors.WrapIf(err, "tunnel request body transfer failed")}offset = end}@@ -127,7 +127,7 @@ func (c *CommandClient) OpenStream(ctx context.Context, tunnel *AgentTunnel, reqif commandName == "" {resolved, ok := ResolveEdgeCommandName(http.MethodGet, req.Path, true).Get()if !ok {- return fmt.Errorf("unsupported edge stream target %q", req.Path)+ return errors.Errorf("unsupported edge stream target %q", req.Path)}commandName = resolved}diff --git a/backend/pkg/libarcane/edge/event_sync.go b/backend/pkg/libarcane/edge/event_sync.goindex 173ca0d94..562b843a3 100644--- a/backend/pkg/libarcane/edge/event_sync.go+++ b/backend/pkg/libarcane/edge/event_sync.go@@ -1,15 +1,16 @@package edgeimport (- "errors""strings""sync"+ "emperror.dev/errors"+"github.com/google/uuid")// ErrNoActiveAgentTunnel is returned when no active agent tunnel exists for outbound event sync.-var ErrNoActiveAgentTunnel = errors.New("no active edge agent tunnel")+const ErrNoActiveAgentTunnel = errors.Sentinel("no active edge agent tunnel")var agentTunnelState struct {mu sync.RWMutexdiff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.goindex 45e97bd8d..df55794f9 100644--- a/backend/pkg/libarcane/edge/poll_control.go+++ b/backend/pkg/libarcane/edge/poll_control.go@@ -4,13 +4,14 @@ import ("github.com/samber/mo"json "encoding/json/v2"- "errors""io""log/slog""net/http""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/labstack/echo/v4")diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.goindex d4f848f99..f5886989c 100644--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go@@ -7,11 +7,12 @@package tunnelpbimport (- protoreflect "google.golang.org/protobuf/reflect/protoreflect"- protoimpl "google.golang.org/protobuf/runtime/protoimpl"reflect "reflect"sync "sync"unsafe "unsafe"++ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl")const (diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.goindex eba05fd77..373719642 100644--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go@@ -8,6 +8,7 @@ package tunnelpbimport (context "context"+grpc "google.golang.org/grpc"codes "google.golang.org/grpc/codes"status "google.golang.org/grpc/status"diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.goindex b488c9c01..33cd658c3 100644--- a/backend/pkg/libarcane/edge/proxy.go+++ b/backend/pkg/libarcane/edge/proxy.go@@ -5,13 +5,13 @@ import ("bytes""context"- "errors"- "fmt""io""log/slog""net/http""time"+ "emperror.dev/errors"+"github.com/labstack/echo/v4")@@ -363,10 +363,10 @@ func DoRequest(ctx context.Context, envID, method, path string, body []byte) (intunnel, ok := GetRegistry().Get(envID).Get()if !ok {- return 0, nil, fmt.Errorf("no active tunnel for environment %s", envID)+ return 0, nil, errors.Errorf("no active tunnel for environment %s", envID)}if tunnel.Conn.IsClosed() {- return 0, nil, fmt.Errorf("tunnel for environment %s is closed", envID)+ return 0, nil, errors.Errorf("tunnel for environment %s is closed", envID)}headers := make(map[string]string)diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.goindex 533ef66c1..429414f19 100644--- a/backend/pkg/libarcane/edge/server.go+++ b/backend/pkg/libarcane/edge/server.go@@ -3,15 +3,15 @@ package edgeimport ("context""crypto/tls"- "errors"- "fmt""io""log/slog""net/http"- "runtime/debug""strings""time"+ "emperror.dev/emperror"+ "emperror.dev/errors"+tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/google/uuid"@@ -501,7 +501,7 @@ func (s *TunnelServer) deliverResponse(ctx context.Context, tunnel *AgentTunnel,select {case pending.ResponseCh <- msg:default:- err := fmt.Errorf("response delivery failed because pending request %s is not consuming messages", msg.ID)+ err := errors.Errorf("response delivery failed because pending request %s is not consuming messages", msg.ID)tunnel.Pending.Delete(msg.ID)pending.failureCh <- errslog.WarnContext(ctx, "Failed pending request with full response channel", "id", msg.ID)@@ -522,7 +522,7 @@ func (s *TunnelServer) deliverStream(ctx context.Context, tunnel *AgentTunnel, mcase <-ctx.Done():returncase <-time.After(streamDeliveryTimeout):- err := fmt.Errorf("stream delivery timed out for pending request %s", msg.ID)+ err := errors.Errorf("stream delivery timed out for pending request %s", msg.ID)tunnel.Pending.Delete(msg.ID)pending.failureCh <- errslog.WarnContext(ctx, "Failed slow pending stream consumer",@@ -645,11 +645,10 @@ func (s *TunnelServer) loggingStreamInterceptorInternal() grpc.StreamServerInterfunc (s *TunnelServer) recoveryStreamInterceptorInternal() grpc.StreamServerInterceptor {return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {defer func() {- if recovered := recover(); recovered != nil {+ if panicErr := emperror.Recover(recover()); panicErr != nil {slog.ErrorContext(ss.Context(), "panic in gRPC tunnel stream","method", info.FullMethod,- "panic", recovered,- "stack", string(debug.Stack()),+ "error", panicErr,)err = status.Error(codes.Internal, "internal tunnel error")}diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.goindex ed5554ef4..5238eedc8 100644--- a/backend/pkg/libarcane/edge/tls.go+++ b/backend/pkg/libarcane/edge/tls.go@@ -10,7 +10,6 @@ import ("crypto/x509"json "encoding/json/v2""encoding/pem"- "errors""fmt""io""log/slog"@@ -25,6 +24,8 @@ import ("syscall""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate""go.getarcane.app/sys/atomic"@@ -64,7 +65,7 @@ func BuildManagerServerTLSConfig(cfg *Config) (*tls.Config, error) {caPool, err := loadCertPoolInternal(strings.TrimSpace(cfg.EdgeMTLSCAFile))if err != nil {- return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)+ return nil, errors.WrapIf(err, "failed to load edge mTLS CA file")}// ClientAuth is intentionally VerifyClientCertIfGiven even when@@ -87,7 +88,7 @@ func BuildManagerServerTLSConfig(cfg *Config) (*tls.Config, error) {func NewManagerHTTPClient(cfg *Config, timeout time.Duration) (*http.Client, error) {baseTransport, ok := http.DefaultTransport.(*http.Transport)if !ok {- return nil, &common.DefaultTransportTypeError{}+ return nil, errors.New("http.DefaultTransport is not *http.Transport")}transport := baseTransport.Clone()tlsConfig, err := buildManagerClientTLSConfigInternal(cfg)@@ -165,15 +166,15 @@ func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *ConfigcaPEM, err := os.ReadFile(caCertPath)if err != nil {- return nil, fmt.Errorf("failed to read generated CA certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to read generated CA certificate")}clientCertPEM, err := os.ReadFile(clientCertPath)if err != nil {- return nil, fmt.Errorf("failed to read generated client certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to read generated client certificate")}clientKeyPEM, err := os.ReadFile(clientKeyPath)if err != nil {- return nil, fmt.Errorf("failed to read generated client key: %w", err)+ return nil, errors.WrapIf(err, "failed to read generated client key")}return &GeneratedMTLSAssets{@@ -243,7 +244,7 @@ func readMTLSEnrollmentMarkerInternal(path string) (time.Time, error) {}enrolledAt, err := time.Parse(time.RFC3339Nano, trimmed)if err != nil {- return time.Time{}, fmt.Errorf("failed to parse edge mTLS enrollment marker %s: %w", path, err)+ return time.Time{}, errors.WrapIff(err, "failed to parse edge mTLS enrollment marker %s", path)}return enrolledAt, nil}@@ -284,7 +285,7 @@ func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error {if !needsEnrollment {if !fileExistsInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName)) {if err := atomic.WriteFile(filepath.Join(assetsDir, generatedMTLSEnrolledName), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o600); err != nil {- return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)+ return errors.WrapIf(err, "failed to write edge mTLS enrollment marker")}}setAgentMTLSAssetPathsInternal(cfg, assetsDir)@@ -314,12 +315,12 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,httpClient, err := NewManagerHTTPClient(cfg, 30*time.Second)if err != nil {- return fmt.Errorf("failed to configure edge mTLS enrollment client: %w", err)+ return errors.WrapIf(err, "failed to configure edge mTLS enrollment client")}req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerBaseURL+"/api/tunnel/mtls/enroll", nil)if err != nil {- return fmt.Errorf("failed to create edge mTLS enrollment request: %w", err)+ return errors.WrapIf(err, "failed to create edge mTLS enrollment request")}req.Header.Set(HeaderAgentToken, cfg.AgentToken)req.Header.Set(HeaderAPIKey, cfg.AgentToken)@@ -327,25 +328,25 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,resp, err := httpClient.Do(req)if err != nil {- return fmt.Errorf("edge mTLS enrollment request failed: %w", err)+ return errors.WrapIf(err, "edge mTLS enrollment request failed")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(io.LimitReader(resp.Body, maxEnrollResponseBytes))- return fmt.Errorf("edge mTLS enrollment failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return errors.Errorf("edge mTLS enrollment failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}var enrollResp enrollMTLSResponseif err := json.UnmarshalRead(io.LimitReader(resp.Body, maxEnrollResponseBytes), &enrollResp); err != nil {- return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", err)+ return errors.WrapIf(err, "failed to decode edge mTLS enrollment response")}if len(enrollResp.Files) == 0 {return errors.New("edge mTLS enrollment response did not include any files")}if err := os.MkdirAll(assetsDir, common.DirPerm); err != nil {- return fmt.Errorf("failed to create edge mTLS asset dir: %w", err)+ return errors.WrapIf(err, "failed to create edge mTLS asset dir")}for _, file := range enrollResp.Files {fileName := filepath.Base(file.Name)@@ -355,15 +356,15 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,perm = 0o600}if err := atomic.WriteFile(targetPath, []byte(file.Content), perm); err != nil {- return fmt.Errorf("failed to write edge mTLS asset %s: %w", file.Name, err)+ return errors.WrapIff(err, "failed to write edge mTLS asset %s", file.Name)}}needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())if needsEnrollment {- return fmt.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)+ return errors.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)}if err := atomic.WriteFile(filepath.Join(assetsDir, generatedMTLSEnrolledName), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o600); err != nil {- return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)+ return errors.WrapIf(err, "failed to write edge mTLS enrollment marker")}setAgentMTLSAssetPathsInternal(cfg, assetsDir)@@ -386,7 +387,7 @@ func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {if caFile := strings.TrimSpace(cfg.EdgeMTLSCAFile); caFile != "" {pool, err := loadSystemOrCustomCertPoolInternal(caFile)if err != nil {- return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)+ return nil, errors.WrapIf(err, "failed to load edge mTLS CA file")}tlsConfig.RootCAs = pool}@@ -397,7 +398,7 @@ func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {keyPath := strings.TrimSpace(cfg.EdgeMTLSKeyFile)needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())if needsEnrollment {- err := fmt.Errorf("edge mTLS client certificate is unusable: %s", reason)+ err := errors.Errorf("edge mTLS client certificate is unusable: %s", reason)if mode == EdgeMTLSModeOptional {slog.Warn("Ignoring unusable optional edge mTLS client certificate; falling back to token auth", "cert_path", certPath, "error", err.Error())return tlsConfig, nil@@ -410,7 +411,7 @@ func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {slog.Warn("Failed to load optional edge mTLS client certificate; falling back to token auth", "cert_path", certPath, "error", err.Error())return tlsConfig, nil}- return nil, fmt.Errorf("failed to load edge mTLS client certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to load edge mTLS client certificate")}tlsConfig.Certificates = []tls.Certificate{cert}}@@ -456,7 +457,7 @@ func ValidateManagerMTLSConfig(cfg *Config) error {_, err := loadCertPoolInternal(cfg.EdgeMTLSCAFile)if err != nil {- return fmt.Errorf("failed to load edge mTLS CA file: %w", err)+ return errors.WrapIf(err, "failed to load edge mTLS CA file")}return nil}@@ -619,7 +620,7 @@ func verifiedPeerCertificateEnvironmentIDMatchesInternal(state *tls.ConnectionStreturn nil}}- return fmt.Errorf("verified edge mTLS client certificate does not match environment %s", strings.TrimSpace(envID))+ return errors.Errorf("verified edge mTLS client certificate does not match environment %s", strings.TrimSpace(envID))}func edgeMTLSAppURLInternal(cfg *Config) string {@@ -660,7 +661,7 @@ func edgeMTLSAssetsDirInternal(cfg *Config) (string, error) {resolved, err := filepath.Abs(baseDir)if err != nil {- return "", fmt.Errorf("failed to resolve edge mTLS assets dir: %w", err)+ return "", errors.WrapIf(err, "failed to resolve edge mTLS assets dir")}return resolved, nil}@@ -680,14 +681,14 @@ func edgeAgentMTLSAssetsDirInternal(cfg *Config) (string, error) {resolved, err := filepath.Abs(baseDir)if err != nil {- return "", fmt.Errorf("failed to resolve edge agent mTLS assets dir: %w", err)+ return "", errors.WrapIf(err, "failed to resolve edge agent mTLS assets dir")}return resolved, nil}func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, string, bool, error) {if err := os.MkdirAll(assetsDir, common.DirPerm); err != nil {- return "", "", false, fmt.Errorf("failed to create edge mTLS assets dir: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to create edge mTLS assets dir")}unlock, err := lockEdgeMTLSPathInternal(ctx, assetsDir, ".ca.lock")@@ -706,7 +707,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, strprivateKey, err := certgen.GenerateP384PrivateKey()if err != nil {- return "", "", false, fmt.Errorf("failed to generate CA private key: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to generate CA private key")}template, err := certgen.NewEdgeMTLSCATemplate()@@ -716,7 +717,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, strcertDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)if err != nil {- return "", "", false, fmt.Errorf("failed to create CA certificate: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to create CA certificate")}if err := writePEMFileInternal(caCertPath, "CERTIFICATE", certDER, common.FilePerm); err != nil {@@ -724,7 +725,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, str}caKeyDER, err := x509.MarshalECPrivateKey(privateKey)if err != nil {- return "", "", false, fmt.Errorf("failed to marshal CA private key: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to marshal CA private key")}if err := writeCAKeyFileInternal(caKeyPath, caKeyDER); err != nil {return "", "", false, err@@ -752,7 +753,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envIcaCertPEM, err := os.ReadFile(caCertPath)if err != nil {- return "", "", false, fmt.Errorf("failed to read CA certificate: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to read CA certificate")}caKeyPEM, err := readCAKeyPEMInternal(caKeyPath)if err != nil {@@ -765,7 +766,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envI}caCert, err := x509.ParseCertificate(caCertBlock.Bytes)if err != nil {- return "", "", false, fmt.Errorf("failed to parse CA certificate: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to parse CA certificate")}caKeyBlock, _ := pem.Decode(caKeyPEM)@@ -774,13 +775,13 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envI}caKey, err := x509.ParseECPrivateKey(caKeyBlock.Bytes)if err != nil {- return "", "", false, fmt.Errorf("failed to parse CA private key: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to parse CA private key")}safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")clientDir := filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID)if err := os.MkdirAll(clientDir, common.DirPerm); err != nil {- return "", "", false, fmt.Errorf("failed to create client cert dir: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to create client cert dir")}unlock, err := lockEdgeMTLSPathInternal(ctx, clientDir, ".client.lock")if err != nil {@@ -804,7 +805,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envIprivateKey, err := certgen.GenerateP384PrivateKey()if err != nil {- return "", "", false, fmt.Errorf("failed to generate client private key: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to generate client private key")}uriSAN, dnsSANs := buildGeneratedClientSANsInternal(envName, safeEnvID, appURL)template, err := certgen.NewEdgeMTLSClientTemplate(expectedCommonName, uriSAN, dnsSANs)@@ -814,7 +815,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envIcertDER, err := x509.CreateCertificate(rand.Reader, template, caCert, &privateKey.PublicKey, caKey)if err != nil {- return "", "", false, fmt.Errorf("failed to create client certificate: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to create client certificate")}if err := writePEMFileInternal(clientCertPath, "CERTIFICATE", certDER, common.FilePerm); err != nil {@@ -822,7 +823,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envI}clientKeyDER, err := x509.MarshalECPrivateKey(privateKey)if err != nil {- return "", "", false, fmt.Errorf("failed to marshal client private key: %w", err)+ return "", "", false, errors.WrapIf(err, "failed to marshal client private key")}if err := writePEMFileInternal(clientKeyPath, "EC PRIVATE KEY", clientKeyDER, 0o600); err != nil {return "", "", false, err@@ -900,11 +901,11 @@ func validateGeneratedCAInternal(certPath, keyPath string) error {}keyBlock, _ := pem.Decode(keyPEM)if keyBlock == nil {- return fmt.Errorf("failed to parse CA private key PEM %s", keyPath)+ return errors.Errorf("failed to parse CA private key PEM %s", keyPath)}privateKey, err := x509.ParseECPrivateKey(keyBlock.Bytes)if err != nil {- return fmt.Errorf("failed to parse CA private key %s: %w", keyPath, err)+ return errors.WrapIff(err, "failed to parse CA private key %s", keyPath)}if privateKey.Curve != elliptic.P384() {return errors.New("generated CA private key is not ECDSA P-384")@@ -925,10 +926,10 @@ func validateGeneratedClientCertificateInternal(certPath, keyPath string, expectreturn errors.New("generated client certificate is not currently valid")}if strings.TrimSpace(expectedCommonName) != "" && cert.Subject.CommonName != expectedCommonName {- return fmt.Errorf("generated client certificate common name %q does not match expected %q", cert.Subject.CommonName, expectedCommonName)+ return errors.Errorf("generated client certificate common name %q does not match expected %q", cert.Subject.CommonName, expectedCommonName)}if expectedURISAN != nil && !certificateHasURISANInternal(cert, expectedURISAN) {- return fmt.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())+ return errors.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())}publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)if !ok || publicKey.Curve != elliptic.P384() {@@ -996,27 +997,27 @@ func agentMTLSAssetsNeedEnrollmentInternal(certPath string, keyPath string, nowfunc validateCertificateKeyPairInternal(cert *x509.Certificate, privateKey *ecdsa.PrivateKey, label string) error {if cert == nil {- return fmt.Errorf("%s certificate is required", label)+ return errors.Errorf("%s certificate is required", label)}if privateKey == nil {- return fmt.Errorf("%s private key is required", label)+ return errors.Errorf("%s private key is required", label)}publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)if !ok {- return fmt.Errorf("%s certificate public key is not ECDSA", label)+ return errors.Errorf("%s certificate public key is not ECDSA", label)}certPublicKeyDER, err := x509.MarshalPKIXPublicKey(publicKey)if err != nil {- return fmt.Errorf("failed to marshal %s certificate public key: %w", label, err)+ return errors.WrapIff(err, "failed to marshal %s certificate public key", label)}privatePublicKeyDER, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)if err != nil {- return fmt.Errorf("failed to marshal %s private key public key: %w", label, err)+ return errors.WrapIff(err, "failed to marshal %s private key public key", label)}if !bytes.Equal(certPublicKeyDER, privatePublicKeyDER) {- return fmt.Errorf("%s certificate public key does not match private key", label)+ return errors.Errorf("%s certificate public key does not match private key", label)}return nil@@ -1025,15 +1026,15 @@ func validateCertificateKeyPairInternal(cert *x509.Certificate, privateKey *ecdsfunc readCertificateInternal(path string) (*x509.Certificate, error) {pemBytes, err := os.ReadFile(path)if err != nil {- return nil, fmt.Errorf("failed to read certificate %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to read certificate %s", path)}block, _ := pem.Decode(pemBytes)if block == nil {- return nil, fmt.Errorf("failed to parse certificate PEM %s", path)+ return nil, errors.Errorf("failed to parse certificate PEM %s", path)}cert, err := x509.ParseCertificate(block.Bytes)if err != nil {- return nil, fmt.Errorf("failed to parse certificate %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to parse certificate %s", path)}return cert, nil}@@ -1041,15 +1042,15 @@ func readCertificateInternal(path string) (*x509.Certificate, error) {func readECPrivateKeyInternal(path string) (*ecdsa.PrivateKey, error) {pemBytes, err := os.ReadFile(path)if err != nil {- return nil, fmt.Errorf("failed to read private key %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to read private key %s", path)}block, _ := pem.Decode(pemBytes)if block == nil {- return nil, fmt.Errorf("failed to parse private key PEM %s", path)+ return nil, errors.Errorf("failed to parse private key PEM %s", path)}privateKey, err := x509.ParseECPrivateKey(block.Bytes)if err != nil {- return nil, fmt.Errorf("failed to parse EC private key %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to parse EC private key %s", path)}return privateKey, nil}@@ -1057,7 +1058,7 @@ func readECPrivateKeyInternal(path string) (*ecdsa.PrivateKey, error) {func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string) (func(), error) {absDir, err := filepath.Abs(dir)if err != nil {- return nil, fmt.Errorf("failed to resolve edge mTLS lock dir: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve edge mTLS lock dir")}lockName = strings.TrimSpace(lockName)if lockName == "" {@@ -1068,7 +1069,7 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string)muValue, _ := managerCALocks.LoadOrStore(lockPath, &sync.Mutex{})mu, ok := muValue.(*sync.Mutex)if !ok {- return nil, &common.ManagerCALockTypeError{}+ return nil, errors.New("manager CA lock value is not *sync.Mutex")}deadline := time.Now().Add(managerCALockTimeout)@@ -1090,7 +1091,7 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string)}if !os.IsExist(err) {mu.Unlock()- return nil, fmt.Errorf("failed to acquire edge mTLS CA lock: %w", err)+ return nil, errors.WrapIf(err, "failed to acquire edge mTLS CA lock")}if time.Now().After(deadline) {if removeStaleEdgeMTLSLockInternal(lockPath) {@@ -1098,7 +1099,7 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string)continue}mu.Unlock()- return nil, fmt.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)+ return nil, errors.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)}mu.Unlock()if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {@@ -1113,7 +1114,7 @@ func waitForEdgeMTLSLockPollInternal(ctx context.Context) error {select {case <-ctx.Done():- return fmt.Errorf("cancelled waiting for edge mTLS CA lock: %w", ctx.Err())+ return errors.WrapIf(ctx.Err(), "cancelled waiting for edge mTLS CA lock")case <-timer.C:return nil}@@ -1144,7 +1145,7 @@ func readEdgeMTLSLockInfoInternal(lockPath string) (*edgeMTLSLockInfo, error) {}pid, err := strconv.Atoi(fields[0])if err != nil {- return nil, fmt.Errorf("parse edge mTLS lock PID: %w", err)+ return nil, errors.WrapIf(err, "parse edge mTLS lock PID")}if pid <= 0 {return nil, errors.New("edge mTLS lock PID must be positive")@@ -1178,7 +1179,7 @@ func edgeMTLSLockPIDAliveInternal(pid int) bool {func writePEMFileInternal(path string, blockType string, bytes []byte, perm os.FileMode) error {pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})if pemBytes == nil {- return fmt.Errorf("failed to encode PEM file %s", path)+ return errors.Errorf("failed to encode PEM file %s", path)}return atomic.WriteFile(path, pemBytes, perm)}@@ -1200,7 +1201,7 @@ func writeCAKeyFileInternal(path string, derBytes []byte) error {ciphertext, err := caKeyEncryptInternal(string(pemBytes))if err != nil {- return fmt.Errorf("failed to encrypt edge mTLS CA private key: %w", err)+ return errors.WrapIf(err, "failed to encrypt edge mTLS CA private key")}if ciphertext == "" {return errors.New("failed to encrypt edge mTLS CA private key: encrypted payload is empty")@@ -1214,16 +1215,16 @@ func writeCAKeyFileInternal(path string, derBytes []byte) error {func readCAKeyPEMInternal(path string) ([]byte, error) {raw, err := os.ReadFile(path)if err != nil {- return nil, fmt.Errorf("failed to read CA private key %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to read CA private key %s", path)}trimmed := strings.TrimSpace(string(raw))if !strings.HasPrefix(trimmed, caKeyEncryptedPrefix) {- return nil, fmt.Errorf("CA private key %s is not in the expected encrypted envelope format", path)+ return nil, errors.Errorf("CA private key %s is not in the expected encrypted envelope format", path)}ciphertext := strings.TrimPrefix(trimmed, caKeyEncryptedPrefix)plaintext, err := libcrypto.Decrypt(ciphertext)if err != nil {- return nil, fmt.Errorf("failed to decrypt CA private key %s: %w", path, err)+ return nil, errors.WrapIff(err, "failed to decrypt CA private key %s", path)}return []byte(plaintext), nil}diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.goindex 978a9ea99..55d6d1d1e 100644--- a/backend/pkg/libarcane/edge/tunnel.go+++ b/backend/pkg/libarcane/edge/tunnel.go@@ -3,9 +3,10 @@ package edgeimport ("context"json "encoding/json/v2"- "errors""io"+ "emperror.dev/errors"+tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1""github.com/gorilla/websocket""google.golang.org/grpc/codes"diff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter.goindex 6ce7c968f..aa3b8616b 100644--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter.go@@ -1,11 +1,11 @@package edgeimport (- "errors"- "fmt""maps""math"+ "emperror.dev/errors"+tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1")@@ -112,9 +112,9 @@ func tunnelMessageToManagerProto(msg *TunnelMessage) (*tunnelpb.ManagerMessage,MessageTypeCommandAck,MessageTypeCommandOutput,MessageTypeCommandComplete:- return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)+ return nil, errors.Errorf("unsupported manager message type: %s", msg.Type)default:- return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)+ return nil, errors.Errorf("unsupported manager message type: %s", msg.Type)}}@@ -209,7 +209,7 @@ func managerProtoToTunnelMessage(msg *tunnelpb.ManagerMessage) (*TunnelMessage,EOF: payload.FileChunk.GetEof(),}, nildefault:- return nil, fmt.Errorf("unsupported manager payload type %T", payload)+ return nil, errors.Errorf("unsupported manager payload type %T", payload)}}@@ -265,7 +265,7 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erro}}}, nilcase MessageTypeEvent:if msg.Event == nil {- return nil, fmt.Errorf("event payload is required for message type: %s", msg.Type)+ return nil, errors.Errorf("event payload is required for message type: %s", msg.Type)}return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Event{Event: &tunnelpb.EventLog{Type: msg.Event.Type,@@ -321,9 +321,9 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erroMessageTypeCommandRequest,MessageTypeStreamOpen,MessageTypeCancelRequest:- return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)+ return nil, errors.Errorf("unsupported agent message type: %s", msg.Type)default:- return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)+ return nil, errors.Errorf("unsupported agent message type: %s", msg.Type)}}@@ -419,7 +419,7 @@ func agentProtoToTunnelMessage(msg *tunnelpb.AgentMessage) (*TunnelMessage, erroError: payload.StreamClose.GetError(),}, nildefault:- return nil, fmt.Errorf("unsupported agent payload type %T", payload)+ return nil, errors.Errorf("unsupported agent payload type %T", payload)}}@@ -434,7 +434,7 @@ func cloneHeaderMap(in map[string]string) map[string]string {func intToInt32(value int, field string) (int32, error) {if value < math.MinInt32 || value > math.MaxInt32 {- return 0, fmt.Errorf("%s value %d is out of int32 range", field, value)+ return 0, errors.Errorf("%s value %d is out of int32 range", field, value)}return int32(value), nil}diff --git a/backend/pkg/libarcane/inspect_compat.go b/backend/pkg/libarcane/inspect_compat.goindex 54459bcde..08b29b7d5 100644--- a/backend/pkg/libarcane/inspect_compat.go+++ b/backend/pkg/libarcane/inspect_compat.go@@ -4,8 +4,6 @@ import ("bufio""context"json "encoding/json/v2"- "errors"- "fmt""io""net/http""net/netip"@@ -14,6 +12,8 @@ import ("strconv""strings"+ "emperror.dev/errors"+containertypes "github.com/moby/moby/api/types/container"networktypes "github.com/moby/moby/api/types/network""github.com/moby/moby/client"@@ -211,7 +211,7 @@ func fetchDockerAPIJSONInternal(ctx context.Context, apiClient client.APIClient,return nil, err}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, fmt.Errorf("docker api GET %s failed with %s: %s", resourcePath, resp.Status, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("docker api GET %s failed with %s: %s", resourcePath, resp.Status, strings.TrimSpace(string(body)))}return body, nildiff --git a/backend/pkg/libarcane/registryauth/helpers.go b/backend/pkg/libarcane/registryauth/helpers.goindex bcf4d651f..bb43376d3 100644--- a/backend/pkg/libarcane/registryauth/helpers.go+++ b/backend/pkg/libarcane/registryauth/helpers.go@@ -1,10 +1,10 @@package registryauthimport (- "fmt""sort""strings"+ "emperror.dev/errors"ref "github.com/distribution/reference"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"dockerregistry "github.com/moby/moby/api/types/registry"@@ -79,7 +79,7 @@ func EncodeAuthHeader(username, password, serverAddress string) (string, error)ServerAddress: serverAddress,})if err != nil {- return "", fmt.Errorf("encode registry auth header: %w", err)+ return "", errors.WrapIf(err, "encode registry auth header")}return auth, nil}@@ -87,7 +87,7 @@ func EncodeAuthHeader(username, password, serverAddress string) (string, error)func DecodeAuthHeader(authEncoded string) (dockerregistry.AuthConfig, error) {cfg, err := dockerauthconfig.Decode(strings.TrimSpace(authEncoded))if err != nil {- return dockerregistry.AuthConfig{}, fmt.Errorf("decode registry auth header: %w", err)+ return dockerregistry.AuthConfig{}, errors.WrapIf(err, "decode registry auth header")}if cfg == nil {return dockerregistry.AuthConfig{}, nildiff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.goindex 589edb292..c5eb1bed9 100644--- a/backend/pkg/libarcane/startup/runtime_identity.go+++ b/backend/pkg/libarcane/startup/runtime_identity.go@@ -8,6 +8,7 @@ import ("path/filepath""strings"+ "emperror.dev/errors"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo")@@ -96,7 +97,7 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConfif inContainer {mountpoints, err := loadMountpointsInternal(mountInfoPath)if err != nil {- return fmt.Errorf("load mountpoints: %w", err)+ return errors.WrapIf(err, "load mountpoints")}if err := prepareWritablePathsInternal(runtimeUID, runtimeGID, mountpoints, projectsDir); err != nil {@@ -129,12 +130,12 @@ func loadRuntimeIdentityRequestInternal(cfg *RuntimeIdentityConfig, inContaineruid, credentialUID, err := parseRuntimeIdentityValueInternal(puid, "PUID")if err != nil {- return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PUID %q: %w", puid, err)+ return runtimeIdentityRequest{}, "", errors.WrapIff(err, "invalid PUID %q", puid)}gid, credentialGID, err := parseRuntimeIdentityValueInternal(pgid, "PGID")if err != nil {- return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PGID %q: %w", pgid, err)+ return runtimeIdentityRequest{}, "", errors.WrapIff(err, "invalid PGID %q", pgid)}return runtimeIdentityRequest{@@ -193,12 +194,12 @@ func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(s}if err := os.MkdirAll(configDir, pkgutils.DirPerm); err != nil {- return fmt.Errorf("create docker config directory: %w", err)+ return errors.WrapIf(err, "create docker config directory")}if configDir == defaultDockerConfigDir && os.Geteuid() == 0 {if err := os.Chown(configDir, uid, gid); err != nil {- return fmt.Errorf("chown docker config directory: %w", err)+ return errors.WrapIf(err, "chown docker config directory")}}@@ -227,7 +228,7 @@ func configureRuntimeDockerConfigEnvInternal(cfg *RuntimeIdentityConfig, setenvconfigDir = defaultDockerConfigDircfg.DockerConfig = configDirif err := setenv("DOCKER_CONFIG", configDir); err != nil {- return "", fmt.Errorf("set DOCKER_CONFIG: %w", err)+ return "", errors.WrapIf(err, "set DOCKER_CONFIG")}return configDir, nil@@ -284,40 +285,40 @@ func prepareWritablePathsInternal(uid int, gid int, mountpoints map[string]strucfunc prepareWritablePathsWithRootsInternal(uid int, gid int, mountpoints map[string]struct{}, projectsDir string, dataDirectory string, buildsDirectory string) error {if err := os.MkdirAll(dataDirectory, pkgutils.DirPerm); err != nil {- return fmt.Errorf("create data directory: %w", err)+ return errors.WrapIf(err, "create data directory")}if err := os.Chown(dataDirectory, uid, gid); err != nil {- return fmt.Errorf("chown data directory: %w", err)+ return errors.WrapIf(err, "chown data directory")}entries, err := os.ReadDir(dataDirectory)if err != nil {- return fmt.Errorf("read data directory: %w", err)+ return errors.WrapIf(err, "read data directory")}for _, entry := range entries {entryPath := filepath.Join(dataDirectory, entry.Name())if _, mounted := mountpoints[entryPath]; mounted {if err := os.Lchown(entryPath, uid, gid); err != nil {- return fmt.Errorf("chown mounted %s: %w", entryPath, err)+ return errors.WrapIff(err, "chown mounted %s", entryPath)}continue}if projectsDir != "" && filepath.Clean(entryPath) == projectsDir {if err := lchownFn(entryPath, uid, gid); err != nil {- return fmt.Errorf("chown %s: %w", entryPath, err)+ return errors.WrapIff(err, "chown %s", entryPath)}continue}if err := chownRecursiveInternal(entryPath, uid, gid, mountpoints, projectsDir); err != nil {- return fmt.Errorf("chown %s: %w", entryPath, err)+ return errors.WrapIff(err, "chown %s", entryPath)}}if _, mounted := mountpoints[buildsDirectory]; mounted {if err := os.Lchown(buildsDirectory, uid, gid); err != nil {- return fmt.Errorf("chown mounted builds directory: %w", err)+ return errors.WrapIf(err, "chown mounted builds directory")}return nil}@@ -326,11 +327,11 @@ func prepareWritablePathsWithRootsInternal(uid int, gid int, mountpoints map[strif os.IsNotExist(err) {return nil}- return fmt.Errorf("stat builds directory: %w", err)+ return errors.WrapIf(err, "stat builds directory")}if err := chownRecursiveInternal(buildsDirectory, uid, gid, mountpoints, projectsDir); err != nil {- return fmt.Errorf("chown builds directory: %w", err)+ return errors.WrapIf(err, "chown builds directory")}return nil@@ -351,16 +352,16 @@ func ensureSQLiteFilesExistInternal(databaseURL string) error {dir := filepath.Dir(sqlitePath)if dir != "" && dir != "." {if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil {- return fmt.Errorf("create sqlite directory %s: %w", dir, err)+ return errors.WrapIff(err, "create sqlite directory %s", dir)}}file, err := os.OpenFile(sqlitePath, os.O_CREATE|os.O_RDWR, pkgutils.FilePerm)if err != nil {- return fmt.Errorf("create sqlite file %s: %w", sqlitePath, err)+ return errors.WrapIff(err, "create sqlite file %s", sqlitePath)}if err := file.Close(); err != nil {- return fmt.Errorf("close sqlite file %s: %w", sqlitePath, err)+ return errors.WrapIff(err, "close sqlite file %s", sqlitePath)}return nil@@ -377,7 +378,7 @@ func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {parsed, err := url.Parse(value)if err != nil {- return "", false, fmt.Errorf("parse sqlite database url: %w", err)+ return "", false, errors.WrapIf(err, "parse sqlite database url")}// For relative URLs like "file:data/arcane.db", url.Parse puts the path indiff --git a/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go b/backend/pkg/libarcane/startup/runtime_identity_int_32bit.goindex 74e465a5d..0200ec55d 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go@@ -3,18 +3,19 @@package startupimport (- "fmt""strconv"++ "emperror.dev/errors")func parseRuntimeIdentityValueInternal(raw string, key string) (int, uint32, error) {value, err := strconv.ParseInt(raw, 10, 32)if err != nil {- return 0, 0, fmt.Errorf("parse %s: %w", key, err)+ return 0, 0, errors.WrapIff(err, "parse %s", key)}if value < 0 {- return 0, 0, fmt.Errorf("%s must be >= 0", key)+ return 0, 0, errors.Errorf("%s must be >= 0", key)}return int(value), uint32(value), nildiff --git a/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go b/backend/pkg/libarcane/startup/runtime_identity_int_64bit.goindex db92c97c7..b1e104f8f 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go@@ -3,23 +3,24 @@package startupimport (- "fmt""math""strconv"++ "emperror.dev/errors")func parseRuntimeIdentityValueInternal(raw string, key string) (int, uint32, error) {value, err := strconv.Atoi(raw)if err != nil {- return 0, 0, fmt.Errorf("parse %s: %w", key, err)+ return 0, 0, errors.WrapIff(err, "parse %s", key)}if value < 0 {- return 0, 0, fmt.Errorf("%s must be >= 0", key)+ return 0, 0, errors.Errorf("%s must be >= 0", key)}if value > math.MaxUint32 {- return 0, 0, fmt.Errorf("%s value %d exceeds max uint32", key, value)+ return 0, 0, errors.Errorf("%s value %d exceeds max uint32", key, value)}return value, uint32(value), nildiff --git a/backend/pkg/libarcane/startup/runtime_identity_linux.go b/backend/pkg/libarcane/startup/runtime_identity_linux.goindex d343c32ed..14c0f8723 100644--- a/backend/pkg/libarcane/startup/runtime_identity_linux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_linux.go@@ -4,20 +4,20 @@ package startupimport ("context"- "errors"- "fmt""os""os/exec""os/signal""syscall"+ "emperror.dev/errors"+"github.com/samber/mo")func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityRequest) error {executable, err := os.Executable()if err != nil {- return fmt.Errorf("resolve executable: %w", err)+ return errors.WrapIf(err, "resolve executable")}groups := runtimeIdentitySupplementaryGroupsInternal(req.DockerHost, resolveSocketGroupInternal)@@ -36,7 +36,7 @@ func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityR}if err := cmd.Start(); err != nil {- return fmt.Errorf("start runtime identity child: %w", err)+ return errors.WrapIf(err, "start runtime identity child")}sigCh := make(chan os.Signal, 2)@@ -70,7 +70,7 @@ func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityRos.Exit(exitErr.ExitCode())}- return fmt.Errorf("wait for runtime identity child: %w", err)+ return errors.WrapIf(err, "wait for runtime identity child")}}}diff --git a/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.goindex 2146784c7..cfed7b073 100644--- a/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go@@ -4,8 +4,9 @@ package startupimport ("context"- "fmt""runtime"++ "emperror.dev/errors")var (@@ -14,5 +15,5 @@ var ()func reexecWithRuntimeIdentityInternal(_ context.Context, req runtimeIdentityRequest) error {- return fmt.Errorf("runtime identity switching is only supported on linux, current platform is %s", runtime.GOOS)+ return errors.Errorf("runtime identity switching is only supported on linux, current platform is %s", runtime.GOOS)}diff --git a/backend/pkg/libarcane/swarm/stack_deploy_engine.go b/backend/pkg/libarcane/swarm/stack_deploy_engine.goindex 209ca0443..41c130f40 100644--- a/backend/pkg/libarcane/swarm/stack_deploy_engine.go+++ b/backend/pkg/libarcane/swarm/stack_deploy_engine.go@@ -4,7 +4,6 @@ import ("context""crypto/sha256""encoding/hex"- "errors""fmt""maps""net/netip"@@ -14,6 +13,8 @@ import ("strings""time"+ "emperror.dev/errors"+composegoloader "github.com/compose-spec/compose-go/v2/loader"composegotypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs"@@ -160,7 +161,7 @@ func DeployStack(ctx context.Context, dockerClient *dockerclient.Client, opts Stcontinue}if _, err := dockerClient.ServiceRemove(ctx, svc.ID, dockerclient.ServiceRemoveOptions{}); err != nil {- return fmt.Errorf("failed to remove swarm service %s: %w", name, err)+ return errors.WrapIff(err, "failed to remove swarm service %s", name)}}}@@ -264,7 +265,7 @@ func RenderStackConfig(ctx context.Context, opts StackRenderOptions) (*StackRendrendered, err := project.MarshalYAML()if err != nil {- return nil, fmt.Errorf("failed to render compose project: %w", err)+ return nil, errors.WrapIf(err, "failed to render compose project")}return &StackRenderResult{@@ -286,7 +287,7 @@ func loadComposeProject(ctx context.Context, projectName, composeContent, overrienvMap, err := parseEnvContent(envContent)if err != nil {- return nil, fmt.Errorf("failed to parse env content: %w", err)+ return nil, errors.WrapIf(err, "failed to parse env content")}workingDir := strings.TrimSpace(providedWorkingDir)@@ -322,7 +323,7 @@ func loadComposeProject(ctx context.Context, projectName, composeContent, overri}})if err != nil {- return nil, fmt.Errorf("failed to load compose project: %w", err)+ return nil, errors.WrapIf(err, "failed to load compose project")}project = project.WithoutUnnecessaryResources()@@ -333,7 +334,7 @@ func loadComposeProject(ctx context.Context, projectName, composeContent, overri// Translate container paths to host paths for Docker executionif pathMapper != nil {if err := pathMapper.TranslateVolumeSources(project); err != nil {- return nil, fmt.Errorf("failed to translate paths for docker host: %w", err)+ return nil, errors.WrapIf(err, "failed to translate paths for docker host")}}@@ -344,7 +345,7 @@ func listStackServices(ctx context.Context, dockerClient *dockerclient.Client, sfilter := make(dockerclient.Filters).Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{Filters: filter})if err != nil {- return nil, fmt.Errorf("failed to list swarm services: %w", err)+ return nil, errors.WrapIf(err, "failed to list swarm services")}services := servicesResult.Items@@ -376,7 +377,7 @@ func ensureSwarmNetworks(ctx context.Context, dockerClient *dockerclient.Client,continue}if !cerrdefs.IsNotFound(err) {- return nil, fmt.Errorf("failed to inspect network %s: %w", stackedName, err)+ return nil, errors.WrapIff(err, "failed to inspect network %s", stackedName)}driver := strings.TrimSpace(cfg.Driver)@@ -398,7 +399,7 @@ func ensureSwarmNetworks(ctx context.Context, dockerClient *dockerclient.Client,}if _, err := dockerClient.NetworkCreate(ctx, stackedName, createOpts); err != nil {- return nil, fmt.Errorf("failed to create network %s: %w", stackedName, err)+ return nil, errors.WrapIff(err, "failed to create network %s", stackedName)}}@@ -449,7 +450,7 @@ func ensureSwarmVolumesInternal(ctx context.Context, dockerClient *dockerclient.if _, err := dockerClient.VolumeInspect(ctx, name, dockerclient.VolumeInspectOptions{}); err == nil {continue} else if !cerrdefs.IsNotFound(err) {- return fmt.Errorf("failed to inspect volume %s: %w", name, err)+ return errors.WrapIff(err, "failed to inspect volume %s", name)}driver := cfg.Driver@@ -463,7 +464,7 @@ func ensureSwarmVolumesInternal(ctx context.Context, dockerClient *dockerclient.DriverOpts: cfg.DriverOpts,Labels: labels,}); err != nil {- return fmt.Errorf("failed to create volume %s: %w", name, err)+ return errors.WrapIff(err, "failed to create volume %s", name)}}return nil@@ -520,7 +521,7 @@ func createConfigResourceInternal(dockerClient *dockerclient.Client) func(contexresp, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})if err != nil {- return resourceMeta{}, fmt.Errorf("failed to create config %s: %w", managedName, err)+ return resourceMeta{}, errors.WrapIff(err, "failed to create config %s", managedName)}return resourceMeta{ID: resp.ID, Name: managedName}, nil}@@ -535,7 +536,7 @@ func createSecretResourceInternal(dockerClient *dockerclient.Client) func(contexresp, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})if err != nil {- return resourceMeta{}, fmt.Errorf("failed to create secret %s: %w", managedName, err)+ return resourceMeta{}, errors.WrapIff(err, "failed to create secret %s", managedName)}return resourceMeta{ID: resp.ID, Name: managedName}, nil}@@ -565,7 +566,7 @@ func ensureManagedFileResourceInternal() (resourceMeta, error) {data, err := resolveFileObjectContent(fileObject, workingDir)if err != nil {- return resourceMeta{}, fmt.Errorf("failed to load %s %s: %w", opts.ResourceType, name, err)+ return resourceMeta{}, errors.WrapIff(err, "failed to load %s %s", opts.ResourceType, name)}hash := hashManagedResource(data)@@ -573,7 +574,7 @@ func ensureManagedFileResourceInternal(if meta, err := opts.Inspect(ctx, managedName); err == nil {return meta, nil} else if !cerrdefs.IsNotFound(err) {- return resourceMeta{}, fmt.Errorf("failed to inspect %s %s: %w", opts.ResourceType, managedName, err)+ return resourceMeta{}, errors.WrapIff(err, "failed to inspect %s %s", opts.ResourceType, managedName)}resourceLabels := mergeLabels(labels, stackLabels)@@ -699,7 +700,7 @@ func createSwarmService(opts.EncodedRegistryAuth = encodedRegistryAuth}if _, err := dockerClient.ServiceCreate(ctx, opts); err != nil {- return fmt.Errorf("failed to create swarm service %s: %w", spec.Name, err)+ return errors.WrapIff(err, "failed to create swarm service %s", spec.Name)}return nil}@@ -740,11 +741,11 @@ func updateSwarmService(if strings.Contains(err.Error(), "service does not have a previous spec") {opts.RegistryAuthFrom = ""if _, retryErr := dockerClient.ServiceUpdate(ctx, existing.ID, opts); retryErr != nil {- return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, retryErr)+ return errors.WrapIff(retryErr, "failed to update swarm service %s", spec.Name)}return nil}- return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, err)+ return errors.WrapIff(err, "failed to update swarm service %s", spec.Name)}return nil}@@ -1028,7 +1029,7 @@ func resolveFileObjectContent(fileConfig composegotypes.FileObjectConfig, workinif fileConfig.Environment != "" {value, ok := os.LookupEnv(fileConfig.Environment)if !ok {- return nil, fmt.Errorf("environment variable %s not set", fileConfig.Environment)+ return nil, errors.Errorf("environment variable %s not set", fileConfig.Environment)}return []byte(value), nil}@@ -1047,7 +1048,7 @@ func resolvePathWithinWorkingDirInternal(workingDir, path string) (string, errorif !filepath.IsAbs(baseDir) {absBaseDir, err := filepath.Abs(baseDir)if err != nil {- return "", fmt.Errorf("failed to resolve working directory %q: %w", workingDir, err)+ return "", errors.WrapIff(err, "failed to resolve working directory %q", workingDir)}baseDir = absBaseDir}@@ -1060,17 +1061,17 @@ func resolvePathWithinWorkingDirInternal(workingDir, path string) (string, errorif !filepath.IsAbs(resolvedPath) {absResolvedPath, err := filepath.Abs(resolvedPath)if err != nil {- return "", fmt.Errorf("failed to resolve config file path %q: %w", path, err)+ return "", errors.WrapIff(err, "failed to resolve config file path %q", path)}resolvedPath = absResolvedPath}relativePath, err := filepath.Rel(baseDir, resolvedPath)if err != nil {- return "", fmt.Errorf("failed to validate config file path %q: %w", path, err)+ return "", errors.WrapIff(err, "failed to validate config file path %q", path)}if relativePath == ".." || strings.HasPrefix(relativePath, ".."+string(filepath.Separator)) {- return "", fmt.Errorf("config file path %q escapes the working directory", path)+ return "", errors.Errorf("config file path %q escapes the working directory", path)}return resolvedPath, nil@@ -1270,7 +1271,7 @@ func normalizeResolveImageMode(value string) (string, error) {case resolveImageAlways, resolveImageChanged, resolveImageNever:return mode, nildefault:- return "", fmt.Errorf("invalid resolve image mode %q: expected always, changed, or never", value)+ return "", errors.Errorf("invalid resolve image mode %q: expected always, changed, or never", value)}}@@ -1363,7 +1364,7 @@ func resolveRegistryAuthForSpec(encodedRegistryAuth, err := registryAuthForImage(ctx, image)if err != nil {- return "", fmt.Errorf("failed to resolve registry auth for image %s: %w", image, err)+ return "", errors.WrapIff(err, "failed to resolve registry auth for image %s", image)}return encodedRegistryAuth, nil@@ -1389,7 +1390,7 @@ func listStaleConfigResourcesInternal(dockerClient *dockerclient.Client) func(coreturn func(ctx context.Context, filters dockerclient.Filters) ([]staleManagedResourceInternal, error) {configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{Filters: filters})if err != nil {- return nil, fmt.Errorf("failed to list stack configs: %w", err)+ return nil, errors.WrapIf(err, "failed to list stack configs")}return collectStaleManagedResourcesInternal(configsResult.Items, func(cfg swarm.Config) staleManagedResourceInternal {@@ -1402,7 +1403,7 @@ func listStaleSecretResourcesInternal(dockerClient *dockerclient.Client) func(coreturn func(ctx context.Context, filters dockerclient.Filters) ([]staleManagedResourceInternal, error) {secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{Filters: filters})if err != nil {- return nil, fmt.Errorf("failed to list stack secrets: %w", err)+ return nil, errors.WrapIf(err, "failed to list stack secrets")}return collectStaleManagedResourcesInternal(secretsResult.Items, func(secret swarm.Secret) staleManagedResourceInternal {@@ -1462,7 +1463,7 @@ func cleanupStaleManagedResourcesInternal(ctx context.Context, stackName string,if isStaleSwarmResourceStillInUse(err) {continue}- return fmt.Errorf("failed to remove stale stack %s %s: %w", opts.ResourceType, resource.Name, err)+ return errors.WrapIff(err, "failed to remove stale stack %s %s", opts.ResourceType, resource.Name)}}diff --git a/backend/pkg/libarcane/system/gpu.go b/backend/pkg/libarcane/system/gpu.goindex ba0b323c7..343a0b6fc 100644--- a/backend/pkg/libarcane/system/gpu.go+++ b/backend/pkg/libarcane/system/gpu.go@@ -4,7 +4,6 @@ import ("bytes""context""encoding/csv"- "errors""fmt""log/slog""os"@@ -14,6 +13,8 @@ import ("sync""time"+ "emperror.dev/errors"+systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/samber/hot")@@ -203,7 +204,7 @@ func getNvidiaStatsInternal(ctx context.Context) ([]systemtypes.GPUStats, error)output, err := cmd.Output()if err != nil {slog.WarnContext(ctx, "Failed to execute nvidia-smi", "error", err)- return nil, fmt.Errorf("nvidia-smi execution failed: %w", err)+ return nil, errors.WrapIf(err, "nvidia-smi execution failed")}reader := csv.NewReader(bytes.NewReader(output))@@ -211,7 +212,7 @@ func getNvidiaStatsInternal(ctx context.Context) ([]systemtypes.GPUStats, error)records, err := reader.ReadAll()if err != nil {slog.WarnContext(ctx, "Failed to parse nvidia-smi CSV output", "error", err)- return nil, fmt.Errorf("failed to parse nvidia-smi output: %w", err)+ return nil, errors.WrapIf(err, "failed to parse nvidia-smi output")}var stats []systemtypes.GPUStats@@ -254,7 +255,7 @@ func getAMDStatsInternal(ctx context.Context) ([]systemtypes.GPUStats, error) {entries, err := os.ReadDir(AMDGPUSysfsPath)if err != nil {slog.WarnContext(ctx, "Failed to read DRM sysfs directory", "error", err)- return nil, fmt.Errorf("failed to read sysfs: %w", err)+ return nil, errors.WrapIf(err, "failed to read sysfs")}var stats []systemtypes.GPUStatsdiff --git a/backend/pkg/libarcane/volumehelper/helper.go b/backend/pkg/libarcane/volumehelper/helper.goindex 7a445ed75..e6b83161d 100644--- a/backend/pkg/libarcane/volumehelper/helper.go+++ b/backend/pkg/libarcane/volumehelper/helper.go@@ -2,13 +2,13 @@ package volumehelperimport ("context"- "errors"- "fmt""io""os""runtime""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount"@@ -78,7 +78,7 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client) (strin} else {defer func() { _ = pullReader.Close() }()if _, err := io.Copy(io.Discard, pullReader); err != nil {- pullErr = fmt.Errorf("read helper image pull response: %w", err)+ pullErr = errors.WrapIf(err, "read helper image pull response")} else {return DefaultToolsImage, nil}@@ -89,7 +89,7 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client) (strinreturn fallback.Image, nil}- return "", fmt.Errorf("failed to resolve helper image: tools image unavailable and arcane fallback not found (pull error: %w)", pullErr)+ return "", errors.WrapIf(pullErr, "failed to resolve helper image: tools image unavailable and arcane fallback not found")}// ResolveArcaneRuntimeImage resolves the current Arcane or Arcane agent imagediff --git a/backend/pkg/libarcane/volumes/compose.go b/backend/pkg/libarcane/volumes/compose.goindex 6f415c8be..4b566e97e 100644--- a/backend/pkg/libarcane/volumes/compose.go+++ b/backend/pkg/libarcane/volumes/compose.go@@ -1,11 +1,11 @@package volumesimport (- "errors"- "fmt""os""strings"+ "emperror.dev/errors"+composetemplate "github.com/compose-spec/compose-go/v2/template""go.yaml.in/yaml/v4")@@ -31,12 +31,12 @@ func composeVolumeKeysWithExplicitNameInternal(composeFiles []string) (map[strinfunc composeVolumeKeysWithExplicitNameInFileInternal(path string) (map[string]struct{}, error) {content, err := os.ReadFile(path)if err != nil {- return nil, fmt.Errorf("read compose file: %w", err)+ return nil, errors.WrapIf(err, "read compose file")}composeData := map[string]any{}if err := yaml.Unmarshal(content, &composeData); err != nil {- return nil, fmt.Errorf("parse compose file: %w", err)+ return nil, errors.WrapIf(err, "parse compose file")}rawVolumes, ok := composeData["volumes"]diff --git a/backend/pkg/libarcane/volumes/volume_rename.go b/backend/pkg/libarcane/volumes/volume_rename.goindex 559405082..a59c6ee37 100644--- a/backend/pkg/libarcane/volumes/volume_rename.go+++ b/backend/pkg/libarcane/volumes/volume_rename.go@@ -2,7 +2,7 @@ package volumesimport ("context"- "errors"+ stderrors "errors""fmt""log/slog""maps"@@ -11,6 +11,7 @@ import ("syscall""time"+ "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs""github.com/docker/compose/v5/pkg/api"@@ -83,7 +84,7 @@ func PlanMigration(ctx context.Context, dockerClient *client.Client, composeProjexplicitVolumeNames, err := composeVolumeKeysWithExplicitNameInternal(composeProject.ComposeFiles)if err != nil {- return nil, fmt.Errorf("failed to parse compose volume names: %w", err)+ return nil, errors.WrapIf(err, "failed to parse compose volume names")}entries, err := collectProjectRenameVolumeEntriesInternal(ctx, dockerClient, composeProject.Volumes, explicitVolumeNames, oldComposeName, newComposeName)@@ -137,7 +138,7 @@ func inspectProjectRenameVolumeEntryInternal(ctx context.Context, dockerClient *if cerrdefs.IsNotFound(err) {return projectVolumeRenameEntryInternal{}, false, nil}- return projectVolumeRenameEntryInternal{}, false, fmt.Errorf("inspect source volume %s: %w", oldName, err)+ return projectVolumeRenameEntryInternal{}, false, errors.WrapIff(err, "inspect source volume %s", oldName)}if err := ensureProjectRenameSourceVolumeDetachedInternal(ctx, dockerClient, oldName); err != nil {return projectVolumeRenameEntryInternal{}, false, err@@ -169,14 +170,13 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Apply(ctx context.Context)for _, entry := range m.entries {if err := createProjectRenamedVolumeInternal(ctx, dockerClient, entry); err != nil {- return errors.Join(err, m.rollbackCreatedTargets(ctx, dockerClient))+ return stderrors.Join(err, m.rollbackCreatedTargets(ctx, dockerClient))}m.createdNew = append(m.createdNew, entry)if err := copyProjectVolumeDataInternal(ctx, dockerClient, copyRuntime, entry.OldName, entry.NewName); err != nil {- return errors.Join(- fmt.Errorf("copy volume data from %s to %s: %w", entry.OldName, entry.NewName, err),- m.rollbackCreatedTargets(ctx, dockerClient),+ return stderrors.Join(errors.+ WrapIff(err, "copy volume data from %s to %s", entry.OldName, entry.NewName), m.rollbackCreatedTargets(ctx, dockerClient),)}}@@ -245,7 +245,7 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.Contexcontinue}preservedTargets[entry.NewName] = struct{}{}- rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{+ rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{OldName: entry.OldName,NewName: entry.NewName,}, errors.New("source volume was already removed")))@@ -258,10 +258,10 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.ContexsourceExists, err := VolumeExists(ctx, dockerClient, entry.OldName)if err != nil {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{+ rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{OldName: entry.OldName,NewName: entry.NewName,- }, fmt.Errorf("inspect source rollback volume %s: %w", entry.OldName, err)))+ }, errors.WrapIff(err, "inspect source rollback volume %s", entry.OldName)))continue}if sourceExists {@@ -271,24 +271,24 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.ContextargetExists, err := VolumeExists(ctx, dockerClient, entry.NewName)if err != nil {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{+ rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{OldName: entry.OldName,NewName: entry.NewName,- }, fmt.Errorf("inspect target rollback volume %s: %w", entry.NewName, err)))+ }, errors.WrapIff(err, "inspect target rollback volume %s", entry.NewName)))continue}if targetExists {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{+ rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(JournalVolume{OldName: entry.OldName,NewName: entry.NewName,}, errProjectRenameRollbackSourceMissingInternal))} else {- rollbackErr = errors.Join(rollbackErr, fmt.Errorf("source volume %s and target volume %s are missing during rollback", entry.OldName, entry.NewName))+ rollbackErr = stderrors.Join(rollbackErr, errors.Errorf("source volume %s and target volume %s are missing during rollback", entry.OldName, entry.NewName))}}- rollbackErr = errors.Join(rollbackErr, m.rollbackCreatedTargetsPreserving(ctx, dockerClient, preservedTargets))+ rollbackErr = stderrors.Join(rollbackErr, m.rollbackCreatedTargetsPreserving(ctx, dockerClient, preservedTargets))if rollbackErr == nil {dockerutil.InvalidateVolumeUsageCache(dockerClient)}@@ -308,12 +308,12 @@ func (m *dockerProjectVolumeRenameMigrationInternal) rollbackCreatedTargetsPresecontinue}if err := removeProjectVolumeHelperContainersInternal(ctx, dockerClient, entry.NewName); err != nil {- rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove helper containers for target volume %s: %w", entry.NewName, err))+ rollbackErr = stderrors.Join(rollbackErr, errors.WrapIff(err, "remove helper containers for target volume %s", entry.NewName))remainingCreated = append(remainingCreated, entry)continue}if err := removeProjectVolumeWithRetryInternal(ctx, dockerClient, entry.NewName, client.VolumeRemoveOptions{Force: true}); err != nil {- rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove target volume %s: %w", entry.NewName, err))+ rollbackErr = stderrors.Join(rollbackErr, errors.WrapIff(err, "remove target volume %s", entry.NewName))remainingCreated = append(remainingCreated, entry)}}@@ -339,7 +339,7 @@ func ensureProjectRenameTargetVolumeAbsentInternal(ctx context.Context, dockerClif cerrdefs.IsNotFound(err) {return nil}- return fmt.Errorf("inspect target volume %s: %w", newName, err)+ return errors.WrapIff(err, "inspect target volume %s", newName)}return &ProjectVolumeRenameConflictError{VolumeName: newName}}@@ -347,7 +347,7 @@ func ensureProjectRenameTargetVolumeAbsentInternal(ctx context.Context, dockerClfunc ensureProjectRenameSourceVolumeDetachedInternal(ctx context.Context, dockerClient *client.Client, oldName string) error {containerIDs, err := dockerutil.GetContainersUsingVolume(ctx, dockerClient, oldName)if err != nil {- return fmt.Errorf("inspect containers using source volume %s: %w", oldName, err)+ return errors.WrapIff(err, "inspect containers using source volume %s", oldName)}if len(containerIDs) > 0 {return &ProjectVolumeRenameInUseError{VolumeName: oldName, ContainerIDs: containerIDs}@@ -363,7 +363,7 @@ func createProjectRenamedVolumeInternal(ctx context.Context, dockerClient *clienhash, err := composepkg.VolumeHash(entry.NewConfig)if err != nil {- return fmt.Errorf("hash target volume %s: %w", entry.NewName, err)+ return errors.WrapIff(err, "hash target volume %s", entry.NewName)}labels[api.ConfigHashLabel] = hash@@ -374,7 +374,7 @@ func createProjectRenamedVolumeInternal(ctx context.Context, dockerClient *clienLabels: labels,})if err != nil {- return fmt.Errorf("create target volume %s: %w", entry.NewName, err)+ return errors.WrapIff(err, "create target volume %s", entry.NewName)}return nil}@@ -382,7 +382,7 @@ func createProjectRenamedVolumeInternal(ctx context.Context, dockerClient *clienfunc removeProjectVolumeHelperContainersInternal(ctx context.Context, dockerClient *client.Client, volumeName string) error {containers, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return fmt.Errorf("list containers for helper cleanup: %w", err)+ return errors.WrapIf(err, "list containers for helper cleanup")}var removeErr error@@ -391,7 +391,7 @@ func removeProjectVolumeHelperContainersInternal(ctx context.Context, dockerCliecontinue}if _, err := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); err != nil && !cerrdefs.IsNotFound(err) {- removeErr = errors.Join(removeErr, fmt.Errorf("remove helper container %s: %w", c.ID, err))+ removeErr = stderrors.Join(removeErr, errors.WrapIff(err, "remove helper container %s", c.ID))}}return removeErr@@ -429,7 +429,7 @@ func removeProjectVolumeWithRetryInternal(ctx context.Context, dockerClient *cli}select {case <-ctx.Done():- return errors.Join(ctx.Err(), err)+ return stderrors.Join(ctx.Err(), err)case <-time.After(200 * time.Millisecond):}}@@ -453,7 +453,7 @@ func copyProjectVolumeDataInternal(ctx context.Context, dockerClient *client.CliSourcePath: projectVolumeCopyMountPathInternal + "/.",})if err != nil {- return fmt.Errorf("read source volume archive: %w", err)+ return errors.WrapIf(err, "read source volume archive")}defer func() { _ = copyResult.Content.Close() }()@@ -469,7 +469,7 @@ func copyProjectVolumeDataInternal(ctx context.Context, dockerClient *client.CliDetail: err.Error(),}}- return fmt.Errorf("write target volume archive: %w", err)+ return errors.WrapIf(err, "write target volume archive")}return nil@@ -496,7 +496,7 @@ func createProjectVolumeCopyHolderContainerInternal(ctx context.Context, dockerCHostConfig: hostConfig,})if err != nil {- return "", nil, fmt.Errorf("create volume copy holder: %w", err)+ return "", nil, errors.WrapIf(err, "create volume copy holder")}cleanup := func() {@@ -592,7 +592,7 @@ func RollbackVolumes(ctx context.Context, dockerClient *client.Client, volumes [var rollbackErr errorfor _, vol := range slices.Backward(volumes) {if err := RollbackVolume(ctx, dockerClient, vol); err != nil {- rollbackErr = errors.Join(rollbackErr, err)+ rollbackErr = stderrors.Join(rollbackErr, err)}}if len(volumes) > 0 {@@ -604,11 +604,11 @@ func RollbackVolumes(ctx context.Context, dockerClient *client.Client, volumes [func RollbackVolume(ctx context.Context, dockerClient *client.Client, vol JournalVolume) error {oldExists, err := VolumeExists(ctx, dockerClient, vol.OldName)if err != nil {- return NewTargetPreservedDuringRollbackError(vol, fmt.Errorf("inspect source rollback volume %s: %w", vol.OldName, err))+ return NewTargetPreservedDuringRollbackError(vol, errors.WrapIff(err, "inspect source rollback volume %s", vol.OldName))}newExists, err := VolumeExists(ctx, dockerClient, vol.NewName)if err != nil {- return NewTargetPreservedDuringRollbackError(vol, fmt.Errorf("inspect target rollback volume %s: %w", vol.NewName, err))+ return NewTargetPreservedDuringRollbackError(vol, errors.WrapIff(err, "inspect target rollback volume %s", vol.NewName))}switch {@@ -626,7 +626,7 @@ func CleanupRollbackTargetVolumes(ctx context.Context, dockerClient *client.Clievar cleanupErr errorfor _, vol := range slices.Backward(volumes) {if err := cleanupProjectRenameRollbackTargetVolumeInternal(ctx, dockerClient, vol); err != nil {- cleanupErr = errors.Join(cleanupErr, err)+ cleanupErr = stderrors.Join(cleanupErr, err)}}return cleanupErr@@ -635,11 +635,11 @@ func CleanupRollbackTargetVolumes(ctx context.Context, dockerClient *client.Cliefunc cleanupProjectRenameRollbackTargetVolumeInternal(ctx context.Context, dockerClient *client.Client, vol JournalVolume) error {oldExists, err := VolumeExists(ctx, dockerClient, vol.OldName)if err != nil {- return fmt.Errorf("inspect source cleanup volume %s: %w", vol.OldName, err)+ return errors.WrapIff(err, "inspect source cleanup volume %s", vol.OldName)}newExists, err := VolumeExists(ctx, dockerClient, vol.NewName)if err != nil {- return fmt.Errorf("inspect target cleanup volume %s: %w", vol.NewName, err)+ return errors.WrapIff(err, "inspect target cleanup volume %s", vol.NewName)}switch {@@ -662,7 +662,7 @@ func removeProjectRenameJournalTargetVolumeInternal(ctx context.Context, dockerCreturn err}if err := removeProjectVolumeWithRetryInternal(ctx, dockerClient, newName, client.VolumeRemoveOptions{Force: true}); err != nil {- return fmt.Errorf("remove rollback target volume %s: %w", newName, err)+ return errors.WrapIff(err, "remove rollback target volume %s", newName)}return nil}@@ -675,7 +675,7 @@ func VolumeExists(ctx context.Context, dockerClient *client.Client, name string)if cerrdefs.IsNotFound(err) {return false, nil}- return false, fmt.Errorf("inspect volume %s: %w", name, err)+ return false, errors.WrapIff(err, "inspect volume %s", name)}type ProjectVolumeRenameConflictError struct {diff --git a/backend/pkg/libarcane/vuln/trivy.go b/backend/pkg/libarcane/vuln/trivy.goindex 5434dd670..4295cf672 100644--- a/backend/pkg/libarcane/vuln/trivy.go+++ b/backend/pkg/libarcane/vuln/trivy.go@@ -6,11 +6,11 @@ package vulnimport ("encoding/base64"json "encoding/json/v2"- "fmt""net/url""runtime""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"containertypes "github.com/moby/moby/api/types/container"dockerregistry "github.com/moby/moby/api/types/registry"@@ -93,7 +93,7 @@ func ParseDockerHost(dockerHost string) (scheme string, socketPath string, err eparsed, err := url.Parse(dockerHost)if err != nil {- return "", "", fmt.Errorf("parse docker host %q: %w", dockerHost, err)+ return "", "", errors.WrapIff(err, "parse docker host %q", dockerHost)}scheme = strings.ToLower(strings.TrimSpace(parsed.Scheme))@@ -101,13 +101,13 @@ func ParseDockerHost(dockerHost string) (scheme string, socketPath string, err ecase "unix":socketPath = strings.TrimSpace(parsed.Path)if socketPath == "" {- return "", "", fmt.Errorf("docker host %q is missing a unix socket path", dockerHost)+ return "", "", errors.Errorf("docker host %q is missing a unix socket path", dockerHost)}return scheme, socketPath, nilcase "tcp", "http", "https":return scheme, "", nildefault:- return "", "", fmt.Errorf("unsupported docker host scheme %q", scheme)+ return "", "", errors.Errorf("unsupported docker host scheme %q", scheme)}}diff --git a/backend/pkg/pagination/db_utils.go b/backend/pkg/pagination/db_utils.goindex b20d5346d..3d5e02b06 100644--- a/backend/pkg/pagination/db_utils.go+++ b/backend/pkg/pagination/db_utils.go@@ -1,9 +1,9 @@package paginationimport (- "fmt""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""gorm.io/gorm")@@ -46,12 +46,12 @@ func ApplyLikeSearch(q *gorm.DB, search string, condition string) *gorm.DB {func PaginateSortAndMapDB[M any, D any](params QueryParams, query *gorm.DB, records *[]M) ([]D, Response, error) {paginationResp, err := PaginateAndSortDB(params, query, records)if err != nil {- return nil, Response{}, fmt.Errorf("paginate db records: %w", err)+ return nil, Response{}, errors.WrapIf(err, "paginate db records")}out, err := mapper.MapSlice[M, D](*records)if err != nil {- return nil, Response{}, fmt.Errorf("map db records: %w", err)+ return nil, Response{}, errors.WrapIf(err, "map db records")}return out, paginationResp, nildiff --git a/backend/pkg/projects/build.go b/backend/pkg/projects/build.goindex 014cf21ad..6d791c9fd 100644--- a/backend/pkg/projects/build.go+++ b/backend/pkg/projects/build.go@@ -1,10 +1,10 @@package projectsimport (- "fmt""path/filepath""strings"+ "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"contextsource "go.getarcane.app/builds/pkg/utils/contextsource")@@ -16,13 +16,13 @@ func ResolveBuildContext(workingDir string, svc composetypes.ServiceConfig, servif contextDir == "" {contextDir = workingDir} else if _, isGitContext, err := contextsource.ParseGitBuildContextSource(contextDir); err != nil {- return "", fmt.Errorf("invalid build context for service %s: %w", serviceName, err)+ return "", errors.WrapIff(err, "invalid build context for service %s", serviceName)} else if !isGitContext && !filepath.IsAbs(contextDir) {contextDir = filepath.Join(workingDir, contextDir)}if contextDir == "" {- return "", fmt.Errorf("build context not set for service %s", serviceName)+ return "", errors.Errorf("build context not set for service %s", serviceName)}return contextDir, nildiff --git a/backend/pkg/projects/compose_override.go b/backend/pkg/projects/compose_override.goindex 7ee071854..2023b2df9 100644--- a/backend/pkg/projects/compose_override.go+++ b/backend/pkg/projects/compose_override.go@@ -1,13 +1,14 @@package projectsimport (- "errors""log/slog""os""path/filepath""slices""strings"+ "emperror.dev/errors"+"github.com/compose-spec/compose-go/v2/cli")diff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.goindex 861f83e8d..5c17accf0 100644--- a/backend/pkg/projects/custom_labels.go+++ b/backend/pkg/projects/custom_labels.go@@ -3,12 +3,12 @@ package projectsimport ("context"- "fmt""maps""os""path/filepath""strings"+ "emperror.dev/errors""github.com/compose-spec/compose-go/v2/loader"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -60,7 +60,7 @@ func ParseArcaneComposeMetadata(ctx context.Context, composeFilePath, projectsDienvLoader := NewEnvLoader(projectsDirectory, workdir, autoInjectEnv)envMap, _, err := envLoader.LoadEnvironment(ctx)if err != nil {- return emptyArcaneComposeMetadataInternal(), fmt.Errorf("load project environment: %w", err)+ return emptyArcaneComposeMetadataInternal(), errors.WrapIf(err, "load project environment")}return ParseArcaneComposeMetadataWithEnv(ctx, composeFilePath, envMap)@@ -92,7 +92,7 @@ func parseArcaneComposeMetadataFromFileInternal(ctx context.Context, composeFileproject, err := loadComposeProjectForMetadataFromFileInternal(ctx, absPath, mergedEnv)if err != nil {- return meta, fmt.Errorf("load compose metadata: %w", err)+ return meta, errors.WrapIf(err, "load compose metadata")}meta = extractArcaneComposeMetadata(project)@@ -287,12 +287,12 @@ func loadProcessEnv() map[string]string {func parseIncludePaths(composeFilePath string) ([]string, error) {content, err := os.ReadFile(composeFilePath)if err != nil {- return nil, fmt.Errorf("read compose file: %w", err)+ return nil, errors.WrapIf(err, "read compose file")}composeData := map[string]any{}if err := yaml.Unmarshal(content, &composeData); err != nil {- return nil, fmt.Errorf("parse compose file: %w", err)+ return nil, errors.WrapIf(err, "parse compose file")}rawIncludes, ok := composeData["include"]diff --git a/backend/pkg/projects/discovery.go b/backend/pkg/projects/discovery.goindex bfef14378..5b455b1f9 100644--- a/backend/pkg/projects/discovery.go+++ b/backend/pkg/projects/discovery.go@@ -1,14 +1,14 @@package projectsimport (- "errors"- "fmt""log/slog""os""path/filepath""regexp""slices""strings"++ "emperror.dev/errors")type DiscoveredProjectDir struct {@@ -71,7 +71,7 @@ func DiscoverProjectDirectories(root string, followSymlinks bool, maxDepth int)return nil, err}if !isDir {- return nil, fmt.Errorf("project root is not a directory: %s", root)+ return nil, errors.Errorf("project root is not a directory: %s", root)}discovered := make([]DiscoveredProjectDir, 0)diff --git a/backend/pkg/projects/env.go b/backend/pkg/projects/env.goindex 778bba5ca..5b4eaf9a0 100644--- a/backend/pkg/projects/env.go+++ b/backend/pkg/projects/env.go@@ -4,8 +4,6 @@ import ("context""crypto/sha256""encoding/hex"- "errors"- "fmt""io""log/slog""maps"@@ -17,6 +15,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/compose-spec/compose-go/v2/dotenv""github.com/samber/hot")@@ -185,12 +185,12 @@ func loadCachedEnvFileInternal(_ context.Context, envCache *hot.HotCache[string,return nil, err}if info.IsDir() {- return nil, fmt.Errorf("path is a directory: %s", path)+ return nil, errors.Errorf("path is a directory: %s", path)}parsed, err := parseProjectEnvFileExistingInternal(path, contextEnv)if err != nil {- return nil, fmt.Errorf("parse env file: %w", err)+ return nil, errors.WrapIf(err, "parse env file")}entry.exists = trueentry.mtime = info.ModTime()@@ -246,7 +246,7 @@ func cloneEnvMapInternal(src EnvMap) EnvMap {func parseProjectEnvFileExistingInternal(path string, contextEnv EnvMap) (EnvMap, error) {f, err := os.Open(path)if err != nil {- return nil, fmt.Errorf("open file: %w", err)+ return nil, errors.WrapIf(err, "open file")}defer func() { _ = f.Close() }()return parseEnvWithContext(f, contextEnv)@@ -275,7 +275,7 @@ func WithTransientValidationEnvFile(projectPath string, effectiveEnvContent *stroriginalExists := readErr == nilif readErr != nil && !os.IsNotExist(readErr) {if !errors.Is(readErr, os.ErrPermission) {- return fmt.Errorf("prepare env file for compose validation: %w", readErr)+ return errors.WrapIf(readErr, "prepare env file for compose validation")}// The file exists but is permission-locked (e.g. chmod 000, foreign-owned).// Its contents can't be verified or safely overwritten, so leave it@@ -296,7 +296,7 @@ func WithTransientValidationEnvFile(projectPath string, effectiveEnvContent *strcontent = *effectiveEnvContent}if writeErr := WriteEnvFile(projectPath, projectPath, content); writeErr != nil {- return fmt.Errorf("prepare env file for compose validation: %w", writeErr)+ return errors.WrapIf(writeErr, "prepare env file for compose validation")}defer func() {@@ -312,7 +312,7 @@ func WithTransientValidationEnvFile(projectPath string, effectiveEnvContent *strif restoreErr != nil && !os.IsNotExist(restoreErr) {if err == nil {- err = fmt.Errorf("restore env file after compose validation: %w", restoreErr)+ err = errors.WrapIf(restoreErr, "restore env file after compose validation")}}}()@@ -334,13 +334,13 @@ func BuildEffectiveEnvContent(gitContent, overrideContent string) (string, errorgitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse git env content: %w", err)+ return "", errors.WrapIf(err, "parse git env content")}maps.Copy(contextEnv, gitEnv)_, err = ParseProjectEnvContent(overrideContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse override env content: %w", err)+ return "", errors.WrapIf(err, "parse override env content")}switch {@@ -370,13 +370,13 @@ func BuildAdditiveOverrideEnvContent(gitContent, localContent string) (string, egitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse git env content: %w", err)+ return "", errors.WrapIf(err, "parse git env content")}maps.Copy(contextEnv, gitEnv)localEnv, err := ParseProjectEnvContent(localContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse local env content: %w", err)+ return "", errors.WrapIf(err, "parse local env content")}override := make(EnvMap)@@ -394,13 +394,13 @@ func buildOverrideEnvContentInternal(gitContent, effectiveContent string) (stringitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse git env content: %w", err)+ return "", errors.WrapIf(err, "parse git env content")}maps.Copy(contextEnv, gitEnv)effectiveEnv, err := ParseProjectEnvContent(effectiveContent, contextEnv)if err != nil {- return "", fmt.Errorf("parse effective env content: %w", err)+ return "", errors.WrapIf(err, "parse effective env content")}override := make(EnvMap)@@ -509,7 +509,7 @@ func WriteManagedEnvFile(projectsDirectory, projectPath, fileName string, unread}return WriteProjectFile(projectsDirectory, projectPath, OverrideEnvFileName, content)default:- return fmt.Errorf("write managed env file: unsupported file name %q", fileName)+ return errors.Errorf("write managed env file: unsupported file name %q", fileName)}}@@ -528,7 +528,7 @@ func parseEnvWithContext(r io.Reader, contextEnv EnvMap) (EnvMap, error) {// Use compose-go's dotenv parser with lookup support for variable expansionenvMap, err := dotenv.ParseWithLookup(r, lookupFn)if err != nil {- return nil, fmt.Errorf("parse env: %w", err)+ return nil, errors.WrapIf(err, "parse env")}return envMap, nil@@ -551,7 +551,7 @@ func readOptionalProjectFileInternal(projectPath, fileName string) (content striif errors.Is(readErr, os.ErrPermission) {return "", false, true, nil}- return "", false, false, fmt.Errorf("read %s: %w", fileName, readErr)+ return "", false, false, errors.WrapIff(readErr, "read %s", fileName)}// formatEnvMapInternal serializes env maps into Arcane's canonical generateddiff --git a/backend/pkg/projects/fs_backup.go b/backend/pkg/projects/fs_backup.goindex 8a575a8f4..a79c18238 100644--- a/backend/pkg/projects/fs_backup.go+++ b/backend/pkg/projects/fs_backup.go@@ -1,14 +1,14 @@package projectsimport (- "errors"- "fmt""os""path""path/filepath""slices""strings"+ "emperror.dev/errors"+"go.getarcane.app/sys/atomic")@@ -59,13 +59,13 @@ type ProjectUpdateBackup struct {func BackupProjectUpdateScope(projectDir, backupDir string, scope ProjectUpdateBackupScope) (*ProjectUpdateBackup, error) {projRoot, err := os.OpenRoot(projectDir)if err != nil {- return nil, fmt.Errorf("open project directory: %w", err)+ return nil, errors.WrapIf(err, "open project directory")}defer func() { _ = projRoot.Close() }()backupRoot, err := os.OpenRoot(backupDir)if err != nil {- return nil, fmt.Errorf("open backup directory: %w", err)+ return nil, errors.WrapIf(err, "open backup directory")}defer func() { _ = backupRoot.Close() }()@@ -108,7 +108,7 @@ func normalizeScopePathsInternal(paths []string) []string {func backupTopLevelFilesInternal(projRoot, backupRoot *os.Root, backup *ProjectUpdateBackup) error {entries, err := os.ReadDir(projRoot.Name())if err != nil {- return fmt.Errorf("read project directory: %w", err)+ return errors.WrapIf(err, "read project directory")}for _, entry := range entries {name := entry.Name()@@ -139,18 +139,18 @@ func backupScopePathInternal(projRoot, backupRoot *os.Root, projectDir, backupDireturn nil}if err != nil {- return fmt.Errorf("inspect project path %s: %w", rel, err)+ return errors.WrapIff(err, "inspect project path %s", rel)}switch {case info.IsDir():destDir := filepath.Join(backupDir, filepath.FromSlash(rel))if err := os.MkdirAll(destDir, 0o755); err != nil {- return fmt.Errorf("create backup directory: %w", err)+ return errors.WrapIf(err, "create backup directory")}skipped, err := CopyDirectoryContentsTolerant(filepath.Join(projectDir, filepath.FromSlash(rel)), destDir)if err != nil {- return fmt.Errorf("backup project directory %s: %w", rel, err)+ return errors.WrapIff(err, "backup project directory %s", rel)}for _, sub := range skipped {backup.Skipped = append(backup.Skipped, path.Join(rel, filepath.ToSlash(sub)))@@ -175,7 +175,7 @@ func shallowestAbsentAncestorInternal(projRoot *os.Root, rel string) (string, erif errors.Is(err, os.ErrNotExist) {return current, nil}- return "", fmt.Errorf("inspect project path %s: %w", current, err)+ return "", errors.WrapIff(err, "inspect project path %s", current)}}return rel, nil@@ -184,7 +184,7 @@ func shallowestAbsentAncestorInternal(projRoot *os.Root, rel string) (string, erfunc copyBackupFileInternal(projRoot, backupRoot *os.Root, rel string, backup *ProjectUpdateBackup) error {info, err := projRoot.Lstat(rel)if err != nil {- return fmt.Errorf("inspect project file %s: %w", rel, err)+ return errors.WrapIff(err, "inspect project file %s", rel)}content, err := projRoot.ReadFile(rel)if err != nil {@@ -192,15 +192,15 @@ func copyBackupFileInternal(projRoot, backupRoot *os.Root, rel string, backup *Pbackup.Skipped = append(backup.Skipped, rel)return nil}- return fmt.Errorf("read project file %s: %w", rel, err)+ return errors.WrapIff(err, "read project file %s", rel)}if dir := path.Dir(rel); dir != "." {if err := backupRoot.MkdirAll(dir, 0o755); err != nil {- return fmt.Errorf("create backup directory: %w", err)+ return errors.WrapIf(err, "create backup directory")}}if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); err != nil {- return fmt.Errorf("write backup file %s: %w", rel, err)+ return errors.WrapIff(err, "write backup file %s", rel)}backup.FileEntries = append(backup.FileEntries, rel)return nil@@ -214,7 +214,7 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bacbackup.Skipped = append(backup.Skipped, rel)return nil}- return fmt.Errorf("read project env symlink %s: %w", rel, err)+ return errors.WrapIff(err, "read project env symlink %s", rel)}resolvedPath, perm, isSymlink, err := resolveEnvFileWriteTargetInternal(envPath)@@ -223,10 +223,10 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bacbackup.Skipped = append(backup.Skipped, rel)return nil}- return fmt.Errorf("resolve project env symlink %s: %w", rel, err)+ return errors.WrapIff(err, "resolve project env symlink %s", rel)}if !isSymlink {- return fmt.Errorf("project env file %s is no longer a symlink", rel)+ return errors.Errorf("project env file %s is no longer a symlink", rel)}content, err := os.ReadFile(resolvedPath)@@ -235,10 +235,10 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bacbackup.Skipped = append(backup.Skipped, rel)return nil}- return fmt.Errorf("read project env symlink target %s: %w", rel, err)+ return errors.WrapIff(err, "read project env symlink target %s", rel)}if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, perm); err != nil {- return fmt.Errorf("write backup file %s: %w", rel, err)+ return errors.WrapIff(err, "write backup file %s", rel)}backup.FileEntries = append(backup.FileEntries, rel)@@ -274,7 +274,7 @@ func dedupeCoveredBackupEntriesInternal(backup *ProjectUpdateBackup) {func RestoreProjectUpdateBackup(projectDir string, backup *ProjectUpdateBackup) error {projRoot, err := os.OpenRoot(projectDir)if err != nil {- return fmt.Errorf("open project directory: %w", err)+ return errors.WrapIf(err, "open project directory")}defer func() { _ = projRoot.Close() }()@@ -287,19 +287,19 @@ func RestoreProjectUpdateBackup(projectDir string, backup *ProjectUpdateBackup)// 3. Mirror backed-up directories back in place.for _, rel := range backup.DirEntries {if err := projRoot.MkdirAll(rel, 0o755); err != nil {- return fmt.Errorf("recreate project directory %s: %w", rel, err)+ return errors.WrapIff(err, "recreate project directory %s", rel)}preserve := skippedUnderInternal(backup.Skipped, rel)src := filepath.Join(backup.BackupDir, filepath.FromSlash(rel))dest := filepath.Join(projectDir, filepath.FromSlash(rel))if err := MirrorDirectoryContentsPreserving(src, dest, preserve); err != nil {- return fmt.Errorf("restore project directory %s: %w", rel, err)+ return errors.WrapIff(err, "restore project directory %s", rel)}}backupRoot, err := os.OpenRoot(backup.BackupDir)if err != nil {- return fmt.Errorf("open backup directory: %w", err)+ return errors.WrapIf(err, "open backup directory")}defer func() { _ = backupRoot.Close() }()@@ -343,12 +343,12 @@ func undoRenamedDirsAndDebrisInternal(projRoot *os.Root, backup *ProjectUpdateBacontinue}if err := projRoot.RemoveAll(src); err != nil {- return fmt.Errorf("remove recreated path %s: %w", src, err)+ return errors.WrapIff(err, "remove recreated path %s", src)}handledAbsent[src] = true}if err := projRoot.Rename(dest, src); err != nil {- return fmt.Errorf("undo rename of %s: %w", src, err)+ return errors.WrapIff(err, "undo rename of %s", src)}}@@ -359,7 +359,7 @@ func undoRenamedDirsAndDebrisInternal(projRoot *os.Root, backup *ProjectUpdateBacontinue}if err := projRoot.RemoveAll(rel); err != nil {- return fmt.Errorf("remove created path %s: %w", rel, err)+ return errors.WrapIff(err, "remove created path %s", rel)}}return nil@@ -379,29 +379,29 @@ func skippedUnderInternal(skipped []string, rel string) []string {func restoreBackupFileInternal(backupRoot, projRoot *os.Root, backup *ProjectUpdateBackup, rel string) error {info, err := backupRoot.Lstat(rel)if err != nil {- return fmt.Errorf("inspect backup file %s: %w", rel, err)+ return errors.WrapIff(err, "inspect backup file %s", rel)}content, err := backupRoot.ReadFile(rel)if err != nil {- return fmt.Errorf("read backup file %s: %w", rel, err)+ return errors.WrapIff(err, "read backup file %s", rel)}if backup.envSymlink != nil && backup.envSymlink.relativePath == rel {return restoreBackupEnvSymlinkInternal(projRoot, backup.envSymlink, content, info.Mode().Perm())}if live, err := projRoot.Lstat(rel); err == nil && live.IsDir() {if err := projRoot.RemoveAll(rel); err != nil {- return fmt.Errorf("remove conflicting directory %s: %w", rel, err)+ return errors.WrapIff(err, "remove conflicting directory %s", rel)}}if dir := path.Dir(rel); dir != "." {if err := projRoot.MkdirAll(dir, 0o755); err != nil {- return fmt.Errorf("recreate parent directory of %s: %w", rel, err)+ return errors.WrapIff(err, "recreate parent directory of %s", rel)}}// Atomic write: a crash mid-restore leaves either the failed-update// content or the fully restored file, never a torn write.if err := atomic.WriteFile(filepath.Join(projRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); err != nil {- return fmt.Errorf("restore project file %s: %w", rel, err)+ return errors.WrapIff(err, "restore project file %s", rel)}return nil}@@ -410,30 +410,30 @@ func restoreBackupEnvSymlinkInternal(projRoot *os.Root, envBackup *projectUpdateenvPath := filepath.Join(projRoot.Name(), filepath.FromSlash(envBackup.relativePath))info, err := os.Lstat(envPath)if err != nil {- return fmt.Errorf("inspect project env symlink during restore: %w", err)+ return errors.WrapIf(err, "inspect project env symlink during restore")}if info.Mode()&os.ModeSymlink == 0 {- return fmt.Errorf("refusing to restore project env file %s: destination is no longer a symlink", envBackup.relativePath)+ return errors.Errorf("refusing to restore project env file %s: destination is no longer a symlink", envBackup.relativePath)}linkTarget, err := os.Readlink(envPath)if err != nil {- return fmt.Errorf("read project env symlink during restore: %w", err)+ return errors.WrapIf(err, "read project env symlink during restore")}if linkTarget != envBackup.linkTarget {- return fmt.Errorf("refusing to restore project env file %s: symlink target changed", envBackup.relativePath)+ return errors.Errorf("refusing to restore project env file %s: symlink target changed", envBackup.relativePath)}resolvedPath, _, isSymlink, err := resolveEnvFileWriteTargetInternal(envPath)if err != nil {- return fmt.Errorf("resolve project env symlink during restore: %w", err)+ return errors.WrapIf(err, "resolve project env symlink during restore")}if !isSymlink || filepath.Clean(resolvedPath) != envBackup.resolvedPath {- return fmt.Errorf("refusing to restore project env file %s: resolved symlink target changed", envBackup.relativePath)+ return errors.Errorf("refusing to restore project env file %s: resolved symlink target changed", envBackup.relativePath)}if err := atomic.WriteFile(resolvedPath, content, perm); err != nil {- return fmt.Errorf("restore project env symlink target %s: %w", envBackup.relativePath, err)+ return errors.WrapIff(err, "restore project env symlink target %s", envBackup.relativePath)}return nil}@@ -441,7 +441,7 @@ func restoreBackupEnvSymlinkInternal(projRoot *os.Root, envBackup *projectUpdatefunc restoreTopLevelFilesInternal(backupRoot, projRoot *os.Root, backup *ProjectUpdateBackup) error {backupEntries, err := os.ReadDir(backupRoot.Name())if err != nil {- return fmt.Errorf("read backup directory: %w", err)+ return errors.WrapIf(err, "read backup directory")}inBackup := make(map[string]bool, len(backupEntries))for _, entry := range backupEntries {@@ -458,7 +458,7 @@ func restoreTopLevelFilesInternal(backupRoot, projRoot *os.Root, backup *ProjectliveEntries, err := os.ReadDir(projRoot.Name())if err != nil {- return fmt.Errorf("read project directory: %w", err)+ return errors.WrapIf(err, "read project directory")}for _, entry := range liveEntries {name := entry.Name()@@ -466,7 +466,7 @@ func restoreTopLevelFilesInternal(backupRoot, projRoot *os.Root, backup *Projectcontinue}if err := projRoot.Remove(name); err != nil {- return fmt.Errorf("prune created file %s: %w", name, err)+ return errors.WrapIff(err, "prune created file %s", name)}}diff --git a/backend/pkg/projects/fs_templates.go b/backend/pkg/projects/fs_templates.goindex c060d0740..5d947f4df 100644--- a/backend/pkg/projects/fs_templates.go+++ b/backend/pkg/projects/fs_templates.go@@ -2,13 +2,13 @@ package projectsimport ("context"- "errors""fmt""os""path/filepath""regexp""strings"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils")@@ -17,15 +17,15 @@ func ReadFolderComposeTemplate(baseDir, folder string) (string, *string, string,folderPath := filepath.Join(baseDir, folder)composePath, err := DetectComposeFile(folderPath)if err != nil {- if _, ok := errors.AsType[*common.ComposeFileNotFoundError](err); ok {+ if errors.Is(err, common.ErrComposeFileNotFound) {return "", nil, "", false, nil}- return "", nil, "", false, fmt.Errorf("detect compose file: %w", err)+ return "", nil, "", false, errors.WrapIf(err, "detect compose file")}b, err := os.ReadFile(composePath)if err != nil {- return "", nil, "", false, fmt.Errorf("read compose %s: %w", composePath, err)+ return "", nil, "", false, errors.WrapIff(err, "read compose %s", composePath)}var envPtr *string@@ -60,11 +60,11 @@ func Slugify(in string) string {func EnsureTemplateDir(ctx context.Context, templatesDir, base string) (dir, composePath, envPath string, err error) {baseDir, derr := GetTemplatesDirectory(ctx, templatesDir)if derr != nil {- return "", "", "", fmt.Errorf("ensure templates dir: %w", derr)+ return "", "", "", errors.WrapIf(derr, "ensure templates dir")}dir = filepath.Join(baseDir, base)if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil {- return "", "", "", fmt.Errorf("failed to create template directory: %w", err)+ return "", "", "", errors.WrapIf(err, "failed to create template directory")}composePath = filepath.Join(dir, "compose.yaml")envPath = filepath.Join(dir, ".env.example")@@ -94,7 +94,7 @@ func WriteTemplateFiles(composePath, envPath, composeContent, envContent string)func EnsureDefaultTemplates(ctx context.Context, configuredTemplatesDir string) error {templatesDir, err := GetTemplatesDirectory(ctx, configuredTemplatesDir)if err != nil {- return fmt.Errorf("get templates directory: %w", err)+ return errors.WrapIf(err, "get templates directory")}composePath := filepath.Join(templatesDir, ".compose.template")@@ -105,28 +105,28 @@ func EnsureDefaultTemplates(ctx context.Context, configuredTemplatesDir string)// Write default compose template if it doesn't existif _, err := os.Stat(composePath); os.IsNotExist(err) {if err := WriteTemplateFile(composePath, getDefaultComposeTemplate()); err != nil {- return fmt.Errorf("write default compose template: %w", err)+ return errors.WrapIf(err, "write default compose template")}}// Write default swarm stack template if it doesn't existif _, err := os.Stat(swarmStackPath); os.IsNotExist(err) {if err := WriteTemplateFile(swarmStackPath, DefaultSwarmStackTemplate()); err != nil {- return fmt.Errorf("write default swarm stack template: %w", err)+ return errors.WrapIf(err, "write default swarm stack template")}}// Write default swarm stack env template if it doesn't existif _, err := os.Stat(swarmStackEnvPath); os.IsNotExist(err) {if err := WriteTemplateFile(swarmStackEnvPath, DefaultSwarmStackEnvTemplate()); err != nil {- return fmt.Errorf("write default swarm stack env template: %w", err)+ return errors.WrapIf(err, "write default swarm stack env template")}}// Write default env template if it doesn't existif _, err := os.Stat(envPath); os.IsNotExist(err) {if err := WriteTemplateFile(envPath, getDefaultEnvTemplate()); err != nil {- return fmt.Errorf("write default env template: %w", err)+ return errors.WrapIf(err, "write default env template")}}diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.goindex 537d20006..45d930292 100644--- a/backend/pkg/projects/fs_util.go+++ b/backend/pkg/projects/fs_util.go@@ -3,7 +3,6 @@ package projectsimport ("bytes""context"- "errors""fmt""log/slog""os"@@ -11,6 +10,8 @@ import ("slices""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/project"@@ -302,7 +303,7 @@ func DirectorySyncContentsChanged(projectPath string, syncFiles []SyncFile, oldS}return false, err} else if !info.IsDir() {- return false, fmt.Errorf("project path is not a directory: %s", projectPath)+ return false, errors.Errorf("project path is not a directory: %s", projectPath)}newFileSet := make(map[string]struct{}, len(syncFiles))@@ -601,7 +602,7 @@ func CreateUniqueDir(projectsRoot, basePath, name string, perm os.FileMode) (pat// Get absolute path of the true projects root for validationprojectsRootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return "", "", fmt.Errorf("failed to resolve projects root directory: %w", err)+ return "", "", errors.WrapIf(err, "failed to resolve projects root directory")}projectsRootAbs = filepath.Clean(projectsRootAbs)@@ -612,7 +613,7 @@ func CreateUniqueDir(projectsRoot, basePath, name string, perm os.FileMode) (pat// Validate candidate is within the allowed projects rootcandidateAbs, absErr := filepath.Abs(candidate)if absErr != nil {- return "", "", fmt.Errorf("failed to resolve candidate path: %w", absErr)+ return "", "", errors.WrapIf(absErr, "failed to resolve candidate path")}candidateAbs = filepath.Clean(candidateAbs)@@ -646,7 +647,7 @@ func CreateUniqueDir(projectsRoot, basePath, name string, perm os.FileMode) (pat// already exists. Callers that must not auto-rename (e.g. GitOps creates, which// must never mint "-N" duplicate projects on a broken binding) use this to fail// loudly instead of suffixing.-var ErrProjectDirExists = errors.New("project directory already exists")+const ErrProjectDirExists = errors.Sentinel("project directory already exists")// CreateExactDir creates basePath (the sanitized project directory) under// projectsRoot WITHOUT any "-N" collision suffixing. It returns ErrProjectDirExists@@ -661,13 +662,13 @@ func CreateExactDir(projectsRoot, basePath, name string, perm os.FileMode) (pathprojectsRootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return "", "", fmt.Errorf("failed to resolve projects root directory: %w", err)+ return "", "", errors.WrapIf(err, "failed to resolve projects root directory")}projectsRootAbs = filepath.Clean(projectsRootAbs)candidateAbs, err := filepath.Abs(basePath)if err != nil {- return "", "", fmt.Errorf("failed to resolve candidate path: %w", err)+ return "", "", errors.WrapIf(err, "failed to resolve candidate path")}candidateAbs = filepath.Clean(candidateAbs)diff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.goindex eacb4324b..57da95334 100644--- a/backend/pkg/projects/fs_writer.go+++ b/backend/pkg/projects/fs_writer.go@@ -1,7 +1,6 @@package projectsimport (- "errors""fmt""log/slog""os"@@ -10,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""go.getarcane.app/sys/atomic")@@ -55,14 +56,14 @@ func WriteComposeFile(projectsRoot, dirPath, content string) error {// Security: Validate dirPath is absolute and clean to prevent path traversalabsPath, err := filepath.Abs(dirPath)if err != nil {- return fmt.Errorf("failed to resolve directory path: %w", err)+ return errors.WrapIf(err, "failed to resolve directory path")}dirPath = filepath.Clean(absPath)// Security: Validate dirPath is within projectsRootrootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return fmt.Errorf("failed to resolve projects root: %w", err)+ return errors.WrapIf(err, "failed to resolve projects root")}rootAbs = filepath.Clean(rootAbs)@@ -71,7 +72,7 @@ func WriteComposeFile(projectsRoot, dirPath, content string) error {}if err := os.MkdirAll(dirPath, pkgutils.DirPerm); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}var composePath string@@ -82,7 +83,7 @@ func WriteComposeFile(projectsRoot, dirPath, content string) error {}if err := atomic.WriteFile(composePath, []byte(content), pkgutils.FilePerm); err != nil {- return fmt.Errorf("failed to write compose file: %w", err)+ return errors.WrapIf(err, "failed to write compose file")}return nil@@ -92,14 +93,14 @@ func WriteProjectFile(projectsRoot, dirPath, fileName, content string) error {// Security: Validate dirPath is absolute and clean to prevent path traversalabsPath, err := filepath.Abs(dirPath)if err != nil {- return fmt.Errorf("failed to resolve directory path: %w", err)+ return errors.WrapIf(err, "failed to resolve directory path")}dirPath = filepath.Clean(absPath)// Security: Validate dirPath is within projectsRootrootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return fmt.Errorf("failed to resolve projects root: %w", err)+ return errors.WrapIf(err, "failed to resolve projects root")}rootAbs = filepath.Clean(rootAbs)@@ -108,11 +109,11 @@ func WriteProjectFile(projectsRoot, dirPath, fileName, content string) error {}if err := os.MkdirAll(dirPath, pkgutils.DirPerm); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}if fileName == "" || filepath.Base(fileName) != fileName || strings.Contains(fileName, string(filepath.Separator)) {- return fmt.Errorf("invalid project file name %q", fileName)+ return errors.Errorf("invalid project file name %q", fileName)}targetPath := filepath.Join(dirPath, fileName)@@ -121,7 +122,7 @@ func WriteProjectFile(projectsRoot, dirPath, fileName, content string) error {if fileName == EffectiveEnvFileName {resolvedPath, resolvedPerm, isSymlink, resolveErr := resolveEnvFileWriteTargetInternal(targetPath)if resolveErr != nil {- return fmt.Errorf("failed to resolve project file %s write target: %w", fileName, resolveErr)+ return errors.WrapIff(resolveErr, "failed to resolve project file %s write target", fileName)}if isSymlink {writePath = resolvedPath@@ -134,11 +135,11 @@ func WriteProjectFile(projectsRoot, dirPath, fileName, content string) error {return nil}if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {- return fmt.Errorf("failed to read project file %s: %w", fileName, readErr)+ return errors.WrapIff(readErr, "failed to read project file %s", fileName)}if err := atomic.WriteFile(writePath, []byte(content), writePerm); err != nil {- return fmt.Errorf("failed to write project file %s: %w", fileName, err)+ return errors.WrapIff(err, "failed to write project file %s", fileName)}return nil@@ -150,7 +151,7 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm oif errors.Is(err, os.ErrNotExist) {return envPath, pkgutils.FilePerm, false, nil}- return "", 0, false, fmt.Errorf("inspect env file: %w", err)+ return "", 0, false, errors.WrapIf(err, "inspect env file")}if info.Mode()&os.ModeSymlink == 0 {return envPath, pkgutils.FilePerm, false, nil@@ -158,14 +159,14 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm oresolvedPath, err := filepath.EvalSymlinks(envPath)if err != nil {- return "", 0, false, fmt.Errorf("resolve env file symlink: %w", err)+ return "", 0, false, errors.WrapIf(err, "resolve env file symlink")}targetInfo, err := os.Stat(resolvedPath)if err != nil {- return "", 0, false, fmt.Errorf("inspect env file symlink target: %w", err)+ return "", 0, false, errors.WrapIf(err, "inspect env file symlink target")}if !targetInfo.Mode().IsRegular() {- return "", 0, false, fmt.Errorf("env file symlink target is not a regular file: %s", resolvedPath)+ return "", 0, false, errors.Errorf("env file symlink target is not a regular file: %s", resolvedPath)}return resolvedPath, targetInfo.Mode().Perm(), true, nil@@ -174,13 +175,13 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm ofunc RemoveProjectFile(projectsRoot, dirPath, fileName string) error {absPath, err := filepath.Abs(dirPath)if err != nil {- return fmt.Errorf("failed to resolve directory path: %w", err)+ return errors.WrapIf(err, "failed to resolve directory path")}dirPath = filepath.Clean(absPath)rootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return fmt.Errorf("failed to resolve projects root: %w", err)+ return errors.WrapIf(err, "failed to resolve projects root")}rootAbs = filepath.Clean(rootAbs)@@ -189,12 +190,12 @@ func RemoveProjectFile(projectsRoot, dirPath, fileName string) error {}if fileName == "" || filepath.Base(fileName) != fileName || strings.Contains(fileName, string(filepath.Separator)) {- return fmt.Errorf("invalid project file name %q", fileName)+ return errors.Errorf("invalid project file name %q", fileName)}targetPath := filepath.Join(dirPath, fileName)if err := os.Remove(targetPath); err != nil && !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("failed to remove project file %s: %w", fileName, err)+ return errors.WrapIff(err, "failed to remove project file %s", fileName)}return nil@@ -211,7 +212,7 @@ func EnsureEnvFile(projectsRoot, dirPath string) error {if _, err := os.Stat(envPath); err == nil {return nil} else if !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("failed to stat env file: %w", err)+ return errors.WrapIf(err, "failed to stat env file")}return WriteEnvFile(projectsRoot, dirPath, "")@@ -246,11 +247,11 @@ func WriteProjectFiles(projectsRoot, dirPath, composeContent string, envContentfunc WriteTemplateFile(filePath, content string) error {dir := filepath.Dir(filePath)if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil {- return fmt.Errorf("failed to create template directory: %w", err)+ return errors.WrapIf(err, "failed to create template directory")}if err := atomic.WriteFile(filePath, []byte(content), pkgutils.FilePerm); err != nil {- return fmt.Errorf("failed to write template file: %w", err)+ return errors.WrapIf(err, "failed to write template file")}return nil@@ -260,11 +261,11 @@ func WriteTemplateFile(filePath, content string) error {func WriteFileWithPerm(filePath, content string, perm os.FileMode) error {dir := filepath.Dir(filePath)if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}if err := atomic.WriteFile(filePath, []byte(content), perm); err != nil {- return fmt.Errorf("failed to write file: %w", err)+ return errors.WrapIf(err, "failed to write file")}return nil@@ -290,7 +291,7 @@ func RollbackRenamedProjectDirectory(oldPath, newPath string) (pathsMissing bool}case !oldExists && newExists:if err := os.Rename(newPath, oldPath); err != nil {- return false, fmt.Errorf("rollback project directory rename: %w", err)+ return false, errors.WrapIf(err, "rollback project directory rename")}case !oldExists && !newExists:pathsMissing = true@@ -308,14 +309,14 @@ func relocateRenameConflictDirectoryInternal(path string) (string, error) {if _, err := os.Stat(conflictPath); err == nil {continue} else if !os.IsNotExist(err) {- return "", fmt.Errorf("check conflict path: %w", err)+ return "", errors.WrapIf(err, "check conflict path")}if err := os.Rename(path, conflictPath); err != nil {- return "", fmt.Errorf("relocate project rename target path: %w", err)+ return "", errors.WrapIf(err, "relocate project rename target path")}return conflictPath, nil}- return "", fmt.Errorf("relocate project rename target path: no available conflict path for %s", path)+ return "", errors.Errorf("relocate project rename target path: no available conflict path for %s", path)}// SyncFile represents a file to be written during directory sync@@ -334,13 +335,13 @@ func WriteSyncedDirectory(projectsRoot, projectPath string, files []SyncFile) ([// Security: Validate projectPath is within projectsRootrootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return nil, fmt.Errorf("failed to resolve projects root: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve projects root")}rootAbs = filepath.Clean(rootAbs)projectAbs, err := filepath.Abs(projectPath)if err != nil {- return nil, fmt.Errorf("failed to resolve project path: %w", err)+ return nil, errors.WrapIf(err, "failed to resolve project path")}projectAbs = filepath.Clean(projectAbs)@@ -350,7 +351,7 @@ func WriteSyncedDirectory(projectsRoot, projectPath string, files []SyncFile) ([// Ensure project directory existsif err := os.MkdirAll(projectAbs, pkgutils.DirPerm); err != nil {- return nil, fmt.Errorf("failed to create project directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create project directory")}writtenPaths := make([]string, 0, len(files))@@ -361,22 +362,22 @@ func WriteSyncedDirectory(projectsRoot, projectPath string, files []SyncFile) ([targetPathClean := filepath.Clean(targetPath)if !IsSafeSubdirectory(projectAbs, targetPathClean) {- return nil, fmt.Errorf("file path %s would escape project directory", file.RelativePath)+ return nil, errors.Errorf("file path %s would escape project directory", file.RelativePath)}// Create parent directoriesparentDir := filepath.Dir(targetPathClean)if err := os.MkdirAll(parentDir, pkgutils.DirPerm); err != nil {- return nil, fmt.Errorf("failed to create directory for %s: %w", file.RelativePath, err)+ return nil, errors.WrapIff(err, "failed to create directory for %s", file.RelativePath)}info, err := os.Stat(targetPathClean)if err == nil && info.IsDir() {if err := os.RemoveAll(targetPathClean); err != nil {- return nil, fmt.Errorf("failed to replace directory at %s: %w", file.RelativePath, err)+ return nil, errors.WrapIff(err, "failed to replace directory at %s", file.RelativePath)}} else if err != nil && !os.IsNotExist(err) {- return nil, fmt.Errorf("failed to inspect target path for %s: %w", file.RelativePath, err)+ return nil, errors.WrapIff(err, "failed to inspect target path for %s", file.RelativePath)}// Write the file. Honor the source's executable bit so scripts arrive@@ -386,7 +387,7 @@ func WriteSyncedDirectory(projectsRoot, projectPath string, files []SyncFile) ([perm = 0o755}if err := atomic.WriteFile(targetPathClean, file.Content, perm); err != nil {- return nil, fmt.Errorf("failed to write file %s: %w", file.RelativePath, err)+ return nil, errors.WrapIff(err, "failed to write file %s", file.RelativePath)}writtenPaths = append(writtenPaths, file.RelativePath)@@ -403,13 +404,13 @@ func CleanupRemovedFiles(projectsRoot, projectPath string, oldFiles, newFiles []// Security: Validate projectPath is within projectsRootrootAbs, err := filepath.Abs(projectsRoot)if err != nil {- return fmt.Errorf("failed to resolve projects root: %w", err)+ return errors.WrapIf(err, "failed to resolve projects root")}rootAbs = filepath.Clean(rootAbs)projectAbs, err := filepath.Abs(projectPath)if err != nil {- return fmt.Errorf("failed to resolve project path: %w", err)+ return errors.WrapIf(err, "failed to resolve project path")}projectAbs = filepath.Clean(projectAbs)diff --git a/backend/pkg/projects/includes.go b/backend/pkg/projects/includes.goindex 298c0a368..4b69dbc0e 100644--- a/backend/pkg/projects/includes.go+++ b/backend/pkg/projects/includes.go@@ -2,12 +2,12 @@ package projectsimport ("context"- "errors"- "fmt""os""path/filepath""strings"+ "emperror.dev/errors"+pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo""go.yaml.in/yaml/v4"@@ -58,7 +58,7 @@ func (l *MissingIncludeStubLoader) Accept(path string) bool {func (l *MissingIncludeStubLoader) Load(_ context.Context, path string) (string, error) {validatedPath, ok := l.resolveMissingIncludeInternal(path).Get()if !ok {- return "", fmt.Errorf("include file is not eligible for validation stub: %s", path)+ return "", errors.Errorf("include file is not eligible for validation stub: %s", path)}if l.stubs == nil {@@ -71,7 +71,7 @@ func (l *MissingIncludeStubLoader) Load(_ context.Context, path string) (string,if l.tempDir == "" {tempDir, err := os.MkdirTemp("", "arcane-compose-include-*")if err != nil {- return "", fmt.Errorf("create validation include temp dir: %w", err)+ return "", errors.WrapIf(err, "create validation include temp dir")}l.tempDir = tempDir}@@ -82,10 +82,10 @@ func (l *MissingIncludeStubLoader) Load(_ context.Context, path string) (string,}stubPath := filepath.Join(l.tempDir, relPath)if err := os.MkdirAll(filepath.Dir(stubPath), 0o755); err != nil {- return "", fmt.Errorf("create validation include directory: %w", err)+ return "", errors.WrapIf(err, "create validation include directory")}if err := os.WriteFile(stubPath, []byte("services: {}\n"), 0o600); err != nil {- return "", fmt.Errorf("write validation include stub: %w", err)+ return "", errors.WrapIf(err, "write validation include stub")}l.stubs[validatedPath] = stubPath@@ -123,7 +123,7 @@ func (l *MissingIncludeStubLoader) Cleanup() {func ParseIncludes(composeFilePath string, envMap EnvMap, includeContent bool) ([]IncludeFile, error) {content, err := os.ReadFile(composeFilePath)if err != nil {- return nil, fmt.Errorf("failed to read compose file: %w", err)+ return nil, errors.WrapIf(err, "failed to read compose file")}return ParseIncludesFromContent(composeFilePath, content, envMap, includeContent)@@ -133,7 +133,7 @@ func ParseIncludes(composeFilePath string, envMap EnvMap, includeContent bool) (func ParseIncludesFromContent(composeFilePath string, content []byte, envMap EnvMap, includeContent bool) ([]IncludeFile, error) {var composeData map[string]anyif err := yaml.Unmarshal(content, &composeData); err != nil {- return nil, fmt.Errorf("failed to parse compose file: %w", err)+ return nil, errors.WrapIf(err, "failed to parse compose file")}// Look for include at root level only (per Docker Compose spec)@@ -208,13 +208,13 @@ func extractIncludePathsFromMapInternal(v map[string]any) ([]string, error) {for _, entry := range p {s, ok := entry.(string)if !ok {- return nil, fmt.Errorf("invalid include path entry: expected string, got %T", entry)+ return nil, errors.Errorf("invalid include path entry: expected string, got %T", entry)}paths = append(paths, s)}return paths, nildefault:- return nil, fmt.Errorf("invalid include path type: %T", v["path"])+ return nil, errors.Errorf("invalid include path type: %T", v["path"])}}@@ -269,7 +269,7 @@ func readIncludeContentInternal(fullPath, includePath string, includeContent boo// File doesn't exist yet - return empty content so it can be createdreturn "# This file will be created when you save changes\nservices:\n", nil}- return "", fmt.Errorf("failed to read include file %s: %w", includePath, err)+ return "", errors.WrapIff(err, "failed to read include file %s", includePath)}// ValidateIncludePathForWrite ensures the include path is safe for write operations@@ -283,7 +283,7 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)// Resolve project directory to absolute path and evaluate symlinksabsProjectDir, err := filepath.Abs(projectDir)if err != nil {- return "", fmt.Errorf("invalid project directory: %w", err)+ return "", errors.WrapIf(err, "invalid project directory")}absProjectDir = filepath.Clean(absProjectDir)@@ -300,7 +300,7 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)absFullPath, err := filepath.Abs(fullPath)if err != nil {- return "", fmt.Errorf("invalid include path: %w", err)+ return "", errors.WrapIf(err, "invalid include path")}absFullPath = filepath.Clean(absFullPath)@@ -309,14 +309,14 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)if evalFullPath, err := filepath.EvalSymlinks(absFullPath); err == nil {evalPath = evalFullPath} else if !errors.Is(err, os.ErrNotExist) {- return "", fmt.Errorf("failed to resolve include path: %w", err)+ return "", errors.WrapIf(err, "failed to resolve include path")} else {// File doesn't exist yet - evaluate parent directory symlinksdir := filepath.Dir(absFullPath)if evalDir, err := filepath.EvalSymlinks(dir); err == nil {evalPath = filepath.Join(evalDir, filepath.Base(absFullPath))} else if !errors.Is(err, os.ErrNotExist) {- return "", fmt.Errorf("failed to resolve parent directory: %w", err)+ return "", errors.WrapIf(err, "failed to resolve parent directory")}}@@ -346,18 +346,18 @@ func WriteIncludeFile(projectDir, includePath, content string) error {dir := filepath.Dir(validatedPath)if dir == "" || dir == "." {- return fmt.Errorf("invalid include path: cannot create directory '%s'", dir)+ return errors.Errorf("invalid include path: cannot create directory '%s'", dir)}// Only create directory if it doesn't existif _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil {- return fmt.Errorf("failed to create directory: %w", err)+ return errors.WrapIf(err, "failed to create directory")}}if err := os.WriteFile(validatedPath, []byte(content), pkgutils.FilePerm); err != nil {- return fmt.Errorf("failed to write include file: %w", err)+ return errors.WrapIf(err, "failed to write include file")}return nildiff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.goindex 74b36a65f..e31628896 100644--- a/backend/pkg/projects/load.go+++ b/backend/pkg/projects/load.go@@ -2,8 +2,6 @@ package projectsimport ("context"- "errors"- "fmt""log/slog""maps""math"@@ -13,6 +11,9 @@ import ("strconv""strings"+ "emperror.dev/emperror"+ "emperror.dev/errors"+interp "github.com/compose-spec/compose-go/v2/interpolation""github.com/compose-spec/compose-go/v2/loader""github.com/compose-spec/compose-go/v2/template"@@ -125,17 +126,20 @@ func DetectComposeFile(dir string) (string, error) {case len(dirMatchedCandidates) == 1:return dirMatchedCandidates[0], nilcase len(dirMatchedCandidates) > 1:- return "", &common.AmbiguousComposeFileError{Dir: dir}+ return "", errors.Errorf("multiple custom compose files found in %q", dir)+case len(composeNamedCandidates) == 1:return composeNamedCandidates[0], nilcase len(composeNamedCandidates) > 1:- return "", &common.AmbiguousComposeFileError{Dir: dir}+ return "", errors.Errorf("multiple custom compose files found in %q", dir)+case len(customCandidates) == 1:return customCandidates[0], nilcase len(customCandidates) > 1:- return "", &common.AmbiguousComposeFileError{Dir: dir}+ return "", errors.Errorf("multiple custom compose files found in %q", dir)+default:- return "", &common.ComposeFileNotFoundError{Dir: dir}+ return "", common.Classify(common.ErrComposeFileNotFound, errors.Errorf("no compose file found in %q", dir))}}@@ -205,7 +209,7 @@ func lenientCastSizeInternal(value string) (any, error) {n = b}if n > math.MaxInt || n < math.MinInt {- return nil, fmt.Errorf("size %d out of range for platform int", n)+ return nil, errors.Errorf("size %d out of range for platform int", n)}return int(n), nil}@@ -270,13 +274,13 @@ func loadComposeProjectInternal(lenient bool,) (project *composetypes.Project, err error) {defer func() {- if recovered := recover(); recovered != nil {+ if panicErr := emperror.Recover(recover()); panicErr != nil {slog.WarnContext(ctx,"panic while loading compose project; compose file may contain invalid syntax","path", composeFile,- "error", recovered,+ "error", panicErr,)- err = fmt.Errorf("load compose project panic for %s: %v", composeFile, recovered)+ err = errors.WrapIff(panicErr, "load compose project panic for %s", composeFile)project = nil}}()@@ -340,7 +344,7 @@ func loadComposeProjectInternal(}})if err != nil {- return nil, fmt.Errorf("load compose project: %w", err)+ return nil, errors.WrapIf(err, "load compose project")}for _, configFile := range cfg.ConfigFiles {@@ -355,7 +359,7 @@ func loadComposeProjectInternal(// Translate container paths to host paths for Docker executionif pathMapper != nil {if err := pathMapper.TranslateVolumeSources(project); err != nil {- return nil, fmt.Errorf("failed to translate paths for docker host: %w", err)+ return nil, errors.WrapIf(err, "failed to translate paths for docker host")}}diff --git a/backend/pkg/projects/path_mapper.go b/backend/pkg/projects/path_mapper.goindex 506735884..da65d89d0 100644--- a/backend/pkg/projects/path_mapper.go+++ b/backend/pkg/projects/path_mapper.go@@ -1,10 +1,10 @@package projectsimport (- "fmt""path/filepath""strings"+ "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/samber/mo")@@ -125,7 +125,7 @@ func (pm *PathMapper) ContainerToHost(containerPath string) (string, error) {// Calculate relative pathrelPath, err := filepath.Rel(pm.containerPrefix, cleaned)if err != nil {- return "", fmt.Errorf("failed to calculate relative path: %w", err)+ return "", errors.WrapIf(err, "failed to calculate relative path")}// Only translate paths within container prefix@@ -164,7 +164,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project) errohostPath, err := pm.ContainerToHost(volume.Source)if err != nil {- return fmt.Errorf("failed to translate volume source %q: %w", volume.Source, err)+ return errors.WrapIff(err, "failed to translate volume source %q", volume.Source)}volume.Source = hostPath@@ -178,7 +178,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project) erroif secret.File != "" {hostPath, err := pm.ContainerToHost(secret.File)if err != nil {- return fmt.Errorf("failed to translate secret file %q: %w", secret.File, err)+ return errors.WrapIff(err, "failed to translate secret file %q", secret.File)}secret.File = hostPathproject.Secrets[name] = secret@@ -190,7 +190,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project) erroif config.File != "" {hostPath, err := pm.ContainerToHost(config.File)if err != nil {- return fmt.Errorf("failed to translate config file %q: %w", config.File, err)+ return errors.WrapIff(err, "failed to translate config file %q", config.File)}config.File = hostPathproject.Configs[name] = configdiff --git a/backend/pkg/projects/project_files.go b/backend/pkg/projects/project_files.goindex 911379637..c43bfe8d3 100644--- a/backend/pkg/projects/project_files.go+++ b/backend/pkg/projects/project_files.go@@ -3,8 +3,6 @@ package projectsimport ("crypto/sha256""encoding/hex"- "errors"- "fmt""hash""io""io/fs"@@ -16,6 +14,8 @@ import ("strings""unicode/utf8"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/config"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/project"@@ -30,11 +30,11 @@ const (DefaultProjectFileTreeMaxEntries = 2000)-var (- ErrProjectFileRevisionConflict = errors.New("project file tree changed; refresh the project and try again")- ErrProjectFileOutsideProjectDirectory = errors.New("path is outside project directory")- ErrProjectFileProtectedPath = errors.New("protected project file cannot be modified")- ErrProjectFileSymlinkPath = errors.New("symlink project paths are not supported")+const (+ ErrProjectFileRevisionConflict = errors.Sentinel("project file tree changed; refresh the project and try again")+ ErrProjectFileOutsideProjectDirectory = errors.Sentinel("path is outside project directory")+ ErrProjectFileProtectedPath = errors.Sentinel("protected project file cannot be modified")+ ErrProjectFileSymlinkPath = errors.Sentinel("symlink project paths are not supported"))type ProjectFileApplyOptions struct {@@ -55,13 +55,13 @@ func ReadProjectFileTree(projectPath string, maxDepth int, skipDirectories, compprojectAbs, err := filepath.Abs(projectPath)if err != nil {- return nil, "", false, fmt.Errorf("resolve project path: %w", err)+ return nil, "", false, errors.WrapIf(err, "resolve project path")}projectAbs = filepath.Clean(projectAbs)root, err := os.OpenRoot(projectAbs)if err != nil {- return nil, "", false, fmt.Errorf("open project directory: %w", err)+ return nil, "", false, errors.WrapIf(err, "open project directory")}defer func() { _ = root.Close() }()@@ -137,7 +137,7 @@ func (w *projectFileTreeWalkerInternal) visit(rel string, entry fs.DirEntry, walinfo, err := entry.Info()if err != nil {- return fmt.Errorf("inspect project file: %w", err)+ return errors.WrapIf(err, "inspect project file")}// fs.WalkDir visits entries in deterministic lexical order, so hashing@@ -200,7 +200,7 @@ func ApplyProjectFileChanges(projectPath string, changes []project.ProjectFileChif opts.ExpectedRevision != "" {_, currentRevision, _, err := ReadProjectFileTree(projectPath, opts.MaxDepth, opts.SkipDirectories, opts.ComposeFileName, opts.MaxEntries)if err != nil {- return fmt.Errorf("read project file tree revision: %w", err)+ return errors.WrapIf(err, "read project file tree revision")}if currentRevision != opts.ExpectedRevision {return ErrProjectFileRevisionConflict@@ -209,7 +209,7 @@ func ApplyProjectFileChanges(projectPath string, changes []project.ProjectFileChroot, err := os.OpenRoot(projectPath)if err != nil {- return fmt.Errorf("open project directory: %w", err)+ return errors.WrapIf(err, "open project directory")}defer func() { _ = root.Close() }()@@ -292,7 +292,7 @@ func ValidateProjectFileName(name string) (string, error) {func applyProjectFileChangeInternal(root *os.Root, protected map[string]bool, change project.ProjectFileChange) error {rel, err := NormalizeProjectRelativePath(change.RelativePath)if err != nil {- return fmt.Errorf("invalid project file path: %w", err)+ return errors.WrapIf(err, "invalid project file path")}switch change.Operation {@@ -311,7 +311,7 @@ func applyProjectFileChangeInternal(root *os.Root, protected map[string]bool, chcase project.FileOpRename:newName, err := ValidateProjectFileName(change.NewName)if err != nil {- return fmt.Errorf("invalid project file name: %w", err)+ return errors.WrapIf(err, "invalid project file name")}return renameManagedProjectPathInternal(root, protected, rel, newName)case project.FileOpMove:@@ -319,7 +319,7 @@ func applyProjectFileChangeInternal(root *os.Root, protected map[string]bool, chcase project.FileOpDelete:return deleteManagedProjectPathInternal(root, protected, rel, change.Recursive)default:- return fmt.Errorf("unsupported project file operation %q", change.Operation)+ return errors.Errorf("unsupported project file operation %q", change.Operation)}}@@ -343,7 +343,7 @@ func createManagedProjectFileInternal(root *os.Root, protected map[string]bool,f, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, pkgutils.FilePerm)if err != nil {if errors.Is(err, os.ErrExist) {- return fmt.Errorf("project file already exists: %s", rel)+ return errors.Errorf("project file already exists: %s", rel)}return mapProjectRootErrorInternal("create project file", err)}@@ -352,7 +352,7 @@ func createManagedProjectFileInternal(root *os.Root, protected map[string]bool,writeErr = closeErr}if writeErr != nil {- return fmt.Errorf("create project file: %w", writeErr)+ return errors.WrapIf(writeErr, "create project file")}return nil}@@ -366,7 +366,7 @@ func createManagedProjectFolderInternal(root *os.Root, protected map[string]bool}if _, err := root.Lstat(rel); err == nil {- return fmt.Errorf("project folder already exists: %s", rel)+ return errors.Errorf("project folder already exists: %s", rel)} else if !errors.Is(err, os.ErrNotExist) {return mapProjectRootErrorInternal("inspect project folder", err)}@@ -390,15 +390,15 @@ func updateManagedProjectFileInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("project file not found: %s", rel)+ return errors.Errorf("project file not found: %s", rel)}return mapProjectRootErrorInternal("inspect project file", err)}if info.IsDir() {- return fmt.Errorf("path is a folder: %s", rel)+ return errors.Errorf("path is a folder: %s", rel)}if info.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink files are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink files are not supported")}if err := root.WriteFile(rel, []byte(content), pkgutils.FilePerm); err != nil {@@ -418,12 +418,12 @@ func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("project path not found: %s", rel)+ return errors.Errorf("project path not found: %s", rel)}return mapProjectRootErrorInternal("inspect project path", err)}if info.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")}targetRel := path.Join(path.Dir(rel), newName)@@ -434,7 +434,7 @@ func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool,return err}if _, err := root.Lstat(targetRel); err == nil {- return fmt.Errorf("project path already exists: %s", targetRel)+ return errors.Errorf("project path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {return mapProjectRootErrorInternal("inspect project path", err)}@@ -462,7 +462,7 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, reparentRel, err := normalizeOptionalProjectParentPathInternal(newParentPath)if err != nil {- return fmt.Errorf("invalid project parent path: %w", err)+ return errors.WrapIf(err, "invalid project parent path")}if parentRel != "" {if err := ensureWritableProjectRelPathInternal(protected, parentRel); err != nil {@@ -473,12 +473,12 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, resourceInfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("project path not found: %s", rel)+ return errors.Errorf("project path not found: %s", rel)}return mapProjectRootErrorInternal("inspect project path", err)}if sourceInfo.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")}if sourceInfo.IsDir() && parentRel != "" && projectFilePathMatchesInternal(parentRel, rel) {return errors.New("folder cannot be moved into itself or a descendant")@@ -502,7 +502,7 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, rereturn err}if _, err := root.Lstat(targetRel); err == nil {- return fmt.Errorf("project path already exists: %s", targetRel)+ return errors.Errorf("project path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {return mapProjectRootErrorInternal("inspect project path", err)}@@ -524,15 +524,15 @@ func validateProjectMoveParentInternal(root *os.Root, parentRel string) error {parentInfo, err := root.Lstat(parentRel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("destination folder not found: %s", parentRel)+ return errors.Errorf("destination folder not found: %s", parentRel)}return mapProjectRootErrorInternal("inspect destination folder", err)}if parentInfo.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink destination folders are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink destination folders are not supported")}if !parentInfo.IsDir() {- return fmt.Errorf("destination path is not a folder: %s", parentRel)+ return errors.Errorf("destination path is not a folder: %s", parentRel)}return nil}@@ -548,12 +548,12 @@ func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("project path not found: %s", rel)+ return errors.Errorf("project path not found: %s", rel)}return mapProjectRootErrorInternal("inspect project path", err)}if info.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")}if info.IsDir() && !recursive {empty, err := isDirectoryEmptyInternal(root, rel)@@ -578,7 +578,7 @@ func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool,}func mapProjectRootErrorInternal(action string, err error) error {- return fmt.Errorf("%s: %w", action, err)+ return errors.WrapIff(err, "%s", action)}func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {@@ -603,7 +603,7 @@ func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {return mapProjectRootErrorInternal("inspect project path", err)}if info.Mode()&os.ModeSymlink != 0 {- return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)+ return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")}}return nil@@ -615,7 +615,7 @@ func ensureWritableProjectRelPathInternal(protected map[string]bool, rel string)}rootName, _, _ := strings.Cut(rel, "/")if protected[rel] || protected[rootName] {- return fmt.Errorf("%w: %s", ErrProjectFileProtectedPath, rel)+ return errors.WrapIff(ErrProjectFileProtectedPath, "%s", rel)}return nil}@@ -626,7 +626,7 @@ func projectFilePathMatchesInternal(relativePath string, rootPath string) bool {func validateProjectTextContentInternal(content string) error {if len(content) > MaxManagedProjectFileBytes {- return fmt.Errorf("file exceeds %d byte limit", MaxManagedProjectFileBytes)+ return errors.Errorf("file exceeds %d byte limit", MaxManagedProjectFileBytes)}if !utf8.ValidString(content) || strings.IndexByte(content, 0) >= 0 {return errors.New("binary files are not supported")@@ -637,7 +637,7 @@ func validateProjectTextContentInternal(content string) error {func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {f, err := root.Open(rel)if err != nil {- return false, fmt.Errorf("open folder: %w", err)+ return false, errors.WrapIf(err, "open folder")}defer func() { _ = f.Close() }()@@ -646,7 +646,7 @@ func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {return true, nil}if err != nil {- return false, fmt.Errorf("read folder: %w", err)+ return false, errors.WrapIf(err, "read folder")}return false, nil}diff --git a/backend/pkg/remenv/client.go b/backend/pkg/remenv/client.goindex cff55901d..ef4550904 100644--- a/backend/pkg/remenv/client.go+++ b/backend/pkg/remenv/client.go@@ -4,13 +4,14 @@ import ("bytes""context"json "encoding/json/v2"- "errors""fmt""io""maps""net/http""strings""time"++ "emperror.dev/errors")const (@@ -147,7 +148,7 @@ func (c *Client) doDirectHTTPInternal(ctx context.Context, req Request) (*ResponhttpReq, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bodyReader)if err != nil {- return nil, &TransportError{Err: fmt.Errorf("failed to create request: %w", err)}+ return nil, &TransportError{Err: errors.WrapIf(err, "failed to create request")}}for key, value := range req.Headers {@@ -162,7 +163,7 @@ func (c *Client) doDirectHTTPInternal(ctx context.Context, req Request) (*ResponrespBody, err := io.ReadAll(resp.Body)if err != nil {- return nil, &TransportError{Err: fmt.Errorf("failed to read response body: %w", err)}+ return nil, &TransportError{Err: errors.WrapIf(err, "failed to read response body")}}return &Response{diff --git a/backend/pkg/scheduler/analytics_job.go b/backend/pkg/scheduler/analytics_job.goindex 86359b9c3..bb069c595 100644--- a/backend/pkg/scheduler/analytics_job.go+++ b/backend/pkg/scheduler/analytics_job.go@@ -4,8 +4,6 @@ import ("bytes""context"json "encoding/json/v2"- "errors"- "fmt""io""log/slog""net/http"@@ -13,6 +11,8 @@ import ("sync""time"+ "emperror.dev/errors"+"github.com/cenkalti/backoff/v5""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -130,13 +130,13 @@ func (j *AnalyticsJob) Run(ctx context.Context) {req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, j.heartbeatURL, bytes.NewReader(body))if err != nil {- return struct{}{}, fmt.Errorf("failed to create request: %w", err)+ return struct{}{}, errors.WrapIf(err, "failed to create request")}req.Header.Set("Content-Type", "application/json")resp, err := j.httpClient.Do(req)if err != nil {- return struct{}{}, fmt.Errorf("failed to send request: %w", err)+ return struct{}{}, errors.WrapIf(err, "failed to send request")}defer func() { _ = resp.Body.Close() }()@@ -157,7 +157,7 @@ func (j *AnalyticsJob) Run(ctx context.Context) {if bodyText != "" {details = append(details, "response="+bodyText)}- return struct{}{}, fmt.Errorf("analytics heartbeat request failed: %s", strings.Join(details, "; "))+ return struct{}{}, errors.Errorf("analytics heartbeat request failed: %s", strings.Join(details, "; "))}return struct{}{}, nil},@@ -203,7 +203,7 @@ func (j *AnalyticsJob) claimHeartbeatAttemptWindowInternal(ctx context.Context)now := j.now().UTC()rawLastAttemptAt, ok, err := j.kvService.Get(ctx, analyticsHeartbeatLastAttemptKey)if err != nil {- return false, fmt.Errorf("failed to load analytics heartbeat attempt state: %w", err)+ return false, errors.WrapIf(err, "failed to load analytics heartbeat attempt state")}if ok {@@ -241,7 +241,7 @@ func (j *AnalyticsJob) claimHeartbeatAttemptWindowInternal(ctx context.Context)// best-effort at-most-once-per-24h check-ins, which avoids duplicate heartbeats// after restarts or partially completed outbound requests.if err := j.kvService.Set(ctx, analyticsHeartbeatLastAttemptKey, now.Format(time.RFC3339Nano)); err != nil {- return false, fmt.Errorf("failed to persist analytics heartbeat attempt state: %w", err)+ return false, errors.WrapIf(err, "failed to persist analytics heartbeat attempt state")}return true, nildiff --git a/backend/pkg/scheduler/image_update_watcher.go b/backend/pkg/scheduler/image_update_watcher.goindex 4221e4080..d677af00b 100644--- a/backend/pkg/scheduler/image_update_watcher.go+++ b/backend/pkg/scheduler/image_update_watcher.go@@ -2,13 +2,13 @@ package schedulerimport ("context"- "errors"- "fmt""log/slog""sync""sync/atomic""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -186,7 +186,7 @@ func (w *ImageUpdateWatcher) RunNow(ctx context.Context) error {run := &imageUpdateScanRunInternal{done: make(chan struct{})}for !w.activeRun.CompareAndSwap(nil, run) {if w.activeRun.Load() != nil {- return &common.ImageScanInProgressError{}+ return common.Classify(common.ErrImageScanInProgress, errors.New("an image update check is already in progress"))}// Lost the CAS to a run that has since been released; retry.}@@ -213,7 +213,7 @@ func (w *ImageUpdateWatcher) RunNow(ctx context.Context) error {results, err := w.imageUpdateService.CheckAllImages(ctx, 0, creds)if err != nil {- return fmt.Errorf("image scan failed: %w", err)+ return errors.WrapIf(err, "image scan failed")}total := len(results)@@ -282,8 +282,7 @@ func (w *ImageUpdateWatcher) runTriggeredScansInternal(ctx context.Context) {return}err := w.RunNow(ctx)- var inProgress *common.ImageScanInProgressError- if errors.As(err, &inProgress) {+ if errors.Is(err, common.ErrImageScanInProgress) {// A manual scan holds the gate; wait it out and re-queue the// trigger so this scan attempt is not lost.if !w.waitForActiveScanInternal(ctx) {diff --git a/backend/pkg/scheduler/image_update_watcher_test.go b/backend/pkg/scheduler/image_update_watcher_test.goindex 06b9430f5..b6cba9172 100644--- a/backend/pkg/scheduler/image_update_watcher_test.go+++ b/backend/pkg/scheduler/image_update_watcher_test.go@@ -303,8 +303,7 @@ func TestImageUpdateWatcher_RunNowReturnsInProgressErrorDuringActiveScan(t *testgo func() { firstErrCh <- watcher.RunNow(context.Background()) }()require.Equal(t, 1, <-scanner.startedCh)- var inProgress *common.ImageScanInProgressError- require.ErrorAs(t, watcher.RunNow(context.Background()), &inProgress)+ require.ErrorIs(t, watcher.RunNow(context.Background()), common.ErrImageScanInProgress)require.Equal(t, 1, scanner.countInternal())close(releaseCh)diff --git a/backend/pkg/scheduler/scheduler.go b/backend/pkg/scheduler/scheduler.goindex 8e829cb65..b71f654a1 100644--- a/backend/pkg/scheduler/scheduler.go+++ b/backend/pkg/scheduler/scheduler.go@@ -2,11 +2,11 @@ package schedulerimport ("context"- "fmt""log/slog""sync""time"+ "emperror.dev/errors"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/robfig/cron/v3""github.com/samber/mo"@@ -90,7 +90,7 @@ func (js *JobScheduler) RunBusWatcherNow(ctx context.Context, watcherID string)watcher, ok := js.watchers[watcherID]js.mu.Unlock()if !ok {- return fmt.Errorf("bus watcher %s is not manually runnable", watcherID)+ return errors.Errorf("bus watcher %s is not manually runnable", watcherID)}return watcher.RunNow(ctx)diff --git a/backend/pkg/utils/dbutil/dbutil.go b/backend/pkg/utils/dbutil/dbutil.goindex 543aa8175..770d5bf8e 100644--- a/backend/pkg/utils/dbutil/dbutil.go+++ b/backend/pkg/utils/dbutil/dbutil.go@@ -4,8 +4,8 @@ package dbutilimport ("context"- "errors"- "fmt"++ "emperror.dev/errors""gorm.io/gorm")@@ -23,7 +23,7 @@ func FirstWhere[T any](ctx context.Context, db *gorm.DB, notFound error, where sif errors.Is(err, gorm.ErrRecordNotFound) && notFound != nil {return nil, notFound}- return nil, fmt.Errorf("failed to query %T: %w", out, err)+ return nil, errors.WrapIff(err, "failed to query %T", out)}return &out, nil}diff --git a/backend/pkg/utils/httpx/outbound_url.go b/backend/pkg/utils/httpx/outbound_url.goindex 654bb5185..1b0ad6452 100644--- a/backend/pkg/utils/httpx/outbound_url.go+++ b/backend/pkg/utils/httpx/outbound_url.go@@ -1,10 +1,10 @@package httpximport (- "errors"- "fmt""net/url""strings"++ "emperror.dev/errors")// ValidateOutboundHTTPURL parses and validates an outbound HTTP(S) target URL.@@ -19,12 +19,12 @@ func ValidateOutboundHTTPURL(rawURL string) (*url.URL, error) {parsed, err := url.Parse(trimmed)if err != nil {- return nil, fmt.Errorf("failed to parse URL: %w", err)+ return nil, errors.WrapIf(err, "failed to parse URL")}scheme := strings.ToLower(parsed.Scheme)if scheme != "http" && scheme != "https" {- return nil, fmt.Errorf("unsupported scheme %q", parsed.Scheme)+ return nil, errors.Errorf("unsupported scheme %q", parsed.Scheme)}if parsed.User != nil {diff --git a/backend/pkg/utils/httpx/request.go b/backend/pkg/utils/httpx/request.goindex 0404a589c..2e8883432 100644--- a/backend/pkg/utils/httpx/request.go+++ b/backend/pkg/utils/httpx/request.go@@ -6,6 +6,8 @@ import ("net/url""strconv""strings"++ "emperror.dev/errors")type HeaderSetter interface {@@ -79,7 +81,7 @@ func GetQueryParam(r *http.Request, name string, required bool) (string, error)q := r.URL.Query()if !q.Has(name) || q.Get(name) == "" {if required {- return "", fmt.Errorf("missing query parameter %s", name)+ return "", errors.Errorf("missing query parameter %s", name)}return "", nil}@@ -92,13 +94,13 @@ func GetIntQueryParam(r *http.Request, name string, required bool) (int, error)q := r.URL.Query()if !q.Has(name) || q.Get(name) == "" {if required {- return 0, fmt.Errorf("missing numeric query parameter %s", name)+ return 0, errors.Errorf("missing numeric query parameter %s", name)}return 0, nil}n, err := strconv.Atoi(q.Get(name))if err != nil {- return 0, fmt.Errorf("invalid numeric query parameter %s: %w", name, err)+ return 0, errors.WrapIff(err, "invalid numeric query parameter %s", name)}return n, nil}diff --git a/backend/pkg/utils/httpx/safe_remote.go b/backend/pkg/utils/httpx/safe_remote.goindex 3b44df04f..fb5226f6f 100644--- a/backend/pkg/utils/httpx/safe_remote.go+++ b/backend/pkg/utils/httpx/safe_remote.go@@ -2,8 +2,6 @@ package httpximport ("context"- "errors"- "fmt""net""net/http""net/netip"@@ -11,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/common")@@ -53,21 +53,21 @@ func ValidateSafeRemoteURL(ctx context.Context, rawURL string, lookupIP LookupIPparsed, err := url.Parse(rawURL)if err != nil {- return nil, &common.UnsafeRemoteURLError{Err: err}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))}scheme := strings.ToLower(parsed.Scheme)if scheme != "http" && scheme != "https" {- return nil, &common.UnsafeRemoteURLError{Err: fmt.Errorf("scheme %q is not allowed", parsed.Scheme)}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("unsupported URL scheme %q", scheme), "Remote URL is not allowed"))}if parsed.User != nil {- return nil, &common.UnsafeRemoteURLError{Err: errors.New("embedded credentials are not allowed")}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("URL credentials are not allowed"), "Remote URL is not allowed"))}host := parsed.Hostname()if host == "" || isBlockedHostnameInternal(host) {- return nil, &common.UnsafeRemoteURLError{Err: fmt.Errorf("host %q is not allowed", host)}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("missing or blocked hostname"), "Remote URL is not allowed"))}ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)@@ -75,7 +75,7 @@ func ValidateSafeRemoteURL(ctx context.Context, rawURL string, lookupIP LookupIPif err == nil {err = errors.New("host did not resolve to an allowed IP")}- return nil, &common.UnsafeRemoteURLError{Err: err}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))}return parsed, nil@@ -106,7 +106,7 @@ func NewSafeOutboundHTTPClient(base *http.Client, lookupIP LookupIPFunc) (*http.transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {host, port, err := net.SplitHostPort(address)if err != nil {- return nil, &common.UnsafeRemoteURLError{Err: err}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))}ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)@@ -152,20 +152,20 @@ func cloneHTTPTransportInternal(base http.RoundTripper) (*http.Transport, error)case nil:defaultTransport, ok := http.DefaultTransport.(*http.Transport)if !ok {- return nil, &common.DefaultTransportTypeError{}+ return nil, errors.New("http.DefaultTransport is not *http.Transport")}return defaultTransport.Clone(), nilcase *http.Transport:return t.Clone(), nildefault:- return nil, fmt.Errorf("unsupported HTTP transport type %T", base)+ return nil, errors.Errorf("unsupported HTTP transport type %T", base)}}func resolveAllowedIPsInternal(ctx context.Context, host string, lookupIP LookupIPFunc) ([]net.IP, error) {if parsedIP := parseIPLiteralInternal(host); parsedIP != nil {if isBlockedIPInternal(parsedIP) {- return nil, &common.UnsafeRemoteURLError{Err: fmt.Errorf("IP %s is not allowed", parsedIP.String())}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("blocked IP address %s", parsedIP), "Remote URL is not allowed"))}return []net.IP{parsedIP}, nil}@@ -181,13 +181,13 @@ func resolveAllowedIPsInternal(ctx context.Context, host string, lookupIP Lookupcontinue}if isBlockedIPInternal(ip) {- return nil, &common.UnsafeRemoteURLError{Err: fmt.Errorf("IP %s is not allowed", ip.String())}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("blocked IP address %s", ip), "Remote URL is not allowed"))}allowed = append(allowed, ip)}if len(allowed) == 0 {- return nil, &common.UnsafeRemoteURLError{Err: errors.New("host did not resolve to an allowed IP")}+ return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("host did not resolve to an allowed IP"), "Remote URL is not allowed"))}return allowed, nildiff --git a/backend/pkg/utils/httpx/safe_remote_test.go b/backend/pkg/utils/httpx/safe_remote_test.goindex 3e034d385..3e3d3802c 100644--- a/backend/pkg/utils/httpx/safe_remote_test.go+++ b/backend/pkg/utils/httpx/safe_remote_test.go@@ -47,8 +47,7 @@ func TestValidateSafeRemoteURL(t *testing.T) {parsed, err := ValidateSafeRemoteURL(context.Background(), tt.rawURL, lookupIP)if tt.wantErr {require.Error(t, err)- var unsafeErr *common.UnsafeRemoteURLError- require.ErrorAs(t, err, &unsafeErr)+ require.ErrorIs(t, err, common.ErrUnsafeRemoteURL)require.Nil(t, parsed)return}@@ -75,8 +74,7 @@ func TestNewSafeOutboundHTTPClient_BlocksUnsafeRedirectTarget(t *testing.T) {_, err = client.Get("http://registry.example.com/redirect")require.Error(t, err)- var unsafeErr *common.UnsafeRemoteURLError- require.ErrorAs(t, err, &unsafeErr)+ require.ErrorIs(t, err, common.ErrUnsafeRemoteURL)}func newRedirectTestClient(listenerAddr string) *http.Client {diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.goindex 29232c598..f91c475e7 100644--- a/backend/pkg/utils/jwtclaims/jwt.go+++ b/backend/pkg/utils/jwtclaims/jwt.go@@ -4,10 +4,11 @@ import ("crypto/rand""encoding/base64"json "encoding/json/v2"- "errors""fmt""strings"+ "emperror.dev/errors"+"github.com/samber/mo""github.com/samber/mo/result")@@ -121,7 +122,7 @@ func CheckOrGenerateJwtSecret(jwtSecret string, requireExplicit bool) []byte {if isDefault {secretBytes := make([]byte, 32)if _, err := rand.Read(secretBytes); err != nil {- panic(fmt.Errorf("failed to generate random JWT secret: %w", err))+ panic(errors.WrapIf(err, "failed to generate random JWT secret"))}return secretBytes}diff --git a/backend/pkg/utils/mapper/mapper.go b/backend/pkg/utils/mapper/mapper.goindex 99cd0636c..18906ead0 100644--- a/backend/pkg/utils/mapper/mapper.go+++ b/backend/pkg/utils/mapper/mapper.go@@ -1,8 +1,7 @@package mapperimport (- "fmt"-+ "emperror.dev/errors""github.com/jinzhu/copier")@@ -10,7 +9,7 @@ func MapSlice[S any, D any](source []S) ([]D, error) {dest := make([]D, len(source))for i := range source {if err := MapStruct(source[i], &dest[i]); err != nil {- return nil, fmt.Errorf("failed to map field %d: %w", i, err)+ return nil, errors.WrapIff(err, "failed to map field %d", i)}}return dest, nil@@ -37,7 +36,7 @@ func MapStructList[S any, D any](source []S, destination *[]D) (err error) {for i, item := range source {err = MapStruct(item, &((*destination)[i]))if err != nil {- return fmt.Errorf("failed to map field %d: %w", i, err)+ return errors.WrapIff(err, "failed to map field %d", i)}}return nildiff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.goindex 4cc68d3cc..df6a7f717 100644--- a/backend/pkg/utils/notifications/config_credentials.go+++ b/backend/pkg/utils/notifications/config_credentials.go@@ -3,10 +3,10 @@ package notificationsimport ("encoding/base64"json "encoding/json/v2"- "errors"- "fmt""log/slog"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""go.getarcane.app/sys/crypto")@@ -16,10 +16,10 @@ func DecodeConfig[T any](config models.JSON, providerName string) (T, error) {var out TconfigBytes, err := json.Marshal(config)if err != nil {- return out, fmt.Errorf("failed to marshal %s config: %w", providerName, err)+ return out, errors.WrapIff(err, "failed to marshal %s config", providerName)}if err := json.Unmarshal(configBytes, &out); err != nil {- return out, fmt.Errorf("failed to unmarshal %s config: %w", providerName, err)+ return out, errors.WrapIff(err, "failed to unmarshal %s config", providerName)}return out, nil}@@ -34,7 +34,7 @@ func DecryptStringCredential(value *string) error {decrypted, err := crypto.Decrypt(*value)if err != nil {if isPlausibleEncryptedCredentialInternal(*value) {- return fmt.Errorf("failed to decrypt notification credential: %w", err)+ return errors.WrapIf(err, "failed to decrypt notification credential")}slog.Warn("Failed to decrypt notification credential, using raw legacy value", "error", err)return nildiff --git a/backend/pkg/utils/notifications/deliver.go b/backend/pkg/utils/notifications/deliver.goindex 052648ad8..45653db13 100644--- a/backend/pkg/utils/notifications/deliver.go+++ b/backend/pkg/utils/notifications/deliver.go@@ -2,10 +2,10 @@ package notificationsimport ("context"- "errors"- "fmt""net/mail"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models")@@ -71,7 +71,7 @@ func deliverDiscord(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendDiscord(ctx, discordConfig, c.Text[MessageFormatMarkdown]); err != nil {- return fmt.Errorf("failed to send Discord notification: %w", err)+ return errors.WrapIf(err, "failed to send Discord notification")}return nil}@@ -88,11 +88,11 @@ func deliverEmail(ctx context.Context, config models.JSON, c Content) error {return errors.New("no recipient email addresses configured")}if _, err := mail.ParseAddress(emailConfig.FromAddress); err != nil {- return fmt.Errorf("invalid from address: %w", err)+ return errors.WrapIf(err, "invalid from address")}for _, addr := range emailConfig.ToAddresses {if _, err := mail.ParseAddress(addr); err != nil {- return fmt.Errorf("invalid to address %s: %w", addr, err)+ return errors.WrapIff(err, "invalid to address %s", addr)}}if err := DecryptStringCredential(&emailConfig.SMTPPassword); err != nil {@@ -106,7 +106,7 @@ func deliverEmail(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {- return fmt.Errorf("failed to send email: %w", err)+ return errors.WrapIf(err, "failed to send email")}return nil}@@ -129,7 +129,7 @@ func deliverTelegram(ctx context.Context, config models.JSON, c Content) error {telegramConfig.ParseMode = "HTML"}if err := SendTelegram(ctx, telegramConfig, c.Text[MessageFormatHTML]); err != nil {- return fmt.Errorf("failed to send Telegram notification: %w", err)+ return errors.WrapIf(err, "failed to send Telegram notification")}return nil}@@ -157,7 +157,7 @@ func deliverSignal(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendSignal(ctx, signalConfig, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Signal notification: %w", err)+ return errors.WrapIf(err, "failed to send Signal notification")}return nil}@@ -168,7 +168,7 @@ func deliverSlack(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendSlack(ctx, slackConfig, c.Text[MessageFormatSlack]); err != nil {- return fmt.Errorf("failed to send Slack notification: %w", err)+ return errors.WrapIf(err, "failed to send Slack notification")}return nil}@@ -179,7 +179,7 @@ func deliverNtfy(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendNtfy(ctx, ntfyConfig, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Ntfy notification: %w", err)+ return errors.WrapIf(err, "failed to send Ntfy notification")}return nil}@@ -201,7 +201,7 @@ func deliverPushover(ctx context.Context, config models.JSON, c Content) error {pushoverConfig.Title = c.DefaultTitle}if err := SendPushover(ctx, pushoverConfig, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Pushover notification: %w", err)+ return errors.WrapIf(err, "failed to send Pushover notification")}return nil}@@ -215,7 +215,7 @@ func deliverGotify(ctx context.Context, config models.JSON, c Content) error {gotifyConfig.Title = c.DefaultTitle}if err := SendGotify(ctx, gotifyConfig, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Gotify notification: %w", err)+ return errors.WrapIf(err, "failed to send Gotify notification")}return nil}@@ -226,7 +226,7 @@ func deliverMatrix(ctx context.Context, config models.JSON, c Content) error {return err}if err := SendMatrix(ctx, matrixConfig, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Matrix notification: %w", err)+ return errors.WrapIf(err, "failed to send Matrix notification")}return nil}@@ -240,7 +240,7 @@ func deliverGeneric(ctx context.Context, config models.JSON, c Content) error {return errors.New("webhook URL not configured")}if err := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain]); err != nil {- return fmt.Errorf("failed to send Generic webhook notification: %w", err)+ return errors.WrapIf(err, "failed to send Generic webhook notification")}return nil}diff --git a/backend/pkg/utils/notifications/discord_sender.go b/backend/pkg/utils/notifications/discord_sender.goindex a2551826a..a3dc39259 100644--- a/backend/pkg/utils/notifications/discord_sender.go+++ b/backend/pkg/utils/notifications/discord_sender.go@@ -2,8 +2,8 @@ package notificationsimport ("context"- "errors"- "fmt"++ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"@@ -34,18 +34,18 @@ func SendDiscord(ctx context.Context, config models.DiscordConfig, message strinshoutrrrURL, err := BuildDiscordURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Discord URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Discord URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Discord sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Discord sender")}errs := sender.Send(message, nil)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Discord message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Discord message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/email_sender.go b/backend/pkg/utils/notifications/email_sender.goindex edcf5d55e..5f142e165 100644--- a/backend/pkg/utils/notifications/email_sender.go+++ b/backend/pkg/utils/notifications/email_sender.go@@ -3,10 +3,10 @@ package notificationsimport ("context""crypto/tls"- "errors"- "fmt""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/wneessen/go-mail")@@ -67,7 +67,7 @@ func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptionsreturn nil, errors.New("SMTP host is empty")}if config.SMTPPort < 1 || config.SMTPPort > 65535 {- return nil, fmt.Errorf("invalid SMTP port: %d", config.SMTPPort)+ return nil, errors.Errorf("invalid SMTP port: %d", config.SMTPPort)}opts := []mail.Option{@@ -103,7 +103,7 @@ func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptionsclient, err := mail.NewClient(config.SMTPHost, opts...)if err != nil {- return nil, fmt.Errorf("failed to construct SMTP client: %w", err)+ return nil, errors.WrapIf(err, "failed to construct SMTP client")}return client, nil@@ -119,7 +119,7 @@ func sendEmailInternal(ctx context.Context, config models.EmailConfig, subject,return errors.New("email send context is required")}if err := ctx.Err(); err != nil {- return fmt.Errorf("email send canceled: %w", err)+ return errors.WrapIf(err, "email send canceled")}if config.FromAddress == "" {@@ -131,21 +131,21 @@ func sendEmailInternal(ctx context.Context, config models.EmailConfig, subject,client, err := buildMailClientInternal(config, options)if err != nil {- return fmt.Errorf("failed to build SMTP client: %w", err)+ return errors.WrapIf(err, "failed to build SMTP client")}msg := mail.NewMsg()if err := msg.From(config.FromAddress); err != nil {- return fmt.Errorf("invalid from address %q: %w", config.FromAddress, err)+ return errors.WrapIff(err, "invalid from address %q", config.FromAddress)}if err := msg.To(config.ToAddresses...); err != nil {- return fmt.Errorf("invalid recipient address(es): %w", err)+ return errors.WrapIf(err, "invalid recipient address(es)")}msg.Subject(subject)msg.SetBodyString(mail.TypeTextHTML, htmlBody)if err := client.DialAndSendWithContext(ctx, msg); err != nil {- return fmt.Errorf("failed to send email: %w", err)+ return errors.WrapIf(err, "failed to send email")}return nildiff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.goindex a957a77c0..eac32e9d9 100644--- a/backend/pkg/utils/notifications/generic_sender.go+++ b/backend/pkg/utils/notifications/generic_sender.go@@ -4,13 +4,14 @@ import ("bytes""context"json "encoding/json/v2"- "errors""fmt""io""net/http""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"@@ -27,7 +28,7 @@ func resolveWebhookURLInternal(config models.GenericConfig) (*url.URL, error) {parsed, err := url.Parse(config.WebhookURL)if err != nil {- return nil, fmt.Errorf("invalid webhook URL: %w", err)+ return nil, errors.WrapIf(err, "invalid webhook URL")}hasScheme := strings.Contains(config.WebhookURL, "://")@@ -39,7 +40,7 @@ func resolveWebhookURLInternal(config models.GenericConfig) (*url.URL, error) {normalized := strings.TrimPrefix(config.WebhookURL, "//")parsed, err = url.Parse(fmt.Sprintf("%s://%s", scheme, normalized))if err != nil {- return nil, fmt.Errorf("invalid webhook URL: %w", err)+ return nil, errors.WrapIf(err, "invalid webhook URL")}}@@ -50,7 +51,7 @@ func resolveWebhookURLInternal(config models.GenericConfig) (*url.URL, error) {switch strings.ToLower(parsed.Scheme) {case "http", "https":default:- return nil, fmt.Errorf("invalid webhook URL scheme: %s", parsed.Scheme)+ return nil, errors.Errorf("invalid webhook URL scheme: %s", parsed.Scheme)}return parsed, nil@@ -142,12 +143,12 @@ func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, titlshoutrrrURL, err := BuildGenericURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Generic URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Generic URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Generic sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Generic sender")}// Build params with title. Always use "title" as the param key — Shoutrrr's@@ -160,7 +161,7 @@ func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, titlerrs := sender.Send(message, ¶ms)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Generic webhook message with title via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Generic webhook message with title via shoutrrr")}}return nil@@ -192,7 +193,7 @@ func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig,body, err := json.Marshal(payload)if err != nil {- return fmt.Errorf("failed to marshal webhook payload: %w", err)+ return errors.WrapIf(err, "failed to marshal webhook payload")}method := strings.ToUpper(config.Method)@@ -202,7 +203,7 @@ func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig,req, err := http.NewRequestWithContext(ctx, method, webhookURL.String(), bytes.NewReader(body))if err != nil {- return fmt.Errorf("failed to create webhook request: %w", err)+ return errors.WrapIf(err, "failed to create webhook request")}contentType := config.ContentType@@ -217,21 +218,21 @@ func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig,resp, err := http.DefaultClient.Do(req)if err != nil {- return fmt.Errorf("failed to send webhook request: %w", err)+ return errors.WrapIf(err, "failed to send webhook request")}defer func() { _ = resp.Body.Close() }()respBody, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read webhook response body: %w", err)+ return errors.WrapIf(err, "failed to read webhook response body")}if resp.StatusCode >= http.StatusBadRequest {- return fmt.Errorf("webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))+ return errors.Errorf("webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))}if !strings.Contains(string(respBody), config.SuccessBodyContains) {- return fmt.Errorf("webhook response did not contain expected success indicator %q: %s", config.SuccessBodyContains, string(respBody))+ return errors.Errorf("webhook response did not contain expected success indicator %q: %s", config.SuccessBodyContains, string(respBody))}return nildiff --git a/backend/pkg/utils/notifications/gotify_sender.go b/backend/pkg/utils/notifications/gotify_sender.goindex a73a91fc7..2246725c9 100644--- a/backend/pkg/utils/notifications/gotify_sender.go+++ b/backend/pkg/utils/notifications/gotify_sender.go@@ -2,12 +2,13 @@ package notificationsimport ("context"- "errors""fmt""net/url""strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"@@ -61,12 +62,12 @@ func BuildGotifyURL(config models.GotifyConfig) (string, error) {func SendGotify(ctx context.Context, config models.GotifyConfig, message string) error {shoutrrrURL, err := BuildGotifyURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Gotify URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Gotify URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Gotify sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Gotify sender")}params := &shoutrrrTypes.Params{}@@ -74,7 +75,7 @@ func SendGotify(ctx context.Context, config models.GotifyConfig, message string)errs := sender.Send(message, params)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Gotify message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Gotify message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/matrix_sender.go b/backend/pkg/utils/notifications/matrix_sender.goindex 07921d974..cdb27fa65 100644--- a/backend/pkg/utils/notifications/matrix_sender.go+++ b/backend/pkg/utils/notifications/matrix_sender.go@@ -2,11 +2,12 @@ package notificationsimport ("context"- "errors""fmt""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"@@ -60,12 +61,12 @@ func BuildMatrixURL(config models.MatrixConfig) (string, error) {func SendMatrix(ctx context.Context, config models.MatrixConfig, message string) error {shoutrrrURL, err := BuildMatrixURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Matrix URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Matrix URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Matrix sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Matrix sender")}params := &shoutrrrTypes.Params{}@@ -73,7 +74,7 @@ func SendMatrix(ctx context.Context, config models.MatrixConfig, message string)errs := sender.Send(message, params)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Matrix message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Matrix message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/ntfy_sender.go b/backend/pkg/utils/notifications/ntfy_sender.goindex 70c0bb555..32d2afa24 100644--- a/backend/pkg/utils/notifications/ntfy_sender.go+++ b/backend/pkg/utils/notifications/ntfy_sender.go@@ -2,11 +2,12 @@ package notificationsimport ("context"- "errors""fmt""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"@@ -97,12 +98,12 @@ func SendNtfy(ctx context.Context, config models.NtfyConfig, message string) errshoutrrrURL, err := BuildNtfyURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Ntfy URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Ntfy URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Ntfy sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Ntfy sender")}params := &shoutrrrTypes.Params{}@@ -110,7 +111,7 @@ func SendNtfy(ctx context.Context, config models.NtfyConfig, message string) errerrs := sender.Send(message, params)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Ntfy message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Ntfy message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/pushover_sender.go b/backend/pkg/utils/notifications/pushover_sender.goindex cabff16ea..dbdbf4a28 100644--- a/backend/pkg/utils/notifications/pushover_sender.go+++ b/backend/pkg/utils/notifications/pushover_sender.go@@ -2,12 +2,12 @@ package notificationsimport ("context"- "errors"- "fmt""net/url""strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr")@@ -70,18 +70,18 @@ func SendPushover(ctx context.Context, config models.PushoverConfig, message strshoutrrrURL, err := BuildPushoverURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Pushover URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Pushover URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Pushover sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Pushover sender")}errs := sender.Send(message, nil)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Pushover message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Pushover message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/signal_sender.go b/backend/pkg/utils/notifications/signal_sender.goindex 01d13f30c..050892206 100644--- a/backend/pkg/utils/notifications/signal_sender.go+++ b/backend/pkg/utils/notifications/signal_sender.go@@ -2,8 +2,8 @@ package notificationsimport ("context"- "errors"- "fmt"++ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"@@ -54,18 +54,18 @@ func SendSignal(ctx context.Context, config models.SignalConfig, message string)shoutrrrURL, err := BuildSignalURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Signal URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Signal URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Signal sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Signal sender")}errs := sender.Send(message, nil)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Signal message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Signal message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/slack_sender.go b/backend/pkg/utils/notifications/slack_sender.goindex a7a743b00..986fc99af 100644--- a/backend/pkg/utils/notifications/slack_sender.go+++ b/backend/pkg/utils/notifications/slack_sender.go@@ -2,8 +2,8 @@ package notificationsimport ("context"- "errors"- "fmt"++ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"@@ -19,7 +19,7 @@ func BuildSlackURL(config models.SlackConfig) (string, error) {// Parse the token to get the token objecttoken, err := slack.ParseToken(config.Token)if err != nil {- return "", fmt.Errorf("invalid Slack token format (expected format: xoxb-... or xoxp-...): %w", err)+ return "", errors.WrapIf(err, "invalid Slack token format (expected format: xoxb-... or xoxp-...)")}slackConfig := &slack.Config{@@ -44,18 +44,18 @@ func SendSlack(ctx context.Context, config models.SlackConfig, message string) eshoutrrrURL, err := BuildSlackURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Slack URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Slack URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Slack sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Slack sender")}errs := sender.Send(message, nil)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Slack message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Slack message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/notifications/telegram_sender.go b/backend/pkg/utils/notifications/telegram_sender.goindex 466f0b470..3670b4938 100644--- a/backend/pkg/utils/notifications/telegram_sender.go+++ b/backend/pkg/utils/notifications/telegram_sender.go@@ -2,8 +2,8 @@ package notificationsimport ("context"- "errors"- "fmt"++ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"@@ -31,7 +31,7 @@ func BuildTelegramURL(config models.TelegramConfig) (string, error) {q.Set("parsemode", config.ParseMode)url.RawQuery = q.Encode()default:- return "", fmt.Errorf("invalid parse mode: %s (must be Markdown, HTML, MarkdownV2, or None)", config.ParseMode)+ return "", errors.Errorf("invalid parse mode: %s (must be Markdown, HTML, MarkdownV2, or None)", config.ParseMode)}}@@ -49,18 +49,18 @@ func SendTelegram(ctx context.Context, config models.TelegramConfig, message strshoutrrrURL, err := BuildTelegramURL(config)if err != nil {- return fmt.Errorf("failed to build shoutrrr Telegram URL: %w", err)+ return errors.WrapIf(err, "failed to build shoutrrr Telegram URL")}sender, err := shoutrrr.CreateSender(shoutrrrURL)if err != nil {- return fmt.Errorf("failed to create shoutrrr Telegram sender: %w", err)+ return errors.WrapIf(err, "failed to create shoutrrr Telegram sender")}errs := sender.Send(message, nil)for _, err := range errs {if err != nil {- return fmt.Errorf("failed to send Telegram message via shoutrrr: %w", err)+ return errors.WrapIf(err, "failed to send Telegram message via shoutrrr")}}return nildiff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.goindex 63e8ac6d0..8385f7511 100644--- a/backend/pkg/utils/path_util.go+++ b/backend/pkg/utils/path_util.go@@ -1,9 +1,10 @@package utilsimport (- "errors""path""strings"++ "emperror.dev/errors")// SanitizeBrowsePath normalizes a path within a rooted file browser.diff --git a/backend/pkg/utils/validation/credential_target.go b/backend/pkg/utils/validation/credential_target.goindex 01bbd6106..43e4c8a7a 100644--- a/backend/pkg/utils/validation/credential_target.go+++ b/backend/pkg/utils/validation/credential_target.go@@ -4,6 +4,8 @@ import ("fmt""slices"+ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models")@@ -40,10 +42,7 @@ func ValidateCredentialTargetChange(slices.Sort(missingFields)if len(missingFields) == 1 {- return &models.ValidationError{- Field: missingFields[0],- Message: fmt.Sprintf("Changing %s requires re-supplying or clearing the %s", targetName, missingFields[0]),- }+ return common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Changing %s requires re-supplying or clearing the %s", targetName, missingFields[0]), "field", missingFields[0]))}return models.NewValidationError(diff --git a/backend/pkg/utils/validation/credential_target_test.go b/backend/pkg/utils/validation/credential_target_test.goindex 8819d32c6..e20b05e16 100644--- a/backend/pkg/utils/validation/credential_target_test.go+++ b/backend/pkg/utils/validation/credential_target_test.go@@ -4,6 +4,8 @@ import ("strings""testing"+ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -90,10 +92,9 @@ func TestValidateCredentialTargetChange(t *testing.T) {switch {case tt.wantField != "":- var validationErr *models.ValidationError- require.ErrorAs(t, err, &validationErr)- assert.Equal(t, tt.wantField, validationErr.Field)- assert.Equal(t, "Changing credential target requires re-supplying or clearing the token", validationErr.Message)+ require.ErrorIs(t, err, common.ErrValidation)+ assert.Contains(t, errors.GetDetails(err), tt.wantField)+ assert.Equal(t, "Changing credential target requires re-supplying or clearing the token", err.Error())case len(tt.wantFields) > 0:var apiErr *models.APIErrorrequire.ErrorAs(t, err, &apiErr)diff --git a/cli/go.mod b/cli/go.modindex 8a8b72bc1..dd39a2423 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -8,6 +8,7 @@ require (charm.land/fang/v2 v2.0.1charm.land/lipgloss/v2 v2.0.5charm.land/log/v2 v2.0.0+ emperror.dev/errors v0.8.1github.com/charmbracelet/x/term v0.2.2github.com/fatih/color v1.19.0github.com/getarcaneapp/arcane/types/v2 v2.5.0@@ -67,6 +68,7 @@ require (github.com/opencontainers/go-digest v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.1.1 // indirectgithub.com/pelletier/go-toml/v2 v2.3.1 // indirect+ github.com/pkg/errors v0.9.1 // indirectgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirectgithub.com/prometheus/client_golang v1.23.2 // indirectgithub.com/prometheus/client_model v0.6.2 // indirect@@ -87,6 +89,7 @@ require (go.opentelemetry.io/otel v1.44.0 // indirectgo.opentelemetry.io/otel/metric v1.44.0 // indirectgo.opentelemetry.io/otel/trace v1.44.0 // indirect+ go.uber.org/multierr v1.11.0 // indirectgo.yaml.in/yaml/v2 v2.4.4 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirectgo.yaml.in/yaml/v4 v4.0.0-rc.6 // indirectdiff --git a/cli/go.sum b/cli/go.sumindex 6e23c9d6c..d40222d21 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -8,6 +8,8 @@ charm.land/lipgloss/v2 v2.0.5 h1:kbNxgeeUOYv5J0YdpxFjfvf3dFvqH8Aci4zB6xqFtrY=charm.land/lipgloss/v2 v2.0.5/go.mod h1:9oqhxt4yxIMe6q5A4kHr44DremZk7J9UNh74GlWa5nc=charm.land/log/v2 v2.0.0 h1:SY3Cey7ipx86/MBXQHwsguOT6X1exT94mmJRdzTNs+s=charm.land/log/v2 v2.0.0/go.mod h1:c3cZSRqm20qUVVAR1WmS/7ab8bgha3C6G7DjPcaVZz0=+emperror.dev/errors v0.8.1 h1:UavXZ5cSX/4u9iyvH6aDcuGkVjeexUGJ7Ij7G4VfQT0=+emperror.dev/errors v0.8.1/go.mod h1:YcRvLPh626Ubn2xqtoprejnA5nFha+TJ+2vew48kWuE=github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g=github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 h1:0kQAzHq8vLs7Pptv+7TxjdETLf/nIqJpIB4oC6Ba4vY=@@ -49,6 +51,8 @@ github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJgithub.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=@@ -125,6 +129,9 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwgithub.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=@@ -161,6 +168,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=@@ -185,8 +194,12 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRkgo.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=+go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=+go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67 h1:nHPqmzoLZv+9OqER7S2oXnIBDAbIaIKKrVtNtDvJzjc=go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67/go.mod h1:WFmSrzphcXaSV4LG3YfIw42bPHDK8A6WsAYZCxyys/c=go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.goindex 2fd408add..a51e4e9ec 100644--- a/cli/internal/ci/ci_detect.go+++ b/cli/internal/ci/ci_detect.go@@ -3,13 +3,13 @@ package ciimport ("context""encoding/json"- "errors"- "fmt""io""net/http""net/url""strings""time"++ "emperror.dev/errors")const (@@ -53,7 +53,7 @@ func DetectToken(ctx context.Context, provider string, audience string, getenv fcase ProviderGeneric:return "", "", errors.New("generic provider requires --token, --token-file, or --token-stdin")default:- return "", "", fmt.Errorf("unsupported federated provider %q", provider)+ return "", "", errors.Errorf("unsupported federated provider %q", provider)}}@@ -66,7 +66,7 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenvparsedURL, err := url.Parse(requestURL)if err != nil {- return "", fmt.Errorf("invalid GitHub Actions OIDC request URL: %w", err)+ return "", errors.WrapIf(err, "invalid GitHub Actions OIDC request URL")}if strings.TrimSpace(audience) != "" {q := parsedURL.Query()@@ -76,30 +76,30 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenvreq, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)if err != nil {- return "", fmt.Errorf("failed to create GitHub Actions OIDC request: %w", err)+ return "", errors.WrapIf(err, "failed to create GitHub Actions OIDC request")}req.Header.Set("Authorization", "Bearer "+requestToken)req.Header.Set("Accept", "application/json")resp, err := httpClient.Do(req)if err != nil {- return "", fmt.Errorf("failed to request GitHub Actions OIDC token: %w", err)+ return "", errors.WrapIf(err, "failed to request GitHub Actions OIDC token")}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))if err != nil {- return "", fmt.Errorf("failed to read GitHub Actions OIDC response: %w", err)+ return "", errors.WrapIf(err, "failed to read GitHub Actions OIDC response")}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", fmt.Errorf("GitHub Actions OIDC request failed with status %d", resp.StatusCode)+ return "", errors.Errorf("GitHub Actions OIDC request failed with status %d", resp.StatusCode)}var payload struct {Value string `json:"value"`}if err := json.Unmarshal(body, &payload); err != nil {- return "", fmt.Errorf("failed to parse GitHub Actions OIDC response: %w", err)+ return "", errors.WrapIf(err, "failed to parse GitHub Actions OIDC response")}token := strings.TrimSpace(payload.Value)if token == "" {diff --git a/cli/internal/client/client.go b/cli/internal/client/client.goindex 16a359800..ce8ff30aa 100644--- a/cli/internal/client/client.go+++ b/cli/internal/client/client.go@@ -26,7 +26,7 @@ import ("bytes""context""encoding/json"- "errors"+ stderrors "errors""fmt""io""net"@@ -36,6 +36,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/runstate"@@ -85,7 +86,7 @@ func New(cfg *types.Config) (*Client, error) {}parsedURL, err := url.Parse(cfg.ServerURL)if err != nil {- return nil, fmt.Errorf("invalid server_url: %w", err)+ return nil, errors.WrapIf(err, "invalid server_url")}envID := cfg.DefaultEnvironment@@ -115,7 +116,7 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {}parsedURL, err := url.Parse(cfg.ServerURL)if err != nil {- return nil, fmt.Errorf("invalid server_url: %w", err)+ return nil, errors.WrapIf(err, "invalid server_url")}envID := cfg.DefaultEnvironment@@ -155,7 +156,7 @@ func newHTTPClientInternal() *http.Client {func NewFromConfig() (*Client, error) {cfg, err := config.Load()if err != nil {- return nil, fmt.Errorf("failed to load config: %w", err)+ return nil, errors.WrapIf(err, "failed to load config")}state := runstate.Get()if strings.TrimSpace(state.EnvOverride) != "" {@@ -180,7 +181,7 @@ func NewFromConfig() (*Client, error) {func NewFromConfigUnauthenticated() (*Client, error) {cfg, err := config.Load()if err != nil {- return nil, fmt.Errorf("failed to load config: %w", err)+ return nil, errors.WrapIf(err, "failed to load config")}state := runstate.Get()if strings.TrimSpace(state.EnvOverride) != "" {@@ -273,7 +274,7 @@ func (c *Client) Request(ctx context.Context, method, path string, body any) (*h// Streaming bodies cannot be replayed, so skip auto-refresh.req, err := http.NewRequestWithContext(ctx, method, fullURL, v)if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)+ return nil, errors.WrapIf(err, "failed to create request")}c.applyAuth(req)req.Header.Set("Content-Type", "application/json")@@ -283,14 +284,14 @@ func (c *Client) Request(ctx context.Context, method, path string, body any) (*hresp, err := c.httpClient.Do(req)if err != nil {logger.GetLogger().Debug("Request failed", "method", method, "url", fullURL, "env_id", c.envID, "duration", time.Since(start).String(), "error", err)- return nil, fmt.Errorf("request failed: %w", err)+ return nil, errors.WrapIf(err, "request failed")}logger.GetLogger().Debug("Response received", "method", method, "url", fullURL, "env_id", c.envID, "status", resp.Status, "duration", time.Since(start).String())return resp, nildefault:jsonBody, err := json.Marshal(body)if err != nil {- return nil, fmt.Errorf("failed to marshal request body: %w", err)+ return nil, errors.WrapIf(err, "failed to marshal request body")}bodyBytes = jsonBody}@@ -311,7 +312,7 @@ func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Rereq, err := http.NewRequestWithContext(ctx, method, fullURL, body)if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)+ return nil, errors.WrapIf(err, "failed to create request")}c.applyAuth(req)@@ -326,7 +327,7 @@ func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Reresp, err := c.httpClient.Do(req)if err != nil {logger.GetLogger().Debug("Raw request failed", "method", method, "url", fullURL, "env_id", c.envID, "duration", time.Since(start).String(), "error", err)- return nil, fmt.Errorf("request failed: %w", err)+ return nil, errors.WrapIf(err, "request failed")}logger.GetLogger().Debug("Raw response received", "method", method, "url", fullURL, "env_id", c.envID, "status", resp.Status, "duration", time.Since(start).String())@@ -339,13 +340,13 @@ func (c *Client) resolveURL(path string) (string, error) {}if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {if _, err := url.Parse(path); err != nil {- return "", fmt.Errorf("invalid path: %w", err)+ return "", errors.WrapIf(err, "invalid path")}return path, nil}rel, err := url.Parse(path)if err != nil {- return "", fmt.Errorf("invalid path: %w", err)+ return "", errors.WrapIf(err, "invalid path")}if c.baseURLParsed == nil {return "", errors.New("invalid base URL")@@ -364,7 +365,7 @@ func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyBytereq, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)+ return nil, errors.WrapIf(err, "failed to create request")}c.applyAuth(req)@@ -383,7 +384,7 @@ func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyByte}continue}- return nil, fmt.Errorf("request failed: %w", err)+ return nil, errors.WrapIf(err, "request failed")}logger.GetLogger().Debug("Response received", "method", method, "url", fullURL, "env_id", c.envID, "attempt", attempt, "status", resp.Status, "duration", time.Since(start).String())@@ -410,7 +411,7 @@ func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyBytereturn resp, nil}- return nil, fmt.Errorf("request failed after %d attempts", attempts)+ return nil, errors.Errorf("request failed after %d attempts", attempts)}func (c *Client) shouldRetry(method string, status int, err error) bool {@@ -426,7 +427,7 @@ func (c *Client) shouldRetry(method string, status int, err error) bool {return false}- if netErr, ok := errors.AsType[net.Error](err); ok {+ if netErr, ok := stderrors.AsType[net.Error](err); ok {return netErr.Timeout()}return true@@ -483,7 +484,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {bodyBytes, err := json.Marshal(map[string]string{"refreshToken": c.refreshToken})if err != nil {- return fmt.Errorf("failed to marshal refresh request: %w", err)+ return errors.WrapIf(err, "failed to marshal refresh request")}if c.baseURLParsed == nil {@@ -494,7 +495,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {req, err := http.NewRequestWithContext(ctx, http.MethodPost, refreshURL, bytes.NewReader(bodyBytes))if err != nil {- return fmt.Errorf("failed to create refresh request: %w", err)+ return errors.WrapIf(err, "failed to create refresh request")}req.Header.Set("Content-Type", "application/json")req.Header.Set("Accept", "application/json")@@ -503,23 +504,23 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {resp, err := c.httpClient.Do(req)if err != nil {logger.GetLogger().Debug("Token refresh request failed", "url", refreshURL, "duration", time.Since(start).String(), "error", err)- return fmt.Errorf("token refresh failed: %w", err)+ return errors.WrapIf(err, "token refresh failed")}defer func() { _ = resp.Body.Close() }()logger.GetLogger().Debug("Token refresh response received", "url", refreshURL, "status", resp.Status, "duration", time.Since(start).String())respBody, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read refresh response: %w", err)+ return errors.WrapIf(err, "failed to read refresh response")}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("token refresh failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(respBody)))+ return errors.Errorf("token refresh failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(respBody)))}var result base.ApiResponse[auth.TokenRefreshResponse]if err := json.Unmarshal(respBody, &result); err != nil {- return fmt.Errorf("failed to parse refresh response: %w", err)+ return errors.WrapIf(err, "failed to parse refresh response")}if !result.Success || result.Data.Token == "" {return errors.New("token refresh failed: unexpected response from server")@@ -536,13 +537,13 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}cfg.JWTToken = result.Data.Tokencfg.APIKey = ""cfg.RefreshToken = newRefreshif err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save refreshed token: %w", err)+ return errors.WrapIf(err, "failed to save refreshed token")}return nil@@ -589,14 +590,14 @@ func (c *Client) DoJSON(ctx context.Context, method, path string, body any, outif resp.StatusCode < 200 || resp.StatusCode >= 300 {b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))- return fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ return errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))}if out == nil {return nil}if err := json.NewDecoder(resp.Body).Decode(out); err != nil {- return fmt.Errorf("failed to decode response: %w", err)+ return errors.WrapIf(err, "failed to decode response")}return nil}@@ -616,12 +617,12 @@ func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]byif resp.StatusCode < 200 || resp.StatusCode >= 300 {b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))- return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ return nil, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))}b, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read response body: %w", err)+ return nil, errors.WrapIf(err, "failed to read response body")}return b, nil}@@ -641,22 +642,22 @@ func DecodeResponseStrict[T any](resp *http.Response) (*APIResponse[T], error) {if resp.StatusCode < 200 || resp.StatusCode >= 300 {body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))- return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read response body: %w", err)+ return nil, errors.WrapIf(err, "failed to read response body")}var result APIResponse[T]if err := json.Unmarshal(body, &result); err != nil {- return nil, fmt.Errorf("failed to decode response: %w (body: %s)", err, string(body))+ return nil, errors.WrapIff(err, "failed to decode response (body: %s)", string(body))}if !result.Success {if strings.TrimSpace(result.Error) != "" {- return &result, fmt.Errorf("API error: %s", result.Error)+ return &result, errors.Errorf("API error: %s", result.Error)}return &result, errors.New("API error: request was not successful")}@@ -678,17 +679,17 @@ func DecodePaginatedResponseStrict[T any](resp *http.Response) (*PaginatedResponif resp.StatusCode < 200 || resp.StatusCode >= 300 {body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))- return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read response body: %w", err)+ return nil, errors.WrapIf(err, "failed to read response body")}var result PaginatedResponse[T]if err := json.Unmarshal(body, &result); err != nil {- return nil, fmt.Errorf("failed to decode response: %w (body: %s)", err, string(body))+ return nil, errors.WrapIff(err, "failed to decode response (body: %s)", string(body))}return &result, nil@@ -706,7 +707,7 @@ func (c *Client) TestConnection(ctx context.Context) error {if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(resp.Body)- return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))+ return errors.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))}return nildiff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.goindex defd92e08..e51dfb9d9 100644--- a/cli/internal/cmdutil/confirm.go+++ b/cli/internal/cmdutil/confirm.go@@ -1,11 +1,12 @@package cmdutilimport (- "errors""fmt""io""strings"+ "emperror.dev/errors"+"github.com/spf13/cobra")@@ -19,7 +20,7 @@ func Confirm(cmd *cobra.Command, prompt string) (bool, error) {var response stringif _, err := fmt.Scanln(&response); err != nil && !errors.Is(err, io.EOF) {// Keep EOF as a default "no" response, but surface other input failures.- return false, fmt.Errorf("failed to read confirmation input: %w", err)+ return false, errors.WrapIf(err, "failed to read confirmation input")}switch strings.ToLower(strings.TrimSpace(response)) {diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.goindex 216cbcd93..a0d73b6cc 100644--- a/cli/internal/cmdutil/context.go+++ b/cli/internal/cmdutil/context.go@@ -1,10 +1,10 @@package cmdutilimport (- "errors"- "fmt""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client"runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime""github.com/spf13/cobra"@@ -68,6 +68,6 @@ func ResolveOutputMode(mode string) (runtimectx.OutputMode, error) {case runtimectx.OutputModeText, runtimectx.OutputModeJSON:return runtimectx.OutputMode(normalized), nildefault:- return "", fmt.Errorf("invalid output mode %q", mode)+ return "", errors.Errorf("invalid output mode %q", mode)}}diff --git a/cli/internal/cmdutil/pagination.go b/cli/internal/cmdutil/pagination.goindex 52ad94379..d577f764f 100644--- a/cli/internal/cmdutil/pagination.go+++ b/cli/internal/cmdutil/pagination.go@@ -1,10 +1,10 @@package cmdutilimport (- "fmt""net/url""strconv"+ "emperror.dev/errors""github.com/spf13/cobra")@@ -22,7 +22,7 @@ func ApplyPaginationParams() (string, error) {parsed, err := url.Parse(path)if err != nil {- return "", fmt.Errorf("failed to parse path: %w", err)+ return "", errors.WrapIf(err, "failed to parse path")}query := parsed.Query()diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.goindex 8a2bfe7c5..ff6633c04 100644--- a/cli/internal/cmdutil/response.go+++ b/cli/internal/cmdutil/response.go@@ -2,11 +2,12 @@ package cmdutilimport ("encoding/json"- "errors""fmt""io""net/http""strings"++ "emperror.dev/errors")const maxErrorBodyBytes = 4096@@ -49,7 +50,7 @@ func DecodeJSON[T any](resp *http.Response, out *T) error {return errors.New("nil decode target")}if err := json.NewDecoder(resp.Body).Decode(out); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}return nil}@@ -58,7 +59,7 @@ func DecodeJSON[T any](resp *http.Response, out *T) error {func PrintJSON(v any) error {b, err := json.MarshalIndent(v, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(b))return nildiff --git a/cli/internal/config/config.go b/cli/internal/config/config.goindex 9e2b8984c..71a525384 100644--- a/cli/internal/config/config.go+++ b/cli/internal/config/config.go@@ -27,6 +27,7 @@ import ("strings""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/go-viper/mapstructure/v2""github.com/samber/hot"@@ -100,7 +101,7 @@ func ConfigPath() (string, error) {home, err := os.UserHomeDir()if err != nil {- return "", fmt.Errorf("failed to get home directory: %w", err)+ return "", errors.WrapIf(err, "failed to get home directory")}return filepath.Join(home, ".config", configFileName), nil@@ -119,7 +120,7 @@ func SetConfigPath(path string) error {if path == "~" || strings.HasPrefix(path, "~/") {home, err := os.UserHomeDir()if err != nil {- return fmt.Errorf("failed to expand config path: %w", err)+ return errors.WrapIf(err, "failed to expand config path")}rel := strings.TrimPrefix(path, "~")path = filepath.Join(home, strings.TrimPrefix(rel, string(os.PathSeparator)))@@ -127,7 +128,7 @@ func SetConfigPath(path string) error {absPath, err := filepath.Abs(path)if err != nil {- return fmt.Errorf("failed to resolve config path: %w", err)+ return errors.WrapIf(err, "failed to resolve config path")}customConfigPath = absPath@@ -155,7 +156,7 @@ func Load() (*types.Config, error) {configCache.Set(path, def)return def, nil}- return nil, fmt.Errorf("failed to read config file: %w", err)+ return nil, errors.WrapIf(err, "failed to read config file")}_ = data@@ -167,7 +168,7 @@ func Load() (*types.Config, error) {v.SetDefault("federated_audience", "")v.SetDefault("log_level", "info")if err := v.ReadInConfig(); err != nil {- return nil, fmt.Errorf("failed to parse config file: %w", err)+ return nil, errors.WrapIf(err, "failed to parse config file")}var cfg types.Config@@ -175,7 +176,7 @@ func Load() (*types.Config, error) {dc.TagName = "mapstructure"dc.WeaklyTypedInput = true}); err != nil {- return nil, fmt.Errorf("failed to unmarshal config: %w", err)+ return nil, errors.WrapIf(err, "failed to unmarshal config")}normalized := normalizeConfig(&cfg)@@ -196,7 +197,7 @@ func Save(c *types.Config) error {// Ensure the config directory existsdir := filepath.Dir(path)if err := os.MkdirAll(dir, 0o700); err != nil {- return fmt.Errorf("failed to create config directory: %w", err)+ return errors.WrapIf(err, "failed to create config directory")}cfg := normalizeConfig(c)@@ -238,10 +239,10 @@ func Save(c *types.Config) error {}if err := v.WriteConfigAs(path); err != nil {- return fmt.Errorf("failed to write config file: %w", err)+ return errors.WrapIf(err, "failed to write config file")}if err := os.Chmod(path, 0o600); err != nil {- return fmt.Errorf("failed to set config permissions: %w", err)+ return errors.WrapIf(err, "failed to set config permissions")}configCache.Set(path, cfg)@@ -262,18 +263,18 @@ func InitDefaultFile() (bool, error) {switch {case err == nil:if info.IsDir() {- return false, fmt.Errorf("config path is a directory: %s", path)+ return false, errors.Errorf("config path is a directory: %s", path)}return false, nilcase os.IsNotExist(err):// Continue and create the file below.default:- return false, fmt.Errorf("failed to stat config path: %w", err)+ return false, errors.WrapIf(err, "failed to stat config path")}dir := filepath.Dir(path)if err := os.MkdirAll(dir, 0o700); err != nil {- return false, fmt.Errorf("failed to create config directory: %w", err)+ return false, errors.WrapIf(err, "failed to create config directory")}v := viper.New()@@ -292,10 +293,10 @@ func InitDefaultFile() (bool, error) {}if err := v.WriteConfigAs(path); err != nil {- return false, fmt.Errorf("failed to write config file: %w", err)+ return false, errors.WrapIf(err, "failed to write config file")}if err := os.Chmod(path, 0o600); err != nil {- return false, fmt.Errorf("failed to set config permissions: %w", err)+ return false, errors.WrapIf(err, "failed to set config permissions")}invalidateCache()@@ -316,28 +317,28 @@ func BackupFile() (backupPath string, moved bool, err error) {switch {case err == nil:if info.IsDir() {- return "", false, fmt.Errorf("config path is a directory: %s", path)+ return "", false, errors.Errorf("config path is a directory: %s", path)}case os.IsNotExist(err):return backupPath, false, nildefault:- return "", false, fmt.Errorf("failed to stat config path: %w", err)+ return "", false, errors.WrapIf(err, "failed to stat config path")}if existingBackup, backupErr := os.Stat(backupPath); backupErr == nil {if existingBackup.IsDir() {- return "", false, fmt.Errorf("backup path is a directory: %s", backupPath)+ return "", false, errors.Errorf("backup path is a directory: %s", backupPath)}rotatedPath := fmt.Sprintf("%s.%s", backupPath, time.Now().UTC().Format("20060102150405"))if err := os.Rename(backupPath, rotatedPath); err != nil {- return "", false, fmt.Errorf("failed to rotate existing backup %s: %w", backupPath, err)+ return "", false, errors.WrapIff(err, "failed to rotate existing backup %s", backupPath)}} else if !os.IsNotExist(backupErr) {- return "", false, fmt.Errorf("failed to stat backup path: %w", backupErr)+ return "", false, errors.WrapIf(backupErr, "failed to stat backup path")}if err := os.Rename(path, backupPath); err != nil {- return "", false, fmt.Errorf("failed to move config to backup: %w", err)+ return "", false, errors.WrapIf(err, "failed to move config to backup")}invalidateCache()diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.goindex f07347b43..29358e94b 100644--- a/cli/internal/prompt/prompt.go+++ b/cli/internal/prompt/prompt.go@@ -1,10 +1,11 @@package promptimport (- "errors""fmt""os"+ "emperror.dev/errors"+"charm.land/bubbles/v2/list"tea "charm.land/bubbletea/v2""github.com/charmbracelet/x/term"@@ -18,7 +19,7 @@ func IsInteractive() bool {// Select prompts the user to select from a list of options and returns the zero-based index.func Select(label string, options []string) (int, error) {if len(options) == 0 {- return -1, fmt.Errorf("no %s options available", label)+ return -1, errors.Errorf("no %s options available", label)}if !IsInteractive() {return -1, errors.New("interactive terminal required")diff --git a/cli/internal/runtime/context.go b/cli/internal/runtime/context.goindex 12b15e91f..9fa82c2f7 100644--- a/cli/internal/runtime/context.go+++ b/cli/internal/runtime/context.go@@ -2,11 +2,11 @@ package runtimeimport ("context"- "fmt""strings""sync""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/config"clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -51,7 +51,7 @@ type AppContext struct {func New(opts Options) (*AppContext, error) {cfg, err := config.Load()if err != nil {- return nil, fmt.Errorf("failed to load config: %w", err)+ return nil, errors.WrapIf(err, "failed to load config")}mode := opts.OutputMode@@ -61,7 +61,7 @@ func New(opts Options) (*AppContext, error) {switch mode {case OutputModeText, OutputModeJSON:default:- return nil, fmt.Errorf("invalid output mode %q (expected text or json)", mode)+ return nil, errors.Errorf("invalid output mode %q (expected text or json)", mode)}return &AppContext{diff --git a/cli/internal/types/config.go b/cli/internal/types/config.goindex e0186418a..b350a7b67 100644--- a/cli/internal/types/config.go+++ b/cli/internal/types/config.go@@ -1,9 +1,10 @@package typesimport (- "errors""maps""strings"++ "emperror.dev/errors")// PaginationResourceConfig defines pagination options for a specific resource.diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.goindex c40f88410..2eb8ad683 100644--- a/cli/pkg/admin/apikeys/cmd.go+++ b/cli/pkg/admin/apikeys/cmd.go@@ -1,12 +1,13 @@package apikeysimport (- "errors""fmt""strconv""strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -51,14 +52,14 @@ func parsePermissionGrantsInternal(tokens []string) ([]apikey.PermissionGrant, ecase 3:env := parts[2]if parts[0] == "" || parts[1] == "" || env == "" {- return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)+ return nil, errors.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)}out = append(out, apikey.PermissionGrant{Permission: parts[0] + ":" + parts[1],EnvironmentID: &env,})default:- return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)+ return nil, errors.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)}}return out, nil@@ -85,18 +86,18 @@ var listCmd = &cobra.Command{path := types.Endpoints.ApiKeys()path, err = cmdutil.ApplyPaginationParams(cmd, path, "apikeys", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list API keys: %w", err)+ return errors.WrapIf(err, "failed to list API keys")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[apikey.ApiKey]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to list API keys: %w", err)+ return errors.WrapIf(err, "failed to list API keys")}if jsonOutput {@@ -160,20 +161,20 @@ var createCmd = &cobra.Command{if expiresAtRaw, _ := cmd.Flags().GetString("expires-at"); expiresAtRaw != "" {parsed, err := time.Parse(time.RFC3339, expiresAtRaw)if err != nil {- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)+ return errors.WrapIf(err, "invalid --expires-at format (use RFC3339)")}createReq.ExpiresAt = &parsed}resp, err := c.Post(cmd.Context(), types.Endpoints.ApiKeys(), createReq)if err != nil {- return fmt.Errorf("failed to create API key: %w", err)+ return errors.WrapIf(err, "failed to create API key")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[apikey.ApiKeyCreatedDto]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to create API key: %w", err)+ return errors.WrapIf(err, "failed to create API key")}if jsonOutput {@@ -216,17 +217,17 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.ApiKey(args[0]))if err != nil {- return fmt.Errorf("failed to delete API key: %w", err)+ return errors.WrapIf(err, "failed to delete API key")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete API key: %w", err)+ return errors.WrapIf(err, "failed to delete API key")}if jsonOutput {var result base.ApiResponse[any]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to delete API key: %w", err)+ return errors.WrapIf(err, "failed to delete API key")}return cmdutil.PrintJSON(result.Data)}@@ -249,13 +250,13 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ApiKey(args[0]))if err != nil {- return fmt.Errorf("failed to get API key: %w", err)+ return errors.WrapIf(err, "failed to get API key")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[apikey.ApiKey]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to get API key: %w", err)+ return errors.WrapIf(err, "failed to get API key")}if jsonOutput {@@ -313,7 +314,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("expires-at") && apikeyUpdateExpiresAt != "" {parsedTime, err := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)if err != nil {- return fmt.Errorf("invalid expires-at format (use RFC3339): %w", err)+ return errors.WrapIf(err, "invalid expires-at format (use RFC3339)")}req.ExpiresAt = &parsedTime}@@ -329,17 +330,17 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.ApiKey(args[0]), req)if err != nil {- return fmt.Errorf("failed to update API key: %w", err)+ return errors.WrapIf(err, "failed to update API key")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update API key: %w", err)+ return errors.WrapIf(err, "failed to update API key")}if jsonOutput {var result base.ApiResponse[any]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to update API key: %w", err)+ return errors.WrapIf(err, "failed to update API key")}return cmdutil.PrintJSON(result.Data)}diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.goindex 6e4e193aa..0dc63d897 100644--- a/cli/pkg/admin/events/cmd.go+++ b/cli/pkg/admin/events/cmd.go@@ -4,6 +4,7 @@ import ("encoding/json""fmt"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -41,24 +42,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.Events()path, err = cmdutil.ApplyPaginationParams(cmd, path, "events", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list events: %w", err)+ return errors.WrapIf(err, "failed to list events")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[event.Event]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -103,24 +104,24 @@ var listEnvCmd = &cobra.Command{path := types.Endpoints.EventsEnvironment(c.EnvID())path, err = cmdutil.ApplyPaginationParams(cmd, path, "events", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list environment events: %w", err)+ return errors.WrapIf(err, "failed to list environment events")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[event.Event]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -177,11 +178,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.Event(args[0]))if err != nil {- return fmt.Errorf("failed to delete event: %w", err)+ return errors.WrapIf(err, "failed to delete event")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete event: %w", err)+ return errors.WrapIf(err, "failed to delete event")}output.Success("Event deleted successfully")diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.goindex 4ab12f42c..b884c8e53 100644--- a/cli/pkg/admin/notifications/cmd.go+++ b/cli/pkg/admin/notifications/cmd.go@@ -5,6 +5,7 @@ import ("fmt""strconv"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -43,19 +44,19 @@ var settingsGetCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.NotificationsSettings(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get settings: %w", err)+ return errors.WrapIf(err, "failed to get settings")}defer func() { _ = resp.Body.Close() }()var result []notification.Responseif err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -101,11 +102,11 @@ var settingsDeleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.NotificationSettingsProvider(c.EnvID(), args[0]))if err != nil {- return fmt.Errorf("failed to delete notification settings: %w", err)+ return errors.WrapIf(err, "failed to delete notification settings")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete notification settings: %w", err)+ return errors.WrapIf(err, "failed to delete notification settings")}output.Success("Notification settings for %s deleted successfully", args[0])@@ -126,11 +127,11 @@ var testProviderCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.NotificationsTestProvider(c.EnvID(), args[0]), nil)if err != nil {- return fmt.Errorf("failed to test notification provider: %w", err)+ return errors.WrapIf(err, "failed to test notification provider")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("notification test failed: %w", err)+ return errors.WrapIf(err, "notification test failed")}if jsonOutput {diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.goindex 647b9d157..9646b0390 100644--- a/cli/pkg/admin/oidcmappings/cmd.go+++ b/cli/pkg/admin/oidcmappings/cmd.go@@ -6,6 +6,7 @@ package oidcmappingsimport ("fmt"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -54,13 +55,13 @@ var listCmd = &cobra.Command{}resp, err := c.Get(cmd.Context(), types.Endpoints.OidcRoleMappings())if err != nil {- return fmt.Errorf("failed to list OIDC mappings: %w", err)+ return errors.WrapIf(err, "failed to list OIDC mappings")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]roletypes.OidcRoleMapping]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to list OIDC mappings: %w", err)+ return errors.WrapIf(err, "failed to list OIDC mappings")}if jsonOutput {@@ -106,12 +107,12 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.OidcRoleMappings(), req)if err != nil {- return fmt.Errorf("failed to create OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to create OIDC mapping")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.OidcRoleMapping]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to create OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to create OIDC mapping")}if jsonOutput {@@ -169,11 +170,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.OidcRoleMapping(args[0]), req)if err != nil {- return fmt.Errorf("failed to update OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to update OIDC mapping")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to update OIDC mapping")}output.Success("OIDC mapping updated")return nil@@ -203,11 +204,11 @@ var deleteCmd = &cobra.Command{}resp, err := c.Delete(cmd.Context(), types.Endpoints.OidcRoleMapping(args[0]))if err != nil {- return fmt.Errorf("failed to delete OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to delete OIDC mapping")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete OIDC mapping: %w", err)+ return errors.WrapIf(err, "failed to delete OIDC mapping")}output.Success("OIDC mapping deleted")return nil@@ -221,12 +222,12 @@ func fetchMappingInternal(cmd *cobra.Command, id string) (*roletypes.OidcRoleMap}resp, err := c.Get(cmd.Context(), types.Endpoints.OidcRoleMapping(id))if err != nil {- return nil, fmt.Errorf("failed to load current mapping: %w", err)+ return nil, errors.WrapIf(err, "failed to load current mapping")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.OidcRoleMapping]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return nil, fmt.Errorf("failed to load current mapping: %w", err)+ return nil, errors.WrapIf(err, "failed to load current mapping")}return &result.Data, nil}diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.goindex b789d4050..e76355c16 100644--- a/cli/pkg/admin/roles/cmd.go+++ b/cli/pkg/admin/roles/cmd.go@@ -6,11 +6,12 @@package rolesimport (- "errors""fmt""strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -67,18 +68,18 @@ var listCmd = &cobra.Command{path := types.Endpoints.Roles()path, err = cmdutil.ApplyPaginationParams(cmd, path, "roles", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list roles: %w", err)+ return errors.WrapIf(err, "failed to list roles")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[roletypes.Role]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to list roles: %w", err)+ return errors.WrapIf(err, "failed to list roles")}if jsonOutput {@@ -118,13 +119,13 @@ var getCmd = &cobra.Command{}resp, err := c.Get(cmd.Context(), types.Endpoints.Role(args[0]))if err != nil {- return fmt.Errorf("failed to get role: %w", err)+ return errors.WrapIf(err, "failed to get role")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.Role]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to get role: %w", err)+ return errors.WrapIf(err, "failed to get role")}if jsonOutput {@@ -177,12 +178,12 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.Roles(), req)if err != nil {- return fmt.Errorf("failed to create role: %w", err)+ return errors.WrapIf(err, "failed to create role")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.Role]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to create role: %w", err)+ return errors.WrapIf(err, "failed to create role")}if jsonOutput {@@ -231,11 +232,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.Role(args[0]), req)if err != nil {- return fmt.Errorf("failed to update role: %w", err)+ return errors.WrapIf(err, "failed to update role")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update role: %w", err)+ return errors.WrapIf(err, "failed to update role")}output.Success("Role updated")@@ -266,11 +267,11 @@ var deleteCmd = &cobra.Command{}resp, err := c.Delete(cmd.Context(), types.Endpoints.Role(args[0]))if err != nil {- return fmt.Errorf("failed to delete role: %w", err)+ return errors.WrapIf(err, "failed to delete role")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete role: %w", err)+ return errors.WrapIf(err, "failed to delete role")}output.Success("Role deleted")return nil@@ -291,13 +292,13 @@ var permissionsCmd = &cobra.Command{}resp, err := c.Get(cmd.Context(), types.Endpoints.RolesAvailablePermissions())if err != nil {- return fmt.Errorf("failed to load permission manifest: %w", err)+ return errors.WrapIf(err, "failed to load permission manifest")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.PermissionsManifest]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to load permission manifest: %w", err)+ return errors.WrapIf(err, "failed to load permission manifest")}if jsonOutput {@@ -330,13 +331,13 @@ var assignmentsCmd = &cobra.Command{}resp, err := c.Get(cmd.Context(), types.Endpoints.UserRoleAssignments(args[0]))if err != nil {- return fmt.Errorf("failed to list assignments: %w", err)+ return errors.WrapIf(err, "failed to list assignments")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]roletypes.RoleAssignment]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to list assignments: %w", err)+ return errors.WrapIf(err, "failed to list assignments")}if jsonOutput {@@ -385,12 +386,12 @@ var assignCmd = &cobra.Command{}resp, err := c.Put(cmd.Context(), types.Endpoints.UserRoleAssignments(args[0]), req)if err != nil {- return fmt.Errorf("failed to set assignments: %w", err)+ return errors.WrapIf(err, "failed to set assignments")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]roletypes.RoleAssignment]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return fmt.Errorf("failed to set assignments: %w", err)+ return errors.WrapIf(err, "failed to set assignments")}if jsonOutput {return cmdutil.PrintJSON(result.Data)@@ -432,12 +433,12 @@ func fetchRoleInternal(cmd *cobra.Command, id string) (*roletypes.Role, error) {}resp, err := c.Get(cmd.Context(), types.Endpoints.Role(id))if err != nil {- return nil, fmt.Errorf("failed to load current role: %w", err)+ return nil, errors.WrapIf(err, "failed to load current role")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[roletypes.Role]if err := cmdutil.DecodeJSON(resp, &result); err != nil {- return nil, fmt.Errorf("failed to load current role: %w", err)+ return nil, errors.WrapIf(err, "failed to load current role")}return &result.Data, nil}diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.goindex b6062ac97..68f7c0b4b 100644--- a/cli/pkg/admin/users/cmd.go+++ b/cli/pkg/admin/users/cmd.go@@ -6,6 +6,7 @@ import ("os""strings"+ "emperror.dev/errors""github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -103,24 +104,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.Users()path, err = cmdutil.ApplyPaginationParams(cmd, path, "users", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list users: %w", err)+ return errors.WrapIf(err, "failed to list users")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[user.User]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -169,7 +170,7 @@ var createCmd = &cobra.Command{fmt.Print("Password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return fmt.Errorf("failed to read password: %w", err)+ return errors.WrapIf(err, "failed to read password")}userCreatePassword = string(bytePassword)fmt.Println()@@ -188,22 +189,22 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.Users(), req)if err != nil {- return fmt.Errorf("failed to create user: %w", err)+ return errors.WrapIf(err, "failed to create user")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create user: %w", err)+ return errors.WrapIf(err, "failed to create user")}var result base.ApiResponse[user.User]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -230,19 +231,19 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.User(args[0]))if err != nil {- return fmt.Errorf("failed to get user: %w", err)+ return errors.WrapIf(err, "failed to get user")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[user.User]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -298,11 +299,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.User(args[0]), req)if err != nil {- return fmt.Errorf("failed to update user: %w", err)+ return errors.WrapIf(err, "failed to update user")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update user: %w", err)+ return errors.WrapIf(err, "failed to update user")}if jsonOutput {@@ -345,11 +346,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.User(args[0]))if err != nil {- return fmt.Errorf("failed to delete user: %w", err)+ return errors.WrapIf(err, "failed to delete user")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete user: %w", err)+ return errors.WrapIf(err, "failed to delete user")}output.Success("User deleted successfully")diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.goindex b50524745..e270af581 100644--- a/cli/pkg/auth/cmd.go+++ b/cli/pkg/auth/cmd.go@@ -2,7 +2,6 @@ package authimport ("encoding/json"- "errors""fmt""io""os"@@ -10,6 +9,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config"@@ -41,27 +42,27 @@ var loginCmd = &cobra.Command{reqBody, err := json.Marshal(auth.OidcDeviceAuthRequest{})if err != nil {- return fmt.Errorf("failed to marshal request: %w", err)+ return errors.WrapIf(err, "failed to marshal request")}resp, err := c.Post(cmd.Context(), types.Endpoints.OIDCDeviceCode(), reqBody)if err != nil {- return fmt.Errorf("device authorization failed: %w", err)+ return errors.WrapIf(err, "device authorization failed")}defer func() { _ = resp.Body.Close() }()bodyBytes, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return errors.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))}var deviceAuth auth.OidcDeviceAuthResponseif err := json.Unmarshal(bodyBytes, &deviceAuth); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Header("Device Login")@@ -80,7 +81,7 @@ var loginCmd = &cobra.Command{tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})if err != nil {- return fmt.Errorf("failed to marshal token request: %w", err)+ return errors.WrapIf(err, "failed to marshal token request")}ticker := time.NewTicker(pollInterval)@@ -99,13 +100,13 @@ var loginCmd = &cobra.Command{tokenResp, err := c.Post(cmd.Context(), types.Endpoints.OIDCDeviceToken(), tokenReqBody)if err != nil {- return fmt.Errorf("device token exchange failed: %w", err)+ return errors.WrapIf(err, "device token exchange failed")}tokenBody, err := io.ReadAll(tokenResp.Body)_ = tokenResp.Body.Close()if err != nil {- return fmt.Errorf("failed to read token response: %w", err)+ return errors.WrapIf(err, "failed to read token response")}if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {@@ -122,13 +123,13 @@ var loginCmd = &cobra.Command{case "access_denied":return errors.New("device authorization denied")default:- return fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))+ return errors.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))}}var tokenResult auth.OidcDeviceTokenResponseif err := json.Unmarshal(tokenBody, &tokenResult); err != nil {- return fmt.Errorf("failed to parse token response: %w", err)+ return errors.WrapIf(err, "failed to parse token response")}if !tokenResult.Success || tokenResult.Token == "" {return errors.New("device token exchange failed: unexpected response from server")@@ -143,7 +144,7 @@ var loginCmd = &cobra.Command{"user": tokenResult.User,}, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -151,13 +152,13 @@ var loginCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}cfg.JWTToken = tokenResult.Tokencfg.RefreshToken = tokenResult.RefreshTokencfg.APIKey = ""if err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save token: %w", err)+ return errors.WrapIf(err, "failed to save token")}output.Success("Login successful")@@ -180,22 +181,22 @@ var logoutCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.AuthLogout(), nil)if err != nil {- return fmt.Errorf("logout failed: %w", err)+ return errors.WrapIf(err, "logout failed")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("logout failed: %w", err)+ return errors.WrapIf(err, "logout failed")}// Clear token from config after successful API logout.cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}cfg.JWTToken = ""cfg.RefreshToken = ""if err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to clear token: %w", err)+ return errors.WrapIf(err, "failed to clear token")}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -227,22 +228,22 @@ var meCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.AuthMe())if err != nil {- return fmt.Errorf("failed to get user info: %w", err)+ return errors.WrapIf(err, "failed to get user info")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to get user info: %w", err)+ return errors.WrapIf(err, "failed to get user info")}var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -251,7 +252,7 @@ var meCmd = &cobra.Command{output.Header("Current User")userBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal user data: %w", err)+ return errors.WrapIf(err, "failed to marshal user data")}fmt.Println(string(userBytes))return nil@@ -270,7 +271,7 @@ var passwordCmd = &cobra.Command{fmt.Print("Current password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return fmt.Errorf("failed to read current password: %w", err)+ return errors.WrapIf(err, "failed to read current password")}currentPassword = string(bytePassword)fmt.Println()@@ -280,7 +281,7 @@ var passwordCmd = &cobra.Command{fmt.Print("New password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return fmt.Errorf("failed to read new password: %w", err)+ return errors.WrapIf(err, "failed to read new password")}newPassword = string(bytePassword)fmt.Println()@@ -298,16 +299,16 @@ var passwordCmd = &cobra.Command{reqBody, err := json.Marshal(changeReq)if err != nil {- return fmt.Errorf("failed to marshal request: %w", err)+ return errors.WrapIf(err, "failed to marshal request")}resp, err := c.Post(cmd.Context(), types.Endpoints.AuthPassword(), reqBody)if err != nil {- return fmt.Errorf("password change failed: %w", err)+ return errors.WrapIf(err, "password change failed")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("password change failed: %w", err)+ return errors.WrapIf(err, "password change failed")}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -334,7 +335,7 @@ var refreshCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}if refreshToken == "" {@@ -343,7 +344,7 @@ var refreshCmd = &cobra.Command{if refreshToken == "" {fmt.Print("Refresh token: ")if _, err := fmt.Scanln(&refreshToken); err != nil {- return fmt.Errorf("failed to read refresh token: %w", err)+ return errors.WrapIf(err, "failed to read refresh token")}}@@ -354,21 +355,21 @@ var refreshCmd = &cobra.Command{reqBody, err := json.Marshal(map[string]string{"refreshToken": refreshToken})if err != nil {- return fmt.Errorf("failed to marshal request: %w", err)+ return errors.WrapIf(err, "failed to marshal request")}resp, err := c.Post(cmd.Context(), types.Endpoints.AuthRefresh(), reqBody)if err != nil {- return fmt.Errorf("token refresh failed: %w", err)+ return errors.WrapIf(err, "token refresh failed")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("token refresh failed: %w", err)+ return errors.WrapIf(err, "token refresh failed")}var result base.ApiResponse[auth.TokenRefreshResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -378,7 +379,7 @@ var refreshCmd = &cobra.Command{"expiresAt": result.Data.ExpiresAt,}, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -391,7 +392,7 @@ var refreshCmd = &cobra.Command{cfg.RefreshToken = result.Data.RefreshToken}if err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save token: %w", err)+ return errors.WrapIf(err, "failed to save token")}output.Success("Token refreshed successfully")@@ -413,11 +414,11 @@ var oidcStatusCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.OIDCStatus())if err != nil {- return fmt.Errorf("failed to get OIDC status: %w", err)+ return errors.WrapIf(err, "failed to get OIDC status")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to get OIDC status: %w", err)+ return errors.WrapIf(err, "failed to get OIDC status")}var result struct {@@ -426,13 +427,13 @@ var oidcStatusCmd = &cobra.Command{MergeAccounts bool `json:"mergeAccounts"`}if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.goindex b0818f469..5f371d3c8 100644--- a/cli/pkg/auth/federated.go+++ b/cli/pkg/auth/federated.go@@ -2,7 +2,6 @@ package authimport ("encoding/json"- "errors""fmt""io""net/http"@@ -11,6 +10,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/ci""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -50,7 +51,7 @@ GitHub Actions example:cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}if strings.TrimSpace(server) != "" {cfg.ServerURL = strings.TrimSpace(server)@@ -84,7 +85,7 @@ GitHub Actions example:cfg.APIKey = ""cfg.RefreshToken = ""if err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save federated token: %w", err)+ return errors.WrapIf(err, "failed to save federated token")}}@@ -100,7 +101,7 @@ GitHub Actions example:"persisted": persist,}, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))case exportOutput:@@ -146,7 +147,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider string, aif strings.TrimSpace(tokenFile) != "" {data, err := os.ReadFile(strings.TrimSpace(tokenFile))if err != nil {- return "", "", fmt.Errorf("failed to read token file: %w", err)+ return "", "", errors.WrapIf(err, "failed to read token file")}token = strings.TrimSpace(string(data))if token == "" {@@ -159,7 +160,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider string, aif tokenStdin || stdinHasDataInternal() {data, err := io.ReadAll(os.Stdin)if err != nil {- return "", "", fmt.Errorf("failed to read token from stdin: %w", err)+ return "", "", errors.WrapIf(err, "failed to read token from stdin")}token = strings.TrimSpace(string(data))if token == "" {@@ -185,21 +186,21 @@ func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjec"Content-Type": "application/x-www-form-urlencoded",})if err != nil {- return nil, fmt.Errorf("federated token exchange failed: %w", err)+ return nil, errors.WrapIf(err, "federated token exchange failed")}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(io.LimitReader(resp.Body, maxFederatedErrorBody))if err != nil {- return nil, fmt.Errorf("failed to read federated token response: %w", err)+ return nil, errors.WrapIf(err, "failed to read federated token response")}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, fmt.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, redactedFederatedExchangeMessageInternal(body))+ return nil, errors.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, redactedFederatedExchangeMessageInternal(body))}var tokenResp federatedtypes.FederatedTokenResponseif err := json.Unmarshal(body, &tokenResp); err != nil {- return nil, fmt.Errorf("failed to parse federated token response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse federated token response")}return &tokenResp, nil}diff --git a/cli/pkg/completion/cmd.go b/cli/pkg/completion/cmd.goindex aeee61b83..fbf5747ae 100644--- a/cli/pkg/completion/cmd.go+++ b/cli/pkg/completion/cmd.go@@ -1,9 +1,9 @@package completionimport (- "fmt""os"+ "emperror.dev/errors""github.com/spf13/cobra")@@ -28,7 +28,7 @@ func NewCommand(root *cobra.Command) *cobra.Command {case "powershell", "pwsh":return root.GenPowerShellCompletionWithDesc(os.Stdout)default:- return fmt.Errorf("unsupported shell %q", args[0])+ return errors.Errorf("unsupported shell %q", args[0])}},}diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.goindex c29b4e52d..a1429583c 100644--- a/cli/pkg/config/cmd.go+++ b/cli/pkg/config/cmd.go@@ -1,7 +1,6 @@package configimport (- "errors""fmt""io""net/http"@@ -11,6 +10,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/config"clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/spf13/cobra"@@ -39,7 +40,7 @@ var configShowCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}path, _ := config.ConfigPath()@@ -118,7 +119,7 @@ Legacy flag syntax (flags shown below) is still supported:RunE: func(cmd *cobra.Command, args []string) error {cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}updated := false@@ -139,7 +140,7 @@ Legacy flag syntax (flags shown below) is still supported:}if err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save config: %w", err)+ return errors.WrapIf(err, "failed to save config")}path, _ := config.ConfigPath()@@ -168,7 +169,7 @@ var configTestCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}if err := cfg.Validate(); err != nil {@@ -181,7 +182,7 @@ var configTestCmd = &cobra.Command{httpClient := &http.Client{Timeout: 10 * time.Second}req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, cfg.ServerURL+"/api/version", nil)if err != nil {- return fmt.Errorf("failed to create request: %w", err)+ return errors.WrapIf(err, "failed to create request")}// Prefer JWT bearer if present, else API key.if cfg.JWTToken != "" {@@ -192,13 +193,13 @@ var configTestCmd = &cobra.Command{resp, err := httpClient.Do(req)if err != nil {- return fmt.Errorf("connection test failed: %w", err)+ return errors.WrapIf(err, "connection test failed")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(resp.Body)- return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))+ return errors.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))}fmt.Println("✓ Connection successful!")@@ -222,7 +223,7 @@ If the config file already exists, this command is a no-op and does not overwritcreated, err := config.InitDefaultFile()if err != nil {- return fmt.Errorf("failed to initialize config: %w", err)+ return errors.WrapIf(err, "failed to initialize config")}if !created {fmt.Printf("Config file already exists at %s (no changes made)\n", path)@@ -251,7 +252,7 @@ This removes the original config file from its previous path.`,backupPath, moved, err := config.BackupFile()if err != nil {- return fmt.Errorf("failed to backup config: %w", err)+ return errors.WrapIf(err, "failed to backup config")}if !moved {fmt.Printf("No config file found at %s (no changes made)\n", path)@@ -380,10 +381,10 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *clitypes.Config) (bool, error)for _, pair := range setResourceLimit {resource, limit, ok := parseResourceLimitPair(pair)if !ok {- return false, fmt.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, errors.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(clitypes.KnownPaginatedResources, ", "))}if limit < 0 {- return false, fmt.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)+ return false, errors.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)}cfg.SetResourceLimit(resource, limit)if limit == 0 {@@ -402,7 +403,7 @@ func applyConfigSetArgs(cfg *clitypes.Config, args []string) (bool, error) {return false, nil}if len(args)%2 != 0 {- return false, fmt.Errorf("expected key/value pairs, got odd number of arguments (%d). Example: `arcane config set server-url http://localhost:3552`", len(args))+ return false, errors.Errorf("expected key/value pairs, got odd number of arguments (%d). Example: `arcane config set server-url http://localhost:3552`", len(args))}updated := false@@ -452,7 +453,7 @@ func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {case "cli-update-channel", "cli_update_channel", "cli-channel", "channel":channel := strings.ToLower(strings.TrimSpace(value))if channel != "stable" && channel != "next" {- return false, fmt.Errorf("invalid cli update channel %q (expected stable or next)", value)+ return false, errors.Errorf("invalid cli update channel %q (expected stable or next)", value)}cfg.CLIUpdateChannel = channelfmt.Printf("Set cli_update_channel = %s\n", channel)@@ -472,10 +473,10 @@ func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {case "resource-limit", "resource_limit":resource, limit, ok := parseResourceLimitPair(value)if !ok {- return false, fmt.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, errors.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(clitypes.KnownPaginatedResources, ", "))}if limit < 0 {- return false, fmt.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)+ return false, errors.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)}cfg.SetResourceLimit(resource, limit)if limit == 0 {@@ -495,13 +496,13 @@ func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {return applyResourceLimitByKey(cfg, key, resource, value)}- return false, fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)+ return false, errors.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)}func applyResourceLimitByKey(cfg *clitypes.Config, key, resourceValue, limitValue string) (bool, error) {resource := clitypes.NormalizePaginatedResource(resourceValue)if resource == "" || !isKnownPaginatedResource(resource) {- return false, fmt.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, errors.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(clitypes.KnownPaginatedResources, ", "))}limit, err := parseLimitValue(key, limitValue)if err != nil {@@ -523,10 +524,10 @@ func isKnownPaginatedResource(resource string) bool {func parseLimitValue(key, value string) (int, error) {parsed, err := strconv.Atoi(strings.TrimSpace(value))if err != nil {- return 0, fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)+ return 0, errors.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)}if parsed < 0 {- return 0, fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, key)+ return 0, errors.Errorf("invalid value %q for key %q (must be >= 0)", value, key)}return parsed, nil}diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.goindex ad83fd303..66c7150f0 100644--- a/cli/pkg/containers/cmd.go+++ b/cli/pkg/containers/cmd.go@@ -3,7 +3,6 @@ package containersimport ("context""encoding/json"- "errors""fmt""io""net/http"@@ -12,6 +11,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -89,19 +90,19 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list containers: %w", err)+ return errors.WrapIf(err, "failed to list containers")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[container.Summary]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -157,13 +158,13 @@ func buildContainersListPath(cmd *cobra.Command, c *client.Client, forceHasUpdatvar err errorpath, err = cmdutil.ApplyPaginationParams(cmd, path, "containers", "limit", containersLimit, 20, "start", containersStart)if err != nil {- return "", fmt.Errorf("failed to build pagination query: %w", err)+ return "", errors.WrapIf(err, "failed to build pagination query")}}parsed, err := url.Parse(path)if err != nil {- return "", fmt.Errorf("failed to parse path: %w", err)+ return "", errors.WrapIf(err, "failed to parse path")}query := parsed.Query()@@ -229,13 +230,13 @@ var containersGetCmd = &cobra.Command{path := types.Endpoints.Container(c.EnvID(), resolved.ID)resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to get container: %w", err)+ return errors.WrapIf(err, "failed to get container")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[container.Details]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resolved = &result.Data}@@ -243,7 +244,7 @@ var containersGetCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -356,23 +357,23 @@ func runContainerPostAction[T any](cmd *cobra.Command, containerRef string, cfgpath := cfg.endpoint(c.EnvID(), resolved.ID)resp, err := c.Post(cmd.Context(), path, nil)if err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}var result base.ApiResponse[T]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -415,13 +416,13 @@ var containersDeleteCmd = &cobra.Command{path := types.Endpoints.Container(c.EnvID(), resolved.ID) + "?force=true"resp, err := c.Delete(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to delete container: %w", err)+ return errors.WrapIf(err, "failed to delete container")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[base.MessageResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if !result.Success {@@ -429,13 +430,13 @@ var containersDeleteCmd = &cobra.Command{if msg == "" {msg = "unknown error"}- return fmt.Errorf("failed to delete container: %s", msg)+ return errors.Errorf("failed to delete container: %s", msg)}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -459,19 +460,19 @@ var containersCountsCmd = &cobra.Command{path := types.Endpoints.ContainersCounts(c.EnvID())resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to get container counts: %w", err)+ return errors.WrapIf(err, "failed to get container counts")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[container.StatusCounts]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -503,10 +504,10 @@ var containersCreateCmd = &cobra.Command{if containerCreateFile != "" {data, err := os.ReadFile(containerCreateFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", containerCreateFile, err)+ return errors.WrapIff(err, "failed to read file %s", containerCreateFile)}if err := json.Unmarshal(data, &req); err != nil {- return fmt.Errorf("failed to parse config file: %w", err)+ return errors.WrapIf(err, "failed to parse config file")}}@@ -584,22 +585,22 @@ var containersCreateCmd = &cobra.Command{path := types.Endpoints.Containers(c.EnvID())resp, err := c.Post(cmd.Context(), path, req)if err != nil {- return fmt.Errorf("failed to create container: %w", err)+ return errors.WrapIf(err, "failed to create container")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create container: %w", err)+ return errors.WrapIf(err, "failed to create container")}var result base.ApiResponse[container.Created]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -729,31 +730,31 @@ func resolveContainer(ctx context.Context, c *client.Client, identifier string,}}- return nil, false, fmt.Errorf("container %q not found; use the container ID or run `arcane containers list`", trimmed)+ return nil, false, errors.Errorf("container %q not found; use the container ID or run `arcane containers list`", trimmed)}func fetchContainerByIdentifier(ctx context.Context, c *client.Client, identifier string) (*container.Details, bool, bool, error) {resp, err := c.Get(ctx, types.Endpoints.Container(c.EnvID(), identifier))if err != nil {- return nil, false, false, fmt.Errorf("failed to resolve container %q: %w", identifier, err)+ return nil, false, false, errors.WrapIff(err, "failed to resolve container %q", identifier)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, false, false, fmt.Errorf("failed to read container response: %w", err)+ return nil, false, false, errors.WrapIf(err, "failed to read container response")}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[container.Details]if err := json.Unmarshal(body, &result); err != nil {- return nil, false, false, fmt.Errorf("failed to parse container response: %w", err)+ return nil, false, false, errors.WrapIf(err, "failed to parse container response")}return &result.Data, true, true, nil}if resp.StatusCode != http.StatusNotFound {- return nil, false, false, fmt.Errorf("failed to resolve container %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, false, false, errors.Errorf("failed to resolve container %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))}return nil, false, false, nil@@ -763,22 +764,22 @@ func searchContainerMatches(ctx context.Context, c *client.Client, identifier stsearchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Containers(c.EnvID()), url.QueryEscape(identifier), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return nil, fmt.Errorf("failed to search containers: %w", err)+ return nil, errors.WrapIf(err, "failed to search containers")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return nil, fmt.Errorf("failed to read containers response: %w", err)+ return nil, errors.WrapIf(err, "failed to read containers response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return nil, fmt.Errorf("failed to search containers (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return nil, errors.Errorf("failed to search containers (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result base.Paginated[container.Summary]if err := json.Unmarshal(searchBody, &result); err != nil {- return nil, fmt.Errorf("failed to parse containers response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse containers response")}identifierLower := strings.ToLower(identifier)@@ -801,10 +802,10 @@ func selectContainerMatch(matches []container.Summary, identifier string, allowP}if !allowPrompt {- return nil, fmt.Errorf("multiple containers match %q; use the container ID or run `arcane containers list`", identifier)+ return nil, errors.Errorf("multiple containers match %q; use the container ID or run `arcane containers list`", identifier)}if len(matches) > maxPromptOptions {- return nil, fmt.Errorf("multiple containers match %q (%d results); refine your query or use the container ID", identifier, len(matches))+ return nil, errors.Errorf("multiple containers match %q (%d results); refine your query or use the container ID", identifier, len(matches))}options := make([]string, 0, len(matches))@@ -833,12 +834,12 @@ func fallbackContainerByIDPrefix(ctx context.Context, c *client.Client, identififallbackPath := fmt.Sprintf("%s?limit=%d", types.Endpoints.Containers(c.EnvID()), 200)fallbackResp, err := c.Get(ctx, fallbackPath)if err != nil {- return nil, false, fmt.Errorf("failed to search containers: %w", err)+ return nil, false, errors.WrapIf(err, "failed to search containers")}fallbackBody, err := io.ReadAll(fallbackResp.Body)_ = fallbackResp.Body.Close()if err != nil {- return nil, false, fmt.Errorf("failed to read containers response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to read containers response")}if fallbackResp.StatusCode < 200 || fallbackResp.StatusCode >= 300 {return nil, false, nil@@ -846,7 +847,7 @@ func fallbackContainerByIDPrefix(ctx context.Context, c *client.Client, identifivar fallbackResult base.Paginated[container.Summary]if err := json.Unmarshal(fallbackBody, &fallbackResult); err != nil {- return nil, false, fmt.Errorf("failed to parse containers response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to parse containers response")}for _, item := range fallbackResult.Data {if strings.HasPrefix(strings.ToLower(item.ID), identifierLower) {diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.goindex 9f408dd12..cadd6d67d 100644--- a/cli/pkg/doctor/cmd.go+++ b/cli/pkg/doctor/cmd.go@@ -2,10 +2,11 @@ package doctorimport ("encoding/json"- "errors""fmt""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/output"runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"@@ -106,7 +107,7 @@ var DoctorCmd = &cobra.Command{if jsonOutput || app.IsJSON() {b, err := json.MarshalIndent(rep, "", " ")if err != nil {- return fmt.Errorf("failed to marshal doctor output: %w", err)+ return errors.WrapIf(err, "failed to marshal doctor output")}fmt.Println(string(b))} else {diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.goindex 31c19986c..5a1f23662 100644--- a/cli/pkg/environments/cmd.go+++ b/cli/pkg/environments/cmd.go@@ -2,12 +2,13 @@ package environmentsimport ("encoding/json"- "errors""fmt""sort""strconv""strings"+ "emperror.dev/errors"+"charm.land/lipgloss/v2""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -62,24 +63,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.Environments()path, err = cmdutil.ApplyPaginationParams(cmd, path, "environments", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list environments: %w", err)+ return errors.WrapIf(err, "failed to list environments")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[environment.Environment]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -132,11 +133,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.Environment(args[0]))if err != nil {- return fmt.Errorf("failed to delete environment: %w", err)+ return errors.WrapIf(err, "failed to delete environment")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete environment: %w", err)+ return errors.WrapIf(err, "failed to delete environment")}output.Success("Environment deleted successfully")@@ -157,19 +158,19 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.Environment(args[0]))if err != nil {- return fmt.Errorf("failed to get environment: %w", err)+ return errors.WrapIf(err, "failed to get environment")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[environment.Environment]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(buildEnvironmentPayloadInternal(result.Data), "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -198,11 +199,11 @@ var testCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.EnvironmentTest(args[0]), nil)if err != nil {- return fmt.Errorf("failed to test environment: %w", err)+ return errors.WrapIf(err, "failed to test environment")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to test environment: %w", err)+ return errors.WrapIf(err, "failed to test environment")}if jsonOutput {@@ -232,7 +233,7 @@ var switchCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}c, err := client.NewFromConfig()@@ -243,13 +244,13 @@ var switchCmd = &cobra.Command{path := fmt.Sprintf("%s?limit=%d", types.Endpoints.Environments(), 200)resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list environments: %w", err)+ return errors.WrapIf(err, "failed to list environments")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[environment.Environment]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if len(result.Data) == 0 {@@ -321,7 +322,7 @@ var switchCmd = &cobra.Command{cfg.DefaultEnvironment = selected.IDif err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save config: %w", err)+ return errors.WrapIf(err, "failed to save config")}output.Success("Default environment set to %s", selected.ID)@@ -363,22 +364,22 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.Environment(args[0]), req)if err != nil {- return fmt.Errorf("failed to update environment: %w", err)+ return errors.WrapIf(err, "failed to update environment")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update environment: %w", err)+ return errors.WrapIf(err, "failed to update environment")}var result base.ApiResponse[environment.Environment]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(buildEnvironmentPayloadInternal(result.Data), "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -406,11 +407,11 @@ var versionCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.EnvironmentVersion(args[0]))if err != nil {- return fmt.Errorf("failed to get environment version: %w", err)+ return errors.WrapIf(err, "failed to get environment version")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to get environment version: %w", err)+ return errors.WrapIf(err, "failed to get environment version")}var result struct {@@ -424,13 +425,13 @@ var versionCmd = &cobra.Command{UpdateAvailable bool `json:"updateAvailable"`}if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/generate/api_key.go b/cli/pkg/generate/api_key.goindex f19013a5a..6ebc7802b 100644--- a/cli/pkg/generate/api_key.go+++ b/cli/pkg/generate/api_key.go@@ -5,6 +5,7 @@ import ("encoding/hex""fmt"+ "emperror.dev/errors""github.com/spf13/cobra")@@ -29,7 +30,7 @@ func init() {func GenerateAPIKey() (string, error) {keyBytes := make([]byte, apiKeyLength)if _, err := crand.Read(keyBytes); err != nil {- return "", fmt.Errorf("failed to generate API key: %w", err)+ return "", errors.WrapIf(err, "failed to generate API key")}return apiKeyPrefix + hex.EncodeToString(keyBytes), nildiff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.goindex 67a328653..8c992633a 100644--- a/cli/pkg/generate/certs.go+++ b/cli/pkg/generate/certs.go@@ -7,7 +7,6 @@ import ("crypto/x509""crypto/x509/pkix""encoding/pem"- "errors""fmt""math/big""net"@@ -17,6 +16,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/spf13/cobra""go.getarcane.app/sys/atomic")@@ -72,7 +73,7 @@ func init() {func generateMTLSOutputInternal() error {outDir, err := filepath.Abs(strings.TrimSpace(mtlsOutDir))if err != nil {- return fmt.Errorf("failed to resolve output directory: %w", err)+ return errors.WrapIf(err, "failed to resolve output directory")}paths, err := generateEdgeMTLSBundleInternal(outDir, strings.TrimSpace(mtlsEnvID), strings.TrimSpace(mtlsAppURL))@@ -97,7 +98,7 @@ func generateMTLSOutputInternal() error {func generateTLSOutputInternal() error {outDir, err := filepath.Abs(strings.TrimSpace(tlsOutDir))if err != nil {- return fmt.Errorf("failed to resolve output directory: %w", err)+ return errors.WrapIf(err, "failed to resolve output directory")}paths, err := generateServerTLSBundleInternal(outDir, strings.TrimSpace(tlsCommonName), tlsHosts, strings.TrimSpace(tlsCertName), strings.TrimSpace(tlsKeyName))@@ -131,12 +132,12 @@ func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMreturn nil, errors.New("env ID is required")}if err := os.MkdirAll(outDir, 0o755); err != nil {- return nil, fmt.Errorf("failed to create output directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create output directory")}caKey, err := GenerateP384PrivateKey()if err != nil {- return nil, fmt.Errorf("failed to generate CA private key: %w", err)+ return nil, errors.WrapIf(err, "failed to generate CA private key")}caTemplate, err := NewEdgeMTLSCATemplate()if err != nil {@@ -145,12 +146,12 @@ func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMcaDER, err := x509.CreateCertificate(crand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)if err != nil {- return nil, fmt.Errorf("failed to create CA certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to create CA certificate")}clientKey, err := GenerateP384PrivateKey()if err != nil {- return nil, fmt.Errorf("failed to generate client private key: %w", err)+ return nil, errors.WrapIf(err, "failed to generate client private key")}trustDomain := EdgeMTLSTrustDomain(appURL)dnsSANs := []string{"arcane-agent"}@@ -164,11 +165,11 @@ func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMcaCert, err := x509.ParseCertificate(caDER)if err != nil {- return nil, fmt.Errorf("failed to parse generated CA certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to parse generated CA certificate")}clientDER, err := x509.CreateCertificate(crand.Reader, clientTemplate, caCert, &clientKey.PublicKey, caKey)if err != nil {- return nil, fmt.Errorf("failed to create client certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to create client certificate")}paths := &edgeMTLSPaths{@@ -200,12 +201,12 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,return nil, errors.New("key file name is required")}if err := os.MkdirAll(outDir, 0o755); err != nil {- return nil, fmt.Errorf("failed to create output directory: %w", err)+ return nil, errors.WrapIf(err, "failed to create output directory")}privateKey, err := GenerateP384PrivateKey()if err != nil {- return nil, fmt.Errorf("failed to generate server private key: %w", err)+ return nil, errors.WrapIf(err, "failed to generate server private key")}template, err := NewServerTLSTemplate(commonName, hosts)@@ -215,7 +216,7 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,certDER, err := x509.CreateCertificate(crand.Reader, template, template, &privateKey.PublicKey, privateKey)if err != nil {- return nil, fmt.Errorf("failed to create server certificate: %w", err)+ return nil, errors.WrapIf(err, "failed to create server certificate")}paths := &serverTLSPaths{@@ -355,7 +356,7 @@ func randomSerialInternal() (*big.Int, error) {limit := new(big.Int).Lsh(big.NewInt(1), 128)serial, err := crand.Int(crand.Reader, limit)if err != nil {- return nil, fmt.Errorf("failed to generate certificate serial: %w", err)+ return nil, errors.WrapIf(err, "failed to generate certificate serial")}return serial, nil}@@ -363,7 +364,7 @@ func randomSerialInternal() (*big.Int, error) {func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, privateKey *ecdsa.PrivateKey) error {keyDER, err := x509.MarshalECPrivateKey(privateKey)if err != nil {- return fmt.Errorf("failed to marshal EC private key: %w", err)+ return errors.WrapIf(err, "failed to marshal EC private key")}if err := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); err != nil {return err@@ -377,7 +378,7 @@ func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, prfunc writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})if pemBytes == nil {- return fmt.Errorf("failed to encode PEM file %s", path)+ return errors.Errorf("failed to encode PEM file %s", path)}return atomic.WriteFile(path, pemBytes, perm)}diff --git a/cli/pkg/generate/secret.go b/cli/pkg/generate/secret.goindex 4297ba39b..3e15967ed 100644--- a/cli/pkg/generate/secret.go+++ b/cli/pkg/generate/secret.go@@ -1,11 +1,12 @@package generateimport (- crand "crypto/rand"+ "crypto/rand""encoding/base64""encoding/hex""fmt"+ "emperror.dev/errors""github.com/spf13/cobra")@@ -31,13 +32,13 @@ func init() {func generateSecrets() error {encryptionKey := make([]byte, secretLength)- if _, err := crand.Read(encryptionKey); err != nil {- return fmt.Errorf("failed to generate encryption key: %w", err)+ if _, err := rand.Read(encryptionKey); err != nil {+ return errors.WrapIf(err, "failed to generate encryption key")}jwtSecret := make([]byte, secretLength)- if _, err := crand.Read(jwtSecret); err != nil {- return fmt.Errorf("failed to generate JWT secret: %w", err)+ if _, err := rand.Read(jwtSecret); err != nil {+ return errors.WrapIf(err, "failed to generate JWT secret")}switch secretFormat {@@ -52,7 +53,7 @@ func generateSecrets() error {case "all":printAllFormats(encryptionKey, jwtSecret)default:- return fmt.Errorf("unknown format: %s (supported: base64, hex, env, docker, all)", secretFormat)+ return errors.Errorf("unknown format: %s (supported: base64, hex, env, docker, all)", secretFormat)}return nildiff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.goindex 2d4351327..381c4191d 100644--- a/cli/pkg/gitops/cmd.go+++ b/cli/pkg/gitops/cmd.go@@ -3,13 +3,14 @@ package gitopsimport ("context""encoding/json"- "errors""fmt""io""net/http""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -60,24 +61,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.GitOpsSyncs(c.EnvID())path, err = cmdutil.ApplyPaginationParams(cmd, path, "gitops-syncs", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list gitops syncs: %w", err)+ return errors.WrapIf(err, "failed to list gitops syncs")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[gitops.GitOpsSync]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -146,23 +147,23 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncs(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to create gitops sync: %w", err)+ return errors.WrapIf(err, "failed to create gitops sync")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create gitops sync: %w", err)+ return errors.WrapIf(err, "failed to create gitops sync")}var result base.ApiResponse[gitops.GitOpsSync]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -193,13 +194,13 @@ var getCmd = &cobra.Command{if !complete {resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to get gitops sync: %w", err)+ return errors.WrapIf(err, "failed to get gitops sync")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.GitOpsSync]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resolved = &result.Data}@@ -207,7 +208,7 @@ var getCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -275,12 +276,12 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID), req)if err != nil {- return fmt.Errorf("failed to update gitops sync: %w", err)+ return errors.WrapIf(err, "failed to update gitops sync")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update gitops sync: %w", err)+ return errors.WrapIf(err, "failed to update gitops sync")}output.Success("GitOps sync %s updated successfully", resolved.Name)@@ -322,11 +323,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to delete gitops sync: %w", err)+ return errors.WrapIf(err, "failed to delete gitops sync")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete gitops sync: %w", err)+ return errors.WrapIf(err, "failed to delete gitops sync")}output.Success("GitOps sync %s deleted successfully", resolved.Name)@@ -352,19 +353,19 @@ var statusCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSyncStatus(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to get gitops sync status: %w", err)+ return errors.WrapIf(err, "failed to get gitops sync status")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.SyncStatus]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -410,19 +411,19 @@ var syncCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)if err != nil {- return fmt.Errorf("failed to trigger gitops sync: %w", err)+ return errors.WrapIf(err, "failed to trigger gitops sync")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.SyncResult]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -437,7 +438,7 @@ var syncCmd = &cobra.Command{if result.Data.Error != nil {errMsg = *result.Data.Error}- return fmt.Errorf("sync failed: %s %s", result.Data.Message, errMsg)+ return errors.Errorf("sync failed: %s %s", result.Data.Message, errMsg)},}@@ -459,20 +460,20 @@ var filesCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSyncFiles(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to get gitops sync files: %w", err)+ return errors.WrapIf(err, "failed to get gitops sync files")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.BrowseResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}files := result.Data.Filesif jsonOutput {resultBytes, err := json.MarshalIndent(files, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -514,23 +515,23 @@ var importCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncsImport(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to import gitops sync: %w", err)+ return errors.WrapIf(err, "failed to import gitops sync")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to import gitops sync: %w", err)+ return errors.WrapIf(err, "failed to import gitops sync")}var result base.ApiResponse[gitops.ImportGitOpsSyncResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -625,25 +626,25 @@ func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string,resp, err := c.Get(ctx, types.Endpoints.GitOpsSync(c.EnvID(), trimmed))if err != nil {- return nil, false, fmt.Errorf("failed to resolve gitops sync %q: %w", trimmed, err)+ return nil, false, errors.WrapIff(err, "failed to resolve gitops sync %q", trimmed)}bodyBytes, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, false, fmt.Errorf("failed to read gitops sync response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to read gitops sync response")}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[gitops.GitOpsSync]if err := json.Unmarshal(bodyBytes, &result); err != nil {- return nil, false, fmt.Errorf("failed to parse gitops sync response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to parse gitops sync response")}return &result.Data, true, nil}if resp.StatusCode != http.StatusNotFound {- return nil, false, fmt.Errorf("failed to resolve gitops sync %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return nil, false, errors.Errorf("failed to resolve gitops sync %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))}identifierLower := strings.ToLower(trimmed)@@ -651,22 +652,22 @@ func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string,searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.GitOpsSyncs(c.EnvID()), url.QueryEscape(trimmed), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return nil, false, fmt.Errorf("failed to search gitops syncs: %w", err)+ return nil, false, errors.WrapIf(err, "failed to search gitops syncs")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return nil, false, fmt.Errorf("failed to read gitops syncs response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to read gitops syncs response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return nil, false, fmt.Errorf("failed to search gitops syncs (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return nil, false, errors.Errorf("failed to search gitops syncs (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result base.Paginated[gitops.GitOpsSync]if err := json.Unmarshal(searchBody, &result); err != nil {- return nil, false, fmt.Errorf("failed to parse gitops syncs response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to parse gitops syncs response")}matches := make([]gitops.GitOpsSync, 0)@@ -682,10 +683,10 @@ func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string,if len(matches) > 1 {if !allowPrompt {- return nil, false, fmt.Errorf("multiple gitops syncs match %q; use the sync ID or run `arcane gitops list`", trimmed)+ return nil, false, errors.Errorf("multiple gitops syncs match %q; use the sync ID or run `arcane gitops list`", trimmed)}if len(matches) > maxPromptOptions {- return nil, false, fmt.Errorf("multiple gitops syncs match %q (%d results); refine your query or use the sync ID", trimmed, len(matches))+ return nil, false, errors.Errorf("multiple gitops syncs match %q (%d results); refine your query or use the sync ID", trimmed, len(matches))}options := make([]string, 0, len(matches))@@ -703,7 +704,7 @@ func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string,return &matches[choice], false, nil}- return nil, false, fmt.Errorf("gitops sync %q not found; use the sync ID or run `arcane gitops list`", trimmed)+ return nil, false, errors.Errorf("gitops sync %q not found; use the sync ID or run `arcane gitops list`", trimmed)}func gitOpsSyncMatches(item gitops.GitOpsSync, identifierLower, original string) bool {diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.goindex e8699c570..56369c0aa 100644--- a/cli/pkg/images/cmd.go+++ b/cli/pkg/images/cmd.go@@ -33,7 +33,6 @@ package imagesimport ("context""encoding/json"- "errors""fmt""io""mime/multipart"@@ -45,6 +44,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/fatih/color""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -97,7 +98,7 @@ var imagesListCmd = &cobra.Command{// Parse the path to handle query paramsu, err := url.Parse(path)if err != nil {- return fmt.Errorf("failed to parse endpoint path: %w", err)+ return errors.WrapIf(err, "failed to parse endpoint path")}q := u.Query()@@ -114,20 +115,20 @@ var imagesListCmd = &cobra.Command{u.RawQuery = q.Encode()path, err = cmdutil.ApplyPaginationParams(cmd, u.String(), "images", "limit", imagesLimit, 0, "start", imagesStart)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}log.Debugf("Listing images from: %s", path)resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list images: %w", err)+ return errors.WrapIf(err, "failed to list images")}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(body))@@ -146,7 +147,7 @@ var imagesListCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}result.Data = filterImagesByUsage(result.Data, imagesInUseOnly, imagesUnusedOnly)result.Pagination.TotalItems = int64(len(result.Data))@@ -154,7 +155,7 @@ var imagesListCmd = &cobra.Command{if cmdutil.JSONOutputEnabled(cmd) {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -208,13 +209,13 @@ var imagesGetCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to get image: %w", err)+ return errors.WrapIf(err, "failed to get image")}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(body))@@ -230,7 +231,7 @@ var imagesGetCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Header("Image Details")@@ -303,7 +304,7 @@ var imagesRemoveCmd = &cobra.Command{if removeForce {u, err := url.Parse(path)if err != nil {- return fmt.Errorf("failed to parse path: %w", err)+ return errors.WrapIf(err, "failed to parse path")}q := u.Query()q.Set("force", "true")@@ -315,17 +316,17 @@ var imagesRemoveCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to remove image: %w", err)+ return errors.WrapIf(err, "failed to remove image")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return errors.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))}body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(body))@@ -343,7 +344,7 @@ var imagesRemoveCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Success("%s", result.Data.Message)@@ -378,19 +379,19 @@ var imagesPullCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), path, requestBody)if err != nil {- return fmt.Errorf("failed to pull image: %w", err)+ return errors.WrapIf(err, "failed to pull image")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("failed to pull image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return errors.Errorf("failed to pull image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))}// Stream the responseif cmdutil.JSONOutputEnabled(cmd) {_, err = io.Copy(cmd.OutOrStdout(), resp.Body)if err != nil {- return fmt.Errorf("failed to read pull stream: %w", err)+ return errors.WrapIf(err, "failed to read pull stream")}return nil}@@ -416,14 +417,14 @@ var imagesPullCmd = &cobra.Command{if err == io.EOF {break}- return fmt.Errorf("failed to decode stream: %w", err)+ return errors.WrapIf(err, "failed to decode stream")}if event.Error != "" {if progressUI != nil {progressUI.Stop()}- return fmt.Errorf("pull error: %s", event.Error)+ return errors.Errorf("pull error: %s", event.Error)}if event.Status == "Downloading" && event.ProgressDetail.Total > 0 {@@ -504,17 +505,17 @@ var imagesPruneCmd = &cobra.Command{}if err != nil {- return fmt.Errorf("failed to prune images: %w", err)+ return errors.WrapIf(err, "failed to prune images")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return errors.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))}body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(body))@@ -533,7 +534,7 @@ var imagesPruneCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Success("Pruned %d images, reclaimed %s", len(result.Data.ImagesDeleted), size.Capacity(result.Data.SpaceReclaimed).String())@@ -559,13 +560,13 @@ var imagesCountsCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to get image counts: %w", err)+ return errors.WrapIf(err, "failed to get image counts")}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(body))@@ -581,7 +582,7 @@ var imagesCountsCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Header("Image Usage Counts")@@ -617,12 +618,12 @@ var imagesUploadCmd = &cobra.Command{// Open the filefile, err := os.Open(filePath)if err != nil {- return fmt.Errorf("failed to open file: %w", err)+ return errors.WrapIf(err, "failed to open file")}defer func() { _ = file.Close() }()fileInfo, err := file.Stat()if err != nil {- return fmt.Errorf("failed to stat file: %w", err)+ return errors.WrapIf(err, "failed to stat file")}pr, pw := io.Pipe()@@ -643,15 +644,15 @@ var imagesUploadCmd = &cobra.Command{go func() {part, err := writer.CreateFormFile("file", filepath.Base(filePath))if err != nil {- _ = pw.CloseWithError(fmt.Errorf("failed to create form file: %w", err))+ _ = pw.CloseWithError(errors.WrapIf(err, "failed to create form file"))return}if _, err := io.Copy(part, file); err != nil {- _ = pw.CloseWithError(fmt.Errorf("failed to copy file: %w", err))+ _ = pw.CloseWithError(errors.WrapIf(err, "failed to copy file"))return}if err := writer.Close(); err != nil {- _ = pw.CloseWithError(fmt.Errorf("failed to close multipart writer: %w", err))+ _ = pw.CloseWithError(errors.WrapIf(err, "failed to close multipart writer"))return}_ = pw.Close()@@ -664,18 +665,18 @@ var imagesUploadCmd = &cobra.Command{resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, path, requestBody, headers)if err != nil {- return fmt.Errorf("failed to upload image: %w", err)+ return errors.WrapIf(err, "failed to upload image")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errorBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("failed to upload image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errorBody)))+ return errors.Errorf("failed to upload image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errorBody)))}respBody, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}log.Debugf("Response body: %s", string(respBody))@@ -691,11 +692,11 @@ var imagesUploadCmd = &cobra.Command{}if err := json.Unmarshal(respBody, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if !result.Success {- return fmt.Errorf("upload failed: %s", string(respBody))+ return errors.Errorf("upload failed: %s", string(respBody))}output.Success("Image uploaded successfully")@@ -770,19 +771,19 @@ func resolveImageID(ctx context.Context, c *client.Client, identifier string, al}}- return "", fmt.Errorf("image %q not found; use the image ID or run `arcane images list`", trimmed)+ return "", errors.Errorf("image %q not found; use the image ID or run `arcane images list`", trimmed)}func resolveImageByID(ctx context.Context, c *client.Client, identifier string) (string, bool, error) {resp, err := c.Get(ctx, types.Endpoints.Image(c.EnvID(), identifier))if err != nil {- return "", false, fmt.Errorf("failed to resolve image %q: %w", identifier, err)+ return "", false, errors.WrapIff(err, "failed to resolve image %q", identifier)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return "", false, fmt.Errorf("failed to read image response: %w", err)+ return "", false, errors.WrapIf(err, "failed to read image response")}if resp.StatusCode == http.StatusOK {@@ -791,16 +792,16 @@ func resolveImageByID(ctx context.Context, c *client.Client, identifier string)Data image.DetailSummary `json:"data"`}if err := json.Unmarshal(body, &result); err != nil {- return "", false, fmt.Errorf("failed to parse image response: %w", err)+ return "", false, errors.WrapIf(err, "failed to parse image response")}if result.Data.ID == "" {- return "", false, fmt.Errorf("image lookup for %q returned empty ID", identifier)+ return "", false, errors.Errorf("image lookup for %q returned empty ID", identifier)}return result.Data.ID, true, nil}if resp.StatusCode != http.StatusNotFound {- return "", false, fmt.Errorf("failed to resolve image %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))+ return "", false, errors.Errorf("failed to resolve image %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))}return "", false, nil@@ -827,17 +828,17 @@ func searchImageMatches(ctx context.Context, c *client.Client, term, trimmed strsearchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Images(c.EnvID()), url.QueryEscape(term), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return nil, fmt.Errorf("failed to search images: %w", err)+ return nil, errors.WrapIf(err, "failed to search images")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return nil, fmt.Errorf("failed to read images response: %w", err)+ return nil, errors.WrapIf(err, "failed to read images response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return nil, fmt.Errorf("failed to search images (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return nil, errors.Errorf("failed to search images (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result struct {@@ -845,7 +846,7 @@ func searchImageMatches(ctx context.Context, c *client.Client, term, trimmed strData []image.Summary `json:"data"`}if err := json.Unmarshal(searchBody, &result); err != nil {- return nil, fmt.Errorf("failed to parse images response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse images response")}return filterImageMatches(result.Data, trimmed), nil@@ -907,10 +908,10 @@ func selectImageMatchID(matches []image.Summary, trimmed string, allowPrompt boo}if !allowPrompt {- return "", false, fmt.Errorf("multiple images match %q; use the image ID or run `arcane images list`", trimmed)+ return "", false, errors.Errorf("multiple images match %q; use the image ID or run `arcane images list`", trimmed)}if len(matches) > maxPromptOptions {- return "", false, fmt.Errorf("multiple images match %q (%d results); refine your query or use the image ID", trimmed, len(matches))+ return "", false, errors.Errorf("multiple images match %q (%d results); refine your query or use the image ID", trimmed, len(matches))}options := make([]string, 0, len(matches))diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.goindex a75aeb559..1dbbbfd59 100644--- a/cli/pkg/images/updates/cmd.go+++ b/cli/pkg/images/updates/cmd.go@@ -5,6 +5,7 @@ import ("fmt""strconv"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -33,18 +34,18 @@ var checkCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ImageUpdatesCheck(c.EnvID(), args[0]))if err != nil {- return fmt.Errorf("failed to check updates: %w", err)+ return errors.WrapIf(err, "failed to check updates")}result, err := client.DecodeResponseStrict[imageupdate.Response](resp)if err != nil {- return fmt.Errorf("failed to check updates: %w", err)+ return errors.WrapIf(err, "failed to check updates")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -76,18 +77,18 @@ var checkAllCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.ImageUpdatesCheckAll(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to check all updates: %w", err)+ return errors.WrapIf(err, "failed to check all updates")}result, err := client.DecodeResponseStrict[imageupdate.BatchResponse](resp)if err != nil {- return fmt.Errorf("failed to check all updates: %w", err)+ return errors.WrapIf(err, "failed to check all updates")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -120,18 +121,18 @@ var checkImageCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ImageUpdatesCheckById(c.EnvID(), args[0]))if err != nil {- return fmt.Errorf("failed to check image update: %w", err)+ return errors.WrapIf(err, "failed to check image update")}result, err := client.DecodeResponseStrict[imageupdate.Response](resp)if err != nil {- return fmt.Errorf("failed to check image update: %w", err)+ return errors.WrapIf(err, "failed to check image update")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -162,18 +163,18 @@ var summaryCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ImageUpdatesSummary(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get summary: %w", err)+ return errors.WrapIf(err, "failed to get summary")}result, err := client.DecodeResponseStrict[imageupdate.Summary](resp)if err != nil {- return fmt.Errorf("failed to get summary: %w", err)+ return errors.WrapIf(err, "failed to get summary")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.goindex bee51341d..49b7a5752 100644--- a/cli/pkg/jobs/cmd.go+++ b/cli/pkg/jobs/cmd.go@@ -2,9 +2,10 @@ package jobsimport ("encoding/json"- "errors""fmt"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -35,22 +36,22 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.JobSchedules(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get job schedules: %w", err)+ return errors.WrapIf(err, "failed to get job schedules")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to get job schedules: %w", err)+ return errors.WrapIf(err, "failed to get job schedules")}var cfg jobschedule.Configif err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {b, err := json.MarshalIndent(cfg, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(b))return nil@@ -97,19 +98,19 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.JobSchedules(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to update job schedules: %w", err)+ return errors.WrapIf(err, "failed to update job schedules")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[jobschedule.Config]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {b, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(b))return nildiff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.goindex 89a982ceb..98a28a6b4 100644--- a/cli/pkg/networks/cmd.go+++ b/cli/pkg/networks/cmd.go@@ -3,13 +3,14 @@ package networksimport ("context""encoding/json"- "errors""fmt""io""net/http""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -55,18 +56,18 @@ var listCmd = &cobra.Command{path := types.Endpoints.Networks(c.EnvID())path, err = cmdutil.ApplyPaginationParams(cmd, path, "networks", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list networks: %w", err)+ return errors.WrapIf(err, "failed to list networks")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[network.Summary]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}result.Data = filterNetworksByUsage(result.Data, inUseOnlyFlag, unusedOnlyFlag)result.Pagination.TotalItems = int64(len(result.Data))@@ -74,7 +75,7 @@ var listCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -122,19 +123,19 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.Network(c.EnvID(), resolvedID))if err != nil {- return fmt.Errorf("failed to get network: %w", err)+ return errors.WrapIf(err, "failed to get network")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[network.Inspect]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -194,21 +195,21 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.Network(c.EnvID(), resolvedID))if err != nil {- return fmt.Errorf("failed to delete network: %w", err)+ return errors.WrapIf(err, "failed to delete network")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete network: %w", err)+ return errors.WrapIf(err, "failed to delete network")}if jsonOutput {var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -231,19 +232,19 @@ var countsCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.NetworksCounts(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get network counts: %w", err)+ return errors.WrapIf(err, "failed to get network counts")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[network.UsageCounts]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -280,22 +281,22 @@ var pruneCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.NetworksPrune(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to prune networks: %w", err)+ return errors.WrapIf(err, "failed to prune networks")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to prune networks: %w", err)+ return errors.WrapIf(err, "failed to prune networks")}var result base.ApiResponse[network.PruneReport]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -351,46 +352,46 @@ func resolveNetworkID(ctx context.Context, c *client.Client, identifier string,resp, err := c.Get(ctx, types.Endpoints.Network(c.EnvID(), trimmed))if err != nil {- return "", "", fmt.Errorf("failed to resolve network %q: %w", trimmed, err)+ return "", "", errors.WrapIff(err, "failed to resolve network %q", trimmed)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return "", "", fmt.Errorf("failed to read network response: %w", err)+ return "", "", errors.WrapIf(err, "failed to read network response")}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[network.Inspect]if err := json.Unmarshal(body, &result); err != nil {- return "", "", fmt.Errorf("failed to parse network response: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse network response")}return result.Data.ID, result.Data.Name, nil}if resp.StatusCode != http.StatusNotFound {- return "", "", fmt.Errorf("failed to resolve network %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))+ return "", "", errors.Errorf("failed to resolve network %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))}searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Networks(c.EnvID()), url.QueryEscape(trimmed), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return "", "", fmt.Errorf("failed to search networks: %w", err)+ return "", "", errors.WrapIf(err, "failed to search networks")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return "", "", fmt.Errorf("failed to read networks response: %w", err)+ return "", "", errors.WrapIf(err, "failed to read networks response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return "", "", fmt.Errorf("failed to search networks (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return "", "", errors.Errorf("failed to search networks (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result base.Paginated[network.Summary]if err := json.Unmarshal(searchBody, &result); err != nil {- return "", "", fmt.Errorf("failed to parse networks response: %w", err)+ return "", "", errors.WrapIf(err, "failed to parse networks response")}identifierLower := strings.ToLower(trimmed)@@ -407,10 +408,10 @@ func resolveNetworkID(ctx context.Context, c *client.Client, identifier string,if len(matches) > 1 {if !allowPrompt {- return "", "", fmt.Errorf("multiple networks match %q; use the network ID or run `arcane networks list`", trimmed)+ return "", "", errors.Errorf("multiple networks match %q; use the network ID or run `arcane networks list`", trimmed)}if len(matches) > maxPromptOptions {- return "", "", fmt.Errorf("multiple networks match %q (%d results); refine your query or use the network ID", trimmed, len(matches))+ return "", "", errors.Errorf("multiple networks match %q (%d results); refine your query or use the network ID", trimmed, len(matches))}options := make([]string, 0, len(matches))@@ -424,7 +425,7 @@ func resolveNetworkID(ctx context.Context, c *client.Client, identifier string,return matches[choice].ID, matches[choice].Name, nil}- return "", "", fmt.Errorf("network %q not found; use the network ID or run `arcane networks list`", trimmed)+ return "", "", errors.Errorf("network %q not found; use the network ID or run `arcane networks list`", trimmed)}func networkMatches(item network.Summary, identifierLower, original string) bool {diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.goindex df437e2af..88a409964 100644--- a/cli/pkg/projects/cmd.go+++ b/cli/pkg/projects/cmd.go@@ -3,7 +3,6 @@ package projectsimport ("context""encoding/json"- "errors""fmt""io""net/http"@@ -14,6 +13,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -80,19 +81,19 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list projects: %w", err)+ return errors.WrapIf(err, "failed to list projects")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[project.Details]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -150,12 +151,12 @@ func buildProjectsListPath(cmd *cobra.Command, c *client.Client, forceHasUpdateFvar err errorpath, err = cmdutil.ApplyPaginationParams(cmd, path, "projects", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return "", fmt.Errorf("failed to build pagination query: %w", err)+ return "", errors.WrapIf(err, "failed to build pagination query")}parsed, err := url.Parse(path)if err != nil {- return "", fmt.Errorf("failed to parse path: %w", err)+ return "", errors.WrapIf(err, "failed to parse path")}query := parsed.Query()@@ -212,11 +213,11 @@ var destroyCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.ProjectDestroy(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to destroy project: %w", err)+ return errors.WrapIf(err, "failed to destroy project")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to destroy project: %w", err)+ return errors.WrapIf(err, "failed to destroy project")}output.Success("Project %s destroyed successfully", resolved.Name)@@ -244,13 +245,13 @@ var getCmd = &cobra.Command{if !complete {resp, err := c.Get(cmd.Context(), types.Endpoints.Project(c.EnvID(), resolved.ID))if err != nil {- return fmt.Errorf("failed to get project: %w", err)+ return errors.WrapIf(err, "failed to get project")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[project.Details]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resolved = &result.Data}@@ -258,7 +259,7 @@ var getCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -370,11 +371,11 @@ func runProjectPostAction(cmd *cobra.Command, projectRef string, cfg projectPostresp, err := c.Post(cmd.Context(), cfg.endpoint(c.EnvID(), resolved.ID), nil)if err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}output.Success(cfg.successMessage, resolved.Name)@@ -393,7 +394,7 @@ var createCmd = &cobra.Command{composeBytes, err := os.ReadFile(createFile)if err != nil {- return fmt.Errorf("failed to read compose file: %w", err)+ return errors.WrapIf(err, "failed to read compose file")}body := project.CreateProject{@@ -404,7 +405,7 @@ var createCmd = &cobra.Command{if createEnvFile != "" {envBytes, err := os.ReadFile(createEnvFile)if err != nil {- return fmt.Errorf("failed to read env file: %w", err)+ return errors.WrapIf(err, "failed to read env file")}body.EnvContent = new(string(envBytes))}@@ -414,22 +415,22 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.Projects(c.EnvID()), body)if err != nil {- return fmt.Errorf("failed to create project: %w", err)+ return errors.WrapIf(err, "failed to create project")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create project: %w", err)+ return errors.WrapIf(err, "failed to create project")}var result base.ApiResponse[project.CreateReponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -470,7 +471,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("file") {composeBytes, err := os.ReadFile(updateFile)if err != nil {- return fmt.Errorf("failed to read compose file: %w", err)+ return errors.WrapIf(err, "failed to read compose file")}body.ComposeContent = new(string(composeBytes))}@@ -478,28 +479,28 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("env-file") {envBytes, err := os.ReadFile(updateEnvFile)if err != nil {- return fmt.Errorf("failed to read env file: %w", err)+ return errors.WrapIf(err, "failed to read env file")}body.EnvContent = new(string(envBytes))}resp, err := c.Put(cmd.Context(), types.Endpoints.Project(c.EnvID(), resolved.ID), body)if err != nil {- return fmt.Errorf("failed to update project: %w", err)+ return errors.WrapIf(err, "failed to update project")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update project: %w", err)+ return errors.WrapIf(err, "failed to update project")}if jsonOutput {var result base.ApiResponse[project.Details]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -528,7 +529,7 @@ var updateIncludesCmd = &cobra.Command{content, err := os.ReadFile(includesFile)if err != nil {- return fmt.Errorf("failed to read include file: %w", err)+ return errors.WrapIf(err, "failed to read include file")}body := project.UpdateIncludeFile{@@ -538,21 +539,21 @@ var updateIncludesCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.ProjectIncludes(c.EnvID(), resolved.ID), body)if err != nil {- return fmt.Errorf("failed to update include file: %w", err)+ return errors.WrapIf(err, "failed to update include file")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update include file: %w", err)+ return errors.WrapIf(err, "failed to update include file")}if jsonOutput {var result base.ApiResponse[project.Details]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -575,19 +576,19 @@ var countsCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ProjectsCounts(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get project counts: %w", err)+ return errors.WrapIf(err, "failed to get project counts")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[map[string]any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -663,25 +664,25 @@ func resolveProject(ctx context.Context, c *client.Client, identifier string, alresp, err := c.Get(ctx, types.Endpoints.Project(c.EnvID(), trimmed))if err != nil {- return nil, false, fmt.Errorf("failed to resolve project %q: %w", trimmed, err)+ return nil, false, errors.WrapIff(err, "failed to resolve project %q", trimmed)}bodyBytes, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, false, fmt.Errorf("failed to read project response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to read project response")}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[project.Details]if err := json.Unmarshal(bodyBytes, &result); err != nil {- return nil, false, fmt.Errorf("failed to parse project response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to parse project response")}return &result.Data, true, nil}if resp.StatusCode != http.StatusNotFound {- return nil, false, fmt.Errorf("failed to resolve project %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return nil, false, errors.Errorf("failed to resolve project %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))}identifierLower := strings.ToLower(trimmed)@@ -689,22 +690,22 @@ func resolveProject(ctx context.Context, c *client.Client, identifier string, alsearchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Projects(c.EnvID()), url.QueryEscape(trimmed), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return nil, false, fmt.Errorf("failed to search projects: %w", err)+ return nil, false, errors.WrapIf(err, "failed to search projects")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return nil, false, fmt.Errorf("failed to read projects response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to read projects response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return nil, false, fmt.Errorf("failed to search projects (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return nil, false, errors.Errorf("failed to search projects (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result base.Paginated[project.Details]if err := json.Unmarshal(searchBody, &result); err != nil {- return nil, false, fmt.Errorf("failed to parse projects response: %w", err)+ return nil, false, errors.WrapIf(err, "failed to parse projects response")}matches := make([]project.Details, 0)@@ -720,10 +721,10 @@ func resolveProject(ctx context.Context, c *client.Client, identifier string, alif len(matches) > 1 {if !allowPrompt {- return nil, false, fmt.Errorf("multiple projects match %q; use the project ID or run `arcane projects list`", trimmed)+ return nil, false, errors.Errorf("multiple projects match %q; use the project ID or run `arcane projects list`", trimmed)}if len(matches) > maxPromptOptions {- return nil, false, fmt.Errorf("multiple projects match %q (%d results); refine your query or use the project ID", trimmed, len(matches))+ return nil, false, errors.Errorf("multiple projects match %q (%d results); refine your query or use the project ID", trimmed, len(matches))}options := make([]string, 0, len(matches))@@ -737,7 +738,7 @@ func resolveProject(ctx context.Context, c *client.Client, identifier string, alreturn &matches[choice], false, nil}- return nil, false, fmt.Errorf("project %q not found; use the project ID or run `arcane projects list`", trimmed)+ return nil, false, errors.Errorf("project %q not found; use the project ID or run `arcane projects list`", trimmed)}func projectMatches(item project.Details, identifierLower, original string) bool {diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.goindex 00ca36872..011e39392 100644--- a/cli/pkg/registries/cmd.go+++ b/cli/pkg/registries/cmd.go@@ -2,9 +2,10 @@ package registriesimport ("encoding/json"- "errors""fmt"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -58,24 +59,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.ContainerRegistries()path, err = cmdutil.ApplyPaginationParams(cmd, path, "registries", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list registries: %w", err)+ return errors.WrapIf(err, "failed to list registries")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[containerregistry.ContainerRegistry]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -119,11 +120,11 @@ var syncCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.ContainerRegistrySync(), nil)if err != nil {- return fmt.Errorf("failed to sync registries: %w", err)+ return errors.WrapIf(err, "failed to sync registries")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to sync registries: %w", err)+ return errors.WrapIf(err, "failed to sync registries")}if jsonOutput {@@ -154,11 +155,11 @@ var testCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.ContainerRegistryTest(args[0]), nil)if err != nil {- return fmt.Errorf("failed to test registry: %w", err)+ return errors.WrapIf(err, "failed to test registry")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to test registry: %w", err)+ return errors.WrapIf(err, "failed to test registry")}if jsonOutput {@@ -189,19 +190,19 @@ var getCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.ContainerRegistry(args[0]))if err != nil {- return fmt.Errorf("failed to get registry: %w", err)+ return errors.WrapIf(err, "failed to get registry")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[containerregistry.ContainerRegistry]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -247,22 +248,22 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.ContainerRegistries(), req)if err != nil {- return fmt.Errorf("failed to create registry: %w", err)+ return errors.WrapIf(err, "failed to create registry")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create registry: %w", err)+ return errors.WrapIf(err, "failed to create registry")}var result base.ApiResponse[containerregistry.ContainerRegistry]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -317,11 +318,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.ContainerRegistry(args[0]), req)if err != nil {- return fmt.Errorf("failed to update registry: %w", err)+ return errors.WrapIf(err, "failed to update registry")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update registry: %w", err)+ return errors.WrapIf(err, "failed to update registry")}if jsonOutput {@@ -364,11 +365,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.ContainerRegistry(args[0]))if err != nil {- return fmt.Errorf("failed to delete registry: %w", err)+ return errors.WrapIf(err, "failed to delete registry")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete registry: %w", err)+ return errors.WrapIf(err, "failed to delete registry")}output.Success("Registry deleted successfully")diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.goindex 82b55b2a5..6fe41fed4 100644--- a/cli/pkg/repos/cmd.go+++ b/cli/pkg/repos/cmd.go@@ -3,7 +3,6 @@ package reposimport ("context""encoding/json"- "errors""fmt""io""net/http"@@ -12,6 +11,8 @@ import ("strconv""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -84,24 +85,24 @@ var listCmd = &cobra.Command{path := types.Endpoints.GitRepositories()path, err = cmdutil.ApplyPaginationParams(cmd, path, "repos", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list repositories: %w", err)+ return errors.WrapIf(err, "failed to list repositories")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[gitops.GitRepository]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -155,7 +156,7 @@ var createCmd = &cobra.Command{if cmd.Flags().Changed("ssh-key") {sshKeyData, err := os.ReadFile(repoCreateSSHKey)if err != nil {- return fmt.Errorf("failed to read SSH key file: %w", err)+ return errors.WrapIf(err, "failed to read SSH key file")}req.SSHKey = string(sshKeyData)}@@ -171,22 +172,22 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositories(), req)if err != nil {- return fmt.Errorf("failed to create repository: %w", err)+ return errors.WrapIf(err, "failed to create repository")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create repository: %w", err)+ return errors.WrapIf(err, "failed to create repository")}var result base.ApiResponse[gitops.GitRepository]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -221,7 +222,7 @@ var getCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -284,7 +285,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("ssh-key") {sshKeyData, err := os.ReadFile(repoUpdateSSHKey)if err != nil {- return fmt.Errorf("failed to read SSH key file: %w", err)+ return errors.WrapIf(err, "failed to read SSH key file")}req.SSHKey = new(string(sshKeyData))}@@ -300,17 +301,17 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.GitRepository(resolved.ID), req)if err != nil {- return fmt.Errorf("failed to update repository: %w", err)+ return errors.WrapIf(err, "failed to update repository")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update repository: %w", err)+ return errors.WrapIf(err, "failed to update repository")}var result base.ApiResponse[gitops.GitRepository]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {if jsonOutput {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}output.Success("Repository updated successfully")return nil@@ -319,7 +320,7 @@ var updateCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -365,11 +366,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.GitRepository(resolved.ID))if err != nil {- return fmt.Errorf("failed to delete repository: %w", err)+ return errors.WrapIf(err, "failed to delete repository")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete repository: %w", err)+ return errors.WrapIf(err, "failed to delete repository")}output.Success("Repository deleted successfully")@@ -395,11 +396,11 @@ var testCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositoryTest(resolved.ID), nil)if err != nil {- return fmt.Errorf("failed to test repository: %w", err)+ return errors.WrapIf(err, "failed to test repository")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("repository connection test failed: %w", err)+ return errors.WrapIf(err, "repository connection test failed")}if jsonOutput {@@ -435,19 +436,19 @@ var branchesCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.GitRepositoryBranches(resolved.ID))if err != nil {- return fmt.Errorf("failed to list branches: %w", err)+ return errors.WrapIf(err, "failed to list branches")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.BranchesResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -502,20 +503,20 @@ var filesCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list files: %w", err)+ return errors.WrapIf(err, "failed to list files")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[gitops.BrowseResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}files := result.Data.Filesif jsonOutput {resultBytes, err := json.MarshalIndent(files, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -554,11 +555,11 @@ var syncCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositoriesSync(), nil)if err != nil {- return fmt.Errorf("failed to sync repositories: %w", err)+ return errors.WrapIf(err, "failed to sync repositories")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to sync repositories: %w", err)+ return errors.WrapIf(err, "failed to sync repositories")}if jsonOutput {@@ -603,13 +604,13 @@ func resolveGitRepository(ctx context.Context, c *client.Client, identifier strilistPath := types.Endpoints.GitRepositories() + "?limit=200"listResp, err := c.Get(ctx, listPath)if err != nil {- return nil, fmt.Errorf("failed to search repositories: %w", err)+ return nil, errors.WrapIf(err, "failed to search repositories")}defer func() { _ = listResp.Body.Close() }()var listResult base.Paginated[gitops.GitRepository]if err := json.NewDecoder(listResp.Body).Decode(&listResult); err != nil {- return nil, fmt.Errorf("failed to parse repository list: %w", err)+ return nil, errors.WrapIf(err, "failed to parse repository list")}lowerIdentifier := strings.ToLower(trimmed)@@ -626,12 +627,12 @@ func resolveGitRepository(ctx context.Context, c *client.Client, identifier striswitch len(matches) {case 0:- return nil, fmt.Errorf("repository %q not found", trimmed)+ return nil, errors.Errorf("repository %q not found", trimmed)case 1:return &matches[0], nildefault:if !prompt.IsInteractive() || len(matches) > maxPromptOptions {- return nil, fmt.Errorf("ambiguous repository %q: %d matches found, please be more specific", trimmed, len(matches))+ return nil, errors.Errorf("ambiguous repository %q: %d matches found, please be more specific", trimmed, len(matches))}options := make([]string, len(matches))for i, m := range matches {diff --git a/cli/pkg/root.go b/cli/pkg/root.goindex cf42db19b..7b7a92455 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -40,6 +40,7 @@ import ("charm.land/fang/v2""charm.land/lipgloss/v2"+ "emperror.dev/errors""github.com/fatih/color""github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/logger"@@ -102,7 +103,7 @@ var rootCmd = &cobra.Command{outputMode = string(runtimectx.OutputModeText)}if outputMode != string(runtimectx.OutputModeText) && outputMode != string(runtimectx.OutputModeJSON) {- return fmt.Errorf("invalid --output value %q (expected text or json)", outputMode)+ return errors.Errorf("invalid --output value %q (expected text or json)", outputMode)}if outputMode == string(runtimectx.OutputModeJSON) {if flag := cmd.Flags().Lookup("json"); flag != nil && !flag.Changed {diff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.goindex 602bc7583..230c94930 100644--- a/cli/pkg/selfupdate/cmd.go+++ b/cli/pkg/selfupdate/cmd.go@@ -7,7 +7,6 @@ import ("crypto/sha256""encoding/hex""encoding/json"- "errors""fmt""io""net/http"@@ -19,6 +18,8 @@ import ("strings""time"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/spf13/cobra"@@ -122,7 +123,7 @@ func newSelfUpdateChannelValueCmdInternal(channel string) *cobra.Command {func setCLIUpdateChannelAndRunInternal(cmd *cobra.Command, channel string) error {channel = normalizeCLIUpdateChannelInternal(channel)if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return fmt.Errorf("invalid update channel %q (expected stable or next)", channel)+ return errors.Errorf("invalid update channel %q (expected stable or next)", channel)}if err := saveCLIUpdateChannelInternal(channel); err != nil {return err@@ -144,7 +145,7 @@ func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {if jsonOutput {resultBytes, err := json.MarshalIndent(plan, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -193,7 +194,7 @@ func buildCLIUpdatePlanInternal(ctx context.Context, overrideChannel string) (*cchannel = inferCLIUpdateChannelInternal(config.Version)}if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return nil, fmt.Errorf("invalid update channel %q (expected next or stable)", channel)+ return nil, errors.Errorf("invalid update channel %q (expected next or stable)", channel)}verboseCLIUpdateInternal("channel=%s target=%s platform=%s/%s", channel, targetPath, runtime.GOOS, runtime.GOARCH)@@ -216,14 +217,14 @@ func buildCLIUpdatePlanInternal(ctx context.Context, overrideChannel string) (*cfunc configuredCLIUpdateChannelInternal() (string, error) {cfg, err := config.Load()if err != nil {- return "", fmt.Errorf("failed to load config: %w", err)+ return "", errors.WrapIf(err, "failed to load config")}channel := normalizeCLIUpdateChannelInternal(cfg.CLIUpdateChannel)if channel == "" {return "", nil}if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return "", fmt.Errorf("invalid configured CLI update channel %q (expected stable or next)", cfg.CLIUpdateChannel)+ return "", errors.Errorf("invalid configured CLI update channel %q (expected stable or next)", cfg.CLIUpdateChannel)}return channel, nil}@@ -231,11 +232,11 @@ func configuredCLIUpdateChannelInternal() (string, error) {func saveCLIUpdateChannelInternal(channel string) error {cfg, err := config.Load()if err != nil {- return fmt.Errorf("failed to load config: %w", err)+ return errors.WrapIf(err, "failed to load config")}cfg.CLIUpdateChannel = channelif err := config.Save(cfg); err != nil {- return fmt.Errorf("failed to save config: %w", err)+ return errors.WrapIf(err, "failed to save config")}return nil}@@ -247,13 +248,13 @@ func resolveCLIUpdateTargetInternal() (string, error) {if pathTarget, err := exec.LookPath("arcane-cli"); err == nil {absTarget, err := filepath.Abs(pathTarget)if err != nil {- return "", fmt.Errorf("failed to resolve arcane-cli from PATH: %w", err)+ return "", errors.WrapIf(err, "failed to resolve arcane-cli from PATH")}return filepath.EvalSymlinks(absTarget)}exe, err := os.Executable()if err != nil {- return "", fmt.Errorf("failed to resolve current executable: %w", err)+ return "", errors.WrapIf(err, "failed to resolve current executable")}return filepath.EvalSymlinks(exe)}@@ -392,16 +393,16 @@ func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return "", fmt.Errorf("failed to fetch latest GitHub release: %w", err)+ return "", errors.WrapIf(err, "failed to fetch latest GitHub release")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", fmt.Errorf("failed to fetch latest GitHub release: HTTP %s", resp.Status)+ return "", errors.Errorf("failed to fetch latest GitHub release: HTTP %s", resp.Status)}var latest githubLatestReleaseif err := json.NewDecoder(resp.Body).Decode(&latest); err != nil {- return "", fmt.Errorf("failed to fetch latest GitHub release: %w", err)+ return "", errors.WrapIf(err, "failed to fetch latest GitHub release")}return strings.TrimSpace(latest.TagName), nil}@@ -437,14 +438,14 @@ func cliArtifactArchInternal() (string, error) {case "arm":return "armv7", nildefault:- return "", fmt.Errorf("unsupported CLI update architecture %s/%s", runtime.GOOS, runtime.GOARCH)+ return "", errors.Errorf("unsupported CLI update architecture %s/%s", runtime.GOOS, runtime.GOARCH)}}func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {tmpDir, err := os.MkdirTemp("", "arcane-cli-update-*")if err != nil {- return fmt.Errorf("failed to create update temp dir: %w", err)+ return errors.WrapIf(err, "failed to create update temp dir")}defer func() { _ = os.RemoveAll(tmpDir) }()@@ -455,7 +456,7 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {if gotSHA, err := sha256FileInternal(downloadPath); err != nil {return err} else if !strings.EqualFold(gotSHA, plan.ArtifactSHA) {- return fmt.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)+ return errors.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)}binaryPath := downloadPath@@ -468,7 +469,7 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {}if err := os.Chmod(binaryPath, 0o755); err != nil {- return fmt.Errorf("failed to make downloaded binary executable: %w", err)+ return errors.WrapIf(err, "failed to make downloaded binary executable")}return replaceExecutableInternal(binaryPath, plan.TargetPath)}@@ -477,7 +478,7 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {targetDir := filepath.Dir(targetPath)tmpTarget, err := os.CreateTemp(targetDir, filepath.Base(targetPath)+".update-*")if err != nil {- return fmt.Errorf("failed to create replacement file in %s: %w", targetDir, err)+ return errors.WrapIff(err, "failed to create replacement file in %s", targetDir)}tmpTargetPath := tmpTarget.Name()cleanup := func() { _ = os.Remove(tmpTargetPath) }@@ -486,41 +487,41 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {if err != nil {_ = tmpTarget.Close()cleanup()- return fmt.Errorf("failed to open downloaded binary: %w", err)+ return errors.WrapIf(err, "failed to open downloaded binary")}defer func() { _ = source.Close() }()if _, err := io.Copy(tmpTarget, source); err != nil {_ = tmpTarget.Close()cleanup()- return fmt.Errorf("failed to write replacement binary: %w", err)+ return errors.WrapIf(err, "failed to write replacement binary")}if err := tmpTarget.Chmod(0o755); err != nil {_ = tmpTarget.Close()cleanup()- return fmt.Errorf("failed to chmod replacement binary: %w", err)+ return errors.WrapIf(err, "failed to chmod replacement binary")}if err := tmpTarget.Sync(); err != nil {_ = tmpTarget.Close()cleanup()- return fmt.Errorf("failed to sync replacement binary: %w", err)+ return errors.WrapIf(err, "failed to sync replacement binary")}if err := tmpTarget.Close(); err != nil {cleanup()- return fmt.Errorf("failed to close replacement binary: %w", err)+ return errors.WrapIf(err, "failed to close replacement binary")}if err := os.Rename(tmpTargetPath, targetPath); err != nil {cleanup()- return fmt.Errorf("failed to replace %s: %w", targetPath, err)+ return errors.WrapIff(err, "failed to replace %s", targetPath)}dirFile, err := os.Open(targetDir)if err != nil {- return fmt.Errorf("failed to open target directory for sync: %w", err)+ return errors.WrapIf(err, "failed to open target directory for sync")}defer func() { _ = dirFile.Close() }()if err := dirFile.Sync(); err != nil {- return fmt.Errorf("failed to sync target directory: %w", err)+ return errors.WrapIf(err, "failed to sync target directory")}return nil}@@ -528,13 +529,13 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {func extractCLIFromTarGzInternal(archivePath, outputPath string) error {file, err := os.Open(archivePath)if err != nil {- return fmt.Errorf("failed to open archive: %w", err)+ return errors.WrapIf(err, "failed to open archive")}defer func() { _ = file.Close() }()gzipReader, err := gzip.NewReader(file)if err != nil {- return fmt.Errorf("failed to read gzip archive: %w", err)+ return errors.WrapIf(err, "failed to read gzip archive")}defer func() { _ = gzipReader.Close() }()@@ -545,7 +546,7 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {break}if err != nil {- return fmt.Errorf("failed to read tar archive: %w", err)+ return errors.WrapIf(err, "failed to read tar archive")}if header.Typeflag != tar.TypeReg {continue@@ -554,19 +555,19 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {continue}if header.Size < 0 || header.Size > maxCLIExtractSize {- return fmt.Errorf("arcane-cli archive entry has invalid size %d", header.Size)+ return errors.Errorf("arcane-cli archive entry has invalid size %d", header.Size)}out, err := os.OpenFile(outputPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)if err != nil {- return fmt.Errorf("failed to create extracted binary: %w", err)+ return errors.WrapIf(err, "failed to create extracted binary")}if _, err := io.CopyN(out, tarReader, header.Size); err != nil {_ = out.Close()- return fmt.Errorf("failed to extract CLI binary: %w", err)+ return errors.WrapIf(err, "failed to extract CLI binary")}if err := out.Close(); err != nil {- return fmt.Errorf("failed to close extracted binary: %w", err)+ return errors.WrapIf(err, "failed to close extracted binary")}return nil}@@ -583,19 +584,19 @@ func fetchTextInternal(ctx context.Context, url string) (string, error) {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return "", fmt.Errorf("failed to fetch %s: %w", url, err)+ return "", errors.WrapIff(err, "failed to fetch %s", url)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", fmt.Errorf("failed to fetch %s: HTTP %s", url, resp.Status)+ return "", errors.Errorf("failed to fetch %s: HTTP %s", url, resp.Status)}limitedBody := &io.LimitedReader{R: resp.Body, N: maxCLIChecksumSize + 1}body, err := io.ReadAll(limitedBody)if err != nil {- return "", fmt.Errorf("failed to read %s: %w", url, err)+ return "", errors.WrapIff(err, "failed to read %s", url)}if len(body) > maxCLIChecksumSize {- return "", fmt.Errorf("failed to read %s: checksum response exceeds maximum size of %d bytes", url, maxCLIChecksumSize)+ return "", errors.Errorf("failed to read %s: checksum response exceeds maximum size of %d bytes", url, maxCLIChecksumSize)}return string(body), nil}@@ -609,29 +610,29 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return fmt.Errorf("failed to download %s: %w", url, err)+ return errors.WrapIff(err, "failed to download %s", url)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("failed to download %s: HTTP %s", url, resp.Status)+ return errors.Errorf("failed to download %s: HTTP %s", url, resp.Status)}out, err := os.OpenFile(outputPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)if err != nil {- return fmt.Errorf("failed to create download file: %w", err)+ return errors.WrapIf(err, "failed to create download file")}limitedBody := &io.LimitedReader{R: resp.Body, N: maxCLIDownloadSize + 1}written, err := io.Copy(out, limitedBody)if err != nil {_ = out.Close()- return fmt.Errorf("failed to write download file: %w", err)+ return errors.WrapIf(err, "failed to write download file")}if written > maxCLIDownloadSize {_ = out.Close()- return fmt.Errorf("downloaded artifact exceeds maximum size of %d bytes", maxCLIDownloadSize)+ return errors.Errorf("downloaded artifact exceeds maximum size of %d bytes", maxCLIDownloadSize)}if err := out.Close(); err != nil {- return fmt.Errorf("failed to close download file: %w", err)+ return errors.WrapIf(err, "failed to close download file")}return nil}@@ -647,13 +648,13 @@ func verboseCLIUpdateInternal(format string, args ...any) {func sha256FileInternal(path string) (string, error) {file, err := os.Open(path)if err != nil {- return "", fmt.Errorf("failed to open %s for SHA-256: %w", path, err)+ return "", errors.WrapIff(err, "failed to open %s for SHA-256", path)}defer func() { _ = file.Close() }()hash := sha256.New()if _, err := io.Copy(hash, file); err != nil {- return "", fmt.Errorf("failed to hash %s: %w", path, err)+ return "", errors.WrapIff(err, "failed to hash %s", path)}return hex.EncodeToString(hash.Sum(nil)), nil}@@ -677,7 +678,7 @@ func findChecksumInternal(checksums string, artifactNames ...string) (string, erreturn strings.ToLower(fields[0]), nil}}- return "", fmt.Errorf("checksum for %s not found", strings.Join(artifactNames, " or "))+ return "", errors.Errorf("checksum for %s not found", strings.Join(artifactNames, " or "))}func checksumEntryNamesInternal(checksums string) []string {diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.goindex 50e07edc8..8dffc2f24 100644--- a/cli/pkg/settings/cmd.go+++ b/cli/pkg/settings/cmd.go@@ -5,6 +5,7 @@ import ("fmt""os"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -50,21 +51,21 @@ var updateCmd = &cobra.Command{data, err := os.ReadFile(settingsUpdateFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", settingsUpdateFile, err)+ return errors.WrapIff(err, "failed to read file %s", settingsUpdateFile)}var req settings.Updateif err := json.Unmarshal(data, &req); err != nil {- return fmt.Errorf("failed to parse settings file: %w", err)+ return errors.WrapIf(err, "failed to parse settings file")}resp, err := c.Put(cmd.Context(), types.Endpoints.Settings(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to update settings: %w", err)+ return errors.WrapIf(err, "failed to update settings")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update settings: %w", err)+ return errors.WrapIf(err, "failed to update settings")}if jsonOutput {@@ -109,19 +110,19 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {resp, err := c.Get(cmd.Context(), cfg.endpoint(c.EnvID()))if err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}defer func() { _ = resp.Body.Close() }()var result []settings.PublicSettingif err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.goindex 46e7c7ead..4d929e85e 100644--- a/cli/pkg/system/cmd.go+++ b/cli/pkg/system/cmd.go@@ -5,6 +5,7 @@ import ("fmt""strconv"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -42,23 +43,23 @@ var pruneCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.SystemPrune(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to prune: %w", err)+ return errors.WrapIf(err, "failed to prune")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to prune: %w", err)+ return errors.WrapIf(err, "failed to prune")}var result base.ApiResponse[system.PruneAllResult]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -82,19 +83,19 @@ var dockerInfoCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.SystemDockerInfo(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get docker info: %w", err)+ return errors.WrapIf(err, "failed to get docker info")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[dockerinfo.Info]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -121,12 +122,12 @@ var containersStartAllCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.SystemContainersStartAll(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to start all containers: %w", err)+ return errors.WrapIf(err, "failed to start all containers")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to start all containers: %w", err)+ return errors.WrapIf(err, "failed to start all containers")}output.Success("Started all containers")@@ -146,12 +147,12 @@ var containersStopAllCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.SystemContainersStopAll(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to stop all containers: %w", err)+ return errors.WrapIf(err, "failed to stop all containers")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to stop all containers: %w", err)+ return errors.WrapIf(err, "failed to stop all containers")}output.Success("Stopped all containers")@@ -171,11 +172,11 @@ var startStoppedCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.SystemStartStopped(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to start stopped containers: %w", err)+ return errors.WrapIf(err, "failed to start stopped containers")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to start stopped containers: %w", err)+ return errors.WrapIf(err, "failed to start stopped containers")}if jsonOutput {@@ -207,11 +208,11 @@ var convertCmd = &cobra.Command{req := map[string]string{"dockerRunCommand": args[0]}resp, err := c.Post(cmd.Context(), types.Endpoints.SystemConvert(c.EnvID()), req)if err != nil {- return fmt.Errorf("failed to convert command: %w", err)+ return errors.WrapIf(err, "failed to convert command")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to convert command: %w", err)+ return errors.WrapIf(err, "failed to convert command")}var result struct {@@ -221,7 +222,7 @@ var convertCmd = &cobra.Command{ServiceName string `json:"serviceName"`}if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {@@ -232,7 +233,7 @@ var convertCmd = &cobra.Command{}resultBytes, err := json.MarshalIndent(out, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -279,11 +280,11 @@ var upgradeCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.SystemUpgrade(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to upgrade system: %w", err)+ return errors.WrapIf(err, "failed to upgrade system")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to upgrade system: %w", err)+ return errors.WrapIf(err, "failed to upgrade system")}if jsonOutput {@@ -313,12 +314,12 @@ var upgradeCheckCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.SystemUpgradeCheck(c.EnvID()))if err != nil {- return fmt.Errorf("failed to check for upgrades: %w", err)+ return errors.WrapIf(err, "failed to check for upgrades")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to check for upgrades: %w", err)+ return errors.WrapIf(err, "failed to check for upgrades")}var result struct {@@ -327,13 +328,13 @@ var upgradeCheckCmd = &cobra.Command{Message string `json:"message"`}if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.goindex 3b470b195..efdf4b8c4 100644--- a/cli/pkg/templates/cmd.go+++ b/cli/pkg/templates/cmd.go@@ -3,7 +3,6 @@ package templatesimport ("context""encoding/json"- "errors""fmt""io""net/http"@@ -14,6 +13,8 @@ import ("strings""unicode"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -85,13 +86,13 @@ var listCmd = &cobra.Command{path = types.Endpoints.TemplatesAll()resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list templates: %w", err)+ return errors.WrapIf(err, "failed to list templates")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]template.Template]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}templates = result.Data@@ -101,18 +102,18 @@ var listCmd = &cobra.Command{path = types.Endpoints.Templates()path, err = cmdutil.ApplyPaginationParams(cmd, path, "templates", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list templates: %w", err)+ return errors.WrapIf(err, "failed to list templates")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[template.Template]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}templates = result.Data@@ -123,7 +124,7 @@ var listCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(jsonPayload, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -166,19 +167,19 @@ var defaultCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.TemplatesDefault())if err != nil {- return fmt.Errorf("failed to get default templates: %w", err)+ return errors.WrapIf(err, "failed to get default templates")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[template.DefaultTemplatesResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -204,19 +205,19 @@ var contentCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.TemplateContent(args[0]))if err != nil {- return fmt.Errorf("failed to get template content: %w", err)+ return errors.WrapIf(err, "failed to get template content")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[template.TemplateContent]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -250,19 +251,19 @@ var registriesCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.TemplatesRegistries())if err != nil {- return fmt.Errorf("failed to list registries: %w", err)+ return errors.WrapIf(err, "failed to list registries")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]template.TemplateRegistry]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -302,19 +303,19 @@ var variablesCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.TemplatesVariables())if err != nil {- return fmt.Errorf("failed to list variables: %w", err)+ return errors.WrapIf(err, "failed to list variables")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]env.Variable]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -360,11 +361,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.Template(args[0]))if err != nil {- return fmt.Errorf("failed to delete template: %w", err)+ return errors.WrapIf(err, "failed to delete template")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete template: %w", err)+ return errors.WrapIf(err, "failed to delete template")}output.Success("Template deleted successfully")@@ -396,11 +397,11 @@ var deleteRegistryCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.TemplateRegistry(args[0]))if err != nil {- return fmt.Errorf("failed to delete registry: %w", err)+ return errors.WrapIf(err, "failed to delete registry")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete registry: %w", err)+ return errors.WrapIf(err, "failed to delete registry")}output.Success("Template registry deleted successfully")@@ -427,7 +428,7 @@ var getCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -462,37 +463,37 @@ func resolveTemplate(ctx context.Context, c *client.Client, identifier string) (resp, err := c.Get(ctx, types.Endpoints.Template(trimmed))if err != nil {- return nil, fmt.Errorf("failed to get template: %w", err)+ return nil, errors.WrapIf(err, "failed to get template")}defer func() { _ = resp.Body.Close() }()if resp.StatusCode == http.StatusOK {var result base.ApiResponse[template.Template]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return nil, fmt.Errorf("failed to parse response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse response")}return &result.Data, nil}if resp.StatusCode != http.StatusNotFound {body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return nil, fmt.Errorf("failed to get template: request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("failed to get template: request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}listResp, err := c.Get(ctx, types.Endpoints.TemplatesAll())if err != nil {- return nil, fmt.Errorf("failed to search templates: %w", err)+ return nil, errors.WrapIf(err, "failed to search templates")}defer func() { _ = listResp.Body.Close() }()if listResp.StatusCode < http.StatusOK || listResp.StatusCode >= http.StatusMultipleChoices {body, _ := io.ReadAll(io.LimitReader(listResp.Body, 4096))- return nil, fmt.Errorf("failed to search templates: request failed with status %d: %s", listResp.StatusCode, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("failed to search templates: request failed with status %d: %s", listResp.StatusCode, strings.TrimSpace(string(body)))}var listResult base.ApiResponse[[]template.Template]if err := json.NewDecoder(listResp.Body).Decode(&listResult); err != nil {- return nil, fmt.Errorf("failed to parse template list: %w", err)+ return nil, errors.WrapIf(err, "failed to parse template list")}lowerIdentifier := strings.ToLower(trimmed)@@ -539,19 +540,19 @@ func resolveTemplate(ctx context.Context, c *client.Client, identifier string) (return selectTemplateMatch(trimmed, topTemplatesFromRankedMatches(ranked, maxTemplatePromptOptions))}- return nil, fmt.Errorf("template %q not found", trimmed)+ return nil, errors.Errorf("template %q not found", trimmed)}func selectTemplateMatch(identifier string, matches []template.Template) (*template.Template, error) {if len(matches) == 0 {- return nil, fmt.Errorf("template %q not found", identifier)+ return nil, errors.Errorf("template %q not found", identifier)}if len(matches) == 1 {return &matches[0], nil}if !prompt.IsInteractive() || len(matches) > maxTemplatePromptOptions {- return nil, fmt.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidates(matches))+ return nil, errors.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidates(matches))}ordered := make([]template.Template, len(matches))@@ -823,7 +824,7 @@ var createCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {content, err := os.ReadFile(templateCreateFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", templateCreateFile, err)+ return errors.WrapIff(err, "failed to read file %s", templateCreateFile)}req := template.CreateRequest{@@ -835,7 +836,7 @@ var createCmd = &cobra.Command{if templateCreateEnvFile != "" {envContent, err := os.ReadFile(templateCreateEnvFile)if err != nil {- return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, err)+ return errors.WrapIff(err, "failed to read env file %s", templateCreateEnvFile)}req.EnvContent = string(envContent)}@@ -847,19 +848,19 @@ var createCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.Templates(), req)if err != nil {- return fmt.Errorf("failed to create template: %w", err)+ return errors.WrapIf(err, "failed to create template")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[template.Template]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -886,7 +887,7 @@ var updateCmd = &cobra.Command{if templateUpdateFile != "" {content, err := os.ReadFile(templateUpdateFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, err)+ return errors.WrapIff(err, "failed to read file %s", templateUpdateFile)}req.Content = string(content)}@@ -894,7 +895,7 @@ var updateCmd = &cobra.Command{if templateUpdateEnvFile != "" {envContent, err := os.ReadFile(templateUpdateEnvFile)if err != nil {- return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, err)+ return errors.WrapIff(err, "failed to read env file %s", templateUpdateEnvFile)}req.EnvContent = string(envContent)}@@ -906,19 +907,19 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.Template(args[0]), req)if err != nil {- return fmt.Errorf("failed to update template: %w", err)+ return errors.WrapIf(err, "failed to update template")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[template.Template]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -944,25 +945,25 @@ var downloadCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.TemplateDownload(args[0]), nil)if err != nil {- return fmt.Errorf("failed to download template: %w", err)+ return errors.WrapIf(err, "failed to download template")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to download template: %w", err)+ return errors.WrapIf(err, "failed to download template")}var result base.ApiResponse[template.TemplateContent]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if templateDownloadOutput != "" {dir := filepath.Dir(templateDownloadOutput)if err := os.MkdirAll(dir, 0o755); err != nil {- return fmt.Errorf("failed to create directory %s: %w", dir, err)+ return errors.WrapIff(err, "failed to create directory %s", dir)}if err := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); err != nil {- return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, err)+ return errors.WrapIff(err, "failed to write file %s", templateDownloadOutput)}output.Success("Template downloaded to %s", templateDownloadOutput)return nil@@ -980,7 +981,7 @@ var defaultsSaveCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {content, err := os.ReadFile(templateDefaultsSaveFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", templateDefaultsSaveFile, err)+ return errors.WrapIff(err, "failed to read file %s", templateDefaultsSaveFile)}req := template.SaveDefaultTemplatesRequest{@@ -990,7 +991,7 @@ var defaultsSaveCmd = &cobra.Command{if templateDefaultsEnvFile != "" {envContent, err := os.ReadFile(templateDefaultsEnvFile)if err != nil {- return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, err)+ return errors.WrapIff(err, "failed to read env file %s", templateDefaultsEnvFile)}req.EnvContent = string(envContent)}@@ -1002,21 +1003,21 @@ var defaultsSaveCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.TemplatesDefault(), req)if err != nil {- return fmt.Errorf("failed to save default templates: %w", err)+ return errors.WrapIf(err, "failed to save default templates")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to save default templates: %w", err)+ return errors.WrapIf(err, "failed to save default templates")}if jsonOutput {var result base.ApiResponse[template.DefaultTemplatesResponse]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -1035,12 +1036,12 @@ var variablesUpdateCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {content, err := os.ReadFile(templateVarsUpdateFile)if err != nil {- return fmt.Errorf("failed to read file %s: %w", templateVarsUpdateFile, err)+ return errors.WrapIff(err, "failed to read file %s", templateVarsUpdateFile)}var variables []env.Variableif err := json.Unmarshal(content, &variables); err != nil {- return fmt.Errorf("failed to parse variables JSON: %w", err)+ return errors.WrapIf(err, "failed to parse variables JSON")}c, err := client.NewFromConfig()@@ -1050,21 +1051,21 @@ var variablesUpdateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.TemplatesVariables(), variables)if err != nil {- return fmt.Errorf("failed to update variables: %w", err)+ return errors.WrapIf(err, "failed to update variables")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to update variables: %w", err)+ return errors.WrapIf(err, "failed to update variables")}if jsonOutput {var result base.ApiResponse[[]env.Variable]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -1095,19 +1096,19 @@ var registriesUpdateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Endpoints.TemplateRegistry(args[0]), req)if err != nil {- return fmt.Errorf("failed to update registry: %w", err)+ return errors.WrapIf(err, "failed to update registry")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[template.TemplateRegistry]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -1132,21 +1133,21 @@ var fetchCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.TemplateFetch())if err != nil {- return fmt.Errorf("failed to fetch templates: %w", err)+ return errors.WrapIf(err, "failed to fetch templates")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to fetch templates: %w", err)+ return errors.WrapIf(err, "failed to fetch templates")}if jsonOutput {var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.goindex af06eaa0c..e4f191941 100644--- a/cli/pkg/updater/cmd.go+++ b/cli/pkg/updater/cmd.go@@ -6,6 +6,7 @@ import ("strconv""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -35,19 +36,19 @@ var statusCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.UpdaterStatus(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get updater status: %w", err)+ return errors.WrapIf(err, "failed to get updater status")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[updater.Status]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -75,19 +76,19 @@ var runCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.UpdaterRun(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to run updater: %w", err)+ return errors.WrapIf(err, "failed to run updater")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[updater.Result]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -115,19 +116,19 @@ var historyCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.UpdaterHistory(c.EnvID()))if err != nil {- return fmt.Errorf("failed to get updater history: %w", err)+ return errors.WrapIf(err, "failed to get updater history")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[[]updater.Result]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/version/cmd.go b/cli/pkg/version/cmd.goindex a7d57f9a3..3e8ff8ac5 100644--- a/cli/pkg/version/cmd.go+++ b/cli/pkg/version/cmd.go@@ -5,6 +5,7 @@ import ("fmt""io"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/logger"@@ -30,7 +31,7 @@ var VersionCmd = &cobra.Command{logger.GetLogger().Debug("Sending request", "endpoint", clitypes.Endpoints.VersionEndpoint)resp, err := c.Get(cmd.Context(), clitypes.Endpoints.VersionEndpoint)if err != nil {- return fmt.Errorf("failed to get version: %w", err)+ return errors.WrapIf(err, "failed to get version")}defer func() { _ = resp.Body.Close() }()@@ -38,7 +39,7 @@ var VersionCmd = &cobra.Command{body, err := io.ReadAll(resp.Body)if err != nil {- return fmt.Errorf("failed to read response: %w", err)+ return errors.WrapIf(err, "failed to read response")}logger.GetLogger().Debug("Raw response", "body", string(body))@@ -46,7 +47,7 @@ var VersionCmd = &cobra.Command{var result version.Infoif err := json.Unmarshal(body, &result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}logger.GetLogger().Debug("Parsed version data", "result", result)@@ -54,7 +55,7 @@ var VersionCmd = &cobra.Command{if cmdutil.JSONOutputEnabled(cmd) {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nildiff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.goindex 5d2024325..31cf2c6a4 100644--- a/cli/pkg/volumes/cmd.go+++ b/cli/pkg/volumes/cmd.go@@ -3,13 +3,14 @@ package volumesimport ("context""encoding/json"- "errors""fmt""io""net/http""net/url""strings"+ "emperror.dev/errors"+"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -62,18 +63,18 @@ var listCmd = &cobra.Command{path := types.Endpoints.Volumes(c.EnvID())path, err = cmdutil.ApplyPaginationParams(cmd, path, "volumes", "limit", limitFlag, 20, "start", startFlag)if err != nil {- return fmt.Errorf("failed to build pagination query: %w", err)+ return errors.WrapIf(err, "failed to build pagination query")}resp, err := c.Get(cmd.Context(), path)if err != nil {- return fmt.Errorf("failed to list volumes: %w", err)+ return errors.WrapIf(err, "failed to list volumes")}defer func() { _ = resp.Body.Close() }()var result base.Paginated[volume.Volume]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}result.Data = filterVolumesByUsage(result.Data, inUseOnlyFlag, unusedOnlyFlag)result.Pagination.TotalItems = int64(len(result.Data))@@ -81,7 +82,7 @@ var listCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(result, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -129,7 +130,7 @@ var getCmd = &cobra.Command{if jsonOutput {resultBytes, err := json.MarshalIndent(resolved, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -180,11 +181,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.Endpoints.Volume(c.EnvID(), resolved.Name))if err != nil {- return fmt.Errorf("failed to delete volume: %w", err)+ return errors.WrapIf(err, "failed to delete volume")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to delete volume: %w", err)+ return errors.WrapIf(err, "failed to delete volume")}output.Success("Volume %s deleted successfully", resolved.Name)@@ -229,22 +230,22 @@ var pruneCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.Endpoints.VolumesPrune(c.EnvID()), nil)if err != nil {- return fmt.Errorf("failed to prune volumes: %w", err)+ return errors.WrapIf(err, "failed to prune volumes")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to prune volumes: %w", err)+ return errors.WrapIf(err, "failed to prune volumes")}var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -284,21 +285,21 @@ func runVolumeDataCommand(cmd *cobra.Command, cfg volumeDataCommandConfig) errorresp, err := c.Get(cmd.Context(), cfg.endpoint(c.EnvID()))if err != nil {- return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ return errors.WrapIff(err, "%s", cfg.failureMessage)}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {if jsonOutput {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}- return fmt.Errorf("%s: %w", cfg.marshalMessage, err)+ return errors.WrapIff(err, "%s", cfg.marshalMessage)}if jsonOutput {@@ -330,19 +331,19 @@ var usageCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.Endpoints.VolumeUsage(c.EnvID(), resolved.Name))if err != nil {- return fmt.Errorf("failed to get volume usage: %w", err)+ return errors.WrapIf(err, "failed to get volume usage")}defer func() { _ = resp.Body.Close() }()var result base.ApiResponse[any]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -351,7 +352,7 @@ var usageCmd = &cobra.Command{output.Header("Volume Usage: %s", resolved.Name)resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal volume usage: %w", err)+ return errors.WrapIf(err, "failed to marshal volume usage")}fmt.Println(string(resultBytes))return nil@@ -396,22 +397,22 @@ var createCmd = &cobra.Command{path := types.Endpoints.Volumes(c.EnvID())resp, err := c.Post(cmd.Context(), path, req)if err != nil {- return fmt.Errorf("failed to create volume: %w", err)+ return errors.WrapIf(err, "failed to create volume")}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return fmt.Errorf("failed to create volume: %w", err)+ return errors.WrapIf(err, "failed to create volume")}var result base.ApiResponse[volume.Volume]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return fmt.Errorf("failed to parse response: %w", err)+ return errors.WrapIf(err, "failed to parse response")}if jsonOutput {resultBytes, err := json.MarshalIndent(result.Data, "", " ")if err != nil {- return fmt.Errorf("failed to marshal JSON: %w", err)+ return errors.WrapIf(err, "failed to marshal JSON")}fmt.Println(string(resultBytes))return nil@@ -475,46 +476,46 @@ func resolveVolume(ctx context.Context, c *client.Client, identifier string, allresp, err := c.Get(ctx, types.Endpoints.Volume(c.EnvID(), trimmed))if err != nil {- return nil, fmt.Errorf("failed to resolve volume %q: %w", trimmed, err)+ return nil, errors.WrapIff(err, "failed to resolve volume %q", trimmed)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, fmt.Errorf("failed to read volume response: %w", err)+ return nil, errors.WrapIf(err, "failed to read volume response")}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[volume.Volume]if err := json.Unmarshal(body, &result); err != nil {- return nil, fmt.Errorf("failed to parse volume response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse volume response")}return &result.Data, nil}if resp.StatusCode != http.StatusNotFound {- return nil, fmt.Errorf("failed to resolve volume %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, errors.Errorf("failed to resolve volume %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))}searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Volumes(c.EnvID()), url.QueryEscape(trimmed), 200)searchResp, err := c.Get(ctx, searchPath)if err != nil {- return nil, fmt.Errorf("failed to search volumes: %w", err)+ return nil, errors.WrapIf(err, "failed to search volumes")}searchBody, err := io.ReadAll(searchResp.Body)_ = searchResp.Body.Close()if err != nil {- return nil, fmt.Errorf("failed to read volumes response: %w", err)+ return nil, errors.WrapIf(err, "failed to read volumes response")}if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {- return nil, fmt.Errorf("failed to search volumes (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))+ return nil, errors.Errorf("failed to search volumes (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))}var result base.Paginated[volume.Volume]if err := json.Unmarshal(searchBody, &result); err != nil {- return nil, fmt.Errorf("failed to parse volumes response: %w", err)+ return nil, errors.WrapIf(err, "failed to parse volumes response")}identifierLower := strings.ToLower(trimmed)@@ -531,10 +532,10 @@ func resolveVolume(ctx context.Context, c *client.Client, identifier string, allif len(matches) > 1 {if !allowPrompt {- return nil, fmt.Errorf("multiple volumes match %q; use the volume name or run `arcane volumes list`", trimmed)+ return nil, errors.Errorf("multiple volumes match %q; use the volume name or run `arcane volumes list`", trimmed)}if len(matches) > maxPromptOptions {- return nil, fmt.Errorf("multiple volumes match %q (%d results); refine your query or use the volume name", trimmed, len(matches))+ return nil, errors.Errorf("multiple volumes match %q (%d results); refine your query or use the volume name", trimmed, len(matches))}options := make([]string, 0, len(matches))@@ -552,7 +553,7 @@ func resolveVolume(ctx context.Context, c *client.Client, identifier string, allreturn &matches[choice], nil}- return nil, fmt.Errorf("volume %q not found; use the volume name or run `arcane volumes list`", trimmed)+ return nil, errors.Errorf("volume %q not found; use the volume name or run `arcane volumes list`", trimmed)}func volumeMatches(item volume.Volume, identifierLower, original string) bool {diff --git a/go.work.sum b/go.work.sumindex a8d44ead2..950729ac3 100644--- a/go.work.sum+++ b/go.work.sum@@ -310,6 +310,8 @@ cyphar.com/go-pathrs v0.2.1 h1:9nx1vOgwVvX1mNBWDu93+vaceedpbsDqo+XuBGL40b8=cyphar.com/go-pathrs v0.2.1/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc=cyphar.com/go-pathrs v0.2.4 h1:iD/mge36swa1UFKdINkr1Frkpp6wZsy3YYEildj9cLY=cyphar.com/go-pathrs v0.2.4/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc=+emperror.dev/emperror v0.33.0/go.mod h1:CeOIKPcppTE8wn+3xBNcdzdHMMIP77sLOHS0Ik56m+w=+emperror.dev/errors v0.8.0/go.mod h1:YcRvLPh626Ubn2xqtoprejnA5nFha+TJ+2vew48kWuE=filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=@@ -2076,14 +2078,10 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ=go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=-go.getarcane.app/sys/cgroup v0.1.1 h1:c39W8FDqMXlKOZrpH+itaY+t8oC0tva0+6ztTrKvVIg=-go.getarcane.app/sys/cgroup v0.1.1/go.mod h1:2dUDhWV8qe9LRnLIqa5VQDhdWbTQ04EepttdIAe9dcM=go.getarcane.app/updater v0.3.6 h1:+BqoycaRsHj+cLVSzcYQuqbHxUKbtmaozMNblz5bVSw=go.getarcane.app/updater v0.3.6/go.mod h1:2ENitZR/lA5MuBn60OZYR5wvU3ZCE+pAgfrebfOlRDA=go.getarcane.app/updater v0.3.7 h1:WqHsxudvt8gvCR7iSHdxdzwH0+hM0FAh64bSypBX9Mo=go.getarcane.app/updater v0.3.7/go.mod h1:9RZOKaBbpUJfVA4Q9/jvqtjvWBwCnVw0OkPeQCnqAAo=-go.getarcane.app/updater v0.6.1 h1:kcRYGwLV+lbkpz6zCdDKM7PgvHnsKBAcyURNmAO4fI4=-go.getarcane.app/updater v0.6.1/go.mod h1:AVEBD3dbm+p8FOkkXGH7yDe2bHMadkYmLo5e9ajHnzI=go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9VI=go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng=go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=diff --git a/types/go.mod b/types/go.modindex 68b14788e..668fa792e 100644--- a/types/go.mod+++ b/types/go.mod@@ -3,6 +3,7 @@ module github.com/getarcaneapp/arcane/types/v2go 1.26.5require (+ emperror.dev/errors v0.8.1github.com/compose-spec/compose-go/v2 v2.13.0github.com/docker/go-units v0.5.0github.com/moby/moby/api v1.55.0@@ -25,6 +26,7 @@ require (github.com/moby/docker-image-spec v1.3.1 // indirectgithub.com/opencontainers/go-digest v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.1.1 // indirect+ github.com/pkg/errors v0.9.1 // indirectgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirectgithub.com/sirupsen/logrus v1.9.4 // indirectgithub.com/xhit/go-str2duration/v2 v2.1.0 // indirect@@ -33,6 +35,7 @@ require (go.opentelemetry.io/otel v1.44.0 // indirectgo.opentelemetry.io/otel/metric v1.44.0 // indirectgo.opentelemetry.io/otel/trace v1.44.0 // indirect+ go.uber.org/multierr v1.11.0 // indirectgo.yaml.in/yaml/v4 v4.0.0-rc.6 // indirectgolang.org/x/sync v0.22.0 // indirectgolang.org/x/sys v0.47.0 // indirectdiff --git a/types/go.sum b/types/go.sumindex 3360c21b7..8e3e1a1b9 100644--- a/types/go.sum+++ b/types/go.sum@@ -1,3 +1,5 @@+emperror.dev/errors v0.8.1 h1:UavXZ5cSX/4u9iyvH6aDcuGkVjeexUGJ7Ij7G4VfQT0=+emperror.dev/errors v0.8.1/go.mod h1:YcRvLPh626Ubn2xqtoprejnA5nFha+TJ+2vew48kWuE=github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 h1:0kQAzHq8vLs7Pptv+7TxjdETLf/nIqJpIB4oC6Ba4vY=github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29/go.mod h1:ZWa7ssZJT30CCDGJ7fk/2SBTq9BIQrrVjrcss0UW2s0=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=@@ -8,6 +10,8 @@ github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYGgithub.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=@@ -41,10 +45,15 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=@@ -63,6 +72,10 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRkgo.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=+go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=+go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=diff --git a/types/project/marshal_utils.go b/types/project/marshal_utils.goindex de92864bb..e9c3d0d29 100644--- a/types/project/marshal_utils.go+++ b/types/project/marshal_utils.go@@ -3,10 +3,10 @@ package projectimport ("encoding/json/jsontext"json "encoding/json/v2"- "fmt""strconv""strings"+ "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/go-units")@@ -37,7 +37,7 @@ var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decode}parsed = int64(floatValue)if floatValue != float64(parsed) {- return fmt.Errorf("invalid UnitBytes value %q", raw)+ return errors.Errorf("invalid UnitBytes value %q", raw)}}*value = composetypes.UnitBytes(parsed)@@ -45,10 +45,10 @@ var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decodecase jsontext.KindInvalid, jsontext.KindFalse, jsontext.KindTrue,jsontext.KindBeginObject, jsontext.KindEndObject,jsontext.KindBeginArray, jsontext.KindEndArray:- return fmt.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())+ return errors.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())}- return fmt.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())+ return errors.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())})type runtimeServiceAlias RuntimeService