Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: use std lib errors (#4263)
Kyle Mendellc37464376e07
diff --git a/.github/.golangci.yml b/.github/.golangci.ymlindex d3648e4c5..e860247a0 100644--- a/.github/.golangci.yml+++ b/.github/.golangci.yml@@ -26,7 +26,6 @@ linters:- exhaustive- exptostd- fatcontext- - forbidigo- forcetypeassert- ginkgolinter- gocheckcompilerdirectives@@ -44,7 +43,6 @@ linters:- govet- grouper- iface- - importas- inamedparam- ineffassign- interfacebloat@@ -95,20 +93,12 @@ linters:type: moduledescription: Detects suspicious Go function implementations.original-url: https://go.ofkm.dev/shimbad- forbidigo:- forbid:- - pattern: ^errors\.(Wrap|Wrapf|WithStack)$- msg: use WrapIf, WrapIff, or WithStackIf so an existing stack is preservedgomoddirectives:replace-local: truereplace-allow-list:# Copacetic v0.14.2 only compiles against the buildx v0.32 imagetools# API; drop once copa supports buildx >= 0.35 and the pin is removed.- github.com/docker/buildx- importas:- alias:- - pkg: errors- alias: stderrorsexclusions:generated: laxpresets:@@ -126,9 +116,6 @@ linters:- linters:- revivetext: "exported:"- - linters:- - forbidigo- path: cli/# Endpoint path builders are intentional one-line functions.- linters:- shimbaddiff --git a/AGENTS.md b/AGENTS.mdindex f7c5c70c0..9bd8f4852 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -89,8 +89,9 @@ the environment proxy, and embedded frontend delivery.Handlers translate typed HTTP data and call services. They do not contain businesslogic. Services receive dependencies through constructors/Fx. Use `slog` for-structured logging and the existing `emperror.dev/errors` and `internal/common`-patterns for wrapped or semantic errors.+structured logging, standard `errors` and `fmt.Errorf("…: %w")` for wrapping,+`internal/common.Classify` for semantic errors, and `types/base.FieldError` for+validation fields.Before adding backend logic, search the owning domain plus:diff --git a/backend/api/buildables.go b/backend/api/buildables.goindex a62c763bc..f89b2f0bf 100644--- a/backend/api/buildables.go+++ b/backend/api/buildables.go@@ -3,10 +3,10 @@package apiimport (+ "errors""net/http""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/buildables""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"@@ -97,8 +97,8 @@ func registerAutoLoginRoutes(apiGroup *echo.Group, authService *auth.AuthServiceStatus: authtypes.AuthenticationStatusAuthenticated,Token: tokenPair.AccessToken,RefreshToken: tokenPair.RefreshToken,- ExpiresAt: &expiresAt,- User: &userResp,+ ExpiresAt: new(expiresAt),+ User: new(userResp),},})})diff --git a/backend/api/handlers/diagnostics.go b/backend/api/handlers/diagnostics.goindex d080af530..58466bb44 100644--- a/backend/api/handlers/diagnostics.go+++ b/backend/api/handlers/diagnostics.go@@ -4,7 +4,6 @@ import ("context""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics"@@ -87,7 +86,7 @@ func (h *DiagnosticsHandler) GetRecentLogs(_ context.Context, _ *DiagnosticsInpufunc (h *DiagnosticsHandler) ScanGoroutineLeaks(_ context.Context, _ *ScanGoroutineLeaksInput) (*ScanGoroutineLeaksOutput, error) {report, err := h.diag.ScanGoroutineLeaks()if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to collect goroutine leak profile").Error())+ return nil, huma.Error500InternalServerError("Failed to collect goroutine leak profile: " + err.Error())}return &ScanGoroutineLeaksOutput{Body: report}, nil}diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.goindex 1e3130b81..af2f72bf8 100644--- a/backend/api/json_serializer.go+++ b/backend/api/json_serializer.go@@ -4,10 +4,10 @@ import (jsonv1 "encoding/json""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""net/http"- "emperror.dev/errors""github.com/labstack/echo/v5""go.getarcane.app/kit/normalization")@@ -34,8 +34,7 @@ func (jsonV2Serializer) Deserialize(c *echo.Context, value any) error {return nil}- var semanticErr *json.SemanticError- if errors.As(err, &semanticErr) {+ if semanticErr, ok := errors.AsType[*json.SemanticError](err); ok {return echo.NewHTTPError(http.StatusBadRequest,fmt.Sprintf(@@ -48,8 +47,7 @@ func (jsonV2Serializer) Deserialize(c *echo.Context, value any) error {).Wrap(err)}- var syntacticErr *jsontext.SyntacticError- if errors.As(err, &syntacticErr) {+ if syntacticErr, ok := errors.AsType[*jsontext.SyntacticError](err); ok {return echo.NewHTTPError(http.StatusBadRequest,fmt.Sprintf("Syntax error: offset=%v, error=%v", syntacticErr.ByteOffset, syntacticErr.Error()),diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.goindex 58ce90472..f0df29378 100644--- a/backend/api/webhooks_trigger.go+++ b/backend/api/webhooks_trigger.go@@ -1,9 +1,9 @@package apiimport (+ "errors""net/http"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/webhook""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/api/ws/container_stats.go b/backend/api/ws/container_stats.goindex f7a2c6ddb..f11d372d6 100644--- a/backend/api/ws/container_stats.go+++ b/backend/api/ws/container_stats.go@@ -3,13 +3,13 @@ package wsimport ("context""encoding/json/v2"+ "errors""log/slog""net/http""strings""sync""time"- "emperror.dev/errors"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/labstack/echo/v5"diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.goindex 87fdff629..1c29692d4 100644--- a/backend/api/ws/diagnostics.go+++ b/backend/api/ws/diagnostics.go@@ -204,3 +204,10 @@ func diagnosticsReadLoopInternal(ctx context.Context, conn *websocket.Conn) <-ch}()return done}++var defaultLogBroadcaster = logs.New(1000)++// LogBroadcaster returns the backend-wide log broadcaster used by diagnostics.+func LogBroadcaster() *logs.Broadcaster {+ return defaultLogBroadcaster+}diff --git a/backend/api/ws/exec.go b/backend/api/ws/exec.goindex edb3adadd..b061c7212 100644--- a/backend/api/ws/exec.go+++ b/backend/api/ws/exec.go@@ -3,6 +3,8 @@ package wsimport ("cmp""context"+ "errors"+ "fmt""io""log/slog""net/http"@@ -10,7 +12,6 @@ import ("sync""time"- "emperror.dev/errors""github.com/coder/websocket"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system"@@ -63,15 +64,15 @@ func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancelexecID, err := h.containerService.CreateExec(ctx, containerID, []string{shell})if err != nil {- h.writeExecErrorInternal(ctx, conn, errors.WithMessage(err, "Error creating exec"))- closeExecInternal(ctx, conn, containerID, "", started, errors.WithMessage(err, "create exec"))+ h.writeExecErrorInternal(ctx, conn, fmt.Errorf("Error creating exec: %w", err)) //nolint:staticcheck // Preserve the existing error message.+ closeExecInternal(ctx, conn, containerID, "", started, fmt.Errorf("create exec: %w", err))return}execSession, err := h.containerService.AttachExec(ctx, containerID, execID)if err != nil {- h.writeExecErrorInternal(ctx, conn, errors.WithMessage(err, "Error attaching to exec"))- closeExecInternal(ctx, conn, containerID, execID, started, errors.WithMessage(err, "attach exec"))+ h.writeExecErrorInternal(ctx, conn, fmt.Errorf("Error attaching to exec: %w", err)) //nolint:staticcheck // Preserve the existing error message.+ closeExecInternal(ctx, conn, containerID, execID, started, fmt.Errorf("attach exec: %w", err))return}// Cleanup must proceed even if the parent ctx is canceled, and must also@@ -152,13 +153,13 @@ func (h *WebSocketHandler) pipeExecOutputInternal(ctx context.Context, conn *webif errors.Is(err, io.EOF) {done <- nil} else {- done <- errors.WithMessage(err, "exec output read")+ done <- fmt.Errorf("exec output read: %w", err)}return}if n > 0 {if err := conn.Write(ctx, websocket.MessageBinary, buf[:n]); err != nil {- done <- errors.WithMessage(err, "websocket write")+ done <- fmt.Errorf("websocket write: %w", err)return}}@@ -169,11 +170,11 @@ func (h *WebSocketHandler) pipeExecInputInternal(ctx context.Context, cancel confor {_, data, err := conn.Read(ctx)if err != nil {- cancel(errors.WithMessage(err, "websocket read"))+ cancel(fmt.Errorf("websocket read: %w", err))return}if _, err := stdin.Write(data); err != nil {- cancel(errors.WithMessage(err, "exec input write"))+ cancel(fmt.Errorf("exec input write: %w", err))return}}diff --git a/backend/api/ws/log_streams.go b/backend/api/ws/log_streams.goindex 57b295b44..a87e7611c 100644--- a/backend/api/ws/log_streams.go+++ b/backend/api/ws/log_streams.go@@ -4,6 +4,7 @@ import ("cmp""context""encoding/json/v2"+ "errors""log/slog""net/http""strconv"@@ -11,7 +12,6 @@ import ("sync/atomic""time"- "emperror.dev/errors"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/labstack/echo/v5"diff --git a/backend/api/ws/logs.go b/backend/api/ws/logs.godeleted file mode 100644index a8a3ec724..000000000--- a/backend/api/ws/logs.go+++ /dev/null@@ -1,10 +0,0 @@-package ws--import "go.getarcane.app/streams/logs"--var defaultLogBroadcaster = logs.New(1000)--// LogBroadcaster returns the backend-wide log broadcaster used by diagnostics.-func LogBroadcaster() *logs.Broadcaster {- return defaultLogBroadcaster-}diff --git a/backend/cli/admin/reset_mfa.go b/backend/cli/admin/reset_mfa.goindex e119bc59e..19935b8a6 100644--- a/backend/cli/admin/reset_mfa.go+++ b/backend/cli/admin/reset_mfa.go@@ -2,12 +2,12 @@ package adminimport ("bufio"+ "errors""fmt""io""log/slog""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/database"@@ -48,7 +48,7 @@ func runResetMFACommandInternal(cmd *cobra.Command, _ []string) error {db, err := database.Initialize(cmd.Context(), cfg.DatabaseURL, database.MigrationOptions{AllowDowngrade: cfg.AllowDowngrade})if err != nil {- return errors.WrapIf(err, "failed to initialize database")+ return fmt.Errorf("failed to initialize database: %w", err)}defer func() {if closeErr := db.Close(); closeErr != nil {@@ -60,18 +60,18 @@ func runResetMFACommandInternal(cmd *cobra.Command, _ []string) error {user, err := userService.GetUserByUsername(cmd.Context(), username)if err != nil {if errors.Is(err, common.ErrUserNotFound) {- return errors.Errorf("user %q not found", username)+ return fmt.Errorf("user %q not found", username)}- return errors.WrapIf(err, "failed to find user")+ return fmt.Errorf("failed to find user: %w", err)}passkeyService := passkey.NewPasskeyService(db, cfg)if err := passkeyService.ResetMFAForUser(cmd.Context(), user.ID); err != nil {- return errors.WrapIf(err, "failed to reset passkey MFA")+ return fmt.Errorf("failed to reset passkey MFA: %w", err)}if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Passkey MFA reset successfully for %q\n", username); err != nil {- return errors.WrapIf(err, "failed to write MFA reset result")+ return fmt.Errorf("failed to write MFA reset result: %w", err)}return nil}@@ -91,11 +91,11 @@ func confirmMFAResetInternal(in io.Reader, out io.Writer, username string) errorreturn errors.New("confirmation input and output are required")}if _, err := fmt.Fprintf(out, "This will disable passkey MFA and revoke all sessions for %q. Type RESET to continue: ", username); err != nil {- return errors.WrapIf(err, "failed to write MFA reset confirmation")+ return fmt.Errorf("failed to write MFA reset confirmation: %w", err)}answer, err := bufio.NewReader(in).ReadString('\n')if err != nil && !errors.Is(err, io.EOF) {- return errors.WrapIf(err, "failed to read MFA reset confirmation")+ return fmt.Errorf("failed to read MFA reset confirmation: %w", err)}if strings.TrimSpace(answer) != "RESET" {return errors.New("MFA reset cancelled")diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.goindex 351e09625..2bf0ac3ff 100644--- a/backend/cli/admin/reset_password.go+++ b/backend/cli/admin/reset_password.go@@ -2,13 +2,13 @@ package adminimport ("context"+ "errors""fmt""io""log/slog""os""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/database"@@ -61,7 +61,7 @@ func runResetPasswordCommandInternal(cmd *cobra.Command, _ []string) error {AllowDowngrade: cfg.AllowDowngrade,})if err != nil {- return errors.WrapIf(err, "failed to initialize database")+ return fmt.Errorf("failed to initialize database: %w", err)}defer func() {if closeErr := db.Close(); closeErr != nil {@@ -81,7 +81,7 @@ func runResetPasswordCommandInternal(cmd *cobra.Command, _ []string) error {}if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Password reset successfully for global administrator %q\n", username); err != nil {- return errors.WrapIf(err, "failed to write password reset result")+ return fmt.Errorf("failed to write password reset result: %w", err)}return nil}@@ -99,12 +99,12 @@ func ensurePasswordResetEnabledInternal(cfg *config.Config) error {func readNewPasswordInternal(out io.Writer, policy string) (string, error) {password, err := readPasswordInternal(out, "New password: ")if err != nil {- return "", errors.WrapIf(err, "failed to read new password")+ return "", fmt.Errorf("failed to read new password: %w", err)}confirmation, err := readPasswordInternal(out, "Confirm new password: ")if err != nil {- return "", errors.WrapIf(err, "failed to read password confirmation")+ return "", fmt.Errorf("failed to read password confirmation: %w", err)}if err := validatePasswordPairInternal(password, confirmation, policy); err != nil {@@ -161,21 +161,21 @@ func resetPasswordInternal(ctx context.Context, db *database.DB, username, passwtarget, err := userService.GetUserByUsername(ctx, username)if err != nil {if errors.Is(err, common.ErrUserNotFound) {- return errors.Errorf("global administrator %q not found", username)+ return fmt.Errorf("global administrator %q not found", username)}- return errors.WrapIf(err, "failed to find user")+ return fmt.Errorf("failed to find user: %w", err)}permissions, err := roleService.ResolvePermissions(ctx, target)if err != nil {- return errors.WrapIf(err, "failed to resolve user permissions")+ return fmt.Errorf("failed to resolve user permissions: %w", err)}if permissions == nil || !permissions.IsGlobalAdmin() {- return errors.Errorf("user %q does not have effective global administrator permissions", username)+ return fmt.Errorf("user %q does not have effective global administrator permissions", username)}if _, err := userService.SetPasswordAndRevokeSessionsExcept(ctx, target, password, ""); err != nil {- return errors.WrapIf(err, "failed to reset password")+ return fmt.Errorf("failed to reset password: %w", err)}return nildiff --git a/backend/cli/health.go b/backend/cli/health.goindex 1992417d9..6b2d72805 100644--- a/backend/cli/health.go+++ b/backend/cli/health.go@@ -3,6 +3,8 @@ package cliimport ("cmp""context"+ "errors"+ "fmt""net""net/http""net/url"@@ -10,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/spf13/cobra")@@ -49,7 +50,7 @@ func buildHealthURLInternal(cfg *config.Config) (string, error) {port := cmp.Or(strings.TrimSpace(cfg.Port), defaultHealthPort)if _, err := strconv.Atoi(port); err != nil {- return "", errors.WrapIff(err, "invalid health port %q", port)+ return "", fmt.Errorf("invalid health port %q: %w", port, err)}hostPort := net.JoinHostPort(healthHost, port)@@ -75,20 +76,20 @@ func runHealthCommandInternal(ctx context.Context, cfg *config.Config, timeout trequest, err := http.NewRequestWithContext(ctx, http.MethodHead, healthURL, nil)if err != nil {- return errors.WrapIf(err, "health check request creation failed")+ return fmt.Errorf("health check request creation failed: %w", err)}client := &http.Client{Timeout: timeout}resp, err := client.Do(request)if err != nil {- return errors.WrapIf(err, "health check request failed")+ return fmt.Errorf("health check request failed: %w", err)}defer func() {_ = resp.Body.Close()}()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return errors.Errorf("health check failed with status %d", resp.StatusCode)+ return fmt.Errorf("health check failed with status %d", resp.StatusCode)}return nildiff --git a/backend/cli/recovery/recovery.go b/backend/cli/recovery/recovery.goindex 8e370a39a..3d96bac3d 100644--- a/backend/cli/recovery/recovery.go+++ b/backend/cli/recovery/recovery.go@@ -4,13 +4,13 @@ import ("cmp""context""encoding/json/v2"+ "errors""fmt""log/slog""os""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/cli/upgrade""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -91,10 +91,10 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {// stopped rather than running with mismatched data and projects.err = fmt.Errorf("rustic system restore failed: %w", err)if len(request.RollbackStages) == 0 {- return errors.Combine(err, errors.New("no pre-restore system backup is available for rollback; Arcane was left stopped"))+ return errors.Join(err, errors.New("no pre-restore system backup is available for rollback; Arcane was left stopped"))}if rollbackErr := runStagesInternal(context.WithoutCancel(ctx), dockerClient, request, request.RollbackStages); rollbackErr != nil {- return errors.Combine(err, fmt.Errorf("restoring the pre-restore system backup failed; Arcane was left stopped: %w", rollbackErr))+ return errors.Join(err, fmt.Errorf("restoring the pre-restore system backup failed; Arcane was left stopped: %w", rollbackErr))}rollbackManifest, readErr := os.ReadFile("/app/data/.arcane-recovery.json")var rollback recoverytypes.Manifest@@ -105,7 +105,7 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {readErr = francis.ClearRestoredHosts(context.WithoutCancel(ctx), rollback.Environment["DATABASE_URL"])}if readErr != nil {- return errors.Combine(err, fmt.Errorf("clear restored actor ownership; Arcane was left stopped: %w", readErr))+ return errors.Join(err, fmt.Errorf("clear restored actor ownership; Arcane was left stopped: %w", readErr))}restart()return fmt.Errorf("%w; the pre-restore system backup was restored", err)diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.goindex 6f726a122..329deb25a 100644--- a/backend/cli/upgrade/upgrade.go+++ b/backend/cli/upgrade/upgrade.go@@ -3,6 +3,7 @@ package upgradeimport ("cmp""context"+ "errors""fmt""log/slog""maps"@@ -10,7 +11,6 @@ import ("strings""time"- "emperror.dev/errors"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -71,7 +71,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {// Connect to DockerdockerClient, err := client.New(client.FromEnv)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}defer func() { _ = dockerClient.Close() }()@@ -81,14 +81,14 @@ func runUpgrade(cmd *cobra.Command, args []string) error {slog.Info("Auto-detecting Arcane container...")targetContainer, err = findArcaneContainer(ctx, dockerClient)if err != nil {- return errors.WrapIf(err, "failed to find Arcane container")+ return fmt.Errorf("failed to find Arcane container: %w", err)}containerName = strings.TrimPrefix(targetContainer.Name, "/")slog.Info("Found Arcane container", "name", containerName, "id", targetContainer.ID[:12])} else {inspectResult, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerName, client.ContainerInspectOptions{})if inspectErr != nil {- return errors.WrapIff(inspectErr, "failed to inspect container %s", containerName)+ return fmt.Errorf("failed to inspect container %s: %w", containerName, inspectErr)}targetContainer = inspectResult.Container}@@ -103,7 +103,7 @@ 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 errors.WrapIf(err, "failed to pull image")+ return fmt.Errorf("failed to pull image: %w", err)}// The pull always runs so a mutable tag gets re-resolved, but when it lands on@@ -118,7 +118,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {// Perform the upgradeslog.Info("Starting container upgrade", "container", containerName)if err := UpgradeContainer(ctx, dockerClient, targetContainer, imageToPull, nil); err != nil {- return errors.WrapIf(err, "failed to upgrade container")+ return fmt.Errorf("failed to upgrade container: %w", err)}slog.Info("Upgrade completed successfully", "container", containerName, "image", imageToPull)@@ -452,7 +452,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldContaoldName := fmt.Sprintf("%s-old-%d", originalName, time.Now().UnixNano())if oldContainer.Config == nil {- return errors.Errorf("container %s inspection has no config; refusing to recreate", originalName)+ return fmt.Errorf("container %s inspection has no config; refusing to recreate", originalName)}// Create new container config@@ -467,7 +467,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldContahostConfig, sanitizedMemorySwappiness, engineInfo, err := compat.PrepareRecreateHostConfigForEngine(ctx, dockerClient, oldContainer.HostConfig)if err != nil {- return errors.WrapIf(err, "prepare host config")+ return fmt.Errorf("prepare host config: %w", err)}if sanitizedMemorySwappiness {slog.Info("Stripped unsupported host config field for recreate",@@ -486,7 +486,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta}hostConfig.Binds, hostConfig.Mounts, err = docker.PreserveVolumeMounts(hostConfig.Binds, hostConfig.Mounts, oldContainer.Mounts)if err != nil {- return errors.WrapIff(err, "preserve volumes of container %s", originalName)+ return fmt.Errorf("preserve volumes of container %s: %w", originalName, err)}// Fix for "conflicting options: hostname and the network mode"@@ -539,14 +539,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 errors.WrapIf(err, "rename old container")+ return fmt.Errorf("rename old container: %w", err)}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 errors.WrapIf(err, "stop old container")+ return fmt.Errorf("stop old container: %w", err)}fmt.Println("PROGRESS:75:Creating new container")@@ -561,7 +561,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 errors.WrapIf(err, "create new container")+ return fmt.Errorf("create new container: %w", err)}fmt.Println("PROGRESS:80:Starting new container")@@ -571,7 +571,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 errors.WrapIf(err, "start new container")+ return fmt.Errorf("start new container: %w", err)}// Wait a moment for the new container to initializediff --git a/backend/frontend/excluded.go b/backend/frontend/excluded.goindex d9d01773b..1653a0b85 100644--- a/backend/frontend/excluded.go+++ b/backend/frontend/excluded.go@@ -4,7 +4,6 @@ package frontendimport "github.com/labstack/echo/v5"-//nolint:shimbad // build-tag stub: the real implementation lives in frontend.gofunc RegisterFrontend(e *echo.Echo) error {_ = ereturn ErrFrontendNotIncludeddiff --git a/backend/frontend/frontend.go b/backend/frontend/frontend.goindex a85e2f7e0..0f46cf191 100644--- a/backend/frontend/frontend.go+++ b/backend/frontend/frontend.go@@ -5,12 +5,12 @@ package frontendimport ("cmp""embed"+ "fmt""io/fs""mime""path""strings"- "emperror.dev/errors""github.com/labstack/echo/v5""github.com/labstack/echo/v5/middleware")@@ -24,15 +24,15 @@ const indexHtmlFileConstant = "index.html"func RegisterFrontend(e *echo.Echo) error {distFS, err := fs.Sub(frontendFS, "dist")if err != nil {- return errors.WrapIf(err, "failed to create sub FS")+ return fmt.Errorf("failed to create sub FS: %w", err)}if err := mime.AddExtensionType(".webmanifest", "application/manifest+json"); err != nil {- return errors.WrapIf(err, "failed to register web manifest MIME type")+ return fmt.Errorf("failed to register web manifest MIME type: %w", err)}appFS, err := fs.Sub(distFS, "_app")if err != nil {- return errors.WrapIf(err, "failed to create app sub FS")+ return fmt.Errorf("failed to create app sub FS: %w", err)}skipAPI := func(c *echo.Context) bool {diff --git a/backend/frontend/shared.go b/backend/frontend/shared.goindex c3eebb4d4..d3ebfc1b9 100644--- a/backend/frontend/shared.go+++ b/backend/frontend/shared.go@@ -1,5 +1,5 @@package frontend-import "emperror.dev/errors"+import "errors"-const ErrFrontendNotIncluded = errors.Sentinel("frontend is not included")+var ErrFrontendNotIncluded = errors.New("frontend is not included")diff --git a/backend/go.mod b/backend/go.modindex 5a262437d..8f05bcefc 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -3,16 +3,12 @@ module github.com/getarcaneapp/arcane/backend/v2go 1.27.1replace (- // Copacetic v0.14.2 only compiles against the buildx v0.32 imagetools API;- // drop this pin once copa supports buildx >= 0.35 and the dependency is bumped.github.com/docker/buildx => github.com/docker/buildx v0.32.1github.com/getarcaneapp/arcane/cli/v2 => ../cligithub.com/getarcaneapp/arcane/types/v2 => ../types)require (- emperror.dev/emperror v0.33.0- emperror.dev/errors v0.8.1github.com/ProtonMail/go-crypto v1.5.2github.com/aws/aws-sdk-go-v2 v1.47.1github.com/aws/aws-sdk-go-v2/config v1.33.6diff --git a/backend/go.sum b/backend/go.sumindex 3a17f05de..e5cb09b7c 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -35,11 +35,6 @@ connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGRdario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=-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=@@ -803,7 +798,6 @@ go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu6go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=-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=@@ -812,7 +806,6 @@ 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.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=diff --git a/backend/internal/activity/backup.go b/backend/internal/activity/backup.godeleted file mode 100644index 508fe085a..000000000--- a/backend/internal/activity/backup.go+++ /dev/null@@ -1,30 +0,0 @@-package activity--import (- "context"-- "emperror.dev/errors"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-)--// FailInterruptedBackups finalizes backup activities before startup admits work.-func (s *ActivityService) FailInterruptedBackups(ctx context.Context, protectedIDs ...string) error {- var pending []Activity- if err := s.db.WithContext(ctx).Where("status IN ?", []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}).Where("id NOT IN ?", append(protectedIDs, "")).Find(&pending).Error; err != nil {- return errors.WrapIf(err, "find interrupted backup activities")- }- const message = "Backup interrupted by Arcane restart"- var result error- for _, entry := range pending {- if s.isTrackedInternal(entry.ID) {- continue- }- switch entry.Metadata["action"] {- case "create_volume_backup", "create_system_backup", "run_system_volume_backups", "scheduled_volume_backup", "scheduled_system_backup":- errMessage := message- _, err := s.CompleteActivity(ctx, entry.ID, activitytypes.StatusFailed, message, &errMessage)- result = errors.Combine(result, err)- }- }- return result-}diff --git a/backend/internal/activity/handler.go b/backend/internal/activity/handler.goindex bbaa65e6a..bd1c83c74 100644--- a/backend/internal/activity/handler.go+++ b/backend/internal/activity/handler.go@@ -3,6 +3,7 @@ package activityimport ("cmp""context"+ "errors""fmt""maps""net/http"@@ -11,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment"diff --git a/backend/internal/activity/job.go b/backend/internal/activity/job.goindex d5a56f7a3..b3892134a 100644--- a/backend/internal/activity/job.go+++ b/backend/internal/activity/job.go@@ -3,9 +3,10 @@ package activityimport ("cmp""context"+ "errors"+ "fmt""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"st "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -57,7 +58,7 @@ func (s *ActivityService) SyncJobRun(ctx context.Context, run st.Run, name strin"metadata": model.Metadata, "updated_at": model.UpdatedAt,}).Error}); err != nil {- return errors.WrapIf(err, "synchronize job activity")+ return fmt.Errorf("synchronize job activity: %w", err)}if changed {// Ordinary activities cannot reopen. Job summaries can, after an explicitdiff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.goindex 65b9b63a0..03f2916b8 100644--- a/backend/internal/activity/service.go+++ b/backend/internal/activity/service.go@@ -3,7 +3,8 @@ package activityimport ("cmp""context"- stderrors "errors"+ "errors"+ "fmt""hash/fnv""log/slog""maps"@@ -12,7 +13,6 @@ 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/settings"@@ -45,7 +45,6 @@ const (// ErrActivityNotCancelable indicates the activity has already reached a terminal// state and can no longer be cancelled.- 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.@@ -56,6 +55,8 @@ const (deleteActivitiesBatchSize = 500)+var ErrActivityNotCancelable = errors.New("activity is not cancelable")+type ActivityService struct {db *database.DB@@ -361,7 +362,7 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityReif slotRelease != nil {slotRelease()}- return nil, errors.WrapIf(err, "failed to create activity")+ return nil, fmt.Errorf("failed to create activity: %w", err)}if slotRelease != nil {s.registerSlotReleaseInternal(model.ID, slotRelease)@@ -511,13 +512,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(&Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update activity")+ return fmt.Errorf("failed to update activity: %w", result.Error)}if result.RowsAffected == 0 {return errors.New("activity not found")}if err := tx.First(&model, "id = ?", activityID).Error; err != nil {- return errors.WrapIf(err, "failed to load updated activity")+ return fmt.Errorf("failed to load updated activity: %w", err)}return nil}); err != nil {@@ -653,22 +654,22 @@ func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, actiif errors.Is(err, gorm.ErrRecordNotFound) {return errors.New("activity not found")}- return errors.WrapIf(err, "failed to load activity")+ return fmt.Errorf("failed to load activity: %w", err)}if err := tx.Create(&messages).Error; err != nil {- return errors.WrapIf(err, "failed to append activity message")+ return fmt.Errorf("failed to append activity message: %w", err)}result := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update activity latest message")+ return fmt.Errorf("failed to update activity latest message: %w", result.Error)}if result.RowsAffected == 0 {return errors.New("activity not found")}if err := tx.First(¤t, "id = ?", activityID).Error; err != nil {- return errors.WrapIf(err, "failed to load updated activity")+ return fmt.Errorf("failed to load updated activity: %w", err)}return nil})@@ -717,15 +718,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 errors.WrapIf(err, "failed to load activity")+ return fmt.Errorf("failed to load activity: %w", err)}updates := completeActivityUpdatesInternal(model.StartedAt, status, finalMessage, errMessage, finalStep, now)if err := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(updates).Error; err != nil {- return errors.WrapIf(err, "failed to complete activity")+ return fmt.Errorf("failed to complete activity: %w", err)}if err := tx.First(&model, "id = ?", activityID).Error; err != nil {- return errors.WrapIf(err, "failed to load completed activity")+ return fmt.Errorf("failed to load completed activity: %w", err)}return nil})@@ -849,13 +850,13 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, actWhere("id = ? AND status IN ?", activityID, []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to cancel activity")+ return fmt.Errorf("failed to cancel activity: %w", result.Error)}if result.RowsAffected == 0 {return ErrActivityNotCancelable}if err := tx.First(&finalized, "id = ? AND environment_id = ?", activityID, environmentID).Error; err != nil {- return errors.WrapIf(err, "failed to load cancelled activity")+ return fmt.Errorf("failed to load cancelled activity: %w", err)}return nil}); err != nil {@@ -879,7 +880,7 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64if err := s.db.WithContext(ctx).Where("type = ? AND status = ? AND started_at < ?", activitytypes.TypeImageUpdateCheck, activitytypes.StatusRunning, cutoff).Find(&staleChecks).Error; err != nil {- return 0, errors.WrapIf(err, "find stale image update checks")+ return 0, fmt.Errorf("find stale image update checks: %w", err)}const message = "Image update check failed because it was stale after Arcane restarted"@@ -888,13 +889,13 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64var failErrs []errorfor i := range staleChecks {if _, err := s.CompleteActivity(ctx, staleChecks[i].ID, activitytypes.StatusFailed, message, &errMessage, "Image update check failed"); err != nil {- failErrs = append(failErrs, errors.WrapIff(err, "fail stale image update check %s", staleChecks[i].ID))+ failErrs = append(failErrs, fmt.Errorf("fail stale image update check %s: %w", staleChecks[i].ID, err))continue}failed++}- return failed, stderrors.Join(failErrs...)+ return failed, errors.Join(failErrs...)}// isTrackedInternal reports whether activityID has a live work registration in@@ -930,7 +931,7 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eWhere("status IN ? AND started_at < ?", activeStatuses, cutoff).Where("type <> ?", activitytypes.TypeJobRun).Find(&candidates).Error; err != nil {- return 0, errors.WrapIf(err, "find abandoned activities")+ return 0, fmt.Errorf("find abandoned activities: %w", err)}const message = "Activity was marked failed because its worker is no longer running"@@ -952,18 +953,18 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eWhere("id = ? AND status IN ?", activityID, activeStatuses).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "fail abandoned activity")+ return fmt.Errorf("fail abandoned activity: %w", result.Error)}if result.RowsAffected == 0 {lostRace = truereturn nil}if err := tx.First(&finalized, "id = ?", activityID).Error; err != nil {- return errors.WrapIf(err, "load failed abandoned activity")+ return fmt.Errorf("load failed abandoned activity: %w", err)}return nil}); err != nil {- sweepErrs = append(sweepErrs, errors.WrapIff(err, "sweep activity %s", activityID))+ sweepErrs = append(sweepErrs, fmt.Errorf("sweep activity %s: %w", activityID, err))continue}if lostRace {@@ -975,7 +976,7 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, eswept++}- return swept, stderrors.Join(sweepErrs...)+ return swept, errors.Join(sweepErrs...)}// ResolveOrphanedQueuedActivities fails any activity still queued at startup.@@ -992,7 +993,7 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context, pWhere("type <> ?", activitytypes.TypeJobRun).Where("id NOT IN ?", append(protectedIDs, "")).Find(&queued).Error; err != nil {- return 0, errors.WrapIf(err, "find orphaned queued activities")+ return 0, fmt.Errorf("find orphaned queued activities: %w", err)}const message = "Queued activity was interrupted by an Arcane restart"@@ -1001,13 +1002,13 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context, pvar failErrs []errorfor i := range queued {if _, err := s.CompleteActivity(ctx, queued[i].ID, activitytypes.StatusFailed, message, &errMessage); err != nil {- failErrs = append(failErrs, errors.WrapIff(err, "fail orphaned queued activity %s", queued[i].ID))+ failErrs = append(failErrs, fmt.Errorf("fail orphaned queued activity %s: %w", queued[i].ID, err))continue}failed++}- return failed, stderrors.Join(failErrs...)+ return failed, errors.Join(failErrs...)}// PatchActivityMetadata merges patch into the activity's existing metadata,@@ -1027,7 +1028,7 @@ func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityIDreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var activity Activityif err := tx.First(&activity, "id = ?", activityID).Error; err != nil {- return errors.WrapIf(err, "failed to load activity")+ return fmt.Errorf("failed to load activity: %w", err)}merged := cloneJSONInternal(activity.Metadata)if merged == nil {@@ -1036,7 +1037,7 @@ func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityIDmaps.Copy(merged, patch)if err := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(map[string]any{"metadata": merged, "updated_at": time.Now()}).Error; err != nil {- return errors.WrapIf(err, "failed to patch activity metadata")+ return fmt.Errorf("failed to patch activity metadata: %w", err)}return nil})@@ -1056,7 +1057,7 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context,Where("type = ? AND status = ?", activitytypes.TypeAutoUpdate, activitytypes.StatusRunning).Where("id NOT IN ?", append(protectedIDs, "")).Find(&stale).Error; err != nil {- return 0, errors.WrapIf(err, "find stale auto-update activities")+ return 0, fmt.Errorf("find stale auto-update activities: %w", err)}var resolved int64@@ -1072,13 +1073,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, errors.WrapIff(err, "resolve stale auto-update activity %s", stale[i].ID))+ resolveErrs = append(resolveErrs, fmt.Errorf("resolve stale auto-update activity %s: %w", stale[i].ID, err))continue}resolved++}- return resolved, stderrors.Join(resolveErrs...)+ return resolved, errors.Join(resolveErrs...)}func completeActivityUpdatesInternal(startedAt time.Time, status activitytypes.Status, finalMessage string, errMessage *string, finalStep []string, now time.Time) map[string]any {@@ -1140,7 +1141,7 @@ func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environmepaginationResp, err := pagination.PaginateAndSortDB(params, q, &activities)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate activities")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate activities: %w", err)}out := make([]activitytypes.Activity, 0, len(activities))@@ -1162,7 +1163,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, errors.WrapIf(err, "failed to load activity")+ return nil, fmt.Errorf("failed to load activity: %w", err)}var messages []ActivityMessage@@ -1171,7 +1172,7 @@ func (s *ActivityService) GetActivityDetail(ctx context.Context, environmentID,Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load activity messages")+ return nil, fmt.Errorf("failed to load activity messages: %w", err)}outMessages := make([]activitytypes.Message, 0, len(messages))@@ -1200,10 +1201,9 @@ func (s *ActivityService) PruneHistory(ctx context.Context, retentionDays, maxEnif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if retentionDays > 0 {cutoff := time.Now().Add(-time.Duration(retentionDays) * 24 * time.Hour)- ids, err := findTerminalActivityIDsInternal(tx.- Where("COALESCE(ended_at, updated_at, created_at) < ?", cutoff))+ ids, err := findTerminalActivityIDsInternal(tx.Where("COALESCE(ended_at, updated_at, created_at) < ?", cutoff))if err != nil {- return errors.WrapIf(err, "failed to find activities older than retention window")+ return fmt.Errorf("failed to find activities older than retention window: %w", err)}count, err := deleteActivitiesByIDInternal(tx, ids)if err != nil {@@ -1243,7 +1243,7 @@ func (s *ActivityService) DeleteHistory(ctx context.Context, environmentID strinif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {ids, err := findTerminalActivityIDsInternal(scopeJobActivityVisibilityInternal(ctx, tx.Where("environment_id = ?", environmentID), environmentID, authz.PermActivitiesDelete))if err != nil {- return errors.WrapIf(err, "failed to find activity history")+ return fmt.Errorf("failed to find activity history: %w", err)}count, err := deleteActivitiesByIDInternal(tx, ids)if err != nil {@@ -1505,7 +1505,7 @@ func findActivityIDsBeyondHistoryLimitInternal(tx *gorm.DB, maxEntries int) ([]s) rankedWHERE ranked.activity_rank > ?`, terminalActivityStatusesInternal(), maxEntries).Scan(&activityIDs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to find excess activities")+ return nil, fmt.Errorf("failed to find excess activities: %w", err)}return activityIDs, nil}@@ -1521,11 +1521,11 @@ func deleteActivitiesByIDInternal(tx *gorm.DB, activityIDs []string) (int64, errbatch := activityIDs[i:end]if err := tx.Where("activity_id IN ?", batch).Delete(&ActivityMessage{}).Error; err != nil {- return totalDeleted, errors.WrapIf(err, "failed to delete activity messages")+ return totalDeleted, fmt.Errorf("failed to delete activity messages: %w", err)}result := tx.Where("id IN ?", batch).Delete(&Activity{})if result.Error != nil {- return totalDeleted, errors.WrapIf(result.Error, "failed to delete activities")+ return totalDeleted, fmt.Errorf("failed to delete activities: %w", result.Error)}totalDeleted += result.RowsAffected}@@ -1549,3 +1549,25 @@ func activityStartedByDTOInternal(model *Activity) *activitytypes.StartedBy {}return startedBy}++// FailInterruptedBackups finalizes backup activities before startup admits work.+func (s *ActivityService) FailInterruptedBackups(ctx context.Context, protectedIDs ...string) error {+ var pending []Activity+ if err := s.db.WithContext(ctx).Where("status IN ?", []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}).Where("id NOT IN ?", append(protectedIDs, "")).Find(&pending).Error; err != nil {+ return fmt.Errorf("find interrupted backup activities: %w", err)+ }+ const message = "Backup interrupted by Arcane restart"+ var result error+ for _, entry := range pending {+ if s.isTrackedInternal(entry.ID) {+ continue+ }+ switch entry.Metadata["action"] {+ case "create_volume_backup", "create_system_backup", "run_system_volume_backups", "scheduled_volume_backup", "scheduled_system_backup":+ errMessage := message+ _, err := s.CompleteActivity(ctx, entry.ID, activitytypes.StatusFailed, message, &errMessage)+ result = errors.Join(result, err)+ }+ }+ return result+}diff --git a/backend/internal/activity/visibility_test.go b/backend/internal/activity/visibility_test.goindex eb0b0073e..c368bd009 100644--- a/backend/internal/activity/visibility_test.go+++ b/backend/internal/activity/visibility_test.go@@ -17,8 +17,8 @@ func TestJobActivityVisibilityFiltersBeforePagination(t *testing.T) {db := setupActivityServiceTestDBInternal(t)service := NewActivityService(db, nil)for _, environmentID := range []string{"0", "private"} {- require.NoError(t, db.Create(&Activity{BaseModel: database.BaseModel{ID: environmentID + "-job"}, EnvironmentID: environmentID, Type: activitytypes.TypeJobRun, Status: activitytypes.StatusSuccess, StartedAt: time.Now(), Metadata: database.JSON{"environmentId": environmentID}}).Error)- require.NoError(t, db.Create(&Activity{BaseModel: database.BaseModel{ID: environmentID + "-pull"}, EnvironmentID: environmentID, Type: activitytypes.TypeImagePull, Status: activitytypes.StatusSuccess, StartedAt: time.Now()}).Error)+ require.NoError(t, db.Create(&Activity{ID: environmentID + "-job", EnvironmentID: environmentID, Type: activitytypes.TypeJobRun, Status: activitytypes.StatusSuccess, StartedAt: time.Now(), Metadata: database.JSON{"environmentId": environmentID}}).Error)+ require.NoError(t, db.Create(&Activity{ID: environmentID + "-pull", EnvironmentID: environmentID, Type: activitytypes.TypeImagePull, Status: activitytypes.StatusSuccess, StartedAt: time.Now()}).Error)}permissions := authz.NewPermissionSet()permissions.PerEnv["0"] = map[string]struct{}{authz.PermActivitiesRead: {}}diff --git a/backend/internal/apikey/handler.go b/backend/internal/apikey/handler.goindex c10898c9e..3799bdafc 100644--- a/backend/internal/apikey/handler.go+++ b/backend/internal/apikey/handler.go@@ -2,9 +2,9 @@ package apikeyimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -156,7 +156,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInputapiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())+ return nil, huma.Error500InternalServerError("Failed to list API keys: " + err.Error())}return &handlerutil.Page[apikeytypes.ApiKey]{@@ -271,7 +271,7 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*hakeys, err := h.apiKeyService.ListApiKeysByUser(ctx, user.ID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())+ return nil, huma.Error500InternalServerError("Failed to list API keys: " + err.Error())}return &handlerutil.Out[[]apikeytypes.ApiKey]{diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.goindex de2c7cdd9..c9c5c1537 100644--- a/backend/internal/apikey/service.go+++ b/backend/internal/apikey/service.go@@ -6,6 +6,8 @@ import ("crypto/rand""crypto/sha256""encoding/hex"+ "errors"+ "fmt""log/slog""maps""slices"@@ -14,7 +16,6 @@ import ("sync/atomic""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/role"@@ -29,11 +30,6 @@ import ()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")-apiKeyPrefix = "arc_"apiKeyLength = 32apiKeyPrefixLen = 8@@ -45,12 +41,22 @@ const (// ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an// API key permissions they themselves do not hold.- 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.- ErrApiKeyPersonalNoGrants = errors.Sentinel("personal API keys inherit the owner's permissions and cannot carry grants")++)++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")++ ErrApiKeyPermissionEscalation = errors.New("cannot grant a permission you do not have")++ ErrApiKeyPersonalNoGrants = errors.New("personal API keys inherit the owner's permissions and cannot carry grants"))var defaultAdminAPIKeyDescription = func() *string {@@ -90,7 +96,7 @@ type ApiKeyService struct {func NewApiKeyService(db *database.DB, userService *user.UserService, roleService *role.RoleService) *ApiKeyService {pepper := make([]byte, 32)if _, err := rand.Read(pepper); err != nil {- panic(errors.WrapIf(err, "failed to generate API key cache pepper"))+ panic(fmt.Errorf("failed to generate API key cache pepper: %w", err))}return &ApiKeyService{cacheKeyPepper: pepper,@@ -129,7 +135,7 @@ func (s *ApiKeyService) BackfillApiKeyPermissions(ctx context.Context) error {// those are an intentional "no access" state we must not overwrite.var keys []ApiKeyif err := s.db.WithContext(ctx).Where("user_id IS NULL OR managed_by IS NOT NULL").Find(&keys).Error; err != nil {- return errors.WrapIf(err, "failed to list bootstrap api keys for backfill")+ return fmt.Errorf("failed to list bootstrap api keys for backfill: %w", err)}if len(keys) == 0 {return nil@@ -139,7 +145,7 @@ func (s *ApiKeyService) BackfillApiKeyPermissions(ctx context.Context) error {for _, key := range keys {var existing int64if err := tx.Model(&role.ApiKeyPermission{}).Where("api_key_id = ?", key.ID).Count(&existing).Error; err != nil {- return errors.WrapIff(err, "failed to count permissions for api key %s", key.ID)+ return fmt.Errorf("failed to count permissions for api key %s: %w", key.ID, err)}if existing > 0 {continue@@ -154,7 +160,7 @@ func (s *ApiKeyService) BackfillApiKeyPermissions(ctx context.Context) error {Permission: p,EnvironmentID: key.EnvironmentID,}).Error; err != nil {- return errors.WrapIf(err, "failed to seed api key permission")+ return fmt.Errorf("failed to seed api key permission: %w", err)}}slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)@@ -182,7 +188,7 @@ func (s *ApiKeyService) backfillPermsForKeyInternal(ctx context.Context, tx *gorif errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, errors.WrapIf(err, "failed to load api key owner")+ return nil, fmt.Errorf("failed to load api key owner: %w", err)}ps, err := s.roleService.ResolveUserPermissionsInDB(ctx, tx, owner.ID)if err != nil {@@ -207,7 +213,7 @@ func (s *ApiKeyService) backfillPermsForKeyInternal(ctx context.Context, tx *gorfunc (s *ApiKeyService) generateApiKey() (string, error) {bytes := make([]byte, apiKeyLength)if _, err := rand.Read(bytes); err != nil {- return "", errors.WrapIf(err, "failed to generate API key")+ return "", fmt.Errorf("failed to generate API key: %w", err)}return apiKeyPrefix + hex.EncodeToString(bytes), nil}@@ -241,7 +247,7 @@ func (s *ApiKeyService) markApiKeyUsedInternal(ctx context.Context, keyID stringModel(&ApiKey{}).Where("id = ? AND (last_used_at IS NULL OR last_used_at < ?)", keyID, cutoff).Update("last_used_at", now).Error; err != nil {- return errors.WrapIf(err, "failed to update API key last-used timestamp")+ return fmt.Errorf("failed to update API key last-used timestamp: %w", err)}return nil}@@ -349,7 +355,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, errors.WrapIf(err, "failed to persist api key permissions")+ return nil, fmt.Errorf("failed to persist api key permissions: %w", err)}// Re-load the just-persisted grants into the response DTO so the// frontend doesn't see `"permissions": null` on a successful create.@@ -370,14 +376,14 @@ func (s *ApiKeyService) validateGrantsAgainstOwnerInternal(ctx context.Context,}user, err := s.userService.GetUserByID(ctx, ownerID)if err != nil {- return errors.WrapIf(err, "load owner for permission validation")+ return fmt.Errorf("load owner for permission validation: %w", err)}ps, err := s.roleService.ResolvePermissions(ctx, user)if err != nil {- return errors.WrapIf(err, "resolve owner permissions")+ return fmt.Errorf("resolve owner permissions: %w", err)}if err := validateGrantsAgainstPermissionSetInternal(ps, grants); err != nil {- return errors.WrapIf(err, "owner's roles do not allow this grant")+ return fmt.Errorf("owner's roles do not allow this grant: %w", err)}return nil}@@ -393,7 +399,7 @@ func validateGrantsAgainstPermissionSetInternal(callerPerms *authz.PermissionSetenvID = *g.EnvironmentID}if !callerPerms.Allows(g.Permission, envID) {- return errors.WrapIff(ErrApiKeyPermissionEscalation, "%s (env=%q)", g.Permission, envID)+ return fmt.Errorf("%s (env=%q): %w", g.Permission, envID, ErrApiKeyPermissionEscalation)}}return nil@@ -452,7 +458,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(keyHash, err := s.hashApiKey(rawKey)if err != nil {- return nil, errors.WrapIf(err, "failed to hash API key")+ return nil, fmt.Errorf("failed to hash API key: %w", err)}ak := &ApiKey{@@ -466,16 +472,13 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(EnvironmentID: environmentID,ExpiresAt: req.ExpiresAt,}-if err := s.db.WithContext(ctx).Create(ak).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create API key")+ return nil, fmt.Errorf("failed to create API key: %w", err)}-+ // A just-minted environment key is about to be linked as the+ // environment's pairing key, so present it as bootstrap already.return &apikey.ApiKeyCreatedDto{- // A just-minted environment key is about to be linked as the- // environment's pairing key, so present it as bootstrap already.- ApiKey: toAPIKeyDTOInternal(ak, environmentID != nil),- Key: rawKey,+ ApiKey: toAPIKeyDTOInternal(ak, environmentID != nil), Key: rawKey,}, nil}@@ -494,7 +497,7 @@ func (s *ApiKeyService) isEnvironmentReferencedApiKeyInternal(ctx context.Contexvar count int64if err := s.db.WithContext(ctx).Table("environments").Where("api_key_id = ?", keyID).Count(&count).Error; err != nil {- return false, errors.WrapIf(err, "failed to check environment references for API key")+ return false, fmt.Errorf("failed to check environment references for API key: %w", err)}return count > 0, nil}@@ -506,7 +509,7 @@ func (s *ApiKeyService) environmentReferencedApiKeyIDsInternal(ctx context.Contevar ids []stringif err := s.db.WithContext(ctx).Table("environments").Where("api_key_id IS NOT NULL").Pluck("api_key_id", &ids).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list environment-referenced API key ids")+ return nil, fmt.Errorf("failed to list environment-referenced API key ids: %w", err)}set := make(map[string]struct{}, len(ids))for _, id := range ids {@@ -560,7 +563,7 @@ func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*common.User,slog.WarnContext(ctx, "Default admin user not found, skipping default admin API key reconciliation", "username", defaultAdminUsername)return nil, nil}- return nil, errors.WrapIf(err, "failed to load default admin user")+ return nil, fmt.Errorf("failed to load default admin user: %w", err)}// The username is mutable and not proof of provenance — never mint the@@ -568,7 +571,7 @@ func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*common.User,if s.roleService != nil {perms, err := s.roleService.ResolvePermissions(ctx, adminUser)if err != nil {- return nil, errors.WrapIf(err, "failed to resolve default admin permissions")+ return nil, fmt.Errorf("failed to resolve default admin permissions: %w", err)}if !perms.IsGlobalAdmin() {slog.WarnContext(ctx, "User is not a global admin, skipping default admin API key reconciliation", "username", defaultAdminUsername)@@ -584,9 +587,8 @@ func (s *ApiKeyService) listManagedAPIKeys(tx *gorm.DB, userID string) ([]ApiKeyif err := tx.Where("user_id = ? AND managed_by = ?", userID, managedByAdminBootstrap).Order("created_at asc, id asc").Find(&managedKeys).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load managed API keys")+ return nil, fmt.Errorf("failed to load managed API keys: %w", err)}-return managedKeys, nil}@@ -595,7 +597,7 @@ func (s *ApiKeyService) deleteManagedAPIKeysByIDs(tx *gorm.DB, ids []string) errreturn nil}if err := tx.Delete(&ApiKey{}, "id IN ?", ids).Error; err != nil {- return errors.WrapIf(err, "failed to delete managed API keys")+ return fmt.Errorf("failed to delete managed API keys: %w", err)}return nil}@@ -628,7 +630,7 @@ func (s *ApiKeyService) updateMatchingManagedAPIKey(tx *gorm.DB, apiKeyID string"description": defaultAdminAPIKeyDescription,"managed_by": managedByAdminBootstrap,}).Error; err != nil {- return errors.WrapIf(err, "failed to update managed API key metadata")+ return fmt.Errorf("failed to update managed API key metadata: %w", err)}return nil}@@ -641,7 +643,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, rawkeyHash, err := s.hashApiKey(rawKey)if err != nil {- return errors.WrapIf(err, "failed to hash API key")+ return fmt.Errorf("failed to hash API key: %w", err)}ak := &ApiKey{@@ -652,9 +654,8 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, rawManagedBy: new(managedByAdminBootstrap),UserID: &userID,}-if err := tx.Create(ak).Error; err != nil {- return errors.WrapIf(err, "failed to create managed API key")+ return fmt.Errorf("failed to create managed API key: %w", err)}return nil}@@ -750,7 +751,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment}}if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {- return nil, errors.WrapIf(err, "failed to persist environment bootstrap key permissions")+ return nil, fmt.Errorf("failed to persist environment bootstrap key permissions: %w", err)}// Re-load grants into the response DTO so callers see the seeded// permissions immediately, not null.@@ -769,7 +770,7 @@ func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKeif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrApiKeyNotFound}- return nil, errors.WrapIf(err, "failed to get API key")+ return nil, fmt.Errorf("failed to get API key: %w", err)}isBootstrap, err := s.isEnvironmentReferencedApiKeyInternal(ctx, ak.ID)if err != nil {@@ -795,7 +796,7 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QuerypaginationResp, err := pagination.PaginateAndSortDB(params, query, &apiKeys)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate API keys")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate API keys: %w", err)}referenced, err := s.environmentReferencedApiKeyIDsInternal(ctx)@@ -826,11 +827,10 @@ func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([if s.roleService != nil {query = query.Preload("PermissionGrants")}- if err := query.- Where("user_id = ?", userID).+ if err := query.Where("user_id = ?", userID).Order("created_at DESC").Find(&apiKeys).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list user api keys")+ return nil, fmt.Errorf("failed to list user api keys: %w", err)}referenced, err := s.environmentReferencedApiKeyIDsInternal(ctx)@@ -857,7 +857,7 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Perif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrApiKeyNotFound}- return nil, errors.WrapIf(err, "failed to get API key")+ return nil, fmt.Errorf("failed to get API key: %w", err)}if isStaticAPIKeyInternal(ak) {return nil, ErrApiKeyProtected@@ -905,11 +905,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 errors.WrapIf(err, "failed to update API key")+ return fmt.Errorf("failed to update API key: %w", err)}if req.Permissions != nil && s.roleService != nil {if err := s.roleService.SetApiKeyPermissionsInDB(ctx, tx, ak.ID, toApiKeyPermissionRowsInternal(ak.ID, req.Permissions)); err != nil {- return errors.WrapIf(err, "failed to update api key permissions")+ return fmt.Errorf("failed to update api key permissions: %w", err)}permissionsUpdated = true}@@ -967,7 +967,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {if errors.Is(err, gorm.ErrRecordNotFound) {return ErrApiKeyNotFound}- return errors.WrapIf(err, "failed to load API key")+ return fmt.Errorf("failed to load API key: %w", err)}if isStaticAPIKeyInternal(apiKey) {return ErrApiKeyProtected@@ -980,7 +980,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {result := s.db.WithContext(ctx).Delete(&ApiKey{}, "id = ?", id)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete API key")+ return fmt.Errorf("failed to delete API key: %w", result.Error)}if result.RowsAffected == 0 {return ErrApiKeyNotFound@@ -1008,7 +1008,7 @@ func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string)user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)if err != nil {- return nil, nil, errors.WrapIf(err, "failed to get user for API key")+ return nil, nil, fmt.Errorf("failed to get user for API key: %w", err)}return user, apiKey, nil@@ -1047,7 +1047,7 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey stgen := s.cacheGen.Load()var apiKeys []ApiKeyif err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {- return nil, errors.WrapIf(err, "failed to find API keys")+ return nil, fmt.Errorf("failed to find API keys: %w", err)}for _, apiKey := range apiKeys {diff --git a/backend/internal/apns/handler.go b/backend/internal/apns/handler.goindex 955d14dc8..4dd7ff2f0 100644--- a/backend/internal/apns/handler.go+++ b/backend/internal/apns/handler.go@@ -2,9 +2,9 @@ package apnsimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/apns/service.go b/backend/internal/apns/service.goindex 83f7a14a6..209af3c3a 100644--- a/backend/internal/apns/service.go+++ b/backend/internal/apns/service.go@@ -8,6 +8,7 @@ import ("crypto/rand""encoding/base64""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -19,7 +20,6 @@ import ("time""uuid"- "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"@@ -79,7 +79,7 @@ func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, erroif stored != "" {decrypted, err := crypto.Decrypt(stored)if err != nil {- return nil, errors.WrapIf(err, "failed to decrypt push signing key")+ return nil, fmt.Errorf("failed to decrypt push signing key: %w", err)}alg, encoded, ok := strings.Cut(decrypted, ":")if !ok {@@ -87,17 +87,17 @@ func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, erro}seed, err = base64.StdEncoding.DecodeString(encoded)if err != nil {- return nil, errors.WrapIf(err, "failed to decode push signing key")+ return nil, fmt.Errorf("failed to decode push signing key: %w", err)}algorithm = alg} else {seed = make([]byte, 32)if _, err := io.ReadFull(rand.Reader, seed); err != nil {- return nil, errors.WrapIf(err, "failed to generate push signing key")+ return nil, fmt.Errorf("failed to generate push signing key: %w", err)}encrypted, err := crypto.Encrypt(algorithm + ":" + base64.StdEncoding.EncodeToString(seed))if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt push signing key")+ return nil, fmt.Errorf("failed to encrypt push signing key: %w", err)}if err := s.settings.UpdateSetting(ctx, "apnsSigningKey", encrypted); err != nil {return nil, err@@ -115,7 +115,7 @@ func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, errocase "ml-dsa-87":key, err := mldsa.NewPrivateKey(mldsa.MLDSA87(), seed)if err != nil {- return nil, errors.WrapIf(err, "failed to load push signing key")+ return nil, fmt.Errorf("failed to load push signing key: %w", err)}return &signerInternal{algorithm: algorithm,@@ -123,31 +123,31 @@ func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, errosign: func(msg []byte) ([]byte, error) { return key.Sign(nil, msg, nil) },}, nildefault:- return nil, errors.Errorf("unsupported push signing key algorithm %q", algorithm)+ return nil, fmt.Errorf("unsupported push signing key algorithm %q", algorithm)}}func (s *ApnsService) relayRequestInternal(ctx context.Context, method, path string, body []byte, signer *signerInternal) (int, []byte, error) {req, err := http.NewRequestWithContext(ctx, method, s.config.ApnsRelayUrl+path, bytes.NewReader(body))if err != nil {- return 0, nil, errors.WrapIf(err, "failed to build push relay request")+ return 0, nil, fmt.Errorf("failed to build push relay request: %w", err)}req.Header.Set("Content-Type", "application/json")if signer != nil {sig, err := signer.sign(body)if err != nil {- return 0, nil, errors.WrapIf(err, "failed to sign push relay request")+ return 0, nil, fmt.Errorf("failed to sign push relay request: %w", err)}req.Header.Set(signatureHeader, base64.StdEncoding.EncodeToString(sig))}resp, err := s.httpClient.Do(req)if err != nil {- return 0, nil, errors.WrapIf(common.ErrApnsRelay, err.Error())+ return 0, nil, fmt.Errorf("%s: %w", err.Error(), common.ErrApnsRelay)}defer func() { _ = resp.Body.Close() }()respBody, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))if err != nil {- return 0, nil, errors.WrapIf(common.ErrApnsRelay, err.Error())+ return 0, nil, fmt.Errorf("%s: %w", err.Error(), common.ErrApnsRelay)}return resp.StatusCode, respBody, nil}@@ -165,20 +165,20 @@ func (s *ApnsService) EnsureChannel(ctx context.Context) (string, error) {}body, err := json.Marshal(map[string]string{"algorithm": signer.algorithm, "publicKey": base64.StdEncoding.EncodeToString(signer.publicKey)})if err != nil {- return "", errors.WrapIf(err, "failed to marshal channel registration")+ return "", fmt.Errorf("failed to marshal channel registration: %w", err)}status, respBody, err := s.relayRequestInternal(ctx, http.MethodPost, "/v1/channels", body, nil)if err != nil {return "", err}if status != http.StatusCreated && status != http.StatusOK {- return "", errors.WrapIff(common.ErrApnsRelay, "channel registration returned %d: %s", status, strings.TrimSpace(string(respBody)))+ return "", fmt.Errorf("channel registration returned %d: %s: %w", status, strings.TrimSpace(string(respBody)), common.ErrApnsRelay)}var parsed struct {ChannelID string `json:"channelId"`}if err := json.Unmarshal(respBody, &parsed); err != nil || parsed.ChannelID == "" {- return "", errors.WrapIf(common.ErrApnsRelay, "channel registration returned no channel id")+ return "", fmt.Errorf("channel registration returned no channel id: %w", common.ErrApnsRelay)}if err := s.settings.UpdateSetting(ctx, "apnsChannelId", parsed.ChannelID); err != nil {return "", err@@ -216,14 +216,14 @@ func (s *ApnsService) RevokeChannel(ctx context.Context) error {}body, err := json.Marshal(map[string]any{"channelId": channelID, "issuedAt": time.Now().UTC(), "nonce": uuid.New().String()})if err != nil {- return errors.WrapIf(err, "failed to marshal channel revocation")+ return fmt.Errorf("failed to marshal channel revocation: %w", err)}status, respBody, err := s.relayRequestInternal(ctx, http.MethodDelete, "/v1/channels/"+channelID, body, signer)if err != nil {return err}if status != http.StatusNoContent && status != http.StatusNotFound && status != http.StatusGone {- return errors.WrapIff(common.ErrApnsRelay, "channel revocation returned %d: %s", status, strings.TrimSpace(string(respBody)))+ return fmt.Errorf("channel revocation returned %d: %s: %w", status, strings.TrimSpace(string(respBody)), common.ErrApnsRelay)}if err := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); err != nil {return err@@ -231,9 +231,12 @@ func (s *ApnsService) RevokeChannel(ctx context.Context) error {slog.InfoContext(ctx, "Revoked push relay channel", "channelId", channelID)}if err := s.db.WithContext(ctx).Where("1 = 1").Delete(&Device{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete push devices")+ return fmt.Errorf("failed to delete push devices: %w", err)}- return errors.WrapIf(s.db.WithContext(ctx).Where("1 = 1").Delete(&OutboxEntry{}).Error, "failed to clear push outbox")+ if err := s.db.WithContext(ctx).Where("1 = 1").Delete(&OutboxEntry{}).Error; err != nil {+ return fmt.Errorf("failed to clear push outbox: %w", err)+ }+ return nil}func (s *ApnsService) IssuePairingToken(ctx context.Context) (apnstypes.PairingToken, error) {@@ -255,11 +258,11 @@ func (s *ApnsService) IssuePairingToken(ctx context.Context) (apnstypes.PairingTNonce string `json:"nonce"`}{channelID, uuid.New().String(), now.Unix(), expiresAt.Unix(), uuid.New().String()})if err != nil {- return apnstypes.PairingToken{}, errors.WrapIf(err, "failed to marshal pairing token")+ return apnstypes.PairingToken{}, fmt.Errorf("failed to marshal pairing token: %w", err)}sig, err := signer.sign(payload)if err != nil {- return apnstypes.PairingToken{}, errors.WrapIf(err, "failed to sign pairing token")+ return apnstypes.PairingToken{}, fmt.Errorf("failed to sign pairing token: %w", err)}token := pairingFormatV1 + "." + base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(sig)return apnstypes.PairingToken{Token: token, ChannelID: channelID, ExpiresAt: expiresAt}, nil@@ -284,7 +287,7 @@ func (s *ApnsService) Status(ctx context.Context, userID string) (apnstypes.Stat}var devices []Deviceif err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("created_at ASC").Find(&devices).Error; err != nil {- return status, errors.WrapIf(err, "failed to list push devices")+ return status, fmt.Errorf("failed to list push devices: %w", err)}for _, d := range devices {status.Devices = append(status.Devices, deviceDTOInternal(d))@@ -322,15 +325,15 @@ func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apnexisting.EnvironmentIDs = environmentIDsexisting.LastSeenAt = &nowif err := s.db.WithContext(ctx).Save(&existing).Error; err != nil {- return apnstypes.Device{}, errors.WrapIf(err, "failed to update push device")+ return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", err)}return deviceDTOInternal(existing), nilcase !errors.Is(err, gorm.ErrRecordNotFound):- return apnstypes.Device{}, errors.WrapIf(err, "failed to load push device")+ return apnstypes.Device{}, fmt.Errorf("failed to load push device: %w", err)}device := Device{UserID: userID, RecipientID: req.RecipientID, Label: req.Label, Events: events, EnvironmentIDs: environmentIDs, LastSeenAt: &now}if err := s.db.WithContext(ctx).Create(&device).Error; err != nil {- return apnstypes.Device{}, errors.WrapIf(err, "failed to register push device")+ return apnstypes.Device{}, fmt.Errorf("failed to register push device: %w", err)}return deviceDTOInternal(device), nil}@@ -341,7 +344,7 @@ func (s *ApnsService) deviceInternal(ctx context.Context, userID, id string) (*Dif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.ErrApnsDeviceNotFound}- return nil, errors.WrapIf(err, "failed to load push device")+ return nil, fmt.Errorf("failed to load push device: %w", err)}return &device, nil}@@ -368,7 +371,7 @@ func (s *ApnsService) UpdateDevice(ctx context.Context, userID, id string, req a}device.LastSeenAt = new(time.Now())if err := s.db.WithContext(ctx).Save(device).Error; err != nil {- return apnstypes.Device{}, errors.WrapIf(err, "failed to update push device")+ return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", err)}return deviceDTOInternal(*device), nil}@@ -378,7 +381,10 @@ func (s *ApnsService) DeleteDevice(ctx context.Context, userID, id string) errorif err != nil {return err}- return errors.WrapIf(s.db.WithContext(ctx).Delete(device).Error, "failed to delete push device")+ if err := s.db.WithContext(ctx).Delete(device).Error; err != nil {+ return fmt.Errorf("failed to delete push device: %w", err)+ }+ return nil}func (s *ApnsService) TestDevice(ctx context.Context, userID, id string) error {@@ -401,14 +407,14 @@ func (s *ApnsService) TestDevice(ctx context.Context, userID, id string) error {"recipientId": device.RecipientID,})if err != nil {- return errors.WrapIf(err, "failed to marshal test push")+ return fmt.Errorf("failed to marshal test push: %w", err)}status, respBody, err := s.relayRequestInternal(ctx, http.MethodPost, "/v1/test", body, signer)if err != nil {return err}if status != http.StatusAccepted && status != http.StatusOK {- return errors.WrapIff(common.ErrApnsRelay, "test push returned %d: %s", status, strings.TrimSpace(string(respBody)))+ return fmt.Errorf("test push returned %d: %s: %w", status, strings.TrimSpace(string(respBody)), common.ErrApnsRelay)}return nil}@@ -479,11 +485,11 @@ func (s *ApnsService) Enqueue(ctx context.Context, environmentID, environmentNam}raw, err := json.Marshal(envelope)if err != nil {- return errors.WrapIf(err, "failed to marshal push envelope")+ return fmt.Errorf("failed to marshal push envelope: %w", err)}entry := OutboxEntry{EventID: envelope.EventID, Envelope: string(raw), NextAttemptAt: time.Now()}if err := s.db.WithContext(ctx).Create(&entry).Error; err != nil {- return errors.WrapIf(err, "failed to enqueue push notification")+ return fmt.Errorf("failed to enqueue push notification: %w", err)}go func() {drainCtx := context.WithoutCancel(ctx)@@ -497,7 +503,7 @@ func (s *ApnsService) Enqueue(ctx context.Context, environmentID, environmentNamfunc (s *ApnsService) recipientsInternal(ctx context.Context, environmentID string, eventType notifications.NotificationEventType) ([]string, error) {var devices []Deviceif err := s.db.WithContext(ctx).Find(&devices).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list push devices")+ return nil, fmt.Errorf("failed to list push devices: %w", err)}permissions := map[string]*authz.PermissionSet{}var recipients []stringdiff --git a/backend/internal/appimages/handler.go b/backend/internal/appimages/handler.goindex ed78e8559..4b1c876ab 100644--- a/backend/internal/appimages/handler.go+++ b/backend/internal/appimages/handler.go@@ -6,7 +6,6 @@ import ("path/filepath""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2"kit "go.getarcane.app/kit/pkg")@@ -150,7 +149,7 @@ func (h *AppImagesHandler) getImageByFilenameInternal(filename string) (*GetAppIfunc (h *AppImagesHandler) getImageWithColor(name, colorOverride string, loop bool) (*GetAppImageOutput, error) {imageData, mimeType, err := h.appImagesService.GetImageWithColor(name, colorOverride, loop)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve image").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve image: " + err.Error())}// Always disable logo caching so theme/logo updates are reflected immediately.diff --git a/backend/internal/appimages/service.go b/backend/internal/appimages/service.goindex 15403ddcd..8d3c6ea60 100644--- a/backend/internal/appimages/service.go+++ b/backend/internal/appimages/service.go@@ -2,12 +2,12 @@ package appimagesimport ("embed"+ "fmt""io/fs""path/filepath""strings""sync"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/settings"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"kit "go.getarcane.app/kit/pkg"@@ -67,7 +67,7 @@ func (s *ApplicationImagesService) GetImageWithColor(name, colorOverride string,s.mu.RUnlock()if !ok {- return nil, "", errors.Errorf("image '%s' not found", name)+ return nil, "", fmt.Errorf("image '%s' not found", name)}// Apply dynamic color replacement for logo SVGsdiff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.goindex f90d049ad..655fcb8b4 100644--- a/backend/internal/auth/handler.go+++ b/backend/internal/auth/handler.go@@ -3,6 +3,7 @@ package authimport ("bytes""context"+ "errors""fmt"stdimage "image""image/jpeg"@@ -15,7 +16,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -326,7 +326,11 @@ func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInputtokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken, handlerutil.SessionMetaFromContext(ctx, input.UserAgent))if err != nil {switch {- case errors.Is(err, common.ErrInvalidToken), errors.Is(err, common.ErrExpiredToken), errors.Is(err, common.ErrTokenValidation), errors.Is(err, common.ErrSessionRevoked), errors.Is(err, common.ErrTokenVersionMismatch):+ case errors.Is(err, common.ErrInvalidToken),+ errors.Is(err, common.ErrExpiredToken),+ errors.Is(err, common.ErrTokenValidation),+ errors.Is(err, common.ErrSessionRevoked),+ errors.Is(err, common.ErrTokenVersionMismatch):return nil, huma.Error401Unauthorized("Invalid or expired refresh token")default:return nil, huma.Error500InternalServerError("Failed to refresh token")diff --git a/backend/internal/auth/huma_middleware_test.go b/backend/internal/auth/huma_middleware_test.goindex d08609977..e84b6671d 100644--- a/backend/internal/auth/huma_middleware_test.go+++ b/backend/internal/auth/huma_middleware_test.go@@ -104,7 +104,7 @@ func TestNewHumaMiddleware_UsesBearerWhenLoopbackProxySendsEnvironmentAccessTokesessionSvc := session.NewSessionService(db)signingKey := newTestSigningKeyInternal()- authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, &config.Config{JWTRefreshExpiry: 24 * time.Hour}, nil).WithSigningKey(signingKey)+ authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, &config.Config{JWTRefreshExpiry: 24 * time.Hour}).WithSigningKey(signingKey)bearerToken := mintHumaMiddlewareTestTokenInternal(t, userSvc, sessionSvc, signingKey, "u-loopback")ps := authz.NewPermissionSet()@@ -268,7 +268,7 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {signingKey := newTestSigningKeyInternal()cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}- authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg, nil).WithSigningKey(signingKey)+ authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg).WithSigningKey(signingKey)_, err := userSvc.CreateUser(context.Background(), &common.User{ID: "u-logout",@@ -356,7 +356,7 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {signingKey := newTestSigningKeyInternal()browserSigningKey := bytes.Repeat([]byte{0x24}, browserSessionSigningKeySize)cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}- authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg, nil).WithSigningKey(signingKey)+ authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg).WithSigningKey(signingKey)authSvc.browserSigningKey = browserSigningKey_, err := userSvc.CreateUser(context.Background(), &common.User{diff --git a/backend/internal/auth/middleware.go b/backend/internal/auth/middleware.goindex e0958f5df..dc7f64a6f 100644--- a/backend/internal/auth/middleware.go+++ b/backend/internal/auth/middleware.go@@ -3,11 +3,11 @@ package authimport ("context""crypto/subtle"+ "errors""log/slog""net/http""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.goindex 58e41163f..59b23a9ca 100644--- a/backend/internal/auth/service.go+++ b/backend/internal/auth/service.go@@ -3,6 +3,7 @@ package authimport ("context""crypto/mldsa"+ "errors""fmt""log/slog""maps"@@ -12,8 +13,6 @@ import ("time""uuid"- "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/database"@@ -22,6 +21,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation""github.com/getarcaneapp/arcane/types/v2/auth"@@ -32,11 +32,11 @@ import (kit "go.getarcane.app/kit/pkg")-const (- ErrInvalidCredentials = errors.Sentinel("invalid credentials")- ErrLocalAuthDisabled = errors.Sentinel("local authentication is disabled")- ErrOidcAuthDisabled = errors.Sentinel("OIDC authentication is disabled")- ErrMFARequired = errors.Sentinel("multi-factor authentication is required")+var (+ ErrInvalidCredentials = errors.New("invalid credentials")+ ErrLocalAuthDisabled = errors.New("local authentication is disabled")+ ErrOidcAuthDisabled = errors.New("OIDC authentication is disabled")+ ErrMFARequired = errors.New("multi-factor authentication is required"))type TokenPair struct {@@ -71,7 +71,6 @@ type AuthService struct {browserSigningKey []byterefreshExpiry time.Durationconfig *config.Config- errorHandler emperror.ErrorHandler// tokenCache is a per-process in-memory cache for verified tokens. A hit// skips signature verification and the user/session lookups; revocation in// this process purges entries, revocation by another process is visible@@ -79,10 +78,7 @@ type AuthService struct {tokenCache *hot.HotCache[string, verifiedTokenEntry]}-func NewAuthService(userService *user.UserService, settingsService *settings.SettingsService, eventService *event.EventService, sessionService *session.SessionService, roleService *role.RoleService, cfg *config.Config, errorHandler emperror.ErrorHandler) *AuthService {- if errorHandler == nil {- errorHandler = emperror.NoopHandler{}- }+func NewAuthService(userService *user.UserService, settingsService *settings.SettingsService, eventService *event.EventService, sessionService *session.SessionService, roleService *role.RoleService, cfg *config.Config) *AuthService {return &AuthService{userService: userService,settingsService: settingsService,@@ -91,7 +87,6 @@ func NewAuthService(userService *user.UserService, settingsService *settings.SetroleService: roleService,refreshExpiry: cfg.JWTRefreshExpiry,config: cfg,- errorHandler: errorHandler,tokenCache: hot.NewHotCache[string, verifiedTokenEntry](hot.LRU, 4096).WithTTL(60 * time.Second).WithJanitor().@@ -102,7 +97,7 @@ func NewAuthService(userService *user.UserService, settingsService *settings.Setfunc (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {appSettings, err := s.settingsService.GetSettings(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get settings")+ return nil, fmt.Errorf("failed to get settings: %w", err)}timeoutMinutes, _ := s.GetSessionTimeout(ctx)@@ -269,7 +264,7 @@ func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, pauserCopy := new(*user)s.runInBackground(ctx, "update_last_login", func(ctx context.Context) error {if _, err := s.userService.UpdateUser(ctx, userCopy, nil); err != nil {- return errors.WrapIf(err, "failed to update user's last login time")+ return fmt.Errorf("failed to update user's last login time: %w", err)}return nil})@@ -602,7 +597,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *common.groups := s.extractOidcGroups(ctx, userInfo, tokenResp)mappings, err := s.roleService.ListOidcMappings(ctx)if err != nil {- return errors.WrapIf(err, "list oidc mappings")+ return fmt.Errorf("list oidc mappings: %w", err)}groupSet := make(map[string]struct{}, len(groups))@@ -741,7 +736,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, met}if s.sessionService == nil {- return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.}userSession, err := s.sessionService.GetSessionByID(ctx, claims.SessionID)@@ -830,7 +825,7 @@ func (s *AuthService) verifyTokenClaimsInternal(ctx context.Context, tokenHash sreturn nil, "", common.ErrTokenVersionMismatch}if s.sessionService == nil {- return nil, "", common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))+ return nil, "", common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.}// Verify user exists in DB@@ -859,7 +854,7 @@ func (s *AuthService) verifyTokenClaimsInternal(ctx context.Context, tokenHash sfunc (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword, currentSessionID string) error {if s.sessionService == nil {- return common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))+ return common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.}user, err := s.userService.GetUserByID(ctx, userID)@@ -944,7 +939,7 @@ func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, currenfunc (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *common.User, meta auth.SessionMeta) (*TokenPair, error) {if s.sessionService == nil {- return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.}refreshExpiry := time.Now().Add(s.refreshExpiry)session, refreshJTI, err := s.sessionService.CreateSession(ctx, user.ID, refreshExpiry, meta)@@ -1044,7 +1039,7 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.Ufunc (s *AuthService) IssueFederatedToken(ctx context.Context, user *common.User, credentialID string, ttlSeconds int) (*TokenPair, error) {if s.sessionService == nil {- return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))+ return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.}if user == nil {return nil, common.ErrUserNotFound@@ -1130,13 +1125,8 @@ func (s *AuthService) runInBackground(ctx context.Context, name string, fn func(go func() {defer func() {- 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)- }+ if panicErr := utils.PanicToError(recover()); panicErr != nil {+ slog.ErrorContext(bgCtx, "Unhandled error", "error", fmt.Errorf("Background task panicked: %w", panicErr), "task", name) //nolint:staticcheck // Preserve the existing error message.}}()diff --git a/backend/internal/auth/token.go b/backend/internal/auth/token.goindex aed41236c..3b7210d1b 100644--- a/backend/internal/auth/token.go+++ b/backend/internal/auth/token.go@@ -3,9 +3,9 @@ package authimport ("context""crypto/mldsa"+ "errors""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/lestrrat-go/jwx/v4/jwa""github.com/lestrrat-go/jwx/v4/jws"diff --git a/backend/internal/backup/engine.go b/backend/internal/backup/engine.goindex c205c2b6d..3eb27086a 100644--- a/backend/internal/backup/engine.go+++ b/backend/internal/backup/engine.go@@ -11,6 +11,7 @@ import ("encoding/hex""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -22,7 +23,6 @@ import ("time""uuid"- "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/image"diff --git a/backend/internal/backup/engine_test.go b/backend/internal/backup/engine_test.goindex b14e306d8..eef8dc481 100644--- a/backend/internal/backup/engine_test.go+++ b/backend/internal/backup/engine_test.go@@ -13,10 +13,7 @@ import (func TestMarkSnapshotDirectoriesInternal(t *testing.T) {files := []string{"/volume", "/volume/folder", "/volume/file.txt", "/volume/link"}- longOutput := "drwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume\"\r\n" +- "drwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume/folder\"\r\n" +- "-rw-r--r-- root root 5 1 Jan 2026 00:00 \"/volume/file.txt\"\r\n" +- "lrwxrwxrwx root root 4 1 Jan 2026 00:00 \"/volume/link\" -> \"file.txt\""+ longOutput := "drwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume\"\r\ndrwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume/folder\"\r\n-rw-r--r-- root root 5 1 Jan 2026 00:00 \"/volume/file.txt\"\r\nlrwxrwxrwx root root 4 1 Jan 2026 00:00 \"/volume/link\" -> \"file.txt\""marked, err := markSnapshotDirectoriesInternal(files, longOutput)require.NoError(t, err)diff --git a/backend/internal/backup/policies.go b/backend/internal/backup/policies.goindex da6a0e460..2f6bf1f3c 100644--- a/backend/internal/backup/policies.go+++ b/backend/internal/backup/policies.go@@ -2,10 +2,10 @@ package backupimport ("context"+ "errors""fmt""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"diff --git a/backend/internal/backup/remote.go b/backend/internal/backup/remote.goindex f641ea771..21bbb7ae1 100644--- a/backend/internal/backup/remote.go+++ b/backend/internal/backup/remote.go@@ -2,10 +2,10 @@ package backupimport ("context"+ "errors""fmt""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"s3util "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/s3"diff --git a/backend/internal/backup/retention.go b/backend/internal/backup/retention.godeleted file mode 100644index f7822147a..000000000--- a/backend/internal/backup/retention.go+++ /dev/null@@ -1,25 +0,0 @@-package backup--import (- "context"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-)--// ExpiredRunIDs returns the IDs of succeeded runs with snapshots that fall-// outside the newest keep entries for one policy, oldest last. Callers delete-// each run through their own delete path so snapshots are forgotten too.-func ExpiredRunIDs(ctx context.Context, db *database.DB, table, policyID string, keep int) ([]string, error) {- var ids []string- err := db.WithContext(ctx).- Table(table).- Where(- "policy_id = ? AND status = ? AND (COALESCE(local_snapshot_id, '') <> '' OR COALESCE(remote_snapshot_id, '') <> '')",- policyID,- "succeeded",- ).- Order("created_at DESC").- Offset(keep).- Pluck("id", &ids).Error- return ids, err-}diff --git a/backend/internal/backup/runs.go b/backend/internal/backup/runs.goindex 9aab8997a..9c0f48c3e 100644--- a/backend/internal/backup/runs.go+++ b/backend/internal/backup/runs.go@@ -3,10 +3,12 @@ package backupimport ("context""encoding/json/v2"+ "errors"+ "fmt""sync""time"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -176,7 +178,7 @@ func (a *backupRunActorInternal) Job(ctx context.Context, _ string, _ actor.Envereturn err}if runErr != nil {- return errors.WrapIf(actor.ErrJobPermanentFailure, runErr.Error())+ return fmt.Errorf("%s: %w", runErr.Error(), actor.ErrJobPermanentFailure)}return nil}@@ -198,7 +200,7 @@ func (a *backupRunActorInternal) executeInternal(ctx context.Context, command baa.engine.mu.Unlock()defer lease.Release(ctx)if failure != nil {- err = errors.Combine(err, failure(ctx, a.id, command.Payload, err))+ err = errors.Join(err, failure(ctx, a.id, command.Payload, err))}return err}@@ -307,3 +309,21 @@ func (e *Engine) ReconcileDispatches(ctx context.Context) error {}return nil}++// ExpiredRunIDs returns the IDs of succeeded runs with snapshots that fall+// outside the newest keep entries for one policy, oldest last. Callers delete+// each run through their own delete path so snapshots are forgotten too.+func ExpiredRunIDs(ctx context.Context, db *database.DB, table, policyID string, keep int) ([]string, error) {+ var ids []string+ err := db.WithContext(ctx).+ Table(table).+ Where(+ "policy_id = ? AND status = ? AND (COALESCE(local_snapshot_id, '') <> '' OR COALESCE(remote_snapshot_id, '') <> '')",+ policyID,+ "succeeded",+ ).+ Order("created_at DESC").+ Offset(keep).+ Pluck("id", &ids).Error+ return ids, err+}diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 00477c9b2..8ca1bb1b6 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -3,6 +3,8 @@ package bootstrapimport ("cmp""context"+ "errors"+ "fmt""io""log/slog""net/http"@@ -10,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -43,7 +44,7 @@ import (func Bootstrap(ctx context.Context) error {if err := gotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "load .env")+ return fmt.Errorf("load .env: %w", err)}cfg := config.Load()runtimeIdentityCfg := &startup.RuntimeIdentityConfig{@@ -55,7 +56,7 @@ func Bootstrap(ctx context.Context) error {ProjectsDirectory: cfg.ProjectsDirectory,}if err := startup.ApplyRequestedRuntimeIdentity(ctx, runtimeIdentityCfg); err != nil {- return errors.WrapIf(err, "apply runtime identity")+ return fmt.Errorf("apply runtime identity: %w", err)}cfg.DockerConfig = runtimeIdentityCfg.DockerConfig@@ -69,10 +70,10 @@ func Bootstrap(ctx context.Context) error {appCtx, cancelApp := context.WithCancel(ctx)appCtx = utils.WithAppLifecycleContext(appCtx)- db, err := initializeDBAndMigrate(appCtx, cfg)+ db, err := initializeDBAndMigrateInternal(appCtx, cfg)if err != nil {cancelApp()- return errors.WrapIf(err, "failed to initialize database")+ return fmt.Errorf("failed to initialize database: %w", err)}defer func() {cancelApp()@@ -86,7 +87,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 errors.WrapIf(err, "start application")+ return fmt.Errorf("start application: %w", err)}select {@@ -99,7 +100,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 errors.WrapIf(err, "stop application")+ return fmt.Errorf("stop application: %w", err)}slog.InfoContext(context.WithoutCancel(appCtx), "Arcane shutdown complete")@@ -422,7 +423,7 @@ func startEdgeTunnelClientIfConfigured(appCtx context.Context, cfg *config.Confislog.InfoContext(appCtx, "Starting edge agent session client", edge.StartupLogAttrs(edgeCfg)...)stop, err := edge.StartTunnelClient(appCtx, edgeCfg, router)if err != nil {- return nil, errors.WrapIf(err, "failed to start edge tunnel client")+ return nil, fmt.Errorf("failed to start edge tunnel client: %w", err)}slog.InfoContext(appCtx, "Edge tunnel client started", "manager_url", cfg.ManagerApiUrl)@@ -439,7 +440,7 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClreq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pairURL, nil)if err != nil {- return errors.WrapIf(err, "failed to create pairing request")+ return fmt.Errorf("failed to create pairing request: %w", err)}req.Header.Set("X-Api-Key", cfg.AgentToken)@@ -455,14 +456,14 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClEdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,}, 10*time.Second)if edgeErr != nil {- return errors.WrapIf(edgeErr, "failed to configure edge pairing client")+ return fmt.Errorf("failed to configure edge pairing client: %w", edgeErr)}httpClient = edgeClient}resp, err := httpClient.Do(req)if err != nil {- return errors.WrapIf(err, "pairing request failed")+ return fmt.Errorf("pairing request failed: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -478,13 +479,25 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClslog.InfoContext(ctx, "Agent already paired with manager", "managerUrl", cfg.ManagerApiUrl)return nil}- return errors.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))+ return fmt.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 errors.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))+ return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))}}++func initializeDBAndMigrateInternal(ctx context.Context, cfg *config.Config) (*database.DB, error) {+ db, err := database.Initialize(ctx, cfg.DatabaseURL, database.MigrationOptions{+ AllowDowngrade: cfg.AllowDowngrade,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to initialize database: %w", err)+ }++ slog.Info("Database initialized successfully")+ return db, nil+}diff --git a/backend/internal/bootstrap/db_bootstrap.go b/backend/internal/bootstrap/db_bootstrap.godeleted file mode 100644index fa23ff7f6..000000000--- a/backend/internal/bootstrap/db_bootstrap.go+++ /dev/null@@ -1,22 +0,0 @@-package bootstrap--import (- "context"- "log/slog"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-)--func initializeDBAndMigrate(ctx context.Context, cfg *config.Config) (*database.DB, error) {- db, err := database.Initialize(ctx, cfg.DatabaseURL, database.MigrationOptions{- AllowDowngrade: cfg.AllowDowngrade,- })- if err != nil {- return nil, errors.WrapIf(err, "failed to initialize database")- }-- slog.Info("Database initialized successfully")- return db, nil-}diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex 41155971f..9c8132c69 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -3,10 +3,10 @@ package bootstrapimport ("context""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/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -45,48 +45,7 @@ func registerEdgeTunnelRoutes(}eventCallback := func(ctx context.Context, envID string, evt *edge.TunnelEvent) error {- if evt == nil {- return errors.New("event payload is required")- }-- if evt.Type == edge.TunnelEventTypeNotificationDispatch {- if notificationService == nil {- return errors.New("notification service is not available for edge dispatch")- }- var payload notificationdto.DispatchRequest- if err := json.Unmarshal(evt.MetadataJSON, &payload); err != nil {- return errors.WrapIf(err, "failed to decode edge notification dispatch payload")- }- _, err := notificationService.DispatchNotificationForEnvironment(ctx, envID, payload)- return errors.WrapIf(err, "failed to dispatch edge notification")- }-- var metadata database.JSON- if len(evt.MetadataJSON) > 0 {- metadata = database.JSON{}- if err := json.Unmarshal(evt.MetadataJSON, &metadata); err != nil {- return errors.WrapIf(err, "failed to decode event metadata")- }- }-- req := event.CreateEventRequest{- Type: event.EventType(evt.Type),- Severity: event.EventSeverity(evt.Severity),- Title: evt.Title,- Description: evt.Description,- ResourceType: new(evt.ResourceType),- ResourceID: new(evt.ResourceID),- ResourceName: new(evt.ResourceName),- UserID: new(evt.UserID),- Username: new(evt.Username),- EnvironmentID: &envID,- Metadata: metadata,- }- _, err := eventService.CreateEvent(ctx, req)- if err != nil {- return errors.WrapIf(err, "failed to persist synced event")- }- return nil+ return handleEdgeEventInternal(ctx, envID, evt, eventService, notificationService)}server := edge.NewTunnelServerWithRegistry(registry, resolver, statusCallback)@@ -257,8 +216,56 @@ func createEdgeConnectionEvent(ctx context.Context, eventService *event.EventSerEnvironmentID: &envID,})if err != nil {- return errors.WrapIf(err, "failed to create edge lifecycle event")+ return fmt.Errorf("failed to create edge lifecycle event: %w", err)}return nil}++func handleEdgeEventInternal(ctx context.Context, envID string, evt *edge.TunnelEvent, eventService *event.EventService, notificationService *notification.NotificationService) error {+ if evt == nil {+ return errors.New("event payload is required")+ }++ if evt.Type == edge.TunnelEventTypeNotificationDispatch {+ if notificationService == nil {+ return errors.New("notification service is not available for edge dispatch")+ }+ var payload notificationdto.DispatchRequest+ if err := json.Unmarshal(evt.MetadataJSON, &payload); err != nil {+ return fmt.Errorf("failed to decode edge notification dispatch payload: %w", err)+ }+ _, err := notificationService.DispatchNotificationForEnvironment(ctx, envID, payload)+ if err != nil {+ return fmt.Errorf("failed to dispatch edge notification: %w", err)+ }+ return nil+ }++ var metadata database.JSON+ if len(evt.MetadataJSON) > 0 {+ metadata = database.JSON{}+ if err := json.Unmarshal(evt.MetadataJSON, &metadata); err != nil {+ return fmt.Errorf("failed to decode event metadata: %w", err)+ }+ }++ req := event.CreateEventRequest{+ Type: event.EventType(evt.Type),+ Severity: event.EventSeverity(evt.Severity),+ Title: evt.Title,+ Description: evt.Description,+ ResourceType: new(evt.ResourceType),+ ResourceID: new(evt.ResourceID),+ ResourceName: new(evt.ResourceName),+ UserID: new(evt.UserID),+ Username: new(evt.Username),+ EnvironmentID: &envID,+ Metadata: metadata,+ }+ _, err := eventService.CreateEvent(ctx, req)+ if err != nil {+ return fmt.Errorf("failed to persist synced event: %w", err)+ }+ return nil+}diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex b1be64dc0..89fcf7e72 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -3,13 +3,14 @@ package bootstrapimport ("context""encoding/json/v2"+ "errors"+ "fmt""log/slog""net/http""slices""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/backup"@@ -95,7 +96,7 @@ func stopJobSchedulerInternal(ctx context.Context, cancelScheduler context.Cance}}}- err := errors.Combine(coordinator.Stop(ctx), jobScheduler.Stop(ctx))+ err := errors.Join(coordinator.Stop(ctx), jobScheduler.Stop(ctx))if err != nil {slog.ErrorContext(ctx, "Job scheduler exited with error", "error", err)return err@@ -178,7 +179,7 @@ func scheduledBackupProtectionInternal(records []schedulertypes.QueueRecord) ([]BackupID string `json:"backupId"`}if err := json.Unmarshal(target.RecoveryData, &checkpoint); err != nil {- return nil, errors.WrapIf(err, "decode startup recovery evidence")+ return nil, fmt.Errorf("decode startup recovery evidence: %w", err)}if checkpoint.BackupID != "" {ids = append(ids, checkpoint.BackupID)diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.goindex 3c6b5c1b8..ebb9e1d80 100644--- a/backend/internal/bootstrap/logger_bootstrap.go+++ b/backend/internal/bootstrap/logger_bootstrap.go@@ -2,13 +2,13 @@ package bootstrapimport ("context"+ "errors""fmt""log/slog""os""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/lmittmann/tint"slogGorm "github.com/orandin/slog-gorm"@@ -51,51 +51,6 @@ func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (strinl.Interface.Trace(ctx, begin, fc, err)}-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)}@@ -262,7 +217,6 @@ 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 4898c906d..ceb102bdb 100644--- a/backend/internal/bootstrap/logger_bootstrap_test.go+++ b/backend/internal/bootstrap/logger_bootstrap_test.go@@ -6,7 +6,6 @@ import ("testing""time"- "emperror.dev/errors""github.com/stretchr/testify/assert")@@ -63,17 +62,3 @@ 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 b58727b2b..3dfd04e59 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -2,13 +2,13 @@ package bootstrapimport ("context"+ "errors""log/slog""net""net/http""path""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/api""github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/frontend"diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.goindex e10080016..b0f193af1 100644--- a/backend/internal/bootstrap/server_bootstrap.go+++ b/backend/internal/bootstrap/server_bootstrap.go@@ -3,13 +3,13 @@ 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""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"diff --git a/backend/internal/build/service.go b/backend/internal/build/service.goindex e4ae34f6f..e5ec0de7b 100644--- a/backend/internal/build/service.go+++ b/backend/internal/build/service.go@@ -3,6 +3,7 @@ package buildimport ("cmp""context"+ "errors""fmt""io""log/slog"@@ -12,7 +13,6 @@ import ("strings""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/docker"@@ -261,7 +261,7 @@ func (s *BuildService) resolveBuildRequestInternal(}if !ok || source == nil {if contextsource.IsPotentialRemoteBuildContextSource(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 buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("unsupported remote build context source %q: only git repository URLs are supported", req.ContextDir)}return req, func() error { return nil }, nil}@@ -278,7 +278,7 @@ func (s *BuildService) resolveBuildRequestInternal(if gitkit.RequiresRemoteProbe(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 }, errors.WrapIff(err, "failed to verify remote git repository %q", source.RepositoryURL)+ return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to verify remote git repository %q: %w", source.RepositoryURL, err)}}@@ -291,7 +291,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 }, errors.WrapIf(err, "invalid git build context subdir")+ return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("invalid git build context subdir: %w", err)}contextDir = filepath.Join(repoPath, filepath.FromSlash(source.Subdir))}@@ -301,7 +301,7 @@ func (s *BuildService) resolveBuildRequestInternal(info, err := os.Stat(contextDir)if err != nil {_ = s.cleanupGitContextInternal(repoPath)- return buildtypes.BuildRequest{}, func() error { return nil }, errors.WrapIf(err, "failed to stat resolved git build context")+ return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to stat resolved git build context: %w", err)}if !info.IsDir() {_ = s.cleanupGitContextInternal(repoPath)@@ -323,7 +323,7 @@ func (s *BuildService) resolveGitBuildAuthInternal(ctx context.Context, rawURL srepository, err := s.gitRepository.FindEnabledRepositoryByURL(ctx, rawURL)if err != nil {- return buildgit.AuthConfig{}, false, errors.WrapIf(err, "failed to resolve git repository credentials")+ return buildgit.AuthConfig{}, false, fmt.Errorf("failed to resolve git repository credentials: %w", err)}if repository == nil {return buildgit.AuthConfig{}, false, nil@@ -331,7 +331,7 @@ func (s *BuildService) resolveGitBuildAuthInternal(ctx context.Context, rawURL sauthConfig, err := s.gitRepository.GetAuthConfig(ctx, repository)if err != nil {- return buildgit.AuthConfig{}, true, errors.WrapIf(err, "failed to load git repository credentials")+ return buildgit.AuthConfig{}, true, fmt.Errorf("failed to load git repository credentials: %w", err)}return authConfig, true, nil@@ -413,7 +413,7 @@ func (s *BuildService) ListImageBuildsByEnvironmentPaginated(ctx context.ContextpaginationResp, err := pagination.PaginateAndSortDB(params, q, &builds)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate builds")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate builds: %w", err)}records := make([]imagetypes.BuildRecord, 0, len(builds))@@ -477,11 +477,9 @@ func (s *BuildService) createBuildRecord(ctx context.Context, environmentID striLoad: req.Load,CreatedAt: time.Now(),}-if err := s.db.WithContext(ctx).Create(record).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create build record")+ return nil, fmt.Errorf("failed to create build record: %w", err)}-return record, nil}@@ -515,7 +513,7 @@ func (s *BuildService) completeBuildRecord(return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Model(&ImageBuild{}).Where("id = ?", buildID).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update build record")+ return fmt.Errorf("failed to update build record: %w", result.Error)}if result.RowsAffected == 0 {return errors.New("build record not found")diff --git a/backend/internal/build/workspace_service.go b/backend/internal/build/workspace_service.goindex 6c7818378..a71224b94 100644--- a/backend/internal/build/workspace_service.go+++ b/backend/internal/build/workspace_service.go@@ -3,6 +3,8 @@ package buildimport ("cmp""context"+ "errors"+ "fmt""io""log/slog""net/http"@@ -11,7 +13,6 @@ import ("path/filepath""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/settings"acfsutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/acfs"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"@@ -39,12 +40,12 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strincleaned, err := kit.SanitizeBrowsePath(dirPath)if err != nil {- return nil, errors.WrapIf(err, "invalid path")+ return nil, fmt.Errorf("invalid path: %w", err)}entries, err := acfs.List(ctx, root, cleaned)if err != nil {- return nil, errors.WrapIf(err, "failed to list directory")+ return nil, fmt.Errorf("failed to list directory: %w", err)}results := make([]workspacetypes.FileEntry, 0, len(entries))@@ -64,7 +65,7 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strcleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {- return nil, "", errors.WrapIf(err, "invalid path")+ return nil, "", fmt.Errorf("invalid path: %w", err)}if maxBytes <= 0 {@@ -73,13 +74,13 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strfile, _, err := acfs.OpenRead(ctx, root, cleaned, maxBytes)if err != nil {- return nil, "", errors.WrapIf(err, "failed to open file")+ return nil, "", fmt.Errorf("failed to open file: %w", err)}defer func() { _ = file.Close() }()content, err := io.ReadAll(file)if err != nil {- return nil, "", errors.WrapIf(err, "failed to read file")+ return nil, "", fmt.Errorf("failed to read file: %w", err)}mimeType := http.DetectContentType(content)@@ -95,12 +96,12 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strincleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {- return nil, 0, errors.WrapIf(err, "invalid path")+ return nil, 0, fmt.Errorf("invalid path: %w", err)}file, size, err := acfs.OpenRead(ctx, root, cleaned, 0)if err != nil {- return nil, 0, errors.WrapIf(err, "failed to open file")+ return nil, 0, fmt.Errorf("failed to open file: %w", err)}return file, size, nil@@ -120,16 +121,16 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,cleaned, err := kit.SanitizeBrowsePath(destPath)if err != nil {- return errors.WrapIf(err, "invalid path")+ return fmt.Errorf("invalid path: %w", err)}if err := acfs.MkdirAll(ctx, root, cleaned, 0o755); err != nil {- return errors.WrapIf(err, "failed to create directory")+ return fmt.Errorf("failed to create directory: %w", err)}targetFile := path.Join(cleaned, safeFilename)if _, err := acfs.WriteFrom(ctx, root, targetFile, content, size, 0o644); err != nil {- return errors.WrapIf(err, "failed to write file")+ return fmt.Errorf("failed to write file: %w", err)}return nil@@ -144,7 +145,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath strcleaned, err := kit.SanitizeBrowsePath(dirPath)if err != nil {- return errors.WrapIf(err, "invalid path")+ return fmt.Errorf("invalid path: %w", err)}if cleaned == "/" {@@ -152,7 +153,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath str}if err := acfs.MkdirAll(ctx, root, cleaned, 0o755); err != nil {- return errors.WrapIf(err, "failed to create directory")+ return fmt.Errorf("failed to create directory: %w", err)}return nil@@ -167,7 +168,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)cleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {- return errors.WrapIf(err, "invalid path")+ return fmt.Errorf("invalid path: %w", err)}if cleaned == "/" {@@ -175,7 +176,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)}if err := acfs.RemoveAll(ctx, root, cleaned); err != nil {- return errors.WrapIf(err, "failed to delete path")+ return fmt.Errorf("failed to delete path: %w", err)}return nil@@ -194,7 +195,7 @@ func (s *BuildWorkspaceService) resolveRoot() (string, error) {cleaned := filepath.Clean(root)if err := os.MkdirAll(cleaned, 0o755); err != nil {- return "", errors.WrapIf(err, "failed to ensure builds directory")+ return "", fmt.Errorf("failed to ensure builds directory: %w", err)}return cleaned, nildiff --git a/backend/internal/common/api_error.go b/backend/internal/common/api_error.goindex 1194d505d..5970aee47 100644--- a/backend/internal/common/api_error.go+++ b/backend/internal/common/api_error.go@@ -1,10 +1,10 @@package commonimport (- stderrors "errors"+ "errors""net/http"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/types/v2/base")type APIErrorCode string@@ -89,25 +89,18 @@ func (e *DockerAPIError) HTTPStatus() int {}func ToAPIError(err error) *APIError {- if apiErr, ok := stderrors.AsType[*APIError](err); ok {+ if apiErr, ok := errors.AsType[*APIError](err); ok {return apiErr}- if dockerAPIErr, ok := stderrors.AsType[*DockerAPIError](err); ok {+ if dockerAPIErr, ok := errors.AsType[*DockerAPIError](err); ok {return NewAPIErrorWithDetails(dockerAPIErr.Message, APIErrorCodeDockerAPIError, dockerAPIErr.HTTPStatus(), dockerAPIErr.Details)}switch {case errors.Is(err, 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+ var details map[string]any+ if fieldErr, ok := errors.AsType[*base.FieldError](err); ok {+ details = map[string]any{"field": fieldErr.Field}}return NewAPIErrorWithDetails(err.Error(), APIErrorCodeValidationError, http.StatusBadRequest, details)case errors.Is(err, ErrBadRequest):diff --git a/backend/internal/common/api_error_test.go b/backend/internal/common/api_error_test.goindex 832e87c64..ff2bd9a49 100644--- a/backend/internal/common/api_error_test.go+++ b/backend/internal/common/api_error_test.go@@ -1,15 +1,16 @@package commonimport (+ "errors""net/http""testing"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/stretchr/testify/require")func TestToAPIErrorMapsClassifiedValidationDetails(t *testing.T) {- err := errors.WithDetails(errors.New("Name is required"), "field", "name")+ var err error = &base.FieldError{Field: "name", Err: errors.New("Name is required")}err = Classify(ErrValidation, err)apiErr := ToAPIError(err)diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex bc5aca5e9..123f8c2ef 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1,22 +1,8 @@package common-import (- "fmt"- "io"-- "emperror.dev/errors"-)+import "errors"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")-// ConfigurationErrorCodeEnvFileUnreadable is the ConfigurationError code reported// alongside ErrProjectEnvUnreadable.ConfigurationErrorCodeEnvFileUnreadable = "env_file_unreadable"@@ -44,95 +30,91 @@ func (e *classified) Unwrap() error { return e.err }func (e *classified) Is(target error) bool { return errors.Is(e.kind, target) }-func (e *classified) Format(s fmt.State, verb rune) {- if verb == 'v' && s.Flag('+') {- _, _ = fmt.Fprintf(s, "%+v", e.err)- return- }-- switch verb {- case 'q':- _, _ = fmt.Fprintf(s, "%q", e.err)- case 's', 'v':- _, _ = io.WriteString(s, e.err.Error())- }-}-+//nolint:staticcheck // Preserve existing API error messages.var (- ErrFeatureDisabled = Classify(ErrForbidden, errors.Sentinel("feature disabled"))- ErrInvalidToken = errors.Sentinel("invalid token")- ErrExpiredToken = errors.Sentinel("token expired")- ErrTokenVersionMismatch = errors.Sentinel("token version mismatch")- ErrUserNotFound = errors.Sentinel("user not found")- ErrAmbiguousUserEmail = Classify(ErrConflict, errors.Sentinel("multiple accounts share this email"))- 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"))- ErrUpdaterNoContainersMatched = Classify(ErrBadRequest, errors.Sentinel("no compose-managed containers matched the requested resources"))- 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"))- ErrApnsDisabled = Classify(ErrForbidden, errors.Sentinel("Mobile push notifications are disabled"))- ErrApnsDeviceNotFound = Classify(ErrNotFound, errors.Sentinel("Mobile push device not found"))- ErrApnsDeviceConflict = Classify(ErrConflict, errors.Sentinel("Mobile push device is already registered"))- ErrApnsRelay = Classify(ErrUnavailable, errors.Sentinel("Push relay request failed"))- 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"))- ErrImageUntagged = Classify(ErrBadRequest, errors.Sentinel("image has no tag; only tagged images can be patched"))- ErrImageLocalOnly = Classify(ErrBadRequest, errors.Sentinel("locally built image has no registry source to patch from; rebuild it to update its packages"))- ErrPatchRequiresContainerdImageStore = Classify(ErrBadRequest, errors.Sentinel("image patching requires Docker's containerd image store; enable the containerd-snapshotter feature in daemon.json and restart Docker"))- ErrPatchScanReportUnavailable = Classify(ErrNotFound, errors.Sentinel("no stored scan report is available for this scan; re-scan the image or patch without a report"))- ErrPatchScanImageMismatch = Classify(ErrBadRequest, errors.Sentinel("the selected scan does not belong to this image"))- ErrContainerComposeManaged = Classify(ErrConflict, errors.Sentinel("container is managed by a compose project; edit it via the project editor"))- ErrContainerNameTaken = Classify(ErrConflict, errors.Sentinel("a container with this name already exists"))- ErrInvalidBackupSelection = Classify(ErrBadRequest, errors.Sentinel("invalid backup file selection"))- ErrSwarmNotEnabled = Classify(ErrBadRequest, errors.Sentinel("Swarm mode is not enabled"))- ErrSwarmManagerRequired = Classify(ErrForbidden, errors.Sentinel("Swarm manager access required"))- 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"))- ErrProjectNotFound = Classify(ErrNotFound, errors.Sentinel("Project not found"))- ErrContainerRegistryNotFound = Classify(ErrNotFound, errors.Sentinel("Container registry not found"))- 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"))- ErrProjectWorkspaceConflict = Classify(ErrConflict, errors.Sentinel("Project workspace changed; refresh it and try again"))- ErrProjectWorkspaceForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden project workspace path"))- ErrProjectWorkspaceBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid project workspace request"))- ErrProjectWorkspaceNotFound = Classify(ErrNotFound, errors.Sentinel("Project workspace file not found"))- ErrVolumeWorkspaceConflict = Classify(ErrConflict, errors.Sentinel("Volume workspace changed; refresh it and try again"))- ErrVolumeWorkspaceForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden volume workspace path"))- ErrVolumeWorkspaceBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid volume workspace request"))- ErrVolumeWorkspaceNotFound = Classify(ErrNotFound, errors.Sentinel("Volume workspace file not found"))- ErrVolumeRenameInvalid = Classify(ErrBadRequest, errors.Sentinel("source and target volume names must be non-empty and different"))- ErrVolumeRenameProtected = Classify(ErrBadRequest, errors.Sentinel("Arcane's internal volumes cannot be renamed"))- ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project compose file not found"))- ErrComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("no compose file found"))- ErrComposeFileEnvInvalid = Classify(ErrValidation, errors.Sentinel("invalid COMPOSE_FILE selection"))- ErrProjectEnvUnreadable = Classify(ErrValidation, errors.Sentinel("project env file is not readable"))- ErrEnvironmentInvalidProxyTarget = Classify(ErrBadRequest, errors.Sentinel("Invalid proxy target URL"))- ErrEnvironmentConnectionTestFailed = Classify(ErrBadRequest, errors.Sentinel("Environment connection test failed"))- ErrUnsafeRemoteURL = Classify(ErrBadRequest, errors.Sentinel("Remote URL is not allowed"))- ErrImageScanInProgress = Classify(ErrConflict, errors.Sentinel("an image update check is already in progress"))- ErrVulnerabilityScanNotFound = Classify(ErrNotFound, errors.Sentinel("Vulnerability scan not found"))- ErrInvalidNotificationPayloadTemplate = Classify(ErrValidation, errors.Sentinel("invalid generic webhook payload template"))- ErrRedeployAfterSyncFailed = errors.Sentinel("redeploy failed")- ErrGitOpsSyncProjectBindingBroken = errors.Sentinel("GitOps sync project binding broken")- ErrUploadSessionNotFound = Classify(ErrNotFound, errors.Sentinel("Upload session not found"))- ErrUploadSessionIncomplete = Classify(ErrConflict, errors.Sentinel("Upload session is incomplete"))- ErrUploadKindMismatch = Classify(ErrBadRequest, errors.Sentinel("Upload session kind does not match this endpoint"))- ErrUploadChunkInvalid = Classify(ErrValidation, errors.Sentinel("Invalid upload chunk"))- ErrUploadSessionInvalid = Classify(ErrValidation, errors.Sentinel("Invalid upload session request"))+ ErrBadRequest = errors.New("kind: bad request")+ ErrValidation = errors.New("kind: validation failed")+ ErrUnauthorized = errors.New("kind: unauthorized")+ ErrForbidden = errors.New("kind: forbidden")+ ErrNotFound = errors.New("kind: not found")+ ErrConflict = errors.New("kind: conflict")+ ErrTimeout = errors.New("kind: timeout")+ ErrUnavailable = errors.New("kind: service unavailable")++ ErrFeatureDisabled = Classify(ErrForbidden, errors.New("feature disabled"))+ ErrInvalidToken = errors.New("invalid token")+ ErrExpiredToken = errors.New("token expired")+ ErrTokenVersionMismatch = errors.New("token version mismatch")+ ErrUserNotFound = errors.New("user not found")+ ErrAmbiguousUserEmail = Classify(ErrConflict, errors.New("multiple accounts share this email"))+ ErrTokenValidation = Classify(ErrUnauthorized, errors.New("Invalid token claims"))+ ErrSessionRevoked = Classify(ErrUnauthorized, errors.New("Session has been revoked"))+ ErrUpgradeInProgress = Classify(ErrConflict, errors.New("an upgrade is already in progress"))+ ErrUpdateAllInProgress = Classify(ErrConflict, errors.New("an update-all job is already in progress"))+ ErrUpdaterNoContainersMatched = Classify(ErrBadRequest, errors.New("no compose-managed containers matched the requested resources"))+ ErrTemplateNotFound = Classify(ErrNotFound, errors.New("Template not found"))+ ErrInvalidEnvKey = Classify(ErrValidation, errors.New("Invalid environment key"))+ ErrGlobalVariableNotFound = Classify(ErrNotFound, errors.New("Global variable not found"))+ ErrApnsDisabled = Classify(ErrForbidden, errors.New("Mobile push notifications are disabled"))+ ErrApnsDeviceNotFound = Classify(ErrNotFound, errors.New("Mobile push device not found"))+ ErrApnsDeviceConflict = Classify(ErrConflict, errors.New("Mobile push device is already registered"))+ ErrApnsRelay = Classify(ErrUnavailable, errors.New("Push relay request failed"))+ ErrGlobalVariableConflict = Classify(ErrConflict, errors.New("Global variable already exists"))+ ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.New("At least one environment is required when a variable is not scoped to all environments"))+ ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.New("A new value is required when making a secret variable readable"))+ ErrImageUntagged = Classify(ErrBadRequest, errors.New("image has no tag; only tagged images can be patched"))+ ErrImageLocalOnly = Classify(ErrBadRequest, errors.New("locally built image has no registry source to patch from; rebuild it to update its packages"))+ ErrPatchRequiresContainerdImageStore = Classify(ErrBadRequest, errors.New("image patching requires Docker's containerd image store; enable the containerd-snapshotter feature in daemon.json and restart Docker"))+ ErrPatchScanReportUnavailable = Classify(ErrNotFound, errors.New("no stored scan report is available for this scan; re-scan the image or patch without a report"))+ ErrPatchScanImageMismatch = Classify(ErrBadRequest, errors.New("the selected scan does not belong to this image"))+ ErrContainerComposeManaged = Classify(ErrConflict, errors.New("container is managed by a compose project; edit it via the project editor"))+ ErrContainerNameTaken = Classify(ErrConflict, errors.New("a container with this name already exists"))+ ErrInvalidBackupSelection = Classify(ErrBadRequest, errors.New("invalid backup file selection"))+ ErrSwarmNotEnabled = Classify(ErrBadRequest, errors.New("Swarm mode is not enabled"))+ ErrSwarmManagerRequired = Classify(ErrForbidden, errors.New("Swarm manager access required"))+ ErrRoleNotFound = Classify(ErrNotFound, errors.New("Role not found"))+ ErrRoleBuiltIn = Classify(ErrForbidden, errors.New("Built-in role cannot be modified"))+ ErrRoleNameTaken = Classify(ErrConflict, errors.New("Role name already in use"))+ ErrUnknownPermission = Classify(ErrValidation, errors.New("Unknown permission"))+ ErrRolePermissionEscalation = Classify(ErrForbidden, errors.New("cannot grant a permission you do not hold"))+ ErrInvalidRoleAssignment = Classify(ErrBadRequest, errors.New("invalid role assignment"))+ ErrFederatedCredentialNotFound = Classify(ErrNotFound, errors.New("federated credential not found"))+ ErrFederatedCredentialInvalid = Classify(ErrValidation, errors.New("invalid federated credential"))+ ErrFederatedCredentialInvalidRequest = Classify(ErrBadRequest, errors.New("invalid federated token exchange request"))+ ErrFederatedCredentialInvalidGrant = Classify(ErrUnauthorized, errors.New("invalid federated token grant"))+ ErrFederatedCredentialPermissionEscalation = Classify(ErrForbidden, errors.New("cannot map a federated credential to a role you do not hold"))+ ErrOidcMappingNotFound = Classify(ErrNotFound, errors.New("OIDC role mapping not found"))+ ErrOidcMappingEnvManaged = Classify(ErrConflict, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))+ ErrNoGlobalAdminRemains = Classify(ErrConflict, errors.New("At least one user must retain a global Admin role assignment"))+ ErrProjectNotFound = Classify(ErrNotFound, errors.New("Project not found"))+ ErrContainerRegistryNotFound = Classify(ErrNotFound, errors.New("Container registry not found"))+ ErrProjectArchived = Classify(ErrConflict, errors.New("project is archived and must be unarchived before this action"))+ ErrProjectMustBeStopped = Classify(ErrConflict, errors.New("project must be stopped before archiving"))+ ErrProjectWorkspaceConflict = Classify(ErrConflict, errors.New("Project workspace changed; refresh it and try again"))+ ErrProjectWorkspaceForbidden = Classify(ErrForbidden, errors.New("Forbidden project workspace path"))+ ErrProjectWorkspaceBadRequest = Classify(ErrBadRequest, errors.New("Invalid project workspace request"))+ ErrProjectWorkspaceNotFound = Classify(ErrNotFound, errors.New("Project workspace file not found"))+ ErrVolumeWorkspaceConflict = Classify(ErrConflict, errors.New("Volume workspace changed; refresh it and try again"))+ ErrVolumeWorkspaceForbidden = Classify(ErrForbidden, errors.New("Forbidden volume workspace path"))+ ErrVolumeWorkspaceBadRequest = Classify(ErrBadRequest, errors.New("Invalid volume workspace request"))+ ErrVolumeWorkspaceNotFound = Classify(ErrNotFound, errors.New("Volume workspace file not found"))+ ErrVolumeRenameInvalid = Classify(ErrBadRequest, errors.New("source and target volume names must be non-empty and different"))+ ErrVolumeRenameProtected = Classify(ErrBadRequest, errors.New("Arcane's internal volumes cannot be renamed"))+ ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.New("Project compose file not found"))+ ErrComposeFileNotFound = Classify(ErrNotFound, errors.New("no compose file found"))+ ErrComposeFileEnvInvalid = Classify(ErrValidation, errors.New("invalid COMPOSE_FILE selection"))+ ErrProjectEnvUnreadable = Classify(ErrValidation, errors.New("project env file is not readable"))+ ErrEnvironmentInvalidProxyTarget = Classify(ErrBadRequest, errors.New("Invalid proxy target URL"))+ ErrEnvironmentConnectionTestFailed = Classify(ErrBadRequest, errors.New("Environment connection test failed"))+ ErrUnsafeRemoteURL = Classify(ErrBadRequest, errors.New("Remote URL is not allowed"))+ ErrImageScanInProgress = Classify(ErrConflict, errors.New("an image update check is already in progress"))+ ErrVulnerabilityScanNotFound = Classify(ErrNotFound, errors.New("Vulnerability scan not found"))+ ErrInvalidNotificationPayloadTemplate = Classify(ErrValidation, errors.New("invalid generic webhook payload template"))+ ErrRedeployAfterSyncFailed = errors.New("redeploy failed")+ ErrGitOpsSyncProjectBindingBroken = errors.New("GitOps sync project binding broken")+ ErrUploadSessionNotFound = Classify(ErrNotFound, errors.New("Upload session not found"))+ ErrUploadSessionIncomplete = Classify(ErrConflict, errors.New("Upload session is incomplete"))+ ErrUploadKindMismatch = Classify(ErrBadRequest, errors.New("Upload session kind does not match this endpoint"))+ ErrUploadChunkInvalid = Classify(ErrValidation, errors.New("Invalid upload chunk"))+ ErrUploadSessionInvalid = Classify(ErrValidation, errors.New("Invalid upload session request")))diff --git a/backend/internal/common/errors_test.go b/backend/internal/common/errors_test.goindex 5bb3fb440..e8c2493a6 100644--- a/backend/internal/common/errors_test.go+++ b/backend/internal/common/errors_test.go@@ -1,30 +1,25 @@package commonimport (- stderrors "errors"+ "errors"+ "fmt""testing"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/stretchr/testify/require")-func TestClassifyPreservesChainDetailsAndSingleStack(t *testing.T) {+func TestClassifyPreservesChainAndField(t *testing.T) {cause := errors.New("root cause")- err := errors.WithDetails(cause, "field", "name")+ var err error = &base.FieldError{Field: "name", Err: cause}err = Classify(ErrInvalidEnvKey, err)- err = errors.WrapIf(err, "validate input")+ err = fmt.Errorf("validate input: %w", err)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)+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ require.Equal(t, "name", fieldErr.Field)}diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.goindex 4563a254c..66dd1de20 100644--- a/backend/internal/config/schema/schema.go+++ b/backend/internal/config/schema/schema.go@@ -5,6 +5,8 @@ import ("cmp""encoding/json/jsontext""encoding/json/v2"+ "errors"+ "fmt""go/ast""go/format""go/parser"@@ -17,7 +19,6 @@ import ("strconv""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"kit "go.getarcane.app/kit/pkg"@@ -157,12 +158,12 @@ var overrideDocRules = map[string]overrideDocRule{func GenerateWithSourceRoot(sourceRoot string) (*SchemaDocument, error) {envConfig, err := collectEnvConfigInternal(sourceRoot)if err != nil {- return nil, errors.WrapIf(err, "collect env config")+ return nil, fmt.Errorf("collect env config: %w", err)}settingOverrides, err := collectSettingEnvOverridesInternal()if err != nil {- return nil, errors.WrapIf(err, "collect setting env overrides")+ return nil, fmt.Errorf("collect setting env overrides: %w", err)}doc := &SchemaDocument{@@ -179,7 +180,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, errors.WrapIf(err, "marshal schema document")+ return nil, fmt.Errorf("marshal schema document: %w", err)}output = append(output, '\n')@@ -230,7 +231,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptifset := token.NewFileSet()file, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)if err != nil {- return nil, errors.WrapIff(err, "parse %s", filename)+ return nil, fmt.Errorf("parse %s: %w", filename, err)}structType, err := findStructTypeInternal(file, structName)@@ -246,7 +247,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptitagValue, err := strconv.Unquote(field.Tag.Value)if err != nil {- return nil, errors.WrapIff(err, "unquote struct tag for %s", structName)+ return nil, fmt.Errorf("unquote struct tag for %s: %w", structName, err)}structTag := reflect.StructTag(tagValue)@@ -258,7 +259,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptioptions := kit.TrimNonEmpty(strings.Split(structTag.Get("options"), ","))typeName, err := exprStringInternal(field.Type)if err != nil {- return nil, errors.WrapIff(err, "render type for %s.%s", structName, field.Names[0].Name)+ return nil, fmt.Errorf("render type for %s.%s: %w", structName, field.Names[0].Name, err)}description := cmp.Or(strings.Join(strings.Fields(field.Doc.Text()), " "), strings.Join(strings.Fields(field.Comment.Text()), " "))@@ -311,7 +312,7 @@ func collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {defaultValue, isPublic, isSensitive, err := defaults.FieldByKey(key)if err != nil {- return nil, errors.WrapIff(err, "lookup default value for %q", key)+ return nil, fmt.Errorf("lookup default value for %q: %w", key, err)}if isSensitive {defaultValue = ""@@ -367,14 +368,14 @@ func findStructTypeInternal(file *ast.File, structName string) (*ast.StructType,structType, ok := typeSpec.Type.(*ast.StructType)if !ok {- return nil, errors.Errorf("%s is not a struct", structName)+ return nil, fmt.Errorf("%s is not a struct", structName)}return structType, nil}}- return nil, errors.Errorf("struct %s not found", structName)+ return nil, fmt.Errorf("struct %s not found", structName)}func exprStringInternal(expr ast.Expr) (string, error) {@@ -392,7 +393,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {} else {wd, err := os.Getwd()if err != nil {- return "", errors.WrapIf(err, "get working directory")+ return "", fmt.Errorf("get working directory: %w", err)}candidates = append(candidates, wd)}@@ -405,7 +406,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {}if strings.TrimSpace(sourceRoot) != "" {- return "", errors.Errorf("resolve source root from %q: expected backend/internal/config/config.go", sourceRoot)+ return "", fmt.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")@@ -414,7 +415,7 @@ func resolveSourceRootInternal(sourceRoot string) (string, error) {func resolveSourceRootCandidateInternal(candidate string) (string, error) {candidate, err := filepath.Abs(candidate)if err != nil {- return "", errors.WrapIff(err, "abs path for %q", candidate)+ return "", fmt.Errorf("abs path for %q: %w", candidate, err)}for current := candidate; ; current = filepath.Dir(current) {@@ -433,7 +434,7 @@ func resolveSourceRootCandidateInternal(candidate string) (string, error) {}}- return "", errors.Errorf("schema sources not found from %q", candidate)+ return "", fmt.Errorf("schema sources not found from %q", candidate)}func hasSchemaSourceFilesInternal(root string) bool {diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.goindex a2238fd2a..0abd5d7c2 100644--- a/backend/internal/container/handler.go+++ b/backend/internal/container/handler.go@@ -2,6 +2,7 @@ package containerimport ("context"+ "errors""fmt""io""maps"@@ -9,7 +10,6 @@ import ("net/netip""strings"- "emperror.dev/errors""github.com/containerd/errdefs""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"@@ -345,7 +345,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContairesult, err := h.containerService.ListContainersPaginated(ctx, params, true, input.IncludeInternal, input.IncludeHidden, input.GroupBy)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list containers").Error())+ return nil, huma.Error500InternalServerError("Failed to list containers: " + err.Error())}return &ListContainersOutput{@@ -363,7 +363,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContaifunc (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*handlerutil.Out[containertypes.StatusCounts], error) {containers, _, _, _, err := h.dockerService.GetAllContainers(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get container counts").Error())+ return nil, huma.Error500InternalServerError("Failed to get container counts: " + err.Error())}containers = FilterExcludedContainers(containers, input.IncludeInternal, input.IncludeHidden)@@ -598,26 +598,26 @@ 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(errors.WithMessage(err, "Invalid port format").Error())+ return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())}if err := applyExposedPorts(input.Body.ExposedPorts, config); err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid port format").Error())+ return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())}hostConfig := buildHostConfigBase(input.Body, portBindings)if err := applyHostConfigOverrides(input.Body, config, hostConfig, portBindings); err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid port format").Error())+ return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())}applyLegacyResourceLimits(input.Body, hostConfig)networkingConfig, err := buildNetworkingConfig(input.Body)if err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid network configuration").Error())+ return nil, huma.Error400BadRequest("Invalid network configuration: " + err.Error())}containerJSON, err := h.containerService.CreateContainer(ctx, config, hostConfig, networkingConfig, input.Body.Name, *user, input.Body.Credentials)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create container").Error())+ return nil, huma.Error500InternalServerError("Failed to create container: " + err.Error())}out := containertypes.Created{@@ -639,7 +639,7 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateConfunc (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*handlerutil.Out[containertypes.Details], error) {details, err := h.containerService.GetContainerDetails(ctx, input.ContainerID)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())+ return nil, huma.Error404NotFound("Failed to retrieve container: " + err.Error())}return &handlerutil.Out[containertypes.Details]{@@ -653,7 +653,7 @@ func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerfunc (h *ContainerHandler) GetContainerProcesses(ctx context.Context, input *GetContainerInput) (*handlerutil.Out[containertypes.Processes], error) {processes, err := h.containerService.GetContainerProcesses(ctx, input.ContainerID)if err != nil {- message := errors.WithMessage(err, "Failed to retrieve container processes").Error()+ message := "Failed to retrieve container processes: " + err.Error()switch {case errdefs.IsNotFound(err):return nil, huma.Error404NotFound(message)@@ -678,9 +678,9 @@ func (h *ContainerHandler) DownloadContainerLogs(ctx context.Context, input *Getreader, filename, err := h.containerService.DownloadLogs(ctx, input.ContainerID)if err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())+ return nil, huma.Error404NotFound("Failed to retrieve container: " + err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to download container logs").Error())+ return nil, huma.Error500InternalServerError("Failed to download container logs: " + err.Error())}return handlerutil.DownloadResponse(reader, -1, filename), nil}@@ -688,7 +688,7 @@ func (h *ContainerHandler) DownloadContainerLogs(ctx context.Context, input *Getfunc (h *ContainerHandler) GenerateCompose(ctx context.Context, input *GenerateComposeInput) (*handlerutil.Out[containertypes.GenerateComposeResponse], error) {composeContent, err := projects.ComposeGenerate(ctx, h.dockerService.DockerHost(), "", input.Body.ContainerIDs)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate compose file").Error())+ return nil, huma.Error500InternalServerError("Failed to generate compose file: " + err.Error())}return &handlerutil.Out[containertypes.GenerateComposeResponse]{@@ -710,7 +710,7 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerAreturn h.containerService.StartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start container").Error())+ return huma.Error500InternalServerError("Failed to start container: " + err.Error())},})}@@ -726,7 +726,7 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAcreturn h.containerService.StopContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to stop container").Error())+ return huma.Error500InternalServerError("Failed to stop container: " + err.Error())},})}@@ -742,7 +742,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containereturn h.containerService.RestartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to restart container").Error())+ return huma.Error500InternalServerError("Failed to restart container: " + err.Error())},})}@@ -759,7 +759,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(errors.WithMessage(err, "Failed to kill container").Error())+ return huma.Error500InternalServerError("Failed to kill container: " + err.Error())},})}@@ -775,7 +775,7 @@ func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerAreturn h.containerService.PauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to pause container").Error())+ return huma.Error500InternalServerError("Failed to pause container: " + err.Error())},})}@@ -791,7 +791,7 @@ func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *Containereturn h.containerService.UnpauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to unpause container").Error())+ return huma.Error500InternalServerError("Failed to unpause container: " + err.Error())},})}@@ -866,7 +866,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(errors.WithMessage(err, "Failed to redeploy container").Error())+ return nil, huma.Error500InternalServerError("Failed to redeploy container: " + err.Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container redeployed", nil)@@ -900,7 +900,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Containfunc (h *ContainerHandler) GetContainerEditConfig(ctx context.Context, input *GetContainerEditConfigInput) (*handlerutil.Out[containertypes.EditConfig], error) {editConfig, err := h.containerService.GetContainerEditConfig(ctx, input.ContainerID)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())+ return nil, huma.Error404NotFound("Failed to retrieve container: " + err.Error())}return &handlerutil.Out[containertypes.EditConfig]{@@ -918,7 +918,7 @@ func editContainerHTTPErrorInternal(err error) error {case errors.Is(err, common.ErrValidation):return huma.Error400BadRequest(err.Error())default:- return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to edit container").Error())+ return huma.Error500InternalServerError("Failed to edit container: " + err.Error())}}@@ -978,7 +978,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteConactivityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", database.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes}, false)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(errors.WithMessage(err, "Failed to delete container").Error())+ return nil, huma.Error500InternalServerError("Failed to delete container: " + err.Error())}activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)diff --git a/backend/internal/container/logs.go b/backend/internal/container/logs.goindex 25131f9c4..07da81301 100644--- a/backend/internal/container/logs.go+++ b/backend/internal/container/logs.go@@ -2,9 +2,10 @@ package containerimport ("context"+ "errors"+ "fmt""io"- "emperror.dev/errors"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"@@ -19,23 +20,23 @@ type demuxedLogsInternal struct {}func (d *demuxedLogsInternal) Close() error {- return errors.Combine(d.logs.Close(), d.pipe.Close())+ return errors.Join(d.logs.Close(), d.pipe.Close())}func (s *ContainerService) openLogsInternal(ctx context.Context, containerID string, options client.ContainerLogsOptions) (io.ReadCloser, client.ContainerInspectResult, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, client.ContainerInspectResult{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, client.ContainerInspectResult{}, fmt.Errorf("failed to connect to Docker: %w", err)}containerInspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {- return nil, client.ContainerInspectResult{}, errors.WrapIf(err, "failed to inspect container for logs")+ return nil, client.ContainerInspectResult{}, fmt.Errorf("failed to inspect container for logs: %w", err)}logs, err := dockerClient.ContainerLogs(ctx, containerID, options)if err != nil {- return nil, client.ContainerInspectResult{}, errors.WrapIf(err, "failed to get container logs")+ return nil, client.ContainerInspectResult{}, fmt.Errorf("failed to get container logs: %w", err)}return logs, containerInspect, nil}diff --git a/backend/internal/container/resource_stats.go b/backend/internal/container/resource_stats.goindex 52d1d5175..abe0eecdd 100644--- a/backend/internal/container/resource_stats.go+++ b/backend/internal/container/resource_stats.go@@ -4,12 +4,13 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors"+ "fmt""log/slog""strings""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -124,7 +125,7 @@ func (s *ContainerService) collectResourceSamplesInternal(ctx context.Context, i}if err := g.Wait(); err != nil {- return nil, errors.WrapIf(err, "failed to collect container resource samples")+ return nil, fmt.Errorf("failed to collect container resource samples: %w", err)}return samples, nil}@@ -172,18 +173,18 @@ func (s *ContainerService) fetchResourceSampleInternal(ctx context.Context, contfunc (s *ContainerService) collectResourceSampleInternal(ctx context.Context, containerID string) (*containertypes.ResourceSample, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}stats, err := dockerClient.ContainerStats(ctx, containerID, client.ContainerStatsOptions{Stream: false, IncludePreviousSample: true})if err != nil {- return nil, errors.WrapIf(err, "failed to fetch container stats")+ return nil, fmt.Errorf("failed to fetch container stats: %w", err)}defer func() { _ = stats.Body.Close() }()var statsData container.StatsResponseif err := json.UnmarshalDecode(jsontext.NewDecoder(stats.Body), &statsData); err != nil {- return nil, errors.WrapIf(err, "failed to decode container stats")+ return nil, fmt.Errorf("failed to decode container stats: %w", err)}built := containerstats.BuildSample(statsData)diff --git a/backend/internal/container/resource_stats_test.go b/backend/internal/container/resource_stats_test.goindex c35a27667..014be0fb1 100644--- a/backend/internal/container/resource_stats_test.go+++ b/backend/internal/container/resource_stats_test.go@@ -161,9 +161,9 @@ func newResourceSortServiceInternal(t *testing.T, fixture *resourceStatsServerInfunc resourceSortParamsInternal(sort, order string, start, limit int) pagination.QueryParams {return pagination.QueryParams{- SortParams: pagination.SortParams{Sort: sort, Order: pagination.SortOrder(order)},- Params: pagination.Params{Start: start, Limit: limit},- Filters: map[string]string{},+ Sort: sort, Order: pagination.SortOrder(order),+ Start: start, Limit: limit,+ Filters: map[string]string{},}}@@ -344,12 +344,10 @@ func TestResourceSortCoalescesConcurrentFetches(t *testing.T) {var wg sync.WaitGrouperrs := make([]error, callers)for i := range callers {- wg.Add(1)- go func() {- defer wg.Done()+ wg.Go(func() {_, err := svc.fetchResourceSampleInternal(t.Context(), "web")errs[i] = err- }()+ })}wg.Wait()for _, err := range errs {diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex a49fe3cbf..e8c08f07a 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -5,6 +5,7 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -14,7 +15,6 @@ 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/docker"@@ -176,7 +176,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "pull_image_timeout","image": imageName,})- return errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageName)+ return fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageName)}s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, database.JSON{@@ -184,7 +184,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "pull_image","image": imageName,})- return errors.WrapIff(pullErr, "failed to pull image %s", imageName)+ return fmt.Errorf("failed to pull image %s: %w", imageName, pullErr)}defer func() { _ = reader.Close() }()@@ -199,7 +199,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker"step": "complete_pull","image": imageName,})- return errors.WrapIf(streamErr, "failed to complete image pull")+ return fmt.Errorf("failed to complete image pull: %w", streamErr)}return nil@@ -214,7 +214,7 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conte"step": "rename_old","backupName": backupName,})- return errors.WrapIf(err, "failed to rename existing container")+ return fmt.Errorf("failed to rename existing container: %w", err)}}@@ -240,7 +240,7 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conte"action": "redeploy","step": "stop",})- return errors.WrapIf(err, "failed to stop container")+ return fmt.Errorf("failed to stop container: %w", err)}func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName, failedStep string, wasRunning bool, user common.User) {@@ -296,7 +296,7 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(c"action": "redeploy","step": "restore_create_original",})- return errors.WrapIf(err, "failed to recreate original auto-remove container")+ return fmt.Errorf("failed to recreate original auto-remove container: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("container", createResp.ID, containerName)()@@ -305,7 +305,7 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(c"action": "redeploy","step": "restore_start_original",})- return errors.WrapIf(err, "failed to restart original auto-remove container")+ return fmt.Errorf("failed to restart original auto-remove container: %w", err)}slog.InfoContext(@@ -328,7 +328,7 @@ func (s *ContainerService) rollbackFailedReplacementStartInternal(ctx context.Cos.eventService.MarkDockerExpectation("container", replacementID, containerName)var cleanupErr errorif _, removeErr := dockerClient.ContainerRemove(ctx, replacementID, client.ContainerRemoveOptions{Force: true}); removeErr != nil {- cleanupErr = errors.WrapIf(removeErr, "failed to remove replacement container")+ cleanupErr = fmt.Errorf("failed to remove replacement container: %w", removeErr)s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", replacementID, containerName, user.ID, user.Username, "0", removeErr, database.JSON{"action": action,"step": "cleanup_failed_start",@@ -337,7 +337,7 @@ func (s *ContainerService) rollbackFailedReplacementStartInternal(ctx context.Coif stopAfterCreate {if restoreErr := s.restoreAutoRemoveContainerAfterStartFailureInternal(ctx, dockerClient, containerInfo, apiVersion, user); restoreErr != nil {- return errors.Combine(startErr, cleanupErr, restoreErr)+ return errors.Join(startErr, cleanupErr, restoreErr)}return startErr}@@ -358,7 +358,7 @@ func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.ContedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": cfg.action})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}metadata := database.JSON{@@ -370,7 +370,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 errors.WrapIf(err, "failed to log action")+ return fmt.Errorf("failed to log action: %w", err)}slog.WarnContext(ctx, "could not log container action", "action", cfg.action, "error", err)}@@ -468,7 +468,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "commit"})- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}repository := strings.TrimSpace(req.Repository)@@ -484,7 +484,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stri})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "container", containerID, reference, user.ID, user.Username, "0", err, database.JSON{"action": "commit", "reference": reference})- return nil, errors.WrapIf(err, "failed to commit container")+ return nil, fmt.Errorf("failed to commit container: %w", err)}metadata := database.JSON{@@ -543,7 +543,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont)return "", false, nil}- return "", true, errors.WrapIff(err, "failed to look up compose project %s", projectName)+ return "", true, fmt.Errorf("failed to look up compose project %s: %w", projectName, err)}if proj == nil {slog.WarnContext(@@ -571,7 +571,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont"projectId": proj.ID,"projectName": proj.Name,})- return "", true, errors.WrapIff(err, "compose redeploy failed for %s/%s", projectName, serviceName)+ return "", true, fmt.Errorf("compose redeploy failed for %s/%s: %w", projectName, serviceName, err)}newID, lookupErr := projects.FindComposeServiceContainerID(ctx, s.dockerService.DockerHost(), projectName, serviceName)@@ -606,7 +606,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "get_client",})- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})@@ -615,7 +615,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "inspect",})- return "", errors.WrapIf(err, "failed to inspect container")+ return "", fmt.Errorf("failed to inspect container: %w", err)}containerInfo := containerJSON.Container@@ -625,7 +625,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st"action": "redeploy","step": "validate_config",})- return "", errors.WrapIf(err, "failed to redeploy container")+ return "", fmt.Errorf("failed to redeploy container: %w", err)}containerName := strings.TrimPrefix(containerInfo.Name, "/")@@ -706,7 +706,7 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker"step": "create","image": imageName,})- return "", errors.WrapIf(err, "failed to recreate container")+ return "", fmt.Errorf("failed to recreate container: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("container", createResp.ID, newName)()@@ -724,7 +724,7 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker"action": action,"step": "stop",})- return "", errors.WrapIf(err, "failed to stop container")+ return "", fmt.Errorf("failed to stop container: %w", err)}}@@ -737,7 +737,7 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker"step": "start","image": imageName,})- return "", errors.WrapIf(err, "failed to start new container")+ return "", fmt.Errorf("failed to start new container: %w", err)}}@@ -840,7 +840,7 @@ func portMapFromCreateInternal(bindings map[string][]containertypes.PortBindingCfor portSpec, bindingList := range bindings {port, err := parsePortSpec(portSpec)if err != nil {- return nil, errors.WrapIff(err, "invalid port %s", portSpec)+ return nil, fmt.Errorf("invalid port %s: %w", portSpec, err)}mapped := make([]network.PortBinding, 0, len(bindingList))for _, binding := range bindingList {@@ -848,7 +848,7 @@ func portMapFromCreateInternal(bindings map[string][]containertypes.PortBindingCif hostIP := strings.TrimSpace(binding.HostIP); hostIP != "" {parsedIP, err := netip.ParseAddr(hostIP)if err != nil {- return nil, errors.WrapIff(err, "invalid host IP %s", hostIP)+ return nil, fmt.Errorf("invalid host IP %s: %w", hostIP, err)}pb.HostIP = parsedIP}@@ -870,14 +870,14 @@ func endpointIPAMFromCreateInternal(ep containertypes.EndpointSettingsCreate) (*if ipv4 != "" {addr, err := netip.ParseAddr(ipv4)if err != nil {- return nil, errors.WrapIff(err, "invalid IPv4 address %s", ipv4)+ return nil, fmt.Errorf("invalid IPv4 address %s: %w", ipv4, err)}cfg.IPv4Address = addr}if ipv6 != "" {addr, err := netip.ParseAddr(ipv6)if err != nil {- return nil, errors.WrapIff(err, "invalid IPv6 address %s", ipv6)+ return nil, fmt.Errorf("invalid IPv6 address %s: %w", ipv6, err)}cfg.IPv6Address = addr}@@ -1048,12 +1048,12 @@ func buildEditNetworkingConfigInternal(containerInspect container.InspectResponsfunc (s *ContainerService) GetContainerEditConfig(ctx context.Context, containerID string) (containertypes.EditConfig, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return containertypes.EditConfig{}, errors.WrapIf(err, "failed to connect to Docker")+ return containertypes.EditConfig{}, fmt.Errorf("failed to connect to Docker: %w", err)}containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {- return containertypes.EditConfig{}, errors.WrapIf(err, "failed to inspect container")+ return containertypes.EditConfig{}, fmt.Errorf("failed to inspect container: %w", err)}containerInfo := containerJSON.Container@@ -1079,7 +1079,7 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string"action": "edit","step": "get_client",})- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})@@ -1088,7 +1088,7 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string"action": "edit","step": "inspect",})- return "", errors.WrapIf(err, "failed to inspect container")+ return "", fmt.Errorf("failed to inspect container: %w", err)}containerInfo := containerJSON.Container@@ -1099,7 +1099,7 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID stringcontainerName := strings.TrimPrefix(containerInfo.Name, "/")if project := dockerutils.ComposeProjectLabel(containerInfo.Config.Labels); project != "" {- return "", errors.WrapIff(common.ErrContainerComposeManaged, "compose project %s", project)+ return "", fmt.Errorf("compose project %s: %w", project, common.ErrContainerComposeManaged)}currentContainerID, currentContainerErr := cgroup.CurrentContainerID()@@ -1120,7 +1120,7 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string}if newName != containerName {if _, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, newName, client.ContainerInspectOptions{}); inspectErr == nil {- return "", errors.WrapIff(common.ErrContainerNameTaken, "container name %s", newName)+ return "", fmt.Errorf("container name %s: %w", newName, common.ErrContainerNameTaken)}}@@ -1160,12 +1160,12 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID stringfunc (s *ContainerService) GetContainerByReference(ctx context.Context, ref string) (*container.InspectResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}containerInspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, ref, client.ContainerInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "container not found")+ return nil, fmt.Errorf("container not found: %w", err)}return new(containerInspect.Container), nil@@ -1205,7 +1205,7 @@ var containerProcessesPsArgs = []string{"-eo", "pid,user,%cpu,%mem,etime,cmd"}func (s *ContainerService) GetContainerProcesses(ctx context.Context, containerID string) (containertypes.Processes, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return containertypes.Processes{}, errors.WrapIf(err, "failed to connect to Docker")+ return containertypes.Processes{}, fmt.Errorf("failed to connect to Docker: %w", err)}timeout := timeouts.DefaultDockerAPI@@ -1217,7 +1217,7 @@ func (s *ContainerService) GetContainerProcesses(ctx context.Context, containerIresult, err := dockerClient.ContainerTop(topCtx, containerID, client.ContainerTopOptions{Arguments: containerProcessesPsArgs})if err != nil {- return containertypes.Processes{}, errors.WrapIf(err, "failed to list container processes")+ return containertypes.Processes{}, fmt.Errorf("failed to list container processes: %w", err)}processes := containertypes.Processes{Titles: result.Titles, Processes: result.Processes}if processes.Titles == nil {@@ -1246,7 +1246,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}// Get container mounts before deletion if we need to remove volumes@@ -1274,7 +1274,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})- return errors.WrapIf(err, "failed to delete container")+ return fmt.Errorf("failed to delete container: %w", err)}// Remove named volumes if requested@@ -1294,7 +1294,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID strierr = s.eventService.LogContainerEvent(ctx, event.EventTypeContainerDelete, containerID, "name", user.ID, user.Username, "0", metadata)if err != nil {- return errors.WrapIf(err, "failed to log action")+ return fmt.Errorf("failed to log action: %w", err)}return nil@@ -1304,7 +1304,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image})- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}_, err = dockerClient.ImageInspect(ctx, config.Image)@@ -1327,10 +1327,10 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containeif pullErr != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image_timeout"})- return nil, errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)+ return nil, fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)}s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image"})- return nil, errors.WrapIff(pullErr, "failed to pull image %s", config.Image)+ return nil, fmt.Errorf("failed to pull image %s: %w", config.Image, pullErr)}defer func() { _ = reader.Close() }()@@ -1340,7 +1340,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe_ = logWriter.Close()if streamErr != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "create", "image": config.Image, "step": "complete_pull"})- return nil, errors.WrapIf(streamErr, "failed to complete image pull")+ return nil, fmt.Errorf("failed to complete image pull: %w", streamErr)}}@@ -1353,7 +1353,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "create"})- return nil, errors.WrapIf(err, "failed to create container")+ return nil, fmt.Errorf("failed to create container: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("container", resp.ID, containerName)()@@ -1369,13 +1369,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, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "start"})- return nil, errors.WrapIf(err, "failed to start container")+ return nil, fmt.Errorf("failed to start container: %w", err)}containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "inspect"})- return nil, errors.WrapIf(err, "failed to inspect created container")+ return nil, fmt.Errorf("failed to inspect created container: %w", err)}return new(containerJSON.Container), nil@@ -1384,12 +1384,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 errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}stats, err := dockerClient.ContainerStats(ctx, containerID, client.ContainerStatsOptions{Stream: true})if err != nil {- return errors.WrapIf(err, "failed to start stats stream")+ return fmt.Errorf("failed to start stats stream: %w", err)}defer func() { _ = stats.Body.Close() }()@@ -1409,7 +1409,7 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,if errors.Is(err, io.EOF) {return nil}- return errors.WrapIf(err, "failed to decode stats")+ return fmt.Errorf("failed to decode stats: %w", err)}recordedAt := statsData.Read@@ -1954,7 +1954,7 @@ func (s *ContainerService) CalculateStatusCounts(items []containertypes.Summary)func (s *ContainerService) CreateExec(ctx context.Context, containerID string, cmd []string) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}execConfig := client.ExecCreateOptions{@@ -1967,7 +1967,7 @@ func (s *ContainerService) CreateExec(ctx context.Context, containerID string, cexecResp, err := dockerClient.ExecCreate(ctx, containerID, execConfig)if err != nil {- return "", errors.WrapIf(err, "failed to create exec")+ return "", fmt.Errorf("failed to create exec: %w", err)}return execResp.ID, nil@@ -2007,14 +2007,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}execAttach, err := dockerClient.ExecAttach(ctx, execID, client.ExecAttachOptions{TTY: true,})if err != nil {- return nil, errors.WrapIf(err, "failed to attach to exec")+ return nil, fmt.Errorf("failed to attach to exec: %w", err)}return &ExecSession{diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex 4864b32e3..b2ee20147 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -414,8 +414,9 @@ func TestApplyEditPreservesUnmanagedSettingsInternal(t *testing.T) {PortBindings: network.PortMap{network.MustParsePort("80/tcp"): {{HostPort: "8080"}}},Sysctls: map[string]string{"net.core.somaxconn": "1024"},LogConfig: container.LogConfig{Type: "json-file", Config: map[string]string{"max-size": "5m"}},++ Ulimits: []*container.Ulimit{{Name: "nofile", Soft: 1024, Hard: 2048}},}- hc.Ulimits = []*container.Ulimit{{Name: "nofile", Soft: 1024, Hard: 2048}}env := []string{"NEW=1"}req := containertypes.Edit{Environment: &env}diff --git a/backend/internal/dashboard/handler.go b/backend/internal/dashboard/handler.goindex a8d2b66ab..fe2f74500 100644--- a/backend/internal/dashboard/handler.go+++ b/backend/internal/dashboard/handler.go@@ -2,12 +2,11 @@ package dashboardimport ("context"- stderrors "errors"+ "errors""net/http""net/url""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -361,7 +360,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont}if len(errs) == attempted {- return nil, stderrors.Join(errs...)+ return nil, errors.Join(errs...)}return snapshot, nil}@@ -370,10 +369,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 := stderrors.AsType[*remenv.StatusError](err); ok && statusErr.StatusCode == http.StatusNotFound {+ if statusErr, ok := errors.AsType[*remenv.StatusError](err); ok && statusErr.StatusCode == http.StatusNotFound {return true}- _, ok := stderrors.AsType[*remenv.DecodeError](err)+ _, ok := errors.AsType[*remenv.DecodeError](err)return ok}@@ -385,7 +384,7 @@ func classifyDashboardStreamErrorInternal(err error) (string, string) {if isDashboardEndpointMissingInternal(err) {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 := stderrors.AsType[*remenv.TransportError](err); ok {+ if transportErr, ok := errors.AsType[*remenv.TransportError](err); ok {return transportErr.Error(), dashboardtypes.StreamErrorCodeUnreachable}return err.Error(), ""diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.goindex d1c3ed711..3dc972168 100644--- a/backend/internal/dashboard/service.go+++ b/backend/internal/dashboard/service.go@@ -2,12 +2,13 @@ package dashboardimport ("context"+ "errors"+ "fmt""sort""strconv""sync/atomic""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -418,7 +419,7 @@ func (s *DashboardService) getPendingContainerUpdatesCountInternal(ctx context.C}updates, err := s.imageService.GetUpdateInfoByContainers(ctx, containers)if err != nil {- return 0, errors.WrapIf(err, "failed to resolve pending container updates")+ return 0, fmt.Errorf("failed to resolve pending container updates: %w", err)}count := 0for _, info := range updates {@@ -436,7 +437,7 @@ func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Concount, err := s.projectService.CountProjectsWithPendingUpdates(ctx, allContainers)if err != nil {- return 0, errors.WrapIf(err, "failed to count projects with updates")+ return 0, fmt.Errorf("failed to count projects with updates: %w", err)}return count, nil@@ -462,7 +463,7 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)Where("expires_at <= ?", time.Now().Add(defaultDashboardAPIKeyExpiryWindow)).Count(&count).Errorif err != nil {- return 0, errors.WrapIf(err, "failed to count expiring API keys")+ return 0, fmt.Errorf("failed to count expiring API keys: %w", err)}return int(count), nildiff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex fbbdfd981..43a9a6ba1 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -3,6 +3,7 @@ package databaseimport ("context""database/sql"+ "errors""fmt""io/fs""log/slog"@@ -14,7 +15,6 @@ import ("strings""time"- "emperror.dev/errors"sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite""github.com/getarcaneapp/arcane/backend/v2/resources"dbtypes "github.com/getarcaneapp/arcane/types/v2/database"@@ -62,7 +62,7 @@ func SetGormLogger(l logger.Interface) {func Initialize(ctx context.Context, databaseURL string, options MigrationOptions) (database *DB, err error) {db, err := connectDatabaseInternal(ctx, databaseURL)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to database")+ return nil, fmt.Errorf("failed to connect to database: %w", err)}// Initialization opens a connection pool before it can fail on migrations or// provider detection; release it rather than leaking it into a failed startup.@@ -82,7 +82,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, errors.WrapIf(err, "failed to get sql.DB")+ return nil, fmt.Errorf("failed to get sql.DB: %w", err)}var dbProvider string@@ -92,12 +92,12 @@ func Initialize(ctx context.Context, databaseURL string, options MigrationOptioncase strings.HasPrefix(databaseURL, "postgres"):dbProvider = dbProviderPostgresdefault:- return nil, errors.Errorf("unsupported database type in URL: %s", databaseURL)+ return nil, fmt.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, errors.WrapIf(err, "failed to run migrations")+ return nil, fmt.Errorf("failed to run migrations: %w", err)}// Set connection pool settings@@ -120,20 +120,20 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, erroswitch {case strings.HasPrefix(databaseURL, "file:"):if err := sqliteutil.RegisterFunctions(); err != nil {- return nil, errors.WrapIf(err, "failed to register SQLite functions")+ return nil, fmt.Errorf("failed to register SQLite functions: %w", err)}connString, err := ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to parse SQLite connection string")+ return nil, fmt.Errorf("failed to parse SQLite connection string: %w", err)}if err := ensureSQLiteDirectoryInternal(connString); err != nil {- return nil, errors.WrapIf(err, "failed to prepare SQLite directory")+ return nil, fmt.Errorf("failed to prepare SQLite directory: %w", err)}dialector = sqlite.Open(connString)case strings.HasPrefix(databaseURL, "postgres"):dialector = postgres.Open(databaseURL)default:- return nil, errors.Errorf("unsupported database type in URL: %s", databaseURL)+ return nil, fmt.Errorf("unsupported database type in URL: %s", databaseURL)}// Retry connection up to 3 times@@ -173,7 +173,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 errors.WrapIff(err, "failed to determine target migration version for %s", dbProvider)+ return fmt.Errorf("failed to determine target migration version for %s: %w", dbProvider, err)}return migrateDatabaseToVersionInternal(ctx, db, dbProvider, options, requiredVersion)@@ -186,19 +186,19 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvideprovider, err := newGooseProviderInternal(db, dbProvider)if err != nil {- return errors.WrapIff(err, "failed to create goose provider for %s", dbProvider)+ return fmt.Errorf("failed to create goose provider for %s: %w", dbProvider, err)}currentVersion, err := provider.GetDBVersion(ctx)if err != nil {- return errors.WrapIff(err, "failed to determine current migration version for %s", dbProvider)+ return fmt.Errorf("failed to determine current migration version for %s: %w", dbProvider, err)}slog.Info("Resolved database migration state", "provider", dbProvider, "currentVersion", currentVersion, "requiredVersion", requiredVersion)if currentVersion > requiredVersion {if !options.AllowDowngrade {- 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)+ 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)}missingVersions, err := missingEmbeddedDowngradeMigrationsInternal(ctx, db, dbProvider, requiredVersion)@@ -206,11 +206,11 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvidereturn err}if len(missingVersions) > 0 {- 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)+ 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)}if _, err := provider.DownTo(ctx, requiredVersion); err != nil {- return errors.WrapIff(err, "failed to downgrade database from version %d to %d for %s using embedded Goose migrations", currentVersion, requiredVersion, dbProvider)+ return fmt.Errorf("failed to downgrade database from version %d to %d for %s using embedded Goose migrations: %w", currentVersion, requiredVersion, dbProvider, err)}slog.Info("Database downgrade completed successfully", "provider", dbProvider, "fromVersion", currentVersion, "toVersion", requiredVersion)@@ -223,7 +223,7 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvide}if _, err := provider.UpTo(ctx, requiredVersion); err != nil {- return errors.WrapIff(err, "failed to apply embedded Goose migrations for %s", dbProvider)+ return fmt.Errorf("failed to apply embedded Goose migrations for %s: %w", dbProvider, err)}slog.Info("Database migrations completed successfully", "provider", dbProvider, "targetVersion", requiredVersion)@@ -249,7 +249,7 @@ func newGooseProviderInternal(db *sql.DB, dbProvider string) (*goose.Provider, eif dialect == goose.DialectPostgres {sessionLocker, err := lock.NewPostgresSessionLocker()if err != nil {- return nil, errors.WrapIf(err, "failed to create Postgres migration session locker")+ return nil, fmt.Errorf("failed to create Postgres migration session locker: %w", err)}options = append(options, goose.WithSessionLocker(sessionLocker))}@@ -260,7 +260,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, errors.WrapIff(err, "failed to load embedded migrations for %s", dbProvider)+ return nil, fmt.Errorf("failed to load embedded migrations for %s: %w", dbProvider, err)}return migrationsFS, nil@@ -273,7 +273,7 @@ func gooseDialectInternal(dbProvider string) (goose.Dialect, error) {case dbProviderPostgres:return goose.DialectPostgres, nildefault:- return "", errors.Errorf("unsupported database provider: %s", dbProvider)+ return "", fmt.Errorf("unsupported database provider: %s", dbProvider)}}@@ -288,7 +288,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvidif legacyState.dirty {if !options.AllowDowngrade {- 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)+ 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)}if err := clearLegacyMigrationDirtyInternal(ctx, db, dbProvider, legacyState.version); err != nil {@@ -312,7 +312,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvidtx, err := db.BeginTx(ctx, nil)if err != nil {- return errors.WrapIff(err, "failed to start legacy migration adoption transaction for %s", dbProvider)+ return fmt.Errorf("failed to start legacy migration adoption transaction for %s: %w", dbProvider, err)}defer func() {_ = tx.Rollback()@@ -348,7 +348,7 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvid}if err := tx.Commit(); err != nil {- return errors.WrapIff(err, "failed to commit legacy migration adoption for %s", dbProvider)+ return fmt.Errorf("failed to commit legacy migration adoption for %s: %w", dbProvider, err)}slog.Info("Adopted legacy migration state into Goose", "provider", dbProvider, "legacyVersion", legacyState.version)@@ -375,7 +375,7 @@ func legacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvider streturn legacyMigrationState{}, false, nil}if err != nil {- return legacyMigrationState{}, false, errors.WrapIff(err, "failed to read legacy migration state for %s", dbProvider)+ return legacyMigrationState{}, false, fmt.Errorf("failed to read legacy migration state for %s: %w", dbProvider, err)}return state, true, nil@@ -386,17 +386,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, errors.WrapIf(err, "failed to check legacy migration table for sqlite")+ return false, fmt.Errorf("failed to check legacy migration table for sqlite: %w", err)}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, errors.WrapIf(err, "failed to check legacy migration table for postgres")+ return false, fmt.Errorf("failed to check legacy migration table for postgres: %w", err)}return exists, nildefault:- return false, errors.Errorf("unsupported database provider: %s", dbProvider)+ return false, fmt.Errorf("unsupported database provider: %s", dbProvider)}}@@ -407,7 +407,7 @@ func clearLegacyMigrationDirtyInternal(ctx context.Context, db *sql.DB, dbProvidreturn err}if _, err := db.ExecContext(ctx, query, args...); err != nil {- return errors.WrapIff(err, "failed to clear legacy dirty migration state for %s version %d", dbProvider, version)+ return fmt.Errorf("failed to clear legacy dirty migration state for %s version %d: %w", dbProvider, version, err)}return nil}@@ -421,7 +421,7 @@ func gooseVersionTableHasAppliedMigrationsInternal(ctx context.Context, db *sql.var version int64applied := kit.Ternary(dbProvider == dbProviderPostgres, "true", "1")if err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, applied)).Scan(&version); err != nil {- return false, errors.WrapIff(err, "failed to read Goose migration state for %s", dbProvider)+ return false, fmt.Errorf("failed to read Goose migration state for %s: %w", dbProvider, err)}return version > 0, nil}@@ -431,17 +431,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, errors.WrapIf(err, "failed to check Goose version table for sqlite")+ return false, fmt.Errorf("failed to check Goose version table for sqlite: %w", err)}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, errors.WrapIf(err, "failed to check Goose version table for postgres")+ return false, fmt.Errorf("failed to check Goose version table for postgres: %w", err)}return exists, nildefault:- return false, errors.Errorf("unsupported database provider: %s", dbProvider)+ return false, fmt.Errorf("unsupported database provider: %s", dbProvider)}}@@ -467,18 +467,18 @@ func createGooseVersionTableInternal(ctx context.Context, execer sqlExecerInterntstamp timestamp NOT NULL DEFAULT now())`, gooseVersionTable)default:- return errors.Errorf("unsupported database provider: %s", dbProvider)+ return fmt.Errorf("unsupported database provider: %s", dbProvider)}if _, err := execer.ExecContext(ctx, query); err != nil {- return errors.WrapIff(err, "failed to create Goose version table for %s", dbProvider)+ return fmt.Errorf("failed to create Goose version table for %s: %w", dbProvider, err)}return nil}func clearGooseVersionTableInternal(ctx context.Context, execer sqlExecerInternal, dbProvider string) error {if _, err := execer.ExecContext(ctx, "DELETE FROM "+gooseVersionTable); err != nil {- return errors.WrapIff(err, "failed to clear Goose version table for %s", dbProvider)+ return fmt.Errorf("failed to clear Goose version table for %s: %w", dbProvider, err)}return nil}@@ -487,14 +487,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 errors.WrapIff(err, "failed to insert Goose migration version %d for sqlite", version)+ return fmt.Errorf("failed to insert Goose migration version %d for sqlite: %w", version, err)}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 errors.WrapIff(err, "failed to insert Goose migration version %d for postgres", version)+ return fmt.Errorf("failed to insert Goose migration version %d for postgres: %w", version, err)}default:- return errors.Errorf("unsupported database provider: %s", dbProvider)+ return fmt.Errorf("unsupported database provider: %s", dbProvider)}return nil}@@ -506,7 +506,7 @@ func sqlWithProviderPlaceholderInternal(dbProvider, queryFormat string, arg any)case dbProviderPostgres:return fmt.Sprintf(queryFormat, "$1"), []any{arg}, nildefault:- return "", nil, errors.Errorf("unsupported database provider: %s", dbProvider)+ return "", nil, fmt.Errorf("unsupported database provider: %s", dbProvider)}}@@ -516,7 +516,7 @@ func getHighestEmbeddedMigrationVersionInternal(dbProvider string) (int64, errorreturn 0, err}if len(versions) == 0 {- return 0, errors.Errorf("no embedded migrations found for %s", dbProvider)+ return 0, fmt.Errorf("no embedded migrations found for %s", dbProvider)}return versions[len(versions)-1], nil@@ -525,7 +525,7 @@ func getHighestEmbeddedMigrationVersionInternal(dbProvider string) (int64, errorfunc getEmbeddedMigrationVersionsInternal(dbProvider string) ([]int64, error) {entries, err := resources.FS.ReadDir("migrations/" + dbProvider)if err != nil {- return nil, errors.WrapIff(err, "failed to read embedded migrations for %s", dbProvider)+ return nil, fmt.Errorf("failed to read embedded migrations for %s: %w", dbProvider, err)}versionsMap := make(map[int64]struct{})@@ -581,7 +581,7 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,rows, err := db.QueryContext(ctx, query, args...)if err != nil {- return nil, errors.WrapIff(err, "failed to read applied migration versions for %s", dbProvider)+ return nil, fmt.Errorf("failed to read applied migration versions for %s: %w", dbProvider, err)}defer func() {_ = rows.Close()@@ -591,14 +591,14 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,for rows.Next() {var version int64if err := rows.Scan(&version); err != nil {- return nil, errors.WrapIff(err, "failed to scan applied migration version for %s", dbProvider)+ return nil, fmt.Errorf("failed to scan applied migration version for %s: %w", dbProvider, err)}if _, ok := embeddedSet[version]; !ok {missing = append(missing, version)}}if err := rows.Err(); err != nil {- return nil, errors.WrapIff(err, "failed to iterate applied migration versions for %s", dbProvider)+ return nil, fmt.Errorf("failed to iterate applied migration versions for %s: %w", dbProvider, err)}return missing, nil@@ -611,7 +611,7 @@ func ParseSQLiteConnectionString(connString string, options dbtypes.SQLiteConnecconnStringUrl, err := url.Parse(connString)if err != nil {- return "", errors.WrapIf(err, "failed to parse SQLite connection string")+ return "", fmt.Errorf("failed to parse SQLite connection string: %w", err)}qs := make(url.Values, len(connStringUrl.Query()))@@ -712,7 +712,7 @@ func ensureSQLiteDirectoryInternal(connString string) error {}pathPart, err := kit.SQLitePathFromDSN(connString)if err != nil {- return errors.WrapIf(err, "failed to parse SQLite DSN")+ return fmt.Errorf("failed to parse SQLite DSN: %w", err)}if pathPart == "" || strings.HasPrefix(pathPart, ":memory:") {return nildiff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.goindex 3458fd8f3..aabe8311e 100644--- a/backend/internal/database/database_test.go+++ b/backend/internal/database/database_test.go@@ -718,10 +718,7 @@ func TestSQLiteMigrations_ColumnAddsAreReversible(t *testing.T) {continue}- assert.True(t, sectionHasSQLInternal(down),- "migration %s adds a column but its '-- +goose Down' has no SQL; add the reversing "+- "ALTER TABLE ... DROP COLUMN (modernc SQLite supports it). A no-op Down breaks "+- "down/up round-trips with a duplicate-column error.", entry.Name())+ assert.True(t, sectionHasSQLInternal(down), "migration %s adds a column but its '-- +goose Down' has no SQL; add the reversing ALTER TABLE ... DROP COLUMN (modernc SQLite supports it). A no-op Down breaks down/up round-trips with a duplicate-column error.", entry.Name())}}diff --git a/backend/internal/database/model.go b/backend/internal/database/model.goindex 32a99d404..fc4ac2c77 100644--- a/backend/internal/database/model.go+++ b/backend/internal/database/model.go@@ -3,10 +3,10 @@ package databaseimport ("database/sql/driver""encoding/json/v2"+ "fmt""time""uuid"- "emperror.dev/errors""gorm.io/gorm")@@ -53,7 +53,7 @@ func JSONScan[T any](dest *T, value any) error {case string:return json.Unmarshal([]byte(v), dest)default:- return errors.Errorf("unsupported scan type for %T: %T", *dest, value)+ return fmt.Errorf("unsupported scan type for %T: %T", *dest, value)}}diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex d6d943f05..c177ba331 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -5,7 +5,6 @@ import ("context""log/slog"- "emperror.dev/emperror""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/apns"@@ -49,7 +48,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/webhook"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/logging""github.com/getarcaneapp/arcane/backend/v2/resources""go.uber.org/fx")@@ -64,7 +62,6 @@ var ActorOptions = fx.Options(// ServiceOptions constructs services once and injects them into route modules.var ServiceOptions = fx.Options(fx.Supply(- fx.Annotate(new(logging.SlogErrorHandler), fx.As(new(emperror.ErrorHandler))),resources.FS,),fx.Provide(diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex 5ea358e9a..421af882c 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -2,12 +2,12 @@ package diimport ("context"+ "errors""log/slog""net/http""time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/auth"@@ -150,7 +150,7 @@ func provideDockerClientServiceInternal(ctx context.Context, lc fx.Lifecycle, dbreturn nil})if err != nil {- err = errors.Combine(err, stopLog(startCtx))+ err = errors.Join(err, stopLog(startCtx))cleanup()}return err@@ -161,7 +161,7 @@ func provideDockerClientServiceInternal(ctx context.Context, lc fx.Lifecycle, dberr = stopStream(stopCtx)}if stopLog != nil {- err = errors.Combine(err, stopLog(stopCtx))+ err = errors.Join(err, stopLog(stopCtx))}if unsubscribe != nil {unsubscribe()@@ -298,7 +298,7 @@ func provideFilesystemWatcherJobInternal(ctx context.Context, lc fx.Lifecycle, pif stop != nil {err = stop(stopCtx)}- return errors.Combine(err, job.Stop(stopCtx))+ return errors.Join(err, job.Stop(stopCtx))},})return job, nildiff --git a/backend/internal/diagnostics/service.go b/backend/internal/diagnostics/service.goindex f17cecd35..ec1ec6797 100644--- a/backend/internal/diagnostics/service.go+++ b/backend/internal/diagnostics/service.go@@ -2,13 +2,14 @@ package diagnosticsimport ("bytes"+ "errors"+ "fmt""runtime""runtime/debug""runtime/pprof""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/types/v2/system")@@ -116,7 +117,7 @@ func (s *DiagnosticsService) ScanGoroutineLeaks() (system.GoroutineLeakReport, evar buf bytes.Bufferif err := p.WriteTo(&buf, 1); err != nil {- return system.GoroutineLeakReport{}, errors.WrapIf(err, "write goroutineleak profile")+ return system.GoroutineLeakReport{}, fmt.Errorf("write goroutineleak profile: %w", err)}now := time.Now().UTC()diff --git a/backend/internal/docker/service.go b/backend/internal/docker/service.goindex d4f112e8a..bece18286 100644--- a/backend/internal/docker/service.go+++ b/backend/internal/docker/service.go@@ -2,13 +2,14 @@ package dockerimport ("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"@@ -99,7 +100,7 @@ func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, eclient.WithHost(host),)if err != nil {- return "", errors.WrapIf(err, "failed to create Docker probe client")+ return "", fmt.Errorf("failed to create Docker probe client: %w", err)}defer closeDockerClientInternal(probeClient, "failed to close probe Docker client")@@ -108,7 +109,7 @@ func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, epingResult, err := probeClient.Ping(ctx, client.PingOptions{})if err != nil {- return "", errors.WrapIf(err, "failed to negotiate Docker API version")+ return "", fmt.Errorf("failed to negotiate Docker API version: %w", err)}apiVersion := strings.TrimSpace(pingResult.APIVersion)@@ -126,7 +127,7 @@ func newDockerClientWithAPIVersionInternal(host, apiVersion string) (*client.Cliclient.WithAPIVersion(apiVersion),)if err != nil {- return nil, errors.WrapIff(err, "failed to configure Docker client API version %s", apiVersion)+ return nil, fmt.Errorf("failed to configure Docker client API version %s: %w", apiVersion, err)}return configuredClient, nil@@ -155,7 +156,7 @@ func (s *DockerClientService) GetClient(ctx context.Context) (*client.Client, ercli, err := newDockerClientInternal(ctx, s.config.DockerHost)if err != nil {- return nil, errors.WrapIf(err, "failed to create Docker client")+ return nil, fmt.Errorf("failed to create Docker client: %w", err)}s.mu.Lock()@@ -179,7 +180,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 errors.WrapIf(err, "failed to refresh Docker client")+ return fmt.Errorf("failed to refresh Docker client: %w", err)}s.mu.Lock()@@ -192,7 +193,7 @@ func (s *DockerClientService) RefreshClient(ctx context.Context) error {cli, err := newDockerClientWithAPIVersionInternal(s.config.DockerHost, apiVersion)if err != nil {- return errors.WrapIf(err, "failed to refresh Docker client")+ return fmt.Errorf("failed to refresh Docker client: %w", err)}s.mu.Lock()@@ -350,7 +351,7 @@ func (s *DockerClientService) ListContainers(ctx context.Context) ([]container.Sreturn listCoalescedInternal(ctx, &s.containerListFlight, func(ctx context.Context) ([]container.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}apiCtx, cancel := context.WithTimeout(ctx, s.apiTimeoutInternal())@@ -358,7 +359,7 @@ func (s *DockerClientService) ListContainers(ctx context.Context) ([]container.ScontainerList, err := dockerClient.ContainerList(apiCtx, client.ContainerListOptions{All: true})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker containers")+ return nil, fmt.Errorf("failed to list Docker containers: %w", err)}return containerList.Items, nil})@@ -368,7 +369,7 @@ func (s *DockerClientService) ListImages(ctx context.Context) ([]image.Summary,return listCoalescedInternal(ctx, &s.imageListFlight, func(ctx context.Context) ([]image.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}apiCtx, cancel := context.WithTimeout(ctx, s.apiTimeoutInternal())@@ -376,7 +377,7 @@ func (s *DockerClientService) ListImages(ctx context.Context) ([]image.Summary,imageList, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{All: true})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker images")+ return nil, fmt.Errorf("failed to list Docker images: %w", err)}return imageList.Items, nil})@@ -385,7 +386,7 @@ func (s *DockerClientService) ListImages(ctx context.Context) ([]image.Summary,func (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]network.Summary, error) {dockerClient, err := s.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}apiCtx, cancel := context.WithTimeout(ctx, s.apiTimeoutInternal())@@ -393,7 +394,7 @@ func (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]netwonetworkList, err := compat.NetworkListWithCompatibility(apiCtx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker networks")+ return nil, fmt.Errorf("failed to list Docker networks: %w", err)}return networkList.Items, nil}@@ -401,7 +402,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}apiCtx, cancel := context.WithTimeout(ctx, s.apiTimeoutInternal())@@ -409,7 +410,7 @@ func (s *DockerClientService) listVolumesInternal(ctx context.Context) (*client.volResp, err := dockerClient.VolumeList(apiCtx, client.VolumeListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker volumes")+ return nil, fmt.Errorf("failed to list Docker volumes: %w", err)}return &volResp, nil}diff --git a/backend/internal/environment/edge_mtls_handler.go b/backend/internal/environment/edge_mtls_handler.goindex df7de89d2..75bd66afd 100644--- a/backend/internal/environment/edge_mtls_handler.go+++ b/backend/internal/environment/edge_mtls_handler.go@@ -3,12 +3,13 @@ package environmentimport ("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"@@ -30,12 +31,12 @@ func generatedEdgeMTLSClientCertPathInternal(cfg *config.Config, envID string) (certPath, err := edge.GeneratedManagerClientMTLSCertPath(edgeCfg, envID)if err != nil {- return "", errors.WrapIf(err, "resolve generated edge mTLS client certificate path")+ return "", fmt.Errorf("resolve generated edge mTLS client certificate path: %w", err)}// os.* rather than acfs: the assets dir may be user-configured to anywhere// on the host, so no confinement root exists for this path.if _, err := os.Stat(certPath); err != nil {- return "", errors.WrapIf(err, "stat generated edge mTLS client certificate")+ return "", fmt.Errorf("stat generated edge mTLS client certificate: %w", err)}return certPath, nil@@ -51,7 +52,7 @@ func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID stri// on the host, so no confinement root exists for this path.certPEM, err := os.ReadFile(certPath)if err != nil {- return nil, errors.WrapIf(err, "read generated edge mTLS client certificate")+ return nil, fmt.Errorf("read generated edge mTLS client certificate: %w", err)}block, _ := pem.Decode(certPEM)@@ -61,7 +62,7 @@ func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID stricert, err := x509.ParseCertificate(block.Bytes)if err != nil {- return nil, errors.WrapIf(err, "parse generated edge mTLS client certificate")+ return nil, fmt.Errorf("parse generated edge mTLS client certificate: %w", err)}expiresAt := cert.NotAfter.UTC()diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.goindex 8b131206d..ee43a132e 100644--- a/backend/internal/environment/environment.go+++ b/backend/internal/environment/environment.go@@ -2,6 +2,7 @@ package environmentimport ("context"+ "errors""fmt""log/slog""net/http"@@ -9,7 +10,6 @@ import ("time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -27,6 +27,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/samber/hot""go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -63,14 +64,20 @@ type EnvironmentService struct {}const (+ // LocalEnvironmentID is the reserved ID of the environment Arcane manages directly.+ LocalEnvironmentID = "0"+ localEnvironmentFallbackNameInternal = "Local"+// SyncDeliveryExpiry bounds how long an accepted config push is trusted. An// agent rebuilt with a fresh data volume while its status stayed online gets// everything again within this window without operator action.SyncDeliveryExpiry = time.Hour+)- ErrEnvironmentAccessTokenRequired = errors.Sentinel("environment access token required")- ErrInvalidEnvironmentAccessToken = errors.Sentinel("invalid environment access token")- ErrEnvironmentNotFound = errors.Sentinel("environment not found")+var (+ ErrEnvironmentAccessTokenRequired = errors.New("environment access token required")+ ErrInvalidEnvironmentAccessToken = errors.New("invalid environment access token")+ ErrEnvironmentNotFound = errors.New("environment not found"))// VariableSyncer pushes the effective global-variable set to one environment.@@ -138,7 +145,7 @@ func (s *EnvironmentService) ResolveEdgeEnvironmentByToken(ctx context.Context,s.logEdgeTokenResolveMissInternal(ctx, token)return "", errors.New("invalid agent token")}- return "", errors.WrapIf(err, "failed to resolve edge environment by token")+ return "", fmt.Errorf("failed to resolve edge environment by token: %w", err)}s.edgeTokens.put(env.ID, token)@@ -206,7 +213,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 errors.WrapIf(err, "failed to update local environment api url")+ return fmt.Errorf("failed to update local environment api url: %w", err)}s.invalidateEnvironmentCacheInternal(LocalEnvironmentID)slog.InfoContext(ctx, "updated local environment api url", "id", LocalEnvironmentID, "url", appUrl)@@ -215,7 +222,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl}if !errors.Is(err, gorm.ErrRecordNotFound) {- return errors.WrapIf(err, "failed to check for local environment")+ return fmt.Errorf("failed to check for local environment: %w", err)}// Create the local environment@@ -231,7 +238,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl}if err := s.db.WithContext(ctx).Create(localEnv).Error; err != nil {- return errors.WrapIf(err, "failed to create local environment")+ return fmt.Errorf("failed to create local environment: %w", err)}slog.InfoContext(ctx, "created local environment record", "id", LocalEnvironmentID)@@ -254,7 +261,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, errors.WrapIf(err, "failed to create environment")+ return nil, fmt.Errorf("failed to create environment: %w", err)}// Create event in background@@ -276,7 +283,7 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrEnvironmentNotFound}- return nil, errors.WrapIf(err, "failed to get environment")+ return nil, fmt.Errorf("failed to get environment: %w", err)}return &envRecord, nil}@@ -317,7 +324,7 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, uupdates["updated_at"] = new(time.Now())if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return nil, errors.WrapIf(err, "failed to update environment")+ return nil, fmt.Errorf("failed to update environment: %w", err)}s.invalidateEnvironmentCacheInternal(id)s.NotifyRuntimeStateChanged()@@ -367,24 +374,22 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, uif err := tx.Table("gitops_syncs").Where("environment_id = ?", id).Pluck("id", &syncIDs).Error; err != nil {- return errors.WrapIf(err, "failed to list environment gitops syncs")+ return fmt.Errorf("failed to list environment gitops syncs: %w", err)}if len(syncIDs) > 0 {if err := tx.Table("projects").Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {- return errors.WrapIf(err, "failed to clear environment gitops project references")+ return fmt.Errorf("failed to clear environment gitops project references: %w", err)}if err := tx.Exec("DELETE FROM gitops_syncs WHERE environment_id = ?", id).Error; err != nil {- return errors.WrapIf(err, "failed to delete environment gitops syncs")+ return fmt.Errorf("failed to delete environment gitops syncs: %w", err)}}-if err := tx.Delete(&Environment{}, "id = ?", id).Error; err != nil {- return errors.WrapIf(err, "failed to delete environment")+ return fmt.Errorf("failed to delete environment: %w", err)}-return nil}); err != nil {if env.Enabled {@@ -449,7 +454,7 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, enresult := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", envID).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update environment with new API key")+ return fmt.Errorf("failed to update environment with new API key: %w", result.Error)}if result.RowsAffected == 0 {// A zero-row update would otherwise report a successful rotation while@@ -492,7 +497,7 @@ func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Contextif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrInvalidEnvironmentAccessToken}- return nil, errors.WrapIf(err, "failed to resolve environment by access token")+ return nil, fmt.Errorf("failed to resolve environment by access token: %w", err)}return &env, nil@@ -501,7 +506,7 @@ func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Contextfunc (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context) ([]containerregistry.Credential, error) {var registries []registry.ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get enabled container registries")+ return nil, fmt.Errorf("failed to get enabled container registries: %w", err)}var creds []containerregistry.Credential@@ -566,3 +571,12 @@ func (s *EnvironmentService) SyncResourcesToEnvironment(ctx context.Context, envreturn nil})}++// DisplayName returns the stored environment name or its readable fallback.+func DisplayName(environmentID, storedName string) string {+ if name := strings.TrimSpace(storedName); name != "" {+ return name+ }+ id := strings.TrimSpace(environmentID)+ return kit.Ternary(id == "" || id == LocalEnvironmentID, localEnvironmentFallbackNameInternal, id)+}diff --git a/backend/internal/environment/environment_caches.go b/backend/internal/environment/environment_caches.goindex eb128c34b..5f5ff0c2a 100644--- a/backend/internal/environment/environment_caches.go+++ b/backend/internal/environment/environment_caches.go@@ -3,12 +3,12 @@ package environmentimport ("cmp""context"+ "errors""slices""strings""sync""time"- "emperror.dev/errors""github.com/samber/hot""github.com/samber/mo")diff --git a/backend/internal/environment/environment_health.go b/backend/internal/environment/environment_health.goindex af34a6ebe..848ce192a 100644--- a/backend/internal/environment/environment_health.go+++ b/backend/internal/environment/environment_health.go@@ -2,11 +2,12 @@ package environmentimport ("context"+ "errors"+ "fmt""log/slog""net/http""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"@@ -57,7 +58,7 @@ func (s *EnvironmentService) ListEnabledEnvironmentIDs(ctx context.Context) ([]sTable("environments").Where("enabled = ?", true).Pluck("id", &ids).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list enabled environments")+ return nil, fmt.Errorf("failed to list enabled environments: %w", err)}return ids, nil}@@ -182,7 +183,7 @@ func (s *EnvironmentService) runHealthCheckInternal(ctx context.Context, envID ssyncErrors = append(syncErrors, err)}}- if err := errors.Combine(syncErrors...); err != nil {+ if err := errors.Join(syncErrors...); err != nil {return schedulertypes.Outcome{Status: schedulertypes.Partial}, err}return schedulertypes.Outcome{Status: schedulertypes.Succeeded}, nil@@ -221,7 +222,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}- return connectionFailure("offline", errors.WrapIf(err, "invalid environment API URL"))+ return connectionFailure("offline", fmt.Errorf("invalid environment API URL: %w", err))}reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)@@ -231,14 +232,14 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}- return connectionFailure("offline", errors.WrapIf(err, "failed to create request"))+ return connectionFailure("offline", fmt.Errorf("failed to create request: %w", err))}resp, err := s.httpClient.Do(req)if err != nil {if customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}- return connectionFailure("offline", errors.WrapIf(err, "connection failed"))+ return connectionFailure("offline", fmt.Errorf("connection failed: %w", err))}defer func() { _ = resp.Body.Close() }()@@ -252,7 +253,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif customApiUrl == nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusError))}- return connectionFailure("error", errors.Errorf("unexpected status code: %d", resp.StatusCode))+ return connectionFailure("error", fmt.Errorf("unexpected status code: %d", resp.StatusCode))}// testEdgeConnection tests connection to an edge agent via its tunnel@@ -274,7 +275,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(EnvironmentStatusOffline))- return "offline", errors.WrapIf(err, "health check via tunnel failed")+ return "offline", fmt.Errorf("health check via tunnel failed: %w", err)}if statusCode == http.StatusOK {@@ -283,7 +284,7 @@ func (s *EnvironmentService) testEdgeConnection(ctx context.Context, id string)}_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusError))- return "error", errors.Errorf("unexpected status code: %d", statusCode)+ return "error", fmt.Errorf("unexpected status code: %d", statusCode)}func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id string) (string, error) {@@ -294,13 +295,13 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id sdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))- return "offline", errors.WrapIf(err, "failed to connect to Docker")+ return "offline", fmt.Errorf("failed to connect to Docker: %w", err)}_, err = dockerClient.Ping(reqCtx, client.PingOptions{})if err != nil {_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))- return "offline", errors.WrapIf(err, "docker ping failed")+ return "offline", fmt.Errorf("docker ping failed: %w", err)}_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOnline))@@ -310,7 +311,7 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id sfunc (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {var currentEnv Environmentif err := s.db.WithContext(ctx).Select("status", "is_edge").Where("id = ?", id).First(¤tEnv).Error; err != nil {- return errors.WrapIf(err, "failed to check environment status")+ return fmt.Errorf("failed to check environment status: %w", err)}if currentEnv.Status == string(EnvironmentStatusPending) {@@ -333,7 +334,7 @@ func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context"updated_at": &now,}if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return errors.WrapIf(err, "failed to update environment status")+ return fmt.Errorf("failed to update environment status: %w", err)}// Direct environments have no tunnel callback, so this health-check write is// the only moment their liveness changes.@@ -354,11 +355,11 @@ func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id`, new(now), string(EnvironmentStatusOnline), new(now), id, now.Add(-30*time.Second))if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update environment heartbeat")+ // The 30s throttle above doubles as the notify throttle: a no-op heartbeat+ // changed nothing worth waking a stream for.+ return fmt.Errorf("failed to update environment heartbeat: %w", result.Error)}- // The 30s throttle above doubles as the notify throttle: a no-op heartbeat- // changed nothing worth waking a stream for.if result.RowsAffected > 0 {s.NotifyRuntimeStateChanged()}@@ -387,7 +388,7 @@ func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Contex}if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {- return errors.WrapIf(err, "failed to update environment connection state")+ return fmt.Errorf("failed to update environment connection state: %w", err)}s.NotifyRuntimeStateChanged()@@ -466,7 +467,7 @@ func (s *EnvironmentService) ReconcileEdgeStatusesOnStartup(ctx context.Context)"updated_at": new(time.Now()),})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to reconcile edge environment statuses")+ return fmt.Errorf("failed to reconcile edge environment statuses: %w", result.Error)}if result.RowsAffected > 0 {diff --git a/backend/internal/environment/environment_listing.go b/backend/internal/environment/environment_listing.goindex ceed35565..0685daebc 100644--- a/backend/internal/environment/environment_listing.go+++ b/backend/internal/environment/environment_listing.go@@ -2,9 +2,9 @@ package environmentimport ("context"+ "fmt""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/environment"@@ -43,12 +43,12 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parapaginationResp, err := pagination.PaginateAndSortDB(params, q, &envs)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate environments")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate environments: %w", err)}out, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {- return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")+ return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)}return out, paginationResp, nil@@ -77,12 +77,12 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternalModel(&Environment{}).Where("hidden = ?", false).Find(&envs).Error; err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list environments")+ return nil, pagination.Response{}, fmt.Errorf("failed to list environments: %w", err)}items, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {- return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")+ return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)}// nil = no restriction; non-nil restricts to the caller's accessible envs.@@ -195,12 +195,12 @@ func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]envWhere("hidden = ?", false).Order("created_at asc, id asc").Find(&envs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list visible environments")+ return nil, fmt.Errorf("failed to list visible environments: %w", err)}out, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {- return nil, errors.WrapIf(mapErr, "failed to map environments")+ return nil, fmt.Errorf("failed to map environments: %w", mapErr)}return out, nil@@ -235,7 +235,7 @@ func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]EnviWhere("hidden = ?", false).Find(&envs).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to list remote environments")+ return nil, fmt.Errorf("failed to list remote environments: %w", err)}s.remoteEnvs.mu.Lock()diff --git a/backend/internal/environment/environment_proxy.go b/backend/internal/environment/environment_proxy.goindex 2906359b1..95eebb289 100644--- a/backend/internal/environment/environment_proxy.go+++ b/backend/internal/environment/environment_proxy.go@@ -3,6 +3,7 @@ package environmentimport ("context""encoding/json/v2"+ "errors""fmt""log/slog""maps"@@ -11,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -32,7 +32,7 @@ import (func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Context) error {envs, err := s.ListRemoteEnvironments(ctx)if err != nil {- return errors.WrapIf(err, "failed to list remote environments for registry sync")+ return fmt.Errorf("failed to list remote environments for registry sync: %w", err)}if len(envs) == 0 {@@ -58,7 +58,7 @@ func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Cont}if failedCount > 0 {- return errors.Errorf("failed to sync registries to %d remote environment(s)", failedCount)+ return fmt.Errorf("failed to sync registries to %d remote environment(s)", failedCount)}return nil@@ -68,7 +68,7 @@ func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Contfunc (s *EnvironmentService) SyncS3DestinationsToRemoteEnvironments(ctx context.Context) error {envs, err := s.ListRemoteEnvironments(ctx)if err != nil {- return errors.WrapIf(err, "failed to list remote environments for S3 destination sync")+ return fmt.Errorf("failed to list remote environments for S3 destination sync: %w", err)}var failedCount int@@ -84,7 +84,7 @@ func (s *EnvironmentService) SyncS3DestinationsToRemoteEnvironments(ctx context.}if failedCount > 0 {- return errors.Errorf("failed to sync S3 destinations to %d remote environment(s)", failedCount)+ return fmt.Errorf("failed to sync S3 destinations to %d remote environment(s)", failedCount)}return nil}@@ -96,7 +96,7 @@ func (s *EnvironmentService) SyncS3DestinationsToRemoteEnvironments(ctx context.func (s *EnvironmentService) CheckS3DestinationReferences(ctx context.Context, destinationID string) error {envs, err := s.ListRemoteEnvironments(ctx)if err != nil {- return errors.WrapIf(err, "failed to list remote environments for S3 destination reference check")+ return fmt.Errorf("failed to list remote environments for S3 destination reference check: %w", err)}for _, env := range envs {if env.AccessToken == nil || strings.TrimSpace(*env.AccessToken) == "" {@@ -108,10 +108,10 @@ func (s *EnvironmentService) CheckS3DestinationReferences(ctx context.Context, dInUse bool `json:"inUse"`}if err := s.ProxyJSONRequestForEnvironment(ctx, env, http.MethodGet, "/api/backups/s3/"+url.PathEscape(destinationID)+"/in-use", nil, &result); err != nil {- return errors.WrapIff(err, "cannot verify S3 destination references on environment %s; restore connectivity before deleting", env.Name)+ return fmt.Errorf("cannot verify S3 destination references on environment %s; restore connectivity before deleting: %w", env.Name, err)}if result.InUse {- return errors.Errorf("still referenced by environment %s", env.Name)+ return fmt.Errorf("still referenced by environment %s", env.Name)}}return nil@@ -128,7 +128,7 @@ type remoteEnvironmentTargetInternal struct {func (s *EnvironmentService) resolveRemoteEnvironmentTargetInternal(ctx context.Context, envID string) (*remoteEnvironmentTargetInternal, error) {envRecord, err := s.GetEnvironmentByID(ctx, envID)if err != nil {- return nil, errors.WrapIf(err, "failed to get environment")+ return nil, fmt.Errorf("failed to get environment: %w", err)}return s.remoteEnvironmentTargetFromModelInternal(*envRecord)@@ -143,7 +143,7 @@ func (s *EnvironmentService) remoteEnvironmentTargetFromModelInternal(environmenif !environment.IsEdge {validatedTargetURL, err := httputils.NormalizeBaseURL(environment.ApiUrl)if err != nil {- return nil, errors.WrapIf(err, "invalid environment API URL")+ return nil, fmt.Errorf("invalid environment API URL: %w", err)}targetURL = validatedTargetURL}@@ -233,7 +233,7 @@ func (s *EnvironmentService) executeRemoteRequestForTargetInternal(resp, err := s.remoteClient.Do(ctx, request)if err != nil {- return nil, errors.WrapIff(err, "failed to send request to environment %s", target.Name)+ return nil, fmt.Errorf("failed to send request to environment %s: %w", target.Name, err)}return resp, nil@@ -314,18 +314,18 @@ func doRemoteEnvironmentTunnelRequestInternal() (*remenv.Response, error) {tunnel, ok := edge.GetRegistry().Get(envID).Get()if !ok {- return nil, errors.WrapIff(remenv.ErrEnvironmentUnavailable, "no active tunnel for environment %s", envID)+ return nil, fmt.Errorf("no active tunnel for environment %s: %w", envID, remenv.ErrEnvironmentUnavailable)}if tunnel.Conn.IsClosed() {- return nil, errors.WrapIff(remenv.ErrEnvironmentUnavailable, "tunnel for environment %s is closed", envID)+ return nil, fmt.Errorf("tunnel for environment %s is closed: %w", envID, remenv.ErrEnvironmentUnavailable)}statusCode, respHeaders, respBody, err := edge.ProxyRequest(ctx, tunnel, method, path, "", headers, body)if err != nil {if errors.Is(err, edge.ErrTunnelConnectionClosed) {- err = errors.Combine(remenv.ErrEnvironmentUnavailable, err)+ err = errors.Join(remenv.ErrEnvironmentUnavailable, err)}- return nil, errors.WrapIf(err, "tunnel request failed")+ return nil, fmt.Errorf("tunnel request failed: %w", err)}return &remenv.Response{@@ -341,7 +341,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, enfunc(reg registry.ContainerRegistry) (containerregistry.Sync, bool, error) {registryType, typeErr := registry.NormalizeRegistryType(reg.RegistryType)if typeErr != nil {- return containerregistry.Sync{}, false, errors.WrapIff(typeErr, "normalize registry type for sync %s", reg.ID)+ return containerregistry.Sync{}, false, fmt.Errorf("normalize registry type for sync %s: %w", reg.ID, typeErr)}syncItem := containerregistry.Sync{@@ -389,7 +389,7 @@ func (s *EnvironmentService) SyncS3DestinationsToEnvironment(ctx context.Contextfunc(destination s3domain.S3Destination) (backuptypes.S3DestinationSync, bool, error) {secret, err := crypto.Decrypt(destination.SecretAccessKey)if err != nil {- return backuptypes.S3DestinationSync{}, false, errors.WrapIff(err, "failed to decrypt S3 destination %s for sync", destination.ID)+ return backuptypes.S3DestinationSync{}, false, fmt.Errorf("failed to decrypt S3 destination %s for sync: %w", destination.ID, err)}return destination.ToSync(secret), true, nil},@@ -479,7 +479,7 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](var records []Modelif err := s.db.WithContext(ctx).Find(&records).Error; err != nil {- return errors.WrapIff(err, "failed to get %s", kind)+ return fmt.Errorf("failed to get %s: %w", kind, err)}syncItems := make([]Item, 0, len(records))@@ -495,11 +495,11 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](reqBody, err := json.Marshal(wrap(syncItems))if err != nil {- return errors.WrapIf(err, "failed to marshal sync request")+ return fmt.Errorf("failed to marshal sync request: %w", err)}unchanged, finishDelivery, err := s.syncGate.Begin(ctx, environmentID, path, reqBody)if err != nil {- return errors.WrapIf(err, "sync cancelled while waiting for an in-flight delivery")+ return fmt.Errorf("sync cancelled while waiting for an in-flight delivery: %w", err)}if unchanged {slog.DebugContext(ctx, "Skipping sync; payload unchanged since last delivery", "kind", kind, "environmentID", environmentID, "environmentName", target.Name)@@ -522,11 +522,11 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](} `json:"data"`}if err := s.proxyJSONRequestForTargetInternal(reqCtx, target, http.MethodPost, path, reqBody, &result); err != nil {- return errors.WrapIf(err, "failed to send sync request")+ return fmt.Errorf("failed to send sync request: %w", err)}if !result.Success {- return errors.Errorf("sync failed: %s", result.Data.Message)+ return fmt.Errorf("sync failed: %s", result.Data.Message)}delivered = truediff --git a/backend/internal/environment/environment_swarm_nodes.go b/backend/internal/environment/environment_swarm_nodes.goindex 8411476bf..9456e88ca 100644--- a/backend/internal/environment/environment_swarm_nodes.go+++ b/backend/internal/environment/environment_swarm_nodes.go@@ -2,11 +2,12 @@ package environmentimport ("context"+ "errors"+ "fmt""log/slog""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""gorm.io/gorm")@@ -17,9 +18,8 @@ func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context,Model(&Environment{}).Where("parent_environment_id = ?", parentEnvironmentID).Find(&envs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list swarm node agent environments")+ return nil, fmt.Errorf("failed to list swarm node agent environments: %w", err)}-return envs, nil}@@ -34,9 +34,8 @@ func (s *EnvironmentService) ListSwarmNodeCandidateEnvironments(ctx context.ContWhere("id <> ?", "0").Order("name ASC").Find(&envs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list swarm node candidate environments")+ return nil, fmt.Errorf("failed to list swarm node candidate environments: %w", err)}-return envs, nil}@@ -50,7 +49,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(var envRecord Environmenterr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Where("id = ?", environmentID).First(&envRecord).Error; err != nil {- return errors.WrapIf(err, "failed to load environment for swarm node binding")+ return fmt.Errorf("failed to load environment for swarm node binding: %w", err)}if envRecord.Hidden {return errors.New("dedicated agent environments cannot be attached as visible environments")@@ -69,7 +68,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(if err := tx.Model(&Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).Count(&existingVisibleBindings).Error; err != nil {- return errors.WrapIf(err, "failed to inspect existing swarm node binding")+ return fmt.Errorf("failed to inspect existing swarm node binding: %w", err)}if existingVisibleBindings > 0 && !rebind {return errors.New("swarm node already has a visible environment binding; explicit rebinding is required")@@ -78,7 +77,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(if err := tx.Model(&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 errors.WrapIf(err, "failed to clear previous swarm node binding")+ return fmt.Errorf("failed to clear previous swarm node binding: %w", err)}}@@ -87,7 +86,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment("swarm_node_id": nodeID,"updated_at": new(time.Now()),}).Error; err != nil {- return errors.WrapIf(err, "failed to bind environment to swarm node")+ return fmt.Errorf("failed to bind environment to swarm node: %w", err)}return tx.Where("id = ?", environmentID).First(&envRecord).Error@@ -108,7 +107,7 @@ func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, parif err := s.db.WithContext(ctx).Model(&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 errors.WrapIf(err, "failed to detach swarm node environment")+ return fmt.Errorf("failed to detach swarm node environment: %w", err)}s.NotifyRuntimeStateChanged()@@ -125,7 +124,7 @@ func (s *EnvironmentService) DeleteSwarmNodeAgentDeployment(ctx context.Context,if errors.Is(err, gorm.ErrRecordNotFound) {return nil}- return errors.WrapIf(err, "failed to load swarm node agent deployment")+ return fmt.Errorf("failed to load swarm node agent deployment: %w", err)}return s.DeleteEnvironment(ctx, envRecord.ID, userID, username)@@ -172,7 +171,7 @@ func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(apiKeyDto, err := s.apiKeyService.CreateEnvironmentApiKey(ctx, env.ID)if err != nil {- return "", errors.WrapIf(err, "failed to create environment API key")+ return "", fmt.Errorf("failed to create environment API key: %w", err)}if err := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); err != nil {@@ -220,7 +219,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(Order("hidden ASC").First(&env).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, "", errors.WrapIf(err, "failed to load swarm node agent environment")+ return nil, "", fmt.Errorf("failed to load swarm node agent environment: %w", err)}if errors.Is(err, gorm.ErrRecordNotFound) {@@ -236,7 +235,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(}if _, createErr := s.CreateEnvironment(ctx, createdEnv, new(userID), new(username)); createErr != nil {- return nil, "", errors.WrapIf(createErr, "failed to create swarm node agent environment")+ return nil, "", fmt.Errorf("failed to create swarm node agent environment: %w", createErr)}env = *createdEnv}@@ -248,7 +247,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(refreshedEnv, err := s.GetEnvironmentByID(ctx, env.ID)if err != nil {- return nil, "", errors.WrapIf(err, "failed to refresh swarm node agent environment")+ return nil, "", fmt.Errorf("failed to refresh swarm node agent environment: %w", err)}return refreshedEnv, apiKey, nil@@ -261,7 +260,7 @@ func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID,}if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {- return errors.WrapIf(err, "failed to update swarm node identity")+ return fmt.Errorf("failed to update swarm node identity: %w", err)}s.NotifyRuntimeStateChanged()diff --git a/backend/internal/environment/environment_sync_test.go b/backend/internal/environment/environment_sync_test.goindex 46065f6c3..915004350 100644--- a/backend/internal/environment/environment_sync_test.go+++ b/backend/internal/environment/environment_sync_test.go@@ -75,7 +75,7 @@ func TestSyncResourcesToEnvironmentOutcomes(t *testing.T) {}}))defer server.Close()- require.NoError(t, db.Create(&environment.Environment{BaseModel: database.BaseModel{ID: "remote"}, Name: "Remote", ApiUrl: server.URL, AccessToken: new("agent-token"), Enabled: true}).Error)+ require.NoError(t, db.Create(&environment.Environment{ID: "remote", Name: "Remote", ApiUrl: server.URL, AccessToken: new("agent-token"), Enabled: true}).Error)service := environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)activityService := activity.NewActivityService(db, nil)id, err := service.SyncResourcesToEnvironment(t.Context(), "remote", &common.User{ID: "operator", Username: "operator"}, activityService)@@ -116,12 +116,12 @@ func TestSyncCredentialDecryptionAbortsSnapshot(t *testing.T) {_, _ = w.Write([]byte(`{"success":true}`))}))defer server.Close()- require.NoError(t, db.Create(&environment.Environment{BaseModel: database.BaseModel{ID: "remote"}, ApiUrl: server.URL, AccessToken: new("agent-token")}).Error)+ require.NoError(t, db.Create(&environment.Environment{ID: "remote", ApiUrl: server.URL, AccessToken: new("agent-token")}).Error)service := environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)var syncResource func(context.Context, string) errorswitch kind {case "registry token", "ECR secret":- row := registry.ContainerRegistry{BaseModel: database.BaseModel{ID: "bad-credential"}, URL: "registry.example.com", RegistryType: registry.RegistryTypeGeneric, Token: "invalid-ciphertext"}+ row := registry.ContainerRegistry{ID: "bad-credential", URL: "registry.example.com", RegistryType: registry.RegistryTypeGeneric, Token: "invalid-ciphertext"}if kind == "ECR secret" {row.RegistryType = registry.RegistryTypeECRrow.AWSSecretAccessKey = "invalid-ciphertext"@@ -129,7 +129,7 @@ func TestSyncCredentialDecryptionAbortsSnapshot(t *testing.T) {require.NoError(t, db.Create(&row).Error)syncResource = service.SyncRegistriesToEnvironmentcase "repository token", "repository SSH key":- row := gitrepo.GitRepository{BaseModel: database.BaseModel{ID: "bad-credential"}, Name: "Repository", URL: "https://example.com/repo.git"}+ row := gitrepo.GitRepository{ID: "bad-credential", Name: "Repository", URL: "https://example.com/repo.git"}if kind == "repository token" {row.Token = "invalid-ciphertext"} else {@@ -138,7 +138,7 @@ func TestSyncCredentialDecryptionAbortsSnapshot(t *testing.T) {require.NoError(t, db.Create(&row).Error)syncResource = service.SyncRepositoriesToEnvironmentcase "S3 secret":- require.NoError(t, db.Create(&s3domain.S3Destination{BaseModel: database.BaseModel{ID: "bad-credential"}, Name: "Backup", SecretAccessKey: "invalid-ciphertext"}).Error)+ require.NoError(t, db.Create(&s3domain.S3Destination{ID: "bad-credential", Name: "Backup", SecretAccessKey: "invalid-ciphertext"}).Error)syncResource = service.SyncS3DestinationsToEnvironment}err := syncResource(t.Context(), "remote")@@ -152,7 +152,7 @@ func TestSyncCredentialDecryptionAbortsSnapshot(t *testing.T) {func TestSyncRepositoriesPreservesEmptyCredentials(t *testing.T) {db := setupSyncDBInternal(t)- require.NoError(t, db.Create(&gitrepo.GitRepository{BaseModel: database.BaseModel{ID: "public-repo"}, Name: "Public", URL: "https://example.com/public.git", AuthType: "none"}).Error)+ require.NoError(t, db.Create(&gitrepo.GitRepository{ID: "public-repo", Name: "Public", URL: "https://example.com/public.git", AuthType: "none"}).Error)server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {var payload gitops.RepositorySyncRequestif err := json.NewDecoder(r.Body).Decode(&payload); err != nil {@@ -166,7 +166,7 @@ func TestSyncRepositoriesPreservesEmptyCredentials(t *testing.T) {_, _ = w.Write([]byte(`{"success":true}`))}))defer server.Close()- require.NoError(t, db.Create(&environment.Environment{BaseModel: database.BaseModel{ID: "remote"}, ApiUrl: server.URL, AccessToken: new("token")}).Error)+ require.NoError(t, db.Create(&environment.Environment{ID: "remote", ApiUrl: server.URL, AccessToken: new("token")}).Error)service := environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)require.NoError(t, service.SyncRepositoriesToEnvironment(t.Context(), "remote"))}@@ -188,8 +188,8 @@ func TestSyncSkipsUnchangedPayloadUntilForgotten(t *testing.T) {defer server.Close()token, err := crypto.Encrypt("secret")require.NoError(t, err)- require.NoError(t, db.Create(®istry.ContainerRegistry{BaseModel: database.BaseModel{ID: "ghcr"}, URL: "ghcr.io", RegistryType: registry.RegistryTypeGeneric, Username: "user", Token: token}).Error)- require.NoError(t, db.Create(&environment.Environment{BaseModel: database.BaseModel{ID: "remote"}, ApiUrl: server.URL, AccessToken: new("agent-token")}).Error)+ require.NoError(t, db.Create(®istry.ContainerRegistry{ID: "ghcr", URL: "ghcr.io", RegistryType: registry.RegistryTypeGeneric, Username: "user", Token: token}).Error)+ require.NoError(t, db.Create(&environment.Environment{ID: "remote", ApiUrl: server.URL, AccessToken: new("agent-token")}).Error)service := environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)sync := func() error { return service.SyncRegistriesToEnvironment(t.Context(), "remote") }changeRegistry := func(url string) {diff --git a/backend/internal/environment/handler.go b/backend/internal/environment/handler.goindex ca055c628..384d01736 100644--- a/backend/internal/environment/handler.go+++ b/backend/internal/environment/handler.go@@ -6,6 +6,7 @@ import ("cmp""context""encoding/json/v2"+ "errors""fmt""log/slog""maps"@@ -17,7 +18,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -531,7 +531,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(errors.WithMessage(err, "Failed to create environment").Error())+ return nil, huma.Error500InternalServerError("Failed to create environment: " + err.Error())}// Generate API key for environment@@ -588,7 +588,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(errors.WithMessage(err, "Failed to create environment").Error())+ return nil, huma.Error500InternalServerError("Failed to create environment: " + err.Error())}// Sync registries and git repositories in background (intentionally detached from request context)@@ -755,7 +755,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(errors.WithMessage(err, "Failed to delete environment").Error())+ return nil, huma.Error500InternalServerError("Failed to delete environment: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/environment/service_test.go b/backend/internal/environment/service_test.goindex dff31395b..c07f20e27 100644--- a/backend/internal/environment/service_test.go+++ b/backend/internal/environment/service_test.go@@ -442,7 +442,7 @@ func TestEnvironmentService_SyncS3DestinationsToEnvironment(t *testing.T) {encryptedSecret, err := crypto.Encrypt("s3-secret")require.NoError(t, err)require.NoError(t, db.WithContext(ctx).Create(&s3domain.S3Destination{- BaseModel: database.BaseModel{ID: "s3-1"},+ ID: "s3-1",Name: "Offsite",Endpoint: "https://s3.example.com",Bucket: "volume-backups",diff --git a/backend/internal/environment/vocabulary.go b/backend/internal/environment/vocabulary.godeleted file mode 100644index 0554dcca7..000000000--- a/backend/internal/environment/vocabulary.go+++ /dev/null@@ -1,22 +0,0 @@-package environment--import (- "strings"-- kit "go.getarcane.app/kit/pkg"-)--// LocalEnvironmentID is the reserved ID of the environment Arcane manages directly.-const (- LocalEnvironmentID = "0"- localEnvironmentFallbackNameInternal = "Local"-)--// DisplayName returns the stored environment name or its readable fallback.-func DisplayName(environmentID, storedName string) string {- if name := strings.TrimSpace(storedName); name != "" {- return name- }- id := strings.TrimSpace(environmentID)- return kit.Ternary(id == "" || id == LocalEnvironmentID, localEnvironmentFallbackNameInternal, id)-}diff --git a/backend/internal/event/handler.go b/backend/internal/event/handler.goindex 3378a5e0d..afffbcd26 100644--- a/backend/internal/event/handler.go+++ b/backend/internal/event/handler.go@@ -6,7 +6,6 @@ import ("net/http""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -99,7 +98,7 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *EventService, resoif _, err := eventService.IngestAgentEvent(c.Request().Context(), environmentID, input); err != nil {return c.JSON(http.StatusInternalServerError, base.ApiResponse[base.MessageResponse]{Success: false,- Data: base.MessageResponse{Message: errors.WithMessage(err, "Failed to create event").Error()},+ Data: base.MessageResponse{Message: "Failed to create event: " + err.Error()},})}@@ -178,7 +177,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(errors.WithMessage(err, "Failed to list events").Error())+ return nil, huma.Error500InternalServerError("Failed to list events: " + err.Error())}return &handlerutil.Page[eventtypes.Event]{@@ -194,7 +193,7 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*handlerutil.Out[EventSeverityCounts], error) {counts, err := h.eventService.GetEventSeverityCounts(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load event statistics").Error())+ return nil, huma.Error500InternalServerError("Failed to load event statistics: " + err.Error())}return &handlerutil.Out[EventSeverityCounts]{@@ -222,7 +221,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(errors.WithMessage(err, "Failed to list events").Error())+ return nil, huma.Error500InternalServerError("Failed to list events: " + err.Error())}return &handlerutil.Page[eventtypes.Event]{@@ -241,7 +240,7 @@ func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput)}if err := h.eventService.DeleteEvent(ctx, input.EventID); err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete event").Error())+ return nil, huma.Error500InternalServerError("Failed to delete event: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/event/service.go b/backend/internal/event/service.goindex 8e92ae719..6b9c2a1e1 100644--- a/backend/internal/event/service.go+++ b/backend/internal/event/service.go@@ -5,6 +5,7 @@ import ("cmp""context""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -13,7 +14,6 @@ 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/middleware"@@ -25,6 +25,7 @@ import ("github.com/samber/mo""github.com/samber/mo/option""go.getarcane.app/kit/pkg/mapping"+ "go.getarcane.app/streams/agg""golang.org/x/text/cases""golang.org/x/text/language""gorm.io/gorm"@@ -101,7 +102,7 @@ func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest)}result := tx.Create(eventRecord)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to create event")+ return fmt.Errorf("failed to create event: %w", result.Error)}inserted = result.RowsAffected > 0return nil@@ -205,7 +206,7 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelmanagerEventsURL, err := managerEventEndpointURL(httpx.ManagerBaseURL(s.cfg.ManagerApiUrl))if err != nil {- return errors.WrapIf(err, "manager API URL is invalid for manager event sync")+ return fmt.Errorf("manager API URL is invalid for manager event sync: %w", err)}payload := CreateEventRequest{@@ -227,19 +228,19 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelbody, err := json.Marshal(payload)if err != nil {- return errors.WrapIf(err, "failed to marshal event payload")+ return fmt.Errorf("failed to marshal event payload: %w", err)}req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerEventsURL, bytes.NewReader(body))if err != nil {- return errors.WrapIf(err, "failed to create manager event request")+ return fmt.Errorf("failed to create manager event request: %w", err)}req.Header.Set("Content-Type", "application/json")req.Header.Set(middleware.HeaderAgentToken, s.cfg.AgentToken)resp, err := s.httpClient.Do(req)if err != nil {- return errors.WrapIf(err, "failed to send event to manager")+ return fmt.Errorf("failed to send event to manager: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -249,9 +250,9 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelbodyBytes, readErr := io.ReadAll(io.LimitReader(resp.Body, 8192))if readErr != nil {- return errors.Errorf("manager event sync failed with status %d", resp.StatusCode)+ return fmt.Errorf("manager event sync failed with status %d", resp.StatusCode)}- return errors.Errorf("manager event sync failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return fmt.Errorf("manager event sync failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))}func managerEventEndpointURL(rawBaseURL string) (string, error) {@@ -262,10 +263,10 @@ func managerEventEndpointURL(rawBaseURL string) (string, error) {baseURL, err := url.Parse(trimmed)if err != nil {- return "", errors.WrapIf(err, "failed to parse manager API URL")+ return "", fmt.Errorf("failed to parse manager API URL: %w", err)}if baseURL.Scheme != "http" && baseURL.Scheme != "https" {- return "", errors.Errorf("unsupported scheme %q", baseURL.Scheme)+ return "", fmt.Errorf("unsupported scheme %q", baseURL.Scheme)}if baseURL.Host == "" {return "", errors.New("manager API URL host is required")@@ -326,12 +327,12 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatiopaginationResp, err := pagination.PaginateAndSortDB(params, q, &events)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)}eventDtos, mapErr := mapping.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {- return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")+ return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)}return eventDtos, paginationResp, nil@@ -356,12 +357,12 @@ func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, envipaginationResp, err := pagination.PaginateAndSortDB(params, q, &events)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)}eventDtos, mapErr := mapping.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {- return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")+ return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)}return eventDtos, paginationResp, nil@@ -420,7 +421,7 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeveritSelect("severity, COUNT(*) AS count").Group("severity").Scan(&rows).Error; err != nil {- return EventSeverityCounts{}, errors.WrapIf(err, "failed to count events by severity")+ return EventSeverityCounts{}, fmt.Errorf("failed to count events by severity: %w", err)}var counts EventSeverityCounts@@ -447,7 +448,7 @@ func (s *EventService) DeleteEvent(ctx context.Context, eventID string) error {err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Delete(&Event{}, "id = ?", eventID)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete event")+ return fmt.Errorf("failed to delete event: %w", result.Error)}if result.RowsAffected == 0 {return errors.New("event not found")@@ -466,7 +467,7 @@ func (s *EventService) DeleteOldEvents(ctx context.Context, olderThan time.Duraterr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {result := tx.Where("timestamp < ?", cutoff).Delete(&Event{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete old events")+ return fmt.Errorf("failed to delete old events: %w", result.Error)}deleted = result.RowsAffectedreturn nil@@ -748,3 +749,31 @@ func (s *EventService) getEventSeverity(eventType EventType) EventSeverity {return def.Severity})(mo.TupleToOption(definition, ok)).OrElse(EventSeverityInfo)}++// RunStreamProducer signals committed event changes so clients can refresh their current query.+func (s *EventService) RunStreamProducer(ctx context.Context, events chan<- eventtypes.StreamEvent) {+ changed := make(chan struct{}, 1)+ unsubscribe := s.changes.Subscribe(func(struct{}) {+ // One pending invalidation covers all changes, without blocking event persistence.+ select {+ case changed <- struct{}{}:+ default:+ }+ })+ defer unsubscribe()++ // Subscribe first so connecting and reconnecting clients cannot miss a change.+ if !agg.Send(ctx, events, eventtypes.StreamEvent{Type: "changed", Timestamp: time.Now()}) {+ return+ }+ for {+ select {+ case <-ctx.Done():+ return+ case <-changed:+ if !agg.Send(ctx, events, eventtypes.StreamEvent{Type: "changed", Timestamp: time.Now()}) {+ return+ }+ }+ }+}diff --git a/backend/internal/event/stream.go b/backend/internal/event/stream.godeleted file mode 100644index 842c7e63e..000000000--- a/backend/internal/event/stream.go+++ /dev/null@@ -1,37 +0,0 @@-package event--import (- "context"- "time"-- eventtypes "github.com/getarcaneapp/arcane/types/v2/event"- "go.getarcane.app/streams/agg"-)--// RunStreamProducer signals committed event changes so clients can refresh their current query.-func (s *EventService) RunStreamProducer(ctx context.Context, events chan<- eventtypes.StreamEvent) {- changed := make(chan struct{}, 1)- unsubscribe := s.changes.Subscribe(func(struct{}) {- // One pending invalidation covers all changes, without blocking event persistence.- select {- case changed <- struct{}{}:- default:- }- })- defer unsubscribe()-- // Subscribe first so connecting and reconnecting clients cannot miss a change.- if !agg.Send(ctx, events, eventtypes.StreamEvent{Type: "changed", Timestamp: time.Now()}) {- return- }- for {- select {- case <-ctx.Done():- return- case <-changed:- if !agg.Send(ctx, events, eventtypes.StreamEvent{Type: "changed", Timestamp: time.Now()}) {- return- }- }- }-}diff --git a/backend/internal/federated/credential.go b/backend/internal/federated/credential.goindex 53d47b793..f069144d5 100644--- a/backend/internal/federated/credential.go+++ b/backend/internal/federated/credential.go@@ -3,10 +3,11 @@ package federatedimport ("cmp""context"+ "errors"+ "fmt""net/url""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -118,7 +119,7 @@ func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req fefunc validateIssuerURLInternal(rawURL string) error {parsed, err := url.Parse(rawURL)if err != nil || parsed == nil || parsed.Host == "" || parsed.Scheme != "https" {- return common.Classify(common.ErrFederatedCredentialInvalid, errors.WithStackIf(errors.New("invalid federated credential: issuerUrl must be an HTTPS URL")))+ return common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential: issuerUrl must be an HTTPS URL"))}return nil}@@ -137,17 +138,17 @@ func (s *FederatedCredentialService) validateRoleGrantAgainstUserInternal(ctx couser, err := s.userService.GetUserByID(ctx, userID)if err != nil {- return errors.WrapIf(err, "load user for federated role validation")+ return fmt.Errorf("load user for federated role validation: %w", err)}permissions, err := s.roleService.ResolvePermissions(ctx, user)if err != nil {- return errors.WrapIf(err, "resolve user permissions")+ return fmt.Errorf("resolve user permissions: %w", err)}if err := s.roleService.ValidateRoleAssignmentAgainstCaller(ctx, permissions, roleID, environmentID); err != nil {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 common.Classify(common.ErrFederatedCredentialPermissionEscalation, fmt.Errorf("cannot map a federated credential to a role you do not hold: %w", err))}- return common.Classify(common.ErrFederatedCredentialInvalid, errors.WrapIf(err, "invalid federated credential"))+ return common.Classify(common.ErrFederatedCredentialInvalid, fmt.Errorf("invalid federated credential: %w", err))}return nil}diff --git a/backend/internal/federated/exchange.go b/backend/internal/federated/exchange.goindex 3a9bc702b..feed9dd11 100644--- a/backend/internal/federated/exchange.go+++ b/backend/internal/federated/exchange.go@@ -3,12 +3,13 @@ package federatedimport ("cmp""context"+ "errors"+ "fmt""log/slog""regexp""strings""time"- "emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -65,7 +66,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedeOrder("id ASC").Find(&credentials).Error; err != nil {logReason = "credential_lookup_failed"- return nil, errors.WrapIf(err, "failed to list federated credentials for issuer")+ return nil, fmt.Errorf("failed to list federated credentials for issuer: %w", err)}now := time.Now()active := credentials[:0]@@ -83,7 +84,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedeverifiedToken, verifiedClaims, err := s.verifySubjectTokenInternal(ctx, issuer, req.SubjectToken)if err != nil {logReason = "token_verification_failed"- return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.WrapIf(err, "invalid federated token grant"))+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, fmt.Errorf("invalid federated token grant: %w", err))}if subject == "" {subject = kit.ToString(jwtclaims.GetByPath(verifiedClaims, defaultFederatedSubjectClaim).OrEmpty())@@ -106,7 +107,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, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.WrapIf(err, "invalid federated token grant"))+ return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, fmt.Errorf("invalid federated token grant: %w", err))}matchedUser = user@@ -170,7 +171,7 @@ func (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.if err := s.db.WithContext(ctx).Where("expires_at < ?", now).Delete(&FederatedTokenReplay{}).Error; err != nil {- return errors.WrapIf(err, "failed to prune federated token replay records")+ return fmt.Errorf("failed to prune federated token replay records: %w", err)}tokenID := strings.TrimSpace(kit.ToString(jwtclaims.GetByPath(claims, "jti").OrEmpty()))@@ -189,7 +190,7 @@ func (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.if strings.Contains(message, "unique") || strings.Contains(message, "duplicate key") {return common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))}- return errors.WrapIf(err, "failed to record federated token replay guard")+ return fmt.Errorf("failed to record federated token replay guard: %w", err)}return nil}@@ -206,14 +207,14 @@ func (s *FederatedCredentialService) keySetForIssuerInternal(ctx context.ContextproviderCtx := oidc.ClientContext(context.WithoutCancel(ctx), s.httpClient)provider, err := oidc.NewProvider(providerCtx, issuer)if err != nil {- return nil, errors.WrapIf(err, "failed to discover federated issuer")+ return nil, fmt.Errorf("failed to discover federated issuer: %w", err)}var metadata struct {JWKSURL string `json:"jwks_uri"`}if err := provider.Claims(&metadata); err != nil {- return nil, errors.WrapIf(err, "failed to read federated issuer metadata")+ return nil, fmt.Errorf("failed to read federated issuer metadata: %w", err)}if metadata.JWKSURL == "" {return nil, errors.New("federated issuer metadata is missing jwks_uri")@@ -224,7 +225,7 @@ func (s *FederatedCredentialService) keySetForIssuerInternal(ctx context.ContextkeySet, err := s.keySetManager.KeySet(context.WithoutCancel(ctx), s.httpClient, metadata.JWKSURL)if err != nil {- return nil, errors.WrapIf(err, "failed to configure federated issuer JWK set")+ return nil, fmt.Errorf("failed to configure federated issuer JWK set: %w", err)}s.providerMu.Lock()s.keySets[issuer] = keySetdiff --git a/backend/internal/federated/handler.go b/backend/internal/federated/handler.goindex 89383165b..ca0d04bc1 100644--- a/backend/internal/federated/handler.go+++ b/backend/internal/federated/handler.go@@ -2,9 +2,9 @@ package federatedimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -237,8 +237,7 @@ func writeFederatedTokenExchangeErrorInternal(c *echo.Context, err error) errorcase errors.Is(err, common.ErrFederatedCredentialInvalidRequest):code = "invalid_request"description = "invalid token exchange request"- case errors.Is(err, common.ErrFederatedCredentialInvalidGrant),- errors.Is(err, common.ErrFederatedCredentialNotFound):+ case errors.Is(err, common.ErrFederatedCredentialInvalidGrant), errors.Is(err, common.ErrFederatedCredentialNotFound):code = "invalid_grant"case errors.Is(err, common.ErrFederatedCredentialInvalid):code = "invalid_request"@@ -257,8 +256,7 @@ func federatedCredentialManagementErrorInternal(err error) error {switch {case errors.Is(err, common.ErrFederatedCredentialNotFound):return huma.Error404NotFound("federated credential not found")- case errors.Is(err, common.ErrFederatedCredentialInvalid),- errors.Is(err, common.ErrFederatedCredentialInvalidRequest):+ case errors.Is(err, common.ErrFederatedCredentialInvalid), errors.Is(err, common.ErrFederatedCredentialInvalidRequest):return huma.Error400BadRequest("invalid federated credential")case errors.Is(err, common.ErrFederatedCredentialPermissionEscalation):return huma.Error403Forbidden("permission denied")diff --git a/backend/internal/federated/playwright.go b/backend/internal/federated/playwright.goindex 5f742f4be..26dc218e4 100644--- a/backend/internal/federated/playwright.go+++ b/backend/internal/federated/playwright.go@@ -4,10 +4,11 @@ package federatedimport ("context"+ "errors"+ "fmt""strings""uuid"- "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/role"@@ -34,7 +35,7 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.ContIsServiceAccount: true,}if err := tx.Create(&serviceUser).Error; err != nil {- return errors.WrapIf(err, "failed to create federated e2e user")+ return fmt.Errorf("failed to create federated e2e user: %w", err)}credential := FederatedCredential{@@ -50,7 +51,7 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.ContTokenTTLSeconds: tokenTTLSeconds,}if err := tx.Create(&credential).Error; err != nil {- return errors.WrapIf(err, "failed to create federated e2e credential")+ return fmt.Errorf("failed to create federated e2e credential: %w", err)}assignment := role.UserRoleAssignment{@@ -59,7 +60,7 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.ContSource: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return errors.WrapIf(err, "failed to create federated e2e role assignment")+ return fmt.Errorf("failed to create federated e2e role assignment: %w", err)}credentialID = credential.IDdiff --git a/backend/internal/federated/service.go b/backend/internal/federated/service.goindex 456847252..f0945933d 100644--- a/backend/internal/federated/service.go+++ b/backend/internal/federated/service.go@@ -2,13 +2,14 @@ package federatedimport ("context"+ "errors"+ "fmt""net/http""strings""sync""time""uuid"- "emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -92,7 +93,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stIsServiceAccount: true,}if err := tx.Create(&serviceUser).Error; err != nil {- return errors.WrapIf(err, "failed to create federated service user")+ return fmt.Errorf("failed to create federated service user: %w", err)}created = FederatedCredential{@@ -111,7 +112,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stExpiresAt: normalized.ExpiresAt,}if err := tx.Create(&created).Error; err != nil {- return errors.WrapIf(err, "failed to create federated credential")+ return fmt.Errorf("failed to create federated credential: %w", err)}assignment := role.UserRoleAssignment{@@ -121,7 +122,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID stSource: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return errors.WrapIf(err, "failed to create federated role assignment")+ return fmt.Errorf("failed to create federated role assignment: %w", err)}return nil})@@ -154,7 +155,7 @@ func (s *FederatedCredentialService) List(ctx context.Context, params paginationresp, err := pagination.PaginateAndSortDB(params, query, &credentials)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate federated credentials")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate federated credentials: %w", err)}result := make([]federatedtypes.FederatedCredential, len(credentials))@@ -175,7 +176,7 @@ func (s *FederatedCredentialService) Get(ctx context.Context, id string) (*federif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return nil, errors.WrapIf(err, "failed to get federated credential")+ return nil, fmt.Errorf("failed to get federated credential: %w", err)}return new(toFederatedCredentialDTOInternal(&credential)), nil}@@ -186,7 +187,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID, iif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return nil, errors.WrapIf(err, "failed to load federated credential")+ return nil, fmt.Errorf("failed to load federated credential: %w", err)}updated, roleChanged, err := applyFederatedCredentialUpdateInternal(credential, req)@@ -202,20 +203,20 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID, ierr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Save(&updated).Error; err != nil {- return errors.WrapIf(err, "failed to update federated credential")+ return fmt.Errorf("failed to update federated credential: %w", err)}if revokeActiveSessions {now := time.Now()if err := tx.Model(&session.UserSession{}).Where("federated_credential_id = ? AND revoked_at IS NULL", updated.ID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return errors.WrapIf(err, "failed to revoke federated credential sessions")+ return fmt.Errorf("failed to revoke federated credential sessions: %w", err)}}if roleChanged {if err := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, role.RoleAssignmentSourceManual).Delete(&role.UserRoleAssignment{}).Error; err != nil {- return errors.WrapIf(err, "failed to clear federated role assignment")+ return fmt.Errorf("failed to clear federated role assignment: %w", err)}assignment := role.UserRoleAssignment{UserID: updated.IdentityUserID,@@ -224,7 +225,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID, iSource: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {- return errors.WrapIf(err, "failed to update federated role assignment")+ return fmt.Errorf("failed to update federated role assignment: %w", err)}}return nil@@ -247,15 +248,15 @@ func (s *FederatedCredentialService) Delete(ctx context.Context, id string) erroif errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))}- return errors.WrapIf(err, "failed to load federated credential")+ return fmt.Errorf("failed to load federated credential: %w", err)}err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Delete(&FederatedCredential{}, "id = ?", credential.ID).Error; err != nil {- return errors.WrapIf(err, "failed to delete federated credential")+ return fmt.Errorf("failed to delete federated credential: %w", err)}if err := tx.Delete(&common.User{}, "id = ?", credential.IdentityUserID).Error; err != nil {- return errors.WrapIf(err, "failed to delete federated service user")+ return fmt.Errorf("failed to delete federated service user: %w", err)}return nil})diff --git a/backend/internal/federated/service_test.go b/backend/internal/federated/service_test.goindex 71531c213..1a8ae7485 100644--- a/backend/internal/federated/service_test.go+++ b/backend/internal/federated/service_test.go@@ -5,6 +5,7 @@ import ("crypto/mldsa""encoding/base64""encoding/json"+ "errors""fmt""net/http""net/http/httptest"@@ -12,7 +13,6 @@ import ("testing""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -149,7 +149,7 @@ func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTestrequire.NoError(t, err)authSvc := auth.NewAuthService(userSvc, settingsSvc, eventSvc, sessionSvc, roleSvc, &config.Config{JWTRefreshExpiry: 24 * time.Hour,- }, nil).WithSigningKey(signingKey)+ }).WithSigningKey(signingKey)keySetManager := oidcjwk.NewKeySetManager(t.Context())t.Cleanup(func() {diff --git a/backend/internal/gitops/backup.go b/backend/internal/gitops/backup.goindex ebb672caa..5f84bab06 100644--- a/backend/internal/gitops/backup.go+++ b/backend/internal/gitops/backup.go@@ -3,6 +3,7 @@ package gitopsimport ("context""encoding/json/v2"+ "errors""fmt""io/fs""log/slog"@@ -14,13 +15,13 @@ 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/event"projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/gitops"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""go.getarcane.app/acfs"@@ -108,7 +109,7 @@ func normalizeSyncModeInternal(mode string) (string, error) {case gitops.SyncModeBackup:return gitops.SyncModeBackup, nildefault:- return "", common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("unsupported sync mode %q", mode), "field", "mode"))+ return "", common.Classify(common.ErrValidation, &base.FieldError{Field: "mode", Err: fmt.Errorf("unsupported sync mode %q", mode)})}}@@ -124,10 +125,10 @@ type backupCreateConfigInternal struct {// prepareBackupCreateInternal validates a backup create request against the project and other backups on the branch.func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, tx *gorm.DB, req gitops.CreateSyncRequest) (*backupCreateConfigInternal, error) {if req.HasDeploymentOptions() {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("deployment options cannot be set on a backup sync"), "field", "mode"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "mode", Err: errors.New("deployment options cannot be set on a backup sync")})}if strings.TrimSpace(req.ProjectID) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("a project is required for a backup sync"), "field", "projectId"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "projectId", Err: errors.New("a project is required for a backup sync")})}project, err := lockProjectForSyncInternal(tx, req.ProjectID)if err != nil {@@ -140,7 +141,7 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, txif err := tx.Model(&projectpkg.GitOpsSync{}).Where("mode = ? AND project_id = ?", gitops.SyncModeBackup, project.ID).Count(&existing).Error; err != nil {- return nil, errors.WrapIf(err, "failed to check existing backups")+ return nil, fmt.Errorf("failed to check existing backups: %w", err)}if existing > 0 {return nil, common.Classify(common.ErrConflict, errors.New("project already has a Git backup; disconnect it first"))@@ -151,7 +152,7 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, txerr = errors.New("backup directory must not contain a .git segment")}if err != nil {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "backupDirectory"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "backupDirectory", Err: err})}if err := ensureBackupDestinationFreeInternal(tx, "", req.RepositoryID, req.Branch, directory); err != nil {return nil, err@@ -161,11 +162,11 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, tx}composeFile, _, err := s.backupComposeFilesInternal(ctx, project)if err != nil {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "projectId"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "projectId", Err: err})}paths, err := normalizeBackupPathsInternal(req.BackupPaths)if err != nil {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "backupPaths"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "backupPaths", Err: err})}config := &backupCreateConfigInternal{project: project, directory: directory, paths: paths, composeFile: composeFile, backupOnSave: true}if req.BackupOnSave != nil {@@ -181,7 +182,7 @@ func lockProjectForSyncInternal(tx *gorm.DB, projectID string) (*projectpkg.Projif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.ErrProjectNotFound}- return nil, errors.WrapIff(err, "failed to get project %s", projectID)+ return nil, fmt.Errorf("failed to get project %s: %w", projectID, err)}return &project, nil}@@ -189,18 +190,17 @@ func lockProjectForSyncInternal(tx *gorm.DB, projectID string) (*projectpkg.Proj// ensureBackupDestinationFreeInternal rejects a destination that overlaps another backup on the same branch.func ensureBackupDestinationFreeInternal(tx *gorm.DB, excludeSyncID, repositoryID, branch, directory string) error {var others []projectpkg.GitOpsSync- q := tx.- Select("id", "backup_directory").+ q := tx.Select("id", "backup_directory").Where("mode = ? AND repository_id = ? AND branch = ?", gitops.SyncModeBackup, repositoryID, branch)if excludeSyncID != "" {q = q.Where("id <> ?", excludeSyncID)}if err := q.Find(&others).Error; err != nil {- return errors.WrapIf(err, "failed to check backup destinations")+ return fmt.Errorf("failed to check backup destinations: %w", err)}for _, other := range others {if other.BackupDirectory == directory || strings.HasPrefix(other.BackupDirectory, directory+"/") || strings.HasPrefix(directory, other.BackupDirectory+"/") {- return common.Classify(common.ErrConflict, errors.Errorf("backup directory %q overlaps with an existing backup at %q on this branch", directory, other.BackupDirectory))+ return common.Classify(common.ErrConflict, fmt.Errorf("backup directory %q overlaps with an existing backup at %q on this branch", directory, other.BackupDirectory))}}return nil@@ -210,12 +210,12 @@ func ensureBackupDestinationFreeInternal(tx *gorm.DB, excludeSyncID, repositoryIfunc (s *GitOpsSyncService) applyModeUpdatesInternal(ctx context.Context, current *projectpkg.GitOpsSync, req gitops.UpdateSyncRequest, updates map[string]any) error {if current.Mode != gitops.SyncModeBackup {if req.HasBackupOptions() {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("backup options cannot be set on a deployment sync"), "field", "mode"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "mode", Err: errors.New("backup options cannot be set on a deployment sync")})}return nil}if req.HasDeploymentOptions() {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("deployment options cannot be set on a backup sync"), "field", "mode"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "mode", Err: errors.New("deployment options cannot be set on a backup sync")})}repositoryID := current.RepositoryIDif req.RepositoryID != nil {@@ -236,7 +236,7 @@ func (s *GitOpsSyncService) applyModeUpdatesInternal(ctx context.Context, currenif req.BackupPaths != nil {paths, err := normalizeBackupPathsInternal(req.BackupPaths)if err != nil {- return common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "backupPaths"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "backupPaths", Err: err})}updates["backup_paths"] = database.StringSlice(paths)}@@ -259,7 +259,7 @@ func (s *GitOpsSyncService) performBackupInternal(ctx context.Context, sync *proreturn result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Failed to load project", err, false)}if !found {- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project not found", errors.Errorf("project %s no longer exists", *sync.ProjectID), false)+ return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project not found", fmt.Errorf("project %s no longer exists", *sync.ProjectID), false)}if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); err != nil {return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project directory is unavailable", err, false)@@ -296,7 +296,7 @@ func (s *GitOpsSyncService) performBackupInternal(ctx context.Context, sync *pro}return result, err}- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailurePushRejected, "Push rejected by remote", errors.Errorf("another writer kept updating branch %s; giving up after %d attempts", sync.Branch, backupPushAttempts), false)+ return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailurePushRejected, "Push rejected by remote", fmt.Errorf("another writer kept updating branch %s; giving up after %d attempts", sync.Branch, backupPushAttempts), false)}// commitBackupInternal runs one checkout-analyze-push attempt; retry reports a rejected push worth repeating.@@ -327,9 +327,9 @@ func (s *GitOpsSyncService) commitBackupInternal(ctx context.Context, sync *projif len(analysis.conflicts) > backupCommitFileLines {names = append(names, "...")}- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureConflict, "Backup files changed in the repository", errors.Errorf("%d backup file(s) changed in the repository since the last backup: %s", len(analysis.conflicts), strings.Join(names, ", ")), true)+ return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureConflict, "Backup files changed in the repository", fmt.Errorf("%d backup file(s) changed in the repository since the last backup: %s", len(analysis.conflicts), strings.Join(names, ", ")), true)case backupPreviewOccupied:- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureDestinationOccupied, "Backup directory already contains unrelated files", errors.Errorf("directory %s on branch %s already contains files that are not an Arcane backup", sync.BackupDirectory, sync.Branch), true)+ return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureDestinationOccupied, "Backup directory already contains unrelated files", fmt.Errorf("directory %s on branch %s already contains files that are not an Arcane backup", sync.BackupDirectory, sync.Branch), true)}var message strings.Builder@@ -418,7 +418,7 @@ func (s *GitOpsSyncService) recordBackupSuccessInternal(ctx context.Context, syn}hashes, err := json.Marshal(snapshot.hashes, json.Deterministic(true))if err != nil {- return errors.WrapIf(err, "failed to encode backup snapshot")+ return fmt.Errorf("failed to encode backup snapshot: %w", err)}updates := map[string]any{"last_sync_at": now,@@ -464,9 +464,9 @@ func (s *GitOpsSyncService) failBackupInternal(ctx context.Context, sync *projec}s.logSyncError(ctx, sync, actor, errMsg)if needsAttention {- return common.Classify(common.ErrConflict, errors.WithMessage(failure, message))+ return common.Classify(common.ErrConflict, fmt.Errorf("%s: %w", message, failure))}- return errors.WithMessage(failure, message)+ return fmt.Errorf("%s: %w", message, failure)}// PreviewBackup reports what the next backup run would commit or why it needs attention.@@ -501,7 +501,7 @@ func (s *GitOpsSyncService) PreviewBackup(ctx context.Context, environmentID, id}checkout, err := s.repoService.CheckoutForWrite(previewCtx, syncRecord.Repository.URL, syncRecord.Branch, authConfig)if err != nil {- return nil, errors.WrapIf(err, "failed to clone repository")+ return nil, fmt.Errorf("failed to clone repository: %w", err)}defer s.repoService.Discard(previewCtx, checkout.RepoPath)analysis, err := analyzeBackupInternal(previewCtx, checkout.RepoPath, syncRecord.BackupDirectory, snapshot, parseBackupSnapshotInternal(syncRecord.LastBackupSnapshot), false)@@ -524,7 +524,7 @@ func (s *GitOpsSyncService) PreviewBackup(ctx context.Context, environmentID, id// ResolveBackupConflict applies the chosen strategy to a backup that needs attention.func (s *GitOpsSyncService) ResolveBackupConflict(ctx context.Context, environmentID, id string, req gitops.ResolveBackupConflictRequest, actor common.User) (*gitops.SyncResult, error) {if req.Strategy != gitops.BackupConflictUseArcane {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("unsupported strategy %q", req.Strategy), "field", "strategy"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "strategy", Err: fmt.Errorf("unsupported strategy %q", req.Strategy)})}syncRecord, err := s.getBackupSyncInternal(ctx, environmentID, id)if err != nil {@@ -589,7 +589,7 @@ func (s *GitOpsSyncService) ReconcileInterruptedBackupsOnStartup(ctx context.Con"backup_pending_since": time.Now(),}).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return errors.WrapIf(err, "failed to reconcile interrupted git backups")+ return fmt.Errorf("failed to reconcile interrupted git backups: %w", err)}return nil}@@ -613,11 +613,11 @@ func normalizeBackupPathsInternal(raw []string) ([]string, error) {for _, entry := range raw {cleaned, err := kit.NormalizeRelativePath(entry)if err != nil {- return nil, errors.WrapIff(err, "invalid backup path %q", entry)+ return nil, fmt.Errorf("invalid backup path %q: %w", entry, err)}base := path.Base(cleaned)if base == projects.GitSourceEnvFileName || base == projects.GlobalEnvFileName || slices.Contains(strings.Split(cleaned, "/"), ".git") {- return nil, errors.Errorf("backup path %q is reserved", entry)+ return nil, fmt.Errorf("backup path %q is reserved", entry)}normalized = append(normalized, cleaned)}@@ -644,7 +644,7 @@ func (s *GitOpsSyncService) backupComposeFilesInternal(ctx context.Context, proj}relative, err := filepath.Rel(project.Path, composePath)if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {- return "", nil, errors.Errorf("compose file %s is outside the project directory", composePath)+ return "", nil, fmt.Errorf("compose file %s is outside the project directory", composePath)}primary := filepath.ToSlash(relative)composeFiles := []string{primary}@@ -662,7 +662,7 @@ func (s *GitOpsSyncService) backupComposeFilesInternal(ctx context.Context, projfunc (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, sync *projectpkg.GitOpsSync, project *projectpkg.Project) (*backupSnapshotInternal, error) {_, composeFiles, err := s.backupComposeFilesInternal(ctx, project)if err != nil {- return nil, errors.WrapIf(git.ErrSelectionInvalid, err.Error())+ return nil, fmt.Errorf("%s: %w", err.Error(), git.ErrSelectionInvalid)}paths := slices.Clone([]string(sync.BackupPaths))for _, composeFile := range composeFiles {@@ -694,7 +694,7 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, synfor _, file := range files {content, err := acfs.ReadFile(ctx, project.Path, "/"+file.Path)if err != nil {- return nil, errors.WrapIff(git.ErrSelectionUnreadable, "cannot re-read %s: %v", file.Path, err)+ return nil, fmt.Errorf("cannot re-read %s: %v: %w", file.Path, err.Error(), git.ErrSelectionUnreadable)}if kit.SHA256Hex(content) != snapshot.hashes[file.Path] {stable = false@@ -705,7 +705,7 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, synreturn snapshot, nil}}- return nil, errors.WrapIf(git.ErrSelectionInvalid, "project files changed while the backup snapshot was being taken")+ return nil, fmt.Errorf("project files changed while the backup snapshot was being taken: %w", git.ErrSelectionInvalid)}// analyzeBackupInternal compares the snapshot with the checkout; baseline is the last push and the only proof the directory is ours.@@ -713,7 +713,7 @@ func analyzeBackupInternal(ctx context.Context, repoPath, directory string, snapanalysis := backupAnalysisInternal{conflicts: []gitops.BackupFileChange{}}entries, err := acfs.List(ctx, repoPath, "/"+directory)if err != nil && !errors.Is(err, fs.ErrNotExist) {- return analysis, errors.WrapIf(err, "failed to inspect remote backup directory")+ return analysis, fmt.Errorf("failed to inspect remote backup directory: %w", err)}occupied := err == nil && len(entries) > 0remote := make(map[string]string)@@ -728,7 +728,7 @@ func analyzeBackupInternal(ctx context.Context, repoPath, directory string, snapif errors.Is(readErr, fs.ErrNotExist) {continue}- return analysis, errors.WrapIff(readErr, "failed to read remote backup file %s", file)+ return analysis, fmt.Errorf("failed to read remote backup file %s: %w", file, readErr)}remote[file] = kit.SHA256Hex(content)}@@ -818,7 +818,7 @@ func (s *GitOpsSyncService) cloneBackupBranchInternal(ctx context.Context, syncR}checkout, err := s.repoService.CheckoutForWrite(ctx, syncRecord.Repository.URL, syncRecord.Branch, authConfig)if err != nil {- return "", func() {}, errors.WrapIf(err, "failed to clone repository")+ return "", func() {}, fmt.Errorf("failed to clone repository: %w", err)}cleanup := func() { s.repoService.Discard(ctx, checkout.RepoPath) }if !checkout.BranchExists {diff --git a/backend/internal/gitops/backup_test.go b/backend/internal/gitops/backup_test.goindex ff6288433..c2206212f 100644--- a/backend/internal/gitops/backup_test.go+++ b/backend/internal/gitops/backup_test.go@@ -127,11 +127,11 @@ func setupGitOpsBackupTestServiceInternal(t *testing.T) *backupTestEnvInternal {repoURL := "http://localhost" + barerequire.NoError(t, db.Create(&gitrepo.GitRepository{- BaseModel: database.BaseModel{ID: "repo-backup"},- Name: "backup-remote",- URL: repoURL,- AuthType: "none",- Enabled: true,+ ID: "repo-backup",+ Name: "backup-remote",+ URL: repoURL,+ AuthType: "none",+ Enabled: true,}).Error)projectPath := filepath.Join(projectsDir, "demo-project")@@ -139,11 +139,11 @@ func setupGitOpsBackupTestServiceInternal(t *testing.T) *backupTestEnvInternal {writeBackupProjectFileInternal(t, projectPath, "compose.yaml", "services:\n app:\n image: nginx:1.27-alpine\n")project := &projectpkg.Project{- BaseModel: database.BaseModel{ID: "proj-backup"},- Name: "demo-project",- DirName: new("demo-project"),- Path: projectPath,- Status: projectpkg.ProjectStatusStopped,+ ID: "proj-backup",+ Name: "demo-project",+ DirName: new("demo-project"),+ Path: projectPath,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -458,11 +458,11 @@ func TestGitOpsBackup_CreateValidation(t *testing.T) {mutate: func(t *testing.T, env *backupTestEnvInternal) {t.Helper()other := &projectpkg.Project{- BaseModel: database.BaseModel{ID: "proj-other"},- Name: "other-project",- DirName: new("other-project"),- Path: filepath.Join(env.projectsDir, "other-project"),- Status: projectpkg.ProjectStatusStopped,+ ID: "proj-other",+ Name: "other-project",+ DirName: new("other-project"),+ Path: filepath.Join(env.projectsDir, "other-project"),+ Status: projectpkg.ProjectStatusStopped,}writeBackupProjectFileInternal(t, other.Path, "compose.yaml", "services: {}\n")require.NoError(t, env.db.Create(other).Error)@@ -653,21 +653,19 @@ func TestGitOpsImport_ForwardsDeployAndLifecycleFields(t *testing.T) {resp, err := env.service.ImportSyncs(ctx, "0", []gitops.ImportGitOpsSyncRequest{{- SyncName: "Media-Server",- GitRepo: "backup-remote",- Branch: "main",- DockerComposePath: "apps/demo/compose.yaml",- SyncDirectory: new(true),- ProjectName: "media-server",- PullImageAfterSync: new(true),- RedeployAfterSync: new(true),- PreDeployConfigRequest: gitops.PreDeployConfigRequest{- PreDeployScriptPath: new("scripts/decrypt.sh"),- PreDeployRunnerImage: new("alpine:3.20"),- PreDeployEnv: new("SOPS_AGE_KEY=secret\n"),- PreDeployTimeoutSec: new(120),- PreDeployNetworkMode: new("bridge"),- },+ SyncName: "Media-Server",+ GitRepo: "backup-remote",+ Branch: "main",+ DockerComposePath: "apps/demo/compose.yaml",+ SyncDirectory: new(true),+ ProjectName: "media-server",+ PullImageAfterSync: new(true),+ RedeployAfterSync: new(true),+ PreDeployScriptPath: new("scripts/decrypt.sh"),+ PreDeployRunnerImage: new("alpine:3.20"),+ PreDeployEnv: new("SOPS_AGE_KEY=secret\n"),+ PreDeployTimeoutSec: new(120),+ PreDeployNetworkMode: new("bridge"),},{SyncName: "plain",diff --git a/backend/internal/gitops/gitops_sync.go b/backend/internal/gitops/gitops_sync.goindex 2b03bfed2..d5db703d7 100644--- a/backend/internal/gitops/gitops_sync.go+++ b/backend/internal/gitops/gitops_sync.go@@ -4,6 +4,7 @@ import ("cmp""context""encoding/json/v2"+ "errors""fmt""io""io/fs"@@ -16,7 +17,6 @@ import ("strings""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/event"@@ -30,6 +30,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/gitops"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -156,7 +157,7 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,// just because the global setting was turned off afterwards.if lifecycleFieldSet && !s.settingsService.GetBoolSetting(ctx, "lifecycleEnabled", false) {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy lifecycle hooks are disabled. An admin must enable lifecycleEnabled in settings before they can be configured.")}) //nolint:staticcheck // Preserve the existing error message.}if effectiveScriptPath != "" {@@ -168,20 +169,20 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,if in.timeoutSec != nil {if *in.timeoutSec < 1 {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployTimeoutSec", Err: errors.New("Timeout must be at least 1 second.")}) //nolint:staticcheck // Preserve the existing error message.}maxTimeoutSec := s.settingsService.GetIntSetting(ctx, "lifecycleMaxTimeoutSec", projectpkg.DefaultMaxTimeoutSec)if maxTimeoutSec > 0 && *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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployTimeoutSec", Err: fmt.Errorf("Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).", *in.timeoutSec, maxTimeoutSec)}) //nolint:staticcheck // Preserve the existing error message.}}if _, err := projectpkg.ParseEnvText(in.env); err != nil {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployEnv"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployEnv", Err: errors.New(err.Error())})}if _, err := projectpkg.ParseExtraMountsText(in.extraMounts); err != nil {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployExtraMounts"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployExtraMounts", Err: errors.New(err.Error())})}return nil@@ -190,35 +191,36 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Context, current *projectpkg.GitOpsSync, in lifecycleConfigInputInternal, scriptPath string) error {if resolveLifecycleEffectiveTargetTypeInternal(current, in.targetType) == "swarm_stack" {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy lifecycle hooks are only supported for project syncs.")}) //nolint:staticcheck // Preserve the existing error message.}if len(scriptPath) > 256 {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must be 256 characters or fewer.")}) //nolint:staticcheck // Preserve the existing error message.}+// 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)) {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must be relative to the project directory.")}) //nolint:staticcheck // Preserve the existing error message.}cleaned := filepath.ToSlash(filepath.Clean(scriptPath))if cleaned == ".." || strings.HasPrefix(cleaned, "../") {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must not escape the project directory.")}) //nolint:staticcheck // Preserve the existing error message.}effectiveRunnerImage := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *projectpkg.GitOpsSync) *string { return c.PreDeployRunnerImage }), in.runnerImage)defaultRunnerImage := strings.TrimSpace(s.settingsService.GetStringSetting(ctx, "lifecycleDefaultRunnerImage", ""))if effectiveRunnerImage == "" && defaultRunnerImage == "" {//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"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployRunnerImage", Err: errors.New("Runner image is required when a script path is set.")}) //nolint:staticcheck // Preserve the existing error message.}if !resolveEffectiveSyncDirectoryInternal(current, in.syncDirectory) {//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 common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy script requires \"Sync entire directory\" so the script is included in the synced files.")}) //nolint:staticcheck // Preserve the existing error message.}return nil@@ -568,17 +570,17 @@ func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentIDcounts, err := s.getFilteredSyncCounts(q)if err != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to get sync counts")+ return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to get sync counts: %w", err)}paginationResp, err := pagination.PaginateAndSortDB(params, q.Preload("Repository").Preload("Project"), &syncs)if err != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to paginate gitops syncs")+ return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to paginate gitops syncs: %w", err)}out, mapErr := mapping.MapSlice[projectpkg.GitOpsSync, gitops.GitOpsSync](syncs)if mapErr != nil {- return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(mapErr, "failed to map syncs")+ return nil, pagination.Response{}, gitops.SyncCounts{}, fmt.Errorf("failed to map syncs: %w", mapErr)}return out, paginationResp, counts, nil@@ -640,7 +642,7 @@ func (s *GitOpsSyncService) getSyncByIDInternal(ctx context.Context, environmentif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.Classify(common.ErrNotFound, errors.New("GitOps sync not found"))}- return nil, errors.WrapIf(err, "failed to get sync")+ return nil, fmt.Errorf("failed to get sync: %w", err)}return &syncRecord, nil}@@ -657,17 +659,16 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringreturn nil, err}if mode == gitops.SyncModeDeploy && req.HasBackupOptions() {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("backup options require mode \"backup\""), "field", "mode"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "mode", Err: errors.New("backup options require mode \"backup\"")})}if mode == gitops.SyncModeDeploy && strings.TrimSpace(req.ComposePath) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("compose path is required"), "field", "composePath"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "composePath", Err: errors.New("compose path is required")})}- // Validate repository existsrepo, 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, errors.WrapIf(err, "repository not found")+ return nil, fmt.Errorf("repository not found: %w", err)}slog.InfoContext(ctx, "Found repository for GitOps sync", "repositoryID", req.RepositoryID, "repositoryName", repo.Name)@@ -749,7 +750,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringif adoptedProject != nil {adoptedProject.GitOpsManagedBy = &syncRecord.IDif err := s.projectService.EnsureGitOpsProjectLinked(ctx, &syncRecord, adoptedProject); err != nil {- return nil, errors.WrapIf(err, "failed to link existing project")+ return nil, fmt.Errorf("failed to link existing project: %w", err)}}@@ -786,7 +787,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string// and not be backed up to Git.func (s *GitOpsSyncService) prepareDeployProjectLinkInternal(ctx context.Context, tx *gorm.DB, req gitops.CreateSyncRequest) (*projectpkg.Project, error) {if strings.TrimSpace(req.TargetType) == "swarm_stack" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("an existing project cannot be linked to a swarm stack sync"), "field", "projectId"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "projectId", Err: errors.New("an existing project cannot be linked to a swarm stack sync")})}project, err := lockProjectForSyncInternal(tx, req.ProjectID)if err != nil {@@ -799,7 +800,7 @@ func (s *GitOpsSyncService) prepareDeployProjectLinkInternal(ctx context.Contextif err := tx.Model(&projectpkg.GitOpsSync{}).Where("mode = ? AND project_id = ?", gitops.SyncModeBackup, project.ID).Count(&backups).Error; err != nil {- return nil, errors.WrapIf(err, "failed to check existing backups")+ return nil, fmt.Errorf("failed to check existing backups: %w", err)}if backups > 0 {return nil, common.Classify(common.ErrConflict, errors.New("project is backed up to Git; disconnect that backup before deploying it from Git"))@@ -854,7 +855,7 @@ func (s *GitOpsSyncService) insertSyncRecordInternal(ctx context.Context, syncRereturn common.Classify(common.ErrConflict, errors.New("project already has a Git backup; disconnect it first"))}slog.ErrorContext(ctx, "Failed to create GitOps sync in database", "name", req.Name, "repositoryID", req.RepositoryID, "environmentID", syncRecord.EnvironmentID, "error", err)- return errors.WrapIf(err, "failed to create sync")+ return fmt.Errorf("failed to create sync: %w", err)}if adoptedProject == nil {return nil@@ -863,7 +864,7 @@ func (s *GitOpsSyncService) insertSyncRecordInternal(ctx context.Context, syncReWhere("id = ? AND (gitops_managed_by IS NULL OR gitops_managed_by = '')", adoptedProject.ID).Update("gitops_managed_by", syncRecord.ID)if linked.Error != nil {- return errors.WrapIf(linked.Error, "failed to link existing project")+ return fmt.Errorf("failed to link existing project: %w", linked.Error)}if linked.RowsAffected != 1 {return common.Classify(common.ErrConflict, errors.New("project is already deployed from Git"))@@ -910,7 +911,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, errors.WrapIf(err, "repository not found")+ return nil, fmt.Errorf("repository not found: %w", err)}updates["repository_id"] = *req.RepositoryID}@@ -976,7 +977,7 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id stif len(updates) > 0 {// Loaded associations must not overwrite explicitly updated foreign keys.if err := s.db.WithContext(ctx).Model(syncRecord).Omit(clause.Associations).Updates(updates).Error; err != nil {- return nil, errors.WrapIf(err, "failed to update sync")+ return nil, fmt.Errorf("failed to update sync: %w", err)}// Log event@@ -1028,14 +1029,16 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id stif err := tx.Model(&projectpkg.Project{}).Where("gitops_managed_by = ?", id).Update("gitops_managed_by", nil).Error; err != nil {- return errors.WrapIf(err, "failed to clear gitops_managed_by")+ return fmt.Errorf("failed to clear gitops_managed_by: %w", err)}+ if err :=++ // 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).- // 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(&projectpkg.GitOpsSync{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete sync")+ tx.Where("id = ?", id).Delete(&projectpkg.GitOpsSync{}).Error; err != nil {+ return fmt.Errorf("failed to delete sync: %w", err)}return nil}); err != nil {@@ -1080,7 +1083,7 @@ func (s *GitOpsSyncService) performSyncAdmittedInternal(ctx context.Context, env// kick, manual trigger, webhook) so they don't race the clone/redeploy.lease, admitted, err := s.jobs.TryAcquire(ctx, id)if err != nil {- return nil, errors.WrapIf(err, "failed to admit GitOps sync")+ return nil, fmt.Errorf("failed to admit GitOps sync: %w", err)}if !admitted {slog.InfoContext(ctx, "GitOps sync already in progress; skipping", "syncId", id)@@ -1446,7 +1449,7 @@ func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, syncslog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "syncMode", syncMode, "projectName", project.Name, "projectId", project.ID, "wasRunning", running)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.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(err, "redeploy failed"))+ return common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", err))}return nil}@@ -1468,7 +1471,7 @@ func (s *GitOpsSyncService) pullImageAfterSyncIfConfiguredInternal(ctx context.Cslog.InfoContext(ctx, "Pulling project images after Git sync (project not running)", "projectName", project.Name, "projectId", project.ID)if err := s.projectService.PullProjectImages(ctx, project.ID, io.Discard, actor, credentials); err != nil {slog.ErrorContext(ctx, "failed to pull project images after Git sync", "error", err, "projectId", project.ID)- return common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(err, "post-sync image pull failed"))+ return common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("post-sync image pull failed: %w", err))}return nil}@@ -1545,7 +1548,7 @@ func (s *GitOpsSyncService) GetSyncStatus(ctx context.Context, environmentID, idfunc (s *GitOpsSyncService) CleanupLeakedScratchDirsOnStartup(ctx context.Context) error {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {- return errors.WrapIf(err, "failed to resolve projects directory for gitops scratch cleanup")+ return fmt.Errorf("failed to resolve projects directory for gitops scratch cleanup: %w", err)}entries, err := acfs.List(ctx, projectsDir, "/")@@ -1553,7 +1556,7 @@ func (s *GitOpsSyncService) CleanupLeakedScratchDirsOnStartup(ctx context.Contexif errors.Is(err, fs.ErrNotExist) {return nil}- return errors.WrapIff(err, "failed to list projects directory %s for gitops scratch cleanup", projectsDir)+ return fmt.Errorf("failed to list projects directory %s for gitops scratch cleanup: %w", projectsDir, err)}removed := 0@@ -1584,7 +1587,7 @@ func (s *GitOpsSyncService) CleanupLeakedCloneDirsOnStartup(ctx context.Context)removed, err := s.repoService.PurgeScratchDirs(ctx, 0)if err != nil {- return errors.WrapIf(err, "failed to purge leaked git clone scratch directories")+ return fmt.Errorf("failed to purge leaked git clone scratch directories: %w", err)}if removed > 0 {slog.InfoContext(ctx, "Cleaned up leaked git clone scratch directories on startup", "count", removed)@@ -1597,7 +1600,7 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) eif err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("environment_id NOT IN (SELECT id FROM environments)").Pluck("id", &syncIDs).Error; err != nil {- return errors.WrapIf(err, "failed to list orphaned gitops syncs")+ return fmt.Errorf("failed to list orphaned gitops syncs: %w", err)}if len(syncIDs) == 0 {return nil@@ -1607,10 +1610,10 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) eif err := tx.Model(&projectpkg.Project{}).Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {- return errors.WrapIf(err, "failed to clear orphaned gitops project references")+ return fmt.Errorf("failed to clear orphaned gitops project references: %w", err)}if err := tx.Where("id IN ?", syncIDs).Delete(&projectpkg.GitOpsSync{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete orphaned gitops syncs")+ return fmt.Errorf("failed to delete orphaned gitops syncs: %w", err)}return nil}); err != nil {@@ -1626,7 +1629,7 @@ func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.if err := s.db.WithContext(ctx).Where("sync_directory = ?", true).Find(&syncs).Error; err != nil {- return errors.WrapIf(err, "failed to list directory syncs for startup reconciliation")+ return fmt.Errorf("failed to list directory syncs for startup reconciliation: %w", err)}for i := range syncs {@@ -1674,7 +1677,7 @@ func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id,// Clone the repositoryrepoPath, err := s.repoService.Clone(browseCtx, repository.URL, syncRecord.Branch, authConfig)if err != nil {- return nil, errors.WrapIf(err, "failed to clone repository")+ return nil, fmt.Errorf("failed to clone repository: %w", err)}defer s.repoService.Discard(browseCtx, repoPath)@@ -1755,7 +1758,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 errors.Errorf("%s", errMsg)+ return fmt.Errorf("%s", errMsg)}// markSyncRedeployFailedInternal records a sync where the file sync wrote@@ -1810,7 +1813,7 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, syproject, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, projecttypes.CreateProjectWorkspaceManifest{}, nil, nil, nil, actor, false)if err != nil {if errors.Is(err, projects.ErrProjectDirExists) {- 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"))+ bindingErr := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: 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, s.failSyncAndDisableAutoSyncInternal(ctx, id, result, sync, actor, "GitOps project binding broken", bindingErr)}@@ -1843,7 +1846,7 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, syslog.InfoContext(ctx, "Redeploying newly created project 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 newly created project after Git sync", "error", err, "projectId", project.ID)- return nil, common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(err, "redeploy failed"))+ return nil, common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", err))}} else if err := s.pullImageAfterSyncIfConfiguredInternal(ctx, sync, project, actor); err != nil {return nil, err@@ -1863,7 +1866,7 @@ 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.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s references missing project %s", sync.ID, *sync.ProjectID), "GitOps sync project binding broken"))+ err := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s", sync.ID, *sync.ProjectID))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)@@ -1926,7 +1929,7 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, syncwalkResult, err := s.repoService.WalkDirectory(ctx, repoPath, sync.ComposePath, maxFiles, maxTotalSize, maxBinarySize)if err != nil {- return nil, errors.WrapIf(err, "failed to walk directory")+ return nil, fmt.Errorf("failed to walk directory: %w", err)}slog.InfoContext(ctx, "Directory walk complete",@@ -1954,7 +1957,7 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync}if !composeFound {- return nil, errors.Errorf("compose file %s not found in walked directory", composeFileName)+ return nil, fmt.Errorf("compose file %s not found in walked directory", composeFileName)}return syncFiles, nil@@ -2001,7 +2004,7 @@ func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, syfunc (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, syncFiles []projects.SyncFile) (stage *stagedDirectorySync, err error) {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get projects directory")+ return nil, fmt.Errorf("failed to get projects directory: %w", err)}// The project-root env files are reserved for the three-file override@@ -2012,7 +2015,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncstageLogical, err := acfs.MkdirTemp(ctx, projectsDir, "/", ".gitops-sync-stage-*")if err != nil {- return nil, errors.WrapIf(err, "failed to create staging directory")+ return nil, fmt.Errorf("failed to create staging directory: %w", err)}defer func() {if err != nil {@@ -2048,19 +2051,19 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncif stage.project != nil {staleFiles, staleErr := projects.StaleComposeFiles(ctx, stage.project.Path, stage.composeFileName, stage.syncedFiles)if staleErr != nil {- return nil, errors.WrapIf(staleErr, "failed to detect stale compose files")+ return nil, fmt.Errorf("failed to detect stale compose files: %w", staleErr)}stage.backupScope.Paths = slices.Concat(stage.syncedFiles, stage.oldSyncedFiles, staleFiles,[]string{projects.EffectiveEnvFileName, projects.GitSourceEnvFileName, projects.OverrideEnvFileName})if err := linkProjectIntoStageInternal(stage.project.Path, stage.stagePath, stage.backupScope.Paths); err != nil {- return nil, errors.WrapIf(err, "failed to stage current project files")+ return nil, fmt.Errorf("failed to stage current project files: %w", err)}if _, err := seedStageEnvFromDirInternal(ctx, stage.project.Path, projectsDir, stage.stagePath); err != nil {return nil, err}stage.contentsChanged, err = projects.DirectorySyncContentsChanged(ctx, stage.project.Path, filteredSyncFiles, stage.oldSyncedFiles, stage.composeFileName)if err != nil {- return nil, errors.WrapIf(err, "failed to compare staged directory changes")+ return nil, fmt.Errorf("failed to compare staged directory changes: %w", err)}} else if err := s.seedStageEnvFromCandidateDirInternal(ctx, sync, projectsDir, stage.stagePath); err != nil {return nil, err@@ -2076,7 +2079,7 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncstage.serviceCount, err = s.projectService.ValidateComposeDirectory(ctx, sync.ProjectName, stage.stagePath, stage.composeFileName)if err != nil {- return nil, errors.WrapIf(err, "invalid compose file")+ return nil, fmt.Errorf("invalid compose file: %w", err)}return stage, nil@@ -2089,19 +2092,19 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, syncfunc (s *GitOpsSyncService) applyDirectorySyncInternal(ctx context.Context, targetPath string, stage *stagedDirectorySync) (string, string, error) {if len(stage.oldSyncedFiles) > 0 {if err := projects.CleanupRemovedFiles(ctx, stage.projectsDir, targetPath, stage.oldSyncedFiles, stage.syncedFiles); err != nil {- return "", "", errors.WrapIf(err, "failed to clean removed synced files")+ return "", "", fmt.Errorf("failed to clean removed synced files: %w", err)}}if err := projects.RemoveStaleComposeFiles(ctx, targetPath, stage.composeFileName, stage.syncedFiles); err != nil {- return "", "", errors.WrapIf(err, "failed to remove stale compose files")+ return "", "", fmt.Errorf("failed to remove stale compose files: %w", err)}// Write the repo files (excluding reserved root env files, handled below)// after cleanup so validation sees the final on-disk tree exactly as it// will exist in the managed project.if _, err := projects.WriteSyncedDirectory(ctx, stage.projectsDir, targetPath, stage.syncFiles); err != nil {- return "", "", errors.WrapIf(err, "failed to write staged sync files")+ return "", "", fmt.Errorf("failed to write staged sync files: %w", err)}// Route the project-root .env through the same three-file override merge@@ -2226,21 +2229,21 @@ func partitionReservedRootEnvFilesInternal(ctx context.Context, syncFiles []projfunc seedStageEnvFromDirInternal(ctx context.Context, sourceDir, projectsDir, stagePath string) (projects.ProjectEnvState, error) {state, err := projects.ReadProjectEnvState(sourceDir)if err != nil {- return state, errors.WrapIff(err, "read env files from %s", sourceDir)+ return state, fmt.Errorf("read env files from %s: %w", sourceDir, err)}if state.HasGitSource {if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.GitSourceEnvFileName, state.GitContent); err != nil {- return state, errors.WrapIf(err, "seed stage .env.git")+ return state, fmt.Errorf("seed stage .env.git: %w", err)}}if state.HasOverride {if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.OverrideEnvFileName, state.OverrideContent); err != nil {- return state, errors.WrapIf(err, "seed stage project.env")+ return state, fmt.Errorf("seed stage project.env: %w", err)}}if state.HasEffective {if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, state.DirectContent); err != nil {- return state, errors.WrapIf(err, "seed stage .env")+ return state, fmt.Errorf("seed stage .env: %w", err)}}return state, nil@@ -2260,7 +2263,7 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Conif errors.Is(err, os.ErrNotExist) {return nil}- return errors.WrapIff(err, "inspect pre-existing project directory %s", candidatePath)+ return fmt.Errorf("inspect pre-existing project directory %s: %w", candidatePath, err)}if !info.IsDir() {return nil@@ -2278,10 +2281,10 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Con// Only .env.git and/or project.env exist, so derive .env from them.merged, mergeErr := projects.BuildEffectiveEnvContent(state.GitContent, state.OverrideContent)if mergeErr != nil {- return errors.WrapIf(mergeErr, "build effective env from pre-existing project")+ return fmt.Errorf("build effective env from pre-existing project: %w", mergeErr)}if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, merged); err != nil {- return errors.WrapIf(err, "seed stage .env")+ return fmt.Errorf("seed stage .env: %w", err)}}@@ -2300,7 +2303,7 @@ func (s *GitOpsSyncService) lookupProjectByIDInternal(ctx context.Context, projeif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, errors.WrapIff(err, "failed to get project %s", projectID)+ return nil, false, fmt.Errorf("failed to get project %s: %w", projectID, err)}return &project, true, nil@@ -2312,7 +2315,7 @@ func (s *GitOpsSyncService) lookupProjectByPathInternal(ctx context.Context, proif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, errors.WrapIff(err, "failed to get project by path %s", projectPath)+ return nil, false, fmt.Errorf("failed to get project by path %s: %w", projectPath, err)}return &project, true, nil@@ -2323,7 +2326,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, errors.WrapIff(err, "failed to list GitOps-managed projects for sync %s", sync.ID)+ return nil, fmt.Errorf("failed to list GitOps-managed projects for sync %s: %w", sync.ID, err)}matches := make([]projectpkg.Project, 0, len(managedProjects))@@ -2347,7 +2350,7 @@ func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Cocase 1:return &matches[0], nildefault:- return nil, errors.Errorf("multiple GitOps-managed projects match sync %s; refusing automatic relink", sync.ID)+ return nil, fmt.Errorf("multiple GitOps-managed projects match sync %s; refusing automatic relink", sync.ID)}}@@ -2359,7 +2362,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contentries, err := acfs.List(ctx, projectsDir, "/")if err != nil {- return "", errors.WrapIff(err, "failed to list projects directory %s", projectsDir)+ return "", fmt.Errorf("failed to list projects directory %s: %w", projectsDir, err)}composeFileName := strings.TrimSpace(filepath.Base(sync.ComposePath))@@ -2390,7 +2393,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contmatches = append(matches, candidatePath)}} else if !errors.Is(statErr, fs.ErrNotExist) {- return "", errors.WrapIff(statErr, "failed to inspect recovery candidate %s", composePath)+ return "", fmt.Errorf("failed to inspect recovery candidate %s: %w", composePath, statErr)}}@@ -2400,7 +2403,7 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx contcase 1:return matches[0], nildefault:- return "", errors.Errorf("multiple candidate project directories match sync %s; refusing automatic relink", sync.ID)+ return "", fmt.Errorf("multiple candidate project directories match sync %s; refusing automatic relink", sync.ID)}}@@ -2481,7 +2484,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,project, err := s.findRecoverableManagedProjectInternal(ctx, sync)if err != nil {if establishedBinding {- 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, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err))}return nil, err}@@ -2495,7 +2498,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,project, err = s.recoverProjectFromDirectoryCandidateInternal(ctx, sync)if err != nil {if establishedBinding {- 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, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err))}return nil, err}@@ -2504,7 +2507,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,}if establishedBinding {- 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, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: no unique recovery candidate was found", sync.ID, *sync.ProjectID))}return nil, nil@@ -2515,7 +2518,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, stage *stagedDirectorySync, actor common.User) (*projectpkg.Project, error) {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get projects directory")+ return nil, fmt.Errorf("failed to get projects directory: %w", err)}// Non-suffixing create: a GitOps sync must never mint a "-N" duplicate. Any@@ -2526,27 +2529,27 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.ConteprojectPath, folderName, err := projects.CreateExactDir(ctx, projectsDir, basePath, sync.ProjectName, utils.DirPerm)if err != nil {if errors.Is(err, projects.ErrProjectDirExists) {- 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, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: 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, errors.WrapIf(err, "failed to create project directory")+ return nil, fmt.Errorf("failed to create project directory: %w", err)}projectLogical, err := acfs.LogicalPath(projectsDir, projectPath)if err != nil {- return nil, errors.WrapIf(err, "failed to resolve created project directory")+ return nil, fmt.Errorf("failed to resolve created project directory: %w", err)}if err := acfs.Remove(ctx, projectsDir, projectLogical); err != nil {- return nil, errors.WrapIf(err, "failed to prepare project directory")+ return nil, fmt.Errorf("failed to prepare project directory: %w", err)}if err := acfs.Rename(ctx, projectsDir, stage.stageLogical, projectLogical); err != nil {- return nil, errors.WrapIf(err, "failed to promote staged project directory")+ return nil, fmt.Errorf("failed to promote staged project directory: %w", err)}stage.stagePath = ""if err := os.Chmod(projectPath, utils.DirPerm); err != nil {_ = acfs.RemoveAll(ctx, projectsDir, projectLogical)- return nil, errors.WrapIf(err, "failed to set project directory permissions")+ return nil, fmt.Errorf("failed to set project directory permissions: %w", err)}project := &projectpkg.Project{@@ -2578,18 +2581,18 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte// itself be a symlink, so it is probed and bootstrapped through os.if info, err := os.Stat(projectPath); err == nil {if !info.IsDir() {- return nil, errors.Errorf("project path is not a directory: %s", projectPath)+ return nil, fmt.Errorf("project path is not a directory: %s", projectPath)}} else if errors.Is(err, os.ErrNotExist) {existed = falseif err := os.MkdirAll(projectPath, utils.DirPerm); err != nil {- return nil, errors.WrapIf(err, "failed to recreate project directory")+ return nil, fmt.Errorf("failed to recreate project directory: %w", err)}if err := os.Chmod(projectPath, utils.DirPerm); err != nil {- return nil, errors.WrapIf(err, "failed to set project directory permissions")+ return nil, fmt.Errorf("failed to set project directory permissions: %w", err)}} else {- return nil, errors.WrapIf(err, "failed to inspect current project directory")+ return nil, fmt.Errorf("failed to inspect current project directory: %w", err)}// Rollback must run even after ctx was cancelled: acfs refuses work on a@@ -2602,7 +2605,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Contevar err errorbackup, removeBackup, err = projects.BackupProjectDirectory(ctx, stage.projectsDir, projectPath, ".gitops-backup-*", stage.backupScope)if err != nil {- return nil, errors.WrapIf(err, "failed to back up current project directory")+ return nil, fmt.Errorf("failed to back up current project directory: %w", err)}defer func() {if !keepBackup {@@ -2626,11 +2629,11 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.ContekeepBackup = trueslog.ErrorContext(ctx, "Failed to restore project directory after sync promotion failure; backup kept", "projectPath", projectPath, "backupPath", backup.BackupDir, "error", restoreErr)}- return errors.Combine(cause, errors.WrapIf(restoreErr, "rollback project directory"))+ return errors.Join(cause, fmt.Errorf("rollback project directory: %w", restoreErr))}if _, _, err := s.applyDirectorySyncInternal(ctx, projectPath, stage); err != nil {- return nil, restore(errors.WrapIf(err, "failed to promote staged project directory"))+ return nil, restore(fmt.Errorf("failed to promote staged project directory: %w", err))}if err := s.db.WithContext(ctx).Model(&projectpkg.Project{}).Where("id = ?", project.ID).Updates(map[string]any{@@ -2638,7 +2641,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte"gitops_managed_by": sync.ID,"updated_at": time.Now(),}).Error; err != nil {- return nil, restore(errors.WrapIf(err, "failed to update project metadata after directory sync"))+ return nil, restore(fmt.Errorf("failed to update project metadata after directory sync: %w", err))}return project, nildiff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.goindex 9edd77db8..c69ee73d9 100644--- a/backend/internal/gitops/handler.go+++ b/backend/internal/gitops/handler.go@@ -4,7 +4,6 @@ import ("cmp""context"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -188,7 +187,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(errors.WithMessage(err, "Failed to list GitOps syncs").Error())+ return nil, huma.Error500InternalServerError("Failed to list GitOps syncs: " + err.Error())}return &ListGitOpsSyncsOutput{@@ -215,7 +214,7 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSsync, err := h.syncService.CreateSync(ctx, input.EnvironmentID, input.Body, actor)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create GitOps sync").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create GitOps sync: "+err.Error())}body, mapErr := handlerutil.MapOneAPIResponse[*project.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {@@ -287,7 +286,7 @@ 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 := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update GitOps sync").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update GitOps sync: "+err.Error())}body, mapErr := handlerutil.MapOneAPIResponse[*project.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {@@ -382,7 +381,7 @@ func (h *GitOpsSyncHandler) PreviewBackup(ctx context.Context, input *BackupPrevpreview, err := h.syncService.PreviewBackup(ctx, input.EnvironmentID, input.SyncID)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to preview Git backup").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to preview Git backup: "+err.Error())}return &handlerutil.Out[gitops.BackupPreview]{@@ -398,7 +397,7 @@ func (h *GitOpsSyncHandler) BackupHistory(ctx context.Context, input *BackupHisthistory, err := h.syncService.GetBackupHistory(ctx, input.EnvironmentID, input.SyncID, min(input.Limit, maxBackupHistoryLimit))if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to load Git backup history").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to load Git backup history: "+err.Error())}return &handlerutil.Out[gitops.BackupHistoryResponse]{@@ -414,7 +413,7 @@ func (h *GitOpsSyncHandler) BackupRevision(ctx context.Context, input *BackupRevrevision, err := h.syncService.GetBackupRevision(ctx, input.EnvironmentID, input.SyncID, input.Commit)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to load Git backup revision").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to load Git backup revision: "+err.Error())}return &handlerutil.Out[gitops.BackupRevision]{@@ -432,7 +431,7 @@ func (h *GitOpsSyncHandler) ResolveBackupConflict(ctx context.Context, input *Reresult, err := h.syncService.ResolveBackupConflict(ctx, input.EnvironmentID, input.SyncID, input.Body, actor)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to resolve Git backup conflict").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to resolve Git backup conflict: "+err.Error())}return &handlerutil.Out[gitops.SyncResult]{diff --git a/backend/internal/gitops/service_test.go b/backend/internal/gitops/service_test.goindex 7e1173f23..ff3407ffa 100644--- a/backend/internal/gitops/service_test.go+++ b/backend/internal/gitops/service_test.go@@ -3,13 +3,14 @@ package gitopsimport ("context""encoding/json"+ "errors"+ "fmt""os""path/filepath""strings""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"@@ -24,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/entityjobs""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"francistest "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis/testing"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/gitops"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"@@ -896,11 +898,7 @@ func TestGitOpsSyncService_DirectorySync_RealWalkWithNestedConfig(t *testing.T)- ./logs:/var/log/traefik- ./config/dynamic_config.yml:/etc/traefik/dynamic_config.yml:ro`))- writeFileInternal(t, repoPath, "traefik (nl10)/config/dynamic_config.yml", []byte(`http:- routers:- dashboard:- rule: Host(`+"`"+`traefik.example.com`+"`"+`)-`))+ writeFileInternal(t, repoPath, "traefik (nl10)/config/dynamic_config.yml", []byte("http:\n routers:\n dashboard:\n rule: Host(`traefik.example.com`)\n"))sync := &projectpkg.GitOpsSync{ID: "sync-directory-real-walk",@@ -962,11 +960,7 @@ func TestGitOpsSyncService_DirectorySync_OverwritesExistingDirectoryAtFilePath(t- ./logs:/var/log/traefik- ./config/dynamic_config.yml:/etc/traefik/dynamic_config.yml:ro`))- writeFileInternal(t, repoPath, "traefik (nl10)/config/dynamic_config.yml", []byte(`http:- routers:- dashboard:- rule: Host(`+"`"+`traefik.example.com`+"`"+`)-`))+ writeFileInternal(t, repoPath, "traefik (nl10)/config/dynamic_config.yml", []byte("http:\n routers:\n dashboard:\n rule: Host(`traefik.example.com`)\n"))projectPath := filepath.Join(projectsDir, "traefik-project")require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "config", "dynamic_config.yml"), 0o755))@@ -1872,7 +1866,9 @@ func TestValidateLifecycleConfig_RejectsScriptWithoutSyncDirectoryOnCreate(t *te})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ require.Equal(t, "preDeployScriptPath", fieldErr.Field)}func TestValidateLifecycleConfig_AcceptsScriptWithSyncDirectoryOnCreate(t *testing.T) {@@ -1895,7 +1891,9 @@ func TestValidateLifecycleConfig_RejectsLifecycleHookForSwarmStack(t *testing.T)})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ require.Equal(t, "preDeployScriptPath", fieldErr.Field)require.Contains(t, err.Error(), "project syncs")}@@ -1909,7 +1907,9 @@ func TestValidateLifecycleConfig_RejectsSwarmTargetChangeWithExistingLifecycleHo})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ require.Equal(t, "preDeployScriptPath", fieldErr.Field)require.Contains(t, err.Error(), "project syncs")}@@ -1933,12 +1933,14 @@ func TestValidateLifecycleConfig_RejectsSyncDirectoryToggleOffWhileScriptStillSe})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- require.Contains(t, errors.GetDetails(err), "preDeployScriptPath")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ require.Equal(t, "preDeployScriptPath", fieldErr.Field)}func TestRedeployAfterSyncFailedError_FormatAndUnwrap(t *testing.T) {cause := errors.New("pre-deploy hook bombed")- err := common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(cause, "redeploy failed"))+ err := common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", cause))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")@@ -1967,7 +1969,7 @@ func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {result := &gitops.SyncResult{Success: true}syncedFiles := []string{"compose.yml", "scripts/pre-deploy.sh"}- hookErr := common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(errors.New("pre-deploy hook failed: exit 1"), "redeploy failed"))+ hookErr := common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", errors.New("pre-deploy hook failed: exit 1")))svc.markSyncRedeployFailedInternal(ctx, sync, sync.ID, "abc123", syncedFiles, hookErr, common.User{ID: "user", Username: "tester"}, result)diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.goindex a9e9aac2d..af12d10eb 100644--- a/backend/internal/gitrepo/handler.go+++ b/backend/internal/gitrepo/handler.go@@ -3,7 +3,6 @@ package gitrepoimport ("context"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -94,7 +93,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *Listrepositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list git repositories").Error())+ return nil, huma.Error500InternalServerError("Failed to list git repositories: " + err.Error())}return &handlerutil.Page[gitops.GitRepository]{@@ -208,7 +207,7 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGiactor := handlerutil.CurrentActor(ctx)if err := h.repoService.TestConnection(ctx, input.ID, input.Branch, actor); err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())+ return nil, huma.Error400BadRequest("Failed to test git repository connection: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -225,7 +224,7 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGifunc (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*handlerutil.Out[gitops.BranchesResponse], error) {branches, err := h.repoService.ListBranches(ctx, input.ID)if err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())+ return nil, huma.Error400BadRequest("Failed to test git repository connection: " + err.Error())}return &handlerutil.Out[gitops.BranchesResponse]{@@ -246,7 +245,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(errors.WithMessage(err, "Failed to test git repository connection").Error())+ return nil, huma.Error400BadRequest("Failed to test git repository connection: " + err.Error())}return &handlerutil.Out[gitops.BrowseResponse]{@@ -261,7 +260,7 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilfunc (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync git repositories").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to sync git repositories: "+err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.goindex 9bd940eca..fa2301d41 100644--- a/backend/internal/gitrepo/service.go+++ b/backend/internal/gitrepo/service.go@@ -3,10 +3,10 @@ package gitrepoimport ("cmp""context"+ "errors""fmt""strings"- "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/event"@@ -16,6 +16,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/gitops""github.com/samber/mo""go.getarcane.app/builds/pkg/contextsource"@@ -52,7 +53,7 @@ func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, parout, paginationResp, err := params.PaginateSortAndMapDB[GitRepository, gitops.GitRepository](q, &repositories)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list git repositories")+ return nil, pagination.Response{}, fmt.Errorf("failed to list git repositories: %w", err)}return out, paginationResp, nil@@ -64,7 +65,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, errors.WrapIf(err, "failed to get repository")+ return nil, fmt.Errorf("failed to get repository: %w", err)}return &repository, nil}@@ -75,7 +76,7 @@ func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name strif errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("repository not found")}- return nil, errors.WrapIf(err, "failed to get repository")+ return nil, fmt.Errorf("failed to get repository: %w", err)}return &repository, nil}@@ -102,7 +103,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, errors.WrapIf(err, "failed to list repositories")+ return nil, fmt.Errorf("failed to list repositories: %w", err)}for i := range repositories {@@ -146,7 +147,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req gitops.if req.Token != "" {encrypted, err := crypto.Encrypt(req.Token)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt token")+ return nil, fmt.Errorf("failed to encrypt token: %w", err)}repository.Token = encrypted}@@ -154,7 +155,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req gitops.if req.SSHKey != "" {encrypted, err := crypto.Encrypt(req.SSHKey)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt SSH key")+ return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)}repository.SSHKey = encrypted}@@ -169,7 +170,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req gitops.}if err := s.db.WithContext(ctx).Create(&repository).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create repository")+ return nil, fmt.Errorf("failed to create repository: %w", err)}// Log event@@ -250,7 +251,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,} else {encrypted, err := crypto.Encrypt(*req.Token)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt token")+ return nil, fmt.Errorf("failed to encrypt token: %w", err)}updates["token"] = encrypted}@@ -262,7 +263,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,} else {encrypted, err := crypto.Encrypt(*req.SSHKey)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt SSH key")+ return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)}updates["ssh_key"] = encrypted}@@ -274,7 +275,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, errors.WrapIf(err, "failed to update repository")+ return nil, fmt.Errorf("failed to update repository: %w", err)}// Log event@@ -298,11 +299,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).Table("gitops_syncs").Where("repository_id = ?", id).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to check repository usage")+ return fmt.Errorf("failed to check repository usage: %w", err)}if count > 0 {- return errors.Errorf("repository is used by %d sync configuration(s)", count)+ return fmt.Errorf("repository is used by %d sync configuration(s)", count)}// Get repository info before deleting@@ -312,7 +313,7 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,}if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&GitRepository{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete repository")+ return fmt.Errorf("failed to delete repository: %w", err)}// Log event@@ -389,7 +390,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *Giif repository.Token != "" {token, err := crypto.Decrypt(repository.Token)if err != nil {- return authConfig, errors.WrapIf(err, "failed to decrypt token")+ return authConfig, fmt.Errorf("failed to decrypt token: %w", err)}authConfig.Token = token}@@ -397,7 +398,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *Giif repository.SSHKey != "" {sshKey, err := crypto.Decrypt(repository.SSHKey)if err != nil {- return authConfig, errors.WrapIf(err, "failed to decrypt SSH key")+ return authConfig, fmt.Errorf("failed to decrypt SSH key: %w", err)}authConfig.SSHKey = sshKey}@@ -416,12 +417,12 @@ func (s *GitRepositoryService) GetCommitIdentity(ctx context.Context, repository}armored, err := crypto.Decrypt(repository.SigningKey)if err != nil {- return identity, errors.WrapIf(err, "failed to decrypt signing key")+ return identity, fmt.Errorf("failed to decrypt signing key: %w", err)}passphrase := ""if repository.SigningKeyPassphrase != "" {if passphrase, err = crypto.Decrypt(repository.SigningKeyPassphrase); err != nil {- return identity, errors.WrapIf(err, "failed to decrypt signing key passphrase")+ return identity, fmt.Errorf("failed to decrypt signing key passphrase: %w", err)}}identity.SignKey, err = git.ParseSigningKey(armored, passphrase)@@ -432,16 +433,16 @@ func (s *GitRepositoryService) GetCommitIdentity(ctx context.Context, repository// returns both encrypted for storage.func encryptSigningKeyInternal(armored, passphrase string) (string, string, error) {if _, err := git.ParseSigningKey(armored, passphrase); err != nil {- return "", "", common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "signingKey"))+ return "", "", common.Classify(common.ErrValidation, &base.FieldError{Field: "signingKey", Err: err})}encryptedKey, err := crypto.Encrypt(armored)if err != nil {- return "", "", errors.WrapIf(err, "failed to encrypt signing key")+ return "", "", fmt.Errorf("failed to encrypt signing key: %w", err)}encryptedPassphrase := ""if passphrase != "" {if encryptedPassphrase, err = crypto.Encrypt(passphrase); err != nil {- return "", "", errors.WrapIf(err, "failed to encrypt signing key passphrase")+ return "", "", fmt.Errorf("failed to encrypt signing key passphrase: %w", err)}}return encryptedKey, encryptedPassphrase, nil@@ -464,7 +465,7 @@ func applySigningKeyUpdateInternal(current *GitRepository, req gitops.UpdateRepo} else if current.SigningKey != "" {decrypted, err := crypto.Decrypt(current.SigningKey)if err != nil {- return errors.WrapIf(err, "failed to decrypt signing key")+ return fmt.Errorf("failed to decrypt signing key: %w", err)}armored = decrypted}@@ -477,7 +478,7 @@ func applySigningKeyUpdateInternal(current *GitRepository, req gitops.UpdateRepo} else if current.SigningKeyPassphrase != "" {decrypted, err := crypto.Decrypt(current.SigningKeyPassphrase)if err != nil {- return errors.WrapIf(err, "failed to decrypt signing key passphrase")+ return fmt.Errorf("failed to decrypt signing key passphrase: %w", err)}passphrase = decrypted}@@ -507,7 +508,7 @@ func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]gbranches, err := s.Client.ListBranches(listCtx, repository.URL, authConfig)if err != nil {- return nil, errors.WrapIf(err, "failed to list branches")+ return nil, fmt.Errorf("failed to list branches: %w", err)}var result []gitops.BranchInfo@@ -539,7 +540,7 @@ func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path// Clone the repositoryrepoPath, err := s.Clone(ctx, repository.URL, branch, authConfig)if err != nil {- return nil, errors.WrapIf(err, "failed to clone repository")+ return nil, fmt.Errorf("failed to clone repository: %w", err)}defer s.Discard(ctx, repoPath)@@ -584,7 +585,7 @@ func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems [func (s *GitRepositoryService) getExistingRepositoriesMap(ctx context.Context) (map[string]*GitRepository, error) {var existing []GitRepositoryif err := s.db.WithContext(ctx).Find(&existing).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get existing repositories")+ return nil, fmt.Errorf("failed to get existing repositories: %w", err)}existingMap := make(map[string]*GitRepository)@@ -605,13 +606,13 @@ func (s *GitRepositoryService) processSyncItem(ctx context.Context, item gitops.func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, item gitops.RepositorySync, existing *GitRepository) error {needsUpdate, err := s.checkRepositoryNeedsUpdate(item, existing)if err != nil {- return errors.WrapIff(err, "failed to reconcile repository %s", item.ID)+ return fmt.Errorf("failed to reconcile repository %s: %w", item.ID, err)}if needsUpdate {// Use Save to trigger GORM callbacks including UpdatedAtif err := s.db.WithContext(ctx).Save(existing).Error; err != nil {- return errors.WrapIff(err, "failed to update repository %s", item.ID)+ return fmt.Errorf("failed to update repository %s: %w", item.ID, err)}}@@ -660,14 +661,14 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitif item.Token != "" {encryptedToken, err = crypto.Encrypt(item.Token)if err != nil {- return errors.WrapIff(err, "failed to encrypt token for repository %s", item.ID)+ return fmt.Errorf("failed to encrypt token for repository %s: %w", item.ID, err)}}if item.SSHKey != "" {encryptedSSHKey, err = crypto.Encrypt(item.SSHKey)if err != nil {- return errors.WrapIff(err, "failed to encrypt SSH key for repository %s", item.ID)+ return fmt.Errorf("failed to encrypt SSH key for repository %s: %w", item.ID, err)}}@@ -675,7 +676,7 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitif item.SigningKey != "" {encryptedSigningKey, encryptedPassphrase, err = encryptSigningKeyInternal(item.SigningKey, item.SigningKeyPassphrase)if err != nil {- return errors.WrapIff(err, "failed to encrypt signing key for repository %s", item.ID)+ return fmt.Errorf("failed to encrypt signing key for repository %s: %w", item.ID, err)}}@@ -697,11 +698,9 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitEnabled: item.Enabled,ID: item.ID,}-if err := s.db.WithContext(ctx).Create(&repo).Error; err != nil {- return errors.WrapIff(err, "failed to create repository %s", item.ID)+ return fmt.Errorf("failed to create repository %s: %w", item.ID, err)}-return nil}@@ -709,7 +708,7 @@ func (s *GitRepositoryService) deleteUnsynced(ctx context.Context, existingMap mfor id := range existingMap {if !syncedIDs[id] {if err := s.db.WithContext(ctx).Delete(&GitRepository{}, "id = ?", id).Error; err != nil {- return errors.WrapIff(err, "failed to delete repository %s", id)+ return fmt.Errorf("failed to delete repository %s: %w", id, err)}}}diff --git a/backend/internal/gitrepo/service_test.go b/backend/internal/gitrepo/service_test.goindex a192f45e9..980804434 100644--- a/backend/internal/gitrepo/service_test.go+++ b/backend/internal/gitrepo/service_test.go@@ -2,17 +2,18 @@ package gitrepoimport ("context"+ "errors""fmt""strings""testing"- "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""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/gitops""github.com/libtnb/sqlite""github.com/stretchr/testify/assert"@@ -101,7 +102,9 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWorequire.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "token")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "token", fieldErr.Field)assert.Contains(t, err.Error(), "repository URL")stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)@@ -125,7 +128,9 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyWrequire.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "sshKey")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "sshKey", fieldErr.Field)assert.Contains(t, err.Error(), "repository URL")stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.goindex fe31b9b0c..36063a6f3 100644--- a/backend/internal/image/handler.go+++ b/backend/internal/image/handler.go@@ -3,12 +3,12 @@ package imageimport ("cmp""context"+ "errors""fmt""io""net/http""strings"- "emperror.dev/errors""github.com/containerd/platforms""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"@@ -329,7 +329,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(errors.WithMessage(err, "Failed to list images").Error())+ return nil, huma.Error500InternalServerError("Failed to list images: " + err.Error())}if images == nil {@@ -350,7 +350,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*handlerutil.Out[image.DetailSummary], error) {out, err := h.imageService.GetImageDetail(ctx, input.ImageID)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Image not found").Error())+ return nil, huma.Error404NotFound("Image not found: " + err.Error())}return &handlerutil.Out[image.DetailSummary]{@@ -508,7 +508,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(errors.WithMessage(err, "Failed to remove image").Error())+ return nil, huma.Error500InternalServerError("Failed to remove image: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -566,7 +566,7 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*hif err := h.imageService.PullImage(runtimeCtx, fullImageName, writer, *user, credentials); err != nil {activitylib.FlushWriter(writer)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image pull failed", err)- _, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())+ _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", err.Error())if f, ok := writer.(http.Flusher); ok {f.Flush()}@@ -624,7 +624,7 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (if _, err := h.buildService.BuildImage(runtimeCtx, input.EnvironmentID, input.Body, writer, "", user); err != nil {activitylib.FlushWriter(writer)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image build failed", err)- _, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())+ _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", err.Error())if f, ok := writer.(http.Flusher); ok {f.Flush()}@@ -653,7 +653,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(errors.WithMessage(err, "Failed to list build history").Error())+ return nil, huma.Error500InternalServerError("Failed to list build history: " + err.Error())}if builds == nil {@@ -684,7 +684,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(errors.WithMessage(err, "Failed to retrieve build history").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve build history: " + err.Error())}return &handlerutil.Out[image.BuildRecord]{@@ -705,7 +705,7 @@ func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput)Until: until,})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune images").Error())+ return nil, huma.Error500InternalServerError("Failed to prune images: " + err.Error())}out := image.NewPruneReport(*report)@@ -763,7 +763,7 @@ func resolvePruneImageUntilInternal(input *PruneImagesInput) string {func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*handlerutil.Out[image.UsageCounts], error) {_, counts, err := h.dockerService.GetAllImages(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get image usage counts").Error())+ return nil, huma.Error500InternalServerError("Failed to get image usage counts: " + err.Error())}return &handlerutil.Out[image.UsageCounts]{@@ -786,7 +786,7 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)if httpErr := upload.SessionHTTPError(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to open upload").Error())+ return nil, huma.Error500InternalServerError("Failed to open upload: " + err.Error())}defer cleanup()@@ -795,7 +795,7 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)result, err := h.imageService.LoadImageFromReader(ctx, file, session.Filename, *user, maxSizeBytes)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load image").Error())+ return nil, huma.Error500InternalServerError("Failed to load image: " + err.Error())}return &handlerutil.Out[image.LoadResult]{diff --git a/backend/internal/image/image.go b/backend/internal/image/image.goindex 16295de82..8a225e21f 100644--- a/backend/internal/image/image.go+++ b/backend/internal/image/image.go@@ -3,6 +3,8 @@ package imageimport ("cmp""context"+ "errors"+ "fmt""io""log/slog""maps"@@ -10,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -70,7 +71,7 @@ func NewImageService(db *database.DB, dockerService *docker.DockerClientService,func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypes.DetailSummary, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}var (@@ -87,7 +88,7 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypvar err errorinspectResult, err := dockerClient.ImageInspect(gctx, id)if err != nil {- return errors.WrapIf(err, "inspect not found")+ return fmt.Errorf("inspect not found: %w", err)}inspect = inspectResult.InspectResponsereturn nil@@ -98,7 +99,7 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypimageList, err := dockerClient.ImageList(gctx, client.ImageListOptions{})if err != nil {- return errors.WrapIf(err, "failed to list images")+ return fmt.Errorf("failed to list images: %w", err)}for _, img := range imageList.Items {if img.ID == id {@@ -141,7 +142,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, event.EventTypeImageError, "image", id, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}imageDetails, inspectErr := dockerClient.ImageInspect(ctx, id)@@ -167,7 +168,7 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, uremoved, err := dockerClient.ImageRemove(ctx, id, options)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", id, imageName, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})- return errors.WrapIf(err, "failed to remove image")+ return fmt.Errorf("failed to remove image: %w", err)}idsToDelete := append(getDeletedImageIDsInternal(removed.Items), id)@@ -196,7 +197,7 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, database.JSON{"action": "pull"})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}slog.DebugContext(ctx, "Attempting to pull image", "image", imageName, "externalCredCount", len(externalCreds))@@ -221,7 +222,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, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, database.JSON{"action": "pull"})- return errors.WrapIff(err, "failed to initiate image pull for %s", imageName)+ return fmt.Errorf("failed to initiate image pull for %s: %w", imageName, err)}defer func() { _ = reader.Close() }()@@ -232,10 +233,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, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "pull", "step": "canceled"})- return errors.WrapIff(streamErr, "image pull stream canceled for %s", imageName)+ return fmt.Errorf("image pull stream canceled for %s: %w", imageName, streamErr)}s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "pull", "step": "read_stream"})- return errors.WrapIff(streamErr, "error reading image pull stream for %s", imageName)+ return fmt.Errorf("error reading image pull stream for %s: %w", imageName, streamErr)}slog.Debug("image pull stream completed", "image", imageName)@@ -262,12 +263,12 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressfunc (s *ImageService) ImageLastTagTime(ctx context.Context, imageName string) (time.Time, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return time.Time{}, errors.WrapIf(err, "failed to connect to Docker")+ return time.Time{}, fmt.Errorf("failed to connect to Docker: %w", err)}inspect, err := dockerClient.ImageInspect(ctx, imageName)if err != nil {- return time.Time{}, errors.WrapIff(err, "failed to inspect image %s", imageName)+ return time.Time{}, fmt.Errorf("failed to inspect image %s: %w", imageName, err)}return inspect.Metadata.LastTagTime, nil}@@ -297,14 +298,14 @@ func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, database.JSON{"action": "tag", "target": target})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("image", "", target)()_, err = dockerClient.ImageTag(ctx, client.ImageTagOptions{Source: source, Target: target})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, database.JSON{"action": "tag", "target": target})- return errors.WrapIf(err, "failed to tag image")+ return fmt.Errorf("failed to tag image: %w", err)}metadata := database.JSON{@@ -330,12 +331,12 @@ func (s *ImageService) GetImageHistory(ctx context.Context, imageName string) ([dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}result, err := dockerClient.ImageHistory(ctx, imageName)if err != nil {- return nil, errors.WrapIf(err, "failed to get image history")+ return nil, fmt.Errorf("failed to get image history: %w", err)}items := make([]imagetypes.HistoryItem, 0, len(result.Items))@@ -361,12 +362,12 @@ func (s *ImageService) SearchImages(ctx context.Context, term string) ([]imagetydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}result, err := dockerClient.ImageSearch(ctx, term, client.ImageSearchOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to search images")+ return nil, fmt.Errorf("failed to search images: %w", err)}items := make([]imagetypes.SearchResult, 0, len(result.Items))@@ -390,12 +391,12 @@ func (s *ImageService) ExportImage(ctx context.Context, imageName string) (io.RedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}reader, err := dockerClient.ImageSave(ctx, []string{imageName})if err != nil {- return nil, errors.WrapIf(err, "failed to export image")+ return nil, fmt.Errorf("failed to export image: %w", err)}return reader, nil}@@ -407,7 +408,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.ReaderdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, database.JSON{"action": "load"})- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}// ImageLoad accepts a tar archive reader and optional load options@@ -415,10 +416,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, errors.Errorf("file size exceeds maximum allowed size of %d MB", maxSizeBytes/(1024*1024))+ return nil, fmt.Errorf("file size exceeds maximum allowed size of %d MB", maxSizeBytes/(1024*1024))}s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, database.JSON{"action": "load", "file": fileName})- return nil, errors.WrapIf(err, "failed to load image from tar")+ return nil, fmt.Errorf("failed to load image from tar: %w", err)}defer func() { _ = loadResp.Close() }()@@ -427,7 +428,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.ReaderstreamErr := dockerutils.RenderJSONMessageStream(loadResp, &responseBuilder)if streamErr != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "load", "file": fileName, "step": "read_response"})- return nil, errors.WrapIf(streamErr, "failed to read load response")+ return nil, fmt.Errorf("failed to read load response: %w", streamErr)}result.Stream = responseBuilder.String()@@ -446,7 +447,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, errors.WrapIf(err, "failed to connect to Docker")+ return false, fmt.Errorf("failed to connect to Docker: %w", err)}_, err = dockerClient.ImageInspect(ctx, imageName)@@ -458,7 +459,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, errors.WrapIff(err, "failed to inspect image %s", imageName)+ return false, fmt.Errorf("failed to inspect image %s: %w", imageName, err)}func (s *ImageService) PullOptionsWithAuth(ctx context.Context, imageRef string, externalCreds []containerregistry.Credential) (client.ImagePullOptions, error) {@@ -475,7 +476,7 @@ func (s *ImageService) PullOptionsWithAuth(ctx context.Context, imageRef string,if utilsregistry.IsRegistryMatch(cred.URL, registryHost) {authStr, err := utilsregistry.EncodeAuthHeader(cred.Username, cred.Token, utilsregistry.NormalizeRegistryURL(cred.URL))if err != nil {- return pullOptions, errors.WrapIf(err, "failed to create auth header")+ return pullOptions, fmt.Errorf("failed to create auth header: %w", err)}pullOptions.RegistryAuth = authStr@@ -490,7 +491,7 @@ func (s *ImageService) PullOptionsWithAuth(ctx context.Context, imageRef string,authStr, err := s.registryService.GetRegistryAuthForHost(ctx, registryHost)if err != nil {- return pullOptions, errors.WrapIf(err, "failed to get registry credentials")+ return pullOptions, fmt.Errorf("failed to get registry credentials: %w", err)}if authStr != "" {pullOptions.RegistryAuth = authStr@@ -532,7 +533,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}filterArgs := make(client.Filters)@@ -549,12 +550,12 @@ func (s *ImageService) PruneImages(ctx context.Context, options systemtypes.Prun}filterArgs = filterArgs.Add("until", options.Until)default:- return nil, errors.Errorf("unsupported image prune mode: %s", options.Mode)+ return nil, fmt.Errorf("unsupported image prune mode: %s", options.Mode)}report, err := dockerClient.ImagePrune(ctx, client.ImagePruneOptions{Filters: filterArgs})if err != nil {- return nil, errors.WrapIf(err, "failed to prune images")+ return nil, fmt.Errorf("failed to prune images: %w", err)}pruneReport := report.Report@@ -626,7 +627,7 @@ func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []svar updateRecords []imageupdate.ImageUpdateRecordif err := s.db.WithContext(ctx).Where("container_id = ? AND project_id = ? AND id IN ?", "", "", imageIDs).Find(&updateRecords).Error; err != nil {- return nil, errors.WrapIf(err, "failed to fetch update records")+ return nil, fmt.Errorf("failed to fetch update records: %w", err)}result := make(map[string]*imagetypes.UpdateInfo, len(updateRecords))@@ -694,7 +695,7 @@ func (s *ImageService) GetUpdateInfoByContainers(ctx context.Context, containers}var records []imageupdate.ImageUpdateRecordif err := s.db.WithContext(ctx).Where("container_id IN ?", tagContainerIDs).Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "failed to fetch container update records")+ return nil, fmt.Errorf("failed to fetch container update records: %w", err)}for i := range records {if records[i].PolicyKey == policies[records[i].ContainerID] {@@ -751,7 +752,7 @@ func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs [Where("container_id = ? AND project_id = ? AND tag IN ? AND repository IN ?", "", "", tags, repositoryCandidates).Order("check_time DESC").Find(&updateRecords).Error; err != nil {- return nil, errors.WrapIf(err, "failed to fetch update records by image refs")+ return nil, fmt.Errorf("failed to fetch update records by image refs: %w", err)}index := indexLatestImageUpdateRecordsInternal(updateRecords)@@ -780,7 +781,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatiovar err errorimageList, err := s.dockerService.ListImages(groupCtx)if err != nil {- return errors.WrapIf(err, "failed to list Docker images")+ return fmt.Errorf("failed to list Docker images: %w", err)}dockerImages = imageListreturn nil@@ -793,7 +794,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatiovar err errorcontainerList, err := s.dockerService.ListContainers(groupCtx)if err != nil {- return errors.WrapIf(err, "failed to list containers")+ return fmt.Errorf("failed to list containers: %w", err)}containers = containerListreturn nil@@ -810,7 +811,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 ? OR image_id IN ?", imageIDs, imageIDs).Find(&updateRecords).Error; err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to fetch image update records")+ return nil, pagination.Response{}, fmt.Errorf("failed to fetch image update records: %w", err)}}diff --git a/backend/internal/image/image_attestations.go b/backend/internal/image/image_attestations.goindex 39c799ebd..f901d8148 100644--- a/backend/internal/image/image_attestations.go+++ b/backend/internal/image/image_attestations.go@@ -6,12 +6,13 @@ import ("compress/gzip""context""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"@@ -79,13 +80,13 @@ func (s *ImageService) GetImageAttestations(ctx context.Context, imageName strinref, err := name.ParseReference(resolution.ImageRef, name.WeakValidation)if err != nil {- return nil, errors.WrapIff(err, "parse image reference %q", resolution.ImageRef)+ return nil, fmt.Errorf("parse image reference %q: %w", resolution.ImageRef, err)}remoteOptions := s.remoteOptionsForImageRefInternal(ctx, resolution.ImageRef)remoteDescriptor, err := remote.Get(ref, remoteOptions...)if err != nil {- return nil, errors.WrapIff(err, "get image manifest %q", resolution.ImageRef)+ return nil, fmt.Errorf("get image manifest %q: %w", resolution.ImageRef, err)}if out.SubjectDigest == "" {@@ -146,10 +147,10 @@ func (s *ImageService) resolveImageAttestationReferenceInternal(ctx context.Cont}if isLikelyLocalImageIDInternal(imageName) {- return imageAttestationReferenceInternal{}, errors.Errorf("image %q does not have a registry reference", imageName)+ return imageAttestationReferenceInternal{}, fmt.Errorf("image %q does not have a registry reference", imageName)}if _, err := name.ParseReference(imageName, name.WeakValidation); err != nil {- return imageAttestationReferenceInternal{}, errors.WrapIff(err, "image %q does not have a registry reference", imageName)+ return imageAttestationReferenceInternal{}, fmt.Errorf("image %q does not have a registry reference: %w", imageName, err)}return imageAttestationReferenceInternal{ImageRef: imageName,@@ -207,7 +208,7 @@ func parseAttestationPlatformInternal(value string) (ocispec.Platform, bool, errplatform, err := platforms.Parse(value)if err != nil {- return ocispec.Platform{}, false, errors.WrapIff(err, "invalid platform %q", value)+ return ocispec.Platform{}, false, fmt.Errorf("invalid platform %q: %w", value, err)}return platform, true, nil}@@ -264,12 +265,12 @@ func imageAttestationSubjectsInternal(descriptor *remote.Descriptor, platform ocindex, err := descriptor.ImageIndex()if err != nil {- return nil, nil, errors.WrapIff(err, "read image index %s", descriptor.Digest.String())+ return nil, nil, fmt.Errorf("read image index %s: %w", descriptor.Digest.String(), err)}indexManifest, err := index.IndexManifest()if err != nil {- return nil, nil, errors.WrapIff(err, "read image index manifest %s", descriptor.Digest.String())+ return nil, nil, fmt.Errorf("read image index manifest %s: %w", descriptor.Digest.String(), err)}subjects := make([]imageAttestationSubjectInternal, 0, len(indexManifest.Manifests)+1)@@ -347,19 +348,19 @@ func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, repif shouldIgnoreReferrersErrorInternal(err) {return nil, nil}- return nil, errors.WrapIff(err, "query image referrers for %s", subject.Digest)+ return nil, fmt.Errorf("query image referrers for %s: %w", subject.Digest, err)}manifest, err := referrers.IndexManifest()if err != nil {- return nil, errors.WrapIff(err, "read image referrers for %s", subject.Digest)+ return nil, fmt.Errorf("read image referrers for %s: %w", subject.Digest, err)}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, errors.WrapIff(err, "get image referrer %s", referrer.Digest.String())+ return nil, fmt.Errorf("get image referrer %s: %w", referrer.Digest.String(), err)}referrerImage, err := referrerDescriptor.Image()@@ -384,8 +385,7 @@ func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, rep}func shouldIgnoreReferrersErrorInternal(err error) bool {- var transportErr *transport.Error- if errors.As(err, &transportErr) {+ if transportErr, ok := errors.AsType[*transport.Error](err); ok {return transportErr.StatusCode == http.StatusNotFound || transportErr.StatusCode == http.StatusMethodNotAllowed}return false@@ -398,7 +398,7 @@ func readInlineAttestationsInternal(ctx context.Context, index v1.ImageIndex, suindexManifest, err := index.IndexManifest()if err != nil {- return nil, errors.WrapIf(err, "read image index manifest for inline attestations")+ return nil, fmt.Errorf("read image index manifest for inline attestations: %w", err)}subjectByDigest := make(map[string]imageAttestationSubjectInternal, len(subjects))@@ -423,7 +423,7 @@ func readInlineAttestationsInternal(ctx context.Context, index v1.ImageIndex, suattestationImage, err := index.Image(descriptor.Digest)if err != nil {- return nil, errors.WrapIff(err, "read inline attestation image %s", descriptor.Digest.String())+ return nil, fmt.Errorf("read inline attestation image %s: %w", descriptor.Digest.String(), err)}items, err := readAttestationImageInternal(ctx, attestationImage, descriptor, subject.Platform, query)@@ -450,7 +450,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, errors.WrapIff(err, "read attestation manifest %s", artifactDescriptor.Digest.String())+ return nil, fmt.Errorf("read attestation manifest %s: %w", artifactDescriptor.Digest.String(), err)}artifactType := artifactDescriptor.ArtifactType@@ -486,7 +486,7 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imagelayer, err := attestationImage.LayerByDigest(layerDescriptor.Digest)if err != nil {- return imagetypes.Attestation{}, false, errors.WrapIff(err, "read attestation layer %s", layerDescriptor.Digest.String())+ return imagetypes.Attestation{}, false, fmt.Errorf("read attestation layer %s: %w", layerDescriptor.Digest.String(), err)}rawStatement, err := readAttestationLayerBytesInternal(layer, layerDescriptor.Digest.String())@@ -496,7 +496,7 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imagestatement, err := parseAttestationStatementInternal(rawStatement)if err != nil {- return imagetypes.Attestation{}, false, errors.WrapIff(err, "parse attestation statement %s", layerDescriptor.Digest.String())+ return imagetypes.Attestation{}, false, fmt.Errorf("parse attestation statement %s: %w", layerDescriptor.Digest.String(), err)}statement.PredicateType = cmp.Or(statement.PredicateType, annotationPredicate)if query.PredicateType != "" && statement.PredicateType != query.PredicateType {@@ -527,20 +527,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, errors.WrapIff(err, "open attestation layer %s", digest)+ return nil, fmt.Errorf("open attestation layer %s: %w", digest, err)}rawStatement, readErr := io.ReadAll(reader)closeErr := reader.Close()if readErr != nil {- return nil, errors.WrapIff(readErr, "read attestation layer %s", digest)+ return nil, fmt.Errorf("read attestation layer %s: %w", digest, readErr)}if closeErr != nil {- return nil, errors.WrapIff(closeErr, "close attestation layer %s", digest)+ return nil, fmt.Errorf("close attestation layer %s: %w", digest, closeErr)}statement, err := decompressAttestationStatementInternal(rawStatement)if err != nil {- return nil, errors.WrapIff(err, "decompress attestation layer %s", digest)+ return nil, fmt.Errorf("decompress attestation layer %s: %w", digest, err)}return statement, nil}diff --git a/backend/internal/image/service_test.go b/backend/internal/image/service_test.goindex 698322c55..995b9483f 100644--- a/backend/internal/image/service_test.go+++ b/backend/internal/image/service_test.go@@ -421,7 +421,7 @@ func TestImageServicePullImageRetriesAnonymouslyAfterAuthRejectedInternal(t *teshttp.Error(w, "unauthorized", http.StatusUnauthorized)return}- _, _ = w.Write([]byte(`{"status":"Pulled anonymously"}` + "\n"))+ _, _ = w.Write([]byte("{\"status\":\"Pulled anonymously\"}\n"))}))t.Cleanup(server.Close)diff --git a/backend/internal/imagepatch/handler.go b/backend/internal/imagepatch/handler.goindex 887dc7774..fbd2c5bfe 100644--- a/backend/internal/imagepatch/handler.go+++ b/backend/internal/imagepatch/handler.go@@ -2,9 +2,9 @@ package imagepatchimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -82,7 +82,7 @@ func (h *ImagePatchHandler) PatchImage(ctx context.Context, input *PatchImageInpcase errors.Is(err, common.ErrNotFound):return nil, huma.Error404NotFound(err.Error())default:- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to patch image").Error())+ return nil, huma.Error500InternalServerError("Failed to patch image: " + err.Error())}}@@ -103,7 +103,7 @@ func (h *ImagePatchHandler) ListPatchTargets(ctx context.Context, input *ListPatif errors.Is(err, common.ErrFeatureDisabled) {return nil, handlerutil.FeatureDisabledError(features.VulnerabilityManagement)}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list image patch targets").Error())+ return nil, huma.Error500InternalServerError("Failed to list image patch targets: " + err.Error())}if targets == nil {targets = []imagepatch.PatchTarget{}@@ -127,7 +127,7 @@ func (h *ImagePatchHandler) ListImagePatches(ctx context.Context, input *ListImarecords, paginationResp, err := h.imagePatchService.ListPatches(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list image patches").Error())+ return nil, huma.Error500InternalServerError("Failed to list image patches: " + err.Error())}if records == nil {records = []imagepatch.PatchRecord{}diff --git a/backend/internal/imagepatch/imagepatch.go b/backend/internal/imagepatch/imagepatch.goindex 1976a49e7..dcb7b3b43 100644--- a/backend/internal/imagepatch/imagepatch.go+++ b/backend/internal/imagepatch/imagepatch.go@@ -5,6 +5,8 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors"+ "fmt""log/slog""maps""os"@@ -12,7 +14,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/containerd/platforms""github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/activity"@@ -97,7 +98,7 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strindockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}if err := requireContainerdImageStoreInternal(runCtx, dockerClient); err != nil {return nil, err@@ -105,7 +106,7 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strinimageInspect, err := dockerClient.ImageInspect(runCtx, imageID)if err != nil {- return nil, errors.WrapIf(err, "failed to inspect image")+ return nil, fmt.Errorf("failed to inspect image: %w", err)}if len(imageInspect.RepoTags) == 0 {return nil, common.ErrImageUntagged@@ -178,7 +179,7 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strinActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer(),}if err := s.db.WithContext(runCtx).Create(record).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create image patch record")+ return nil, fmt.Errorf("failed to create image patch record: %w", err)}slog.InfoContext(runCtx, "image patch queued",@@ -384,11 +385,11 @@ func platformPinnedRefInternal(ctx context.Context, imageRef string, target ispefunc resolvePatchedRef(imageRef, patchedTag, suffix string) (string, error) {named, err := reference.ParseNormalizedNamed(imageRef)if err != nil {- return "", errors.WrapIf(err, "failed to parse image reference")+ return "", fmt.Errorf("failed to parse image reference: %w", err)}name, tag, err := copacommon.ResolvePatchedImageName(named, patchedTag, suffix)if err != nil {- return "", errors.WrapIf(err, "failed to resolve patched image name")+ return "", fmt.Errorf("failed to resolve patched image name: %w", err)}return name + ":" + tag, nil}@@ -489,7 +490,7 @@ func (s *ImagePatchService) ListPatches(ctx context.Context, envID string, parampaginationResp, err := pagination.PaginateAndSortDB(params, q, &records)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate image patches")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate image patches: %w", err)}dtos := make([]imagepatch.PatchRecord, 0, len(records))@@ -508,7 +509,7 @@ func (s *ImagePatchService) PatchedRefs(ctx context.Context, envID string) (map[Where("environment_id = ? AND status = ?", envID, string(imagepatch.PatchStatusCompleted)).Distinct().Pluck("patched_ref", &refs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list patched image refs")+ return nil, fmt.Errorf("failed to list patched image refs: %w", err)}set := make(map[string]struct{}, len(refs))for _, ref := range refs {@@ -559,7 +560,7 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,var scans []vulnerability.VulnerabilityScanRecordpaginationResp, err := pagination.PaginateAndSortDB(params, q, &scans)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list patch targets")+ return nil, pagination.Response{}, fmt.Errorf("failed to list patch targets: %w", err)}if len(scans) == 0 {@@ -627,7 +628,7 @@ func (s *ImagePatchService) latestPatchesByImageInternal(ctx context.Context, enWhere("environment_id = ? AND original_image_id IN ?", envID, imageIDs).Order("original_image_id, created_at DESC, id").Find(&patchRows).Error; err != nil {- return nil, nil, errors.WrapIf(err, "failed to load latest image patches")+ return nil, nil, fmt.Errorf("failed to load latest image patches: %w", err)}lastPatchByImageID := make(map[string]*ImagePatchRecord, len(imageIDs))patchedNamesByImageID := make(map[string][]string, len(imageIDs))@@ -659,7 +660,7 @@ func (s *ImagePatchService) latestPatchesByImageInternal(ctx context.Context, enWhere("image_name IN ?", patchedNames).Order("scan_time DESC").Find(&patchScans).Error; err != nil {- return nil, nil, errors.WrapIf(err, "failed to load patched image scans")+ return nil, nil, fmt.Errorf("failed to load patched image scans: %w", err)}latestScanByName := make(map[string]*vulnerability.VulnerabilityScanRecord, len(patchScans))for i := range patchScans {@@ -697,7 +698,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID string}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, 0, errors.WrapIf(err, "failed to connect to Docker")+ return 0, 0, fmt.Errorf("failed to connect to Docker: %w", err)}if err := requireContainerdImageStoreInternal(ctx, dockerClient); err != nil {return 0, 0, err@@ -708,7 +709,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID stringWhere("id IN (?)", s.db.Model(&vulnerability.VulnerabilityReportRecord{}).Select("image_id")).Where("image_name NOT LIKE 'sha256:%' AND image_name NOT LIKE '%<none>%' AND image_name <> id").Find(&scans).Error; err != nil {- return 0, 0, errors.WrapIf(err, "failed to list vulnerability scans")+ return 0, 0, fmt.Errorf("failed to list vulnerability scans: %w", err)}patchedRefs, err := s.PatchedRefs(ctx, envID)@@ -718,7 +719,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID stringfor i := range scans {if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {- return patched, skipped + len(scans) - i, errors.WrapIff(common.ErrFeatureDisabled, "remaining patches stopped because feature %s was disabled", features.VulnerabilityManagement)+ return patched, skipped + len(scans) - i, fmt.Errorf("remaining patches stopped because feature %s was disabled: %w", features.VulnerabilityManagement, common.ErrFeatureDisabled)}scan := &scans[i]@@ -757,7 +758,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID stringfunc requireContainerdImageStoreInternal(ctx context.Context, dockerClient *client.Client) error {info, err := dockerClient.Info(ctx, client.InfoOptions{})if err != nil {- return errors.WrapIf(err, "failed to inspect Docker")+ return fmt.Errorf("failed to inspect Docker: %w", err)}for _, status := range info.Info.DriverStatus {if status[0] == "driver-type" && status[1] == "io.containerd.snapshotter.v1" {diff --git a/backend/internal/imageupdate/handler.go b/backend/internal/imageupdate/handler.goindex 4354b1cfb..cc3674357 100644--- a/backend/internal/imageupdate/handler.go+++ b/backend/internal/imageupdate/handler.go@@ -5,7 +5,6 @@ import ("net/http""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -132,7 +131,7 @@ func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckIruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.imageUpdateService.CheckImageUpdate(runtimeCtx, input.ImageRef)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())+ return nil, huma.Error500InternalServerError("Failed to check image update: " + err.Error())}return &handlerutil.Out[imageupdate.Response]{@@ -151,7 +150,7 @@ func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *ChruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)result, err := h.imageUpdateService.CheckImageUpdateByID(runtimeCtx, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())+ return nil, huma.Error500InternalServerError("Failed to check image update: " + err.Error())}return &handlerutil.Out[imageupdate.Response]{@@ -176,7 +175,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(errors.WithMessage(err, "Failed to check image updates").Error())+ return nil, huma.Error500InternalServerError("Failed to check image updates: " + err.Error())}return &handlerutil.Out[imageupdate.BatchResponse]{@@ -191,7 +190,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(errors.WithMessage(err, "Failed to check all images").Error())+ return nil, huma.Error500InternalServerError("Failed to check all images: " + err.Error())}return &handlerutil.Out[imageupdate.BatchResponse]{@@ -215,7 +214,7 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Getresult, err := h.getUpdateInfoByImageRefs(ctx, imageRefs)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image updates").Error())+ return nil, huma.Error500InternalServerError("Failed to check image updates: " + err.Error())}return &handlerutil.Out[map[string]*imagetypes.UpdateInfo]{@@ -229,7 +228,7 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Getfunc (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*handlerutil.Out[imageupdate.Summary], error) {summary, err := h.imageUpdateService.GetUpdateSummary(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get update summary").Error())+ return nil, huma.Error500InternalServerError("Failed to get update summary: " + err.Error())}return &handlerutil.Out[imageupdate.Summary]{diff --git a/backend/internal/imageupdate/image_update.go b/backend/internal/imageupdate/image_update.goindex 5ede51b22..841f3ec8f 100644--- a/backend/internal/imageupdate/image_update.go+++ b/backend/internal/imageupdate/image_update.go@@ -3,6 +3,7 @@ package imageupdateimport ("cmp""context"+ "errors""fmt""log/slog""maps"@@ -11,8 +12,6 @@ import ("sync""time"- "emperror.dev/emperror"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/activity"@@ -108,7 +107,7 @@ func (s *ImageUpdateService) dockerClientInternal(ctx context.Context) (*client.}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}return dockerClient, nil}@@ -128,7 +127,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, errors.WrapIf(err, "load project build image references")+ return nil, fmt.Errorf("load project build image references: %w", err)}for i := range projectRows {@@ -451,7 +450,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.Cif err != nil {partial := digestResult // may contain auth metadata even on errorif partial == nil {- return nil, nil, errors.WrapIf(err, "failed to get remote digest")+ return nil, nil, fmt.Errorf("failed to get remote digest: %w", err)}return &imageupdate.Response{Error: err.Error(),@@ -461,7 +460,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.CAuthUsername: partial.AuthUsername,AuthRegistry: partial.AuthRegistry,UsedCredential: partial.UsedCredential,- }, nil, errors.WrapIf(err, "failed to get remote digest")+ }, nil, fmt.Errorf("failed to get remote digest: %w", err)}if snapshot == nil {@@ -482,7 +481,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.CUsedCredential: digestResult.UsedCredential,}, nil, nil}- return nil, nil, errors.WrapIf(err, "failed to get local digest")+ return nil, nil, fmt.Errorf("failed to get local digest: %w", err)}}@@ -659,7 +658,7 @@ func (s *ImageUpdateService) getImageRefByIDInternal(ctx context.Context, imageIreturn imageRef, nil}- return "", errors.Errorf("image not found: no local image or running container found for %s", imageID)+ return "", fmt.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) {@@ -702,7 +701,7 @@ func (s *ImageUpdateService) resolveImageRefFromContainers(ctx context.Context,return c.Image, nil}}- return "", errors.Errorf("no container found using image %s", imageID)+ return "", fmt.Errorf("no container found using image %s", imageID)}func (s *ImageUpdateService) getAllImageRefsInternal(ctx context.Context, limit int) ([]string, error) {@@ -715,7 +714,7 @@ func (s *ImageUpdateService) getAllImageRefsInternal(ctx context.Context, limitimageList, err := dockerClient.ImageList(imageCtx, client.ImageListOptions{})cancelImage()if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker images")+ return nil, fmt.Errorf("failed to list Docker images: %w", err)}containerCtx, cancelContainers := s.dockerAPIContextInternal(ctx)@@ -854,7 +853,7 @@ func (s *ImageUpdateService) inspectLocalImageSnapshotInternal(ctx context.ConteinspectResponse, err := dockerClient.ImageInspect(apiCtx, imageRef)if err != nil {- return nil, errors.WrapIf(err, "failed to inspect image")+ return nil, fmt.Errorf("failed to inspect image: %w", err)}var allDigests []string@@ -908,7 +907,7 @@ func (s *ImageUpdateService) CheckImageUpdateByID(ctx context.Context, imageID sif logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageScan, imageID, "", common.SystemUser.ID, common.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, errors.WrapIf(err, "failed to get image reference")+ return nil, fmt.Errorf("failed to get image reference: %w", err)}result, err := s.CheckImageUpdate(ctx, imageRef)if err != nil {@@ -1128,7 +1127,7 @@ func (s *ImageUpdateService) saveUpdateResultByIDInternal(ctx context.Context, idockerImage, err := dockerClient.ImageInspect(apiCtx, imageID)if err != nil {- return errors.WrapIf(err, "failed to inspect image")+ return fmt.Errorf("failed to inspect image: %w", err)}repo, tag := extractRepoAndTagFromImage(dockerImage.InspectResponse)@@ -1160,7 +1159,7 @@ func (s *ImageUpdateService) getImageIDByRef(ctx context.Context, imageRef strininspectResponse, err := dockerClient.ImageInspect(apiCtx, imageRef)if err != nil {- return "", errors.WrapIf(err, "image not found")+ return "", fmt.Errorf("image not found: %w", err)}return inspectResponse.ID, nil}@@ -1172,7 +1171,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,snapshot, err := s.inspectLocalImageSnapshotInternal(ctx, imageRef, nil)if err != nil {- return errors.WrapIf(err, "inspect pulled image")+ return fmt.Errorf("inspect pulled image: %w", err)}checkTime := time.Now().UTC()@@ -1198,13 +1197,13 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,if err := tx.Model(&ImageUpdateRecord{}).Where("id LIKE 'ref::%' AND tag = ? AND repository IN ?", tag, repositories).Update("has_update", false).Error; err != nil {- return errors.WrapIf(err, "clear stale image updates")+ return fmt.Errorf("clear stale image updates: %w", err)}}}if err := savePreparedUpdateResultWithTxInternal(tx, snapshot.ImageID, snapshot.Repository, snapshot.Tag, result); err != nil {- return errors.WrapIf(err, "save pulled image update state")+ return fmt.Errorf("save pulled image update state: %w", err)}return nil@@ -1222,7 +1221,7 @@ func (s *ImageUpdateService) StoredUpdateByImageID(ctx context.Context, imageIDif errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil}- return nil, false, errors.WrapIf(err, "get stored image update by image id")+ return nil, false, fmt.Errorf("get stored image update by image id: %w", err)}return &record, true, nil@@ -1234,7 +1233,7 @@ func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[striif err := s.db.WithContext(ctx).Where("has_update = ? AND notification_sent = ? AND project_id = ?", true, false, "").Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get unnotified updates")+ return nil, fmt.Errorf("failed to get unnotified updates: %w", err)}result := make(map[string]*ImageUpdateRecord)@@ -1250,13 +1249,13 @@ func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[strifunc (s *ImageUpdateService) filterUnnotifiedByMonitoringInternal(ctx context.Context, records map[string]*ImageUpdateRecord) error {dockerClient, err := s.dockerClientInternal(ctx)if err != nil {- return errors.WrapIf(err, "resolve update-check eligibility")+ return fmt.Errorf("resolve update-check eligibility: %w", err)}apiCtx, cancel := s.dockerAPIContextInternal(ctx)listed, err := dockerClient.ContainerList(apiCtx, client.ContainerListOptions{All: true})cancel()if err != nil {- return errors.WrapIf(err, "list containers for update-check eligibility")+ return fmt.Errorf("list containers for update-check eligibility: %w", err)}eligibility := newMonitoringEligibilityInternal(listed.Items)for id, record := range records {@@ -1577,9 +1576,9 @@ 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 panicErr := emperror.Recover(recover()); panicErr != nil {+ if panicErr := utils.PanicToError(recover()); panicErr != nil {// Don't re-panic: the caller is the long-lived watcher goroutine.- err = errors.WrapIf(panicErr, "image update check panicked")+ err = fmt.Errorf("image update check panicked: %w", panicErr)slog.ErrorContext(ctx, "image update check panicked", "activityId", activityID, "error", err)}if err != nil {@@ -1615,7 +1614,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefscomposeBuildRefs, composeErr := s.composeBuildImageRefsInternal(scanCtx)if composeErr != nil {- err = errors.WrapIf(composeErr, "prepare compose build image references")+ err = fmt.Errorf("prepare compose build image references: %w", composeErr)return results, err}@@ -1636,8 +1635,8 @@ 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 panicErr := emperror.Recover(recover()); panicErr != nil {- checkErr = errors.WrapIf(panicErr, "image update check panicked")+ if panicErr := utils.PanicToError(recover()); panicErr != nil {+ checkErr = fmt.Errorf("image update check panicked: %w", panicErr)slog.ErrorContext(groupCtx, "image update check worker panicked", "activityId", activityID, "imageRef", img.canonicalRef, "error", checkErr)}}()@@ -1647,7 +1646,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 = errors.WrapIff(err, "image update check timed out after %s", timeouts.DefaultImageUpdateScan)+ err = fmt.Errorf("image update check timed out after %s: %w", timeouts.DefaultImageUpdateScan, err)}slog.ErrorContext(ctx, "Batch check error", "error", err)return results, err@@ -1715,7 +1714,7 @@ func (s *ImageUpdateService) SendBatchUpdateNotifications(ctx context.Context) eswitch {case err != nil:slog.WarnContext(ctx, "Failed to get unnotified updates", "error", err.Error())- return errors.WrapIf(err, "flush pending update notifications")+ return fmt.Errorf("flush pending update notifications: %w", err)case len(unnotifiedUpdates) > 0:updatesToNotify := make(map[string]*imageupdate.Response)imageIDsToMark := make([]string, 0, len(unnotifiedUpdates))@@ -1765,7 +1764,7 @@ func (s *ImageUpdateService) SendBatchUpdateNotifications(ctx context.Context) efunc (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, errors.WrapIf(err, "failed to get image references")+ return nil, fmt.Errorf("failed to get image references: %w", err)}if len(imageRefs) == 0 {@@ -1791,7 +1790,7 @@ func (s *ImageUpdateService) DeleteRecordsForImages(ctx context.Context, imageIDreturn nil}if err := s.db.WithContext(ctx).Where("id IN ? OR image_id IN ?", imageIDs, imageIDs).Delete(&ImageUpdateRecord{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete image update records")+ return fmt.Errorf("failed to delete image update records: %w", err)}return nil}@@ -1819,7 +1818,7 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {}imageResult := imageScoped.Delete(&ImageUpdateRecord{})if imageResult.Error != nil {- return errors.WrapIf(imageResult.Error, "failed to delete orphaned records")+ return fmt.Errorf("failed to delete orphaned records: %w", imageResult.Error)}containers, err := s.dockerService.ListContainers(ctx)@@ -1836,7 +1835,7 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {}containerResult := containerScoped.Delete(&ImageUpdateRecord{})if containerResult.Error != nil {- return errors.WrapIf(containerResult.Error, "failed to delete orphaned container records")+ return fmt.Errorf("failed to delete orphaned container records: %w", containerResult.Error)}if deleted := imageResult.RowsAffected + containerResult.RowsAffected; deleted > 0 {diff --git a/backend/internal/imageupdate/tag_updates.go b/backend/internal/imageupdate/tag_updates.goindex f2e603cf9..2438516fc 100644--- a/backend/internal/imageupdate/tag_updates.go+++ b/backend/internal/imageupdate/tag_updates.go@@ -2,13 +2,13 @@ package imageupdateimport ("context"+ "errors""fmt""log/slog""slices""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -166,7 +166,7 @@ func (s *ImageUpdateService) checkContainerTagUpdatesInternal(ctx context.Contexlisted, err := dockerClient.ContainerList(apiCtx, client.ContainerListOptions{All: true})cancel()if err != nil {- return results, errors.WrapIf(err, "list containers for tag update checks")+ return results, fmt.Errorf("list containers for tag update checks: %w", err)}// This engine only reads. Containers excluded from automatic installationdiff --git a/backend/internal/job/activity.go b/backend/internal/job/activity.goindex 3c6907150..ab7464183 100644--- a/backend/internal/job/activity.go+++ b/backend/internal/job/activity.go@@ -2,10 +2,10 @@ package jobimport ("context"+ "errors""strings""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/types/v2/meta"st "github.com/getarcaneapp/arcane/types/v2/scheduler"diff --git a/backend/internal/job/execution.go b/backend/internal/job/execution.goindex 75a637e45..50f7e96f3 100644--- a/backend/internal/job/execution.go+++ b/backend/internal/job/execution.go@@ -3,11 +3,11 @@ package jobimport ("cmp""context"+ "errors""log/slog""net""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"@@ -140,8 +140,7 @@ func (s *JobService) executeRunInternal(ctx context.Context, run st.Run) (st.Out}func classifyOutcomeInternal(jobID string, outcome st.Outcome, err error) (st.Outcome, error) {- var resultErr *st.OutcomeError- if errors.As(err, &resultErr) {+ if resultErr, ok := errors.AsType[*st.OutcomeError](err); ok {return resultErr.Outcome, err}if err == nil {diff --git a/backend/internal/job/remote.go b/backend/internal/job/remote.goindex 1bd80a7e4..2da9e5f45 100644--- a/backend/internal/job/remote.go+++ b/backend/internal/job/remote.go@@ -3,12 +3,12 @@ package jobimport ("context""encoding/json/v2"+ "errors""net/http""net/url""sort""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/types/v2/jobschedule"@@ -208,9 +208,9 @@ func (s *JobService) RetryRemoteRun(ctx context.Context, environmentID, jobID, r}var (- errRemoteIneligibleInternal = errors.Sentinel("Remote job is disabled or no longer eligible")- errRemoteReceiptMissingInternal = errors.Sentinel("Agent no longer has the delivery receipt; verify the operation before retrying")- errRemoteRetryUncertainInternal = errors.Sentinel("Remote retry acknowledgement was lost; inspect the agent before retrying again")+ errRemoteIneligibleInternal = errors.New("Remote job is disabled or no longer eligible") //nolint:staticcheck // Preserve the existing error message.+ errRemoteReceiptMissingInternal = errors.New("Agent no longer has the delivery receipt; verify the operation before retrying") //nolint:staticcheck // Preserve the existing error message.+ errRemoteRetryUncertainInternal = errors.New("Remote retry acknowledgement was lost; inspect the agent before retrying again") //nolint:staticcheck // Preserve the existing error message.)func remoteJobEligibleInternal(jobs []jobschedule.JobStatus, id string) bool {@@ -258,7 +258,7 @@ func (s *JobService) admitRemoteInternal(ctx context.Context, run st.Run, cataloreturn st.Run{}, err}if accepted.RunID != run.ID {- return st.Run{}, errors.New("Agent returned an inconsistent delivery receipt")+ return st.Run{}, errors.New("Agent returned an inconsistent delivery receipt") //nolint:staticcheck // Preserve the existing error message.}return st.Run{ID: run.ID, JobID: run.JobID, Status: accepted.Status, Outcome: st.Outcome{Status: accepted.Status}}, nil}@@ -278,7 +278,7 @@ func (s *JobService) retryDeliveryInternal(ctx context.Context, run st.Run, pathreturn st.Run{}, err}if retried.ID != run.ID || retried.JobID != run.JobID {- return st.Run{}, errors.New("Agent returned an inconsistent retry receipt")+ return st.Run{}, errors.New("Agent returned an inconsistent retry receipt") //nolint:staticcheck // Preserve the existing error message.}return retried, nil}diff --git a/backend/internal/job/remote_history.go b/backend/internal/job/remote_history.goindex 4549d9392..0a60fb4d7 100644--- a/backend/internal/job/remote_history.go+++ b/backend/internal/job/remote_history.go@@ -2,12 +2,12 @@ package jobimport ("context"+ "errors""net/http""net/url""sort""strconv"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"st "github.com/getarcaneapp/arcane/types/v2/scheduler"diff --git a/backend/internal/job/remote_resolution.go b/backend/internal/job/remote_resolution.goindex 28c76bd66..e48e9c16b 100644--- a/backend/internal/job/remote_resolution.go+++ b/backend/internal/job/remote_resolution.go@@ -3,11 +3,11 @@ package jobimport ("context""encoding/json/v2"+ "errors""net/http""net/url""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"st "github.com/getarcaneapp/arcane/types/v2/scheduler")diff --git a/backend/internal/job/remote_resolution_test.go b/backend/internal/job/remote_resolution_test.goindex a0a2d6c0d..59cf768fd 100644--- a/backend/internal/job/remote_resolution_test.go+++ b/backend/internal/job/remote_resolution_test.go@@ -9,7 +9,6 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -55,7 +54,7 @@ func TestResolveRemoteRunConfirmsOwnerAfterLostResponse(t *testing.T) {assert.NoError(t, writeErr)}))defer server.Close()- require.NoError(t, db.Create(&environment.Environment{BaseModel: database.BaseModel{ID: "remote"}, Name: "agent", ApiUrl: server.URL, Enabled: true}).Error)+ require.NoError(t, db.Create(&environment.Environment{ID: "remote", Name: "agent", ApiUrl: server.URL, Enabled: true}).Error)svc := &JobService{runs: q, environment: environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)}ctx := context.WithValue(t.Context(), middleware.ContextKeyUserPermissions, authz.EnvironmentPermissionSet("remote"))_, err = svc.ResolveRun(ctx, "remote", local.JobID, local.ID, "operator")diff --git a/backend/internal/job/resolution.go b/backend/internal/job/resolution.goindex d66c7d8b4..a06bb8007 100644--- a/backend/internal/job/resolution.go+++ b/backend/internal/job/resolution.go@@ -2,8 +2,8 @@ package jobimport ("context"+ "errors"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"diff --git a/backend/internal/job/run_routes.go b/backend/internal/job/run_routes.goindex 6e6f23cec..737b35c40 100644--- a/backend/internal/job/run_routes.go+++ b/backend/internal/job/run_routes.go@@ -2,10 +2,10 @@ package jobimport ("context"+ "errors""net/http""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -109,8 +109,7 @@ func (h *JobSchedulesHandler) RestartWorker(ctx context.Context, input *jobsched}func jobHTTPErrorInternal(err error) error {- var status huma.StatusError- if errors.As(err, &status) {+ if _, ok := errors.AsType[huma.StatusError](err); ok {return err}if errors.Is(err, runs.ErrRunNotFound) {diff --git a/backend/internal/job/runtime_status.go b/backend/internal/job/runtime_status.goindex 16b05b8f8..919d6dc63 100644--- a/backend/internal/job/runtime_status.go+++ b/backend/internal/job/runtime_status.go@@ -2,11 +2,11 @@ package jobimport ("context"+ "fmt""slices""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/types/v2/jobschedule"st "github.com/getarcaneapp/arcane/types/v2/scheduler")@@ -16,7 +16,7 @@ func (s *JobService) addRuntimeStatusInternal(ctx context.Context, environmentIDif s.runs != nil {records, err := s.runs.Records(ctx)if err != nil {- return errors.WrapIf(err, "load durable job status")+ return fmt.Errorf("load durable job status: %w", err)}for _, record := range records {if record.EnvironmentID == environmentID {diff --git a/backend/internal/job/service.go b/backend/internal/job/service.goindex 5db4b2e3b..30b716016 100644--- a/backend/internal/job/service.go+++ b/backend/internal/job/service.go@@ -3,12 +3,13 @@ package jobimport ("cmp""context"+ "errors"+ "fmt""log/slog""sort""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -137,7 +138,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedulecontinue}if _, err := parser.Parse(*field.update); err != nil {- return jobschedule.Config{}, errors.WrapIff(err, "invalid cron expression for %s", field.key)+ return jobschedule.Config{}, fmt.Errorf("invalid cron expression for %s: %w", field.key, err)}}@@ -160,14 +161,12 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedulereturn s.GetJobSchedules(ctx), nil}if err := s.settings.UpdateSettingValues(ctx, valuesToUpdate); err != nil {- return jobschedule.Config{}, errors.WrapIf(err, "failed to update job schedules")+ return jobschedule.Config{}, fmt.Errorf("failed to update job schedules: %w", err)}if err := s.RescheduleJobsForSettingKeys(ctx, changedKeys); err != nil {restoreErr := s.restoreJobSchedulesInternal(ctx, previousValues, changedKeys)- return jobschedule.Config{}, errors.Combine(errors.- WrapIf(err, "failed to apply job schedule update"), restoreErr,- )+ return jobschedule.Config{}, errors.Join(fmt.Errorf("failed to apply job schedule update: %w", err), restoreErr)}return s.GetJobSchedules(ctx), nil@@ -200,7 +199,7 @@ func (s *JobService) RescheduleJobsForSettingKeys(ctx context.Context, changedKe}}- return errors.Combine(rescheduleErrors...)+ return errors.Join(rescheduleErrors...)}// jobRescheduleContextInternal prefers the app lifecycle context so cron jobs@@ -237,23 +236,23 @@ func (s *JobService) rescheduleAffectedJobInternal(ctx context.Context, jobID stjob, ok := s.scheduler.GetJob(jobID)if !ok {- return errors.Errorf("job %s not found in scheduler", jobID)+ return fmt.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 errors.WrapIff(err, "reschedule job %s", jobID)+ return fmt.Errorf("reschedule job %s: %w", jobID, err)}runtimeState, ok := s.scheduler.GetJobRuntimeState(jobID)if !ok {- return errors.Errorf("job %s has no runtime scheduler state", jobID)+ return fmt.Errorf("job %s has no runtime scheduler state", jobID)}expectedSchedule := job.Schedule(rescheduleCtx)if runtimeState.Schedule != expectedSchedule {- return errors.Errorf("job %s runtime schedule %q does not match requested schedule %q", jobID, runtimeState.Schedule, expectedSchedule)+ return fmt.Errorf("job %s runtime schedule %q does not match requested schedule %q", jobID, runtimeState.Schedule, expectedSchedule)}return nil}@@ -268,11 +267,11 @@ func (s *JobService) restoreJobSchedulesInternal(ctx context.Context, previousVaupdates = append(updates, libarcane.SettingUpdate{Key: key, Value: value})}if err := s.settings.UpdateSettingValues(ctx, updates); err != nil {- return errors.WrapIf(err, "failed to restore previous job schedules")+ return fmt.Errorf("failed to restore previous job schedules: %w", err)}if err := s.RescheduleJobsForSettingKeys(ctx, changedKeys); err != nil {- return errors.WrapIf(err, "failed to restore runtime job schedules")+ return fmt.Errorf("failed to restore runtime job schedules: %w", err)}return nildiff --git a/backend/internal/job/service_test.go b/backend/internal/job/service_test.goindex cf719d2ae..b3356f246 100644--- a/backend/internal/job/service_test.go+++ b/backend/internal/job/service_test.go@@ -2,10 +2,10 @@ package jobimport ("context"+ "errors""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"@@ -355,8 +355,8 @@ func TestJobService_Submit_PersistsImageUpdateWatcherRun(t *testing.T) {jobSvc := newJobServiceForTestInternal(t, db, settingsSvc, &config.Config{})jobSvc.SetScheduler(ctx, scheduler)require.NoError(t, db.AutoMigrate(&common.User{}, &role.Role{}, &role.UserRoleAssignment{}))- require.NoError(t, db.Create(&common.User{BaseModel: database.BaseModel{ID: "operator"}, Username: "operator"}).Error)- require.NoError(t, db.Create(&role.Role{BaseModel: database.BaseModel{ID: "jobs-manager"}, Name: "Jobs manager", Permissions: database.StringSlice{authz.PermJobsManage}}).Error)+ require.NoError(t, db.Create(&common.User{ID: "operator", Username: "operator"}).Error)+ require.NoError(t, db.Create(&role.Role{ID: "jobs-manager", Name: "Jobs manager", Permissions: database.StringSlice{authz.PermJobsManage}}).Error)require.NoError(t, db.Create(&role.UserRoleAssignment{UserID: "operator", RoleID: "jobs-manager"}).Error)jobSvc.roles = role.NewRoleService(db)run, err := jobSvc.Submit(ctx, schedulertypes.Request{JobID: "image-polling", EnvironmentID: "0", Trigger: "manual", RequestedBy: "operator"})diff --git a/backend/internal/kv/service.go b/backend/internal/kv/service.goindex b72747934..b38e31746 100644--- a/backend/internal/kv/service.go+++ b/backend/internal/kv/service.go@@ -2,11 +2,12 @@ package kvimport ("context"+ "errors"+ "fmt""strconv""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""gorm.io/gorm""gorm.io/gorm/clause"@@ -28,7 +29,7 @@ func (s *KVService) Get(ctx context.Context, key string) (string, bool, error) {return "", false, nil}if err != nil {- return "", false, errors.WrapIff(err, "failed to load kv entry %q", key)+ return "", false, fmt.Errorf("failed to load kv entry %q: %w", key, err)}return entry.Value, true, nil@@ -43,7 +44,7 @@ func (s *KVService) Set(ctx context.Context, key, value string) error {}).Create(&entry).Errorif err != nil {- return errors.WrapIff(err, "failed to upsert kv entry %q", key)+ return fmt.Errorf("failed to upsert kv entry %q: %w", key, err)}return nil@@ -51,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(&KVEntry{}, "key = ?", key).Error; err != nil {- return errors.WrapIff(err, "failed to delete kv entry %q", key)+ return fmt.Errorf("failed to delete kv entry %q: %w", key, err)}return nil}@@ -60,7 +61,7 @@ func (s *KVService) ListByPrefix(ctx context.Context, prefix string) ([]KVEntry,var entries []KVEntryescapedPrefix := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(prefix)if err := s.db.WithContext(ctx).Where("key LIKE ? ESCAPE '\\'", escapedPrefix+"%").Find(&entries).Error; err != nil {- return nil, errors.WrapIff(err, "failed to list kv entries with prefix %q", prefix)+ return nil, fmt.Errorf("failed to list kv entries with prefix %q: %w", prefix, err)}return entries, nil}@@ -75,7 +76,7 @@ func (s *KVService) GetTyped[T any](ctx context.Context, key string, defaultValuparsedValue, err := parse(rawValue)if err != nil {- return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as %T", key, defaultValue)+ return defaultValue, fmt.Errorf("failed to parse kv entry %q as %T: %w", key, defaultValue, err)}return parsedValue, nil@@ -113,7 +114,7 @@ func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64)currentValue, parseErr := strconv.ParseInt(entry.Value, 10, 64)if parseErr != nil {- return errors.WrapIff(parseErr, "failed to parse kv entry %q as int64", key)+ return fmt.Errorf("failed to parse kv entry %q as int64: %w", key, parseErr)}nextValue = currentValue + delta@@ -121,7 +122,7 @@ func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64)return tx.Save(&entry).Error})if err != nil {- return 0, errors.WrapIff(err, "failed to increment kv entry %q", key)+ return 0, fmt.Errorf("failed to increment kv entry %q: %w", key, err)}return nextValue, nil@@ -130,11 +131,17 @@ func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64)// CreateIfAbsent atomically creates an entry without replacing an existing value.func (s *KVService) CreateIfAbsent(ctx context.Context, key, value string) (bool, error) {result := s.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&KVEntry{Key: key, Value: value})- return result.RowsAffected == 1, errors.WrapIf(result.Error, "create kv entry")+ if err := result.Error; err != nil {+ return result.RowsAffected == 1, fmt.Errorf("create kv entry: %w", err)+ }+ return result.RowsAffected == 1, nil}// CompareAndSwap updates only the exact value read by the caller.func (s *KVService) CompareAndSwap(ctx context.Context, key, previous, next string) (bool, error) {result := s.db.WithContext(ctx).Model(&KVEntry{}).Where("key = ? AND value = ?", key, previous).Updates(map[string]any{"value": next, "updated_at": time.Now()})- return result.RowsAffected == 1, errors.WrapIf(result.Error, "compare and swap kv entry")+ if err := result.Error; err != nil {+ return result.RowsAffected == 1, fmt.Errorf("compare and swap kv entry: %w", err)+ }+ return result.RowsAffected == 1, nil}diff --git a/backend/internal/middleware/activity_batch.go b/backend/internal/middleware/activity_batch.godeleted file mode 100644index 03b318446..000000000--- a/backend/internal/middleware/activity_batch.go+++ /dev/null@@ -1,21 +0,0 @@-package middleware--import (- "strings"-- "github.com/danielgtaylor/huma/v2"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"-)--// NewActivityBatchID lifts the client-supplied activity batch ID header into the-// request context so activities spawned by one logical bulk action can be-// grouped without threading the ID through every handler. Invalid values are-// ignored by utils.WithActivityBatchID.-func NewActivityBatchID() func(ctx huma.Context, next func(huma.Context)) {- return func(ctx huma.Context, next func(huma.Context)) {- if batchID := strings.TrimSpace(ctx.Header(HeaderActivityBatchID)); batchID != "" {- ctx = huma.WithContext(ctx, utils.WithActivityBatchID(ctx.Context(), batchID))- }- next(ctx)- }-}diff --git a/backend/internal/middleware/context.go b/backend/internal/middleware/context.goindex eb19f433b..e99d0d29a 100644--- a/backend/internal/middleware/context.go+++ b/backend/internal/middleware/context.go@@ -2,8 +2,11 @@ package middlewareimport ("context"+ "strings"+ "github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils")const (@@ -68,3 +71,16 @@ func GetRemoteAddrFromContext(ctx context.Context) string {remoteAddr, _ := ctx.Value(ContextKeyRemoteAddr).(string)return remoteAddr}++// NewActivityBatchID lifts the client-supplied activity batch ID header into the+// request context so activities spawned by one logical bulk action can be+// grouped without threading the ID through every handler. Invalid values are+// ignored by utils.WithActivityBatchID.+func NewActivityBatchID() func(ctx huma.Context, next func(huma.Context)) {+ return func(ctx huma.Context, next func(huma.Context)) {+ if batchID := strings.TrimSpace(ctx.Header(HeaderActivityBatchID)); batchID != "" {+ ctx = huma.WithContext(ctx, utils.WithActivityBatchID(ctx.Context(), batchID))+ }+ next(ctx)+ }+}diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 25ad1991a..314a68d7c 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -4,6 +4,8 @@ import ("bytes""context""encoding/json/v2"+ "errors"+ "fmt""io""log/slog""mime"@@ -15,7 +17,6 @@ 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"@@ -156,7 +157,7 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) eif !enabled {return c.JSON(http.StatusBadRequest, map[string]any{"success": false,- "data": map[string]any{"error": errors.New("Environment is disabled").Error()},+ "data": map[string]any{"error": errors.New("Environment is disabled").Error()}, //nolint:staticcheck // Preserve the existing error message.})}@@ -341,7 +342,7 @@ func proxiedVolumeWorkspacePermissionsInternal(request *http.Request) ([]string,// System temp scratch for the multipart replay buffer: no acfs root exists for it.captured, err := os.CreateTemp("", "arcane-volume-workspace-manifest-*")if err != nil {- return nil, errors.WrapIf(err, "create workspace manifest buffer")+ return nil, fmt.Errorf("create workspace manifest buffer: %w", err)}defer func() {_, _ = captured.Seek(0, io.SeekStart)@@ -357,28 +358,28 @@ func proxiedVolumeWorkspacePermissionsInternal(request *http.Request) ([]string,for {part, nextErr := reader.NextPart()if nextErr != nil {- return nil, errors.WrapIf(nextErr, "find workspace manifest part")+ return nil, fmt.Errorf("find workspace manifest part: %w", nextErr)}if part.FormName() != "manifest" || part.FileName() != "" {if closeErr := part.Close(); closeErr != nil {- return nil, errors.WrapIf(closeErr, "skip multipart field before workspace manifest")+ return nil, fmt.Errorf("skip multipart field before workspace manifest: %w", closeErr)}continue}manifestJSON, readErr := io.ReadAll(io.LimitReader(part, maxProxiedWorkspaceManifestBytes+1))closeErr := part.Close()if readErr != nil {- return nil, errors.WrapIf(readErr, "read workspace manifest")+ return nil, fmt.Errorf("read workspace manifest: %w", readErr)}if closeErr != nil {- return nil, errors.WrapIf(closeErr, "close workspace manifest part")+ return nil, fmt.Errorf("close workspace manifest part: %w", closeErr)}if len(manifestJSON) > maxProxiedWorkspaceManifestBytes {return nil, errors.New("workspace manifest is too large")}var manifest volumetypes.WorkspaceUpdateManifestif err := json.Unmarshal(manifestJSON, &manifest); err != nil {- return nil, errors.WrapIf(err, "decode workspace manifest")+ return nil, fmt.Errorf("decode workspace manifest: %w", err)}required, valid := authz.VolumeWorkspaceRequiredPermissions(manifest.FileChanges)if !valid {@@ -404,8 +405,8 @@ func proxiedGitOpsSyncPermissionsInternal(request *http.Request, method, suffixbody, readErr := io.ReadAll(io.LimitReader(request.Body, maxProxiedGitOpsSyncBodyBytes+1))closeErr := request.Body.Close()- if err := errors.Combine(readErr, closeErr); err != nil {- return nil, errors.WrapIf(err, "read gitops sync body")+ if err := errors.Join(readErr, closeErr); err != nil {+ return nil, fmt.Errorf("read gitops sync body: %w", err)}if len(body) > maxProxiedGitOpsSyncBodyBytes {return nil, errors.New("gitops sync body is too large")@@ -420,12 +421,12 @@ func proxiedGitOpsSyncPermissionsInternal(request *http.Request, method, suffixvar items []syncBodyInternalif isImport {if err := json.Unmarshal(body, &items); err != nil {- return nil, errors.WrapIf(err, "decode gitops sync import body")+ return nil, fmt.Errorf("decode gitops sync import body: %w", err)}} else {var single syncBodyInternalif err := json.Unmarshal(body, &single); err != nil {- return nil, errors.WrapIf(err, "decode gitops sync body")+ return nil, fmt.Errorf("decode gitops sync body: %w", err)}items = []syncBodyInternal{single}}@@ -467,7 +468,7 @@ func (b *proxiedReplayBodyInternal) Close() error {originalErr := b.original.Close()// System temp scratch: no acfs root exists for it.removeErr := os.Remove(b.path)- return errors.Combine(capturedErr, originalErr, removeErr)+ return errors.Join(capturedErr, originalErr, removeErr)}func (m *EnvironmentMiddleware) proxyActiveEdgeTunnelInternal(c *echo.Context, envID string, accessToken *string) (bool, error) {@@ -706,7 +707,7 @@ func (m *EnvironmentMiddleware) proxyHTTP(c *echo.Context, target string, accessreq, err := m.createProxyRequest(c, target, accessToken)if err != nil {- errMessage := errors.WithMessage(err, "Failed to create proxy request").Error()+ errMessage := "Failed to create proxy request: " + err.Error()if errors.Is(err, common.ErrEnvironmentInvalidProxyTarget) {errMessage = err.Error()}@@ -720,7 +721,7 @@ func (m *EnvironmentMiddleware) proxyHTTP(c *echo.Context, target string, accessif err != nil {return c.JSON(http.StatusBadGateway, map[string]any{"success": false,- "data": map[string]any{"error": errors.WithMessage(err, "Proxy request failed").Error()},+ "data": map[string]any{"error": "Proxy request failed: " + err.Error()},})}defer func() { _ = resp.Body.Close() }()@@ -733,7 +734,7 @@ func (m *EnvironmentMiddleware) createProxyRequest(c *echo.Context, target strinsrcReq := c.Request()validatedTarget, err := httputils.ValidateOutboundHTTPURL(target)if err != nil {- return nil, common.Classify(common.ErrEnvironmentInvalidProxyTarget, errors.WrapIf(err, "Invalid proxy target URL"))+ return nil, common.Classify(common.ErrEnvironmentInvalidProxyTarget, fmt.Errorf("Invalid proxy target URL: %w", err)) //nolint:staticcheck // Preserve the existing error message.}// The body is streamed straight through rather than buffered: volume backupdiff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.goindex f4391df03..efe19720c 100644--- a/backend/internal/network/handler.go+++ b/backend/internal/network/handler.go@@ -3,11 +3,11 @@ package networkimport ("cmp""context"+ "errors""net/http""sort""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -189,7 +189,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(errors.WithMessage(err, "Failed to list networks").Error())+ return nil, huma.Error500InternalServerError("Failed to list networks: " + err.Error())}return &ListNetworksOutput{@@ -205,7 +205,7 @@ func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInfunc (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetworkCountsInput) (*handlerutil.Out[networktypes.UsageCounts], error) {_, inuse, unused, total, err := h.dockerService.GetAllNetworks(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get network counts").Error())+ return nil, huma.Error500InternalServerError("Failed to get network counts: " + err.Error())}return &handlerutil.Out[networktypes.UsageCounts]{@@ -228,7 +228,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkdockerOptions, err := mapping.MapOne[networktypes.CreateOptions, client.NetworkCreateOptions](input.Body.Options)if err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid network options").Error())+ return nil, huma.Error400BadRequest("Invalid network options: " + err.Error())}if !input.Body.Options.EnableIPv6 {dockerOptions.EnableIPv6 = nil@@ -256,12 +256,12 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkreturn createErr})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create network").Error())+ return nil, huma.Error500InternalServerError("Failed to create network: " + err.Error())}out, err := mapping.MapOne[dockernetwork.CreateResponse, networktypes.CreateResponse](*response)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())+ return nil, huma.Error500InternalServerError("Failed to map network: " + err.Error())}out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -276,12 +276,12 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkfunc (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput) (*handlerutil.Out[networktypes.Inspect], error) {networkInspect, err := h.networkService.GetNetworkByID(ctx, input.NetworkID)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Network not found").Error())+ return nil, huma.Error404NotFound("Network not found: " + err.Error())}out, err := mapping.MapOne[dockernetwork.Inspect, networktypes.Inspect](*networkInspect)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())+ return nil, huma.Error500InternalServerError("Failed to map network: " + err.Error())}// Ensure ID is mapped correctly@@ -375,7 +375,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkreturn h.networkService.RemoveNetwork(runtimeCtx, input.NetworkID, *user)})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to remove network").Error())+ return nil, huma.Error500InternalServerError("Failed to remove network: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -414,7 +414,7 @@ func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectConif errors.Is(err, common.ErrValidation) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to connect container to network").Error())+ return nil, huma.Error500InternalServerError("Failed to connect container to network: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -451,7 +451,7 @@ func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *Disconnreturn h.networkService.DisconnectContainer(runtimeCtx, input.NetworkID, input.Body, *user)})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to disconnect container from network").Error())+ return nil, huma.Error500InternalServerError("Failed to disconnect container from network: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -479,12 +479,12 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksreturn pruneErr})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune networks").Error())+ return nil, huma.Error500InternalServerError("Failed to prune networks: " + err.Error())}out, err := mapping.MapOne[dockernetwork.PruneReport, networktypes.PruneReport](*report)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())+ return nil, huma.Error500InternalServerError("Failed to map network: " + err.Error())}out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()diff --git a/backend/internal/network/service.go b/backend/internal/network/service.goindex 47ca81b02..0ee4b4dad 100644--- a/backend/internal/network/service.go+++ b/backend/internal/network/service.go@@ -10,7 +10,6 @@ import ("sort""strings"- "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/docker"@@ -45,12 +44,12 @@ func NewNetworkService(db *database.DB, dockerService *docker.DockerClientServicfunc (s *NetworkService) GetNetworkByID(ctx context.Context, id string) (*network.Inspect, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}networkInspect, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "network not found")+ return nil, fmt.Errorf("network not found: %w", err)}return new(networkInspect.Network), nil@@ -59,19 +58,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}containers, err := s.dockerService.ListContainers(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to list containers")+ return nil, fmt.Errorf("failed to list containers: %w", err)}containerInfoByID := buildTopologyContainerInfoInternal(containers)networkList, err := compat.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker networks")+ return nil, fmt.Errorf("failed to list Docker networks: %w", err)}topology := &networktypes.Topology{@@ -94,7 +93,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.inspected, err := compat.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})if err != nil {- return errors.WrapIff(err, "failed to inspect network %s", rawNetwork.Name)+ return fmt.Errorf("failed to inspect network %s: %w", rawNetwork.Name, err)}inspectedNetworks[i] = struct {@@ -180,14 +179,14 @@ func (s *NetworkService) CreateNetwork(ctx context.Context, name string, optionsdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("network", "", name)()response, err := dockerClient.NetworkCreate(ctx, name, options)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})- return nil, errors.WrapIf(err, "failed to create network")+ return nil, fmt.Errorf("failed to create network: %w", err)}metadata := database.JSON{@@ -216,7 +215,7 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user commdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete"})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}networkInfo, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})@@ -225,7 +224,7 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user commdefer s.eventService.BeginDockerResourceSuppressionWindow("network", id, networkName)()if _, err := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", err, database.JSON{"action": "delete"})- return errors.WrapIf(err, "failed to remove network")+ return fmt.Errorf("failed to remove network: %w", err)}metadata := database.JSON{@@ -244,7 +243,7 @@ func (s *NetworkService) ConnectContainer(ctx context.Context, networkID string,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "connect", "containerId": req.ContainerID})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}endpoint := &network.EndpointSettings{Aliases: req.Aliases}@@ -255,14 +254,14 @@ func (s *NetworkService) ConnectContainer(ctx context.Context, networkID string,if ipv4 != "" {addr, parseErr := netip.ParseAddr(ipv4)if parseErr != nil {- return common.Classify(common.ErrValidation, errors.WrapIff(parseErr, "invalid IPv4 address %s", ipv4))+ return common.Classify(common.ErrValidation, fmt.Errorf("invalid IPv4 address %s: %w", ipv4, parseErr))}ipam.IPv4Address = addr}if ipv6 != "" {addr, parseErr := netip.ParseAddr(ipv6)if parseErr != nil {- return common.Classify(common.ErrValidation, errors.WrapIff(parseErr, "invalid IPv6 address %s", ipv6))+ return common.Classify(common.ErrValidation, fmt.Errorf("invalid IPv6 address %s: %w", ipv6, parseErr))}ipam.IPv6Address = addr}@@ -274,7 +273,7 @@ func (s *NetworkService) ConnectContainer(ctx context.Context, networkID string,EndpointConfig: endpoint,}); err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "connect", "containerId": req.ContainerID})- return errors.WrapIf(err, "failed to connect container to network")+ return fmt.Errorf("failed to connect container to network: %w", err)}metadata := database.JSON{@@ -294,7 +293,7 @@ func (s *NetworkService) DisconnectContainer(ctx context.Context, networkID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "disconnect", "containerId": req.ContainerID})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.NetworkDisconnect(ctx, networkID, client.NetworkDisconnectOptions{@@ -302,7 +301,7 @@ func (s *NetworkService) DisconnectContainer(ctx context.Context, networkID striForce: req.Force,}); err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "disconnect", "containerId": req.ContainerID})- return errors.WrapIf(err, "failed to disconnect container from network")+ return fmt.Errorf("failed to disconnect container from network: %w", err)}metadata := database.JSON{@@ -321,14 +320,14 @@ func (s *NetworkService) DisconnectContainer(ctx context.Context, networkID strifunc (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneReport, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}filterArgs := make(client.Filters)report, err := dockerClient.NetworkPrune(ctx, client.NetworkPruneOptions{Filters: filterArgs})if err != nil {- return nil, errors.WrapIf(err, "failed to prune networks")+ return nil, fmt.Errorf("failed to prune networks: %w", err)}pruneReport := report.Report@@ -346,19 +345,19 @@ 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{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)}containers, err := s.dockerService.ListContainers(ctx)if err != nil {- return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to list containers")+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list containers: %w", err)}inUseByID, inUseByName := dockerutil.BuildNetworkUsageMaps(containers)networkList, err := compat.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {- return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to list Docker networks")+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list Docker networks: %w", err)}rawNets := networkList.Items@@ -401,7 +400,7 @@ func (s *NetworkService) convertToNetworkSummaries(rawNets []network.Summary, infor _, n := range rawNets {netDto, err := mapping.MapOne[network.Summary, networktypes.Summary](n)if err != nil {- return nil, errors.WrapIf(err, "failed to map network")+ return nil, fmt.Errorf("failed to map network: %w", err)}netDto.InUse = inUseByID[netDto.ID] || inUseByName[netDto.Name]netDto.IsDefault = dockerutil.IsDefaultNetwork(netDto.Name)diff --git a/backend/internal/notification/email_templates.go b/backend/internal/notification/email_templates.goindex bcc388478..3e1b7692c 100644--- a/backend/internal/notification/email_templates.go+++ b/backend/internal/notification/email_templates.go@@ -9,7 +9,6 @@ import ("sort""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications""github.com/getarcaneapp/arcane/backend/v2/resources""github.com/getarcaneapp/arcane/types/v2/imageupdate"@@ -151,37 +150,37 @@ func (s *NotificationService) renderPruneReportEmailTemplateInternal(environmentfunc (s *NotificationService) renderTemplatesInternal(name string, data any, textRequired bool) (string, string, error) {htmlContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_html.tmpl", name))if err != nil {- return "", "", errors.WrapIf(err, "failed to read HTML template")+ return "", "", fmt.Errorf("failed to read HTML template: %w", err)}htmlTmpl, err := template.New("html").Parse(string(htmlContent))if err != nil {- return "", "", errors.WrapIf(err, "failed to parse HTML template")+ return "", "", fmt.Errorf("failed to parse HTML template: %w", err)}var htmlBuf bytes.Bufferif err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {- return "", "", errors.WrapIf(err, "failed to execute HTML template")+ return "", "", fmt.Errorf("failed to execute HTML template: %w", err)}textContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_text.tmpl", name))if err != nil {if textRequired {- return "", "", errors.WrapIf(err, "failed to read text template")+ return "", "", fmt.Errorf("failed to read text template: %w", err)}return htmlBuf.String(), "", nil}textTmpl, err := template.New("text").Parse(string(textContent))if err != nil {if textRequired {- return "", "", errors.WrapIf(err, "failed to parse text template")+ return "", "", fmt.Errorf("failed to parse text template: %w", err)}return htmlBuf.String(), "", nil}var textBuf bytes.Bufferif err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {if textRequired {- return "", "", errors.WrapIf(err, "failed to execute text template")+ return "", "", fmt.Errorf("failed to execute text template: %w", err)}return htmlBuf.String(), "", nil}diff --git a/backend/internal/notification/handler.go b/backend/internal/notification/handler.goindex 25ad8b76b..60a7c961c 100644--- a/backend/internal/notification/handler.go+++ b/backend/internal/notification/handler.go@@ -2,10 +2,10 @@ package notificationimport ("context"+ "errors""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"@@ -153,7 +153,7 @@ func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, in}settings, err := h.notificationService.GetAllSettings(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list notification settings").Error())+ return nil, huma.Error500InternalServerError("Failed to list notification settings: " + err.Error())}responses := make([]notification.Response, len(settings))@@ -230,7 +230,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, inprovider := notifications.NotificationProvider(input.Provider)if err := h.notificationService.DeleteSettings(ctx, provider); err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete notification settings").Error())+ return nil, huma.Error500InternalServerError("Failed to delete notification settings: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -253,7 +253,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(errors.WithMessage(err, "Failed to send test notification").Error())+ return nil, huma.Error500InternalServerError("Failed to send test notification: " + err.Error())}return &handlerutil.Out[notification.TestResponse]{diff --git a/backend/internal/notification/notification.go b/backend/internal/notification/notification.goindex 908bdf130..d30596b1b 100644--- a/backend/internal/notification/notification.go+++ b/backend/internal/notification/notification.go@@ -5,6 +5,7 @@ import ("cmp""context""encoding/json/v2"+ "errors""fmt""html""io"@@ -15,7 +16,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -60,9 +60,6 @@ var notificationTargetFieldByProviderInternal = map[notifications.NotificationPr}const (- ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")- ErrUnsupportedDispatchKind = errors.Sentinel("unsupported notification dispatch kind")-notificationDispatchConcurrencyInternal = 4notificationTestTypeSimple = "simple"@@ -75,6 +72,11 @@ const (logoURLPath = "/api/app-images/logo-email")+var (+ ErrUnauthorizedNotificationDispatch = errors.New("unauthorized notification dispatch")+ ErrUnsupportedDispatchKind = errors.New("unsupported notification dispatch kind")+)+type NotificationService struct {db *database.DBconfig *config.Config@@ -129,7 +131,10 @@ func (s *NotificationService) resolveNotificationTargetInternal(ctx context.Cont}, nil}if trimmedEnvironmentID != "0" {- return NotificationTarget{}, errors.WrapIf(err, "failed to resolve notification environment")+ if err != nil {+ return NotificationTarget{}, fmt.Errorf("failed to resolve notification environment: %w", err)+ }+ return NotificationTarget{}, nil}if err != nil {slog.WarnContext(ctx, "Failed to resolve local environment, falling back to 'Local Docker'", "error", err)@@ -150,7 +155,7 @@ func (s *NotificationService) resolveNotificationTargetForAccessTokenInternal(ctenv, err := s.environmentSvc.ResolveEnvironmentByAccessToken(ctx, accessToken)if err != nil {if errors.Is(err, environment.ErrEnvironmentAccessTokenRequired) || errors.Is(err, environment.ErrInvalidEnvironmentAccessToken) {- return NotificationTarget{}, errors.WithStackIf(ErrUnauthorizedNotificationDispatch)+ return NotificationTarget{}, ErrUnauthorizedNotificationDispatch}return NotificationTarget{}, err}@@ -169,7 +174,7 @@ func (s *NotificationService) resolveNotificationTargetForAccessTokenInternal(ctfunc (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.Context, payload notificationdto.DispatchRequest) (notificationdto.DispatchResponse, error) {body, err := json.Marshal(payload)if err != nil {- return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to marshal notification dispatch payload")+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to marshal notification dispatch payload: %w", err)}publishViaTunnel := func() error {@@ -185,7 +190,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.// instead so their notifications are not silently lost (#3002).if s.config == nil || strings.TrimSpace(httpx.ManagerBaseURL(s.config.ManagerApiUrl)) == "" || strings.TrimSpace(s.config.AgentToken) == "" {if err := publishViaTunnel(); err != nil {- return notificationdto.DispatchResponse{}, errors.WrapIf(err, "notification dispatch needs either MANAGER_API_URL + AGENT_TOKEN or a connected edge tunnel")+ return notificationdto.DispatchResponse{}, fmt.Errorf("notification dispatch needs either MANAGER_API_URL + AGENT_TOKEN or a connected edge tunnel: %w", err)}return notificationdto.DispatchResponse{Message: "notification dispatched via edge tunnel"}, nil}@@ -193,7 +198,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.dispatchURL := strings.TrimRight(httpx.ManagerBaseURL(s.config.ManagerApiUrl), "/") + "/api/notifications/dispatch"req, err := http.NewRequestWithContext(ctx, http.MethodPost, dispatchURL, bytes.NewReader(body))if err != nil {- return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to create notification dispatch request")+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to create notification dispatch request: %w", err)}req.Header.Set("Content-Type", "application/json")req.Header.Set(middleware.HeaderApiKey, s.config.AgentToken)@@ -205,7 +210,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.if tunnelErr := publishViaTunnel(); tunnelErr == nil {return notificationdto.DispatchResponse{Message: "notification dispatched via edge tunnel"}, nil}- return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to dispatch notification to manager")+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to dispatch notification to manager: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -214,7 +219,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.Data notificationdto.DispatchResponse `json:"data"`}if err := json.UnmarshalRead(resp.Body, &apiResponse); err != nil {- return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to decode manager notification dispatch response")+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", err)}return apiResponse.Data, nil}@@ -227,7 +232,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.if tunnelErr := publishViaTunnel(); tunnelErr == nil {return notificationdto.DispatchResponse{Message: "notification dispatched via edge tunnel"}, nil}- return notificationdto.DispatchResponse{}, errors.Errorf("manager notification dispatch failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))+ return notificationdto.DispatchResponse{}, fmt.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) {@@ -325,14 +330,14 @@ func (s *NotificationService) dispatchForTargetInternal(ctx context.Context, tarlogManagerDispatchNotificationInternal(ctx, target, payload.Kind)return dispatchResponse, s.sendAutoHealNotificationForTargetInternal(ctx, target, payload.AutoHeal.ContainerName, payload.AutoHeal.ContainerID)default:- return notificationdto.DispatchResponse{}, errors.WrapIff(ErrUnsupportedDispatchKind, "%s", payload.Kind)+ return notificationdto.DispatchResponse{}, fmt.Errorf("%s: %w", payload.Kind, ErrUnsupportedDispatchKind)}}func (s *NotificationService) GetAllSettings(ctx context.Context) ([]NotificationSettings, error) {var settings []NotificationSettingsif err := s.db.WithContext(ctx).Find(&settings).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get notification settings")+ return nil, fmt.Errorf("failed to get notification settings: %w", err)}return settings, nil}@@ -382,13 +387,13 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, providConfig: config,}if err := s.db.WithContext(ctx).Create(&setting).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create notification settings")+ return nil, fmt.Errorf("failed to create notification settings: %w", err)}} else {setting.Enabled = enabledsetting.Config = configif err := s.db.WithContext(ctx).Save(&setting).Error; err != nil {- return nil, errors.WrapIf(err, "failed to update notification settings")+ return nil, fmt.Errorf("failed to update notification settings: %w", err)}}@@ -462,7 +467,7 @@ func encryptNotificationConfigCredentialsInternal(provider notifications.Notificencrypted, err := encryptNotificationCredentialInternal(value)if err != nil {- return nil, errors.WrapIff(err, "failed to encrypt notification credential %q", field)+ return nil, fmt.Errorf("failed to encrypt notification credential %q: %w", field, err)}encryptedConfig[field] = encrypted}@@ -514,13 +519,11 @@ func cloneNotificationConfigInternal(config database.JSON) database.JSON {func (s *NotificationService) DeleteSettings(ctx context.Context, provider notifications.NotificationProvider) error {if err := s.db.WithContext(ctx).Where("provider = ?", provider).Delete(&NotificationSettings{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete notification settings")+ return fmt.Errorf("failed to delete notification settings: %w", err)}return nil}-// SendImageUpdateNotification dispatches a single-image update notification and-func (s *NotificationService) isEventEnabled(config database.JSON, eventType notifications.NotificationEventType) bool {events, ok := config["events"].(map[string]any)if !ok {@@ -586,9 +589,6 @@ func (s *NotificationService) logNotificationInternal(ctx context.Context, envir}}-// SendBatchImageUpdateNotification dispatches a batched image-update notification-// and returns the number of eligible providers it was delivered to (0 means no-// notifyEnabledProvidersInternal is the single fan-out loop behind every// notification event: it walks all provider settings, skips disabled providers// and providers with the event unsubscribed, dispatches to the rest, logs each@@ -604,7 +604,7 @@ func (s *NotificationService) notifyEnabledProvidersInternal() (int, error) {settings, err := s.GetAllSettings(ctx)if err != nil {- return 0, errors.WrapIf(err, "failed to get notification settings")+ return 0, fmt.Errorf("failed to get notification settings: %w", err)}eligible := make([]NotificationSettings, 0, len(settings))@@ -651,7 +651,7 @@ func (s *NotificationService) notifyEnabledProvidersInternal(}if len(errs) > 0 {- return delivered, errors.Errorf("notification errors: %s", strings.Join(errs, "; "))+ return delivered, fmt.Errorf("notification errors: %s", strings.Join(errs, "; "))}return delivered, nil}@@ -698,7 +698,7 @@ func (s *NotificationService) imageUpdateNotificationContentInternal(environmentRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderEmailTemplateInternal(environmentName, imageRef, updateInfo)if err != nil {- return "", "", errors.WrapIf(err, "failed to render email template")+ return "", "", fmt.Errorf("failed to render email template: %w", err)}subject := notifications.BuildEmailSubject(environmentName, "Container Update Available: "+notifications.SanitizeForEmail(imageRef))return subject, htmlBody, nil@@ -717,7 +717,7 @@ func (s *NotificationService) containerUpdateNotificationContentInternal(environRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderContainerUpdateEmailTemplateInternal(environmentName, containerName, imageRef, oldDigest, newDigest)if err != nil {- return "", "", errors.WrapIf(err, "failed to render email template")+ return "", "", fmt.Errorf("failed to render email template: %w", err)}subject := notifications.BuildEmailSubject(environmentName, "Container Updated: "+notifications.SanitizeForEmail(containerName))return subject, htmlBody, nil@@ -746,7 +746,7 @@ func (s *NotificationService) vulnerabilityNotificationContentInternal(environmeRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderVulnerabilitySummaryEmailTemplateInternal(environmentName, payload)if err != nil {- return "", "", errors.WrapIf(err, "failed to render summary email template")+ return "", "", fmt.Errorf("failed to render summary email template: %w", err)}subject := notifications.BuildEmailSubject(environmentName, "Daily Vulnerability Summary: "+notifications.SanitizeForEmail(payload.CVEID))return subject, htmlBody, nil@@ -765,7 +765,7 @@ func (s *NotificationService) batchImageUpdateNotificationContentInternal(enviroRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderBatchEmailTemplateInternal(environmentName, updates)if err != nil {- return "", "", errors.WrapIf(err, "failed to render email template")+ return "", "", fmt.Errorf("failed to render email template: %w", err)}updateCount := len(updates)plural := kit.Ternary(updateCount > 1, "s", "")@@ -836,7 +836,7 @@ func (s *NotificationService) batchContainerUpdateNotificationContentInternal(enRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderBatchContainerUpdateEmailTemplateInternal(environmentName, entries)if err != nil {- return "", "", errors.WrapIf(err, "failed to render email template")+ return "", "", fmt.Errorf("failed to render email template: %w", err)}updateCount := len(entries)plural := kit.Ternary(updateCount > 1, "s", "")@@ -859,7 +859,7 @@ func (s *NotificationService) pruneReportNotificationContentInternal(environmentRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderPruneReportEmailTemplateInternal(environmentName, result)if err != nil {- return "", "", errors.WrapIf(err, "failed to render email template")+ return "", "", fmt.Errorf("failed to render email template: %w", err)}subject := notifications.BuildEmailSubject(environmentName, fmt.Sprintf("System Prune Report: %s Reclaimed", notifications.FormatBytes(result.SpaceReclaimed)))return subject, htmlBody, nil@@ -1296,11 +1296,11 @@ func (s *NotificationService) testNotificationContentInternal(environmentName, tfunc (s *NotificationService) TestNotification(ctx context.Context, environmentID string, provider notifications.NotificationProvider, testType string) (string, error) {setting, err := s.GetSettingsByProvider(ctx, provider)if err != nil {- return "", errors.Errorf("please save your %s settings before testing", provider)+ return "", fmt.Errorf("please save your %s settings before testing", provider)}testType = cmp.Or(strings.TrimSpace(testType), notificationTestTypeSimple)if _, ok := supportedNotificationTestTypes[testType]; !ok {- return "", errors.Errorf("unsupported notification test type: %s", testType)+ return "", fmt.Errorf("unsupported notification test type: %s", testType)}warning := s.testNotificationWarningInternal(setting, testType)@@ -1321,7 +1321,7 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentIcontent.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, testEventType)handled, sendErr := notifications.Deliver(ctx, provider, setting.Config, content)if !handled {- return "", errors.Errorf("unknown provider: %s", provider)+ return "", fmt.Errorf("unknown provider: %s", provider)}return warning, sendErr}@@ -1331,7 +1331,7 @@ func (s *NotificationService) sendTestEmailInternal(ctx context.Context, environRenderEmail: func() (string, string, error) {htmlBody, _, err := s.renderTestEmailTemplateInternal(environmentName)if err != nil {- return "", "", errors.WrapIf(err, "failed to render test email template")+ return "", "", fmt.Errorf("failed to render test email template: %w", err)}return notifications.BuildEmailSubject(environmentName, "Test Email from Arcane"), htmlBody, nil},diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.goindex af9825639..a05361c9b 100644--- a/backend/internal/oidc/handler.go+++ b/backend/internal/oidc/handler.go@@ -2,12 +2,12 @@ package oidcimport ("context"+ "errors""log/slog""net/http""strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -245,7 +245,7 @@ func RegisterOidc(api huma.API, authService *auth.AuthService, passkeyService *pfunc (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput) (*GetOidcStatusOutput, error) {status, err := h.authService.GetOidcConfigurationStatus(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve OIDC status").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve OIDC status: " + err.Error())}return &GetOidcStatusOutput{@@ -306,7 +306,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(errors.WithMessage(err, "Failed to generate OIDC auth URL").Error())+ return nil, huma.Error500InternalServerError("Failed to generate OIDC auth URL: " + err.Error())}// Build state cookie (600 seconds = 10 minutes). Secure is resolved from the@@ -347,7 +347,7 @@ 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(errors.WithMessage(err, "OIDC callback failed").Error())+ return nil, huma.Error400BadRequest("OIDC callback failed: " + err.Error())}// Reconcile the provider identity first, then require passkey MFA before@@ -423,7 +423,7 @@ func (h *OidcHandler) InitiateDeviceAuth(ctx context.Context, _ *InitiateDeviceAresponse, err := h.oidcService.InitiateDeviceAuth(ctx)if err != nil {slog.WarnContext(ctx, "Device authorization initiation failed", "error", err)- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate OIDC auth URL").Error())+ return nil, huma.Error500InternalServerError("Failed to generate OIDC auth URL: " + err.Error())}return &InitiateDeviceAuthOutput{@@ -451,7 +451,7 @@ 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(errors.WithMessage(err, "OIDC callback failed").Error())+ return nil, huma.Error400BadRequest("OIDC callback failed: " + err.Error())}}diff --git a/backend/internal/oidc/service.go b/backend/internal/oidc/service.goindex 953b6877e..e917dd087 100644--- a/backend/internal/oidc/service.go+++ b/backend/internal/oidc/service.go@@ -6,6 +6,7 @@ import ("crypto/tls""encoding/base64""encoding/json/v2"+ "errors""fmt""log/slog""net/http"@@ -15,7 +16,6 @@ import ("sync""time"- "emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -83,7 +83,7 @@ func (s *OidcService) keySetInternal(ctx context.Context, jwksURL string, skipTLfunc (s *OidcService) getEffectiveConfigInternal(ctx context.Context) (*settings.OidcConfig, error) {oidcConfig, err := s.authService.GetOidcConfig(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get OIDC config")+ return nil, fmt.Errorf("failed to get OIDC config: %w", err)}if oidcConfig.IssuerURL == "" {return nil, errors.New("issuer URL must be configured")@@ -216,7 +216,7 @@ func (s *OidcService) ValidateMobileRedirectURI(ctx context.Context, uri string)if slices.Contains(s.GetMobileRedirectAllowlist(ctx), uri) {return nil}- return errors.Errorf("mobile redirect URI %q is not in the configured allowlist", uri)+ return fmt.Errorf("mobile redirect URI %q is not in the configured allowlist", uri)}func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo, origin, mobileRedirectURI string) (string, string, error) {@@ -232,7 +232,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo, origin, mprovider, err = s.getOrDiscoverProviderInternal(ctx, oidcConfig)if err != nil {slog.Error("GenerateAuthURL: provider discovery failed", "issuer", oidcConfig.IssuerURL, "error", err)- return "", "", errors.WrapIf(err, "failed to discover provider")+ return "", "", fmt.Errorf("failed to discover provider: %w", err)}}@@ -262,7 +262,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo, origin, mstateJSON, err := json.Marshal(stateData)if err != nil {slog.Error("GenerateAuthURL: failed to marshal state", "error", err)- return "", "", errors.WrapIf(err, "failed to encode state")+ return "", "", fmt.Errorf("failed to encode state: %w", err)}encodedState := base64.URLEncoding.EncodeToString(stateJSON)@@ -292,7 +292,7 @@ func (s *OidcService) getOrDiscoverProviderInternal(ctx context.Context, cfg *secancel()if discoverErr != nil {slog.ErrorContext(ctx, "getOrDiscoverProviderInternal: discovery failed", "issuer", providerKey.issuer, "skipTls", providerKey.skipTLS, "error", discoverErr)- return nil, errors.WrapIff(discoverErr, "failed to discover provider at %s", providerKey.issuer)+ return nil, fmt.Errorf("failed to discover provider at %s: %w", providerKey.issuer, discoverErr)}providers[providerKey] = discoveredslog.DebugContext(ctx, "getOrDiscoverProviderInternal: provider cached", "issuer", providerKey.issuer, "effectiveIssuer", discoveredIssuer, "skipTls", providerKey.skipTLS)@@ -339,7 +339,7 @@ func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *settings.Otoken, 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, errors.WrapIf(err, "failed to exchange authorization code")+ return nil, fmt.Errorf("failed to exchange authorization code: %w", err)}slog.Debug("exchangeTokenInternal: token exchange successful", "has_access_token", token.AccessToken != "", "has_refresh_token", token.RefreshToken != "")@@ -367,14 +367,14 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *settings.Oidif claims != nil {return claims, nil}- return nil, errors.WrapIf(err, "failed to fetch userinfo")+ return nil, fmt.Errorf("failed to fetch userinfo: %w", err)}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, errors.WrapIf(err, "failed to decode userinfo claims")+ return nil, fmt.Errorf("failed to decode userinfo claims: %w", err)}slog.Debug("fetchClaimsInternal: fetched userinfo claims successfully")case cfg.UserinfoEndpoint != "":@@ -384,7 +384,7 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *settings.Oidif claims != nil {return claims, nil}- return nil, errors.WrapIf(err, "failed to fetch userinfo")+ return nil, fmt.Errorf("failed to fetch userinfo: %w", err)}userInfoClaims = manualClaimsslog.Debug("fetchClaimsInternal: fetched userinfo claims successfully")@@ -431,7 +431,7 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *settdefer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, errors.Errorf("userinfo endpoint returned status %d", resp.StatusCode)+ return nil, fmt.Errorf("userinfo endpoint returned status %d", resp.StatusCode)}var claims map[string]any@@ -481,7 +481,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, errors.WrapIf(err, "invalid state parameter")+ return nil, fmt.Errorf("invalid state parameter: %w", err)}if state != stateData.State {@@ -521,7 +521,7 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.JWKSURL string `json:"jwks_uri"`}if err := provider.Claims(&meta); err != nil {- return nil, "", errors.WrapIf(err, "failed to read provider metadata")+ return nil, "", fmt.Errorf("failed to read provider metadata: %w", err)}issuer, jwksURL = meta.Issuer, meta.JWKSURL} else {@@ -533,7 +533,7 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.keySet, err := s.keySetInternal(ctx, jwksURL, cfg.SkipTlsVerify)if err != nil {- return nil, "", errors.WrapIf(err, "failed to configure provider JWK set")+ return nil, "", fmt.Errorf("failed to configure provider JWK set: %w", err)}providerCtx := oidc.ClientContext(ctx, s.getHttpClientInternal(cfg.SkipTlsVerify))verifier := oidc.NewVerifier(issuer, keySet, verifierConfig)@@ -541,7 +541,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, "", errors.WrapIf(err, "failed to verify ID token")+ return nil, "", fmt.Errorf("failed to verify ID token: %w", err)}if nonce != "" {@@ -550,7 +550,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, "", errors.WrapIf(err, "failed to verify nonce")+ return nil, "", fmt.Errorf("failed to verify nonce: %w", err)}if claims.Nonce != nonce {slog.Error("HandleCallback: nonce mismatch", "expected", nonce, "got", claims.Nonce)@@ -566,7 +566,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, errors.WrapIf(err, "failed to fetch user claims")+ return nil, nil, fmt.Errorf("failed to fetch user claims: %w", err)}subject := jwtclaims.GetStringClaim(claims, "sub")@@ -699,14 +699,14 @@ func (s *OidcService) getDeviceAuthorizationEndpointInternal(ctx context.Contextprovider, err := s.getOrDiscoverProviderInternal(ctx, cfg)if err != nil {- return "", errors.WrapIf(err, "failed to discover provider")+ return "", fmt.Errorf("failed to discover provider: %w", err)}var claims struct {DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`}if err := provider.Claims(&claims); err != nil {- return "", errors.WrapIf(err, "failed to get device authorization endpoint from provider")+ return "", fmt.Errorf("failed to get device authorization endpoint from provider: %w", err)}if claims.DeviceAuthorizationEndpoint == "" {@@ -731,7 +731,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, errors.WrapIf(err, "device authorization request failed")+ return nil, fmt.Errorf("device authorization request failed: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -739,15 +739,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, errors.Errorf("device authorization failed: %s", errMsg)+ return nil, fmt.Errorf("device authorization failed: %s", errMsg)}}- return nil, errors.Errorf("device authorization endpoint returned status %d", resp.StatusCode)+ return nil, fmt.Errorf("device authorization endpoint returned status %d", resp.StatusCode)}var respData map[string]anyif err := json.UnmarshalRead(resp.Body, &respData); err != nil {- return nil, errors.WrapIf(err, "failed to decode device authorization response")+ return nil, fmt.Errorf("failed to decode device authorization response: %w", err)}return respData, nil@@ -840,13 +840,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, errors.WrapIf(err, "token request failed")+ return nil, fmt.Errorf("token request failed: %w", err)}defer func() { _ = resp.Body.Close() }()var tokenResp map[string]anyif err := json.UnmarshalRead(resp.Body, &tokenResp); err != nil {- return nil, errors.WrapIf(err, "failed to decode token response")+ return nil, fmt.Errorf("failed to decode token response: %w", err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {@@ -861,10 +861,10 @@ func (s *OidcService) makeTokenRequestInternal(ctx context.Context, endpoint strcase "access_denied":return nil, errors.New("access_denied")default:- return nil, errors.Errorf("token exchange failed: %s", errMsg)+ return nil, fmt.Errorf("token exchange failed: %s", errMsg)}}- return nil, errors.Errorf("token endpoint returned status %d", resp.StatusCode)+ return nil, fmt.Errorf("token endpoint returned status %d", resp.StatusCode)}return tokenResp, nildiff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.goindex 0e733c1ef..f5233b4d2 100644--- a/backend/internal/passkey/handler.go+++ b/backend/internal/passkey/handler.go@@ -3,11 +3,11 @@ package passkeyimport ("context""encoding/json/v2"+ "errors""net/http""strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common"diff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.goindex 58295c051..178d06c24 100644--- a/backend/internal/passkey/service.go+++ b/backend/internal/passkey/service.go@@ -9,6 +9,8 @@ import ("encoding/base64""encoding/hex""encoding/json/v2"+ "errors"+ "fmt""log/slog""net/url""strings"@@ -17,7 +19,6 @@ import ("unicode/utf8""uuid"- "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"@@ -52,20 +53,20 @@ const ()var (- ErrPasskeyServiceUnavailable = errors.Sentinel("passkey service is unavailable")- ErrPasskeyCeremony = errors.Sentinel("invalid or expired passkey ceremony")- ErrPasskeyTransaction = errors.Sentinel("invalid or expired authentication transaction")- ErrPasskeyResponse = errors.Sentinel("invalid passkey response")- ErrPasskeyNotFound = errors.Sentinel("passkey not found")- ErrPasskeyExists = errors.Sentinel("passkey already registered")- ErrPasskeyStepUpRequired = errors.Sentinel("fresh step-up authentication is required")- ErrPasskeyMFAEnabled = errors.Sentinel("passkey MFA must be disabled first")- ErrPasskeyMFAAlreadyEnabled = errors.Sentinel("passkey MFA is already enabled")- ErrPasskeyMFANotEnabled = errors.Sentinel("passkey MFA is not enabled")- ErrPasskeyNoCredential = errors.Sentinel("no passkeys are registered")- ErrPasskeyLastCredential = errors.Sentinel("cannot remove the last usable authentication method")- ErrPasskeyRecoveryCode = errors.Sentinel("invalid recovery code")- ErrPasskeyName = errors.Sentinel("invalid passkey name")+ ErrPasskeyServiceUnavailable = errors.New("passkey service is unavailable")+ ErrPasskeyCeremony = errors.New("invalid or expired passkey ceremony")+ ErrPasskeyTransaction = errors.New("invalid or expired authentication transaction")+ ErrPasskeyResponse = errors.New("invalid passkey response")+ ErrPasskeyNotFound = errors.New("passkey not found")+ ErrPasskeyExists = errors.New("passkey already registered")+ ErrPasskeyStepUpRequired = errors.New("fresh step-up authentication is required")+ ErrPasskeyMFAEnabled = errors.New("passkey MFA must be disabled first")+ ErrPasskeyMFAAlreadyEnabled = errors.New("passkey MFA is already enabled")+ ErrPasskeyMFANotEnabled = errors.New("passkey MFA is not enabled")+ ErrPasskeyNoCredential = errors.New("no passkeys are registered")+ ErrPasskeyLastCredential = errors.New("cannot remove the last usable authentication method")+ ErrPasskeyRecoveryCode = errors.New("invalid recovery code")+ ErrPasskeyName = errors.New("invalid passkey name")authenticatorNamesOnce sync.OnceauthenticatorNames map[string]string@@ -148,8 +149,9 @@ func NewPasskeyService(db *database.DB, cfg *config.Config) *PasskeyService {parsedURL, err := url.Parse(strings.TrimSpace(cfg.GetAppURL()))if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {- s.initErr = errors.WrapIf(err, "invalid APP_URL for WebAuthn")- if err == nil {+ if err != nil {+ s.initErr = fmt.Errorf("invalid APP_URL for WebAuthn: %w", err)+ } else {s.initErr = errors.New("invalid APP_URL for WebAuthn")}return s@@ -222,12 +224,12 @@ func (s *PasskeyService) loadWebAuthnUserInternal(ctx context.Context, userID stif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction}- return nil, errors.WrapIf(err, "failed to load passkey user")+ return nil, fmt.Errorf("failed to load passkey user: %w", err)}var rows []Passkeyif err := s.db.WithContext(ctx).Where("user_id = ? AND rp_id = ?", user.ID, s.rpID).Order("created_at ASC").Find(&rows).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load passkeys")+ return nil, fmt.Errorf("failed to load passkeys: %w", err)}credentials := make([]webauthn.Credential, len(rows))@@ -286,7 +288,7 @@ func (s *PasskeyService) LoginAvailable(ctx context.Context) (bool, error) {Where("passkeys.rp_id = ?", s.rpID)var available boolif err := s.db.WithContext(ctx).Raw("SELECT EXISTS (?)", credentials).Scan(&available).Error; err != nil {- return false, errors.WrapIf(err, "failed to check passkey login availability")+ return false, fmt.Errorf("failed to check passkey login availability: %w", err)}return available, nil}@@ -301,7 +303,7 @@ func (s *PasskeyService) BeginPasskeyLogin(ctx context.Context) (*PasskeyChallenassertion, session, err := s.webAuthn.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))if err != nil {- return nil, errors.WrapIf(err, "failed to begin passkey login")+ return nil, fmt.Errorf("failed to begin passkey login: %w", err)}ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeLogin, nil, nil, nil, session)@@ -333,7 +335,7 @@ func (s *PasskeyService) BeginMFAAuthentication(ctx context.Context, userID stritransaction := newAuthTransactionInternal(userID, authTransactionKindMFA, source, meta, nil)if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create MFA transaction")+ return nil, fmt.Errorf("failed to create MFA transaction: %w", err)}challenge, err := s.beginMFAForTransactionInternal(ctx, transaction)if err != nil {@@ -376,12 +378,12 @@ func (s *PasskeyService) beginMFAForTransactionInternal(ctx context.Context, traif err := s.db.WithContext(ctx).Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transaction.ID, passkeyCeremonyPurposeMFA).Delete(&PasskeyCeremony{}).Error; err != nil {- return nil, errors.WrapIf(err, "failed to replace MFA ceremony")+ return nil, fmt.Errorf("failed to replace MFA ceremony: %w", err)}assertion, webSession, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))if err != nil {- return nil, errors.WrapIf(err, "failed to begin MFA passkey ceremony")+ return nil, fmt.Errorf("failed to begin MFA passkey ceremony: %w", err)}transactionID := transaction.ID@@ -420,13 +422,13 @@ func (s *PasskeyService) BeginStepUp(ctx context.Context, userID, sessionID stritransaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, session.UserSessionSourceLocal, meta, &sessionID)if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create step-up transaction")+ return nil, fmt.Errorf("failed to create step-up transaction: %w", err)}assertion, session, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))if err != nil {_ = s.db.WithContext(ctx).Delete(transaction).Error- return nil, errors.WrapIf(err, "failed to begin step-up passkey ceremony")+ return nil, fmt.Errorf("failed to begin step-up passkey ceremony: %w", err)}transactionID := transaction.ID@@ -469,7 +471,7 @@ func (s *PasskeyService) BeginRegistration(ctx context.Context, userID, sessionIwebauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementRequired),)if err != nil {- return nil, errors.WrapIf(err, "failed to begin passkey registration")+ return nil, fmt.Errorf("failed to begin passkey registration: %w", err)}userIDPointer := userID@@ -588,7 +590,7 @@ func (s *PasskeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyItransaction := newAuthTransactionInternal(user.ID, authTransactionKindMobilePasskey, session.UserSessionSourcePasskey, auth.SessionMeta{}, nil)transaction.SecretHash = &codeChallengeif err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create mobile passkey transaction")+ return nil, fmt.Errorf("failed to create mobile passkey transaction: %w", err)}return &auth.MobilePasskeyCompletion{TransactionID: transaction.ID, ExpiresAt: transaction.ExpiresAt}, nil}@@ -608,7 +610,7 @@ func (s *PasskeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transacif errors.Is(err, gorm.ErrRecordNotFound) {return ErrPasskeyTransaction}- return errors.WrapIf(err, "failed to load mobile passkey transaction")+ return fmt.Errorf("failed to load mobile passkey transaction: %w", err)}now := time.Now()@@ -616,7 +618,7 @@ func (s *PasskeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transacWhere("id = ? AND status = ? AND expires_at > ?", transaction.ID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to complete mobile passkey transaction")+ return fmt.Errorf("failed to complete mobile passkey transaction: %w", result.Error)}return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)})@@ -663,11 +665,11 @@ func (s *PasskeyService) FinishRecoveryCode(ctx context.Context, transactionID,if errors.Is(err, gorm.ErrRecordNotFound) {return ErrPasskeyTransaction}- return errors.WrapIf(err, "failed to lock MFA transaction")+ return fmt.Errorf("failed to lock MFA transaction: %w", err)}var recoveryCodes []PasskeyRecoveryCodeif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ? AND used_at IS NULL", transaction.UserID).Find(&recoveryCodes).Error; err != nil {- return errors.WrapIf(err, "failed to load recovery codes")+ return fmt.Errorf("failed to load recovery codes: %w", err)}var matched *PasskeyRecoveryCode@@ -685,7 +687,7 @@ func (s *PasskeyService) FinishRecoveryCode(ctx context.Context, transactionID,Where("id = ? AND used_at IS NULL", matched.ID).Updates(map[string]any{"used_at": now, "updated_at": now})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to consume recovery code")+ return fmt.Errorf("failed to consume recovery code: %w", result.Error)}if result.RowsAffected != 1 {return ErrPasskeyRecoveryCode@@ -695,7 +697,7 @@ func (s *PasskeyService) FinishRecoveryCode(ctx context.Context, transactionID,Where("id = ? AND status = ? AND expires_at > ?", transaction.ID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to complete MFA transaction")+ return fmt.Errorf("failed to complete MFA transaction: %w", result.Error)}return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)})@@ -740,7 +742,7 @@ func (s *PasskeyService) CreatePasswordStepUpGrant(ctx context.Context, userID,}transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, session.UserSessionSourceLocal, auth.SessionMeta{}, &sessionID)if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create password step-up transaction")+ return nil, fmt.Errorf("failed to create password step-up transaction: %w", err)}return s.issueStepUpGrantInternal(ctx, transaction.ID)}@@ -764,7 +766,7 @@ func (s *PasskeyService) VerifyStepUpToken(ctx context.Context, userID, sessionIif err := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("user_id = ? AND session_id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?", userID, sessionID, authTransactionKindStepUp, authTransactionCompleted, hash, time.Now()).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to verify step-up grant")+ return fmt.Errorf("failed to verify step-up grant: %w", err)}return kit.Ternary[error](count != 1, ErrPasskeyStepUpRequired, nil)}@@ -775,7 +777,7 @@ func (s *PasskeyService) ListPasskeys(ctx context.Context, userID string) ([]Pas}var rows []Passkeyif err := s.db.WithContext(ctx).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Order("created_at ASC").Find(&rows).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list passkeys")+ return nil, fmt.Errorf("failed to list passkeys: %w", err)}result := make([]PasskeySummary, len(rows))for i := range rows {@@ -826,11 +828,11 @@ func (s *PasskeyService) RenamePasskey(ctx context.Context, userID, passkeyID, nreturn nil, ErrPasskeyNotFound}if result.Error != nil {- return nil, errors.WrapIf(result.Error, "failed to load passkey")+ return nil, fmt.Errorf("failed to load passkey: %w", result.Error)}now := time.Now()if err := s.db.WithContext(ctx).Model(&row).Updates(map[string]any{"name": name, "updated_at": now}).Error; err != nil {- return nil, errors.WrapIf(err, "failed to rename passkey")+ return nil, fmt.Errorf("failed to rename passkey: %w", err)}row.Name = namerow.UpdatedAt = &now@@ -848,11 +850,11 @@ func (s *PasskeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {- return errors.WrapIf(err, "failed to lock user for passkey deletion")+ return fmt.Errorf("failed to lock user for passkey deletion: %w", err)}var count int64if err := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to count passkeys")+ return fmt.Errorf("failed to count passkeys: %w", err)}if user.PasskeyMFAEnabled && count <= 1 {return ErrPasskeyMFAEnabled@@ -866,7 +868,7 @@ func (s *PasskeyService) DeletePasskey(ctx context.Context, userID, passkeyID, s}result := tx.Where("id = ? AND user_id = ? AND rp_id = ?", passkeyID, userID, s.rpID).Delete(&Passkey{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete passkey")+ return fmt.Errorf("failed to delete passkey: %w", result.Error)}return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyNotFound, nil)})@@ -886,7 +888,7 @@ func (s *PasskeyService) GetMFAStatus(ctx context.Context, userID string) (*MFAS}var recoveryCodes int64if err := s.db.WithContext(ctx).Model(&PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", userID).Count(&recoveryCodes).Error; err != nil {- return nil, errors.WrapIf(err, "failed to count recovery codes")+ return nil, fmt.Errorf("failed to count recovery codes: %w", err)}return &MFAStatus{Enabled: user.PasskeyMFAEnabled, PasskeyCount: passkeyCount, RecoveryCodesRemaining: int(recoveryCodes)}, nil}@@ -905,11 +907,11 @@ func (s *PasskeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUerr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {- return errors.WrapIf(err, "failed to lock user for MFA enable")+ return fmt.Errorf("failed to lock user for MFA enable: %w", err)}var count int64if err := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to count passkeys for MFA enable")+ return fmt.Errorf("failed to count passkeys for MFA enable: %w", err)}if count == 0 {return ErrPasskeyNoCredential@@ -918,13 +920,13 @@ func (s *PasskeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUreturn ErrPasskeyMFAAlreadyEnabled}if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", true).Error; err != nil {- return errors.WrapIf(err, "failed to enable passkey MFA")+ return fmt.Errorf("failed to enable passkey MFA: %w", err)}if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {- return errors.WrapIf(err, "failed to replace recovery codes")+ return fmt.Errorf("failed to replace recovery codes: %w", err)}if err := tx.Create(&rows).Error; err != nil {- return errors.WrapIf(err, "failed to create recovery codes")+ return fmt.Errorf("failed to create recovery codes: %w", err)}return nil})@@ -944,16 +946,16 @@ func (s *PasskeyService) DisableMFA(ctx context.Context, userID, sessionID, steperr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {- return errors.WrapIf(err, "failed to lock user for MFA disable")+ return fmt.Errorf("failed to lock user for MFA disable: %w", err)}if !user.PasskeyMFAEnabled {return ErrPasskeyMFANotEnabled}if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {- return errors.WrapIf(err, "failed to disable passkey MFA")+ return fmt.Errorf("failed to disable passkey MFA: %w", err)}if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete recovery codes")+ return fmt.Errorf("failed to delete recovery codes: %w", err)}now := time.Now()query := tx.Model(&session.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID)@@ -961,7 +963,7 @@ func (s *PasskeyService) DisableMFA(ctx context.Context, userID, sessionID, stepquery = query.Where("id <> ?", sessionID)}if err := query.Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return errors.WrapIf(err, "failed to revoke sessions after MFA disable")+ return fmt.Errorf("failed to revoke sessions after MFA disable: %w", err)}return nil})@@ -982,15 +984,18 @@ func (s *PasskeyService) RegenerateRecoveryCodes(ctx context.Context, userID, seerr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var user common.Userif err := tx.Where("id = ?", userID).First(&user).Error; err != nil {- return errors.WrapIf(err, "failed to load user for recovery code regeneration")+ return fmt.Errorf("failed to load user for recovery code regeneration: %w", err)}if !user.PasskeyMFAEnabled {return ErrPasskeyMFANotEnabled}if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {- return errors.WrapIf(err, "failed to replace recovery codes")+ return fmt.Errorf("failed to replace recovery codes: %w", err)}- return errors.WrapIf(tx.Create(&rows).Error, "failed to create recovery codes")+ if err := tx.Create(&rows).Error; err != nil {+ return fmt.Errorf("failed to create recovery codes: %w", err)+ }+ return nil})if err != nil {return nil, err@@ -1010,23 +1015,23 @@ func (s *PasskeyService) ResetMFAForUser(ctx context.Context, userID string) errif errors.Is(err, gorm.ErrRecordNotFound) {return ErrPasskeyTransaction}- return errors.WrapIf(err, "failed to load user for MFA reset")+ return fmt.Errorf("failed to load user for MFA reset: %w", err)}if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {- return errors.WrapIf(err, "failed to disable passkey MFA")+ return fmt.Errorf("failed to disable passkey MFA: %w", err)}if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete recovery codes")+ return fmt.Errorf("failed to delete recovery codes: %w", err)}if err := tx.Where("user_id = ?", userID).Delete(&PasskeyCeremony{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete passkey ceremonies")+ return fmt.Errorf("failed to delete passkey ceremonies: %w", err)}if err := tx.Where("user_id = ?", userID).Delete(&AuthTransaction{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete authentication transactions")+ return fmt.Errorf("failed to delete authentication transactions: %w", err)}now := time.Now()if err := tx.Model(&session.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return errors.WrapIf(err, "failed to revoke sessions after MFA reset")+ return fmt.Errorf("failed to revoke sessions after MFA reset: %w", err)}return nil})@@ -1038,7 +1043,7 @@ func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose str}serialized, err := json.Marshal(session)if err != nil {- return nil, errors.WrapIf(err, "failed to serialize WebAuthn session")+ return nil, fmt.Errorf("failed to serialize WebAuthn session: %w", err)}expiresAt := session.Expiresif expiresAt.IsZero() {@@ -1055,7 +1060,7 @@ func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose strExpiresAt: expiresAt,}if err := s.db.WithContext(ctx).Create(ceremony).Error; err != nil {- return nil, errors.WrapIf(err, "failed to store passkey ceremony")+ return nil, fmt.Errorf("failed to store passkey ceremony: %w", err)}return ceremony, nil}@@ -1065,7 +1070,7 @@ func (s *PasskeyService) sweepCeremoniesInternal(ctx context.Context) error {if err := s.db.WithContext(ctx).Where("expires_at <= ? OR consumed_at IS NOT NULL", now).Delete(&PasskeyCeremony{}).Error; err != nil {- return errors.WrapIf(err, "failed to sweep passkey ceremonies")+ return fmt.Errorf("failed to sweep passkey ceremonies: %w", err)}return nil}@@ -1080,13 +1085,13 @@ func (s *PasskeyService) consumeCeremonyInternal(ctx context.Context, ceremonyIDif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyCeremony}- return nil, errors.WrapIf(err, "failed to load passkey ceremony")+ return nil, fmt.Errorf("failed to load passkey ceremony: %w", err)}result := s.db.WithContext(ctx).Model(&PasskeyCeremony{}).Where("id = ? AND purpose = ? AND consumed_at IS NULL AND expires_at > ?", ceremonyID, purpose, now).Updates(map[string]any{"consumed_at": now, "updated_at": now})if result.Error != nil {- return nil, errors.WrapIf(result.Error, "failed to consume passkey ceremony")+ return nil, fmt.Errorf("failed to consume passkey ceremony: %w", result.Error)}if result.RowsAffected != 1 {return nil, ErrPasskeyCeremony@@ -1104,7 +1109,7 @@ func (s *PasskeyService) loadPendingTransactionInternal(ctx context.Context, traif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction}- return nil, errors.WrapIf(err, "failed to load authentication transaction")+ return nil, fmt.Errorf("failed to load authentication transaction: %w", err)}return &transaction, nil}@@ -1158,7 +1163,7 @@ func (s *PasskeyService) completeTransactionInternal(ctx context.Context, transaWhere("id = ? AND status = ? AND expires_at > ?", transactionID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to complete authentication transaction")+ return fmt.Errorf("failed to complete authentication transaction: %w", result.Error)}return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)}@@ -1175,14 +1180,14 @@ func (s *PasskeyService) issueStepUpGrantInternal(ctx context.Context, transacti"updated_at": now,})if result.Error != nil {- return nil, errors.WrapIf(result.Error, "failed to store step-up grant")+ return nil, fmt.Errorf("failed to store step-up grant: %w", result.Error)}if result.RowsAffected != 1 {return nil, ErrPasskeyTransaction}var transaction AuthTransactionif err := s.db.WithContext(ctx).Where("id = ?", transactionID).First(&transaction).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load step-up grant")+ return nil, fmt.Errorf("failed to load step-up grant: %w", err)}return &StepUpGrant{Token: token, ExpiresAt: transaction.ExpiresAt}, nil}@@ -1207,7 +1212,7 @@ func (s *PasskeyService) loadUserModelInternal(ctx context.Context, userID strinif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction}- return nil, errors.WrapIf(err, "failed to load user")+ return nil, fmt.Errorf("failed to load user: %w", err)}return &user, nil}@@ -1223,7 +1228,7 @@ func (s *PasskeyService) ensureActiveSessionInternal(ctx context.Context, userIDif errors.Is(err, gorm.ErrRecordNotFound) {return ErrPasskeyStepUpRequired}- return errors.WrapIf(err, "failed to validate active session")+ return fmt.Errorf("failed to validate active session: %w", err)}return nil}@@ -1231,7 +1236,7 @@ func (s *PasskeyService) ensureActiveSessionInternal(ctx context.Context, userIDfunc (s *PasskeyService) countPasskeysInternal(ctx context.Context, userID string) (int, error) {var count int64if err := s.db.WithContext(ctx).Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {- return 0, errors.WrapIf(err, "failed to count passkeys")+ return 0, fmt.Errorf("failed to count passkeys: %w", err)}return int(count), nil}@@ -1246,7 +1251,10 @@ func (s *PasskeyService) persistCredentialInternal(ctx context.Context, userID sreturn nil, ErrPasskeyExists}if !errors.Is(result.Error, gorm.ErrRecordNotFound) {- return nil, errors.WrapIf(result.Error, "failed to check existing passkey")+ if err := result.Error; err != nil {+ return nil, fmt.Errorf("failed to check existing passkey: %w", err)+ }+ return nil, nil}transports := make(database.StringSlice, len(credential.Transport))for i, transport := range credential.Transport {@@ -1278,7 +1286,7 @@ func (s *PasskeyService) persistCredentialInternal(ctx context.Context, userID sif strings.Contains(strings.ToLower(err.Error()), "unique") {return nil, ErrPasskeyExists}- return nil, errors.WrapIf(err, "failed to store passkey")+ return nil, fmt.Errorf("failed to store passkey: %w", err)}return row, nil}@@ -1303,7 +1311,7 @@ func (s *PasskeyService) updateCredentialAfterAssertionInternal(ctx context.Cont"updated_at": now,})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to update passkey counter")+ return fmt.Errorf("failed to update passkey counter: %w", result.Error)}return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyResponse, nil)}@@ -1360,7 +1368,7 @@ func normalizePasskeyNameInternal(name string) (string, error) {return "", ErrPasskeyName}if utf8.RuneCountInString(name) > maxPasskeyNameRunes {- return "", errors.WrapIf(ErrPasskeyName, "passkey name is too long")+ return "", fmt.Errorf("passkey name is too long: %w", ErrPasskeyName)}return name, nil}@@ -1405,7 +1413,7 @@ func generateRecoveryCodeRowsInternal(userID string) ([]string, []PasskeyRecoverfor i := range codes {raw := make([]byte, 16)if _, err := rand.Read(raw); err != nil {- return nil, nil, errors.WrapIf(err, "failed to generate recovery code")+ return nil, nil, fmt.Errorf("failed to generate recovery code: %w", err)}encoded := strings.TrimRight(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), "=")codes[i] = groupRecoveryCodeInternal(encoded)diff --git a/backend/internal/playwright/gitops.go b/backend/internal/playwright/gitops.goindex aa4e55870..1374909cc 100644--- a/backend/internal/playwright/gitops.go+++ b/backend/internal/playwright/gitops.go@@ -4,9 +4,10 @@ package playwrightimport ("context"+ "errors"+ "fmt""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -29,7 +30,7 @@ func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) errordefer cancel()actor, err := ps.userService.GetUserByUsername(ctx, "arcane")if err != nil {- return errors.WrapIf(err, "failed to get arcane user")+ return fmt.Errorf("failed to get arcane user: %w", err)}repositoryID, err := ps.ensureTestRepositoryInternal(ctx, *actor)if err != nil {@@ -43,10 +44,10 @@ func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) errorif !created || sync.LastSyncStatus == nil || *sync.LastSyncStatus != "success" || sync.LastSyncError != nil {result, err := ps.syncService.PerformSync(ctx, "0", sync.ID, *actor)if err != nil {- return errors.WrapIf(err, "failed to sync GitOps test project")+ return fmt.Errorf("failed to sync GitOps test project: %w", err)}if !result.Success {- return errors.Errorf("GitOps test sync failed: %s", result.Message)+ return fmt.Errorf("GitOps test sync failed: %s", result.Message)}sync, err = ps.syncService.GetSyncByID(ctx, "0", sync.ID)if err != nil {@@ -58,7 +59,7 @@ func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) error}details, err := ps.projectService.GetProjectDetails(ctx, *sync.ProjectID, projecttypes.DetailsOptions{})if err != nil {- return errors.WrapIf(err, "failed to verify GitOps test project")+ return fmt.Errorf("failed to verify GitOps test project: %w", err)}if details.Name != testProjectNameInternal || details.GitOpsManagedBy == nil || *details.GitOpsManagedBy != sync.ID || details.LastSyncCommit == nil || *details.LastSyncCommit != *sync.LastSyncCommit {return errors.New("GitOps test project does not match its managed sync")@@ -96,7 +97,7 @@ func (ps *PlaywrightService) ensureTestRepositoryInternal(ctx context.Context, arepositoryID = created.ID}if err := ps.repositoryService.TestConnection(ctx, repositoryID, testBranchInternal, actor); err != nil {- return "", errors.WrapIf(err, "failed to connect to GitOps test repository")+ return "", fmt.Errorf("failed to connect to GitOps test repository: %w", err)}return repositoryID, nil}diff --git a/backend/internal/playwright/service.go b/backend/internal/playwright/service.goindex 5927a6f33..7ebc627ac 100644--- a/backend/internal/playwright/service.go+++ b/backend/internal/playwright/service.go@@ -7,7 +7,6 @@ import ("fmt""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/gitops""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"@@ -42,7 +41,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, errors.WrapIf(err, "failed to get arcane user")+ return nil, fmt.Errorf("failed to get arcane user: %w", err)}// Grant every recognized permission globally so the test key behaves like@@ -65,7 +64,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, errors.WrapIff(err, "failed to create test API key %d", i+1)+ return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, err)}createdKeys = append(createdKeys, apiKey)@@ -87,7 +86,7 @@ func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {apiKeys, _, err := ps.apiKeyService.ListApiKeys(ctx, params)if err != nil {- return errors.WrapIf(err, "failed to list API keys")+ return fmt.Errorf("failed to list API keys: %w", err)}for _, apiKey := range apiKeys {diff --git a/backend/internal/port/service.go b/backend/internal/port/service.goindex a73639485..f3194a644 100644--- a/backend/internal/port/service.go+++ b/backend/internal/port/service.go@@ -6,7 +6,6 @@ import ("strconv""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/docker"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -26,7 +25,7 @@ func NewPortService(dockerService *docker.DockerClientService) *PortService {func (s *PortService) ListPortsPaginated(ctx context.Context, params pagination.QueryParams) ([]porttypes.PortMapping, pagination.Response, error) {containers, err := s.dockerService.ListContainers(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list containers")+ return nil, pagination.Response{}, fmt.Errorf("failed to list containers: %w", err)}items := make([]porttypes.PortMapping, 0)diff --git a/backend/internal/project/deployment.go b/backend/internal/project/deployment.goindex 734d0bb9a..39ee31829 100644--- a/backend/internal/project/deployment.go+++ b/backend/internal/project/deployment.go@@ -2,7 +2,7 @@ package projectimport ("context"- stderrors "errors"+ "errors""fmt""io""io/fs"@@ -12,7 +12,6 @@ import ("slices""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -68,9 +67,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 errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageRef)+ return fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageRef)}- return errors.WrapIff(err, "failed to pull image %s", imageRef)+ return fmt.Errorf("failed to pull image %s: %w", imageRef, err)}s.reconcilePulledImageRefsInternal(ctx, []string{imageRef})@@ -85,7 +84,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID stif discoverTags {effective, _, err := s.loadComposeProjectForProjectInternal(ctx, proj, nil, servicesToUpdate...)if err != nil {- return errors.WrapIf(err, "load project for service image checks")+ return fmt.Errorf("load project for service image checks: %w", err)}changes, err := s.projectServiceImageChangesInternal(ctx, proj, effective)if err != nil {@@ -111,13 +110,13 @@ func (s *ProjectService) updateProjectServicesInternal(ctx context.Context, projprepare := prepareProjectBindDirectoriesInternal(projectFromDb.Path)compProj, _, err := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, prepare, servicesToUpdate...)if err != nil {- return errors.WrapIf(err, "failed to load compose project")+ return fmt.Errorf("failed to load compose project: %w", err)}dependents, stoppedDependents := s.existingNamespaceDependentsInternal(ctx, compProj, servicesToUpdate)if len(dependents)+len(stoppedDependents) > 0 {slog.InfoContext(ctx, "recreating namespace dependents with updated services", "projectID", projectID, "services", servicesToUpdate, "dependents", dependents, "stoppedDependents", stoppedDependents)if compProj, _, err = s.loadComposeProjectForProjectInternal(ctx, projectFromDb, prepare, slices.Concat(servicesToUpdate, dependents, stoppedDependents)...); err != nil {- return errors.WrapIf(err, "failed to load compose project with dependents")+ return fmt.Errorf("failed to load compose project with dependents: %w", err)}}@@ -133,7 +132,7 @@ func (s *ProjectService) updateProjectServicesInternal(ctx context.Context, projif 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 errors.WrapIf(err, "resolve registry credentials")+ return fmt.Errorf("resolve registry credentials: %w", err)}progressWriter, _ := ctx.Value(dockerutil.ProgressWriterKey{}).(io.Writer)@@ -231,7 +230,7 @@ func prepareProjectBindDirectoriesInternal(projectPath string) projects.PreparePcontinue}if err := ensureProjectBindDirectoryInternal(ctx, projectPath, volume.Source); err != nil {- return errors.WrapIff(err, "bind source %s for service %s", volume.Source, serviceName)+ return fmt.Errorf("bind source %s for service %s: %w", volume.Source, serviceName, err)}}}@@ -286,7 +285,7 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, uservices, servicesErr := s.GetProjectServices(ctx, projectID)switch {case servicesErr != nil && !errors.Is(servicesErr, common.ErrProjectComposeFileNotFound):- return errors.WrapIf(servicesErr, "cannot verify project is stopped before archiving")+ return fmt.Errorf("cannot verify project is stopped before archiving: %w", servicesErr)case servicesErr == nil:if _, running := getServiceCounts(services); running > 0 {return common.Classify(common.ErrProjectMustBeStopped, errors.New("project must be stopped before archiving"))@@ -298,7 +297,7 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, u"is_archived": true,"archived_at": now,}).Error; err != nil {- return errors.WrapIf(err, "failed to archive project")+ return fmt.Errorf("failed to archive project: %w", err)}metadata := database.JSON{"action": "archived", "projectID": projectID, "projectName": proj.Name}@@ -320,7 +319,7 @@ func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string,"is_archived": false,"archived_at": gorm.Expr("NULL"),}).Error; err != nil {- return errors.WrapIf(err, "failed to unarchive project")+ return fmt.Errorf("failed to unarchive project: %w", err)}metadata := database.JSON{"action": "unarchived", "projectID": projectID, "projectName": proj.Name}@@ -332,7 +331,7 @@ func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string,func (s *ProjectService) DeployProject(ctx context.Context, projectID string, user common.User, options *projecttypes.DeployOptions) error {projectFromDb, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {- return errors.WrapIf(err, "failed to get project")+ return fmt.Errorf("failed to get project: %w", err)}if projectFromDb != nil && projectFromDb.IsArchived {return common.Classify(common.ErrProjectArchived, errors.New("project is archived and must be unarchived before this action"))@@ -342,7 +341,7 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us}if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); err != nil {- return errors.WrapIf(err, "failed to update project status to deploying")+ return fmt.Errorf("failed to update project status to deploying: %w", err)}var closeSuppression func()defer func() {@@ -402,18 +401,18 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, userproj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if lerr != nil {_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)- return errors.WrapIf(lerr, "failed to load compose project")+ return fmt.Errorf("failed to load compose project: %w", lerr)}if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusStopped); err != nil {- return errors.WrapIf(err, "failed to update project status to stopping")+ return fmt.Errorf("failed to update project status to stopping: %w", err)}defer s.eventService.BeginComposeSuppressionWindow(proj.Name)()if err := projects.ComposeDown(ctx, proj, false); err != nil {_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)- return errors.WrapIf(err, "failed to bring down project")+ return fmt.Errorf("failed to bring down project: %w", err)}metadata := database.JSON{@@ -434,11 +433,11 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, userfunc (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, manifest projecttypes.CreateProjectWorkspaceManifest, uploads map[int][]byte, uiTags []string, uiTagColors map[string]projecttypes.TagColor, user common.User, allowNameSuffixOptions ...bool) (*Project, error) {normalizedUITags, err := projects.NormalizeProjectTags(uiTags)if err != nil {- return nil, errors.WrapIf(err, "invalid project tags")+ return nil, fmt.Errorf("invalid project tags: %w", err)}normalizedTagColors, err := normalizeProjectTagColorsInternal(uiTagColors)if err != nil {- return nil, errors.WrapIf(err, "invalid project tag colors")+ return nil, fmt.Errorf("invalid project tag colors: %w", err)}allowNameSuffix := trueif len(allowNameSuffixOptions) > 0 {@@ -453,7 +452,7 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentprojectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return nil, errors.WrapIf(err, "failed to get projects directory")+ return nil, fmt.Errorf("failed to get projects directory: %w", err)}basePath := filepath.Join(projectsDirectory, sanitized)@@ -464,11 +463,11 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentprojectPath, folderName, err = projects.CreateExactDir(ctx, projectsDirectory, basePath, name, utils.DirPerm)}if err != nil {- return nil, errors.WrapIf(err, "failed to create project directory")+ return nil, fmt.Errorf("failed to create project directory: %w", err)}projectLogical, err := acfs.LogicalPath(projectsDirectory, projectPath)if err != nil {- return nil, errors.WrapIf(err, "failed to resolve created project directory")+ return nil, fmt.Errorf("failed to resolve created project directory: %w", err)}proj := &Project{@@ -496,13 +495,13 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent// creates (allowNameSuffix=true) stay strict.if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, projectPath, name, composeContent, envContent, nil, "", !allowNameSuffix); err != nil {_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)- return nil, errors.WrapIf(err, "invalid compose file")+ return nil, fmt.Errorf("invalid compose file: %w", err)}if err := projects.WriteProjectFiles(ctx, projectsDirectory, projectPath, composeContent, envContent); err != nil {// Best-effort cleanup to restore pre-transaction behavior._ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)- return nil, errors.WrapIf(err, "failed to save project files")+ return nil, fmt.Errorf("failed to save project files: %w", err)}composeMeta, err := projects.ParseArcaneComposeMetadata(ctx,@@ -523,7 +522,7 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentreturn createUIProjectTagsInternal(tx, proj.ID, normalizedUITags, normalizedTagColors)}); err != nil {_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)- return nil, errors.WrapIf(err, "failed to create project")+ return nil, fmt.Errorf("failed to create project: %w", err)}s.refreshComposeProjectNameInternal(ctx, proj)s.refreshProjectImageRefsInternal(ctx, proj)@@ -533,11 +532,13 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentreturn deleteProjectWithTagsInternal(tx, proj.ID)})fileCleanupErr := acfs.RemoveAll(cleanupCtx, projectsDirectory, projectLogical)- return nil, stderrors.Join(- errors.WrapIf(err, "reconcile Compose project tags"),- errors.WrapIf(databaseCleanupErr, "rollback project database state after tag reconciliation failure"),- errors.WrapIf(fileCleanupErr, "rollback project files after tag reconciliation failure"),- )+ if databaseCleanupErr != nil {+ databaseCleanupErr = fmt.Errorf("rollback project database state after tag reconciliation failure: %w", databaseCleanupErr)+ }+ if fileCleanupErr != nil {+ fileCleanupErr = fmt.Errorf("rollback project files after tag reconciliation failure: %w", fileCleanupErr)+ }+ return nil, errors.Join(fmt.Errorf("reconcile Compose project tags: %w", err), databaseCleanupErr, fileCleanupErr)}metadata := database.JSON{"action": "create", "projectID": proj.ID, "projectName": proj.Name, "path": projectPath}@@ -584,7 +585,7 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r// parent directory and names the project directory itself.if err := acfs.RemoveAll(ctx, filepath.Dir(proj.Path), "/"+filepath.Base(proj.Path)); err != nil {slog.ErrorContext(ctx, "Failed to remove project files", "path", proj.Path, "error", err)- return errors.WrapIf(err, "failed to remove project files")+ return fmt.Errorf("failed to remove project files: %w", err)}slog.InfoContext(ctx, "Project files removed successfully", "path", proj.Path)}@@ -592,7 +593,7 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, rif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {return deleteProjectWithTagsInternal(tx, projectID)}); err != nil {- return errors.WrapIf(err, "failed to delete project from database")+ return fmt.Errorf("failed to delete project from database: %w", err)}if !removeFiles {@@ -674,7 +675,7 @@ func (s *ProjectService) PullProjectImages(ctx context.Context, projectID stringcompProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if lerr != nil {- return errors.WrapIf(lerr, "failed to load compose project")+ return fmt.Errorf("failed to load compose project: %w", lerr)}defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()@@ -696,7 +697,7 @@ func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID strprojectModel, _, derr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if derr != nil {- return errors.WrapIff(derr, "failed to load compose project in %s", projectFromDb.Path)+ return fmt.Errorf("failed to load compose project in %s: %w", projectFromDb.Path, derr)}defer s.eventService.BeginComposeSuppressionWindow(projectModel.Name)()@@ -717,7 +718,7 @@ func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectcompProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if lerr != nil {- return errors.WrapIf(lerr, "failed to load compose project")+ return fmt.Errorf("failed to load compose project: %w", lerr)}defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()@@ -759,20 +760,20 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, s}if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRestarting); err != nil {- return errors.WrapIf(err, "failed to update project status to restarting")+ return fmt.Errorf("failed to update project status to restarting: %w", err)}compProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)if lerr != nil {_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)- return errors.WrapIf(lerr, "failed to load compose project")+ return fmt.Errorf("failed to load compose project: %w", lerr)}defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()if err := projects.ComposeRestart(ctx, compProj, services); err != nil {_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)- return errors.WrapIf(err, "failed to restart project")+ return fmt.Errorf("failed to restart project: %w", err)}metadata := database.JSON{diff --git a/backend/internal/project/details.go b/backend/internal/project/details.goindex fd0e6cb10..b19bbbd2e 100644--- a/backend/internal/project/details.go+++ b/backend/internal/project/details.go@@ -4,6 +4,8 @@ import ("bufio""cmp""context"+ "errors"+ "fmt""io""log/slog""maps"@@ -14,7 +16,6 @@ import ("sync""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"@@ -71,16 +72,14 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contex}serviceCount, runningCount := getServiceCounts(services)-if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{"status": status,"service_count": serviceCount,"running_count": runningCount,"updated_at": time.Now(),}).Error; err != nil {- return errors.WrapIf(err, "failed to update project status and counts")+ return fmt.Errorf("failed to update project status and counts: %w", err)}-return nil}@@ -92,7 +91,7 @@ func (s *ProjectService) updateProjectStatusInternal(ctx context.Context, id str})if res.Error != nil {- return errors.WrapIf(res.Error, "failed to update project status")+ return fmt.Errorf("failed to update project status: %w", res.Error)}return nil@@ -109,7 +108,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinreturn s.projectServicesFromContainersInternal(ctx, projectFromDb, s.ProjectMetadata(ctx, *projectFromDb, nil))}if derr != nil {- return []ProjectServiceInfo{}, errors.WrapIff(derr, "failed to load compose project in %s", projectFromDb.Path)+ return []ProjectServiceInfo{}, fmt.Errorf("failed to load compose project in %s: %w", projectFromDb.Path, derr)}projectsDirectory, projectsDirErr := s.GetProjectsDirectory(ctx)@@ -126,7 +125,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strincontainers, err := projects.ComposePs(ctx, s.dockerService.DockerHost(), composeProject, nil, true)if err != nil {slog.Error("compose ps error", "projectName", composeProject.Name, "error", err)- return nil, errors.WrapIf(err, "failed to get compose services status")+ return nil, fmt.Errorf("failed to get compose services status: %w", err)}imageIDs := s.runtimeImageIDsByContainerInternal(ctx, composeProject.Name)currentContainerID, currentContainerErr := cgroup.CurrentContainerID()@@ -232,7 +231,7 @@ func (s *ProjectService) GetProjectContent(ctx context.Context, projectID string}composePath, composeErr = projects.DetectComposeFile(ctx, projectsDirectory, proj.Path)if composeErr != nil && (!errors.Is(composeErr, common.ErrProjectEnvUnreadable) || composePath == "") {- return "", "", "", errors.WrapIf(composeErr, "failed to identify project compose file")+ return "", "", "", fmt.Errorf("failed to identify project compose file: %w", composeErr)}default:return "", "", "", composeErr@@ -252,7 +251,7 @@ func (s *ProjectService) populateDetailsComposeContentInternal(ctx context.Conte}composeContent, _, overrideContent, err := s.GetProjectContent(ctx, proj.ID)if err != nil {- return errors.WrapIf(err, "failed to read project compose content")+ return fmt.Errorf("failed to read project compose content: %w", err)}resp.ComposeContent = composeContentresp.OverrideFileName, resp.OverrideContent = resolveDetailsOverrideInternal(proj.Path, overrideContent, composeSelection)@@ -273,7 +272,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringvar resp project.Detailsif err := mapping.MapStruct(proj, &resp); err != nil {- return project.Details{}, errors.WrapIf(err, "failed to map project")+ return project.Details{}, fmt.Errorf("failed to map project: %w", err)}resp.CreatedAt = proj.CreatedAt.Format(time.RFC3339)@@ -318,7 +317,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringif opts.IncludeEnvState {envState, err := projects.ReadProjectEnvState(proj.Path)if err != nil {- return project.Details{}, errors.WrapIf(err, "failed to read project env state")+ return project.Details{}, fmt.Errorf("failed to read project env state: %w", err)}effectiveEnvContent, err := resolveStoredEffectiveEnvContentInternal(envState)if err != nil {@@ -796,7 +795,7 @@ func mergeProjectContainerUpdateInfoInternal(base map[string]*imagetypes.UpdateIfunc (s *ProjectService) getProjectImageRefsFromComposeInternal(ctx context.Context, proj Project, env *projectMetadataEnvInternal) ([]string, []string, error) {composeProject, err := s.getCachedComposeProjectInternal(ctx, &proj, env)if err != nil {- return nil, nil, errors.WrapIf(err, "load compose project")+ return nil, nil, fmt.Errorf("load compose project: %w", err)}return projects.ImageRefsFromComposeServices(composeProject.Services), projects.BuildImageRefsFromComposeProject(composeProject), nildiff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.goindex 2a50c198c..497151bbe 100644--- a/backend/internal/project/handler.go+++ b/backend/internal/project/handler.go@@ -2,7 +2,7 @@ package projectimport ("context"- stderrors "errors"+ "errors""fmt""io""log/slog"@@ -11,7 +11,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -402,7 +401,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(errors.WithMessage(err, "Failed to list projects").Error())+ return nil, huma.Error500InternalServerError("Failed to list projects: " + err.Error())}if projects == nil {@@ -422,7 +421,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInfunc (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*handlerutil.Out[projecttypes.StatusCounts], error) {_, running, stopped, total, archived, err := h.projectService.GetProjectStatusCounts(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project status counts").Error())+ return nil, huma.Error500InternalServerError("Failed to get project status counts: " + err.Error())}return &handlerutil.Out[projecttypes.StatusCounts]{@@ -442,7 +441,7 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetPfunc (h *ProjectHandler) ListProjectTags(ctx context.Context, _ *ListProjectTagsInput) (*handlerutil.Out[[]projecttypes.TagOption], error) {options, err := h.projectService.ListProjectTagOptions(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list project tags").Error())+ return nil, huma.Error500InternalServerError("Failed to list project tags: " + err.Error())}if options == nil {options = []projecttypes.TagOption{}@@ -554,7 +553,7 @@ func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectIDif err := cfg.Action(opCtx, writer); err != nil {activitylib.FlushWriter(writer)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.FailureMessage, err)- _, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())+ _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", err.Error())if f, ok := writer.(http.Flusher); ok {f.Flush()}@@ -608,7 +607,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpuif errors.Is(err, common.ErrProjectArchived) || errors.Is(err, common.ErrProjectEnvUnreadable) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to bring down project").Error())+ return nil, huma.Error500InternalServerError("Failed to bring down project: " + err.Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", nil)@@ -625,13 +624,13 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu}func projectUpdateHTTPErrorInternal(err error) error {- if conflictErr, ok := stderrors.AsType[*volumetypes.ProjectVolumeRenameConflictError](err); ok {+ if conflictErr, ok := errors.AsType[*volumetypes.ProjectVolumeRenameConflictError](err); ok {return huma.Error409Conflict(conflictErr.Error())}- if inUseErr, ok := stderrors.AsType[*volumetypes.ProjectVolumeRenameInUseError](err); ok {+ if inUseErr, ok := errors.AsType[*volumetypes.ProjectVolumeRenameInUseError](err); ok {return huma.Error409Conflict(inUseErr.Error())}- if spaceErr, ok := stderrors.AsType[*volumetypes.ProjectVolumeRenameInsufficientSpaceError](err); ok {+ if spaceErr, ok := errors.AsType[*volumetypes.ProjectVolumeRenameInsufficientSpaceError](err); ok {return huma.NewError(http.StatusInsufficientStorage, spaceErr.Error())}return projectWorkspaceRequestHTTPErrorInternal(err)@@ -697,7 +696,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectif httpErr := projectWorkspaceRequestHTTPErrorInternal(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create project").Error())+ return nil, huma.Error500InternalServerError("Failed to create project: " + err.Error())}var response projecttypes.CreateReponse@@ -716,7 +715,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectresponse.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()response.Tags, err = h.projectService.GetProjectTags(ctx, proj.ID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load project tags").Error())+ return nil, huma.Error500InternalServerError("Failed to load project tags: " + err.Error())}return &handlerutil.Out[projecttypes.CreateReponse]{@@ -735,7 +734,7 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, projecttypes.DetailsOptions{})if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())+ return nil, huma.Error404NotFound("Failed to get project details: " + err.Error())}return &handlerutil.Out[projecttypes.Details]{@@ -753,7 +752,7 @@ func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Contexdetails, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, opts)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())+ return nil, huma.Error404NotFound("Failed to get project details: " + err.Error())}return &handlerutil.Out[projecttypes.Details]{@@ -842,7 +841,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(errors.WithMessage(err, "Failed to destroy project").Error())+ return nil, huma.Error500InternalServerError("Failed to destroy project: " + err.Error())}activitylib.FlushWriter(activityWriter)activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", nil)@@ -889,7 +888,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectif httpErr := projectUpdateHTTPErrorInternal(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())+ return nil, huma.Error400BadRequest("Failed to update project: " + err.Error())}details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, projecttypes.DetailsOptions{@@ -901,7 +900,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectIncludeUpdateInfo: true,})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project details").Error())+ return nil, huma.Error500InternalServerError("Failed to get project details: " + err.Error())}details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -972,7 +971,7 @@ func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []return h.projectService.UpdateProjectServices(runtimeCtx, projectID, services, user, true)},Error: projectArchivedActionErrorInternal(func(err error) error {- return huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())+ return huma.Error400BadRequest("Failed to update project: " + err.Error())}),}}@@ -990,7 +989,7 @@ func (h *ProjectHandler) restartProjectActivityConfigInternal(services []string)return h.projectService.RestartProject(runtimeCtx, projectID, services, user)},Error: projectArchivedActionErrorInternal(func(err error) error {- return huma.Error400BadRequest(errors.WithMessage(err, "Failed to restart project").Error())+ return huma.Error400BadRequest("Failed to restart project: " + err.Error())}),}}@@ -1069,7 +1068,7 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjeif errors.Is(err, common.ErrProjectMustBeStopped) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to archive project").Error())+ return nil, huma.Error500InternalServerError("Failed to archive project: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -1091,7 +1090,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(errors.WithMessage(err, "Failed to unarchive project").Error())+ return nil, huma.Error500InternalServerError("Failed to unarchive project: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/project/lifecycle.go b/backend/internal/project/lifecycle.goindex ed6cb41aa..158c0d8b7 100644--- a/backend/internal/project/lifecycle.go+++ b/backend/internal/project/lifecycle.go@@ -4,6 +4,7 @@ import ("bufio""cmp""context"+ "errors""fmt""io""log/slog"@@ -14,7 +15,6 @@ import ("strings""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -119,7 +119,7 @@ func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *Project, async, err := loadGitOpsSyncForProjectInternal(ctx, s.db, project.ID)if err != nil {- return errors.WrapIf(err, "failed to load gitops sync for lifecycle hook")+ return fmt.Errorf("failed to load gitops sync for lifecycle hook: %w", err)}if sync == nil || sync.PreDeployScriptPath == nil || strings.TrimSpace(*sync.PreDeployScriptPath) == "" {return nil@@ -131,21 +131,21 @@ func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *Project, afunc (s *LifecycleService) executePreDeployInternal(ctx context.Context, project *Project, sync *GitOpsSync, actor common.User) error {runnerImage := s.resolveRunnerImageInternal(ctx, sync)if runnerImage == "" {- return errors.Errorf("pre-deploy script %q is configured but no runner image is set on the GitOps sync or lifecycleDefaultRunnerImage setting", *sync.PreDeployScriptPath)+ return fmt.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(ctx, project.Path, scriptPath); err != nil {- return errors.WrapIf(err, "invalid pre-deploy script path")+ return fmt.Errorf("invalid pre-deploy script path: %w", err)}hookEnv, err := ParseEnvText(sync.PreDeployEnv)if err != nil {- return errors.WrapIf(err, "invalid lifecycle env config")+ return fmt.Errorf("invalid lifecycle env config: %w", err)}extraMounts, err := ParseExtraMountsText(sync.PreDeployExtraMounts)if err != nil {- return errors.WrapIf(err, "invalid lifecycle extra mounts config")+ return fmt.Errorf("invalid lifecycle extra mounts config: %w", err)}timeout := s.resolveTimeoutInternal(ctx, sync.PreDeployTimeoutSec)@@ -185,7 +185,7 @@ func (s *LifecycleService) executePreDeployInternal(ctx context.Context, projectreturn runErr}if exitCode != 0 {- return errors.Errorf("pre-deploy script exited with status %d", exitCode)+ return fmt.Errorf("pre-deploy script exited with status %d", exitCode)}return nil}@@ -218,11 +218,11 @@ func (s *LifecycleService) runScriptInContainerInternal() (stdoutContent, stderrContent string, exitCode int64, err error) {dockerClient, dErr := s.dockerService.GetClient(ctx)if dErr != nil {- return "", "", 0, errors.WrapIf(dErr, "failed to connect to Docker")+ return "", "", 0, fmt.Errorf("failed to connect to Docker: %w", dErr)}if err := s.ensureRunnerImageInternal(ctx, dockerClient, runnerImage, actor); err != nil {- return "", "", 0, errors.WrapIff(err, "failed to ensure runner image %s", runnerImage)+ return "", "", 0, fmt.Errorf("failed to ensure runner image %s: %w", runnerImage, err)}// Resolve the workspace mount. When Arcane runs inside a container whose@@ -290,7 +290,7 @@ func (s *LifecycleService) runScriptInContainerInternal(HostConfig: hostConfig,})if err != nil {- return "", "", 0, errors.WrapIf(err, "create lifecycle container")+ return "", "", 0, fmt.Errorf("create lifecycle container: %w", err)}containerID := resp.IDdefer removeLifecycleContainerInternal(ctx, dockerClient, containerID, apiTimeoutSec)@@ -298,7 +298,7 @@ func (s *LifecycleService) runScriptInContainerInternal(startCtx, startCancel := context.WithTimeout(ctx, timeouts.GetDuration(apiTimeoutSec, timeouts.DefaultDockerAPI))defer startCancel()if _, err := dockerClient.ContainerStart(startCtx, containerID, client.ContainerStartOptions{}); err != nil {- return "", "", 0, errors.WrapIf(err, "start lifecycle container")+ return "", "", 0, fmt.Errorf("start lifecycle container: %w", err)}logsCtx, logsCancel := context.WithCancel(ctx)@@ -309,7 +309,7 @@ func (s *LifecycleService) runScriptInContainerInternal(Follow: true,})if err != nil {- return "", "", 0, errors.WrapIf(err, "stream lifecycle container logs")+ return "", "", 0, fmt.Errorf("stream lifecycle container logs: %w", err)}stdoutBuf := capture.New(lifecycleMaxOutputBytes)@@ -331,17 +331,20 @@ func (s *LifecycleService) runScriptInContainerInternal(exitCode = result.StatusCodeif result.Error != nil && result.Error.Message != "" {drainLifecycleLogsInternal(ctx, logsCancel, logs, logDone)- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), exitCode, errors.Errorf("lifecycle container reported error: %s", result.Error.Message)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), exitCode, fmt.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, errors.WrapIff(context.DeadlineExceeded, "pre-deploy script timed out after %s", timeout)+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("pre-deploy script timed out after %s: %w", timeout, context.DeadlineExceeded)}if errors.Is(waitErr, context.Canceled) {- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, errors.WrapIf(waitErr, "pre-deploy script cancelled")+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("pre-deploy script cancelled: %w", waitErr)}- return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, errors.WrapIf(waitErr, "lifecycle container wait failed")+ if waitErr != nil {+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, fmt.Errorf("lifecycle container wait failed: %w", waitErr)+ }+ return markTruncatedInternal(stdoutBuf), markTruncatedInternal(stderrBuf), 0, nil}drainLifecycleLogsInternal(ctx, logsCancel, logs, logDone)@@ -367,9 +370,9 @@ func (s *LifecycleService) ensureRunnerImageInternal(ctx context.Context, dockerif err := s.imageService.PullImage(pullCtx, image, io.Discard, actor, nil); err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return errors.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", image)+ return fmt.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", image)}- return errors.WrapIff(err, "pull runner image %s", image)+ return fmt.Errorf("pull runner image %s: %w", image, err)}return nil}@@ -481,19 +484,19 @@ func validateScriptPathInternal(ctx context.Context, projectPath, scriptPath str// 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 errors.Errorf("script path %q must be relative to the project directory", scriptPath)+ return fmt.Errorf("script path %q must be relative to the project directory", scriptPath)}absProject, err := filepath.Abs(projectPath)if err != nil {- return errors.WrapIf(err, "resolve project path")+ return fmt.Errorf("resolve project path: %w", err)}absScript, err := filepath.Abs(filepath.Join(absProject, scriptPath))if err != nil {- return errors.WrapIf(err, "resolve script path")+ return fmt.Errorf("resolve script path: %w", err)}if !projects.IsSafeSubdirectory(absProject, absScript) {- return errors.Errorf("script path %q escapes project directory", scriptPath)+ return fmt.Errorf("script path %q escapes project directory", scriptPath)}entry, err := acfs.Stat(ctx, absProject, "/"+filepath.ToSlash(scriptPath), false)@@ -509,13 +512,13 @@ func validateScriptPathInternal(ctx context.Context, projectPath, scriptPath str)return nil}- return errors.WrapIff(err, "stat script %q", scriptPath)+ return fmt.Errorf("stat script %q: %w", scriptPath, err)}if entry.IsSymlink {- return errors.Errorf("script path %q is a symlink; symlinks are not allowed", scriptPath)+ return fmt.Errorf("script path %q is a symlink; symlinks are not allowed", scriptPath)}if entry.IsDirectory {- return errors.Errorf("script path %q refers to a directory", scriptPath)+ return fmt.Errorf("script path %q refers to a directory", scriptPath)}return nil}@@ -530,7 +533,7 @@ func ParseEnvText(raw *string) (map[string]string, error) {}env, err := parseKeyValueEnvInternal(*raw)if err != nil {- return nil, errors.WrapIf(err, "invalid env entry")+ return nil, fmt.Errorf("invalid env entry: %w", err)}return env, nil}@@ -558,7 +561,7 @@ func ParseExtraMountsText(raw *string) ([]lifecycletype.ExtraMount, error) {parts := strings.Split(line, ":")if len(parts) < 2 || len(parts) > 3 {- return nil, errors.Errorf("line %d: expected src:tgt[:ro|:rw], got %q", lineNum, line)+ return nil, fmt.Errorf("line %d: expected src:tgt[:ro|:rw], got %q", lineNum, line)}mount := lifecycletype.ExtraMount{Source: parts[0], Target: parts[1]}@@ -569,7 +572,7 @@ func ParseExtraMountsText(raw *string) ([]lifecycletype.ExtraMount, error) {case "rw":mount.Readonly = falsedefault:- return nil, errors.Errorf("line %d: invalid mode %q (expected \"ro\" or \"rw\")", lineNum, parts[2])+ return nil, fmt.Errorf("line %d: invalid mode %q (expected \"ro\" or \"rw\")", lineNum, parts[2])}}@@ -577,16 +580,16 @@ func ParseExtraMountsText(raw *string) ([]lifecycletype.ExtraMount, error) {// 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, errors.Errorf("line %d: source %q must be an absolute path", lineNum, mount.Source)+ return nil, fmt.Errorf("line %d: source %q must be an absolute path", lineNum, mount.Source)}if !path.IsAbs(filepath.ToSlash(mount.Target)) {- return nil, errors.Errorf("line %d: target %q must be an absolute path", lineNum, mount.Target)+ return nil, fmt.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, errors.WrapIf(err, "read extra mounts config")+ return nil, fmt.Errorf("read extra mounts config: %w", err)}return mounts, nil}@@ -611,17 +614,17 @@ func parseKeyValueEnvInternal(stdout string) (map[string]string, error) {}idx := strings.IndexByte(line, '=')if idx <= 0 {- return nil, errors.Errorf("line %d: expected KEY=VALUE, got %q", lineNum, line)+ return nil, fmt.Errorf("line %d: expected KEY=VALUE, got %q", lineNum, line)}key := line[:idx]value := line[idx+1:]if !lifecycleEnvKeyRegex.MatchString(key) {- return nil, errors.Errorf("line %d: invalid env key %q", lineNum, key)+ return nil, fmt.Errorf("line %d: invalid env key %q", lineNum, key)}env[key] = value}if err := scanner.Err(); err != nil {- return nil, errors.WrapIf(err, "read stdout")+ return nil, fmt.Errorf("read stdout: %w", err)}return env, nil}diff --git a/backend/internal/project/listing.go b/backend/internal/project/listing.goindex b6d0677ce..113efd7bd 100644--- a/backend/internal/project/listing.go+++ b/backend/internal/project/listing.go@@ -12,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors"composeapi "github.com/docker/compose/v5/pkg/api""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/image"@@ -154,7 +153,7 @@ func (s *ProjectService) projectServicesFromContainersInternal(ctx context.Contefunc (s *ProjectService) ListAllProjects(ctx context.Context) ([]Project, error) {var items []Projectif err := s.db.WithContext(ctx).Find(&items).Error; err != nil {- return nil, errors.WrapIf(err, "list projects")+ return nil, fmt.Errorf("list projects: %w", err)}return items, nil}@@ -163,7 +162,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {followProjectSymlinks := s.settingsService.GetBoolSetting(ctx, "followProjectSymlinks", false)projectsDir, err := s.GetProjectsDirectory(ctx)if err != nil {- return 0, errors.WrapIf(err, "could not determine projects directory")+ return 0, fmt.Errorf("could not determine projects directory: %w", err)}// os.* rather than acfs: this probes the projects directory itself, which is@@ -174,7 +173,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {return 0, nil}if statErr != nil {- return 0, errors.WrapIff(statErr, "unable to access projects directory %s", projectsDir)+ return 0, fmt.Errorf("unable to access projects directory %s: %w", projectsDir, statErr)}if !info.IsDir() {return 0, nil@@ -182,7 +181,7 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {discoveredProjects, discoveryErr := projects.DiscoverProjectDirectories(ctx, projectsDir, followProjectSymlinks, s.config.ProjectScanMaxDepth)if discoveryErr != nil {- return 0, errors.WrapIff(discoveryErr, "failed to discover project directories in %s", projectsDir)+ return 0, fmt.Errorf("failed to discover project directories in %s: %w", projectsDir, discoveryErr)}return len(discoveredProjects), nil@@ -204,7 +203,7 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCounvar projectsList []Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {- return folderCount, 0, 0, 0, 0, errors.WrapIf(err, "failed to list projects")+ return folderCount, 0, 0, 0, 0, fmt.Errorf("failed to list projects: %w", err)}totalProjects = len(projectsList)@@ -288,7 +287,7 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Quevar projectsArray []ProjectpaginationResp, err := pagination.PaginateAndSortDB(params, query, &projectsArray)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate projects")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate projects: %w", err)}slog.DebugContext(ctx, "Retrieved projects from database",@@ -377,7 +376,7 @@ func (s *ProjectService) filterProjectsWithDerivedFiltersInternal(query = applyProjectSearchDBFilterInternal(query, term)}if err := query.Find(&projectsArray).Error; err != nil {- return pagination.FilterResult[project.Details]{}, errors.WrapIf(err, "failed to list projects")+ return pagination.FilterResult[project.Details]{}, fmt.Errorf("failed to list projects: %w", err)}// Filtering, searching, and sorting only read database columns, tags, and@@ -789,7 +788,7 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, alvar err errorallContainers, err = s.listGlobalComposeContainersInternal(ctx)if err != nil {- return 0, errors.WrapIf(err, "failed to list containers for project update count")+ return 0, fmt.Errorf("failed to list containers for project update count: %w", err)}}@@ -798,7 +797,7 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, al// everything here saves the known-name pass its own table scan.var allProjects []Projectif err := s.db.WithContext(ctx).Find(&allProjects).Error; err != nil {- return 0, errors.WrapIf(err, "failed to list projects for update count")+ return 0, fmt.Errorf("failed to list projects for update count: %w", err)}activeProjects := make([]Project, 0, len(allProjects))diff --git a/backend/internal/project/path_diagnostics_other.go b/backend/internal/project/path_diagnostics_other.goindex 01c529ac1..a4f17b614 100644--- a/backend/internal/project/path_diagnostics_other.go+++ b/backend/internal/project/path_diagnostics_other.go@@ -5,11 +5,7 @@ package projectimport "fmt"func describeLifecyclePathAccessInternal(projectPath, resolvedScriptPath string) string {- return fmt.Sprintf(- "Project path=%q, resolved script path=%q. "+- "Ensure the Arcane process can traverse every parent directory and inspect the script. "+- "A script being executable is not sufficient when ownership, ACLs, or mount permissions block access.",- projectPath,+ return fmt.Sprintf("Project path=%q, resolved script path=%q. Ensure the Arcane process can traverse every parent directory and inspect the script. A script being executable is not sufficient when ownership, ACLs, or mount permissions block access.", projectPath,resolvedScriptPath,)}diff --git a/backend/internal/project/service.go b/backend/internal/project/service.goindex 7a0c4603a..2af36b453 100644--- a/backend/internal/project/service.go+++ b/backend/internal/project/service.go@@ -2,6 +2,8 @@ package projectimport ("context"+ "errors"+ "fmt""io""log/slog""os"@@ -11,7 +13,6 @@ import ("sync""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -77,7 +78,7 @@ func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *Gireturn nil}if project.GitOpsManagedBy != nil && *project.GitOpsManagedBy != "" && *project.GitOpsManagedBy != sync.ID {- return errors.Errorf("project %s is already managed by a different GitOps sync", project.ID)+ return fmt.Errorf("project %s is already managed by a different GitOps sync", project.ID)}cacheBinding := func() {@@ -104,12 +105,12 @@ func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *Giif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if len(updatesSync) > 0 {if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Updates(updatesSync).Error; err != nil {- return errors.WrapIff(err, "failed to relink GitOps sync %s", sync.ID)+ return fmt.Errorf("failed to relink GitOps sync %s: %w", sync.ID, err)}}if len(updatesProject) > 0 {if err := tx.Model(&Project{}).Where("id = ?", project.ID).Updates(updatesProject).Error; err != nil {- return errors.WrapIff(err, "failed to relink project %s to GitOps sync %s", project.ID, sync.ID)+ return fmt.Errorf("failed to relink project %s to GitOps sync %s: %w", project.ID, sync.ID, err)}}return nil@@ -156,13 +157,13 @@ func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *G}if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(project).Error; err != nil {- return errors.WrapIf(err, "failed to create project")+ return fmt.Errorf("failed to create project: %w", err)}if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {- return errors.WrapIf(err, "failed to update sync with project ID")+ return fmt.Errorf("failed to update sync with project ID: %w", err)}if err := tx.Model(&Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", sync.ID).Error; err != nil {- return errors.WrapIf(err, "failed to mark project as GitOps-managed")+ return fmt.Errorf("failed to mark project as GitOps-managed: %w", err)}return nil}); err != nil {@@ -329,7 +330,7 @@ func (s *ProjectService) ResolveRegistryCredentials(ctx context.Context) ([]contcredentials, err := s.RegistryCredentialsProvider(ctx)if err != nil {- return nil, errors.WrapIf(err, "get enabled registry credentials")+ return nil, fmt.Errorf("get enabled registry credentials: %w", err)}return credentials, nil@@ -425,7 +426,7 @@ func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id striif errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("project not found")}- return nil, errors.WrapIf(err, "failed to get project")+ return nil, fmt.Errorf("failed to get project: %w", err)}return &projectModel, nil}@@ -443,7 +444,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strinreturn &proj, nil}if !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, errors.WrapIf(err, "failed to get project by name")+ return nil, fmt.Errorf("failed to get project by name: %w", err)}if cachedProject, found, cacheErr := s.lookupProjectByCachedComposeNameInternal(ctx, normalized); cacheErr != nil {@@ -453,7 +454,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strin}if err := s.rebuildComposeNameCacheInternal(ctx); err != nil {- return nil, errors.WrapIf(err, "failed to list projects by compose name")+ return nil, fmt.Errorf("failed to list projects by compose name: %w", err)}if cachedProject, found, cacheErr := s.lookupProjectByCachedComposeNameInternal(ctx, normalized); cacheErr != nil {@@ -462,7 +463,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strinreturn cachedProject, nil}- return nil, errors.Errorf("project not found: %s", name)+ return nil, fmt.Errorf("project not found: %s", name)}// EnsureProjectPathUnderRoot validates that the project's path is a safe subdirectory of the configured projects root.@@ -471,7 +472,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strinfunc (s *ProjectService) EnsureProjectPathUnderRoot(ctx context.Context, proj *Project, persist bool) error {projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return errors.WrapIf(err, "failed to get projects directory")+ return fmt.Errorf("failed to get projects directory: %w", err)}rootAbs, _ := filepath.Abs(projectsDirectory)@@ -593,9 +594,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, errors.WrapIf(err, "request canceled or timed out")+ return nil, false, fmt.Errorf("request canceled or timed out: %w", err)}- return nil, false, errors.WrapIf(err, "failed to get project by cached compose name")+ return nil, false, fmt.Errorf("failed to get project by cached compose name: %w", err)}if projects.NormalizeProjectName(projectModel.Name) != normalizedName {s.composeNames.invalidateInternal(normalizedName)@@ -669,7 +670,7 @@ func (s *ProjectService) resolveProjectComposeFileUncachedInternal(ctx context.Cif syncID := gitOpsSyncIDInternal(proj); syncID != "" {composePath, found, err := s.gitOpsComposePathInternal(ctx, syncID, env)if err != nil {- return "", errors.WrapIff(err, "failed to resolve GitOps compose path for project %s", proj.ID)+ return "", fmt.Errorf("failed to resolve GitOps compose path for project %s: %w", proj.ID, err)}if found {composeFileName := strings.TrimSpace(filepath.Base(composePath))@@ -683,7 +684,7 @@ func (s *ProjectService) resolveProjectComposeFileUncachedInternal(ctx context.Creturn candidate, nil}} else if !os.IsNotExist(statErr) {- return "", errors.WrapIff(statErr, "failed to inspect GitOps compose file %s", candidate)+ return "", fmt.Errorf("failed to inspect GitOps compose file %s: %w", candidate, statErr)}}}@@ -694,7 +695,7 @@ func (s *ProjectService) resolveProjectComposeFileUncachedInternal(ctx context.Cif errors.Is(err, common.ErrProjectEnvUnreadable) {return "", err}- return "", common.Classify(common.ErrProjectComposeFileNotFound, errors.WrapIf(err, "Project compose file not found"))+ return "", common.Classify(common.ErrProjectComposeFileNotFound, fmt.Errorf("Project compose file not found: %w", err))}return composeFile, nildiff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex 9ac70024a..5ee767768 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -7,6 +7,7 @@ import ("errors""fmt""io"+ "maps""net/http""net/http/httptest""net/netip"@@ -4391,11 +4392,8 @@ func TestProjectService_DeployProject_StopsOnBuildPreparationError(t *testing.T)projectsRoot := t.TempDir()projectDir := filepath.Join(projectsRoot, "demo")require.NoError(t, os.MkdirAll(projectDir, 0o755))- composeContent := "services:\n" +- " web:\n" +- " pull_policy: build\n" +- " build:\n" +- " context: .\n"+ composeContent := "services:\n web:\n pull_policy: build\n build:\n context: .\n"+require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte(composeContent), 0o644))require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot+":"+projectsRoot))@@ -4429,15 +4427,8 @@ func TestProjectService_DeployProject_BuildsGeneratedImageWithoutPull(t *testingprojectsRoot := t.TempDir()projectDir := filepath.Join(projectsRoot, "demo")require.NoError(t, os.MkdirAll(projectDir, 0o755))- composeContent := "services:\n" +- " caddy:\n" +- " build:\n" +- " dockerfile_inline: |\n" +- " FROM caddy:builder AS builder\n" +- " RUN xcaddy build --with github.com/caddyserver/replace-response\n" +- "\n" +- " FROM caddy:latest\n" +- " COPY --from=builder /usr/bin/caddy /usr/bin/caddy\n"+ composeContent := "services:\n caddy:\n build:\n dockerfile_inline: |\n FROM caddy:builder AS builder\n RUN xcaddy build --with github.com/caddyserver/replace-response\n\n FROM caddy:latest\n COPY --from=builder /usr/bin/caddy /usr/bin/caddy\n"+require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte(composeContent), 0o644))require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot+":"+projectsRoot))@@ -7543,9 +7534,7 @@ func TestDiscoveredProjectTagUpdatesRemainScoped(t *testing.T) {require.Len(t, rows, 1, "updater=false containers keep their check results")for _, policy := range []map[string]string{{labels.LabelUpdateStrategy: "digest"}, {labels.LabelUpdateStrategy: "tag", labels.LabelUpdateConstraint: "3.1.x"}, {labels.LabelUpdateStrategy: "tag", labels.LabelUpdateTagPattern: ".*"}, {labels.LabelUpdateStrategy: "tag", imageref.UpdateCheckLabel: "off"}} {current := map[string]string{"com.docker.compose.project": "first-project", "com.docker.compose.service": "web"}- for key, value := range policy {- current[key] = value- }+ maps.Copy(current, policy)containers[1].Labels = currentrows = buildDiscoveredComposeProjectUpdateRowsInternal(t.Context(), containers, nil, imageSvc, "")require.Empty(t, rows, "stale records must not mark discovered projects updated")diff --git a/backend/internal/project/sync.go b/backend/internal/project/sync.goindex 24efafd75..83ced465c 100644--- a/backend/internal/project/sync.go+++ b/backend/internal/project/sync.go@@ -3,6 +3,8 @@ package projectimport ("cmp""context"+ "errors"+ "fmt""log/slog""os""path/filepath"@@ -10,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/samber/mo"@@ -98,7 +99,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, errors.WrapIf(err, "list projects for image ref backfill")+ return 0, fmt.Errorf("list projects for image ref backfill: %w", err)}for i := range projectsList {if err := ctx.Err(); err != nil {@@ -112,7 +113,7 @@ func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context) (int, errfunc (s *ProjectService) resolveProjectsByChangedPathsInternal(ctx context.Context, paths []string) ([]Project, error) {var projectsList []Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {- return nil, errors.WrapIf(err, "list projects for changed paths")+ return nil, fmt.Errorf("list projects for changed paths: %w", err)}seen := make(map[string]struct{})@@ -154,7 +155,7 @@ func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {if os.IsNotExist(discoveryErr) {return nil}- return errors.WrapIff(discoveryErr, "Failed to discover projects in %q", projectsDir)+ return fmt.Errorf("Failed to discover projects in %q: %w", projectsDir, discoveryErr) //nolint:staticcheck // Preserve the existing error message.}renameSyncState := s.activeProjectRenameSyncStateInternal(ctx)@@ -208,13 +209,13 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaslog.Log(ctx, serviceCountLogLevel, "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 errors.WrapIff(cerr, "create project for %q failed", dirPath)+ return fmt.Errorf("create project for %q failed: %w", dirPath, cerr)}s.warnDuplicateComposeNameForPathInternal(ctx, composeMetadata.resolvedProjectName, dirPath, proj.ID)return s.reconcileComposeTagsForProjectInternal(ctx, proj)}if err != nil {- return errors.WrapIff(err, "query existing project for %q failed", dirPath)+ return fmt.Errorf("query existing project for %q failed: %w", dirPath, err)}updates := map[string]any{}@@ -250,7 +251,7 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaModel(&Project{}).Where("id = ?", existing.ID).Updates(updates).Error; uerr != nil {- return errors.WrapIff(uerr, "update project %s failed", existing.ID)+ return fmt.Errorf("update project %s failed: %w", existing.ID, uerr)}if serviceCountErr == nil {s.warnDuplicateComposeNameForPathInternal(ctx, composeMetadata.resolvedProjectName, dirPath, existing.ID)@@ -279,7 +280,7 @@ func (s *ProjectService) warnDuplicateComposeNameForPathInternal(ctx context.Confunc (s *ProjectService) cleanupDBProjectsInternal(ctx context.Context, seen map[string]struct{}, followProjectSymlinks bool, projectsDir string, maxDepth int) error {var all []Projectif err := s.db.WithContext(ctx).Find(&all).Error; err != nil {- return errors.WrapIf(err, "list projects for cleanup failed")+ return fmt.Errorf("list projects for cleanup failed: %w", err)}// Decide deletions without performing them. Collecting decisions up front lets@@ -516,7 +517,7 @@ func (s *ProjectService) resolveEffectiveEnvContentForUpdateInternal(projectPathstate, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return nil, errors.WrapIf(err, "read project env state")+ return nil, fmt.Errorf("read project env state: %w", err)}effectiveContent, err := resolveStoredEffectiveEnvContentInternal(state)@@ -537,7 +538,7 @@ func resolveStoredEffectiveEnvContentInternal(state projects.ProjectEnvState) (sif state.HasGitSource || state.HasOverride {effectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return "", errors.WrapIf(err, "build effective env content")+ return "", fmt.Errorf("build effective env content: %w", err)}return effectiveContent, nil}@@ -547,7 +548,7 @@ func resolveStoredEffectiveEnvContentInternal(state projects.ProjectEnvState) (sfunc persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projectsDirectory, envContent string) error {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return errors.WrapIf(err, "read project env state")+ return fmt.Errorf("read project env state: %w", err)}// WriteManagedEnvFile skips unreadable paths so git sync keeps working; an@@ -558,7 +559,7 @@ func persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projec}for _, name := range targets {if info, statErr := os.Stat(filepath.Join(projectPath, name)); statErr == nil && info.IsDir() {- return errors.Errorf("cannot save environment: %s is a directory", name)+ return fmt.Errorf("cannot save environment: %s is a directory", name)}}@@ -580,12 +581,12 @@ func persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projecoverrideContent, err := projects.BuildOverrideEnvContent(state.GitContent, envContent)if err != nil {- return errors.WrapIf(err, "build override env content")+ return fmt.Errorf("build override env content: %w", err)}effectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, overrideContent)if err != nil {- return errors.WrapIf(err, "build effective env content")+ return fmt.Errorf("build effective env content: %w", err)}if err := projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent); err != nil {@@ -598,7 +599,7 @@ func persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projecfunc (s *ProjectService) ensureEffectiveEnvFileInternal(ctx context.Context, projectPath, projectsDirectory string) error {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return errors.WrapIf(err, "read project env state")+ return fmt.Errorf("read project env state: %w", err)}if !state.HasGitSource {@@ -617,7 +618,7 @@ func (s *ProjectService) ensureEffectiveEnvFileInternal(ctx context.Context, proeffectiveContent, err := projects.BuildEffectiveEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return errors.WrapIf(err, "build effective env content")+ return fmt.Errorf("build effective env content: %w", err)}return projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent)@@ -626,7 +627,7 @@ func (s *ProjectService) ensureEffectiveEnvFileInternal(ctx context.Context, profunc (s *ProjectService) prepareGitSyncEnvUpdateInternal(projectPath string, gitEnvContent *string) (gitSyncEnvUpdateInternal, error) {state, err := projects.ReadProjectEnvState(projectPath)if err != nil {- return gitSyncEnvUpdateInternal{}, errors.WrapIf(err, "read project env state")+ return gitSyncEnvUpdateInternal{}, fmt.Errorf("read project env state: %w", err)}update := gitSyncEnvUpdateInternal{@@ -654,7 +655,7 @@ func (s *ProjectService) prepareGitSyncEnvUpdateInternal(projectPath string, giteffectiveContent, err := projects.BuildEffectiveEnvContent(*gitEnvContent, overrideContent)if err != nil {- return gitSyncEnvUpdateInternal{}, errors.WrapIf(err, "build effective env content")+ return gitSyncEnvUpdateInternal{}, fmt.Errorf("build effective env content: %w", err)}update.effectiveContent = &effectiveContent@@ -666,7 +667,7 @@ func (s *ProjectService) resolveOverrideContentForGitSyncInternal(state projectscase state.HasGitSource:overrideContent, err := projects.BuildOverrideEnvContent(state.GitContent, state.OverrideContent)if err != nil {- return "", errors.WrapIf(err, "build override env content")+ return "", fmt.Errorf("build override env content: %w", err)}return overrideContent, nilcase state.HasOverride:@@ -676,13 +677,13 @@ func (s *ProjectService) resolveOverrideContentForGitSyncInternal(state projects}overrideContent, err := projects.BuildOverrideEnvContent(gitEnvContent, effectiveContent)if err != nil {- return "", errors.WrapIf(err, "build override env content")+ return "", fmt.Errorf("build override env content: %w", err)}return overrideContent, nilcase strings.TrimSpace(state.DirectContent) != "":overrideContent, err := projects.BuildAdditiveOverrideEnvContent(gitEnvContent, state.DirectContent)if err != nil {- return "", errors.WrapIf(err, "build override env content")+ return "", fmt.Errorf("build override env content: %w", err)}return overrideContent, nildefault:@@ -735,14 +736,14 @@ func persistGitSyncEnvFilesInternal(ctx context.Context, projectPath, projectsDifunc (s *ProjectService) ApplyGitSyncEnvToDirectory(ctx context.Context, projectPath, projectsDirectory string, gitEnvContent *string) (before, after string, err error) {update, err := s.prepareGitSyncEnvUpdateInternal(projectPath, gitEnvContent)if err != nil {- return "", "", errors.WrapIf(err, "failed to resolve git env state")+ return "", "", fmt.Errorf("failed to resolve git env state: %w", err)}before = update.state.DirectContentif update.effectiveContent != nil {after = *update.effectiveContent}if err := persistGitSyncEnvFilesInternal(ctx, projectPath, projectsDirectory, update); err != nil {- return "", "", errors.WrapIf(err, "failed to sync git env files")+ return "", "", fmt.Errorf("failed to sync git env files: %w", err)}return before, after, nil}diff --git a/backend/internal/project/tags.go b/backend/internal/project/tags.goindex 11213bdcc..a7c92c30b 100644--- a/backend/internal/project/tags.go+++ b/backend/internal/project/tags.go@@ -2,10 +2,11 @@ package projectimport ("context"+ "errors"+ "fmt""sort""strings"- "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/event"@@ -31,7 +32,7 @@ func (s *ProjectService) GetProjectTags(ctx context.Context, projectID string) (func (s *ProjectService) ListProjectTagOptions(ctx context.Context) ([]projecttypes.TagOption, error) {var rows []ProjectTagif err := s.db.WithContext(ctx).Order("name, source DESC, color").Find(&rows).Error; err != nil {- return nil, errors.WrapIf(err, "list project tag options")+ return nil, fmt.Errorf("list project tag options: %w", err)}options := make([]projecttypes.TagOption, 0)for _, row := range rows {@@ -60,48 +61,54 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name svar projectModel Projecterr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&projectModel, "id = ?", projectID).Error; err != nil {- return errors.WrapIf(err, "find project for tag update")+ return fmt.Errorf("find project for tag update: %w", err)}var composeCount int64if err := tx.Model(&ProjectTag{}).Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceCompose).Count(&composeCount).Error; err != nil {- return errors.WrapIf(err, "check Compose tag source")+ return fmt.Errorf("check Compose tag source: %w", err)}if composeCount > 0 {return errComposeTagReadOnly}- if attached {- var existing int64- if err := tx.Model(&ProjectTag{}).- Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).- Count(&existing).Error; err != nil {- return errors.WrapIf(err, "check UI tag source")+ if !attached {+ if err := tx.Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).+ Delete(&ProjectTag{}).Error; err != nil {+ return fmt.Errorf("detach UI project tag: %w", err)}- if existing > 0 {- return nil- }- var count int64- if err := tx.Model(&ProjectTag{}).- Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceUI).- Count(&count).Error; err != nil {- return errors.WrapIf(err, "count UI project tags")- }- if count >= projectpkg.ProjectTagsPerSourceLimit {- return errors.Errorf("a project cannot have more than %d UI tags", projectpkg.ProjectTagsPerSourceLimit)- }- resolvedColor, err := resolveProjectTagColorInternal(tx, normalized, normalizedColor)- if err != nil {- return err- }- row := ProjectTag{ProjectID: projectID, Name: normalized, Source: string(projecttypes.TagSourceUI), Color: string(resolvedColor)}- return errors.WrapIf(tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error, "attach UI project tag")+ return nil}- return errors.WrapIf(tx.Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).- Delete(&ProjectTag{}).Error, "detach UI project tag")+ var existing int64+ if err := tx.Model(&ProjectTag{}).+ Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).+ Count(&existing).Error; err != nil {+ return fmt.Errorf("check UI tag source: %w", err)+ }+ if existing > 0 {+ return nil+ }+ var count int64+ if err := tx.Model(&ProjectTag{}).+ Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceUI).+ Count(&count).Error; err != nil {+ return fmt.Errorf("count UI project tags: %w", err)+ }+ if count >= projectpkg.ProjectTagsPerSourceLimit {+ return fmt.Errorf("a project cannot have more than %d UI tags", projectpkg.ProjectTagsPerSourceLimit)+ }+ resolvedColor, err := resolveProjectTagColorInternal(tx, normalized, normalizedColor)+ if err != nil {+ return err+ }+ row := ProjectTag{ProjectID: projectID, Name: normalized, Source: string(projecttypes.TagSourceUI), Color: string(resolvedColor)}+ if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil {+ return fmt.Errorf("attach UI project tag: %w", err)+ }+ return nil})if err != nil {return nil, err@@ -120,10 +127,10 @@ func (s *ProjectService) reconcileComposeProjectTagsInternal(ctx context.Contextreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var projectModel Projectif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&projectModel, "id = ?", projectID).Error; err != nil {- return errors.WrapIf(err, "find project for Compose tag reconciliation")+ return fmt.Errorf("find project for Compose tag reconciliation: %w", err)}if err := tx.Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceCompose).Delete(&ProjectTag{}).Error; err != nil {- return errors.WrapIf(err, "clear Compose project tags")+ return fmt.Errorf("clear Compose project tags: %w", err)}if len(normalized) == 0 {return nil@@ -132,7 +139,10 @@ func (s *ProjectService) reconcileComposeProjectTagsInternal(ctx context.Contextfor _, tag := range normalized {rows = append(rows, ProjectTag{ProjectID: projectID, Name: tag.Name, Source: string(projecttypes.TagSourceCompose), Color: string(tag.Color)})}- return errors.WrapIf(tx.Create(&rows).Error, "replace Compose project tags")+ if err := tx.Create(&rows).Error; err != nil {+ return fmt.Errorf("replace Compose project tags: %w", err)+ }+ return nil})}@@ -155,7 +165,7 @@ func normalizeComposeProjectTagsInternal(tags []projecttypes.TagOption) ([]projecontinue}if len(result) >= projectpkg.ProjectTagsPerSourceLimit {- return nil, errors.Errorf("a project cannot have more than %d compose tags", projectpkg.ProjectTagsPerSourceLimit)+ return nil, fmt.Errorf("a project cannot have more than %d compose tags", projectpkg.ProjectTagsPerSourceLimit)}seen[name] = struct{}{}result = append(result, projecttypes.TagOption{Name: name, Color: color})@@ -175,7 +185,10 @@ func createUIProjectTagsInternal(tx *gorm.DB, projectID string, tags []string, c}rows = append(rows, ProjectTag{ProjectID: projectID, Name: tag, Source: string(projecttypes.TagSourceUI), Color: string(color)})}- return errors.WrapIf(tx.Create(&rows).Error, "attach initial project tags")+ if err := tx.Create(&rows).Error; err != nil {+ return fmt.Errorf("attach initial project tags: %w", err)+ }+ return nil}func resolveProjectTagColorInternal(tx *gorm.DB, name string, fallback projecttypes.TagColor) (projecttypes.TagColor, error) {@@ -187,7 +200,7 @@ func resolveProjectTagColorInternal(tx *gorm.DB, name string, fallback projecttycase errors.Is(err, gorm.ErrRecordNotFound):return projectpkg.NormalizeProjectTagColor(fallback)default:- return "", errors.WrapIf(err, "resolve project tag color")+ return "", fmt.Errorf("resolve project tag color: %w", err)}}@@ -223,12 +236,15 @@ func excludeComposeOwnedUITagsInternal(uiTags []string, composeTags []projecttypfunc deleteProjectWithTagsInternal(tx *gorm.DB, projectID string) error {if err := tx.Where("project_id = ?", projectID).Delete(&ProjectTag{}).Error; err != nil {- return errors.WrapIf(err, "delete project tags")+ return fmt.Errorf("delete project tags: %w", err)}if err := tx.Where("mode = ? AND project_id = ?", gitopstypes.SyncModeBackup, projectID).Delete(&GitOpsSync{}).Error; err != nil {- return errors.WrapIf(err, "delete project git backups")+ return fmt.Errorf("delete project git backups: %w", err)}- return errors.WrapIf(tx.Delete(&Project{}, "id = ?", projectID).Error, "delete project")+ if err := tx.Delete(&Project{}, "id = ?", projectID).Error; err != nil {+ return fmt.Errorf("delete project: %w", err)+ }+ return nil}func (s *ProjectService) reconcileComposeTagsForProjectInternal(ctx context.Context, projectModel *Project) error {@@ -237,7 +253,7 @@ func (s *ProjectService) reconcileComposeTagsForProjectInternal(ctx context.Cont}composeFile, err := s.ResolveProjectComposeFile(ctx, projectModel)if err != nil {- return errors.WrapIf(err, "resolve Compose file for tag reconciliation")+ return fmt.Errorf("resolve Compose file for tag reconciliation: %w", err)}projectsDirectory, err := s.GetProjectsDirectory(ctx)if err != nil {@@ -260,7 +276,7 @@ func (s *ProjectService) loadProjectTagsInternal(ctx context.Context, projectIDs}var rows []ProjectTagif err := s.db.WithContext(ctx).Where("project_id IN ?", projectIDs).Order("project_id, name, source, color").Find(&rows).Error; err != nil {- return nil, errors.WrapIf(err, "load project tags")+ return nil, fmt.Errorf("load project tags: %w", err)}for _, row := range rows {tags := result[row.ProjectID]diff --git a/backend/internal/project/update.go b/backend/internal/project/update.goindex 63c99ade9..85ca5822b 100644--- a/backend/internal/project/update.go+++ b/backend/internal/project/update.go@@ -4,7 +4,7 @@ import ("bytes""context""encoding/json/v2"- stderrors "errors"+ "errors""fmt""io""log/slog"@@ -15,7 +15,6 @@ import ("time""unicode/utf8"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -111,7 +110,7 @@ func ensureProjectEnvReadableInternal(ctx context.Context, projectsDirectory, prif cfgErr == nil || !cfgErr.BlocksOperations {return nil}- return common.Classify(common.ErrProjectEnvUnreadable, errors.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it", cfgErr.Path, cfgErr.UID, cfgErr.GID))+ return common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it", cfgErr.Path, cfgErr.UID, cfgErr.GID))}// resolveAuthoritativeProjectNameInternal enforces that a top-level `name:` in@@ -154,7 +153,7 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx contextstateCommitted := projectStateCommitted != nil && *projectStateCommittedif err != nil && volumeMigrationApplied && !stateCommitted {if rollbackErr := volumeMigration.Rollback(ctx); rollbackErr != nil {- err = stderrors.Join(err, errors.WrapIf(rollbackErr, "failed to rollback project volume rename"))+ err = errors.Join(err, fmt.Errorf("failed to rollback project volume rename: %w", rollbackErr))}}}()@@ -181,7 +180,7 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx contextfunc (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *Project) error {tx := s.db.WithContext(ctx).Begin()if tx.Error != nil {- return errors.WrapIf(tx.Error, "failed to start project update transaction")+ return fmt.Errorf("failed to start project update transaction: %w", tx.Error)}txCommitted := false@@ -192,10 +191,10 @@ func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *Pr}()if err := tx.Save(proj).Error; err != nil {- return errors.WrapIf(err, "failed to update project")+ return fmt.Errorf("failed to update project: %w", err)}if err := tx.Commit().Error; err != nil {- return errors.WrapIf(err, "failed to commit project update")+ return fmt.Errorf("failed to commit project update: %w", err)}txCommitted = truereturn nil@@ -208,12 +207,12 @@ func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context,if backup != nil {if restoreErr := projects.RestoreProjectDirectoryBackup(ctx, projectsDirectory, proj.Path, backup); restoreErr != nil {- err = stderrors.Join(err, errors.WrapIf(restoreErr, "failed to restore project files after update failure"))+ err = errors.Join(err, fmt.Errorf("failed to restore project files after update failure: %w", restoreErr))}}if *journalActive {if recoverErr := s.recoverProjectRenameJournalForProjectInternal(ctx, projectID); recoverErr != nil {- err = stderrors.Join(err, errors.WrapIf(recoverErr, "project rename recovery failed"))+ err = errors.Join(err, fmt.Errorf("project rename recovery failed: %w", recoverErr))} else {*journalActive = false}@@ -266,11 +265,11 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectIDenvUpdate, err := s.prepareGitSyncEnvUpdateInternal(proj.Path, gitEnvContent)if err != nil {- return nil, false, errors.WrapIf(err, "failed to resolve git env state")+ return nil, false, fmt.Errorf("failed to resolve git env state: %w", err)}if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, composeContent, envUpdate.effectiveContent, gitOverrideContent, gitOverrideFileName, true); err != nil {- return nil, false, errors.WrapIf(err, "invalid compose file")+ return nil, false, fmt.Errorf("invalid compose file: %w", err)}backup, cleanupBackup, err := s.prepareProjectUpdateBackupInternal(ctx, projectsDirectory, proj.Path, &composeContent, gitEnvContent, gitOverrideContent)@@ -356,16 +355,16 @@ func (s *ProjectService) logGitSyncProjectUpdateInternal(ctx context.Context, pr// the caller restores the pre-update backup.func (s *ProjectService) applyGitSyncProjectFilesInternal(ctx context.Context, proj *Project, projectsDirectory, composeContent string, envUpdate gitSyncEnvUpdateInternal, gitOverrideContent *string, gitOverrideFileName string, projectStateCommitted *bool) error {if err := persistGitSyncEnvFilesInternal(ctx, proj.Path, projectsDirectory, envUpdate); err != nil {- return errors.WrapIf(err, "failed to sync git env files")+ return fmt.Errorf("failed to sync git env files: %w", err)}if err := projects.WriteComposeFile(ctx, projectsDirectory, proj.Path, composeContent); err != nil {- return errors.WrapIf(err, "failed to save compose file")+ return fmt.Errorf("failed to save compose file: %w", err)}if err := projects.WriteComposeOverrideFile(ctx, projectsDirectory, proj.Path, gitOverrideContent, gitOverrideFileName); err != nil {- return errors.WrapIf(err, "failed to sync git override file")+ return fmt.Errorf("failed to sync git override file: %w", err)}if err := s.db.WithContext(ctx).Save(proj).Error; err != nil {- return errors.WrapIf(err, "failed to update project")+ return fmt.Errorf("failed to update project: %w", err)}if projectStateCommitted != nil {*projectStateCommitted = true@@ -379,12 +378,12 @@ func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID striif errors.Is(err, gorm.ErrRecordNotFound) {return Project{}, "", errors.New("project not found")}- return Project{}, "", errors.WrapIf(err, "failed to get project")+ return Project{}, "", fmt.Errorf("failed to get project: %w", err)}projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return Project{}, "", errors.WrapIf(err, "failed to get projects directory")+ return Project{}, "", fmt.Errorf("failed to get projects directory: %w", err)}if err := s.EnsureProjectPathUnderRoot(ctx, &proj, false); err != nil {@@ -405,7 +404,7 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctpreviewLogical, err := acfs.MkdirTemp(ctx, projectsDirectory, "/", ".project-update-preview-*")if err != nil {- return nil, errors.WrapIf(err, "failed to create project update preview")+ return nil, fmt.Errorf("failed to create project update preview: %w", err)}previewPath := filepath.Join(projectsDirectory, filepath.FromSlash(strings.TrimPrefix(previewLogical, "/")))defer func() {@@ -419,13 +418,13 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ct}()if _, err := acfs.CopyDir(ctx, proj.Path, previewPath, acfstypes.CopyOptions{}); err != nil {- return nil, errors.WrapIf(err, "failed to prepare project update preview")+ return nil, fmt.Errorf("failed to prepare project update preview: %w", err)}previewProject := *projpreviewProject.Path = previewPathif err := s.persistUpdatedProjectFiles(ctx, &previewProject, projectsDirectory, composeContent, envContent, overrideContent); err != nil {- return nil, errors.WrapIf(err, "failed to prepare project update preview")+ return nil, fmt.Errorf("failed to prepare project update preview: %w", err)}return s.prepareProjectRenameVolumeMigrationInternal(ctx, &previewProject, name)@@ -442,12 +441,12 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationInternal(ctx contextif errors.Is(err, common.ErrProjectComposeFileNotFound) {return nil, nil}- return nil, errors.WrapIf(err, "failed to load compose project for volume rename")+ return nil, fmt.Errorf("failed to load compose project for volume rename: %w", err)}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker for volume rename")+ return nil, fmt.Errorf("failed to connect to Docker for volume rename: %w", err)}registry := ""@@ -490,11 +489,11 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *Pcase composeContent != nil:effectiveEnvContent, err := s.resolveEffectiveEnvContentForUpdateInternal(proj.Path, envContent)if err != nil {- return errors.WrapIf(err, "invalid compose file")+ return fmt.Errorf("invalid compose file: %w", err)}valOverride, valOverrideName := projects.ResolveEffectiveOverrideForValidation(proj.Path, overrideContent)if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, *composeContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {- return errors.WrapIf(err, "invalid compose file")+ return fmt.Errorf("invalid compose file: %w", err)}// The env is persisted first so WriteComposeFile targets the COMPOSE_FILE// base the updated .env selects, not the one the old .env selected. A@@ -502,16 +501,16 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *P// clients omit it when the compose editor is unchanged.if envContent != nil {if err := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}} else if err := s.ensureEffectiveEnvFileInternal(ctx, proj.Path, projectsDirectory); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}if err := projects.WriteComposeFile(ctx, projectsDirectory, proj.Path, *composeContent); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}if err := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}case overrideContent != nil:if err := s.persistOverrideOnlyUpdateInternal(ctx, proj, projectsDirectory, envContent, overrideContent); err != nil {@@ -534,23 +533,23 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *Pfunc (s *ProjectService) persistOverrideOnlyUpdateInternal(ctx context.Context, proj *Project, projectsDirectory string, envContent, overrideContent *string) error {baseContent, _, err := projects.ReadProjectFiles(ctx, proj.Path, "")if err != nil {- return errors.WrapIf(err, "failed to read project files")+ return fmt.Errorf("failed to read project files: %w", err)}effectiveEnvContent, err := s.resolveEffectiveEnvContentForUpdateInternal(proj.Path, envContent)if err != nil {- return errors.WrapIf(err, "invalid compose file")+ return fmt.Errorf("invalid compose file: %w", err)}valOverride, valOverrideName := projects.ResolveEffectiveOverrideForValidation(proj.Path, overrideContent)if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, baseContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {- return errors.WrapIf(err, "invalid compose file")+ return fmt.Errorf("invalid compose file: %w", err)}if envContent != nil {if err := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}}if err := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); err != nil {- return errors.WrapIf(err, "failed to save project files")+ return fmt.Errorf("failed to save project files: %w", err)}return nil}@@ -560,18 +559,18 @@ func (s *ProjectService) ensureProjectStoppedForRenameInternal(ctx context.Contereturn nil}if proj.Status != ProjectStatusStopped && proj.Status != ProjectStatusUnknown {- return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)+ return fmt.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 errors.WrapIff(err, "project must be stopped before renaming (current status: %s): failed to verify live status", proj.Status)+ return fmt.Errorf("project must be stopped before renaming (current status: %s): failed to verify live status: %w", proj.Status, err)}status := calculateProjectStatus(services)if status != ProjectStatusStopped {- return errors.Errorf("project must be stopped before renaming (current status: %s)", status)+ return fmt.Errorf("project must be stopped before renaming (current status: %s)", status)}serviceCount, runningCount := getServiceCounts(services)@@ -593,7 +592,7 @@ func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *P}if proj.Status != ProjectStatusStopped {- return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)+ return fmt.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)}newDirName := projects.SanitizeProjectName(newName)@@ -606,14 +605,14 @@ func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *Pif currentPath != targetPath {targetLogical, err := acfs.LogicalPath(projectsDirectory, targetPath)if err != nil {- return errors.WrapIf(err, "failed to resolve project directory rename target")+ return fmt.Errorf("failed to resolve project directory rename target: %w", err)}exists, err := acfs.Exists(ctx, projectsDirectory, targetLogical)if err != nil {- return errors.WrapIf(err, "failed to check project directory rename target")+ return fmt.Errorf("failed to check project directory rename target: %w", err)}if exists {- return errors.Errorf("project directory already exists: %s", targetPath)+ return fmt.Errorf("project directory already exists: %s", targetPath)}// An imported project can live outside the projects directory, in which@@ -630,7 +629,7 @@ func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *Perr = acfs.Rename(ctx, projectsDirectory, currentLogical, targetLogical)}if err != nil {- return errors.WrapIf(err, "failed to rename project directory")+ return fmt.Errorf("failed to rename project directory: %w", err)}proj.Path = targetPath@@ -772,11 +771,11 @@ func (s *ProjectService) writeProjectRenameJournalInternal(ctx context.Context,payload, err := json.Marshal(journal)if err != nil {- return errors.WrapIf(err, "marshal project rename journal")+ return fmt.Errorf("marshal project rename journal: %w", err)}if err := s.KVService.Set(ctx, projecttypes.RenameJournalKeyPrefix+journal.ProjectID, string(payload)); err != nil {- return errors.WrapIf(err, "write project rename journal")+ return fmt.Errorf("write project rename journal: %w", err)}return nil}@@ -804,10 +803,10 @@ func (s *ProjectService) writeProjectRenameRollbackCleanupInternal(ctx context.C}payload, err := json.Marshal(cleanup)if err != nil {- return errors.WrapIf(err, "marshal project rename rollback cleanup")+ return fmt.Errorf("marshal project rename rollback cleanup: %w", err)}if err := s.KVService.Set(ctx, projecttypes.RenameRollbackCleanupKeyPrefix+journal.ProjectID, string(payload)); err != nil {- return errors.WrapIf(err, "write project rename rollback cleanup")+ return fmt.Errorf("write project rename rollback cleanup: %w", err)}return nil}@@ -833,15 +832,15 @@ func (s *ProjectService) RecoverProjectRenameJournals(ctx context.Context) errorfor _, entry := range entries {var journal projecttypes.RenameJournalif err := json.Unmarshal([]byte(entry.Value), &journal); err != nil {- recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "decode project rename journal %s", entry.Key))+ recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename journal %s: %w", entry.Key, err))continue}if err := s.recoverProjectRenameJournalInternal(ctx, &journal); err != nil {- recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "recover project rename journal %s", entry.Key))+ recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename journal %s: %w", entry.Key, err))continue}}- return stderrors.Join(recoverErr, s.recoverProjectRenameRollbackCleanupsInternal(ctx))+ return errors.Join(recoverErr, s.recoverProjectRenameRollbackCleanupsInternal(ctx))}func (s *ProjectService) recoverProjectRenameJournalForProjectInternal(ctx context.Context, projectID string) error {@@ -856,7 +855,7 @@ func (s *ProjectService) recoverProjectRenameJournalForProjectInternal(ctx contevar journal projecttypes.RenameJournalif err := json.Unmarshal([]byte(raw), &journal); err != nil {- return errors.WrapIf(err, "decode project rename journal")+ return fmt.Errorf("decode project rename journal: %w", err)}return s.recoverProjectRenameJournalInternal(ctx, &journal)}@@ -869,7 +868,7 @@ func (s *ProjectService) recoverProjectRenameJournalInternal(ctx context.Contextvar proj ProjectdbErr := s.db.WithContext(ctx).First(&proj, "id = ?", journal.ProjectID).Errorif dbErr != nil && !errors.Is(dbErr, gorm.ErrRecordNotFound) {- return errors.WrapIf(dbErr, "load project for rename recovery")+ return fmt.Errorf("load project for rename recovery: %w", dbErr)}projectCommitted := dbErr == nil && (proj.Name == journal.NewName || filepath.Clean(proj.Path) == filepath.Clean(journal.NewPath))@@ -890,11 +889,11 @@ func (s *ProjectService) recoverProjectRenameRollbackCleanupsInternal(ctx contexfor _, entry := range entries {var cleanup projecttypes.RenameRollbackCleanupif err := json.Unmarshal([]byte(entry.Value), &cleanup); err != nil {- recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "decode project rename rollback cleanup %s", entry.Key))+ recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename rollback cleanup %s: %w", entry.Key, err))continue}if err := s.recoverProjectRenameRollbackCleanupInternal(ctx, &cleanup); err != nil {- recoverErr = stderrors.Join(recoverErr, errors.WrapIff(err, "recover project rename rollback cleanup %s", entry.Key))+ recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename rollback cleanup %s: %w", entry.Key, err))continue}}@@ -916,7 +915,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 errors.WrapIf(dbErr, "load project for rename rollback cleanup")+ return fmt.Errorf("load project for rename rollback cleanup: %w", dbErr)}if proj.Name != cleanup.OldName || filepath.Clean(proj.Path) != filepath.Clean(cleanup.OldPath) {@@ -937,7 +936,7 @@ func (s *ProjectService) projectRenameRecoveryDockerInternal(ctx context.ContextdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}return dockerClient, nil@@ -1017,7 +1016,7 @@ func prepareProjectServiceImagesInternal(source []byte, effective *composetypes.return nil, nil, errors.New("tag updates require a single YAML document")}if len(document.Content) != 1 {- return nil, nil, errors.New("Compose source must contain a mapping")+ return nil, nil, errors.New("Compose source must contain a mapping") //nolint:staticcheck // Preserve the existing error message.}if err := validateImageUpdateSourceInternal(document.Content[0]); err != nil {return nil, nil, err@@ -1027,7 +1026,7 @@ func prepareProjectServiceImagesInternal(source []byte, effective *composetypes.}servicesNode := composeImageFieldInternal(document.Content[0], "services")if servicesNode == nil || servicesNode.Kind != yaml.MappingNode {- return nil, nil, errors.New("Compose source has no services mapping")+ return nil, nil, errors.New("Compose source has no services mapping") //nolint:staticcheck // Preserve the existing error message.}serviceNames := make([]string, 0, len(changes))// Rewrite image scalars in place; re-encoding the node tree drops blank lines and operator formatting.@@ -1046,7 +1045,7 @@ func prepareProjectServiceImagesInternal(source []byte, effective *composetypes.}serviceNode := composeImageFieldInternal(servicesNode, name)if composeImageFieldInternal(serviceNode, "extends") != nil {- return nil, nil, errors.Errorf("tag updates do not rewrite extended service %s; update its source manually", name)+ return nil, nil, fmt.Errorf("tag updates do not rewrite extended service %s; update its source manually", name)}imageNode := composeImageFieldInternal(serviceNode, "image")if imageNode == nil || imageNode.Kind != yaml.ScalarNode || imageNode.Tag != "!!str" {@@ -1162,7 +1161,7 @@ func persistProjectServiceImagesInternal(ctx context.Context, projectPath, logicreturn fmt.Errorf("recheck Compose source: %w", err)}if !bytes.Equal(current, original) {- return errors.New("Compose source changed during the image update; check updates again")+ return errors.New("Compose source changed during the image update; check updates again") //nolint:staticcheck // Preserve the existing error message.}if err := acfs.Write(ctx, projectPath, logical, updated, acfs.WriteOptions{Mode: os.FileMode(entry.UnixMode).Perm()}); err != nil {return fmt.Errorf("persist Compose image changes: %w", err)@@ -1192,30 +1191,30 @@ func (s *ProjectService) projectServiceImageChangeInternal(ctx context.Context,return nil, nil}if configuredPolicy.Strategy == "tag" && (refs.IsDigestPinnedReference(service.Image) || refs.IsImageIDLikeReference(service.Image)) {- return nil, errors.Errorf("service %s has an immutable image reference", name)+ return nil, fmt.Errorf("service %s has an immutable image reference", name)}tagPolicy, resolveErr := tagpolicy.Resolve(service.Image, configuredPolicy)if resolveErr != nil {- return nil, errors.WrapIff(resolveErr, "resolve service %s update policy", name)+ return nil, fmt.Errorf("resolve service %s update policy: %w", name, resolveErr)}if tagPolicy.Strategy == "digest" {return nil, nil}if policy.IsUpdateDisabled(service.Labels) {- return nil, errors.Errorf("updates are disabled for service %s", name)+ return nil, fmt.Errorf("updates are disabled for service %s", name)}if service.Build != nil {- return nil, errors.Errorf("tag discovery is unsupported for locally built service %s", name)+ return nil, fmt.Errorf("tag discovery is unsupported for locally built service %s", name)}if proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != "" {return nil, errors.New("tag updates cannot edit a GitOps-managed project; update image tags in the source repository")}if refs.IsDigestPinnedReference(service.Image) || refs.IsImageIDLikeReference(service.Image) {- return nil, errors.Errorf("service %s has an immutable image reference", name)+ return nil, fmt.Errorf("service %s has an immutable image reference", name)}parsed, err := refs.NormalizeReference(service.Image)if err != nil {- return nil, errors.WrapIff(err, "parse service %s image", name)+ return nil, fmt.Errorf("parse service %s image: %w", name, err)}if s.containerRegistryService == nil {return nil, errors.New("registry service unavailable for tag updates")@@ -1226,11 +1225,11 @@ func (s *ProjectService) projectServiceImageChangeInternal(ctx context.Context,}tags, err := s.containerRegistryService.ListImageTags(ctx, service.Image, credentials)if err != nil {- return nil, errors.WrapIff(err, "list service %s image tags", name)+ return nil, fmt.Errorf("list service %s image tags: %w", name, err)}selected, err := tagpolicy.Select(parsed.Tag, tags, tagPolicy)if err != nil {- return nil, errors.WrapIff(err, "select service %s image tag", name)+ return nil, fmt.Errorf("select service %s image tag: %w", name, err)}if selected != parsed.Tag {return &updatertypes.ServiceImageChange{ExpectedRef: service.Image, TargetRef: parsed.RegistryHost + "/" + parsed.Repository + ":" + selected}, nildiff --git a/backend/internal/project/workspace.go b/backend/internal/project/workspace.goindex 2152e391a..5550527dc 100644--- a/backend/internal/project/workspace.go+++ b/backend/internal/project/workspace.go@@ -3,13 +3,14 @@ package projectimport ("context""encoding/json/v2"+ "errors"+ "fmt""io""net/http""os""path/filepath""strings"- "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/event"@@ -44,7 +45,7 @@ func (s *ProjectService) GetProjectWorkspace(ctx context.Context, projectID striworkspacepkg.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB),)if err != nil {- return nil, errors.WrapIf(err, "read project workspace")+ return nil, fmt.Errorf("read project workspace: %w", err)}if ownedPaths, ownedErr := s.gitOpsOwnedWorkspacePathsInternal(ctx, proj); ownedErr == nil && len(ownedPaths) > 0 {for i := range files {@@ -92,7 +93,7 @@ func (s *ProjectService) GetProjectWorkspaceFile(ctx context.Context, projectID,defer func() { _ = reader.Close() }()content, err := io.ReadAll(reader)if err != nil {- return nil, errors.WrapIf(err, "read project workspace file")+ return nil, fmt.Errorf("read project workspace file: %w", err)}response.MimeType = http.DetectContentType(content)if !workspacepkg.IsTextContent(content) {@@ -169,14 +170,14 @@ func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID sopts := s.projectWorkspaceApplyOptionsInternal(ctx, proj, manifest.FileTreeRevision)if err := projects.ApplyProjectWorkspaceChanges(proj.Path, manifest.FileChanges, uploads, opts); err != nil {if restoreErr := projects.RestoreProjectUpdateBackup(ctx, proj.Path, backup); restoreErr != nil {- return nil, errors.Combine(wrapProjectWorkspaceErrorInternal(err), errors.WrapIf(restoreErr, "rollback project workspace"))+ return nil, errors.Join(wrapProjectWorkspaceErrorInternal(err), fmt.Errorf("rollback project workspace: %w", restoreErr))}return nil, wrapProjectWorkspaceErrorInternal(err)}s.refreshProjectImageRefsInternal(ctx, proj)if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {- return nil, errors.WrapIf(err, "refresh project after workspace update")+ return nil, fmt.Errorf("refresh project after workspace update: %w", err)}s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, proj.ID, proj.Name, user, database.JSON{"action": "update_project_workspace",@@ -193,7 +194,7 @@ func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Context}rel, err := kit.NormalizeRelativePath(relativePath)if err != nil {- return nil, "", "", acfstypes.Entry{}, common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, "invalid project workspace path"))+ return nil, "", "", acfstypes.Entry{}, common.Classify(common.ErrProjectWorkspaceForbidden, fmt.Errorf("invalid project workspace path: %w", err))}composeFileName := projects.DefaultComposeFileNameif composeFile, resolveErr := s.ResolveProjectComposeFile(ctx, proj); resolveErr == nil {@@ -216,19 +217,19 @@ func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Context}func classifyProjectWorkspaceACFSErrorInternal(err error, operation string) error {+ if err == nil {+ return nil+ }+switch {- case errors.Is(err, acfs.ErrInvalidPath),- errors.Is(err, acfs.ErrOutsideRoot),- errors.Is(err, acfs.ErrSymlinkLoop),- errors.Is(err, acfs.ErrSymlink):- return common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, operation))- case errors.Is(err, acfs.ErrAlreadyExists),- errors.Is(err, acfs.ErrNotEmpty):- return common.Classify(common.ErrProjectWorkspaceConflict, errors.WrapIf(err, operation))+ case errors.Is(err, acfs.ErrInvalidPath), errors.Is(err, acfs.ErrOutsideRoot), errors.Is(err, acfs.ErrSymlinkLoop), errors.Is(err, acfs.ErrSymlink):+ return common.Classify(common.ErrProjectWorkspaceForbidden, fmt.Errorf("%s: %w", operation, err))+ case errors.Is(err, acfs.ErrAlreadyExists), errors.Is(err, acfs.ErrNotEmpty):+ return common.Classify(common.ErrProjectWorkspaceConflict, fmt.Errorf("%s: %w", operation, err))case os.IsNotExist(err):return common.Classify(common.ErrProjectWorkspaceNotFound, errors.New("project workspace file not found"))default:- return errors.WrapIf(err, operation)+ return fmt.Errorf("%s: %w", operation, err)}}@@ -259,7 +260,7 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,}sync, err := loadGitOpsSyncForProjectInternal(ctx, s.db, proj.ID)if err != nil {- return nil, errors.WrapIf(err, "load gitops sync for workspace")+ return nil, fmt.Errorf("load gitops sync for workspace: %w", err)}if sync == nil {return nil, nil@@ -276,7 +277,7 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,// Fail closed: an incomplete ownership set would expose synced files// as editable, and the next sync would silently overwrite the edits.if err := json.Unmarshal([]byte(*sync.SyncedFiles), &files); err != nil {- return nil, errors.WrapIf(err, "parse gitops synced files for workspace")+ return nil, fmt.Errorf("parse gitops synced files for workspace: %w", err)}for _, f := range files {add(f)@@ -330,8 +331,7 @@ func validateWorkspaceChangesAgainstGitOpsInternal(changes []projecttypes.Workspfor _, change := range changes {for _, target := range workspaceChangeTargetPathsInternal(change) {if touchesOwned(target) {- return common.Classify(common.ErrProjectWorkspaceForbidden,- errors.Errorf("%q is managed by git sync and can only be changed in the git repository", target))+ return common.Classify(common.ErrProjectWorkspaceForbidden, fmt.Errorf("%q is managed by git sync and can only be changed in the git repository", target))}}}@@ -339,11 +339,15 @@ func validateWorkspaceChangesAgainstGitOpsInternal(changes []projecttypes.Worksp}func wrapProjectWorkspaceErrorInternal(err error) error {+ if err == nil {+ return nil+ }+switch {case errors.Is(err, projects.ErrProjectWorkspaceRevisionConflict):- return common.Classify(common.ErrProjectWorkspaceConflict, errors.WithStackIf(err))+ return common.Classify(common.ErrProjectWorkspaceConflict, err)case errors.Is(err, acfs.ErrAlreadyExists), errors.Is(err, acfs.ErrNotEmpty):- return common.Classify(common.ErrProjectWorkspaceConflict, errors.WrapIf(err, "conflicting project workspace path"))+ return common.Classify(common.ErrProjectWorkspaceConflict, fmt.Errorf("conflicting project workspace path: %w", err))case errors.Is(err, projects.ErrProjectWorkspaceOutsideProjectDirectory),errors.Is(err, projects.ErrProjectWorkspaceProtectedPath),errors.Is(err, projects.ErrProjectWorkspaceSymlinkPath),@@ -351,8 +355,8 @@ func wrapProjectWorkspaceErrorInternal(err error) error {errors.Is(err, acfs.ErrInvalidPath),errors.Is(err, acfs.ErrSymlinkLoop),errors.Is(err, acfs.ErrSymlink):- return common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, "forbidden project workspace path"))+ return common.Classify(common.ErrProjectWorkspaceForbidden, fmt.Errorf("forbidden project workspace path: %w", err))default:- return common.Classify(common.ErrProjectWorkspaceBadRequest, errors.WrapIf(err, "invalid project workspace request"))+ return common.Classify(common.ErrProjectWorkspaceBadRequest, fmt.Errorf("invalid project workspace request: %w", err))}}diff --git a/backend/internal/registry/browse.go b/backend/internal/registry/browse.goindex 025303483..e14e820fe 100644--- a/backend/internal/registry/browse.go+++ b/backend/internal/registry/browse.go@@ -3,12 +3,13 @@ package registryimport ("cmp""context"+ "errors"+ "fmt""net/http""slices""strings""sync"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -117,7 +118,7 @@ func (s *ContainerRegistryService) DeleteRepositoryTag(ctx context.Context, id,}tagRef, err := name.NewTag(repo.Name()+":"+strings.TrimSpace(tag), target.nameOptions...)if err != nil {- return "", common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid tag %q", tag))+ return "", common.Classify(common.ErrValidation, fmt.Errorf("invalid tag %q: %w", tag, err))}descriptor, err := remote.Head(tagRef, target.options...)@@ -146,7 +147,7 @@ func (s *ContainerRegistryService) browseTargetInternal(ctx context.Context, id}registryName, err := name.NewRegistry(host, nameOptions...)if err != nil {- return nil, common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid registry URL %q", reg.URL))+ return nil, common.Classify(common.ErrValidation, fmt.Errorf("invalid registry URL %q: %w", reg.URL, err))}credential, err := s.credentialForRegistryInternal(ctx, reg)@@ -177,11 +178,11 @@ func (t *browseTargetInternal) repositoryInternal(repository string) (name.Reposreturn name.Repository{}, common.Classify(common.ErrValidation, errors.New("repository is required"))}if t.prefix != "" && !strings.HasPrefix(repository, t.prefix+"/") {- return name.Repository{}, common.Classify(common.ErrValidation, errors.Errorf("repository %q is outside the registry namespace %q", repository, t.prefix))+ return name.Repository{}, common.Classify(common.ErrValidation, fmt.Errorf("repository %q is outside the registry namespace %q", repository, t.prefix))}repo, err := name.NewRepository(t.registry.Name()+"/"+repository, t.nameOptions...)if err != nil {- return name.Repository{}, common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid repository %q", repository))+ return name.Repository{}, common.Classify(common.ErrValidation, fmt.Errorf("invalid repository %q: %w", repository, err))}return repo, nil}@@ -299,22 +300,25 @@ func tagPlatformInternal(img v1.Image, platform *v1.Platform, digest v1.Hash) (c// classifyBrowseErrorInternal maps distribution API failures to API error kinds.func classifyBrowseErrorInternal(err error, message string) error {+ if err == nil {+ return nil+ }+if errors.Is(err, context.DeadlineExceeded) {- return common.Classify(common.ErrTimeout, errors.WrapIf(err, message))+ return common.Classify(common.ErrTimeout, fmt.Errorf("%s: %w", message, err))}// Upstream auth failures are not Arcane permission failures, so they must not map to 401/403.if isUnauthorizedRegistryErrorInternal(err) {- return common.Classify(common.ErrBadRequest, errors.WrapIf(err, message+": the registry denied access with the configured credentials"))+ return common.Classify(common.ErrBadRequest, fmt.Errorf("%s: %w", message+": the registry denied access with the configured credentials", err))}- var transportErr *transport.Error- if errors.As(err, &transportErr) {+ if transportErr, ok := errors.AsType[*transport.Error](err); ok {switch transportErr.StatusCode {case http.StatusNotFound:- return common.Classify(common.ErrNotFound, errors.WrapIf(err, message))+ return common.Classify(common.ErrNotFound, fmt.Errorf("%s: %w", message, err))case http.StatusMethodNotAllowed:- return common.Classify(common.ErrBadRequest, errors.WrapIf(err, message+": the registry does not allow this operation"))+ return common.Classify(common.ErrBadRequest, fmt.Errorf("%s: %w", message+": the registry does not allow this operation", err))}}- return common.Classify(common.ErrUnavailable, errors.WrapIf(err, message))+ return common.Classify(common.ErrUnavailable, fmt.Errorf("%s: %w", message, err))}diff --git a/backend/internal/registry/browse_handler.go b/backend/internal/registry/browse_handler.goindex 9e645e0d5..278381df6 100644--- a/backend/internal/registry/browse_handler.go+++ b/backend/internal/registry/browse_handler.go@@ -3,7 +3,6 @@ package registryimport ("context"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -80,7 +79,7 @@ func (h *ContainerRegistryHandler) ListRepositories(ctx context.Context, input *repositories, paginationResp, err := h.registryService.ListRepositories(ctx, input.ID, params)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to list repositories").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list repositories: "+err.Error())}return &handlerutil.Page[containerregistry.Repository]{@@ -99,7 +98,7 @@ func (h *ContainerRegistryHandler) ListTags(ctx context.Context, input *ListRegitags, paginationResp, err := h.registryService.ListRepositoryTags(ctx, input.ID, input.Repository, params)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to list tags").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to list tags: "+err.Error())}return &handlerutil.Page[containerregistry.RepositoryTag]{@@ -116,7 +115,7 @@ func (h *ContainerRegistryHandler) DeleteTag(ctx context.Context, input *DeleteRdigest, err := h.registryService.DeleteRepositoryTag(ctx, input.ID, input.Repository, input.Tag)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete tag").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete tag: "+err.Error())}return &handlerutil.Out[containerregistry.DeleteTagResponse]{diff --git a/backend/internal/registry/browse_test.go b/backend/internal/registry/browse_test.goindex b60940753..82f324ab7 100644--- a/backend/internal/registry/browse_test.go+++ b/backend/internal/registry/browse_test.go@@ -80,8 +80,8 @@ func imageSizeInternal(t *testing.T, img v1.Image) int64 {func browseParamsInternal(search string) pagination.QueryParams {return pagination.QueryParams{- SearchQuery: pagination.SearchQuery{Search: search},- Params: pagination.Params{Start: 0, Limit: 20},+ Search: search,+ Start: 0, Limit: 20,}}@@ -123,7 +123,7 @@ func TestContainerRegistryService_ListRepositoryTagsSingleImageInternal(t *testisvc := NewContainerRegistryService(db, nil, nil, nil)id := createBrowseTestRegistryInternal(t, db, host, "", "")- tags, page, err := svc.ListRepositoryTags(context.Background(), id, "team/api", pagination.QueryParams{Params: pagination.Params{Start: 0, Limit: 1}})+ tags, page, err := svc.ListRepositoryTags(context.Background(), id, "team/api", pagination.QueryParams{Start: 0, Limit: 1})require.NoError(t, err)assert.EqualValues(t, 2, page.TotalItems)require.Len(t, tags, 1)@@ -155,9 +155,9 @@ func TestContainerRegistryService_ListRepositoryTagsIndexInternal(t *testing.T)require.NoError(t, err)index := mutate.AppendManifests(empty.Index,- mutate.IndexAddendum{Add: arm64Image, Descriptor: v1.Descriptor{Platform: &arm64}},- mutate.IndexAddendum{Add: amd64Image, Descriptor: v1.Descriptor{Platform: &amd64}},- mutate.IndexAddendum{Add: attestation, Descriptor: v1.Descriptor{Platform: &v1.Platform{OS: "unknown", Architecture: "unknown"}}},+ mutate.IndexAddendum{Add: arm64Image, Platform: &arm64},+ mutate.IndexAddendum{Add: amd64Image, Platform: &amd64},+ mutate.IndexAddendum{Add: attestation, Platform: &v1.Platform{OS: "unknown", Architecture: "unknown"}},)ref, err := name.ParseReference(host + "/team/api:multi")require.NoError(t, err)diff --git a/backend/internal/registry/ecr_token.go b/backend/internal/registry/ecr_token.goindex 795e6493c..9f87e7618 100644--- a/backend/internal/registry/ecr_token.go+++ b/backend/internal/registry/ecr_token.go@@ -3,11 +3,12 @@ package registryimport ("context""encoding/base64"+ "errors"+ "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"@@ -58,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, errors.WrapIff(decErr, "failed to decrypt AWS secret key for registry %s", reg.URL)+ return nil, fmt.Errorf("failed to decrypt AWS secret key for registry %s: %w", reg.URL, decErr)}secretKey = strings.TrimSpace(secretKey)if secretKey == "" {- return nil, errors.Errorf("AWS secret access key is empty for registry %s", reg.URL)+ return nil, fmt.Errorf("AWS secret access key is empty for registry %s", reg.URL)}// Call AWS ECR GetAuthorizationToken.@@ -75,33 +76,33 @@ func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context,)),)if cfgErr != nil {- return nil, errors.WrapIff(cfgErr, "failed to load AWS config for registry %s", reg.URL)+ return nil, fmt.Errorf("failed to load AWS config for registry %s: %w", reg.URL, cfgErr)}ecrClient := ecr.NewFromConfig(cfg)result, ecrErr := ecrClient.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})if ecrErr != nil {- return nil, errors.WrapIff(ecrErr, "failed to get ECR authorization token for registry %s", reg.URL)+ return nil, fmt.Errorf("failed to get ECR authorization token for registry %s: %w", reg.URL, ecrErr)}if len(result.AuthorizationData) == 0 || result.AuthorizationData[0].AuthorizationToken == nil {- return nil, errors.Errorf("ECR returned empty authorization data for registry %s", reg.URL)+ return nil, fmt.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, errors.WrapIff(decodeErr, "failed to decode ECR token for registry %s", reg.URL)+ return nil, fmt.Errorf("failed to decode ECR token for registry %s: %w", reg.URL, decodeErr)}parts := strings.SplitN(string(decoded), ":", 2)if len(parts) != 2 || parts[1] == "" {- return nil, errors.Errorf("unexpected ECR token format for registry %s", reg.URL)+ return nil, fmt.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, errors.WrapIff(encErr, "failed to encrypt ECR token for registry %s", reg.URL)+ return nil, fmt.Errorf("failed to encrypt ECR token for registry %s: %w", reg.URL, encErr)}now := time.Now().UTC()reg.ECRToken = encryptedTokendiff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.goindex 942c0c460..1b4a9da72 100644--- a/backend/internal/registry/handler.go+++ b/backend/internal/registry/handler.go@@ -5,7 +5,6 @@ import ("log/slog""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -173,7 +172,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Liregistries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list registries").Error())+ return nil, huma.Error500InternalServerError("Failed to list registries: " + err.Error())}return &handlerutil.Page[containerregistry.ContainerRegistry]{@@ -189,7 +188,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Lifunc (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *struct{}) (*handlerutil.Out[containerregistry.PullUsageResponse], error) {usage, err := h.registryService.GetRegistryPullUsage(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve registry").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve registry: " + err.Error())}return &handlerutil.Out[containerregistry.PullUsageResponse]{@@ -205,7 +204,7 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Crreg, err := h.registryService.CreateRegistry(ctx, input.Body)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create registry").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create registry: "+err.Error())}h.triggerRemoteRegistrySync(ctx, "registry creation")@@ -225,7 +224,7 @@ func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetCoreg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve registry: "+err.Error())}body, mapErr := handlerutil.MapOneAPIResponse[*ContainerRegistry, containerregistry.ContainerRegistry](reg, func(error) string {@@ -243,7 +242,7 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Upreg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update registry").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update registry: "+err.Error())}h.triggerRemoteRegistrySync(ctx, "registry update")@@ -262,7 +261,7 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Upfunc (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete registry").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete registry: "+err.Error())}h.triggerRemoteRegistrySync(ctx, "registry deletion")@@ -282,13 +281,13 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Testreg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve registry: "+err.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(errors.WithMessage(err, "Registry test failed").Error())+ return nil, huma.Error400BadRequest("Registry test failed: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{@@ -302,11 +301,11 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestdecryptedToken, err := crypto.Decrypt(reg.Token)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to decrypt token").Error())+ return nil, huma.Error500InternalServerError("Failed to decrypt token: " + err.Error())}if err := h.registryService.TestRegistry(ctx, reg.URL, reg.Username, decryptedToken); err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Registry test failed").Error())+ return nil, huma.Error400BadRequest("Registry test failed: " + err.Error())}noCredentials := strings.TrimSpace(reg.Username) == "" && strings.TrimSpace(decryptedToken) == ""@@ -326,7 +325,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Testfunc (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {apiErr := common.ToAPIError(err)- return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync registries").Error())+ return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to sync registries: "+err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.goindex 2c1f728d0..aa1924dce 100644--- a/backend/internal/registry/service.go+++ b/backend/internal/registry/service.go@@ -3,13 +3,13 @@ package registryimport ("context""encoding/json/v2"- stderrors "errors"+ "errors"+ "fmt""log/slog""net/http""strings""time"- "emperror.dev/errors""github.com/cenkalti/backoff/v5"cerrdefs "github.com/containerd/errdefs"ref "github.com/distribution/reference"@@ -22,6 +22,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/google/go-containerregistry/pkg/authn""github.com/google/go-containerregistry/pkg/v1/remote/transport"@@ -149,7 +150,7 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetfunc (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]ContainerRegistry, error) {var registries []ContainerRegistryif err := s.db.WithContext(ctx).Find(®istries).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get container registries")+ return nil, fmt.Errorf("failed to get container registries: %w", err)}return registries, nil}@@ -165,7 +166,7 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, pout, paginationResp, err := params.PaginateSortAndMapDB[ContainerRegistry, containerregistry.ContainerRegistry](q, ®istries)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list container registries")+ return nil, pagination.Response{}, fmt.Errorf("failed to list container registries: %w", err)}return out, paginationResp, nil@@ -177,7 +178,7 @@ func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id strinif errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.ErrContainerRegistryNotFound}- return nil, errors.WrapIf(err, "failed to get container registry")+ return nil, fmt.Errorf("failed to get container registry: %w", err)}return ®istryRecord, nil}@@ -208,40 +209,38 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req contaif registryType == RegistryTypeECR {if strings.TrimSpace(req.AWSAccessKeyID) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Access Key ID is required"), "field", "awsAccessKeyId"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "awsAccessKeyId", Err: errors.New("AWS Access Key ID is required")})}if strings.TrimSpace(req.AWSRegion) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Region is required"), "field", "awsRegion"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "awsRegion", Err: errors.New("AWS Region is required")})}if strings.TrimSpace(req.AWSSecretAccessKey) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Secret Access Key is required"), "field", "awsSecretAccessKey"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "awsSecretAccessKey", Err: errors.New("AWS Secret Access Key is required")})}encryptedSecret, err := crypto.Encrypt(req.AWSSecretAccessKey)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt AWS secret access key")+ return nil, fmt.Errorf("failed to encrypt AWS secret access key: %w", err)}registryRecord.AWSAccessKeyID = req.AWSAccessKeyIDregistryRecord.AWSSecretAccessKey = encryptedSecretregistryRecord.AWSRegion = req.AWSRegion} else {if strings.TrimSpace(req.Username) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Username is required"), "field", "username"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("Username is required")}) //nolint:staticcheck // Preserve the existing error message.}if strings.TrimSpace(req.Token) == "" {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Token is required"), "field", "token"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "token", Err: errors.New("Token is required")}) //nolint:staticcheck // Preserve the existing error message.}encryptedToken, err := crypto.Encrypt(req.Token)if err != nil {- return nil, errors.WrapIf(err, "failed to encrypt token")+ return nil, fmt.Errorf("failed to encrypt token: %w", err)}registryRecord.Username = req.UsernameregistryRecord.Token = encryptedToken}-if err := s.db.WithContext(ctx).Create(registryRecord).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create registry")+ return nil, fmt.Errorf("failed to create registry: %w", err)}-return registryRecord, nil}@@ -305,12 +304,11 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string}registryRecord.UpdatedAt = time.Now()-if err := s.db.WithContext(ctx).Save(registryRecord).Error; err != nil {- return nil, errors.WrapIf(err, "failed to update registry")+ return nil, fmt.Errorf("failed to update registry: %w", err)}-- return registryRecord, nil+ return registryRecord,+ nil}func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *ContainerRegistry, registryType *string) error {@@ -324,7 +322,7 @@ func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *Con}if nextType != registry.RegistryType {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Registry type cannot be changed after creation"), "field", "registryType"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "registryType", Err: errors.New("Registry type cannot be changed after creation")}) //nolint:staticcheck // Preserve the existing error message.}return nil@@ -337,19 +335,19 @@ func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *Conif req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "" {encryptedSecret, err := crypto.Encrypt(*req.AWSSecretAccessKey)if err != nil {- return errors.WrapIf(err, "failed to encrypt AWS secret access key")+ return fmt.Errorf("failed to encrypt AWS secret access key: %w", err)}utils.ApplyChanged(®istry.AWSSecretAccessKey, mo.Some(encryptedSecret))}if strings.TrimSpace(registry.AWSAccessKeyID) == "" {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Access Key ID is required"), "field", "awsAccessKeyId"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsAccessKeyId", Err: errors.New("AWS Access Key ID is required")})}if strings.TrimSpace(registry.AWSRegion) == "" {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Region is required"), "field", "awsRegion"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsRegion", Err: errors.New("AWS Region is required")})}if strings.TrimSpace(registry.AWSSecretAccessKey) == "" {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("AWS Secret Access Key is required"), "field", "awsSecretAccessKey"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsSecretAccessKey", Err: errors.New("AWS Secret Access Key is required")})}if req.AWSAccessKeyID != nil || req.AWSSecretAccessKey != nil || req.AWSRegion != nil {@@ -366,13 +364,13 @@ func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registryif req.Token != nil && *req.Token != "" {encryptedToken, err := crypto.Encrypt(*req.Token)if err != nil {- return errors.WrapIf(err, "failed to encrypt token")+ return fmt.Errorf("failed to encrypt token: %w", err)}utils.ApplyChanged(®istry.Token, mo.Some(encryptedToken))}if strings.TrimSpace(registry.Username) == "" {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Username is required"), "field", "username"))+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("Username is required")}) //nolint:staticcheck // Preserve the existing error message.}return nil@@ -380,7 +378,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(&ContainerRegistry{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete container registry")+ return fmt.Errorf("failed to delete container registry: %w", err)}return nil}@@ -394,7 +392,7 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id strdecryptedToken, err := crypto.Decrypt(registryRecord.Token)if err != nil {- return "", errors.WrapIf(err, "failed to decrypt token")+ return "", fmt.Errorf("failed to decrypt token: %w", err)}return decryptedToken, nil@@ -404,7 +402,7 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id strfunc (s *ContainerRegistryService) GetEnabledRegistries(ctx context.Context) ([]ContainerRegistry, error) {var registries []ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get enabled container registries")+ return nil, fmt.Errorf("failed to get enabled container registries: %w", err)}return registries, nil}@@ -642,7 +640,7 @@ func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg Cotoken, err := crypto.Decrypt(reg.Token)if err != nil {- return nil, "credential", username, errors.WrapIf(err, "failed to decrypt Docker Hub credential")+ return nil, "credential", username, fmt.Errorf("failed to decrypt Docker Hub credential: %w", err)}token = strings.TrimSpace(token)@@ -733,7 +731,7 @@ func (s *ContainerRegistryService) setCachedRateLimitInternal(ctx context.Contexfunc normalizePullRegistryHostInternal(imageRef string) (string, error) {registryHost, err := utilsregistry.GetRegistryAddress(imageRef)if err != nil {- return "", errors.WrapIff(err, "parse image registry for %q", imageRef)+ return "", fmt.Errorf("parse image registry for %q: %w", imageRef, err)}return utilsregistry.NormalizeRegistryForComparison(registryHost), nil@@ -789,7 +787,7 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURLServerAddress: normalizeRegistryServerAddressInternal(registryURL),})if err != nil {- return errors.WrapIf(err, "registry login failed")+ return fmt.Errorf("registry login failed: %w", err)}return nil@@ -800,7 +798,7 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURLfunc (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *ContainerRegistry) error {ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)if err != nil {- return errors.WrapIf(err, "failed to obtain ECR token")+ return fmt.Errorf("failed to obtain ECR token: %w", err)}dockerClient, err := s.getDockerClientInternal(ctx)@@ -814,7 +812,7 @@ func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *ConServerAddress: normalizeRegistryServerAddressInternal(reg.URL),})if err != nil {- return errors.WrapIf(err, "ECR registry login failed")+ return fmt.Errorf("ECR registry login failed: %w", err)}return nil@@ -908,7 +906,7 @@ func (s *ContainerRegistryService) InspectImageDigest(ctx context.Context, image}lastResult = fallbackResult- lastErr = errors.WrapIf(stderrors.Join(err, fallbackErr), "daemon digest lookup failed; registry fallback failed")+ lastErr = fmt.Errorf("daemon digest lookup failed; registry fallback failed: %w", errors.Join(err, fallbackErr))return nil, backoff.Permanent(lastErr)}, backoff.WithBackOff(bo), backoff.WithMaxTries(5))@@ -964,13 +962,13 @@ func registryOperationWithCredentialsInternal[T any](ctx context.Context, s *Con}lastErr = errif !isUnauthorizedRegistryErrorInternal(err) {- return zero, lastResult, errors.WrapIff(err, "%s failed with credentials", operation)+ return zero, lastResult, fmt.Errorf("%s failed with credentials: %w", operation, err)}}if lastErr != nil {// Docker Hub anonymous quotas are too small to be worth a retry; elsewhere a stale credential must not break public images.if isDockerHubRegistryInternal(registryHost) {- return zero, lastResult, errors.WrapIff(lastErr, "%s failed", operation)+ return zero, lastResult, fmt.Errorf("%s failed: %w", operation, lastErr)}slog.DebugContext(ctx, "credentialed registry lookup failed, retrying anonymously","registry", registryHost,@@ -984,9 +982,9 @@ func registryOperationWithCredentialsInternal[T any](ctx context.Context, s *Conreturn value, result, nil}if credErr != nil && isUnauthorizedRegistryErrorInternal(err) {- return zero, result, errors.WrapIff(stderrors.Join(err, credErr), "%s: anonymous access unauthorized; credential lookup failed", operation)+ return zero, result, fmt.Errorf("%s: anonymous access unauthorized; credential lookup failed: %w", operation, errors.Join(err, credErr))}- return zero, result, errors.WrapIff(err, "%s failed", operation)+ return zero, result, fmt.Errorf("%s failed: %w", operation, err)}func (s *ContainerRegistryService) getDockerClientInternal(ctx context.Context) (RegistryDaemonClient, error) {@@ -996,7 +994,7 @@ func (s *ContainerRegistryService) getDockerClientInternal(ctx context.Context)dockerClient, err := s.dockerClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get docker client")+ return nil, fmt.Errorf("failed to get docker client: %w", err)}if dockerClient == nil {return nil, errors.New("docker client unavailable")@@ -1031,7 +1029,7 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx coregistries, err := s.GetEnabledRegistries(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to load enabled registries")+ return nil, fmt.Errorf("failed to load enabled registries: %w", err)}creds := make([]resolvedRegistryCredential, 0, len(registries))@@ -1060,7 +1058,7 @@ func (s *ContainerRegistryService) credentialForRegistryInternal(ctx context.Conif reg.RegistryType == RegistryTypeECR {ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)if err != nil {- return nil, errors.WrapIf(err, "failed to get ECR token")+ return nil, fmt.Errorf("failed to get ECR token: %w", err)}return &resolvedRegistryCredential{Username: ecrUser,@@ -1076,7 +1074,7 @@ func (s *ContainerRegistryService) credentialForRegistryInternal(ctx context.Contoken, err := crypto.Decrypt(reg.Token)if err != nil {- return nil, errors.WrapIf(err, "failed to decrypt registry token")+ return nil, fmt.Errorf("failed to decrypt registry token: %w", err)}token = strings.TrimSpace(token)if token == "" {@@ -1119,7 +1117,7 @@ func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItemsfunc (s *ContainerRegistryService) getExistingRegistriesMapInternal(ctx context.Context) (map[string]*ContainerRegistry, error) {var existingRegistries []ContainerRegistryif err := s.db.WithContext(ctx).Find(&existingRegistries).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get existing registries")+ return nil, fmt.Errorf("failed to get existing registries: %w", err)}existingMap := make(map[string]*ContainerRegistry)@@ -1147,7 +1145,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 errors.WrapIff(err, "failed to update registry %s", item.ID)+ return fmt.Errorf("failed to update registry %s: %w", item.ID, err)}}@@ -1195,7 +1193,7 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containtokenChanged, err := utils.ApplyEncrypted(&existing.Token, item.Token)if err != nil {- return false, errors.WrapIff(err, "failed to apply token for registry %s", existing.ID)+ return false, fmt.Errorf("failed to apply token for registry %s: %w", existing.ID, err)}return tokenChanged || needsUpdate, nil}@@ -1207,7 +1205,7 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containif item.AWSSecretAccessKey != "" {secretChanged, err := utils.ApplyEncrypted(&existing.AWSSecretAccessKey, item.AWSSecretAccessKey)if err != nil {- return false, errors.WrapIff(err, "failed to apply AWS secret for registry %s", existing.ID)+ return false, fmt.Errorf("failed to apply AWS secret for registry %s: %w", existing.ID, err)}credChanged = secretChanged || credChanged}@@ -1251,21 +1249,19 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.ContextencryptedToken, err := crypto.Encrypt(item.Token)if err != nil {- return errors.WrapIff(err, "failed to encrypt token for new registry %s", item.ID)+ return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)}newRegistry.Token = encryptedToken} else if item.AWSSecretAccessKey != "" {encryptedSecret, err := crypto.Encrypt(item.AWSSecretAccessKey)if err != nil {- return errors.WrapIff(err, "failed to encrypt AWS secret for new registry %s", item.ID)+ return fmt.Errorf("failed to encrypt AWS secret for new registry %s: %w", item.ID, err)}newRegistry.AWSSecretAccessKey = encryptedSecret}-if err := s.db.WithContext(ctx).Create(newRegistry).Error; err != nil {- return errors.WrapIff(err, "failed to create registry %s", item.ID)+ return fmt.Errorf("failed to create registry %s: %w", item.ID, err)}-return nil}@@ -1279,7 +1275,7 @@ func NormalizeRegistryType(value string) (string, error) {case RegistryTypeGeneric, RegistryTypeECR:return registryType, nildefault:- return "", common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Registry type must be one of: generic, ecr"), "field", "registryType"))+ return "", common.Classify(common.ErrValidation, &base.FieldError{Field: "registryType", Err: errors.New("Registry type must be one of: generic, ecr")}) //nolint:staticcheck // Preserve the existing error message.}}@@ -1293,7 +1289,7 @@ func normalizeRepositoryNamesInternal(raw []string) (database.StringSlice, error// A repository name is only a path, so pair it with placeholder domain// and tag segments to validate it against the reference grammar.if _, err := ref.ParseNormalizedNamed("registry.invalid/" + name + "/placeholder:latest"); err != nil {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("invalid repository name %q", name), "field", "repositoryNames"))+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "repositoryNames", Err: fmt.Errorf("invalid repository name %q", name)})}result = append(result, name)}@@ -1305,7 +1301,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(&ContainerRegistry{}).Error; err != nil {- return errors.WrapIff(err, "failed to delete registry %s", id)+ return fmt.Errorf("failed to delete registry %s: %w", id, err)}}}@@ -1343,8 +1339,7 @@ func isUnauthorizedRegistryErrorInternal(err error) bool {if cerrdefs.IsUnauthorized(err) || cerrdefs.IsPermissionDenied(err) {return true}- var registryErr *transport.Error- if errors.As(err, ®istryErr) {+ if registryErr, ok := errors.AsType[*transport.Error](err); ok {return registryErr.StatusCode == http.StatusUnauthorized || registryErr.StatusCode == http.StatusForbidden}@@ -1426,7 +1421,7 @@ func (s *ContainerRegistryService) fetchDigestFromDaemonInternal(ctx context.Conif credential != nil {authHeader, err := utilsregistry.EncodeAuthHeader(credential.Username, credential.Token, credential.ServerAddress)if err != nil {- return "", errors.WrapIff(err, "encode registry auth header for %s", registryHost)+ return "", fmt.Errorf("encode registry auth header for %s: %w", registryHost, err)}inspectOptions.EncodedRegistryAuth = authHeader}@@ -1437,7 +1432,7 @@ func (s *ContainerRegistryService) fetchDigestFromDaemonInternal(ctx context.Con}digestValue, err := digest.Normalize(inspectResult.Descriptor.Digest.String())if err != nil {- return "", errors.WrapIff(err, "distribution inspect returned invalid digest for %s", normalizedRef)+ return "", fmt.Errorf("distribution inspect returned invalid digest for %s: %w", normalizedRef, err)}return digestValue, nil}diff --git a/backend/internal/registry/service_label.go b/backend/internal/registry/service_label.goindex c85113c77..d74e4442a 100644--- a/backend/internal/registry/service_label.go+++ b/backend/internal/registry/service_label.go@@ -2,11 +2,12 @@ package registryimport ("context"+ "errors"+ "fmt""runtime""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/google/go-containerregistry/pkg/name"v1 "github.com/google/go-containerregistry/pkg/v1"@@ -53,18 +54,18 @@ func (s *ContainerRegistryService) ImageVersionLabel(ctx context.Context, imageRfunc fetchImageVersionLabelInternal(ctx context.Context, imageRef string) (string, error) {parsedRef, err := name.ParseReference(imageRef)if err != nil {- return "", errors.WrapIff(err, "invalid image reference %q", imageRef)+ return "", fmt.Errorf("invalid image reference %q: %w", imageRef, err)}img, err := remote.Image(parsedRef,remote.WithContext(ctx),remote.WithPlatform(v1.Platform{OS: "linux", Architecture: runtime.GOARCH}))if err != nil {- return "", errors.WrapIff(err, "version label fetch failed for %s", imageRef)+ return "", fmt.Errorf("version label fetch failed for %s: %w", imageRef, err)}cfg, err := img.ConfigFile()if err != nil {- return "", errors.WrapIff(err, "version label fetch failed for %s", imageRef)+ return "", fmt.Errorf("version label fetch failed for %s: %w", imageRef, err)}if cfg == nil || strings.TrimSpace(cfg.Config.Labels[ociImageVersionLabel]) == "" {return "", ErrNoVersionLabeldiff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.goindex 09c2ddec7..03eff3785 100644--- a/backend/internal/registry/service_test.go+++ b/backend/internal/registry/service_test.go@@ -4,6 +4,7 @@ import ("context""encoding/base64""encoding/json"+ "errors""net/http""net/http/httptest""net/url"@@ -11,10 +12,10 @@ import ("testing""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/kv"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/libtnb/sqlite"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"@@ -406,7 +407,9 @@ func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "registryType")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "registryType", fieldErr.Field)}func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(t *testing.T) {@@ -421,7 +424,9 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "username")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "username", fieldErr.Field)}func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *testing.T) {@@ -436,7 +441,9 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "token")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "token", fieldErr.Field)}func TestContainerRegistryService_CreateRegistry_AcceptsValidGenericCredentials(t *testing.T) {@@ -470,7 +477,9 @@ func TestContainerRegistryService_UpdateRegistry_RejectsBlankingUsername(t *testrequire.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "username")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "username", fieldErr.Field)}func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvided(t *testing.T) {@@ -522,7 +531,9 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTorequire.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "token")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "token", fieldErr.Field)stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)require.NoError(t, loadErr)@@ -634,7 +645,9 @@ func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "registryType")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "registryType", fieldErr.Field)}func TestContainerRegistryService_UpdateRegistry_AllowsSameRegistryType(t *testing.T) {@@ -1333,7 +1346,9 @@ func TestContainerRegistryService_CreateRegistry_RejectsInvalidRepositoryName(tRepositoryNames: []string{"team:latest"},})require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), "repositoryNames")+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, "repositoryNames", fieldErr.Field)}func TestContainerRegistryService_UpdateRegistry_RepositoryNamesPointerSemantics(t *testing.T) {diff --git a/backend/internal/registry/tags.go b/backend/internal/registry/tags.goindex 72f784609..a7423abb3 100644--- a/backend/internal/registry/tags.go+++ b/backend/internal/registry/tags.go@@ -2,8 +2,8 @@ package registryimport ("context"+ "errors"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/google/go-containerregistry/pkg/authn"diff --git a/backend/internal/registry/tags_test.go b/backend/internal/registry/tags_test.goindex 615852623..c476b5d9c 100644--- a/backend/internal/registry/tags_test.go+++ b/backend/internal/registry/tags_test.go@@ -3,12 +3,12 @@ package registryimport ("context""encoding/base64"+ "errors""io""net/http""strings""testing"- "emperror.dev/errors""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"diff --git a/backend/internal/role/handler.go b/backend/internal/role/handler.goindex d31eb993f..d11c3f308 100644--- a/backend/internal/role/handler.go+++ b/backend/internal/role/handler.go@@ -2,9 +2,9 @@ package roleimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"diff --git a/backend/internal/role/service.go b/backend/internal/role/service.goindex bc0b43792..d16119863 100644--- a/backend/internal/role/service.go+++ b/backend/internal/role/service.go@@ -3,13 +3,14 @@ package roleimport ("context""encoding/json/v2"+ "errors"+ "fmt""log/slog""maps""slices""strings""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/kv"@@ -26,18 +27,10 @@ import ()const (- // permissionCacheTTL bounds how long a resolved PermissionSet is reused- // before re-querying the DB. The service also invalidates entries explicitly- // on mutation paths, so this TTL is a safety net.- permissionCacheTTL = 60 * time.Second-+ permissionCacheTTL = 60 * time.SecondlegacyRoleBackfillCompletedKey = "migration.legacy_user_roles.v1.completed")-// RoleService owns role definitions, user role assignments, OIDC role-// mappings, and API key permissions. It resolves a caller's effective-// PermissionSet on demand and caches the result per-user / per-key for a-// short TTL to keep the hot path off the database.type RoleService struct {db *database.DBuserCache *hot.HotCache[string, *authz.PermissionSet]@@ -58,10 +51,6 @@ func NewRoleService(db *database.DB) *RoleService {}}-// ---------- Boot-time reconciliation & safety checks ------------// EnsureBuiltInRoles overwrites the permission set on every built-in role to-// match the Go constants. Idempotent. Called at boot after migrations succeed.func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {builtIns := map[string]struct {name string@@ -86,7 +75,7 @@ func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {BuiltIn: true,}if err := tx.Save(&role).Error; err != nil {- return errors.WrapIff(err, "failed to upsert built-in role %s", id)+ return fmt.Errorf("failed to upsert built-in role %s: %w", id, err)}}return nil@@ -109,7 +98,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {claimed, err := kv.NewKVService(&database.DB{DB: tx}).CreateIfAbsent(ctx, legacyRoleBackfillCompletedKey, time.Now().UTC().Format(time.RFC3339))if err != nil {- return errors.WrapIf(err, "failed to claim legacy role backfill marker")+ return fmt.Errorf("failed to claim legacy role backfill marker: %w", err)}if !claimed {return nil@@ -118,7 +107,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {if err := tx.Table("users").Select("id, roles").Where("NOT EXISTS (SELECT 1 FROM user_role_assignments ura WHERE ura.user_id = users.id)").Scan(&rows).Error; err != nil {- return errors.WrapIf(err, "failed to read legacy users.roles for backfill")+ return fmt.Errorf("failed to read legacy users.roles for backfill: %w", err)}for _, u := range rows {roleID := kit.Ternary(legacyRolesContainsAdminInternal(u.Roles), authz.BuiltInRoleAdmin, authz.BuiltInRoleViewer)@@ -129,7 +118,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {}result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&assignment)if result.Error != nil {- return errors.WrapIff(result.Error, "failed to backfill assignment for user %s", u.ID)+ return fmt.Errorf("failed to backfill assignment for user %s: %w", u.ID, result.Error)}inserted += result.RowsAffected}@@ -167,14 +156,11 @@ func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {return err}if count == 0 {- return common.Classify(common.ErrNoGlobalAdminRemains, errors.- New("At least one user must retain a global Admin role assignment"))+ return common.Classify(common.ErrNoGlobalAdminRemains, errors.New("At least one user must retain a global Admin role assignment")) //nolint:staticcheck // Preserve the existing error message.}return nil}-// ---------- Role CRUD -----------func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParams) ([]Role, pagination.Response, error) {var roles []Rolequery := s.db.WithContext(ctx).Model(&Role{})@@ -186,7 +172,7 @@ func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryPararesp, err := pagination.PaginateAndSortDB(params, query, &roles)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate roles")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate roles: %w", err)}return roles, resp, nil}@@ -194,7 +180,7 @@ func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParafunc (s *RoleService) ListAllRoles(ctx context.Context) ([]Role, error) {var roles []Roleif err := s.db.WithContext(ctx).Order("name").Find(&roles).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list roles")+ return nil, fmt.Errorf("failed to list roles: %w", err)}return roles, nil}@@ -220,7 +206,7 @@ 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(&Role{}).Where("name = ?", input.Name).Count(&conflict).Error; err != nil {- return errors.WrapIf(err, "failed to check role name uniqueness")+ return fmt.Errorf("failed to check role name uniqueness: %w", err)}if conflict > 0 {return common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))@@ -245,7 +231,7 @@ func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error)Where("role_id = ?", roleID).Distinct("user_id").Pluck("user_id", &ids).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list users assigned to role")+ return nil, fmt.Errorf("failed to list users assigned to role: %w", err)}if len(ids) == 0 {return ids, nil@@ -256,7 +242,7 @@ func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error)Where("id IN ?", ids).Order("id").Pluck("id", &locked).Error; err != nil {- return nil, errors.WrapIf(err, "failed to lock users assigned to role")+ return nil, fmt.Errorf("failed to lock users assigned to role: %w", err)}return ids, nil}@@ -276,15 +262,15 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptiif errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))}- return errors.WrapIf(err, "failed to load role")+ return fmt.Errorf("failed to load role: %w", err)}if existing.BuiltIn {- return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified"))+ return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified")) //nolint:staticcheck // Preserve the existing error message.}if input.Name != existing.Name {var conflict int64if err := tx.Model(&Role{}).Where("name = ? AND id <> ?", input.Name, id).Count(&conflict).Error; err != nil {- return errors.WrapIf(err, "failed to check role name uniqueness")+ return fmt.Errorf("failed to check role name uniqueness: %w", err)}if conflict > 0 {return common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))@@ -297,7 +283,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptiexisting.Description = input.Descriptionexisting.Permissions = permissionsif err := tx.Save(&existing).Error; err != nil {- return errors.WrapIf(err, "failed to update role")+ return fmt.Errorf("failed to update role: %w", err)}out = existingreturn nil@@ -317,22 +303,20 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))}- return errors.WrapIf(err, "failed to load role")+ return fmt.Errorf("failed to load role: %w", err)}if existing.BuiltIn {- 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"))+ return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified")) //nolint:staticcheck // Preserve the existing error message.}+ // Collect affected users before deleting the role.ids, err := lockAssignedUserRowsInternal(tx, id)if err != nil {return err}affected = idsif err := tx.Delete(&Role{}, "id = ?", id).Error; err != nil {- return errors.WrapIf(err, "failed to delete role")+ return fmt.Errorf("failed to delete role: %w", err)}return nil})@@ -357,7 +341,7 @@ func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID strinDistinct("user_id").Where("role_id = ?", roleID).Count(&count).Error; err != nil {- return 0, errors.WrapIf(err, "failed to count users assigned to role")+ return 0, fmt.Errorf("failed to count users assigned to role: %w", err)}return int(count), nil}@@ -370,7 +354,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, errors.WrapIf(err, "failed to list user assignments")+ return nil, fmt.Errorf("failed to list user assignments: %w", err)}return out, nil}@@ -396,18 +380,18 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contexif errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrUserNotFound}- return errors.WrapIf(err, "failed to lock user for assignment update")+ return fmt.Errorf("failed to lock user for assignment update: %w", err)}if err := validateAssignmentsExistInternal(tx, desired); err != nil {return err}if err := tx.Where("user_id = ? AND source = ?", userID, source).Delete(&UserRoleAssignment{}).Error; err != nil {- return errors.WrapIff(err, "failed to clear %s assignments", source)+ return fmt.Errorf("failed to clear %s assignments: %w", source, err)}if len(desired) > 0 {if err := tx.Create(&desired).Error; err != nil {- return errors.WrapIff(err, "failed to insert %s assignments", source)+ return fmt.Errorf("failed to insert %s assignments: %w", source, err)}}count, err := s.countEffectiveGlobalAdminsInternal(ctx, tx, "")@@ -415,7 +399,7 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contexreturn err}if count == 0 {- return common.Classify(common.ErrNoGlobalAdminRemains, errors.New("At least one user must retain a global Admin role assignment"))+ return common.Classify(common.ErrNoGlobalAdminRemains, errors.New("At least one user must retain a global Admin role assignment")) //nolint:staticcheck // Preserve the existing error message.}return nil})@@ -451,7 +435,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)roleIDs := slices.Collect(maps.Keys(roleIDSet))var found []stringif err := tx.Model(&Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {- return errors.WrapIf(err, "failed to verify role ids")+ return fmt.Errorf("failed to verify role ids: %w", err)}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -459,7 +443,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)}for id := range roleIDSet {if _, ok := foundSet[id]; !ok {- return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: role %q does not exist", id))+ return common.Classify(common.ErrInvalidRoleAssignment, fmt.Errorf("invalid role assignment: role %q does not exist", id))}}}@@ -468,7 +452,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)envIDs := slices.Collect(maps.Keys(envIDSet))var found []stringif err := tx.Table("environments").Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {- return errors.WrapIf(err, "failed to verify environment ids")+ return fmt.Errorf("failed to verify environment ids: %w", err)}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -476,7 +460,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)}for id := range envIDSet {if _, ok := foundSet[id]; !ok {- return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: environment %q does not exist", id))+ return common.Classify(common.ErrInvalidRoleAssignment, fmt.Errorf("invalid role assignment: environment %q does not exist", id))}}}@@ -517,7 +501,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, txquery = query.Where("u.id <> ?", excludedUserID)}if err := query.Scan(&rows).Error; err != nil {- return 0, errors.WrapIf(err, "failed to list global role permissions for admin count")+ return 0, fmt.Errorf("failed to list global role permissions for admin count: %w", err)}permissionsByUser := make(map[string]*authz.PermissionSet, len(rows))@@ -529,7 +513,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, tx}perms, err := decodePermissionsJSONInternal(r.Permissions)if err != nil {- return 0, errors.WrapIf(err, "failed to decode role permissions")+ return 0, fmt.Errorf("failed to decode role permissions: %w", err)}ps.AddGlobal(perms...)}@@ -577,13 +561,13 @@ func (s *RoleService) ResolveUserPermissionsInDB(_ context.Context, tx *gorm.DB,Joins("INNER JOIN roles r ON r.id = ura.role_id").Where("ura.user_id = ?", userID).Scan(&rows).Error; err != nil {- return nil, errors.WrapIf(err, "failed to resolve user permissions")+ return nil, fmt.Errorf("failed to resolve user permissions: %w", err)}ps := authz.NewPermissionSet()for _, r := range rows {perms, err := decodePermissionsJSONInternal(r.Permissions)if err != nil {- return nil, errors.WrapIf(err, "failed to decode role permissions")+ return nil, fmt.Errorf("failed to decode role permissions: %w", err)}if r.EnvironmentID == nil {ps.AddGlobal(perms...)@@ -616,7 +600,7 @@ func (s *RoleService) ResolveExecutionPermissions(ctx context.Context, userID, kdb := s.db.WithContext(ctx)var user common.Userif err := db.Select("id").First(&user, "id = ?", userID).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load requesting user")+ return nil, fmt.Errorf("failed to load requesting user: %w", err)}if keyID == "" {return s.ResolveUserPermissionsInDB(ctx, db, userID)@@ -629,7 +613,7 @@ func (s *RoleService) ResolveExecutionPermissions(ctx context.Context, userID, kExpiresAt *time.Time}if err := db.Table("api_keys").Select("id, kind, user_id, environment_id, expires_at").Where("id = ?", keyID).Take(&key).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load requesting API key")+ return nil, fmt.Errorf("failed to load requesting API key: %w", err)}if key.UserID == nil || *key.UserID != userID || (key.ExpiresAt != nil && !key.ExpiresAt.After(time.Now())) {return nil, errors.New("requesting API key is no longer valid")@@ -680,7 +664,7 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID strfunc (s *RoleService) resolveApiKeyPermissionsInDBInternal(db *gorm.DB, apiKeyID string) (*authz.PermissionSet, error) {var grants []ApiKeyPermissionif err := db.Where("api_key_id = ?", apiKeyID).Find(&grants).Error; err != nil {- return nil, errors.WrapIf(err, "failed to resolve api key permissions")+ return nil, fmt.Errorf("failed to resolve api key permissions: %w", err)}permissions := authz.NewPermissionSet()for _, grant := range grants {@@ -713,11 +697,11 @@ func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB,grants[i].ApiKeyID = apiKeyID}if err := tx.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Delete(&ApiKeyPermission{}).Error; err != nil {- return errors.WrapIf(err, "failed to clear api key permissions")+ return fmt.Errorf("failed to clear api key permissions: %w", err)}if len(grants) > 0 {if err := tx.WithContext(ctx).Create(&grants).Error; err != nil {- return errors.WrapIf(err, "failed to insert api key permissions")+ return fmt.Errorf("failed to insert api key permissions: %w", err)}}return nil@@ -728,7 +712,7 @@ func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB,func (s *RoleService) ListOidcMappings(ctx context.Context) ([]OidcRoleMapping, error) {var out []OidcRoleMappingif err := s.db.WithContext(ctx).Order("claim_value, role_id").Find(&out).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list oidc mappings")+ return nil, fmt.Errorf("failed to list oidc mappings: %w", err)}return out, nil}@@ -758,7 +742,7 @@ func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleIDSource: OidcMappingSourceManual,}if err := tx.Create(&mapping).Error; err != nil {- return errors.WrapIf(err, "failed to create oidc mapping")+ return fmt.Errorf("failed to create oidc mapping: %w", err)}return nil})@@ -784,7 +768,7 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolif errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}- return errors.WrapIf(err, "failed to load mapping")+ return fmt.Errorf("failed to load mapping: %w", err)}if existing.Source == OidcMappingSourceEnv {return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))@@ -796,7 +780,7 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolexisting.RoleID = roleIDexisting.EnvironmentID = environmentIDif err := tx.Save(&existing).Error; err != nil {- return errors.WrapIf(err, "failed to update mapping")+ return fmt.Errorf("failed to update mapping: %w", err)}out = existingreturn nil@@ -822,7 +806,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {normalized := slices.Collect(maps.Keys(roleIDSet))var found []stringif err := tx.Model(&Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {- return errors.WrapIf(err, "failed to verify role ids")+ return fmt.Errorf("failed to verify role ids: %w", err)}foundSet := make(map[string]struct{}, len(found))for _, id := range found {@@ -830,7 +814,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {}for _, id := range normalized {if _, ok := foundSet[id]; !ok {- return common.Classify(common.ErrInvalidRoleAssignment, errors.Errorf("invalid role assignment: role %q does not exist", id))+ return common.Classify(common.ErrInvalidRoleAssignment, fmt.Errorf("invalid role assignment: role %q does not exist", id))}}return nil@@ -843,13 +827,13 @@ func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}- return errors.WrapIf(err, "failed to load mapping")+ return fmt.Errorf("failed to load mapping: %w", err)}if existing.Source == OidcMappingSourceEnv {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(&OidcRoleMapping{}, "id = ?", id).Error; err != nil {- return errors.WrapIf(err, "failed to delete mapping")+ return fmt.Errorf("failed to delete mapping: %w", err)}return nil})@@ -873,14 +857,14 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri}var specs []roletypes.OidcRoleMappingSpecif err := json.Unmarshal([]byte(rawSpec), &specs); err != nil {- return errors.WrapIf(err, "invalid OIDC_ROLE_MAPPINGS JSON")+ return fmt.Errorf("invalid OIDC_ROLE_MAPPINGS JSON: %w", err)}for i, sp := range specs {if strings.TrimSpace(sp.ClaimValue) == "" {- return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: claimValue is required", i)+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: claimValue is required", i)}if strings.TrimSpace(sp.RoleID) == "" {- return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: roleId is required", i)+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: roleId is required", i)}}@@ -890,17 +874,17 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec strifor i, sp := range specs {var count int64if err := tx.Model(&Role{}).Where("id = ?", sp.RoleID).Count(&count).Error; err != nil {- return errors.WrapIff(err, "OIDC_ROLE_MAPPINGS[%d]: failed to verify role", i)+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: failed to verify role: %w", i, err)}if count == 0 {- return errors.Errorf("OIDC_ROLE_MAPPINGS[%d]: role %q does not exist", i, sp.RoleID)+ return fmt.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 = ?", OidcMappingSourceEnv).Delete(&OidcRoleMapping{}).Error; err != nil {- return errors.WrapIf(err, "failed to clear env-managed mappings")+ return fmt.Errorf("failed to clear env-managed mappings: %w", err)}if len(specs) == 0 {slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled (empty)", "envManagedCount", 0)@@ -916,7 +900,7 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri}}if err := tx.Create(&rows).Error; err != nil {- return errors.WrapIf(err, "failed to insert env-managed mappings")+ return fmt.Errorf("failed to insert env-managed mappings: %w", err)}slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled", "envManagedCount", len(rows))return nildiff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.goindex 6280a5b46..d20edeaee 100644--- a/backend/internal/role/service_test.go+++ b/backend/internal/role/service_test.go@@ -2,12 +2,12 @@ package roleimport ("context"+ "errors""path/filepath""slices""testing""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/session"@@ -383,7 +383,7 @@ func TestResolveExecutionPermissions(t *testing.T) {user := createTestUser(t, db, "owner", "owner")grantGlobalAdmin(t, service, user.ID)environmentID := "env-1"- key := testApiKeyRow{BaseModel: database.BaseModel{ID: "personal"}, Kind: "personal", UserID: &user.ID, EnvironmentID: &environmentID}+ key := testApiKeyRow{ID: "personal", Kind: "personal", UserID: &user.ID, EnvironmentID: &environmentID}require.NoError(t, db.Create(&key).Error)permissions, err := service.ResolveExecutionPermissions(t.Context(), user.ID, key.ID)require.NoError(t, err)@@ -403,7 +403,7 @@ func TestResolveExecutionPermissions(t *testing.T) {db, service := setupUserAndRoleServices(t)user := createTestUser(t, db, "owner", "owner")environmentID := "env-1"- key := testApiKeyRow{BaseModel: database.BaseModel{ID: "scoped"}, Kind: "scoped", UserID: &user.ID, EnvironmentID: &environmentID}+ key := testApiKeyRow{ID: "scoped", Kind: "scoped", UserID: &user.ID, EnvironmentID: &environmentID}require.NoError(t, db.Create(&key).Error)require.NoError(t, service.SetApiKeyPermissions(t.Context(), key.ID, []ApiKeyPermission{{Permission: authz.PermJobsManage}}))cached, err := service.ResolveApiKeyPermissions(t.Context(), key.ID)@@ -427,11 +427,11 @@ func TestResolveExecutionPermissions(t *testing.T) {emptyEnvironment := ""expired := time.Now().Add(-time.Minute)for _, key := range []testApiKeyRow{- {BaseModel: database.BaseModel{ID: "expired"}, Kind: "personal", UserID: &user.ID, ExpiresAt: &expired},- {BaseModel: database.BaseModel{ID: "other-owner"}, Kind: "personal", UserID: &otherOwner},- {BaseModel: database.BaseModel{ID: "ownerless"}, Kind: "scoped"},- {BaseModel: database.BaseModel{ID: "invalid-kind"}, Kind: "unknown", UserID: &user.ID},- {BaseModel: database.BaseModel{ID: "invalid-scope"}, Kind: "personal", UserID: &user.ID, EnvironmentID: &emptyEnvironment},+ {ID: "expired", Kind: "personal", UserID: &user.ID, ExpiresAt: &expired},+ {ID: "other-owner", Kind: "personal", UserID: &otherOwner},+ {ID: "ownerless", Kind: "scoped"},+ {ID: "invalid-kind", Kind: "unknown", UserID: &user.ID},+ {ID: "invalid-scope", Kind: "personal", UserID: &user.ID, EnvironmentID: &emptyEnvironment},} {require.NoError(t, db.Create(&key).Error)_, err := service.ResolveExecutionPermissions(t.Context(), user.ID, key.ID)diff --git a/backend/internal/s3/handler.go b/backend/internal/s3/handler.goindex dd8a1ccb7..e8846dedb 100644--- a/backend/internal/s3/handler.go+++ b/backend/internal/s3/handler.go@@ -2,10 +2,10 @@ package s3import ("context"+ "errors""log/slog""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/s3/service.go b/backend/internal/s3/service.goindex 961cc1233..a72cc4577 100644--- a/backend/internal/s3/service.go+++ b/backend/internal/s3/service.go@@ -2,10 +2,10 @@ package s3import ("context"+ "errors""fmt""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -308,7 +308,7 @@ func (s *S3DestinationService) SyncS3Destinations(ctx context.Context, destinaticontinue}if err := s.DeleteS3Destination(ctx, existing[i].ID); err != nil {- removeErr = errors.Combine(removeErr, fmt.Errorf("failed to remove unsynced S3 destination %s: %w", existing[i].ID, err))+ removeErr = errors.Join(removeErr, fmt.Errorf("failed to remove unsynced S3 destination %s: %w", existing[i].ID, err))}}return removeErrdiff --git a/backend/internal/s3/service_test.go b/backend/internal/s3/service_test.goindex e8472ade8..2f72115f5 100644--- a/backend/internal/s3/service_test.go+++ b/backend/internal/s3/service_test.go@@ -68,8 +68,8 @@ func TestS3DestinationService_CRUD(t *testing.T) {require.NotEqual(t, "secret-key", stored.SecretAccessKey)listed, page, err := service.ListS3Destinations(ctx, pagination.QueryParams{- SearchQuery: pagination.SearchQuery{Search: "arcane-backups"},- Params: pagination.Params{Limit: 20},+ Search: "arcane-backups",+ Limit: 20,})require.NoError(t, err)require.EqualValues(t, 1, page.TotalItems)diff --git a/backend/internal/session/service.go b/backend/internal/session/service.goindex 630c0f106..122d8c89b 100644--- a/backend/internal/session/service.go+++ b/backend/internal/session/service.go@@ -4,11 +4,12 @@ import ("cmp""context""crypto/subtle"+ "errors"+ "fmt""strings""time""uuid"- "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/pkg/utils/dbutil"@@ -43,11 +44,9 @@ func (s *SessionService) CreateSession(ctx context.Context, userID string, expirLastUsedAt: now,ExpiresAt: expiresAt,}-if err := s.db.WithContext(ctx).Create(session).Error; err != nil {- return nil, "", errors.WrapIf(err, "failed to create user session")+ return nil, "", fmt.Errorf("failed to create user session: %w", err)}-return session, refreshJTI, nil}@@ -63,11 +62,9 @@ func (s *SessionService) CreateFederatedSession(ctx context.Context, userID striLastUsedAt: now,ExpiresAt: expiresAt,}-if err := s.db.WithContext(ctx).Create(session).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create federated user session")+ return nil, fmt.Errorf("failed to create federated user session: %w", err)}-return session, nil}@@ -81,7 +78,7 @@ func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (if errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.ErrInvalidToken}- return nil, errors.WrapIf(err, "failed to get user session")+ return nil, fmt.Errorf("failed to get user session: %w", err)}return &session, nil}@@ -103,7 +100,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID, refrif errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrInvalidToken}- return errors.WrapIf(err, "failed to get user session for rotation")+ return fmt.Errorf("failed to get user session for rotation: %w", err)}if err := ValidateActive(&session); err != nil {return err@@ -123,7 +120,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID, refrWhere("id = ? AND refresh_token_hash = ? AND revoked_at IS NULL", session.ID, session.RefreshTokenHash).Updates(updates)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to rotate refresh token")+ return fmt.Errorf("failed to rotate refresh token: %w", result.Error)}if result.RowsAffected != 1 {return common.ErrInvalidToken@@ -153,7 +150,7 @@ func (s *SessionService) RevokeSession(ctx context.Context, sessionID string) erif err := s.db.WithContext(ctx).Model(&UserSession{}).Where("id = ? AND revoked_at IS NULL", sessionID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return errors.WrapIf(err, "failed to revoke user session")+ return fmt.Errorf("failed to revoke user session: %w", err)}return nil}@@ -165,7 +162,7 @@ func (s *SessionService) DeleteExpiredSessions(ctx context.Context, revokedRetenWhere("expires_at < ? OR (revoked_at IS NOT NULL AND revoked_at < ?)", now, revokedCutoff).Delete(&UserSession{})if result.Error != nil {- return 0, errors.WrapIf(result.Error, "failed to delete expired user sessions")+ return 0, fmt.Errorf("failed to delete expired user sessions: %w", result.Error)}return result.RowsAffected, nil}@@ -189,7 +186,7 @@ func RevokeAllUserSessionsExceptInDB(ctx context.Context, db *gorm.DB, userID, equery = query.Where("id <> ?", exceptSessionID)}if err := query.Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {- return errors.WrapIf(err, "failed to revoke user sessions")+ return fmt.Errorf("failed to revoke user sessions: %w", err)}return nil}@@ -200,7 +197,7 @@ func ValidateActive(userSession *UserSession) error {return common.ErrInvalidToken}if userSession.RevokedAt != nil {- return common.Classify(common.ErrSessionRevoked, errors.New("Session has been revoked"))+ return common.Classify(common.ErrSessionRevoked, errors.New("Session has been revoked")) //nolint:staticcheck // Preserve the existing error message.}return kit.Ternary[error](time.Now().After(userSession.ExpiresAt), common.ErrExpiredToken, nil)}diff --git a/backend/internal/settings/features.go b/backend/internal/settings/features.goindex 735b20610..a509ecce9 100644--- a/backend/internal/settings/features.go+++ b/backend/internal/settings/features.go@@ -2,9 +2,9 @@ package settingsimport ("context"+ "fmt""strconv"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/types/v2/features"kit "go.getarcane.app/kit/pkg"@@ -33,5 +33,5 @@ func (s *SettingsService) RequireFeature(ctx context.Context, id features.ID) erif s.IsFeatureEnabled(ctx, id) {return nil}- return errors.WrapIff(common.ErrFeatureDisabled, "feature %s is disabled", id)+ return fmt.Errorf("feature %s is disabled: %w", id, common.ErrFeatureDisabled)}diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.goindex 8c870122c..c91e9baa1 100644--- a/backend/internal/settings/handler.go+++ b/backend/internal/settings/handler.go@@ -2,13 +2,13 @@ package settingsimport ("context"+ "errors""fmt""net/http""os""strconv""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"diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.goindex 0f01433b4..d711d0503 100644--- a/backend/internal/settings/model.go+++ b/backend/internal/settings/model.go@@ -1,6 +1,8 @@package settingsimport (+ "errors"+ "fmt""reflect""slices""strconv"@@ -8,7 +10,6 @@ import ("sync""time"- "emperror.dev/errors"kit "go.getarcane.app/kit/pkg")@@ -328,7 +329,7 @@ func (s *Settings) UpdateField(key, value string, noSensitive bool) error {valueField := rv.Field(field.index).FieldByName("Value")if !valueField.CanSet() {- return errors.Errorf("field Value in SettingVariable is not settable for config key '%s'", key)+ return fmt.Errorf("field Value in SettingVariable is not settable for config key '%s'", key)}valueField.SetString(value)diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex df5c6b50d..d082aa26a 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -6,6 +6,7 @@ import ("crypto/rand""crypto/sha256""encoding/base64"+ "errors""fmt""log/slog""maps"@@ -20,7 +21,6 @@ import ("time""uuid"- "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"@@ -30,6 +30,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/concurrency""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/features"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings""github.com/samber/mo"@@ -94,12 +95,12 @@ func NewSettingsService(ctx context.Context, db *database.DB) (*SettingsService,err := svc.LoadDatabaseSettings(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to load settings")+ return nil, fmt.Errorf("failed to load settings: %w", err)}err = svc.setupInstanceID(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to setup instance ID")+ return nil, fmt.Errorf("failed to setup instance ID: %w", err)}go svc.runEffectsInternal()@@ -145,7 +146,7 @@ func (s *SettingsService) NotifySettingsChanges(ctx context.Context, keys ...strfor _, key := range keys {value, _, _, err := cfg.FieldByKey(key)if err != nil {- return errors.WrapIff(err, "load changed setting '%s'", key)+ return fmt.Errorf("load changed setting '%s': %w", key, err)}updates = append(updates, libarcane.SettingUpdate{Key: key, Value: value})}@@ -179,7 +180,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 errors.WrapIf(err, "failed to refresh settings cache")+ return fmt.Errorf("failed to refresh settings cache: %w", err)}return nil@@ -322,18 +323,17 @@ func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *var loaded []SettingVariablequeryCtx, queryCancel := context.WithTimeout(ctx, 10*time.Second)defer queryCancel()- err := db.- WithContext(queryCtx).+ err := db.WithContext(queryCtx).Find(&loaded).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to load configuration from the database")+ return nil, fmt.Errorf("failed to load configuration from the database: %w", err)}for _, v := range loaded {err = dest.UpdateField(v.Key, v.Value, false)if err != nil && !errors.Is(err, SettingKeyNotFoundError{}) {- return nil, errors.WrapIff(err, "failed to process settings for key '%s'", v.Key)+ return nil, fmt.Errorf("failed to process settings for key '%s': %w", v.Key, err)}}@@ -349,7 +349,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat// Fetch all settings once to avoid N+1 queries for internal keysvar allSettings []SettingVariableif err := db.WithContext(ctx).Find(&allSettings).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load settings for env config")+ return nil, fmt.Errorf("failed to load settings for env config: %w", err)}settingsMap := make(map[string]string, len(allSettings))for _, s := range allSettings {@@ -502,7 +502,7 @@ func validateSettingValueInternal(key, value string) error {}for _, definition := range features.All() {if definition.SettingKey == key && value != "true" && value != "false" {- return common.Classify(common.ErrValidation, errors.Errorf("%s must be true or false", key))+ return common.Classify(common.ErrValidation, fmt.Errorf("%s must be true or false", key))}}return nil@@ -513,7 +513,7 @@ func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string)return err}if err := libarcane.ValidateCronSetting(key, value); err != nil {- return errors.WrapIff(err, "invalid cron expression for %s", key)+ return fmt.Errorf("invalid cron expression for %s: %w", key, err)}s.writes.Lock()defer s.writes.Unlock()@@ -640,7 +640,7 @@ func (s *SettingsService) updateSettingsInternal(ctx context.Context, updates se}for _, field := range required {if strings.TrimSpace(field.value) == "" {- return settingsUpdateResultInternal{}, common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Enabling OIDC requires %s", field.key), "field", field.key))+ return settingsUpdateResultInternal{}, common.Classify(common.ErrValidation, &base.FieldError{Field: field.key, Err: fmt.Errorf("Enabling OIDC requires %s", field.key)}) //nolint:staticcheck // Preserve the existing error message.}}}@@ -711,7 +711,7 @@ func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg,}if err := cfg.UpdateField(key, value, false); err != nil {- return nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)+ return nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)}valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: key, Value: value})@@ -720,7 +720,7 @@ func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg,}if err := libarcane.ValidateCronSetting(key, value); err != nil {- return nil, errors.WrapIff(err, "invalid cron expression for %s", key)+ return nil, fmt.Errorf("invalid cron expression for %s: %w", key, err)}var valueToSave string@@ -739,7 +739,7 @@ func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg,continue}if err != nil {- return nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)+ return nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)}valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: key, Value: valueToSave})@@ -773,7 +773,7 @@ func (s *SettingsService) persistSettings(ctx context.Context, values []SettingVsetting.Value = normalization.Text(setting.Value, true, true)}if err := tx.Save(&setting).Error; err != nil {- return errors.WrapIff(err, "failed to update setting %s", setting.Key)+ return fmt.Errorf("failed to update setting %s: %w", setting.Key, err)}}return nil@@ -805,13 +805,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 errors.WrapIff(err, "failed to create default setting %s", defaultSetting.Key)+ return fmt.Errorf("failed to create default setting %s: %w", defaultSetting.Key, err)}case err != nil:- return errors.WrapIff(err, "failed to check for existing setting %s", defaultSetting.Key)+ return fmt.Errorf("failed to check for existing setting %s: %w", defaultSetting.Key, err)case slices.Contains(retiredSettingValuesInternal[defaultSetting.Key], existing.Value):if err := tx.Model(&SettingVariable{}).Where("key = ?", defaultSetting.Key).Update("value", defaultSetting.Value).Error; err != nil {- return errors.WrapIff(err, "failed to replace retired default for setting %s", defaultSetting.Key)+ return fmt.Errorf("failed to replace retired default for setting %s: %w", defaultSetting.Key, err)}}}@@ -838,7 +838,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {result := s.db.WithContext(ctx).Where("key NOT IN ?", keys).Delete(&SettingVariable{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to prune unknown settings")+ return fmt.Errorf("failed to prune unknown settings: %w", result.Error)}if result.RowsAffected > 0 {slog.InfoContext(ctx, "Pruned unknown settings", "count", result.RowsAffected)@@ -922,15 +922,15 @@ func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, keycase errors.Is(err, gorm.ErrRecordNotFound):newVar := SettingVariable{Key: key, Value: envVal}if err := tx.Create(&newVar).Error; err != nil {- return errors.WrapIff(err, "persist env setting %s", key)+ return fmt.Errorf("persist env setting %s: %w", key, err)}slog.DebugContext(ctx, "Created setting from environment", "key", key)case err != nil:- return errors.WrapIff(err, "check setting %s", key)+ return fmt.Errorf("check setting %s: %w", key, err)default:if existing.Value != envVal {if err := tx.Model(&existing).Update("value", envVal).Error; err != nil {- return errors.WrapIff(err, "update env setting %s", key)+ return fmt.Errorf("update env setting %s: %w", key, err)}slog.DebugContext(ctx, "Updated setting from environment", "key", key)}@@ -971,7 +971,7 @@ func (s *SettingsService) setupInstanceID(ctx context.Context) error {err := s.UpdateSetting(ctx, "instanceId", uuid.New().String())if err != nil {- return errors.WrapIf(err, "failed to set instance ID in database")+ return fmt.Errorf("failed to set instance ID in database: %w", err)}return nil@@ -1060,7 +1060,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 errors.WrapIf(err, "failed to load encryption key")+ return fmt.Errorf("failed to load encryption key: %w", err)}if sv.Value != "" {@@ -1075,7 +1075,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erroif notFound {if createErr := tx.Create(&SettingVariable{Key: keyName, Value: generatedKey}).Error; createErr != nil {- return errors.WrapIf(createErr, "failed to persist encryption key")+ return fmt.Errorf("failed to persist encryption key: %w", createErr)}return nil}@@ -1083,7 +1083,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erroif updErr := tx.Model(&SettingVariable{}).Where("key = ?", keyName).Update("value", generatedKey).Error; updErr != nil {- return errors.WrapIf(updErr, "failed to update encryption key")+ return fmt.Errorf("failed to update encryption key: %w", updErr)}return nil})@@ -1100,7 +1100,10 @@ func (s *SettingsService) EnsureJwtSigningKey(ctx context.Context) (*mldsa.Privareturn nil, err}key, err := mldsa.NewPrivateKey(mldsa.MLDSA87(), seed)- return key, errors.WrapIf(err, "failed to load jwt signing key")+ if err != nil {+ return key, fmt.Errorf("failed to load jwt signing key: %w", err)+ }+ return key, nil}func (s *SettingsService) EnsureBrowserSessionSigningKey(ctx context.Context) ([]byte, error) {@@ -1120,39 +1123,45 @@ func (s *SettingsService) ensureEncryptedKeyInternal(ctx context.Context, keyNamvar sv SettingVariableerr := tx.Where("key = ?", keyName).First(&sv).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- return errors.WrapIf(err, "failed to load signing key")+ return fmt.Errorf("failed to load signing key: %w", err)}if sv.Value != "" {decoded, decErr := libcrypto.Decrypt(sv.Value)if decErr != nil {- return errors.WrapIf(decErr, "failed to decrypt signing key")+ return fmt.Errorf("failed to decrypt signing key: %w", decErr)}key, decErr = base64.StdEncoding.DecodeString(decoded)if decErr != nil {- return errors.WrapIf(decErr, "failed to decode signing key")+ return fmt.Errorf("failed to decode signing key: %w", decErr)}if len(key) != size {- return errors.Errorf("invalid signing key length: got %d, want %d", len(key), size)+ return fmt.Errorf("invalid signing key length: got %d, want %d", len(key), size)}return nil}key = make([]byte, size)if _, genErr := rand.Read(key); genErr != nil {- return errors.WrapIf(genErr, "failed to generate signing key")+ return fmt.Errorf("failed to generate signing key: %w", genErr)}encrypted, encErr := libcrypto.Encrypt(base64.StdEncoding.EncodeToString(key))if encErr != nil {- return errors.WrapIf(encErr, "failed to encrypt signing key")+ return fmt.Errorf("failed to encrypt signing key: %w", encErr)}if errors.Is(err, gorm.ErrRecordNotFound) {- return errors.WrapIf(tx.Create(&SettingVariable{Key: keyName, Value: encrypted}).Error, "failed to persist signing key")+ if err := tx.Create(&SettingVariable{Key: keyName, Value: encrypted}).Error; err != nil {+ return fmt.Errorf("failed to persist signing key: %w", err)+ }+ return nil}- return errors.WrapIf(tx.Model(&SettingVariable{}).+ if err := tx.Model(&SettingVariable{}).Where("key = ?", keyName).- Update("value", encrypted).Error, "failed to update signing key")+ Update("value", encrypted).Error; err != nil {+ return fmt.Errorf("failed to update signing key: %w", err)+ }+ return nil})if err != nil {return nil, err@@ -1180,7 +1189,7 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projecreturn nil}if err != nil {- return errors.WrapIf(err, "failed to load projectsDirectory setting")+ return fmt.Errorf("failed to load projectsDirectory setting: %w", err)}value := strings.TrimSpace(projectsDirSetting.Value)@@ -1193,11 +1202,11 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projeccwd, _ := os.Getwd()absPath, absErr := filepath.Abs(value)if absErr != nil {- return errors.WrapIf(absErr, "failed to resolve relative path to absolute")+ return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)}slog.InfoContext(ctx, "Normalizing projects directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)if err := s.updateSettingValueNoRefreshInternal(ctx, "projectsDirectory", absPath); err != nil {- return errors.WrapIf(err, "failed to update projectsDirectory")+ return fmt.Errorf("failed to update projectsDirectory: %w", err)}if err := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); err != nil {return err@@ -1228,7 +1237,7 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {return nil}if err != nil {- return errors.WrapIf(err, "failed to load buildsDirectory setting")+ return fmt.Errorf("failed to load buildsDirectory setting: %w", err)}value := strings.TrimSpace(buildsDirSetting.Value)@@ -1240,11 +1249,11 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {cwd, _ := os.Getwd()absPath, absErr := filepath.Abs(value)if absErr != nil {- return errors.WrapIf(absErr, "failed to resolve relative path to absolute")+ return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)}slog.InfoContext(ctx, "Normalizing builds directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)if err := s.updateSettingValueNoRefreshInternal(ctx, buildsKey, absPath); err != nil {- return errors.WrapIf(err, "failed to update buildsDirectory")+ return fmt.Errorf("failed to update buildsDirectory: %w", err)}if err := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); err != nil {return errdiff --git a/backend/internal/swarm/easy_join.go b/backend/internal/swarm/easy_join.godeleted file mode 100644index 5009fdb64..000000000--- a/backend/internal/swarm/easy_join.go+++ /dev/null@@ -1,64 +0,0 @@-package swarm--import (- "context"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"- "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"- kit "go.getarcane.app/kit/pkg"-)--// GetJoinCandidates lists environments available to join the selected manager.-func (s *SwarmService) GetJoinCandidates(ctx context.Context, environmentID string) ([]swarmtypes.SwarmJoinCandidate, error) {- var identity *SwarmNodeIdentity- var err error- if environmentID == environment.LocalEnvironmentID {- identity, err = s.GetLocalNodeIdentity(ctx)- } else {- identity, err = s.fetchSwarmNodeIdentityViaEdgeInternal(ctx, environmentID)- }- if err != nil {- return nil, errors.WrapIf(err, "failed to inspect Easy Join manager")- }- if !identity.SwarmActive || identity.Role == "worker" {- return []swarmtypes.SwarmJoinCandidate{}, nil- }- if identity.Role != "manager" {- return nil, errors.New("unexpected swarm node role")- }-- nodes, _, err := s.ListNodesPaginated(ctx, environmentID, pagination.QueryParams{Limit: -1})- if err != nil {- return nil, err- }- boundEnvironmentIDs := make(map[string]struct{}, len(nodes))- for _, node := range nodes {- if node.Agent.EnvironmentID != nil {- boundEnvironmentIDs[*node.Agent.EnvironmentID] = struct{}{}- }- }-- environments, err := s.environmentService.ListSwarmNodeCandidateEnvironments(ctx)- if err != nil {- return nil, err- }- candidates := make([]swarmtypes.SwarmJoinCandidate, 0, len(environments))- for _, candidate := range environments {- if candidate.ID == environmentID {- continue- }- if _, bound := boundEnvironmentIDs[candidate.ID]; bound {- continue- }- environmentType := kit.Ternary(candidate.IsEdge, "edge", "direct")- candidates = append(candidates, swarmtypes.SwarmJoinCandidate{- EnvironmentID: candidate.ID,- EnvironmentName: candidate.Name,- EnvironmentType: environmentType,- Status: candidate.Status,- })- }- return candidates, nil-}diff --git a/backend/internal/swarm/handler.go b/backend/internal/swarm/handler.goindex 695f378b7..09a5798eb 100644--- a/backend/internal/swarm/handler.go+++ b/backend/internal/swarm/handler.go@@ -3,13 +3,13 @@ package swarmimport ("cmp""context"+ "errors""log/slog""maps""net/http""slices""strings"- "emperror.dev/errors""github.com/containerd/errdefs""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -424,7 +424,7 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServiceparams := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListServicesPaginated(ctx, params)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm services").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm services: "+err.Error())}if items == nil {items = []swarmtypes.ServiceSummary{}@@ -448,9 +448,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(errors.WithMessage(err, "Swarm service not found").Error())+ return nil, huma.Error404NotFound("Swarm service not found: " + err.Error())}- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm service not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm service not found: "+err.Error())}return &handlerutil.Out[swarmtypes.ServiceInspect]{Body: base.ApiResponse[swarmtypes.ServiceInspect]{Success: true, Data: *service}}, nil@@ -470,7 +470,7 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInpfunc (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceCreateResponse], error) {resp, err := h.swarmService.CreateService(ctx, input.Body)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to create swarm service").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to create swarm service: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.create", "swarm_service", resp.ID, "", map[string]any{"serviceId": resp.ID})@@ -492,7 +492,7 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServfunc (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to update swarm service").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to update swarm service: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.update", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -515,9 +515,9 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServfunc (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {if errdefs.IsNotFound(err) {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm service not found").Error())+ return nil, huma.Error404NotFound("Swarm service not found: " + err.Error())}- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to remove swarm service").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to remove swarm service: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.delete", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -539,7 +539,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSerparams := handlerutil.PaginationParams(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, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm tasks: "+err.Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -562,7 +562,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSerfunc (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to update swarm service").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to update swarm service: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.rollback", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})@@ -584,7 +584,7 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmfunc (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to update swarm service").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to update swarm service: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "service.scale", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID, "replicas": input.Body.Replicas})@@ -606,7 +606,7 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInputparams := handlerutil.PaginationParams(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, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm nodes").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm nodes: "+err.Error())}if items == nil {items = []swarmtypes.NodeSummary{}@@ -630,9 +630,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(errors.WithMessage(err, "Swarm node not found").Error())+ return nil, huma.Error404NotFound("Swarm node not found: " + err.Error())}- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}return &handlerutil.Out[swarmtypes.NodeSummary]{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil@@ -658,9 +658,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(errors.WithMessage(err, "Swarm node not found").Error())+ return nil, huma.Error404NotFound("Swarm node not found: " + err.Error())}- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}user, err := handlerutil.RequireUser(ctx)@@ -805,7 +805,7 @@ func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdent// when the node update fails.func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.update", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -826,7 +826,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) (*handlerutil.Out[base.MessageResponse], error) {if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.delete", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID, "force": input.Force})@@ -847,7 +847,7 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp// when the promotion fails.func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.promote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -868,7 +868,7 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI// when the demotion fails.func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Swarm node not found").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Swarm node not found: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "node.demote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})@@ -890,7 +890,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTaparams := handlerutil.PaginationParams(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, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm tasks: "+err.Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -913,7 +913,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInputparams := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)items, paginationResp, err := h.swarmService.ListTasksPaginated(ctx, params)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm tasks").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm tasks: "+err.Error())}if items == nil {items = []swarmtypes.TaskSummary{}@@ -936,7 +936,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInpparams := handlerutil.PaginationParams(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, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to list swarm stacks").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to list swarm stacks: "+err.Error())}if items == nil {items = []swarmtypes.StackSummary{}@@ -960,7 +960,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInpfunc (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*handlerutil.Out[swarmtypes.StackDeployResponse], error) {resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to deploy swarm stack").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to deploy swarm stack: "+err.Error())}h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.deploy", "swarm_stack", input.Body.Name, input.Body.Name, map[string]any{"stack": input.Body.Name})@@ -1166,7 +1166,7 @@ func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatusfunc (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*handlerutil.Out[swarmtypes.SwarmInfo], error) {info, err := h.swarmService.GetSwarmInfo(ctx)if err != nil {- return nil, mapSwarmServiceErrorInternal(err, errors.WithMessage(err, "Failed to inspect swarm").Error())+ return nil, mapSwarmServiceErrorInternal(err, "Failed to inspect swarm: "+err.Error())}return &handlerutil.Out[swarmtypes.SwarmInfo]{Body: base.ApiResponse[swarmtypes.SwarmInfo]{Success: true, Data: *info}}, nil@@ -1210,8 +1210,7 @@ func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*hdetail := redactSwarmJoinTokenInternal(err.Error(), input.Body.JoinToken)slog.WarnContext(ctx, "swarm join failed", "environmentId", input.EnvironmentID, "operation", "join-swarm", "error", detail)httpErr := mapSwarmServiceErrorInternal(err, detail)- var model *huma.ErrorModel- if errors.As(httpErr, &model) {+ if model, ok := errors.AsType[*huma.ErrorModel](httpErr); ok {model.Detail = redactSwarmJoinTokenInternal(model.Detail, input.Body.JoinToken)}return nil, httpErr@@ -1671,8 +1670,7 @@ func mapSwarmServiceErrorInternal(err error, fallback string) error {if errdefs.IsConflict(err) {return huma.Error409Conflict(err.Error())}- var remoteStatus *remenv.StatusError- if errors.As(err, &remoteStatus) && remoteStatus.StatusCode >= 400 && remoteStatus.StatusCode <= 599 {+ if remoteStatus, ok := errors.AsType[*remenv.StatusError](err); ok && remoteStatus.StatusCode >= 400 && remoteStatus.StatusCode <= 599 {return huma.NewError(remoteStatus.StatusCode, fallback)}errText := strings.ToLower(err.Error())diff --git a/backend/internal/swarm/swarm.go b/backend/internal/swarm/swarm.goindex 56a832f54..50760ca0c 100644--- a/backend/internal/swarm/swarm.go+++ b/backend/internal/swarm/swarm.go@@ -6,6 +6,7 @@ import ("context"stdjson "encoding/json""encoding/json/v2"+ "errors""fmt""io/fs""log/slog"@@ -20,7 +21,6 @@ import ("sync""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/docker"@@ -121,7 +121,7 @@ func (s *SwarmService) IsEnabled(ctx context.Context) (bool, error) {enabled, err := s.kvService.GetBool(ctx, KVKeySwarmEnabled, false)if err != nil {- return false, errors.WrapIf(err, "failed to read swarm enabled state")+ return false, fmt.Errorf("failed to read swarm enabled state: %w", err)}return enabled, nil@@ -134,19 +134,19 @@ func (s *SwarmService) ListServicesPaginated(ctx context.Context, params paginatdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{Status: true})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)}services := servicesResult.Items// Fetch nodes to resolve node IDs to hostnamesnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)}nodes := nodesResult.ItemsnodeNameByID := make(map[string]string, len(nodes))@@ -157,7 +157,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{}, errors.WrapIf(err, "failed to list networks")+ return nil, pagination.Response{}, fmt.Errorf("failed to list networks: %w", err)}networks := networksResult.ItemsnetworkNameByID := make(map[string]string, len(networks))@@ -168,7 +168,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{}, errors.WrapIf(err, "failed to list swarm tasks")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)}tasks := tasksResult.ItemsserviceNodes := make(map[string]map[string]struct{})@@ -211,12 +211,12 @@ func (s *SwarmService) GetService(ctx context.Context, serviceID string) (*swarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm service")+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)}service := serviceResult.Service@@ -364,13 +364,13 @@ func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.ServicedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}// Unmarshal spec from JSONvar spec swarm.ServiceSpecif err := json.Unmarshal(req.Spec, &spec); err != nil {- return nil, errors.WrapIf(err, "failed to parse service spec")+ return nil, fmt.Errorf("failed to parse service spec: %w", err)}optionsPayload := swarmtypes.ServiceCreateOptions{}@@ -387,7 +387,7 @@ func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.ServiceQueryRegistry: optionsPayload.QueryRegistry,})if err != nil {- return nil, errors.WrapIf(err, "failed to create swarm service")+ return nil, fmt.Errorf("failed to create swarm service: %w", err)}return &swarmtypes.ServiceCreateResponse{@@ -403,14 +403,14 @@ func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, reqdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}versionIndex := req.Versionif versionIndex == 0 {serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm service")+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)}versionIndex = serviceResult.Service.Version.Index}@@ -432,7 +432,7 @@ func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, reqQueryRegistry: optionsPayload.QueryRegistry,})if err != nil {- return nil, errors.WrapIf(err, "failed to update swarm service")+ return nil, fmt.Errorf("failed to update swarm service: %w", err)}return &swarmtypes.ServiceUpdateResponse{@@ -447,11 +447,11 @@ func (s *SwarmService) RemoveService(ctx context.Context, serviceID string) errodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.ServiceRemove(ctx, serviceID, dockerclient.ServiceRemoveOptions{}); err != nil {- return errors.WrapIf(err, "failed to remove swarm service")+ return fmt.Errorf("failed to remove swarm service: %w", err)}return nil@@ -464,7 +464,7 @@ func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}options := dockerclient.ServiceLogsOptions{@@ -479,7 +479,7 @@ func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string,logs, err := dockerClient.ServiceLogs(ctx, serviceID, options)if err != nil {- return errors.WrapIf(err, "failed to get service logs")+ return fmt.Errorf("failed to get service logs: %w", err)}defer func() { _ = logs.Close() }()@@ -497,7 +497,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{}, errors.WrapIf(err, "failed to list remote swarm nodes")+ return nil, pagination.Response{}, fmt.Errorf("failed to list remote swarm nodes: %w", err)}if !remote.Success {return nil, pagination.Response{}, errors.New("remote swarm node listing failed")@@ -514,12 +514,12 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID strdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)}nodes := nodesResult.Items@@ -545,7 +545,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, errors.WrapIf(err, "failed to inspect remote swarm node")+ return nil, fmt.Errorf("failed to inspect remote swarm node: %w", err)}if !remote.Success {return nil, errors.New("remote swarm node inspection failed")@@ -561,12 +561,12 @@ func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID stringdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm node")+ return nil, fmt.Errorf("failed to inspect swarm node: %w", err)}items := []swarmtypes.NodeSummary{swarmtypes.NewNodeSummary(nodeResult.Node)}@@ -628,7 +628,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, errors.Errorf("environment reports swarm node %s instead of %s", runtime.identity.SwarmNodeID, nodeID)+ return nil, fmt.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)@@ -641,12 +641,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect local Docker engine")+ return nil, fmt.Errorf("failed to inspect local Docker engine: %w", err)}swarmInfo := infoResult.Info@@ -993,7 +993,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, errors.WrapIf(err, "failed to get remote swarm join tokens")+ return nil, fmt.Errorf("failed to get remote swarm join tokens: %w", err)}if !response.Success {return nil, errors.New("remote swarm join-token request failed")@@ -1189,12 +1189,12 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)}services := servicesResult.Items@@ -1205,7 +1205,7 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)}nodes := nodesResult.Items@@ -1216,7 +1216,7 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params paginationtasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm tasks")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)}tasks := tasksResult.Items@@ -1239,12 +1239,12 @@ func (s *SwarmService) ListStacksPaginated(ctx context.Context, environmentID stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)}services := servicesResult.Items@@ -1312,7 +1312,7 @@ func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, redockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}_, stackSourceDir, err := s.resolveSwarmStackSourceDirInternal(ctx, environmentID, stackName)@@ -1366,12 +1366,12 @@ func (s *SwarmService) GetSwarmInfo(ctx context.Context) (*swarmtypes.SwarmInfo,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm")+ return nil, fmt.Errorf("failed to inspect swarm: %w", err)}return new(swarmtypes.NewSwarmInfo(infoResult.Swarm)), nil@@ -1380,7 +1380,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}spec, err := decodeSwarmSpecInternal(req.Spec)@@ -1392,7 +1392,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, errors.WrapIff(err, "failed to parse default address pool %q", raw)+ return nil, fmt.Errorf("failed to parse default address pool %q: %w", raw, err)}defaultAddrPool = append(defaultAddrPool, prefix.Masked())}@@ -1410,7 +1410,7 @@ func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitReSubnetSize: req.SubnetSize,})if err != nil {- return nil, errors.WrapIf(err, "failed to initialize swarm")+ return nil, fmt.Errorf("failed to initialize swarm: %w", err)}s.persistSwarmEnabledStateInternal(ctx, true)@@ -1421,7 +1421,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 errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.SwarmJoin(ctx, dockerclient.SwarmJoinOptions{@@ -1432,7 +1432,7 @@ func (s *SwarmService) JoinSwarm(ctx context.Context, req swarmtypes.SwarmJoinReJoinToken: req.JoinToken,Availability: req.Availability,}); err != nil {- return errors.WrapIf(err, "failed to join swarm")+ return fmt.Errorf("failed to join swarm: %w", err)}s.persistSwarmEnabledStateInternal(ctx, true)@@ -1447,11 +1447,11 @@ func (s *SwarmService) LeaveSwarm(ctx context.Context, req swarmtypes.SwarmLeavedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.SwarmLeave(ctx, dockerclient.SwarmLeaveOptions{Force: req.Force}); err != nil {- return errors.WrapIf(err, "failed to leave swarm")+ return fmt.Errorf("failed to leave swarm: %w", err)}s.persistSwarmEnabledStateInternal(ctx, false)@@ -1466,11 +1466,11 @@ func (s *SwarmService) UnlockSwarm(ctx context.Context, req swarmtypes.SwarmUnlodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.SwarmUnlock(ctx, dockerclient.SwarmUnlockOptions{Key: req.Key}); err != nil {- return errors.WrapIf(err, "failed to unlock swarm")+ return fmt.Errorf("failed to unlock swarm: %w", err)}return nil@@ -1483,12 +1483,12 @@ func (s *SwarmService) GetSwarmUnlockKey(ctx context.Context) (*swarmtypes.SwarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}unlockResult, err := dockerClient.SwarmGetUnlockKey(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to get swarm unlock key")+ return nil, fmt.Errorf("failed to get swarm unlock key: %w", err)}return &swarmtypes.SwarmUnlockKeyResponse{UnlockKey: unlockResult.Key}, nil@@ -1501,12 +1501,12 @@ func (s *SwarmService) GetSwarmJoinTokens(ctx context.Context) (*swarmtypes.SwardockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm")+ return nil, fmt.Errorf("failed to inspect swarm: %w", err)}return &swarmtypes.SwarmJoinTokensResponse{@@ -1522,12 +1522,12 @@ func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypesdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return errors.WrapIf(err, "failed to inspect swarm")+ return fmt.Errorf("failed to inspect swarm: %w", err)}rotateWorker := req.RotateWorkerToken@@ -1543,7 +1543,7 @@ func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypesRotateWorkerToken: rotateWorker,RotateManagerToken: rotateManager,}); err != nil {- return errors.WrapIf(err, "failed to rotate swarm join tokens")+ return fmt.Errorf("failed to rotate swarm join tokens: %w", err)}return nil@@ -1556,14 +1556,14 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}version := req.Versionif version == 0 {infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})if err != nil {- return errors.WrapIf(err, "failed to inspect swarm")+ return fmt.Errorf("failed to inspect swarm: %w", err)}version = infoResult.Swarm.Version.Index}@@ -1580,7 +1580,7 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmRotateManagerToken: req.RotateManagerToken,RotateManagerUnlockKey: req.RotateManagerUnlockKey,}); err != nil {- return errors.WrapIf(err, "failed to update swarm spec")+ return fmt.Errorf("failed to update swarm spec: %w", err)}return nil@@ -1603,12 +1603,12 @@ func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm service")+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)}updateResult, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{@@ -1617,7 +1617,7 @@ func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*Rollback: "previous",})if err != nil {- return nil, errors.WrapIf(err, "failed to rollback swarm service")+ return nil, fmt.Errorf("failed to rollback swarm service: %w", err)}return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil@@ -1630,12 +1630,12 @@ func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, replidockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm service")+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)}service := serviceResult.Service@@ -1648,7 +1648,7 @@ func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, repliSpec: service.Spec,})if err != nil {- return nil, errors.WrapIf(err, "failed to scale swarm service")+ return nil, fmt.Errorf("failed to scale swarm service: %w", err)}return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil@@ -1661,7 +1661,7 @@ func applySwarmServiceScaleInternal(mode *swarm.ServiceMode, replicas uint64) ercase mode.ReplicatedJob != nil:mode.ReplicatedJob.TotalCompletions = &replicasdefault:- return errors.WrapIf(cerrdefs.ErrInvalidArgument, "scale can only be used with replicated or replicated-job mode")+ return fmt.Errorf("scale can only be used with replicated or replicated-job mode: %w", cerrdefs.ErrInvalidArgument)}return nil@@ -1674,12 +1674,12 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})if err != nil {- return errors.WrapIf(err, "failed to inspect swarm node")+ return fmt.Errorf("failed to inspect swarm node: %w", err)}version := cmp.Or(req.Version, nodeResult.Node.Version.Index)@@ -1702,7 +1702,7 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtVersion: swarm.Version{Index: version},Spec: spec,}); err != nil {- return errors.WrapIf(err, "failed to update swarm node")+ return fmt.Errorf("failed to update swarm node: %w", err)}return nil@@ -1715,11 +1715,11 @@ func (s *SwarmService) RemoveNode(ctx context.Context, nodeID string, force booldockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.NodeRemove(ctx, nodeID, dockerclient.NodeRemoveOptions{Force: force}); err != nil {- return errors.WrapIf(err, "failed to remove swarm node")+ return fmt.Errorf("failed to remove swarm node: %w", err)}return nil@@ -1750,7 +1750,7 @@ func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -1808,7 +1808,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif errors.Is(err, fs.ErrNotExist) {return nil, cerrdefs.ErrNotFound}- return nil, errors.WrapIf(err, "failed to read swarm stack compose source")+ return nil, fmt.Errorf("failed to read swarm stack compose source: %w", err)}overrideContent := ""@@ -1816,7 +1816,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif err == nil {overrideContent = string(overrideBytes)} else if !errors.Is(err, fs.ErrNotExist) {- return nil, errors.WrapIf(err, "failed to read swarm stack override source")+ return nil, fmt.Errorf("failed to read swarm stack override source: %w", err)}envContent := ""@@ -1824,7 +1824,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNif err == nil {envContent = string(envBytes)} else if !errors.Is(err, fs.ErrNotExist) {- return nil, errors.WrapIf(err, "failed to read swarm stack env source")+ return nil, fmt.Errorf("failed to read swarm stack env source: %w", err)}var files []swarmtypes.SyncFile@@ -1847,7 +1847,7 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackNreturn nil})if err != nil && !errors.Is(err, fs.ErrNotExist) {- return nil, errors.WrapIf(err, "failed to read additional swarm stack source files")+ return nil, fmt.Errorf("failed to read additional swarm stack source files: %w", err)}return &swarmtypes.StackSource{@@ -1907,7 +1907,7 @@ func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, staif restoreErr != nil {slog.WarnContext(ctx, "failed to restore swarm stack source after deploy failure", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", restoreErr)}- return nil, errors.WrapIf(err, "failed to redeploy swarm stack from updated source")+ return nil, fmt.Errorf("failed to redeploy swarm stack from updated source: %w", err)}return &swarmtypes.StackSource{@@ -1930,7 +1930,7 @@ func (s *SwarmService) listPersistedStackSourcesInternal(ctx context.Context, enif errors.Is(err, fs.ErrNotExist) {return map[string]swarmtypes.StackSummary{}, nil}- return nil, errors.WrapIf(err, "failed to list swarm stack source directories")+ return nil, fmt.Errorf("failed to list swarm stack source directories: %w", err)}stacks := make(map[string]swarmtypes.StackSummary, len(entries))@@ -1968,7 +1968,7 @@ func (s *SwarmService) buildPersistedStackSourceSummaryInternal(ctx context.Contif errors.Is(err, fs.ErrNotExist) {return nil, cerrdefs.ErrNotFound}- return nil, errors.WrapIf(err, "failed to stat swarm stack compose source")+ return nil, fmt.Errorf("failed to stat swarm stack compose source: %w", err)}createdAt := composeEntry.ModTime@@ -1983,7 +1983,7 @@ func (s *SwarmService) buildPersistedStackSourceSummaryInternal(ctx context.ContupdatedAt = envEntry.ModTime}} else if !errors.Is(err, fs.ErrNotExist) {- return nil, errors.WrapIf(err, "failed to stat swarm stack env source")+ return nil, fmt.Errorf("failed to stat swarm stack env source: %w", err)}return &swarmtypes.StackSummary{@@ -2008,7 +2008,7 @@ func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackNamedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -2041,7 +2041,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 errors.WrapIff(err, "failed to remove swarm service %s", service.Spec.Name)+ return fmt.Errorf("failed to remove swarm service %s: %w", service.Spec.Name, err)}}@@ -2059,7 +2059,7 @@ func (s *SwarmService) ListStackServicesPaginated(ctx context.Context, stackNamedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -2088,7 +2088,7 @@ func (s *SwarmService) ListStackTasksPaginated(ctx context.Context, stackName stdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)@@ -2118,7 +2118,7 @@ func (s *SwarmService) RenderStackConfig(ctx context.Context, environmentID stri}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}pm := appfs.NewPathMapperForConfiguredDirectory(ctx,@@ -2164,12 +2164,12 @@ func (s *SwarmService) ListConfigs(ctx context.Context) ([]swarmtypes.ConfigSummdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list swarm configs")+ return nil, fmt.Errorf("failed to list swarm configs: %w", err)}items := make([]swarmtypes.ConfigSummary, 0, len(configsResult.Items))@@ -2186,12 +2186,12 @@ func (s *SwarmService) GetConfig(ctx context.Context, configID string) (*swarmtydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}cfgResult, err := dockerClient.ConfigInspect(ctx, configID, dockerclient.ConfigInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm config")+ return nil, fmt.Errorf("failed to inspect swarm config: %w", err)}return new(swarmtypes.NewConfigSummary(cfgResult.Config)), nil@@ -2209,12 +2209,12 @@ func (s *SwarmService) CreateConfig(ctx context.Context, req swarmtypes.ConfigCrdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}createResult, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})if err != nil {- return nil, errors.WrapIf(err, "failed to create swarm config")+ return nil, fmt.Errorf("failed to create swarm config: %w", err)}return s.GetConfig(ctx, createResult.ID)@@ -2227,11 +2227,11 @@ func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.ConfigRemove(ctx, configID, dockerclient.ConfigRemoveOptions{}); err != nil {- return errors.WrapIf(err, "failed to remove swarm config")+ return fmt.Errorf("failed to remove swarm config: %w", err)}return nil@@ -2244,12 +2244,12 @@ func (s *SwarmService) ListSecrets(ctx context.Context) ([]swarmtypes.SecretSummdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list swarm secrets")+ return nil, fmt.Errorf("failed to list swarm secrets: %w", err)}items := make([]swarmtypes.SecretSummary, 0, len(secretsResult.Items))@@ -2266,12 +2266,12 @@ func (s *SwarmService) GetSecret(ctx context.Context, secretID string) (*swarmtydockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}secretResult, err := dockerClient.SecretInspect(ctx, secretID, dockerclient.SecretInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to inspect swarm secret")+ return nil, fmt.Errorf("failed to inspect swarm secret: %w", err)}return new(swarmtypes.NewSecretSummary(secretResult.Secret)), nil@@ -2289,12 +2289,12 @@ func (s *SwarmService) CreateSecret(ctx context.Context, req swarmtypes.SecretCrdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}createResult, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})if err != nil {- return nil, errors.WrapIf(err, "failed to create swarm secret")+ return nil, fmt.Errorf("failed to create swarm secret: %w", err)}return s.GetSecret(ctx, createResult.ID)@@ -2307,11 +2307,11 @@ func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}if _, err := dockerClient.SecretRemove(ctx, secretID, dockerclient.SecretRemoveOptions{}); err != nil {- return errors.WrapIf(err, "failed to remove swarm secret")+ return fmt.Errorf("failed to remove swarm secret: %w", err)}return nil@@ -2320,12 +2320,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{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)}servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm services")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)}serviceNameByID := make(map[string]string, len(servicesResult.Items))@@ -2335,7 +2335,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.ContextnodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm nodes")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)}nodeNameByID := make(map[string]string, len(nodesResult.Items))@@ -2348,7 +2348,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Context}tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{Filters: filters})if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list swarm tasks")+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)}items := make([]swarmtypes.TaskSummary, 0, len(tasksResult.Items))@@ -2365,7 +2365,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, errors.WrapIf(err, "failed to list swarm nodes")+ return nil, fmt.Errorf("failed to list swarm nodes: %w", err)}nodeNameByID := make(map[string]string, len(nodesResult.Items))@@ -2375,7 +2375,7 @@ func (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClienetworksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list networks")+ return nil, fmt.Errorf("failed to list networks: %w", err)}networkNameByID := make(map[string]string, len(networksResult.Items))@@ -2390,7 +2390,7 @@ func (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClietasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list swarm tasks")+ return nil, fmt.Errorf("failed to list swarm tasks: %w", err)}serviceNodes := make(map[string]map[string]struct{})@@ -2437,7 +2437,7 @@ func (s *SwarmService) listStackServicesRawInternal(ctx context.Context, dockerCStatus: true,})if err != nil {- return nil, errors.WrapIf(err, "failed to list stack services")+ return nil, fmt.Errorf("failed to list stack services: %w", err)}return servicesResult.Items, nil@@ -2462,7 +2462,7 @@ func (s *SwarmService) waitForRemovedServiceTasksInternal(ctx context.Context, dfor {tasksResult, err := dockerClient.TaskList(waitCtx, dockerclient.TaskListOptions{Filters: taskFilters})if err != nil {- return errors.WrapIf(err, "failed to list tasks while waiting for stack removal")+ return fmt.Errorf("failed to list tasks while waiting for stack removal: %w", err)}hasActiveTasks := false@@ -2478,7 +2478,7 @@ func (s *SwarmService) waitForRemovedServiceTasksInternal(ctx context.Context, dselect {case <-waitCtx.Done():- return errors.WrapIf(waitCtx.Err(), "timed out waiting for stack task convergence")+ return fmt.Errorf("timed out waiting for stack task convergence: %w", waitCtx.Err())case <-ticker.C:}}@@ -2515,7 +2515,7 @@ func decodeConfigSpecInternal(raw stdjson.RawMessage) (swarm.ConfigSpec, error)var spec swarm.ConfigSpecif err := json.Unmarshal(raw, &spec); err != nil {- return swarm.ConfigSpec{}, errors.WrapIf(err, "failed to parse config spec")+ return swarm.ConfigSpec{}, fmt.Errorf("failed to parse config spec: %w", err)}if strings.TrimSpace(spec.Name) == "" {@@ -2533,7 +2533,7 @@ func decodeSwarmSpecInternal(raw stdjson.RawMessage) (swarm.Spec, error) {var spec swarm.Specif err := json.Unmarshal(trimmed, &spec); err != nil {- return swarm.Spec{}, errors.WrapIf(err, "failed to parse swarm spec")+ return swarm.Spec{}, fmt.Errorf("failed to parse swarm spec: %w", err)}if spec.Labels == nil {@@ -2555,7 +2555,7 @@ func decodeSecretSpecInternal(raw stdjson.RawMessage) (swarm.SecretSpec, error)var spec swarm.SecretSpecif err := json.Unmarshal(raw, &spec); err != nil {- return swarm.SecretSpec{}, errors.WrapIf(err, "failed to parse secret spec")+ return swarm.SecretSpec{}, fmt.Errorf("failed to parse secret spec: %w", err)}if strings.TrimSpace(spec.Name) == "" {@@ -2578,10 +2578,10 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmenstackLogical, err := acfs.LogicalPath(rootDir, stackSourceDir)if err != nil {- return errors.WrapIf(err, "swarm stack source directory is outside its root")+ return fmt.Errorf("swarm stack source directory is outside its root: %w", err)}if err := acfs.MkdirAll(ctx, rootDir, stackLogical, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create swarm stack source directory")+ return fmt.Errorf("failed to create swarm stack source directory: %w", err)}syncFiles := make([]appfs.SyncFile, 0, len(files)+3)@@ -2621,15 +2621,15 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmenexistingFiles = append(existingFiles, strings.TrimPrefix(entry.Path, "/"))return nil}); err != nil {- return errors.WrapIf(err, "failed to inspect existing swarm stack files")+ return fmt.Errorf("failed to inspect existing swarm stack files: %w", err)}writtenFiles, err := appfs.WriteSyncedDirectory(ctx, rootDir, stackSourceDir, syncFiles)if err != nil {- return errors.WrapIf(err, "failed to write swarm stack files")+ return fmt.Errorf("failed to write swarm stack files: %w", err)}if err := appfs.CleanupRemovedFiles(ctx, rootDir, stackSourceDir, existingFiles, writtenFiles); err != nil {- return errors.WrapIf(err, "failed to remove stale swarm stack files")+ return fmt.Errorf("failed to remove stale swarm stack files: %w", err)}return nil@@ -2647,10 +2647,10 @@ func (s *SwarmService) deleteStackSourceInternal(ctx context.Context, environmenstackLogical, err := acfs.LogicalPath(rootDir, stackSourceDir)if err != nil {- return errors.WrapIf(err, "swarm stack source directory is outside its root")+ return fmt.Errorf("swarm stack source directory is outside its root: %w", err)}if err := acfs.RemoveAll(ctx, rootDir, stackLogical); err != nil {- return errors.WrapIf(err, "failed to remove swarm stack source directory")+ return fmt.Errorf("failed to remove swarm stack source directory: %w", err)}// Best-effort cleanup of now-empty environment directory.@@ -2715,10 +2715,10 @@ func (s *SwarmService) ensureSwarmManagerInternal(ctx context.Context) error {}if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {- return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled"))+ return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled")) //nolint:staticcheck // Preserve the existing error message.}if !info.Swarm.ControlAvailable {- return common.Classify(common.ErrSwarmManagerRequired, errors.New("Swarm manager access required"))+ return common.Classify(common.ErrSwarmManagerRequired, errors.New("Swarm manager access required")) //nolint:staticcheck // Preserve the existing error message.}return nil@@ -2731,7 +2731,7 @@ func (s *SwarmService) ensureSwarmActiveInternal(ctx context.Context) error {}if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {- return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled"))+ return common.Classify(common.ErrSwarmNotEnabled, errors.New("Swarm mode is not enabled")) //nolint:staticcheck // Preserve the existing error message.}return nil@@ -2740,12 +2740,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{}, errors.WrapIf(err, "failed to connect to Docker")+ return system.Info{}, fmt.Errorf("failed to connect to Docker: %w", err)}infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})if err != nil {- return system.Info{}, errors.WrapIf(err, "failed to get Docker info")+ return system.Info{}, fmt.Errorf("failed to get Docker info: %w", err)}return infoResult.Info, nil@@ -2763,7 +2763,7 @@ func (s *SwarmService) SyncSwarmEnabledState(ctx context.Context) error {}if err := s.kvService.SetBool(ctx, KVKeySwarmEnabled, enabled); err != nil {- return errors.WrapIf(err, "persist swarm enabled state")+ return fmt.Errorf("persist swarm enabled state: %w", err)}return nil@@ -2926,3 +2926,56 @@ func sanitizeServiceSpecInternal(spec *swarm.ServiceSpec) {}}}++// GetJoinCandidates lists environments available to join the selected manager.+func (s *SwarmService) GetJoinCandidates(ctx context.Context, environmentID string) ([]swarmtypes.SwarmJoinCandidate, error) {+ var identity *SwarmNodeIdentity+ var err error+ if environmentID == environment.LocalEnvironmentID {+ identity, err = s.GetLocalNodeIdentity(ctx)+ } else {+ identity, err = s.fetchSwarmNodeIdentityViaEdgeInternal(ctx, environmentID)+ }+ if err != nil {+ return nil, fmt.Errorf("failed to inspect Easy Join manager: %w", err)+ }+ if !identity.SwarmActive || identity.Role == "worker" {+ return []swarmtypes.SwarmJoinCandidate{}, nil+ }+ if identity.Role != "manager" {+ return nil, errors.New("unexpected swarm node role")+ }++ nodes, _, err := s.ListNodesPaginated(ctx, environmentID, pagination.QueryParams{Limit: -1})+ if err != nil {+ return nil, err+ }+ boundEnvironmentIDs := make(map[string]struct{}, len(nodes))+ for _, node := range nodes {+ if node.Agent.EnvironmentID != nil {+ boundEnvironmentIDs[*node.Agent.EnvironmentID] = struct{}{}+ }+ }++ environments, err := s.environmentService.ListSwarmNodeCandidateEnvironments(ctx)+ if err != nil {+ return nil, err+ }+ candidates := make([]swarmtypes.SwarmJoinCandidate, 0, len(environments))+ for _, candidate := range environments {+ if candidate.ID == environmentID {+ continue+ }+ if _, bound := boundEnvironmentIDs[candidate.ID]; bound {+ continue+ }+ environmentType := kit.Ternary(candidate.IsEdge, "edge", "direct")+ candidates = append(candidates, swarmtypes.SwarmJoinCandidate{+ EnvironmentID: candidate.ID,+ EnvironmentName: candidate.Name,+ EnvironmentType: environmentType,+ Status: candidate.Status,+ })+ }+ return candidates, nil+}diff --git a/backend/internal/system/handler.go b/backend/internal/system/handler.goindex d8b9114b8..98f25e835 100644--- a/backend/internal/system/handler.go+++ b/backend/internal/system/handler.go@@ -3,11 +3,11 @@ package systemimport ("cmp""context"+ "errors""log/slog""net/http""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -260,12 +260,12 @@ func (h *SystemHandler) rejectIfAgentModeInternal() error {func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*struct{}, error) {dockerClient, err := h.dockerService.GetClient(ctx)if err != nil {- return nil, huma.Error503ServiceUnavailable(errors.WithMessage(err, "Failed to connect to Docker").Error())+ return nil, huma.Error503ServiceUnavailable("Failed to connect to Docker: " + err.Error())}_, err = dockerClient.Ping(ctx, client.PingOptions{})if err != nil {- return nil, huma.Error503ServiceUnavailable(errors.WithMessage(err, "Docker is not responsive").Error())+ return nil, huma.Error503ServiceUnavailable("Docker is not responsive: " + err.Error())}return nil, nil@@ -275,17 +275,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(errors.WithMessage(err, "Failed to connect to Docker").Error())+ return nil, huma.Error500InternalServerError("Failed to connect to Docker: " + err.Error())}version, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get Docker version").Error())+ return nil, huma.Error500InternalServerError("Failed to get Docker version: " + err.Error())}infoResult, err := dockerClient.Info(ctx, client.InfoOptions{})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get Docker info").Error())+ return nil, huma.Error500InternalServerError("Failed to get Docker info: " + err.Error())}info := infoResult.Info@@ -380,7 +380,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(errors.WithMessage(err, "Failed to start containers").Error())+ return nil, huma.Error500InternalServerError("Failed to start containers: " + err.Error())}return &handlerutil.Out[containertypes.ActionResult]{@@ -396,7 +396,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(errors.WithMessage(err, "Failed to start stopped containers").Error())+ return nil, huma.Error500InternalServerError("Failed to start stopped containers: " + err.Error())}return &handlerutil.Out[containertypes.ActionResult]{@@ -412,7 +412,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(errors.WithMessage(err, "Failed to stop containers").Error())+ return nil, huma.Error500InternalServerError("Failed to stop containers: " + err.Error())}return &handlerutil.Out[containertypes.ActionResult]{@@ -457,7 +457,7 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckUBody: UpgradeCheckResultData{CanUpgrade: false,Error: true,- Message: errors.WithMessage(err, "Failed to check for updates").Error(),+ Message: "Failed to check for updates: " + err.Error(),},}, nil}@@ -494,10 +494,10 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradslog.Error("System upgrade failed", "error", err, "user", user.Username)if errors.Is(err, common.ErrUpgradeInProgress) {- return nil, huma.Error409Conflict(errors.WithMessage(err, "Failed to initiate upgrade").Error())+ return nil, huma.Error409Conflict("Failed to initiate upgrade: " + err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())+ return nil, huma.Error500InternalServerError("Failed to initiate upgrade: " + err.Error())}message := kit.Ternary(@@ -540,7 +540,7 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdaif errors.Is(err, common.ErrUpdateAllInProgress) {return nil, huma.Error409Conflict(err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())+ return nil, huma.Error500InternalServerError("Failed to initiate upgrade: " + err.Error())}return &handlerutil.Out[EnvironmentUpdateJob]{diff --git a/backend/internal/system/memory.go b/backend/internal/system/memory.goindex 2e93d2635..788358d42 100644--- a/backend/internal/system/memory.go+++ b/backend/internal/system/memory.go@@ -2,12 +2,12 @@ package systemimport ("context"+ "errors""log/slog""runtime""strings""time"- "emperror.dev/errors""github.com/moby/moby/client""go.getarcane.app/docker/compat""go.getarcane.app/sys/cgroup"@@ -78,7 +78,7 @@ func (s *SystemService) loadDockerHostMemoryInternal(ctx context.Context) (dockereturn dockerHostMemoryInfo{}, err}if info.Info.MemTotal <= 0 {- return dockerHostMemoryInfo{}, errors.New("Docker host memory total is unavailable")+ return dockerHostMemoryInfo{}, errors.New("Docker host memory total is unavailable") //nolint:staticcheck // Preserve the existing error message.}return dockerHostMemoryInfo{root: root, total: uint64(info.Info.MemTotal)}, nil}diff --git a/backend/internal/system/prune_recovery.go b/backend/internal/system/prune_recovery.goindex 0095b3d45..5fe8990b7 100644--- a/backend/internal/system/prune_recovery.go+++ b/backend/internal/system/prune_recovery.go@@ -3,6 +3,7 @@ package systemimport ("context""encoding/json/v2"+ "errors""fmt""regexp""slices"@@ -10,7 +11,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"diff --git a/backend/internal/system/system.go b/backend/internal/system/system.goindex 38b787b4d..4088fd5aa 100644--- a/backend/internal/system/system.go+++ b/backend/internal/system/system.go@@ -3,13 +3,13 @@ package systemimport ("cmp""context"+ "errors""fmt""log/slog""strings""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -502,7 +502,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 errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}filterArgs := make(client.Filters)@@ -515,7 +515,7 @@ func (s *SystemService) pruneContainersInternal(ctx context.Context, options sysreport, err := dockerClient.ContainerPrune(ctx, client.ContainerPruneOptions{Filters: filterArgs})if err != nil {- return errors.WrapIf(err, "failed to prune containers")+ return fmt.Errorf("failed to prune containers: %w", err)}result.ContainersPruned = report.Report.ContainersDeleted@@ -527,7 +527,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 errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}filterArgs := make(client.Filters)@@ -545,12 +545,12 @@ func (s *SystemService) pruneImagesInternal(ctx context.Context, options system.filterArgs = filterArgs.Add("dangling", "false")filterArgs = filterArgs.Add("until", options.Until)default:- return errors.Errorf("unsupported image prune mode: %s", options.Mode)+ return fmt.Errorf("unsupported image prune mode: %s", options.Mode)}report, err := dockerClient.ImagePrune(ctx, client.ImagePruneOptions{Filters: filterArgs})if err != nil {- return errors.WrapIf(err, "failed to prune images")+ return fmt.Errorf("failed to prune images: %w", err)}slog.InfoContext(ctx, "Image pruning completed", "images_deleted", len(report.Report.ImagesDeleted), "bytes_reclaimed", report.Report.SpaceReclaimed)@@ -578,9 +578,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, errors.WrapIf(err, "build cache pruning failed (connection)").Error())+ result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed (connection): %w", err).Error())slog.ErrorContext(ctx, "Error connecting to Docker for build cache prune", "error", err.Error())- return errors.WrapIf(err, "failed to connect to Docker for build cache prune")+ return fmt.Errorf("failed to connect to Docker for build cache prune: %w", err)}pruneOptions := client.BuildCachePruneOptions{@@ -597,9 +597,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, errors.WrapIf(err, "build cache pruning failed").Error())+ result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed: %w", err).Error())slog.ErrorContext(ctx, "Error pruning build cache", "error", err.Error())- return errors.WrapIf(err, "failed to prune build cache")+ return fmt.Errorf("failed to prune build cache: %w", err)}slog.InfoContext(ctx, "build cache pruning completed", "cache_entries_deleted", len(report.Report.CachesDeleted), "bytes_reclaimed", report.Report.SpaceReclaimed)@@ -627,7 +627,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 errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}filterArgs := make(client.Filters)@@ -640,7 +640,7 @@ func (s *SystemService) pruneNetworksInternal(ctx context.Context, options systereport, err := dockerClient.NetworkPrune(ctx, client.NetworkPruneOptions{Filters: filterArgs})if err != nil {- return errors.WrapIf(err, "failed to prune networks")+ return fmt.Errorf("failed to prune networks: %w", err)}slog.InfoContext(ctx, "Network prune completed", "networks_deleted", len(report.Report.NetworksDeleted))diff --git a/backend/internal/system/upgrade_service.go b/backend/internal/system/upgrade_service.goindex 32fee61c3..37245809e 100644--- a/backend/internal/system/upgrade_service.go+++ b/backend/internal/system/upgrade_service.go@@ -3,7 +3,7 @@ package systemimport ("context""encoding/json/v2"- stderrors "errors"+ "errors""fmt""io""io/fs"@@ -16,7 +16,6 @@ import ("sync/atomic""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -162,13 +161,13 @@ func (s *SystemUpgradeService) prepareUpgradeInternal(ctx context.Context, user// Fall back to the container this process runs incontainerId, err = s.getCurrentContainerIDInternal(ctx)if err != nil {- return nil, errors.WrapIf(err, "get current container")+ return nil, fmt.Errorf("get current container: %w", err)}}currentContainer, err := s.findArcaneContainerInternal(ctx, containerId)if err != nil {- return nil, errors.WrapIf(err, "inspect container")+ return nil, fmt.Errorf("inspect container: %w", err)}containerName := strings.TrimPrefix(currentContainer.Name, "/")@@ -218,7 +217,7 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p// This will run independently of the current containerdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}// Pull the upgrader image first to ensure it exists@@ -231,14 +230,14 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, ppullReader, err := dockerClient.ImagePull(pullCtx, upgraderImage, client.ImagePullOptions{})if err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return "", errors.Errorf("upgrader image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", upgraderImage)+ return "", fmt.Errorf("upgrader image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", upgraderImage)}- return "", errors.WrapIf(err, "pull upgrader image")+ return "", fmt.Errorf("pull upgrader image: %w", err)}// Drain and validate the JSON stream to complete the pull.if err := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); err != nil {_ = pullReader.Close()- return "", errors.WrapIf(err, "failed to complete upgrader image pull")+ return "", fmt.Errorf("failed to complete upgrader image pull: %w", err)}if closeErr := pullReader.Close(); closeErr != nil {slog.Warn("Failed to close upgrader image pull reader", "error", closeErr)@@ -270,7 +269,7 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p},)if err != nil {- return "", errors.WrapIf(err, "resolve upgrader docker runtime")+ return "", fmt.Errorf("resolve upgrader docker runtime: %w", err)}upgradeCmd := []string{prepared.binaryPath, "upgrade", "--container", prepared.containerName}@@ -329,13 +328,13 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, pName: upgraderName,})if err != nil {- return "", errors.WrapIf(err, "create upgrader container")+ return "", fmt.Errorf("create upgrader container: %w", err)}// 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 "", errors.WrapIf(err, "start upgrader container")+ return "", fmt.Errorf("start upgrader container: %w", err)}slog.Info("Upgrade container started", "upgraderId", resp.ID[:12], "upgraderName", upgraderName)@@ -388,7 +387,7 @@ func (s *SystemUpgradeService) resolveUpgradeTargetImageInternal(ctx context.Con}resolved, err := resolveSelfUpgradeTargetImageInternal(currentImageRef, info)if err != nil {- return "", errors.WrapIf(err, "resolve upgrade target image")+ return "", fmt.Errorf("resolve upgrade target image: %w", err)}return resolved, nil}@@ -407,11 +406,11 @@ func resolveSelfUpgradeTargetImageInternal(currentImageRef string, info *versionparsed, err := ref.Parse(currentImageRef)if err != nil {- return "", errors.WrapIff(err, "parse current image reference %q", currentImageRef)+ return "", fmt.Errorf("parse current image reference %q: %w", currentImageRef, err)}named, ok := parsed.(ref.Named)if !ok {- return "", errors.Errorf("current image reference %q is not a named image", currentImageRef)+ return "", fmt.Errorf("current image reference %q is not a named image", currentImageRef)}newestDigest, newestVersion := newestTargetIdentifiersInternal(info)@@ -424,11 +423,11 @@ func resolveSelfUpgradeTargetImageInternal(currentImageRef string, info *version}targetDigest := digest.Digest(newestDigest)if err := targetDigest.Validate(); err != nil {- return "", errors.WrapIff(err, "resolved newest digest %q is not a valid digest", newestDigest)+ return "", fmt.Errorf("resolved newest digest %q is not a valid digest: %w", newestDigest, err)}withDigest, err := ref.WithDigest(named, targetDigest)if err != nil {- return "", errors.WrapIff(err, "build target reference for %q", named.Name())+ return "", fmt.Errorf("build target reference for %q: %w", named.Name(), err)}return withDigest.String(), nil}@@ -441,19 +440,19 @@ func resolveSelfUpgradeTargetImageInternal(currentImageRef string, info *version}if newestVersion == "" {- return "", errors.Errorf("running exact release %q but the newest release could not be resolved", tagged.Tag())+ return "", fmt.Errorf("running exact release %q but the newest release could not be resolved", tagged.Tag())}newest := kit.EnsurePrefix(newestVersion, "v")if !semver.IsValid(newest) {- return "", errors.Errorf("resolved newest version %q is not a valid semver release", newestVersion)+ return "", fmt.Errorf("resolved newest version %q is not a valid semver release", newestVersion)}if semver.Compare(newest, kit.EnsurePrefix(tagged.Tag(), "v")) < 0 {- return "", errors.Errorf("newest release %q is older than the running %q; refusing to downgrade", newestVersion, tagged.Tag())+ return "", fmt.Errorf("newest release %q is older than the running %q; refusing to downgrade", newestVersion, tagged.Tag())}withTag, err := ref.WithTag(named, newest)if err != nil {- return "", errors.WrapIff(err, "build target reference for %q", named.Name())+ return "", fmt.Errorf("build target reference for %q: %w", named.Name(), err)}return withTag.String(), nil}@@ -506,7 +505,7 @@ func ResolveUpgraderRuntimeOptions(scheme, socketPath, err := vuln.ParseDockerHost(dockerHost)if err != nil {- return nil, nil, "", errors.WrapIff(err, "resolve docker host %q", dockerHost)+ return nil, nil, "", fmt.Errorf("resolve docker host %q: %w", dockerHost, err)}if scheme != "unix" {@@ -526,7 +525,7 @@ func ResolveUpgraderRuntimeOptions(isRunningInDocker,)if err != nil {- return nil, nil, "", errors.WrapIf(err, "resolve unix socket source")+ return nil, nil, "", fmt.Errorf("resolve unix socket source: %w", err)}mounts := []mount.Mount{{@@ -605,19 +604,7 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,}}- return container.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.- New("could not find Arcane container"))+ return container.InspectResponse{}, common.Classify(common.ErrNotFound, errors.New("could not find Arcane container"))}const (@@ -663,7 +650,7 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user common.Uactive, err := s.activeUpdateAllJobInternal(ctx)if err != nil {- return nil, errors.WrapIf(err, "check for active update-all job")+ return nil, fmt.Errorf("check for active update-all job: %w", err)}if active != nil {return nil, common.Classify(common.ErrUpdateAllInProgress, errors.New("an update-all job is already in progress"))@@ -702,7 +689,7 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user common.Ujob.Results = append(EnvironmentUpdateResults{managerResult}, remoteResults...)if err := s.db.WithContext(ctx).Create(job).Error; err != nil {- return nil, errors.WrapIf(err, "create update-all job")+ return nil, fmt.Errorf("create update-all job: %w", err)}slog.InfoContext(ctx, "Update-all started; upgrading agents first", "jobId", job.ID, "user", user.Username)@@ -1110,7 +1097,7 @@ func updateAllAgentFailureStatusInternal(err error) EnvironmentUpdateResultStatureturn EnvironmentUpdateResultStatusFailed}// The environment answered with a non-success status — reached, not offline.- if _, ok := stderrors.AsType[*remenv.StatusError](err); ok {+ if _, ok := errors.AsType[*remenv.StatusError](err); ok {return EnvironmentUpdateResultStatusFailed}return EnvironmentUpdateResultStatusSkippedOffline@@ -1369,12 +1356,12 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir strreturn 0, nil}if err != nil {- return 0, errors.WrapIf(err, "open upgrade log directory")+ return 0, fmt.Errorf("open upgrade log directory: %w", err)}defer root.Close()entries, err := fs.ReadDir(root.FS(), ".")if err != nil {- return 0, errors.WrapIf(err, "read upgrade log directory")+ return 0, fmt.Errorf("read upgrade log directory: %w", err)}cutoff := now.Add(-time.Duration(retentionDays) * 24 * time.Hour)@@ -1382,7 +1369,7 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir strvar failures []errorfor _, entry := range entries {if err := ctx.Err(); err != nil {- return removed, stderrors.Join(append(failures, err)...)+ return removed, errors.Join(append(failures, err)...)}if !upgradeLogNameInternal.MatchString(entry.Name()) {continue@@ -1392,7 +1379,7 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir strcontinue}if err != nil {- failures = append(failures, errors.WrapIff(err, "inspect upgrade log %s", entry.Name()))+ failures = append(failures, fmt.Errorf("inspect upgrade log %s: %w", entry.Name(), err))continue}if !info.Mode().IsRegular() || !info.ModTime().Before(cutoff) {@@ -1400,11 +1387,11 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir str}if err := root.Remove(entry.Name()); err != nil {if !errors.Is(err, os.ErrNotExist) {- failures = append(failures, errors.WrapIff(err, "remove upgrade log %s", entry.Name()))+ failures = append(failures, fmt.Errorf("remove upgrade log %s: %w", entry.Name(), err))}continue}removed++}- return removed, stderrors.Join(failures...)+ return removed, errors.Join(failures...)}diff --git a/backend/internal/system/upgrade_service_test.go b/backend/internal/system/upgrade_service_test.goindex 2cbe9a4af..41211800b 100644--- a/backend/internal/system/upgrade_service_test.go+++ b/backend/internal/system/upgrade_service_test.go@@ -2,10 +2,10 @@ package systemimport ("context"+ "errors""fmt""testing"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"versiontypes "github.com/getarcaneapp/arcane/types/v2/version"diff --git a/backend/internal/systembackup/background.go b/backend/internal/systembackup/background.goindex 33b118a1f..999873f97 100644--- a/backend/internal/systembackup/background.go+++ b/backend/internal/systembackup/background.go@@ -3,10 +3,10 @@ package systembackupimport ("context""encoding/json/v2"+ "errors""fmt""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -42,7 +42,7 @@ func (s *SystemBackupService) StartBackup(ctx context.Context, user common.User,defer lease.Release(ctx)if runErr != nil {if saveErr := s.db.WithContext(context.WithoutCancel(workCtx)).Model(&SystemBackupRun{}).Where("id = ?", prepared.run.ID).Updates(map[string]any{"status": SystemBackupStatusFailed, "error": runErr.Error()}).Error; saveErr != nil {- runErr = errors.Combine(runErr, errors.WrapIf(saveErr, "save backup failure"))+ runErr = errors.Join(runErr, fmt.Errorf("save backup failure: %w", saveErr))}}activitylib.CompleteHandlerActivity(workCtx, s.activityService, activityID, "Arcane system backup created successfully", runErr)@@ -260,7 +260,7 @@ func (s *SystemBackupService) finishRecoveredDestinationsInternal(ctx context.Co}if checkpoint.S3Enabled && run.RemoteSnapshotID == "" {if staged.ID == "" {- return errors.New("System backup has no snapshot to replicate")+ return errors.New("System backup has no snapshot to replicate") //nolint:staticcheck // Preserve the existing error message.}snapshot, err := s.engine.Replicate(ctx, dockerClient, local, staged.ID, remote, key, "arcane-system-recovery", backup.RunSnapshotTag(run.ID))if err != nil {@@ -318,7 +318,7 @@ func (s *SystemBackupService) executeDurableBackupInternal(ctx context.Context,if ctx.Err() == nil {if err != nil {saveErr := s.db.WithContext(ctx).Model(&SystemBackupRun{}).Where("id = ?", command.Checkpoint.BackupID).Updates(map[string]any{"status": SystemBackupStatusFailed, "error": err.Error()}).Error- err = errors.Combine(err, saveErr)+ err = errors.Join(err, saveErr)}activitylib.CompleteHandlerActivity(ctx, s.activityService, command.ActivityID, "Arcane system backup created successfully", err)}diff --git a/backend/internal/systembackup/handler.go b/backend/internal/systembackup/handler.goindex c276843b0..d6d23d56d 100644--- a/backend/internal/systembackup/handler.go+++ b/backend/internal/systembackup/handler.go@@ -2,10 +2,10 @@ package systembackupimport ("context"+ "errors""net/http""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"diff --git a/backend/internal/systembackup/service.go b/backend/internal/systembackup/service.goindex ffb74ee75..a51ce3fc0 100644--- a/backend/internal/systembackup/service.go+++ b/backend/internal/systembackup/service.go@@ -5,6 +5,7 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""log/slog""maps"@@ -17,7 +18,6 @@ import ("time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -313,11 +313,11 @@ func (s *SystemBackupService) createStagedSystemRecoverySnapshotInternal(ctx con// S3 so remote backups and restore safety snapshots remain available.remoteRepository, repoErr := s.remoteRepositoryInternal(ctx, destinationID)if repoErr != nil {- return backup.Snapshot{}, backup.Repository{}, false, errors.Combine(localStagingErr, repoErr)+ return backup.Snapshot{}, backup.Repository{}, false, errors.Join(localStagingErr, repoErr)}remoteSnapshot, snapshotErr := s.snapshotWithStagedDatabaseInternal(ctx, dockerClient, remoteRepository, recoveryKey, backupID)if snapshotErr != nil {- return backup.Snapshot{}, backup.Repository{}, false, errors.Combine(localStagingErr, fmt.Errorf("failed to create S3 system recovery snapshot: %w", snapshotErr))+ return backup.Snapshot{}, backup.Repository{}, false, errors.Join(localStagingErr, fmt.Errorf("failed to create S3 system recovery snapshot: %w", snapshotErr))}return remoteSnapshot, remoteRepository, true, nil}@@ -440,7 +440,7 @@ func (s *SystemBackupService) completeBackupInternal(ctx context.Context, run *Srun.Status, run.Error = SystemBackupStatusSucceeded, ""}if saveErr := s.db.WithContext(context.WithoutCancel(ctx)).Save(run).Error; saveErr != nil {- err = errors.Combine(err, fmt.Errorf("failed to save system backup result: %w", saveErr))+ err = errors.Join(err, fmt.Errorf("failed to save system backup result: %w", saveErr))}if err == nil {err = jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "system_backup", ID: cmp.Or(run.PolicyID, run.ID), Status: schedulertypes.Succeeded})@@ -554,7 +554,7 @@ func (s *SystemBackupService) backupSnapshotLocationsInternal(ctx context.Contexif run.LocalSnapshotID != "" {repository, err := s.localRepositoryInternal(ctx, dockerClient, true)if err != nil {- setupErr = errors.Combine(setupErr, fmt.Errorf("open local system backup repository: %w", err))+ setupErr = errors.Join(setupErr, fmt.Errorf("open local system backup repository: %w", err))} else {locations = append(locations, systemBackupSnapshotLocationInternal{name: "local", destination: backuptypes.SystemBackupDestinationLocal,@@ -565,7 +565,7 @@ func (s *SystemBackupService) backupSnapshotLocationsInternal(ctx context.Contexif run.RemoteSnapshotID != "" {repository, err := s.remoteRepositoryInternal(ctx, run.S3DestinationID)if err != nil {- setupErr = errors.Combine(setupErr, fmt.Errorf("open S3 system backup repository: %w", err))+ setupErr = errors.Join(setupErr, fmt.Errorf("open S3 system backup repository: %w", err))} else {locations = append(locations, systemBackupSnapshotLocationInternal{name: "S3", destination: backuptypes.SystemBackupDestinationS3, s3DestinationID: run.S3DestinationID,@@ -594,7 +594,7 @@ func (session systemBackupSnapshotSessionInternal) firstReadableSnapshotInternalif err == nil {return snapshot, nil}- inspectErr = errors.Combine(inspectErr, err)+ inspectErr = errors.Join(inspectErr, err)}if inspectErr == nil {inspectErr = errors.New("system backup has no Rustic snapshot")@@ -634,7 +634,7 @@ func (session systemBackupSnapshotSessionInternal) availableProjectSnapshotsIntefor _, location := range locations {snapshot, err := session.inspectProjectSnapshotInternal(ctx, location)if err != nil {- inspectErr = errors.Combine(inspectErr, err)+ inspectErr = errors.Join(inspectErr, err)continue}snapshots = append(snapshots, snapshot)@@ -715,13 +715,13 @@ func (s *SystemBackupService) BrowseBackupFiles(ctx context.Context, id, recoverfor _, location := range locations {snapshot, inspectErr := session.inspectProjectManifestInternal(ctx, location)if inspectErr != nil {- browseErr = errors.Combine(browseErr, inspectErr)+ browseErr = errors.Join(browseErr, inspectErr)continue}snapshotRoot := path.Join(snapshot.layout.projectsPath, listPath)listed, listErr := s.engine.ListSnapshotFiles(ctx, dockerClient, location.repository, key, location.snapshotID, snapshotRoot+"/", recursive)if listErr != nil {- browseErr = errors.Combine(browseErr, fmt.Errorf("browse %s system recovery snapshot: %w", location.name, listErr))+ browseErr = errors.Join(browseErr, fmt.Errorf("browse %s system recovery snapshot: %w", location.name, listErr))continue}entries := projectEntriesFromSnapshotInternal(listed, snapshot.layout, listPath, recursive)@@ -781,7 +781,7 @@ func (session systemBackupSnapshotSessionInternal) restoreEntryInternal(ctx contif err == nil {return nil}- restoreErr = errors.Combine(restoreErr, fmt.Errorf("restore from %s snapshot: %w", snapshot.name, err))+ restoreErr = errors.Join(restoreErr, fmt.Errorf("restore from %s snapshot: %w", snapshot.name, err))}if restoreErr == nil {restoreErr = errors.New("file is unavailable in every readable system recovery snapshot")@@ -824,7 +824,7 @@ func (session systemBackupSnapshotSessionInternal) rollbackInternal(ctx context.for _, selectedEntry := range slices.Backward(selected) {if !safetySnapshotContainsPathInternal(safety, selectedEntry.Path) {if err := removeProjectFileInternal(ctx, destination.directory, selectedEntry.Path); err != nil {- rollbackErr = errors.Combine(rollbackErr, fmt.Errorf("remove newly restored project path %s: %w", selectedEntry.Path, err))+ rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove newly restored project path %s: %w", selectedEntry.Path, err))}continue}@@ -838,7 +838,7 @@ func (session systemBackupSnapshotSessionInternal) rollbackInternal(ctx context.DestinationPath: path.Join(destination.target.Path, selectedEntry.Path),ExtraMounts: destination.target.Mounts[1:],}); err != nil {- rollbackErr = errors.Combine(rollbackErr, fmt.Errorf("restore project path %s from safety backup: %w", selectedEntry.Path, err))+ rollbackErr = errors.Join(rollbackErr, fmt.Errorf("restore project path %s from safety backup: %w", selectedEntry.Path, err))}}return rollbackErr@@ -853,7 +853,7 @@ func (session systemBackupSnapshotSessionInternal) restoreSelectedInternal(ctx crollbackErr := session.rollbackInternal(context.WithoutCancel(ctx), safety, affected, destination)restoreErr := fmt.Errorf("failed to restore project path %s from system backup: %w", selectedEntry.Path, err)if rollbackErr != nil {- return errors.Combine(restoreErr, fmt.Errorf("failed to roll back project files from pre-restore system backup: %w", rollbackErr))+ return errors.Join(restoreErr, fmt.Errorf("failed to roll back project files from pre-restore system backup: %w", rollbackErr))}return fmt.Errorf("%w; affected project files were rolled back", restoreErr)}@@ -976,17 +976,17 @@ func (s *SystemBackupService) deleteRunsInternal(ctx context.Context, runs []*Sy}deleteErr := s.forgetLocalSnapshotsInternal(ctx, dockerClient, key, localRuns)for destinationID, group := range remoteGroups {- deleteErr = errors.Combine(deleteErr, s.forgetRemoteSnapshotsInternal(ctx, dockerClient, key, destinationID, group))+ deleteErr = errors.Join(deleteErr, s.forgetRemoteSnapshotsInternal(ctx, dockerClient, key, destinationID, group))}for _, run := range runs {if run.LocalSnapshotID == "" && run.RemoteSnapshotID == "" {if err := s.db.WithContext(ctx).Delete(run).Error; err != nil {- deleteErr = errors.Combine(deleteErr, fmt.Errorf("failed to delete system backup record: %w", err))+ deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete system backup record: %w", err))}continue}if saveErr := s.db.WithContext(ctx).Save(run).Error; saveErr != nil {- deleteErr = errors.Combine(deleteErr, saveErr)+ deleteErr = errors.Join(deleteErr, saveErr)}}return deleteErr@@ -1723,14 +1723,14 @@ func (s *SystemBackupService) backupSourceLayoutInternal(ctx context.Context, do}layout.mounts, err = sourceMountsInternal(mounts, inContainer, layout.dataDirectory, snapshotDataPath)if err != nil {- return backupSourceLayoutInternal{}, errors.WrapIf(err, "resolve Arcane data source")+ return backupSourceLayoutInternal{}, fmt.Errorf("resolve Arcane data source: %w", err)}if !external {return layout, nil}projectMounts, err := sourceMountsInternal(mounts, inContainer, layout.projectsDirectory, snapshotProjectsPath)if err != nil {- return backupSourceLayoutInternal{}, errors.WrapIf(err, "resolve projects source")+ return backupSourceLayoutInternal{}, fmt.Errorf("resolve projects source: %w", err)}layout.mounts = append(layout.mounts, projectMounts...)layout.sources = append(layout.sources, snapshotProjectsPath)@@ -1798,7 +1798,7 @@ func (session systemBackupSnapshotSessionInternal) readSnapshotLayoutInternal(ctfor _, candidate := range manifestCandidateRootsInternal {data, err := session.service.engine.ReadSnapshotTextFile(ctx, session.dockerClient, location.repository, session.recoveryKey, location.snapshotID, path.Join(candidate, systemRecoveryManifestName))if err != nil {- readErr = errors.Combine(readErr, err)+ readErr = errors.Join(readErr, err)continue}manifestData, manifestRoot = data, candidate@@ -1984,7 +1984,7 @@ func (s *SystemBackupService) projectsRestoreDestinationInternal(ctx context.Con}target, err := restoreTargetInternal(mounts, directory, selectiveProjectsRestoreTarget, "")if err != nil {- return projectsRestoreDestinationInternal{}, errors.WrapIf(err, "resolve projects directory for restore")+ return projectsRestoreDestinationInternal{}, fmt.Errorf("resolve projects directory for restore: %w", err)}return projectsRestoreDestinationInternal{directory: directory, target: target}, nil}diff --git a/backend/internal/systembackup/service_test.go b/backend/internal/systembackup/service_test.goindex cbc36bd08..86af6eb4d 100644--- a/backend/internal/systembackup/service_test.go+++ b/backend/internal/systembackup/service_test.go@@ -3,6 +3,7 @@ package systembackupimport ("context""encoding/json/v2"+ "errors""net/http""net/http/httptest""os"@@ -10,7 +11,6 @@ import ("slices""testing"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"diff --git a/backend/internal/systembackup/snapshot.go b/backend/internal/systembackup/snapshot.goindex 162463c26..fa955bd17 100644--- a/backend/internal/systembackup/snapshot.go+++ b/backend/internal/systembackup/snapshot.go@@ -3,6 +3,7 @@ package systembackupimport ("context""database/sql"+ "errors""fmt""io/fs""os"@@ -10,7 +11,6 @@ import ("syscall""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/moby/moby/client")@@ -80,7 +80,7 @@ func (s *SystemBackupService) snapshotWithStagedDatabaseInternal(ctx context.Conif cleanupErr != nil {cleanupErr = fmt.Errorf("remove unconfirmed system snapshot %s: %w", snapshot.ID, cleanupErr)}- return backup.Snapshot{}, errors.Combine(err, cleanupErr)+ return backup.Snapshot{}, errors.Join(err, cleanupErr)}// snapshotSourceFilesInternal records inputs before taking the database snapshot.diff --git a/backend/internal/systembackup/system_volume.go b/backend/internal/systembackup/system_volume.goindex 290c7da68..7168e47dd 100644--- a/backend/internal/systembackup/system_volume.go+++ b/backend/internal/systembackup/system_volume.go@@ -3,13 +3,13 @@ package systembackupimport ("context""encoding/json/v2"+ "errors""fmt""log/slog""slices""strings""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"diff --git a/backend/internal/template/handler.go b/backend/internal/template/handler.goindex 2dc6129c1..7d12a3f9d 100644--- a/backend/internal/template/handler.go+++ b/backend/internal/template/handler.go@@ -4,8 +4,8 @@ import ("cmp""context""encoding/json/v2"+ "errors"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -272,7 +272,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatetemplates, paginationResp, err := h.templateService.GetAllTemplatesPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())+ return nil, huma.Error500InternalServerError("Failed to get templates: " + err.Error())}return &handlerutil.Page[templatetypes.Template]{@@ -288,12 +288,12 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatefunc (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*handlerutil.Out[[]templatetypes.Template], error) {templates, err := h.templateService.GetAllTemplates(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())+ return nil, huma.Error500InternalServerError("Failed to get templates: " + err.Error())}out, mapErr := mapping.MapSlice[ComposeTemplate, templatetypes.Template](templates)if mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())+ return nil, huma.Error500InternalServerError("Failed to map templates: " + mapErr.Error())}return &handlerutil.Out[[]templatetypes.Template]{@@ -315,12 +315,12 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInpif errors.Is(err, common.ErrTemplateNotFound) {return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template").Error())+ return nil, huma.Error500InternalServerError("Failed to get template: " + err.Error())}var out templatetypes.Templateif mapErr := mapping.MapStruct(tmpl, &out); mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())+ return nil, huma.Error500InternalServerError("Failed to map templates: " + mapErr.Error())}return &handlerutil.Out[templatetypes.Template]{@@ -342,7 +342,7 @@ func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTempif errors.Is(err, common.ErrTemplateNotFound) {return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template content").Error())+ return nil, huma.Error500InternalServerError("Failed to get template content: " + err.Error())}return &handlerutil.Out[templatetypes.TemplateContent]{@@ -367,12 +367,12 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl}if err := h.templateService.CreateTemplate(ctx, tmpl); err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create template").Error())+ return nil, huma.Error500InternalServerError("Failed to create template: " + err.Error())}var out templatetypes.Templateif mapErr := mapping.MapStruct(tmpl, &out); mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())+ return nil, huma.Error500InternalServerError("Failed to map templates: " + mapErr.Error())}return &handlerutil.Out[templatetypes.Template]{@@ -404,17 +404,17 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplif errors.Is(err, common.ErrTemplateNotFound) {return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update template").Error())+ return nil, huma.Error500InternalServerError("Failed to update template: " + err.Error())}updated, err := h.templateService.GetTemplate(ctx, input.ID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template").Error())+ return nil, huma.Error500InternalServerError("Failed to get template: " + err.Error())}var out templatetypes.Templateif mapErr := mapping.MapStruct(updated, &out); mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())+ return nil, huma.Error500InternalServerError("Failed to map templates: " + mapErr.Error())}return &handlerutil.Out[templatetypes.Template]{@@ -435,7 +435,7 @@ func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplif errors.Is(err, common.ErrTemplateNotFound) {return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete template").Error())+ return nil, huma.Error500InternalServerError("Failed to delete template: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -459,7 +459,7 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTif errors.Is(err, common.ErrTemplateNotFound) {return nil, huma.Error404NotFound("Template not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to download template").Error())+ return nil, huma.Error500InternalServerError("Failed to download template: " + err.Error())}if !tmpl.IsRemote {return nil, huma.Error400BadRequest("Template is already local")@@ -467,12 +467,12 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTlocalTemplate, err := h.templateService.DownloadTemplate(ctx, tmpl)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to download template").Error())+ return nil, huma.Error500InternalServerError("Failed to download template: " + err.Error())}var out templatetypes.Templateif mapErr := mapping.MapStruct(localTemplate, &out); mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())+ return nil, huma.Error500InternalServerError("Failed to map templates: " + mapErr.Error())}return &handlerutil.Out[templatetypes.Template]{@@ -506,11 +506,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) (*handlerutil.Out[base.MessageResponse], error) {if err := h.templateService.SaveComposeTemplate(ctx, input.Body.ComposeContent); err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())+ return nil, huma.Error500InternalServerError("Failed to save default template: " + err.Error())}if err := h.templateService.SaveEnvTemplate(ctx, input.Body.EnvContent); err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())+ return nil, huma.Error500InternalServerError("Failed to save default template: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -562,12 +562,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(errors.WithMessage(err, "Failed to create registry").Error())+ return nil, huma.Error500InternalServerError("Failed to create registry: " + err.Error())}var out templatetypes.TemplateRegistryif mapErr := mapping.MapStruct(registry, &out); mapErr != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())+ return nil, huma.Error500InternalServerError("Failed to map registry: " + mapErr.Error())}return &handlerutil.Out[templatetypes.TemplateRegistry]{@@ -594,7 +594,7 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplif err.Error() == "registry not found" {return nil, huma.Error404NotFound("Registry not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update registry").Error())+ return nil, huma.Error500InternalServerError("Failed to update registry: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -617,7 +617,7 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplif err.Error() == "registry not found" {return nil, huma.Error404NotFound("Registry not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete registry").Error())+ return nil, huma.Error500InternalServerError("Failed to delete registry: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{diff --git a/backend/internal/template/service.go b/backend/internal/template/service.goindex 2bd47079c..26c367e35 100644--- a/backend/internal/template/service.go+++ b/backend/internal/template/service.go@@ -3,6 +3,7 @@ package templateimport ("context""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -15,7 +16,6 @@ import ("time""uuid"- "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/settings"@@ -131,7 +131,7 @@ func (s *TemplateService) ensureRemoteTemplatesLoaded(_ context.Context) error {}templates, found, err := s.remoteCache.Get(struct{}{})if err != nil {- return errors.WrapIf(err, "failed to load remote templates")+ return fmt.Errorf("failed to load remote templates: %w", err)}return kit.Ternary(!found || len(templates) == 0, errNoRemoteTemplates, nil)}@@ -139,7 +139,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 errors.WrapIf(err, "failed to load remote templates")+ return fmt.Errorf("failed to load remote templates: %w", err)}if len(templates) == 0 {@@ -232,11 +232,11 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*ComposeTif 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, errors.WrapIf(err, "failed to query local template")+ return nil, fmt.Errorf("failed to query local template: %w", err)}if err := s.ensureRemoteTemplatesLoaded(ctx); err != nil && !errors.Is(err, errNoRemoteTemplates) {- return nil, errors.WrapIff(err, "template %q lookup failed: registry refresh error", id)+ return nil, fmt.Errorf("template %q lookup failed: registry refresh error: %w", id, err)}if found := s.lookupRemoteFromCacheInternal(id); found != nil {@@ -249,15 +249,15 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*ComposeTif 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, errors.WrapIff(refreshErr, "template %q not found and registry refresh failed", id)+ return nil, fmt.Errorf("template %q not found and registry refresh failed: %w", id, refreshErr)}if found := s.lookupRemoteFromCacheInternal(id); found != nil {return found, nil}- 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.Classify(common.ErrTemplateNotFound, fmt.Errorf("Template not found: %w", fmt.Errorf("template %q not found in any registered registry (cache size=%d after refresh)", id, s.remoteCacheSizeInternal()))) //nolint:staticcheck // Preserve the existing error message.}- return nil, common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))+ return nil, common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.}func (s *TemplateService) lookupRemoteFromCacheInternal(id string) *ComposeTemplate {@@ -297,7 +297,7 @@ func (s *TemplateService) CreateTemplate(ctx context.Context, template *ComposeTsetTemplateIconURL(template, projects.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 errors.WrapIf(err, "failed to create template")+ return fmt.Errorf("failed to create template: %w", err)}return nil})@@ -311,9 +311,9 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updatesvar existing ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))+ return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.}- return errors.WrapIf(err, "failed to find template")+ return fmt.Errorf("failed to find template: %w", err)}if existing.IsRemote {@@ -325,11 +325,9 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updatesexisting.Content = updates.Contentexisting.EnvContent = updates.EnvContentsetTemplateIconURL(&existing, projects.ResolveTemplateIconURL(ctx, existing.Content, mo.PointerToOption(existing.EnvContent).OrEmpty()))-if err := tx.Save(&existing).Error; err != nil {- return errors.WrapIf(err, "failed to update template")+ return fmt.Errorf("failed to update template: %w", err)}-return nil})}@@ -339,9 +337,9 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {var existing ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))+ return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.}- return errors.WrapIf(err, "failed to find template")+ return fmt.Errorf("failed to find template: %w", err)}if existing.IsRemote {@@ -350,20 +348,19 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {baseDir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return errors.WrapIf(err, "failed to get templates directory")+ return fmt.Errorf("failed to get templates directory: %w", err)}templatePath := filepath.Join(baseDir, existing.Name)if entry, err := acfs.Stat(ctx, baseDir, "/"+existing.Name, false); err == nil && entry.IsDirectory {if _, err := projects.DetectComposeFile(ctx, "", templatePath); err == nil {if err := acfs.RemoveAll(ctx, baseDir, entry.Path); err != nil {- return errors.WrapIf(err, "failed to delete template directory")+ return fmt.Errorf("failed to delete template directory: %w", err)}}}-if err := tx.Delete(&existing).Error; err != nil {- return errors.WrapIf(err, "failed to delete template")+ return fmt.Errorf("failed to delete template: %w", err)}return nil})@@ -376,7 +373,7 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {func (s *TemplateService) readDefaultTemplateInternal(ctx context.Context, fileName string) (string, error) {baseDir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to get templates directory")+ return "", fmt.Errorf("failed to get templates directory: %w", err)}content, err := acfs.ReadFile(ctx, baseDir, "/"+fileName)if err != nil {@@ -415,7 +412,7 @@ func (s *TemplateService) GetSwarmStackEnvTemplate(ctx context.Context) string {func (s *TemplateService) SaveComposeTemplate(ctx context.Context, content string) error {baseDir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return errors.WrapIf(err, "failed to get templates directory")+ return fmt.Errorf("failed to get templates directory: %w", err)}return acfs.Write(ctx, baseDir, "/.compose.template", []byte(content), acfs.WriteOptions{Mode: utils.FilePerm})}@@ -432,7 +429,7 @@ func (s *TemplateService) GetEnvTemplate(ctx context.Context) string {func (s *TemplateService) SaveEnvTemplate(ctx context.Context, content string) error {baseDir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return errors.WrapIf(err, "failed to get templates directory")+ return fmt.Errorf("failed to get templates directory: %w", err)}return acfs.Write(ctx, baseDir, "/.env.template", []byte(content), acfs.WriteOptions{Mode: utils.FilePerm})}@@ -441,7 +438,7 @@ func (s *TemplateService) GetRegistries(ctx context.Context) ([]TemplateRegistryvar registries []TemplateRegistryerr := s.db.WithContext(ctx).Find(®istries).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to get registries")+ return nil, fmt.Errorf("failed to get registries: %w", err)}return registries, nil}@@ -473,7 +470,7 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *Templateregistry.Description = manifest.Description}} else if registry.Name == "" || registry.Description == "" {- return errors.WrapIf(err, "failed to fetch registry manifest")+ return fmt.Errorf("failed to fetch registry manifest: %w", err)}}@@ -486,7 +483,7 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *Templateerr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Create(registry).Error; err != nil {- return errors.WrapIf(err, "failed to create registry")+ return fmt.Errorf("failed to create registry: %w", err)}return nil})@@ -508,7 +505,7 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updatesif errors.Is(err, gorm.ErrRecordNotFound) {return errors.New("registry not found")}- return errors.WrapIf(err, "failed to find registry")+ return fmt.Errorf("failed to find registry: %w", err)}if err := s.hydrateRegistryUpdates(ctx, updates, &existing); err != nil {@@ -550,7 +547,7 @@ func (s *TemplateService) hydrateRegistryUpdates(ctx context.Context, updates, eupdates.Description = manifest.Description}} else if urlChanged && (updates.Name == "" || updates.Description == "") {- return errors.WrapIf(err, "failed to fetch registry manifest")+ return fmt.Errorf("failed to fetch registry manifest: %w", err)}}return nil@@ -639,17 +636,17 @@ func (s *TemplateService) doGET(ctx context.Context, url string) ([]byte, error)}resp, err := client.Do(req)if err != nil {- return nil, errors.WrapIff(err, "failed to fetch %s", url)+ return nil, fmt.Errorf("failed to fetch %s: %w", url, err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return nil, errors.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)+ return nil, fmt.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, errors.WrapIff(err, "failed to read response body from %s", url)+ return nil, fmt.Errorf("failed to read response body from %s: %w", url, err)}return body, nil}@@ -663,7 +660,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *Templclient, req, err := s.newSafeRequestInternal(ctx, http.MethodGet, reg.URL)if err != nil {- return nil, errors.WrapIf(err, "create request")+ return nil, fmt.Errorf("create request: %w", err)}if fetchMeta != nil && fetchMeta.LastModified != "" {req.Header.Set("If-Modified-Since", fetchMeta.LastModified)@@ -671,7 +668,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *Templresp, err := client.Do(req)if err != nil {- return nil, errors.WrapIf(err, "request failed")+ return nil, fmt.Errorf("request failed: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -682,17 +679,17 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *Templreturn nil, errors.New("received 304 without cached data")}if resp.StatusCode != http.StatusOK {- return nil, errors.Errorf("unexpected status %d", resp.StatusCode)+ return nil, fmt.Errorf("unexpected status %d", resp.StatusCode)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, errors.WrapIf(err, "read body")+ return nil, fmt.Errorf("read body: %w", err)}var regDTO tmpl.RemoteRegistryif err := json.Unmarshal(body, ®DTO); err != nil {- return nil, errors.WrapIf(err, "parse registry JSON")+ return nil, fmt.Errorf("parse registry JSON: %w", err)}templates := make([]ComposeTemplate, 0, len(regDTO.Templates))@@ -720,7 +717,7 @@ func (s *TemplateService) fetchRegistryManifest(ctx context.Context, url string)}var reg tmpl.RemoteRegistryif err := json.Unmarshal(body, ®); err != nil {- return nil, errors.WrapIf(err, "failed to parse registry JSON")+ return nil, fmt.Errorf("failed to parse registry JSON: %w", err)}if reg.Name == "" || len(reg.Templates) == 0 {return nil, errors.New("invalid registry manifest: missing required fields (name, templates)")@@ -761,7 +758,7 @@ func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *Coreturn template.Content, envContent, nil}if template.Metadata == nil || template.Metadata.RemoteURL == nil || strings.TrimSpace(*template.Metadata.RemoteURL) == "" {- return "", "", errors.Errorf("remote template %q is missing compose_url in registry metadata", template.ID)+ return "", "", fmt.Errorf("remote template %q is missing compose_url in registry metadata", template.ID)}return s.fetchRemoteTemplateFiles(ctx, template)@@ -774,7 +771,7 @@ func (s *TemplateService) fetchRemoteTemplateFiles(ctx context.Context, templatecomposeContent, err := s.fetchURL(ctx, *template.Metadata.RemoteURL)if err != nil {- return "", "", errors.WrapIff(err, "failed to fetch compose content from %s", *template.Metadata.RemoteURL)+ return "", "", fmt.Errorf("failed to fetch compose content from %s: %w", *template.Metadata.RemoteURL, err)}var envContent string@@ -862,7 +859,7 @@ func (s *TemplateService) newSafeRequestInternal(ctx context.Context, method, rareq, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), nil)if err != nil {- return nil, nil, errors.WrapIff(err, "failed to create request for %s", rawURL)+ return nil, nil, fmt.Errorf("failed to create request for %s: %w", rawURL, err)}return client, req, nil@@ -889,15 +886,14 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remoterr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var existing ComposeTemplate- if err := tx.- Where("is_remote = ? AND registry_id IS NULL AND (description = ? OR name = ?)", false, srcDesc, base).+ if 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 errors.WrapIf(err, "failed to check existing template")+ return fmt.Errorf("failed to check existing template: %w", err)} else if err == nil {// Existing template foundcomposeContent, envContent, err := s.FetchTemplateContent(ctx, remoteTemplate)if err != nil {- return errors.WrapIf(err, "failed to fetch template content for existing local template")+ return fmt.Errorf("failed to fetch template content for existing local template: %w", err)}envPtr, werr := projects.WriteTemplateFiles(composePath, envPath, composeContent, envContent)@@ -910,7 +906,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remotexisting.Metadata = cloneTemplateMetadata(remoteTemplate.Metadata)if err := tx.Save(&existing).Error; err != nil {- return errors.WrapIf(err, "failed to update existing local template")+ return fmt.Errorf("failed to update existing local template: %w", err)}resultTemplate = &existingreturn nil@@ -919,7 +915,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot// New templatecomposeContent, envContent, err := s.FetchTemplateContent(ctx, remoteTemplate)if err != nil {- return errors.WrapIf(err, "failed to fetch template content for download")+ return fmt.Errorf("failed to fetch template content for download: %w", err)}envPtr, werr := projects.WriteTemplateFiles(composePath, envPath, composeContent, envContent)@@ -941,7 +937,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot}if err := tx.Create(localTemplate).Error; err != nil {- return errors.WrapIf(err, "failed to save local template")+ return fmt.Errorf("failed to save local template: %w", err)}resultTemplate = localTemplatereturn nil@@ -1028,8 +1024,7 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, de// Matching on name as a fallback keeps a single row across templates-directory// reconfigurations or compose-filename renames within the same folder, but// only for templates previously imported from disk.- q := tx.- Where("is_remote = ? AND registry_id IS NULL AND (description = ? OR (name = ? AND description LIKE ?))", false, desc, name, "Imported from %").+ q := tx.Where("is_remote = ? AND registry_id IS NULL AND (description = ? OR (name = ? AND description LIKE ?))", false, desc, name, "Imported from %").First(&existing)if q.Error == nil {@@ -1041,12 +1036,15 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, deexisting.IsRemote = falsesetTemplateIconURL(&existing, iconURL)if err := tx.Save(&existing).Error; err != nil {- return errors.WrapIff(err, "update template %s", existing.ID)+ return fmt.Errorf("update template %s: %w", existing.ID, err)}return nil}if !errors.Is(q.Error, gorm.ErrRecordNotFound) {- return errors.WrapIf(q.Error, "query existing template")+ if err := q.Error; err != nil {+ return fmt.Errorf("query existing template: %w", err)+ }+ return nil}tpl := &ComposeTemplate{@@ -1063,7 +1061,7 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, de}setTemplateIconURL(tpl, iconURL)if err := tx.Create(tpl).Error; err != nil {- return errors.WrapIff(err, "insert template %s", name)+ return fmt.Errorf("insert template %s: %w", name, err)}return nil})@@ -1087,7 +1085,7 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) edir, err := s.getTemplatesDirectoryInternal(ctx)if err != nil {- return errors.WrapIf(err, "ensure templates dir")+ return fmt.Errorf("ensure templates dir: %w", err)}entries, err := acfs.List(ctx, dir, "/")@@ -1095,7 +1093,7 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) eif os.IsNotExist(err) {return nil}- return errors.WrapIff(err, "read dir %s", dir)+ return fmt.Errorf("read dir %s: %w", dir, err)}for _, ent := range entries {@@ -1147,7 +1145,7 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,if composeTemplate.IsRemote {composeContent, envContent, err = s.FetchTemplateContent(ctx, composeTemplate)if err != nil {- return nil, errors.WrapIf(err, "failed to fetch template content")+ return nil, fmt.Errorf("failed to fetch template content: %w", err)}} else {composeContent = composeTemplate.Content@@ -1160,7 +1158,7 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,var outTemplate tmpl.Templateif mapErr := mapping.MapStruct(composeTemplate, &outTemplate); mapErr != nil {- return nil, errors.WrapIf(mapErr, "failed to map template")+ return nil, fmt.Errorf("failed to map template: %w", mapErr)}// Parse services from compose content using compose-go library@@ -1190,7 +1188,7 @@ func (s *TemplateService) getMergedTemplates(ctx context.Context) ([]ComposeTempvar templates []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, errors.WrapIf(err, "failed to get local templates")+ return nil, fmt.Errorf("failed to get local templates: %w", err)}if err := s.ensureRemoteTemplatesLoaded(ctx); err != nil {diff --git a/backend/internal/updater/actors.go b/backend/internal/updater/actors.goindex 564d318a1..b9eaa8d2a 100644--- a/backend/internal/updater/actors.go+++ b/backend/internal/updater/actors.go@@ -2,9 +2,9 @@ package updaterimport ("context"+ "errors""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -181,7 +181,7 @@ func (a *singleUpdateActorInternal) Job(ctx context.Context, _ string, data actodefer release()var command arcaneupdater.SingleUpdateCommandif err := data.Decode(&command); err != nil {- return errors.Combine(err, actor.ErrJobPermanentFailure)+ return errors.Join(err, actor.ErrJobPermanentFailure)}var state arcaneupdater.SingleUpdateStateif err := s.singleUpdates.GetState(ctx, singleUpdateStateTypeInternal, command.ActivityID, &state); err != nil {diff --git a/backend/internal/updater/admission.go b/backend/internal/updater/admission.godeleted file mode 100644index 2b6620101..000000000--- a/backend/internal/updater/admission.go+++ /dev/null@@ -1,26 +0,0 @@-package updater--import (- "context"-- "emperror.dev/errors"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-)--type updateAdmissionKeyInternal struct{}--var errUpdateBusyInternal = errors.New("another container update is running")--func (s *UpdaterService) acquireUpdateInternal(ctx context.Context) (context.Context, func(), error) {- if s.admission == nil || ctx.Value(updateAdmissionKeyInternal{}) == s {- return ctx, func() {}, nil- }- lease, admitted, err := s.admission.TryAcquire(ctx, schedulertypes.AdmissionKey{Scope: "updater"})- if err != nil {- return ctx, nil, err- }- if !admitted {- return ctx, nil, errUpdateBusyInternal- }- return context.WithValue(ctx, updateAdmissionKeyInternal{}, s), func() { lease.Release(ctx) }, nil-}diff --git a/backend/internal/updater/handler.go b/backend/internal/updater/handler.goindex a87cb133f..4b616176c 100644--- a/backend/internal/updater/handler.go+++ b/backend/internal/updater/handler.go@@ -2,10 +2,10 @@ package updaterimport ("context"+ "errors""net/http""reflect"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -121,9 +121,9 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)out, err := h.updaterService.ApplyPending(runtimeCtx, options)if err != nil {if errors.Is(err, common.ErrBadRequest) {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to run updater").Error())+ return nil, huma.Error400BadRequest("Failed to run updater: " + err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())+ return nil, huma.Error500InternalServerError("Failed to run updater: " + err.Error())}return &handlerutil.Out[*updater.Result]{@@ -155,7 +155,7 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdatehistory, err := h.updaterService.GetHistory(ctx, limit)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get updater history").Error())+ return nil, huma.Error500InternalServerError("Failed to get updater history: " + err.Error())}return &handlerutil.Out[[]AutoUpdateRecord]{@@ -171,7 +171,7 @@ func (h *UpdaterHandler) updateContainerInternal(ctx context.Context, input *Updif input.Async {activity, err := h.updaterService.AcceptSingleContainerUpdate(runtimeCtx, input.ContainerID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to accept container update").Error())+ return nil, huma.Error500InternalServerError("Failed to accept container update: " + err.Error())}return &updateContainerOutput{Status: http.StatusAccepted,@@ -180,7 +180,7 @@ func (h *UpdaterHandler) updateContainerInternal(ctx context.Context, input *Upd}out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())+ return nil, huma.Error500InternalServerError("Failed to run updater: " + err.Error())}return &updateContainerOutput{diff --git a/backend/internal/updater/recovery.go b/backend/internal/updater/recovery.goindex caedf5927..383feda5f 100644--- a/backend/internal/updater/recovery.go+++ b/backend/internal/updater/recovery.go@@ -4,11 +4,11 @@ import ("cmp""context""encoding/json/v2"+ "errors""log/slog""strings""sync"- "emperror.dev/errors"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"@@ -78,10 +78,10 @@ func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result updater.ResprogressMessage = evidenceErr.Error()}progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: result.ResourceID, ResourceType: string(result.ResourceType), Status: status, Message: progressMessage, ActivityID: activityIDFromContextInternal(ctx)})- err := errors.Combine(recordErr, progressErr, evidenceErr)+ err := errors.Join(recordErr, progressErr, evidenceErr)if progress, ok := ctx.Value(updateProgressKeyInternal{}).(*updateProgressInternal); ok && err != nil {progress.mu.Lock()- progress.err = errors.Combine(progress.err, err)+ progress.err = errors.Join(progress.err, err)progress.mu.Unlock()}return err@@ -111,7 +111,7 @@ func (s *UpdaterService) verifyFrozenResultInternal(ctx context.Context, resourcfunc (p *updateProgressInternal) completeBatchInternal(ctx context.Context, options arcaneupdater.Options, out *arcaneupdater.Result, batchCompleted bool, err error) error {activityID := activityIDFromContextInternal(ctx)p.mu.Lock()- err = errors.Combine(err, p.err)+ err = errors.Join(err, p.err)recordingFailed := p.err != nil_, durableRun := jobcontext.Run(ctx)selfTriggered := p.selfTriggered && durableRun@@ -129,9 +129,9 @@ func (p *updateProgressInternal) completeBatchInternal(ctx context.Context, optistatus = schedulertypes.NeedsAttention}if selfTriggered {- err = errors.Combine(err, jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: selfID, ResourceType: "container", Status: schedulertypes.NeedsAttention, ActivityID: activityID, Message: "Self-update completion requires review"}))+ err = errors.Join(err, jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: selfID, ResourceType: "container", Status: schedulertypes.NeedsAttention, ActivityID: activityID, Message: "Self-update completion requires review"}))status = schedulertypes.NeedsAttention- err = errors.Combine(err, errors.New("self-update was triggered but completion requires review"))+ err = errors.Join(err, errors.New("self-update was triggered but completion requires review"))}batchType := updateBatchTypeInternal(ctx, options, batchCompleted)checkpoint := schedulertypes.TargetOutcome{ID: "auto-update", ResourceType: batchType, Status: status, ActivityID: activityID}@@ -139,7 +139,7 @@ func (p *updateProgressInternal) completeBatchInternal(ctx context.Context, opticheckpoint.Message = err.Error()}checkpointErr := jobcontext.Progress(ctx, checkpoint)- err = errors.Combine(err, checkpointErr)+ err = errors.Join(err, checkpointErr)if err != nil {out.Success = false}diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.goindex 7ac68754a..30abb00a7 100644--- a/backend/internal/updater/service.go+++ b/backend/internal/updater/service.go@@ -3,6 +3,7 @@ package updaterimport ("cmp""context"+ "errors""fmt""io""log/slog"@@ -12,7 +13,6 @@ import ("sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -130,7 +130,7 @@ func NewUpdaterService(}engine, err := updater.New(service.configInternal())if err != nil {- return nil, errors.WrapIf(err, "configure updater engine")+ return nil, fmt.Errorf("configure updater engine: %w", err)}service.engine = engineevents.SetDockerUpdatingContainers(func() []string { return engine.Status().ContainerIDs })@@ -334,19 +334,19 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, optionsStatus: arcaneupdater.StatusFailed,Error: engineErr.Error(),})- engineErrs = append(engineErrs, errors.WrapIff(engineErr, "%s", containerID))+ engineErrs = append(engineErrs, fmt.Errorf("%s: %w", containerID, engineErr))target.Status = schedulertypes.Failedtarget.Message = engineErr.Error()}if err := jobcontext.Progress(ctx, target); err != nil {- return errors.Combine(err, errors.Combine(engineErrs...))+ return errors.Join(err, errors.Join(engineErrs...))}}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.Combine(engineErrs...)+ return errors.Join(engineErrs...)}// resolveScopedContainerIDsInternal maps a scoped options payload to the@@ -365,7 +365,7 @@ func (s *UpdaterService) resolveScopedContainerIDsInternal(ctx context.Context,case "image":return s.containerIDsForImagesInternal(ctx, requested)default:- return nil, errors.Errorf("unsupported scoped update type %q", options.Type)+ return nil, fmt.Errorf("unsupported scoped update type %q", options.Type)}}@@ -396,7 +396,7 @@ func (s *UpdaterService) containerIDsForProjectsInternal(ctx context.Context, prcontainers, _, _, _, err := s.deps.Docker.GetAllContainers(ctx)if err != nil {- return nil, errors.WrapIf(err, "list containers")+ return nil, fmt.Errorf("list containers: %w", err)}var ids []string@@ -436,7 +436,7 @@ func (s *UpdaterService) containerIDsForImagesInternal(ctx context.Context, imagcontainers, _, _, _, err := s.deps.Docker.GetAllContainers(ctx)if err != nil {- return nil, errors.WrapIf(err, "list containers")+ return nil, fmt.Errorf("list containers: %w", err)}var ids []string@@ -484,7 +484,7 @@ func (s *UpdaterService) AcceptSingleContainerUpdate(ctx context.Context, contaistate := arcaneupdater.SingleUpdateState{Command: command, Status: "queued"}if err := s.singleUpdates.SetState(workCtx, singleUpdateStateTypeInternal, activity.ID, state, nil); err != nil {s.finishSingleContainerUpdateInternal(workCtx, activity.ID, nil, err)- return nil, errors.WrapIf(err, "persist container update")+ return nil, fmt.Errorf("persist container update: %w", err)}if err := s.dispatchSingleInternal(workCtx, state); err != nil {s.loggerInternal().WarnContext(workCtx, "container update dispatch deferred", "activityId", activity.ID, "error", err)@@ -553,7 +553,7 @@ func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]AutoUpdatquery = query.Limit(limit)}if err := query.Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "get history")+ return nil, fmt.Errorf("get history: %w", err)}return records, nil}@@ -567,7 +567,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 errors.Errorf("%s: container is not an Arcane self-update target", source)+ return fmt.Errorf("%s: container is not an Arcane self-update target", source)}return s.TriggerSelfUpdate(ctx, updater.SelfUpdateTarget{ContainerID: containerID,@@ -663,7 +663,7 @@ func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progresif s.deps.Projects != nil {resolved, err := s.deps.Projects.ResolveRegistryCredentials(pullCtx)if err != nil {- return errors.WrapIf(err, "resolve registry credentials")+ return fmt.Errorf("resolve registry credentials: %w", err)}if err := s.deps.ImagePuller.PullImage(pullCtx, pulledRef, writer, s.deps.SystemUser, resolved); err != nil {return err@@ -688,7 +688,7 @@ func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]updater.Imavar records []imageupdate.ImageUpdateRecordif err := s.deps.DB.WithContext(ctx).Where("has_update = ? AND project_id = ?", true, "").Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "query pending image updates")+ return nil, fmt.Errorf("query pending image updates: %w", err)}// Flush pending "Updates Available" notifications before the engine@@ -740,7 +740,7 @@ func (s *UpdaterService) ProjectByComposeName(ctx context.Context, composeName sreturn updater.ComposeProject{}, err}if project == nil {- return updater.ComposeProject{}, errors.Errorf("compose project not found: %s", composeName)+ return updater.ComposeProject{}, fmt.Errorf("compose project not found: %s", composeName)}return updater.ComposeProject{ID: project.ID, Name: project.Name}, nil}@@ -764,7 +764,7 @@ func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target updater.S}if s == nil || s.deps.SelfUpgrade == nil {instanceType := cmp.Or(strings.TrimSpace(target.InstanceType), "server")- return errors.Errorf("%s self-update requires CLI upgrade service", instanceType)+ return fmt.Errorf("%s self-update requires CLI upgrade service", instanceType)}// A server self-update stops this process before the run can complete its@@ -775,7 +775,7 @@ func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target updater.S}if _, err := s.deps.SelfUpgrade.TriggerUpgradeViaCLI(ctx, s.deps.SystemUser, target); err != nil {- return errors.WrapIf(err, "CLI upgrade failed")+ return fmt.Errorf("CLI upgrade failed: %w", err)}if progress, ok := ctx.Value(updateProgressKeyInternal{}).(*updateProgressInternal); ok {progress.mu.Lock()@@ -996,7 +996,7 @@ func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.item, err = s.deps.Activity.StartActivity(ctx, request)}if err != nil {- return nil, nil, errors.WrapIf(err, "start container update activity")+ return nil, nil, fmt.Errorf("start container update activity: %w", err)}return item, workCtx, nil}@@ -1341,7 +1341,7 @@ func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]stru}if successfulSources == 0 {- return nil, errors.Combine(errs...)+ return nil, errors.Join(errs...)}s.loggerInternal().DebugContext(ctx, "collectUsedImages: collected used images", "count", len(out))@@ -1524,3 +1524,21 @@ func (s *UpdaterService) tagFrozenPullInternal(ctx context.Context, pulledRef, i_, err = dockerClient.ImageTag(ctx, client.ImageTagOptions{Source: pulledRef, Target: imageRef})return err}++type updateAdmissionKeyInternal struct{}++var errUpdateBusyInternal = errors.New("another container update is running")++func (s *UpdaterService) acquireUpdateInternal(ctx context.Context) (context.Context, func(), error) {+ if s.admission == nil || ctx.Value(updateAdmissionKeyInternal{}) == s {+ return ctx, func() {}, nil+ }+ lease, admitted, err := s.admission.TryAcquire(ctx, schedulertypes.AdmissionKey{Scope: "updater"})+ if err != nil {+ return ctx, nil, err+ }+ if !admitted {+ return ctx, nil, errUpdateBusyInternal+ }+ return context.WithValue(ctx, updateAdmissionKeyInternal{}, s), func() { lease.Release(ctx) }, nil+}diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.goindex 17e22245c..6ea7f435d 100644--- a/backend/internal/updater/service_test.go+++ b/backend/internal/updater/service_test.go@@ -790,7 +790,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(tvar releaseOnce sync.Oncedefer releaseOnce.Do(func() { close(release) })require.NoError(t, runtime.RegisterActor(singleUpdateTypeInternal, func(_ string, _ *actor.Service) actor.Actor {- return &blockingSingleUpdateActorInternal{singleUpdateActorInternal: singleUpdateActorInternal{service: svc}, started: started, release: release}+ return &blockingSingleUpdateActorInternal{service: svc, started: started, release: release}}))francistest.Start(t, runtime)go func() {diff --git a/backend/internal/updater/tag_updates.go b/backend/internal/updater/tag_updates.goindex 219089618..cb62a59a3 100644--- a/backend/internal/updater/tag_updates.go+++ b/backend/internal/updater/tag_updates.go@@ -3,10 +3,11 @@ package updaterimport ("cmp""context"+ "errors"+ "fmt""strings""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"@@ -143,7 +144,7 @@ func (s *UpdaterService) CheckProjectUpdates(ctx context.Context, projectID stri}return tx.Create(&records).Error}); err != nil {- return nil, errors.WrapIf(err, "save project update checks")+ return nil, fmt.Errorf("save project update checks: %w", err)}return project.BuildConfiguredUpdateInfo(projectID, details.Services, nil, records), nil}diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.goindex 96de4a1fd..546329d43 100644--- a/backend/internal/user/handler.go+++ b/backend/internal/user/handler.go@@ -2,10 +2,10 @@ package userimport ("context"+ "errors""strings""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -150,7 +150,7 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*hausers, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list users").Error())+ return nil, huma.Error500InternalServerError("Failed to list users: " + err.Error())}return &handlerutil.Page[usertypes.User]{diff --git a/backend/internal/user/service.go b/backend/internal/user/service.goindex 1fb76f43f..bb7aef4f3 100644--- a/backend/internal/user/service.go+++ b/backend/internal/user/service.go@@ -5,13 +5,13 @@ import ("crypto/rand""crypto/subtle""encoding/base64"+ "errors""fmt""log/slog""maps""slices""strings"- "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/role"@@ -51,15 +51,15 @@ type UserService struct {argon2Params *Argon2Params}-const (- ErrCannotRemoveLastAdmin = errors.Sentinel("cannot remove the last admin user")- ErrUsernameRequired = errors.Sentinel("username is required")- ErrUsernameTaken = errors.Sentinel("username already in use")+var (+ ErrCannotRemoveLastAdmin = errors.New("cannot remove the last admin user")+ ErrUsernameRequired = errors.New("username is required")+ ErrUsernameTaken = errors.New("username already in use")// ErrInsufficientPrivilege is returned when a caller attempts to modify a// target whose effective privilege is equal to or higher than the caller's// (e.g. a delegated users:update holder trying to edit a global admin).- ErrInsufficientPrivilege = errors.Sentinel("insufficient privilege to modify this user")+ ErrInsufficientPrivilege = errors.New("insufficient privilege to modify this user"))func NewUserService(db *database.DB, roleService *role.RoleService) *UserService {@@ -149,7 +149,7 @@ func (s *UserService) CreateUser(ctx context.Context, user *common.User) (*commoif isDuplicateKeyErrorInternal(tx, err) {return ErrUsernameTaken}- return errors.WrapIf(err, "failed to create user")+ return fmt.Errorf("failed to create user: %w", err)}return nil})@@ -177,7 +177,7 @@ func (s *UserService) GetUserByOidcSubjectId(ctx context.Context, subjectId strifunc (s *UserService) GetUserByEmail(ctx context.Context, email string) (*common.User, error) {var users []common.Userif err := s.db.DB.WithContext(ctx).Where("email = ?", email).Limit(2).Find(&users).Error; err != nil {- return nil, errors.WrapIf(err, "failed to query users by email")+ return nil, fmt.Errorf("failed to query users by email: %w", err)}switch len(users) {case 0:@@ -226,12 +226,11 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gormuserIDs = append(userIDs, actorID)}var lockedUsers []common.User- if err := tx.- Clauses(clause.Locking{Strength: "UPDATE"}).+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id IN ?", userIDs).Order("id ASC").Find(&lockedUsers).Error; err != nil {- return errors.WrapIf(err, "failed to lock users")+ return fmt.Errorf("failed to lock users: %w", err)}targetFound := falseactorFound := actorID == ""@@ -252,7 +251,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gormif revalidateActor {currentActorPerms, err := s.roleService.ResolveUserPermissionsInDB(ctx, tx, actorID)if err != nil {- return errors.WrapIf(err, "failed to resolve actor permissions")+ return fmt.Errorf("failed to resolve actor permissions: %w", err)}if currentActorPerms != nil && currentActorPerms.IsGlobalAdmin() {return nil@@ -260,7 +259,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gorm}targetPerms, err := s.roleService.ResolveUserPermissionsInDB(ctx, tx, targetID)if err != nil {- return errors.WrapIf(err, "failed to resolve target permissions")+ return fmt.Errorf("failed to resolve target permissions: %w", err)}return kit.Ternary[error](targetPerms != nil && targetPerms.IsGlobalAdmin(), ErrInsufficientPrivilege, nil)}@@ -280,7 +279,7 @@ func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPeif isDuplicateKeyErrorInternal(tx, err) {return ErrUsernameTaken}- return errors.WrapIf(err, "failed to update user")+ return fmt.Errorf("failed to update user: %w", err)}return nil})@@ -315,7 +314,7 @@ func (s *UserService) SetPassword(ctx context.Context, user *common.User, passwohashedPassword, err := s.HashPassword(password)if err != nil {- return nil, errors.WrapIf(err, "failed to hash password")+ return nil, fmt.Errorf("failed to hash password: %w", err)}user.PasswordHash = hashedPassword@@ -337,25 +336,24 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, ushashedPassword, err := s.HashPassword(password)if err != nil {- return nil, errors.WrapIf(err, "failed to hash password")+ return nil, fmt.Errorf("failed to hash password: %w", err)}var updatedUser common.Usererr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.- Clauses(clause.Locking{Strength: "UPDATE"}).+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrUserNotFound}- return errors.WrapIf(err, "failed to load user for password reset")+ return fmt.Errorf("failed to load user for password reset: %w", err)}updatedUser.PasswordHash = hashedPasswordupdatedUser.RequiresPasswordChange = falseif err := tx.Save(&updatedUser).Error; err != nil {- return errors.WrapIf(err, "failed to update user password")+ return fmt.Errorf("failed to update user password: %w", err)}return session.RevokeAllUserSessionsExceptInDB(ctx, tx, updatedUser.ID, exceptSessionID)})@@ -378,14 +376,13 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userIDvar out *common.Usererr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var u common.User- if err := tx.- Clauses(clause.Locking{Strength: "UPDATE"}).+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&u).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrUserNotFound}- return errors.WrapIf(err, "failed to load user for OIDC merge")+ return fmt.Errorf("failed to load user for OIDC merge: %w", err)}// If already linked to a different subject, abort@@ -406,9 +403,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 errors.WrapIf(err, "oidc subject is already linked to another user")+ return fmt.Errorf("oidc subject is already linked to another user: %w", err)}- return errors.WrapIf(err, "failed to persist OIDC merge")+ return fmt.Errorf("failed to persist OIDC merge: %w", err)}out = &ureturn nil@@ -428,12 +425,12 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {if s.roleService != nil {var count int64if err := s.db.WithContext(ctx).Model(&common.User{}).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to count users")+ return fmt.Errorf("failed to count users: %w", err)}if count > 0 {admins, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, "")if err != nil {- return errors.WrapIf(err, "failed to count global admins")+ return fmt.Errorf("failed to count global admins: %w", err)}if admins > 0 {return nil@@ -448,13 +445,13 @@ 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(&common.User{}).Count(&count).Error; err != nil {- return errors.WrapIf(err, "failed to count users")+ return fmt.Errorf("failed to count users: %w", err)}if count == 0 {hashedPassword, err := s.HashPassword("arcane-admin")if err != nil {- return errors.WrapIf(err, "failed to hash default admin password")+ return fmt.Errorf("failed to hash default admin password: %w", err)}email := "admin@localhost"displayName := "Arcane Admin"@@ -466,7 +463,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {RequiresPasswordChange: true,}if err := tx.Create(userModel).Error; err != nil {- return errors.WrapIf(err, "failed to create default admin user")+ return fmt.Errorf("failed to create default admin user: %w", err)}adminUserID = userModel.IDslog.InfoContext(ctx, "👑 Default admin user created!")@@ -485,7 +482,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {if errors.Is(err, gorm.ErrRecordNotFound) {return nil}- return errors.WrapIf(err, "failed to look up default admin user")+ return fmt.Errorf("failed to look up default admin user: %w", err)}adminUserID = existing.IDreturn nil@@ -508,7 +505,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUserID string) error {assignments, err := s.roleService.ListUserAssignments(ctx, adminUserID)if err != nil {- return errors.WrapIf(err, "failed to list default admin assignments")+ return fmt.Errorf("failed to list default admin assignments: %w", err)}for _, a := range assignments {if a.RoleID == authz.BuiltInRoleAdmin && a.EnvironmentID == nil {@@ -526,7 +523,7 @@ func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUsEnvironmentID: nil,})if err := s.roleService.SetUserAssignments(ctx, adminUserID, manual); err != nil {- return errors.WrapIf(err, "failed to grant default admin global role")+ return fmt.Errorf("failed to grant default admin global role: %w", err)}slog.InfoContext(ctx, "Default admin granted global Admin role assignment", "user_id", adminUserID)return nil@@ -559,9 +556,8 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *autif err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, id); err != nil {return err}-if err := tx.Delete(&common.User{}, "id = ?", id).Error; err != nil {- return errors.WrapIf(err, "failed to delete user")+ return fmt.Errorf("failed to delete user: %w", err)}return nil})@@ -583,7 +579,7 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.paginationResp, err := pagination.PaginateAndSortDB(params, query, &users)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate users")+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate users: %w", err)}result := s.toUserResponseDtosInternal(ctx, users)@@ -596,7 +592,7 @@ func (s *UserService) ToUserResponseDto(ctx context.Context, u common.User) (useif dto.IsGlobalAdmin && s.roleService != nil {remaining, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, u.ID)if err != nil {- return user.User{}, errors.WrapIf(err, "failed to check whether user can be deleted")+ return user.User{}, fmt.Errorf("failed to check whether user can be deleted: %w", err)}dto.CanDelete = remaining > 0}@@ -703,8 +699,7 @@ func (s *UserService) GetUser(ctx context.Context, userID string) (*common.User,func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *gorm.DB) (*common.User, error) {var userRecord common.User- err := tx.- WithContext(ctx).+ err := tx.WithContext(ctx).Where("id = ?", userID).First(&userRecord).Error@@ -720,7 +715,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []byMimeType: mimeType,}if err := tx.Save(&avatar).Error; err != nil {- return errors.WrapIf(err, "failed to save avatar data")+ return fmt.Errorf("failed to save avatar data: %w", err)}err := tx.Model(&common.User{}).@@ -729,7 +724,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []by"has_avatar": true,}).Errorif err != nil {- return errors.WrapIf(err, "failed to update user avatar flag")+ return fmt.Errorf("failed to update user avatar flag: %w", err)}return nil})@@ -739,7 +734,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(&UserAvatar{}).Error; err != nil {- return errors.WrapIf(err, "failed to delete avatar data")+ return fmt.Errorf("failed to delete avatar data: %w", err)}err := tx.Model(&common.User{}).@@ -748,7 +743,7 @@ func (s *UserService) DeleteAvatar(ctx context.Context, userID string) error {"has_avatar": false,}).Errorif err != nil {- return errors.WrapIf(err, "failed to update user avatar flag")+ return fmt.Errorf("failed to update user avatar flag: %w", err)}return nil})diff --git a/backend/internal/variable/handler.go b/backend/internal/variable/handler.goindex c8543a464..b47adb583 100644--- a/backend/internal/variable/handler.go+++ b/backend/internal/variable/handler.go@@ -2,9 +2,9 @@ package variableimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -249,7 +249,7 @@ func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *Gvars, err := h.variableService.ReadLocalEnvFile(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve global variables").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve global variables: " + err.Error())}return &handlerutil.Out[[]env.Variable]{@@ -275,7 +275,7 @@ func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, inputif errors.Is(err, common.ErrInvalidEnvKey) {return nil, huma.Error400BadRequest(err.Error())}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update global variables").Error())+ return nil, huma.Error500InternalServerError("Failed to update global variables: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -290,7 +290,9 @@ func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, inputfunc variableMutationHTTPErrorInternal(err error) error {switch {- case errors.Is(err, common.ErrInvalidEnvKey), errors.Is(err, common.ErrGlobalVariableSecretValueRequired), errors.Is(err, common.ErrGlobalVariableScopeRequired):+ case errors.Is(err, common.ErrInvalidEnvKey),+ errors.Is(err, common.ErrGlobalVariableSecretValueRequired),+ errors.Is(err, common.ErrGlobalVariableScopeRequired):return huma.Error400BadRequest(err.Error())case errors.Is(err, common.ErrGlobalVariableNotFound):return huma.Error404NotFound(err.Error())diff --git a/backend/internal/variable/service_test.go b/backend/internal/variable/service_test.goindex 1937e140d..1ad6557f9 100644--- a/backend/internal/variable/service_test.go+++ b/backend/internal/variable/service_test.go@@ -3,6 +3,7 @@ package variableimport ("context""encoding/json"+ "errors""fmt""io""net/http"@@ -14,7 +15,6 @@ 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/environment"diff --git a/backend/internal/variable/variable.go b/backend/internal/variable/variable.goindex b041cc39c..c03abfc74 100644--- a/backend/internal/variable/variable.go+++ b/backend/internal/variable/variable.go@@ -5,6 +5,7 @@ import ("bytes""context""encoding/json/v2"+ "errors""fmt""io/fs""log/slog"@@ -18,7 +19,6 @@ 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/environment"@@ -84,7 +84,7 @@ func NewVariableService(db *database.DB, environmentService *environment.Environfunc (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariable, error) {variables, err := s.loadVariablesInternal(ctx)if err != nil {- return nil, errors.WrapIf(err, "Failed to retrieve global variables")+ return nil, fmt.Errorf("Failed to retrieve global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}result := make([]env.GlobalVariable, 0, len(variables))@@ -97,7 +97,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.Classify(common.ErrInvalidEnvKey, errors.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))+ return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.}envIDs, err := s.normalizeScopeInternal(ctx, req.AllEnvironments, req.EnvironmentIDs)@@ -109,7 +109,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, errors.WrapIf(err, "Failed to update global variables")+ return nil, fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}}@@ -125,7 +125,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobreturn err}if err := tx.Omit("Environments").Create(&variable).Error; err != nil {- return errors.WrapIf(err, "failed to create global variable")+ return fmt.Errorf("failed to create global variable: %w", err)}return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)})@@ -142,16 +142,16 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req envvar variable GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").First(&variable, "id = ?", id).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found"))+ return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found")) //nolint:staticcheck // Preserve the existing error message.}- return nil, errors.WrapIf(err, "Failed to retrieve global variables")+ return nil, fmt.Errorf("Failed to retrieve global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}key := variable.Keyif req.Key != nil {key = strings.TrimSpace(*req.Key)if !envKeyPattern.MatchString(key) {- return nil, common.Classify(common.ErrInvalidEnvKey, errors.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))+ return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.}}@@ -180,7 +180,7 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req envreturn err}if err := tx.Omit("Environments").Save(&variable).Error; err != nil {- return errors.WrapIf(err, "failed to update global variable")+ return fmt.Errorf("failed to update global variable: %w", err)}return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)})@@ -198,7 +198,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 *GlobalVariable, reqValue *string, isSecret bool) (string, error) {if variable.IsSecret && !isSecret && reqValue == nil {- return "", common.Classify(common.ErrGlobalVariableSecretValueRequired, errors.New("A new value is required when making a secret variable readable"))+ return "", common.Classify(common.ErrGlobalVariableSecretValueRequired, errors.New("A new value is required when making a secret variable readable")) //nolint:staticcheck // Preserve the existing error message.}switch {@@ -208,14 +208,14 @@ func resolveUpdatedValueInternal(variable *GlobalVariable, reqValue *string, isS}encrypted, err := crypto.Encrypt(*reqValue)if err != nil {- return "", errors.WrapIf(err, "Failed to update global variables")+ return "", fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}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 "", errors.WrapIf(err, "Failed to update global variables")+ return "", fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}return encrypted, nildefault:@@ -251,10 +251,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(&GlobalVariable{}, "id = ?", id)if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete global variable")+ return fmt.Errorf("failed to delete global variable: %w", result.Error)}if result.RowsAffected == 0 {- return common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found"))+ return common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found")) //nolint:staticcheck // Preserve the existing error message.}return tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", id).Error})@@ -326,7 +326,7 @@ func (s *VariableService) ForgetSyncState(envID string) {func (s *VariableService) syncEnvironmentInternal(ctx context.Context, envID string) error {if envID != environment.LocalEnvironmentID {if err := s.importRemoteLegacyVarsOnceInternal(ctx, envID); err != nil {- return errors.WrapIff(err, "failed to import existing variables from environment %s", envID)+ return fmt.Errorf("failed to import existing variables from environment %s: %w", envID, err)}}@@ -341,11 +341,11 @@ func (s *VariableService) syncEnvironmentInternal(ctx context.Context, envID strbody, err := json.Marshal(env.Summary{Variables: vars})if err != nil {- return errors.WrapIf(err, "failed to marshal variables for sync")+ return fmt.Errorf("failed to marshal variables for sync: %w", err)}unchanged, finishDelivery, err := s.syncGate.Begin(ctx, envID, agentVariablesPath, body)if err != nil {- return errors.WrapIf(err, "variable sync cancelled while waiting for an in-flight delivery")+ return fmt.Errorf("variable sync cancelled while waiting for an in-flight delivery: %w", err)}if unchanged {return nil@@ -473,7 +473,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 "", errors.WrapIf(err, "failed to get projects directory")+ return "", fmt.Errorf("failed to get projects directory: %w", err)}return filepath.Join(projectsDirectory, projects.GlobalEnvFileName), nil@@ -491,7 +491,7 @@ func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable,slog.DebugContext(ctx, "Global variables file does not exist yet", "path", envPath)return []env.Variable{}, nil}- return nil, errors.WrapIf(err, "failed to open global variables file")+ return nil, fmt.Errorf("failed to open global variables file: %w", err)}vars := []env.Variable{}@@ -531,7 +531,7 @@ func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable,}if err := scanner.Err(); err != nil {- return nil, errors.WrapIf(err, "error reading global variables file")+ return nil, fmt.Errorf("error reading global variables file: %w", err)}return vars, nil@@ -547,7 +547,7 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Vari// through os before acfs opens it.projectsDirectory := filepath.Dir(envPath)if err := os.MkdirAll(projectsDirectory, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create projects directory")+ return fmt.Errorf("failed to create projects directory: %w", err)}var builder strings.Builder@@ -561,13 +561,10 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Varikey := strings.TrimSpace(v.Key)if !envKeyPattern.MatchString(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))+ return common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.}+ // Preserve intentional whitespace inside the quoted value.value := v.Valueif strings.ContainsAny(value, " \t\n\r#") {@@ -582,7 +579,7 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Varimode = os.FileMode(entry.UnixMode).Perm()}if err := acfs.Write(ctx, projectsDirectory, "/"+projects.GlobalEnvFileName, []byte(builder.String()), acfs.WriteOptions{Mode: mode, InPlace: true}); err != nil {- return errors.WrapIf(err, "failed to write global variables file")+ return fmt.Errorf("failed to write global variables file: %w", err)}slog.InfoContext(ctx, "Updated global variables",@@ -690,7 +687,7 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []enreturn replaceVariableScopeRowsInternal(tx, variable.ID, []string{scopeEnvID})})if err != nil {- return errors.WrapIff(err, "failed to import legacy variable %q", key)+ return fmt.Errorf("failed to import legacy variable %q: %w", key, err)}covered[key] = trueslog.InfoContext(ctx, "Imported legacy global variable", "key", key, "environment_id", scopeEnvID)@@ -706,7 +703,7 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []enfunc (s *VariableService) loadVariablesInternal(ctx context.Context) ([]GlobalVariable, error) {var variables []GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").Order("key").Find(&variables).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load global variables")+ return nil, fmt.Errorf("failed to load global variables: %w", err)}return variables, nil}@@ -728,15 +725,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.Classify(common.ErrGlobalVariableScopeRequired, errors.New("At least one environment is required when a variable is not scoped to all environments"))+ return nil, common.Classify(common.ErrGlobalVariableScopeRequired, errors.New("At least one environment is required when a variable is not scoped to all environments")) //nolint:staticcheck // Preserve the existing error message.}var count int64if err := s.db.WithContext(ctx).Model(&environment.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {- return nil, errors.WrapIf(err, "Failed to update global variables")+ return nil, fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}if count != int64(len(unique)) {- return nil, errors.New("Failed to update global variables: one or more environments do not exist")+ return nil, errors.New("Failed to update global variables: one or more environments do not exist") //nolint:staticcheck // Preserve the existing error message.}return unique, nil}@@ -751,7 +748,7 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key, excludquery = query.Where("id <> ?", excludeID)}if err := query.Find(&others).Error; err != nil {- return errors.WrapIf(err, "failed to check for conflicting variables")+ return fmt.Errorf("failed to check for conflicting variables: %w", err)}for _, other := range others {@@ -759,12 +756,12 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key, excludcontinue}if allEnvironments {- return common.Classify(common.ErrGlobalVariableConflict, errors.Errorf("A variable named %q already exists for an overlapping environment scope", key))+ return common.Classify(common.ErrGlobalVariableConflict, fmt.Errorf("A variable named %q already exists for an overlapping environment scope", key)) //nolint:staticcheck // Preserve the existing error message.}otherIDs := scopedEnvironmentIDsInternal(other.Environments)for _, id := range envIDs {if slices.Contains(otherIDs, id) {- return common.Classify(common.ErrGlobalVariableConflict, errors.Errorf("A variable named %q already exists for an overlapping environment scope", key))+ return common.Classify(common.ErrGlobalVariableConflict, fmt.Errorf("A variable named %q already exists for an overlapping environment scope", key)) //nolint:staticcheck // Preserve the existing error message.}}}@@ -775,24 +772,21 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key, exclud// 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 errors.WrapIf(err, "failed to clear variable scope")+ return fmt.Errorf("failed to clear variable scope: %w", err)}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 errors.WrapIf(err, "failed to set variable scope")+ return fmt.Errorf("failed to set variable scope: %w", err)}}return nil}func wrapVariableMutationErrorInternal(err error) error {- if err == nil ||- errors.Is(err, common.ErrGlobalVariableConflict) ||- errors.Is(err, common.ErrGlobalVariableNotFound) ||- errors.Is(err, common.ErrInvalidEnvKey) {+ if err == nil || errors.Is(err, common.ErrGlobalVariableConflict) || errors.Is(err, common.ErrGlobalVariableNotFound) || errors.Is(err, common.ErrInvalidEnvKey) {return err}- return errors.WrapIf(err, "Failed to update global variables")+ return fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.}func scopedEnvironmentIDsInternal(environments []environment.Environment) []string {diff --git a/backend/internal/version/service.go b/backend/internal/version/service.goindex f643fae3e..8dbfc8ef6 100644--- a/backend/internal/version/service.go+++ b/backend/internal/version/service.go@@ -3,13 +3,13 @@ package versionimport ("context""encoding/json/v2"+ "errors""fmt""log/slog""net/http""strings""time"- "emperror.dev/errors"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/buildables""github.com/getarcaneapp/arcane/backend/v2/internal/apns"@@ -32,9 +32,10 @@ import ()const (- versionTTL = 3 * time.Hour- versionCheckURL = "https://api.github.com/repos/getarcaneapp/arcane/releases/latest"- defaultRequestTimeout = 15 * time.Second+ versionStreamPollInterval = 5 * time.Minute+ versionTTL = 3 * time.Hour+ versionCheckURL = "https://api.github.com/repos/getarcaneapp/arcane/releases/latest"+ defaultRequestTimeout = 15 * time.Second)type latestRelease struct {@@ -103,17 +104,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{}, errors.WrapIf(err, "create GitHub request")+ return latestRelease{}, fmt.Errorf("create GitHub request: %w", err)}resp, err := s.httpClient.Do(req)if err != nil {- return latestRelease{}, errors.WrapIf(err, "get latest release")+ return latestRelease{}, fmt.Errorf("get latest release: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return latestRelease{}, errors.Errorf("GitHub API returned status %d", resp.StatusCode)+ return latestRelease{}, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)}var payload struct {@@ -122,7 +123,7 @@ func (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latestPublishedAt string `json:"published_at"`}if err := json.UnmarshalRead(resp.Body, &payload); err != nil {- return latestRelease{}, errors.WrapIf(err, "decode payload")+ return latestRelease{}, fmt.Errorf("decode payload: %w", err)}if payload.TagName == "" {return latestRelease{}, errors.New("GitHub API returned empty tag name")@@ -525,3 +526,48 @@ func (s *VersionService) checkDigestBasedUpdate(ctx context.Context, currentTag,return updateAvailable, latestDigest}++// RunStreamProducer shares one version poll loop across every connected client and emits a snapshot whenever it changes.+func (s *VersionService) RunStreamProducer(ctx context.Context, events chan<- version.StreamEvent) {+ s.streamHub.Subscribe(ctx, "local",+ func(runCtx context.Context, publish func(version.StreamEvent)) {+ var last *version.Info+ poll := func() {+ info := s.GetAppVersionInfo(runCtx)+ if runCtx.Err() != nil {+ return+ }+ if last != nil {+ if last.UpdateAvailable == info.UpdateAvailable &&+ last.NewestVersion == info.NewestVersion &&+ last.NewestDigest == info.NewestDigest &&+ last.CurrentTag == info.CurrentTag &&+ last.CurrentDigest == info.CurrentDigest &&+ last.ReleaseURL == info.ReleaseURL &&+ last.ReleaseNotes == info.ReleaseNotes &&+ last.ReleasedAt == info.ReleasedAt {+ return+ }+ }+ last = info+ publish(version.StreamEvent{Type: "snapshot", Info: info, Timestamp: time.Now()})+ }++ poll()++ ticker := time.NewTicker(versionStreamPollInterval)+ defer ticker.Stop()++ for {+ select {+ case <-runCtx.Done():+ return+ case <-ticker.C:+ poll()+ }+ }+ },+ func(event version.StreamEvent) bool {+ return agg.Send(ctx, events, event)+ })+}diff --git a/backend/internal/version/stream.go b/backend/internal/version/stream.godeleted file mode 100644index 9e281a3f2..000000000--- a/backend/internal/version/stream.go+++ /dev/null@@ -1,56 +0,0 @@-package version--import (- "context"- "time"-- "github.com/getarcaneapp/arcane/types/v2/version"- "go.getarcane.app/streams/agg"-)--const versionStreamPollInterval = 5 * time.Minute--// RunStreamProducer shares one version poll loop across every connected client and emits a snapshot whenever it changes.-func (s *VersionService) RunStreamProducer(ctx context.Context, events chan<- version.StreamEvent) {- s.streamHub.Subscribe(ctx, "local",- func(runCtx context.Context, publish func(version.StreamEvent)) {- var last *version.Info- poll := func() {- info := s.GetAppVersionInfo(runCtx)- if runCtx.Err() != nil {- return- }- if last != nil {- if last.UpdateAvailable == info.UpdateAvailable &&- last.NewestVersion == info.NewestVersion &&- last.NewestDigest == info.NewestDigest &&- last.CurrentTag == info.CurrentTag &&- last.CurrentDigest == info.CurrentDigest &&- last.ReleaseURL == info.ReleaseURL &&- last.ReleaseNotes == info.ReleaseNotes &&- last.ReleasedAt == info.ReleasedAt {- return- }- }- last = info- publish(version.StreamEvent{Type: "snapshot", Info: info, Timestamp: time.Now()})- }-- poll()-- ticker := time.NewTicker(versionStreamPollInterval)- defer ticker.Stop()-- for {- select {- case <-runCtx.Done():- return- case <-ticker.C:- poll()- }- }- },- func(event version.StreamEvent) bool {- return agg.Send(ctx, events, event)- })-}diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.goindex cab55f998..5fdc2d37e 100644--- a/backend/internal/volume/backup.go+++ b/backend/internal/volume/backup.go@@ -6,6 +6,7 @@ import ("compress/gzip""context""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -15,7 +16,6 @@ import ("time""uuid"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -193,7 +193,7 @@ func (s *VolumeService) ensureBackupVolumeInternal(ctx context.Context) error {Name: s.backupVolumeName,})if err != nil {- return errors.WrapIf(err, "failed to create backup volume")+ return fmt.Errorf("failed to create backup volume: %w", err)}}return nil@@ -241,7 +241,7 @@ func (s *VolumeService) stopRunningContainersForBackupInternal(ctx context.Contecandidate := containersByID[containerID]if err := s.containerService.StopContainer(ctx, containerID, user); err != nil {stillStopped, restartErr := s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)- return stillStopped, errors.Combine(fmt.Errorf("failed to stop container %s before volume backup: %w", containerID, err), restartErr)+ return stillStopped, errors.Join(fmt.Errorf("failed to stop container %s before volume backup: %w", containerID, err), restartErr)}stopped = append(stopped, candidate)}@@ -313,9 +313,9 @@ func (s *VolumeService) startContainersAfterBackupInternal(ctx context.Context,var restartErr errorfor _, stopped := range remaining {if lastErr := lastErrors[stopped.ID]; lastErr != nil {- restartErr = errors.Combine(restartErr, fmt.Errorf("failed to restart container %s after volume backup: %w", stopped.ID, lastErr))+ restartErr = errors.Join(restartErr, fmt.Errorf("failed to restart container %s after volume backup: %w", stopped.ID, lastErr))} else {- restartErr = errors.Combine(restartErr, fmt.Errorf("failed to restart container %s after volume backup: replacement did not appear within %s", stopped.ID, volumeBackupContainerRecoveryTimeout))+ restartErr = errors.Join(restartErr, fmt.Errorf("failed to restart container %s after volume backup: replacement did not appear within %s", stopped.ID, volumeBackupContainerRecoveryTimeout))}}return remaining, restartErr@@ -443,13 +443,13 @@ func (s *VolumeService) sanitizeBackupPathInternal(input string) (string, error)}cleaned := path.Clean(trimmed)if cleaned == "." || cleaned == "/" {- return "", errors.Errorf("invalid path: %s", input)+ return "", fmt.Errorf("invalid path: %s", input)}if path.IsAbs(cleaned) {cleaned = strings.TrimPrefix(cleaned, "/")}if cleaned == "" || cleaned == "." || cleaned == "/" || strings.HasPrefix(cleaned, "..") || strings.Contains(cleaned, "/../") {- return "", errors.Errorf("invalid path: %s", input)+ return "", fmt.Errorf("invalid path: %s", input)}return cleaned, nil}@@ -457,7 +457,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 "", errors.WrapIf(err, "invalid backup id")+ return "", fmt.Errorf("invalid backup id: %w", err)}if strings.Contains(cleaned, "/") {return "", errors.New("invalid backup id: path separators not allowed")@@ -727,7 +727,7 @@ func (s *VolumeService) completeBackupInternal(ctx context.Context, entry *Volumentry.Status, entry.Error = VolumeBackupStatusSucceeded, ""}if saveErr := s.db.WithContext(context.WithoutCancel(ctx)).Save(entry).Error; saveErr != nil {- return errors.Combine(err, fmt.Errorf("failed to save volume backup result: %w", saveErr))+ return errors.Join(err, fmt.Errorf("failed to save volume backup result: %w", saveErr))}if err == nil {err = jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "volume_backup", ID: entry.VolumeName, Status: schedulertypes.Succeeded})@@ -757,7 +757,7 @@ func (s *VolumeService) executeBackupInternal(ctx context.Context, entry *Volumedefer func() {if containersStopped {_, restartErr := s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)- err = errors.Combine(err, restartErr)+ err = errors.Join(err, restartErr)}}()if err != nil {@@ -930,7 +930,8 @@ func (s *VolumeService) UploadBackup(ctx context.Context, backupID, s3Destinatioif err := s.db.WithContext(ctx).Save(&entry).Error; err != nil {return nil, fmt.Errorf("failed to save uploaded volume backup: %w", err)}- return &entry, nil+ return &entry,+ nil}func (s *VolumeService) DeleteBackup(ctx context.Context, backupID string, user *common.User) error {@@ -982,12 +983,12 @@ func (s *VolumeService) deleteRusticBackupsInternal(ctx context.Context, entries}deleteErr := s.forgetLocalSnapshotsInternal(ctx, dockerClient, localEntries)for key, group := range remoteGroups {- deleteErr = errors.Combine(deleteErr, s.forgetRemoteSnapshotsInternal(ctx, dockerClient, key.destinationID, key.instanceID, group))+ deleteErr = errors.Join(deleteErr, s.forgetRemoteSnapshotsInternal(ctx, dockerClient, key.destinationID, key.instanceID, group))}for _, entry := range entries {if entry.LocalSnapshotID == "" && entry.RemoteSnapshotID == "" {if err := s.db.WithContext(ctx).Delete(entry).Error; err != nil {- deleteErr = errors.Combine(deleteErr, fmt.Errorf("failed to delete volume backup record: %w", err))+ deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete volume backup record: %w", err))continue}s.logBackupDeleteEventInternal(ctx, entry.VolumeName, entry.ID, user)@@ -1002,7 +1003,7 @@ func (s *VolumeService) deleteRusticBackupsInternal(ctx context.Context, entriesentry.Destination = volumetypes.BackupDestinationS3}if saveErr := s.db.WithContext(ctx).Save(entry).Error; saveErr != nil {- deleteErr = errors.Combine(deleteErr, saveErr)+ deleteErr = errors.Join(deleteErr, saveErr)}}return deleteErr@@ -1101,7 +1102,7 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupIDdefer func() {if containersStopped {_, restartErr := s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)- err = errors.Combine(err, restartErr)+ err = errors.Join(err, restartErr)}}()if err != nil {@@ -1339,7 +1340,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backdefer func() {if containersStopped {_, restartErr := s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)- err = errors.Combine(err, restartErr)+ err = errors.Join(err, restartErr)}}()if err != nil {@@ -1498,12 +1499,12 @@ func (s *VolumeService) createBackupTempContainerWithMountInternal(ctx context.CHostConfig: hostConfig,})if err != nil {- return "", nil, errors.WrapIf(err, "failed to create backup temp container")+ return "", nil, fmt.Errorf("failed to create backup temp container: %w", err)}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return "", nil, errors.WrapIf(err, "failed to start backup temp container")+ return "", nil, fmt.Errorf("failed to start backup temp container: %w", err)}cleanup := func() {@@ -1602,13 +1603,13 @@ func (s *VolumeService) restoreArchiveBackupInternal(ctx context.Context, dockerHostConfig: hostConfig,})if err != nil {- return errors.WrapIf(err, "failed to create restore container")+ return fmt.Errorf("failed to create restore container: %w", err)}defer func() {_, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())}()if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {- return errors.WrapIf(err, "failed to start restore container")+ return fmt.Errorf("failed to start restore container: %w", err)}waitResult := dockerClient.ContainerWait(ctx, resp.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})var waitBody container.WaitResponse@@ -1620,7 +1621,7 @@ func (s *VolumeService) restoreArchiveBackupInternal(ctx context.Context, dockercase waitBody = <-waitResult.Result:}if waitBody.StatusCode != 0 {- return errors.Errorf("restore container exited with code %d (volume may be partially wiped)", waitBody.StatusCode)+ return fmt.Errorf("restore container exited with code %d (volume may be partially wiped)", waitBody.StatusCode)}return nil}@@ -1678,7 +1679,10 @@ func (s *VolumeService) restoreBackupFilesInContainerInternal(ctx context.Contexargs = append(args, "./"+cleaned)}_, stderr, err := s.execInContainerInternal(ctx, containerID, "", args)- return stderr, errors.WrapIf(err, "failed to restore files")+ if err != nil {+ return stderr, fmt.Errorf("failed to restore files: %w", err)+ }+ return stderr, nil}func (s *VolumeService) restoreArchiveBackupFilesInternal(ctx context.Context, dockerClient *client.Client, volumeName, backupID string, cleanedPaths []string) error {@@ -1708,17 +1712,17 @@ func (s *VolumeService) restoreArchiveBackupFilesInternal(ctx context.Context, dHostConfig: hostConfig,})if err != nil {- return errors.WrapIf(err, "failed to create restore container")+ return fmt.Errorf("failed to create restore container: %w", err)}defer func() {_, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())}()if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {- return errors.WrapIf(err, "failed to start restore container")+ return fmt.Errorf("failed to start restore container: %w", err)}stderr, err := s.restoreBackupFilesInContainerInternal(ctx, resp.ID, filename, cleanedPaths)if err != nil {- return errors.WrapIf(err, "failed to restore files")+ return fmt.Errorf("failed to restore files: %w", err)}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore files stderr", "backup_id", backupID, "stderr", strings.TrimSpace(stderr))@@ -1731,11 +1735,11 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,gzr, err := gzip.NewReader(archive)if err != nil {- return errors.WrapIf(err, "invalid archive")+ return fmt.Errorf("invalid archive: %w", err)}if _, err := tar.NewReader(gzr).Next(); err != nil {_ = gzr.Close()- return errors.WrapIf(err, "invalid archive")+ return fmt.Errorf("invalid archive: %w", err)}_ = gzr.Close()@@ -1747,7 +1751,7 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,})preBackup, err := s.CreateBackup(ctx, volumeName, user, VolumeBackupTriggerSafety, volumetypes.CreateBackupRequest{Destination: volumetypes.BackupDestinationLocal})if err != nil {- return errors.WrapIf(err, "failed to create pre-restore backup")+ return fmt.Errorf("failed to create pre-restore backup: %w", err)}dockerClient, err := s.dockerService.GetClient(ctx)@@ -1764,26 +1768,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 errors.WrapIf(err, "failed to create temp restore dir")+ return fmt.Errorf("failed to create temp restore dir: %w", err)}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore temp dir stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))}if _, err := archive.Seek(0, io.SeekStart); err != nil {- return errors.WrapIf(err, "failed to read uploaded archive")+ return fmt.Errorf("failed to read uploaded archive: %w", err)}_, err = dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{DestinationPath: tmpDir,Content: archive,})if err != nil {- return errors.WrapIf(err, "failed to restore from uploaded archive")+ return fmt.Errorf("failed to restore from uploaded archive: %w", err)}_, 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 errors.WrapIf(err, "uploaded archive appears empty or invalid")+ return fmt.Errorf("uploaded archive appears empty or invalid: %w", err)}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore validate stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1791,7 +1795,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 errors.WrapIf(err, "failed to clear volume before restore")+ return fmt.Errorf("failed to clear volume before restore: %w", err)}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore clear stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1800,7 +1804,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 errors.WrapIf(err, "failed to move restored files into place")+ return fmt.Errorf("failed to move restored files into place: %w", err)}if strings.TrimSpace(stderr) != "" {slog.DebugContext(ctx, "volume service: restore move stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))@@ -1823,7 +1827,8 @@ func (s *VolumeService) loadVolumeBackupPoliciesInternal(ctx context.Context, voif err := s.db.WithContext(ctx).Where("volume_name = ?", volumeName).Order("created_at ASC").Find(&policies).Error; err != nil {return nil, fmt.Errorf("failed to load volume backup policies: %w", err)}- return policies, nil+ return policies,+ nil}func (s *VolumeService) loadVolumeBackupPolicyInternal(ctx context.Context, volumeName, policyID string) (*VolumeBackupPolicy, error) {diff --git a/backend/internal/volume/backup_run.go b/backend/internal/volume/backup_run.goindex 725905c03..f08f5f6bf 100644--- a/backend/internal/volume/backup_run.go+++ b/backend/internal/volume/backup_run.go@@ -3,8 +3,8 @@ package volumeimport ("context""encoding/json/v2"+ "errors"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -204,7 +204,7 @@ func (s *VolumeService) executeDurableBackupInternal(ctx context.Context, runIDif ctx.Err() == nil {if err != nil {saveErr := s.db.WithContext(ctx).Model(&VolumeBackup{}).Where("id = ?", command.Checkpoint.BackupID).Updates(map[string]any{"status": VolumeBackupStatusFailed, "error": err.Error()}).Error- err = errors.Combine(err, saveErr)+ err = errors.Join(err, saveErr)}activitylib.CompleteHandlerActivity(ctx, s.activityService, command.ActivityID, "Volume backup created successfully", err)}diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.goindex 729795a19..6e7b63a89 100644--- a/backend/internal/volume/handler.go+++ b/backend/internal/volume/handler.go@@ -3,6 +3,7 @@ package volumeimport ("cmp""context"+ "errors""fmt""io""log/slog"@@ -11,7 +12,6 @@ import ("strconv""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -600,7 +600,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(errors.WithMessage(err, "Failed to list volumes").Error())+ return nil, huma.Error500InternalServerError("Failed to list volumes: " + err.Error())}if volumes == nil {@@ -625,7 +625,7 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInputfunc (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*handlerutil.Out[*volumetypes.Volume], error) {vol, err := h.volumeService.GetVolumeByName(ctx, input.VolumeName)if err != nil {- return nil, huma.Error404NotFound(errors.WithMessage(err, "Volume not found").Error())+ return nil, huma.Error404NotFound("Volume not found: " + err.Error())}return &handlerutil.Out[*volumetypes.Volume]{@@ -672,7 +672,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInpreturn createErr})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create volume").Error())+ return nil, huma.Error500InternalServerError("Failed to create volume: " + err.Error())}response.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -739,7 +739,7 @@ func (h *VolumeHandler) RenameVolume(ctx context.Context, input *RenameVolumeInpcase errors.Is(err, common.ErrNotFound):return nil, huma.Error404NotFound(err.Error())default:- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to rename volume").Error())+ return nil, huma.Error500InternalServerError("Failed to rename volume: " + err.Error())}}response.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()@@ -773,7 +773,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(errors.WithMessage(err, "Failed to delete volume").Error())+ return nil, huma.Error500InternalServerError("Failed to delete volume: " + err.Error())}return &handlerutil.Out[base.MessageResponse]{@@ -805,7 +805,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInpreturn pruneErr})if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune volumes").Error())+ return nil, huma.Error500InternalServerError("Failed to prune volumes: " + err.Error())}return &handlerutil.Out[VolumePruneReportData]{@@ -824,7 +824,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInpfunc (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*handlerutil.Out[VolumeUsageResponse], error) {inUse, containers, err := h.volumeService.GetVolumeUsage(ctx, input.VolumeName)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume usage").Error())+ return nil, huma.Error500InternalServerError("Failed to get volume usage: " + err.Error())}return &handlerutil.Out[VolumeUsageResponse]{@@ -842,7 +842,7 @@ func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsagfunc (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*handlerutil.Out[VolumeUsageCountsData], error) {_, _, counts, err := h.volumeService.ListVolumesPaginated(ctx, pagination.QueryParams{}, input.IncludeInternal)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume counts").Error())+ return nil, huma.Error500InternalServerError("Failed to get volume counts: " + err.Error())}return &handlerutil.Out[VolumeUsageCountsData]{@@ -1159,7 +1159,7 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndReif httpErr := upload.SessionHTTPError(err); httpErr != nil {return nil, httpErr}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to open upload").Error())+ return nil, huma.Error500InternalServerError("Failed to open upload: " + err.Error())}defer cleanup()diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.goindex 0c5ecd489..c14d1012e 100644--- a/backend/internal/volume/helper_container.go+++ b/backend/internal/volume/helper_container.go@@ -5,12 +5,13 @@ import ("cmp""context""encoding/json/v2"+ "errors"+ "fmt""io""log/slog""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -46,14 +47,14 @@ func (s *VolumeService) requireVolumeHelperACFSInternal(ctx context.Context, volstdout, stderr, err := s.execInContainerInternal(ctx, containerID, "", []string{"acfs", "version"})if err != nil {- return errors.WrapIf(err, "volume workspace requires an ACFS-capable tools image: "+strings.TrimSpace(stderr))+ return fmt.Errorf("%s: %w", "volume workspace requires an ACFS-capable tools image: "+strings.TrimSpace(stderr), err)}var response acfstypes.VersionResponseif err := json.Unmarshal([]byte(stdout), &response); err != nil {- return errors.WrapIf(err, "parse ACFS tools-image capability")+ return fmt.Errorf("parse ACFS tools-image capability: %w", err)}if response.Protocol < acfstypes.ProtocolVersion {- return errors.Errorf("volume workspace requires ACFS protocol %d, tools image provides protocol %d", acfstypes.ProtocolVersion, response.Protocol)+ return fmt.Errorf("volume workspace requires ACFS protocol %d, tools image provides protocol %d", acfstypes.ProtocolVersion, response.Protocol)}s.helperMu.Lock()@@ -111,7 +112,7 @@ func (s *VolumeService) getVolumeHelperImageInternal(ctx context.Context, docker}dockerClient, err = s.dockerService.GetClient(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to get docker client")+ return "", fmt.Errorf("failed to get docker client: %w", err)}}@@ -141,7 +142,7 @@ func (s *VolumeService) getVolumeHelperImageInternal(ctx context.Context, dockerreturn fallback.Image, nil}- return "", errors.WrapIf(pullErr, "failed to resolve helper image: tools image unavailable and arcane fallback not found")+ return "", fmt.Errorf("failed to resolve helper image: tools image unavailable and arcane fallback not found: %w", pullErr)}func (s *VolumeService) acquireVolumeHelperInternal(ctx context.Context, volumeName string) (string, func(), error) {@@ -203,7 +204,7 @@ func (s *VolumeService) resolveHelperInternal(ctx context.Context, dockerClientvar shared anyselect {case <-ctx.Done():- return "", errors.WrapIf(ctx.Err(), "canceled waiting for volume helper container")+ return "", fmt.Errorf("canceled waiting for volume helper container: %w", ctx.Err())case result := <-resultCh:if result.Err != nil {return "", result.Err@@ -269,12 +270,12 @@ func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerHostConfig: hostConfig,})if err != nil {- return "", nil, errors.WrapIf(err, "failed to create temp container")+ return "", nil, fmt.Errorf("failed to create temp container: %w", err)}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return "", nil, errors.WrapIf(err, "failed to start temp container")+ return "", nil, fmt.Errorf("failed to start temp container: %w", err)}cleanup := func() {@@ -351,7 +352,7 @@ func (s *VolumeService) ReapIdleHelpers(ctx context.Context, idleTimeout time.DudockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, errors.WrapIf(err, "failed to get docker client for idle helper reap")+ return 0, fmt.Errorf("failed to get docker client for idle helper reap: %w", err)}staleIDs := s.collectStaleHelperIDsInternal(time.Now(), idleTimeout)@@ -406,7 +407,7 @@ func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) errordockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to get docker client for helper stop")+ return fmt.Errorf("failed to get docker client for helper stop: %w", err)}containerID := s.takeHelperIDInternal(volumeName)@@ -415,7 +416,7 @@ func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error}if _, err := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); err != nil {- return errors.WrapIf(err, "failed to remove helper container")+ return fmt.Errorf("failed to remove helper container: %w", err)}return nil@@ -439,12 +440,12 @@ func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int,dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return 0, errors.WrapIf(err, "failed to get docker client for orphan helper cleanup")+ return 0, fmt.Errorf("failed to get docker client for orphan helper cleanup: %w", err)}containers, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: true})if err != nil {- return 0, errors.WrapIf(err, "failed to list containers for orphan helper cleanup")+ return 0, fmt.Errorf("failed to list containers for orphan helper cleanup: %w", err)}removedCount := 0@@ -500,9 +501,9 @@ func (s *VolumeService) execInContainerInternal(ctx context.Context, containerIDif exitCode != 0 {execErr := cmp.Or(strings.TrimSpace(stderr.String()), strings.TrimSpace(stdout.String()))if execErr != "" {- return stdout.String(), stderr.String(), errors.Errorf("command exited with code %d: %s", exitCode, execErr)+ return stdout.String(), stderr.String(), fmt.Errorf("command exited with code %d: %s", exitCode, execErr)}- return stdout.String(), stderr.String(), errors.Errorf("command exited with code %d", exitCode)+ return stdout.String(), stderr.String(), fmt.Errorf("command exited with code %d", exitCode)}return stdout.String(), stderr.String(), nildiff --git a/backend/internal/volume/listing.go b/backend/internal/volume/listing.goindex 7e2100bfa..a8d98d360 100644--- a/backend/internal/volume/listing.go+++ b/backend/internal/volume/listing.go@@ -3,12 +3,12 @@ package volumeimport ("cmp""context"+ "fmt""log/slog""regexp""strings""time"- "emperror.dev/errors"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"@@ -27,17 +27,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, errors.WrapIf(err, "failed to connect to Docker")+ return false, nil, fmt.Errorf("failed to connect to Docker: %w", err)}vol, err := dockerClient.VolumeInspect(ctx, name, client.VolumeInspectOptions{})if err != nil {- return false, nil, errors.WrapIf(err, "volume not found")+ return false, nil, fmt.Errorf("volume not found: %w", err)}containerIDs, err := docker.GetContainersUsingVolume(ctx, dockerClient, vol.Volume.Name)if err != nil {- return false, nil, errors.WrapIf(err, "failed to get containers using volume")+ return false, nil, fmt.Errorf("failed to get containers using volume: %w", err)}inUse := len(containerIDs) > 0@@ -60,12 +60,12 @@ func (s *VolumeService) GetVolumeSizes(ctx context.Context) (map[string]VolumeSidockerClient, err := s.dockerService.GetClient(apiCtx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}usageVolumes, err := docker.GetVolumeUsageData(apiCtx, dockerClient)if err != nil {- return nil, errors.WrapIf(err, "failed to get volume usage data")+ return nil, fmt.Errorf("failed to get volume usage data: %w", err)}result := make(map[string]VolumeSizeData, len(usageVolumes))@@ -107,7 +107,7 @@ func enrichVolumesWithUsageDataInternal(volumes, usageVolumes []volume.Volume) [func (s *VolumeService) buildVolumeContainerMapInternal(ctx context.Context) (map[string][]string, error) {containers, err := s.dockerService.ListContainers(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to list containers")+ return nil, fmt.Errorf("failed to list containers: %w", err)}volumeContainerMap := make(map[string][]string)@@ -312,11 +312,11 @@ func mountedVolumeNamesInternal(mounts []container.MountPoint) map[string]structfunc (s *VolumeService) ListBackupVolumeOptions(ctx context.Context) ([]backuptypes.SystemVolumeBackupOption, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}result, err := dockerClient.VolumeList(ctx, client.VolumeListOptions{})if err != nil {- return nil, errors.WrapIf(err, "failed to list Docker volumes")+ return nil, fmt.Errorf("failed to list Docker volumes: %w", err)}arcaneVolumes := make(map[string]struct{})if inspect, inspectErr := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient); inspectErr == nil && inspect != nil {@@ -344,7 +344,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{}, errors.WrapIf(err, "failed to connect to Docker")+ return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)}// Run volume list and container list in parallel for better performance@@ -377,7 +377,7 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginat// Wait for both resultsvolResult := <-volChanif volResult.err != nil {- return nil, pagination.Response{}, volumetypes.UsageCounts{}, errors.WrapIf(volResult.err, "failed to list Docker volumes")+ return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to list Docker volumes: %w", volResult.err)}containerResult := <-containerChandiff --git a/backend/internal/volume/rename.go b/backend/internal/volume/rename.goindex d44aad415..25e66762d 100644--- a/backend/internal/volume/rename.go+++ b/backend/internal/volume/rename.go@@ -2,11 +2,11 @@ package volumeimport ("context"- stderrors "errors"+ "errors"+ "fmt""log/slog""strings"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -34,7 +34,7 @@ func (s *VolumeService) RenameVolume(ctx context.Context, oldName, newName strindockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "connect", err)- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}source, err := dockerClient.VolumeInspect(ctx, oldName, client.VolumeInspectOptions{})@@ -43,7 +43,7 @@ func (s *VolumeService) RenameVolume(ctx context.Context, oldName, newName strinerr = common.Classify(common.ErrNotFound, err)}s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "inspect", err)- return nil, errors.WrapIf(err, "inspect source volume")+ return nil, fmt.Errorf("inspect source volume: %w", err)}if s.isInternalVolumeInternal(volumetypes.NewSummary(source.Volume)) {return nil, common.ErrVolumeRenameProtected@@ -70,22 +70,21 @@ func (s *VolumeService) RenameVolume(ctx context.Context, oldName, newName strinif err := s.renameVolumeMetadataInternal(ctx, oldName, newName); err != nil {rollbackErr := migration.Rollback(ctx)- combinedErr := stderrors.Join(errors.WrapIf(err, "rename volume metadata"), rollbackErr)+ combinedErr := errors.Join(fmt.Errorf("rename volume metadata: %w", err), rollbackErr)s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "metadata", combinedErr)return nil, combinedErr}if committer, ok := migration.(volumetypes.Committer); ok {if err := committer.Commit(ctx); err != nil {- var cleanupErr *volumetypes.SourceCleanupError- if errors.As(err, &cleanupErr) {+ if _, ok := errors.AsType[*volumetypes.SourceCleanupError](err); ok {// The copy and metadata are committed; only removing the source// failed, so the rename itself succeeded.slog.WarnContext(ctx, "volume renamed but source volume could not be removed", "oldVolume", oldName, "newVolume", newName, "error", err.Error())} else {metadataErr := s.renameVolumeMetadataInternal(ctx, newName, oldName)rollbackErr := migration.Rollback(ctx)- combinedErr := stderrors.Join(err, metadataErr, rollbackErr)+ combinedErr := errors.Join(err, metadataErr, rollbackErr)s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "commit", combinedErr)return nil, combinedErr}@@ -98,7 +97,7 @@ func (s *VolumeService) RenameVolume(ctx context.Context, oldName, newName strinrenamed, err := s.GetVolumeByName(ctx, newName)if err != nil {s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "inspect-renamed", err)- return nil, errors.WrapIf(err, "inspect renamed volume")+ return nil, fmt.Errorf("inspect renamed volume: %w", err)}metadata := database.JSON{"action": "rename", "oldName": oldName, "newName": newName}@@ -118,10 +117,10 @@ func (s *VolumeService) renameVolumeMetadataInternal(ctx context.Context, oldNamreturn s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Model(&VolumeBackup{}).Where("volume_name = ?", oldName).Update("volume_name", newName).Error; err != nil {- return errors.WrapIf(err, "rename volume backup history")+ return fmt.Errorf("rename volume backup history: %w", err)}if err := tx.Model(&VolumeBackupPolicy{}).Where("volume_name = ?", oldName).Update("volume_name", newName).Error; err != nil {- return errors.WrapIf(err, "rename volume backup policies")+ return fmt.Errorf("rename volume backup policies: %w", err)}return nil})diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.goindex ec8056944..14b12a774 100644--- a/backend/internal/volume/service.go+++ b/backend/internal/volume/service.go@@ -2,11 +2,11 @@ package volumeimport ("context"+ "fmt""log/slog""strings""sync"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -120,12 +120,12 @@ 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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}volResult, err := dockerClient.VolumeInspect(ctx, name, client.VolumeInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "volume not found")+ return nil, fmt.Errorf("volume not found: %w", err)}vol := volResult.Volume@@ -162,21 +162,21 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("volume", options.Name, options.Name)()created, err := dockerClient.VolumeCreate(ctx, options)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})- return nil, errors.WrapIf(err, "failed to create volume")+ return nil, fmt.Errorf("failed to create volume: %w", err)}defer s.eventService.BeginDockerResourceSuppressionWindow("volume", created.Volume.Name, created.Volume.Name)()vol, err := dockerClient.VolumeInspect(ctx, created.Volume.Name, client.VolumeInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", created.Volume.Name, created.Volume.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver, "step": "inspect"})- return nil, errors.WrapIf(err, "failed to inspect created volume")+ return nil, fmt.Errorf("failed to inspect created volume: %w", err)}metadata := database.JSON{@@ -198,7 +198,7 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boodockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}// Stop any read-only browse helper first; a helper mounting the volume would@@ -212,7 +212,7 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force booForce: force,}); err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})- return errors.WrapIf(err, "failed to remove volume")+ return fmt.Errorf("failed to remove volume: %w", err)}metadata := database.JSON{@@ -238,7 +238,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, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}// Stop all read-only browse helpers first; a helper mounting a volume marks it@@ -252,7 +252,7 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (// Note: Volumes are considered "in use" if referenced by any container (running or stopped)volumePruneResult, err := dockerClient.VolumePrune(ctx, buildVolumePruneOptionsInternal(all))if err != nil {- return nil, errors.WrapIf(err, "failed to prune volumes")+ return nil, fmt.Errorf("failed to prune volumes: %w", err)}metadata := buildVolumePruneMetadataInternal(all, len(volumePruneResult.Report.VolumesDeleted), volumePruneResult.Report.SpaceReclaimed)diff --git a/backend/internal/volume/service_test.go b/backend/internal/volume/service_test.goindex 6d815a26c..3b4a131e6 100644--- a/backend/internal/volume/service_test.go+++ b/backend/internal/volume/service_test.go@@ -896,7 +896,7 @@ func TestVolumeBackupContainerLifecycleStopsAndRestartsOnlyRunningContainersUsin})service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)- actor := common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"}+ actor := common.User{ID: "user-1", Username: "tester"}stopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)require.NoError(t, err)require.Len(t, stopped, 1)@@ -940,7 +940,7 @@ func TestVolumeBackupContainerLifecycleRollsBackStoppedContainersOnStopFailure(t})service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)- actor := common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"}+ actor := common.User{ID: "user-1", Username: "tester"}stillStopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)require.ErrorContains(t, err, "failed to stop container second")require.Empty(t, stillStopped)@@ -1000,7 +1000,7 @@ func TestVolumeBackupContainerLifecycleWaitsForRunningComposeReplacement(t *test})service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)- actor := common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"}+ actor := common.User{ID: "user-1", Username: "tester"}stopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)require.NoError(t, err)require.Len(t, stopped, 1)diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.goindex df318fed0..1f75d01b5 100644--- a/backend/internal/volume/workspace.go+++ b/backend/internal/volume/workspace.go@@ -8,7 +8,7 @@ import ("encoding/hex""encoding/json/jsontext""encoding/json/v2"- stderrors "errors"+ "errors""fmt""io""log/slog"@@ -20,7 +20,6 @@ import ("sync""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -102,7 +101,7 @@ func (s *VolumeService) readVolumeWorkspaceFromContainerInternal(ctx context.ConCmd: cmd,}, pipeWriter, &stderr)if execErr == nil && exitCode != 0 {- execErr = errors.Errorf("acfs walk exited with code %d", exitCode)+ execErr = fmt.Errorf("acfs walk exited with code %d", exitCode)}_ = pipeWriter.CloseWithError(execErr)done <- execErr@@ -118,7 +117,7 @@ func (s *VolumeService) readVolumeWorkspaceFromContainerInternal(ctx context.Conreturn nil, classifyVolumeWorkspaceExecErrorInternal(execErr, stderr.String(), "read volume workspace")}if parseErr != nil {- return nil, errors.WrapIf(parseErr, "parse volume workspace")+ return nil, fmt.Errorf("parse volume workspace: %w", parseErr)}return workspace, nil@@ -133,14 +132,14 @@ func decodeVolumeWorkspaceWalkInternal(source io.Reader, maxEntries int, maxFilefor {var record acfstypes.WalkRecorderr := json.UnmarshalDecode(decoder, &record)- if stderrors.Is(err, io.EOF) {+ if errors.Is(err, io.EOF) {break}if err != nil {return nil, err}if record.Version != acfstypes.ProtocolVersion {- return nil, errors.Errorf("unsupported acfs protocol %d", record.Version)+ return nil, fmt.Errorf("unsupported acfs protocol %d", record.Version)}if trailerSeen {return nil, errors.New("acfs walk emitted a record after its trailer")@@ -227,7 +226,7 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,}rel, err := kit.NormalizeRelativePath(relativePath)if err != nil {- return nil, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))+ return nil, common.Classify(common.ErrVolumeWorkspaceForbidden, fmt.Errorf("invalid volume workspace path: %w", err))}containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)if err != nil {@@ -245,10 +244,10 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,}var statResponse acfstypes.StatResponseif err := json.Unmarshal([]byte(stdout), &statResponse); err != nil {- return nil, errors.WrapIf(err, "parse volume workspace stat")+ return nil, fmt.Errorf("parse volume workspace stat: %w", err)}if statResponse.Version != acfstypes.ProtocolVersion {- return nil, errors.Errorf("unsupported acfs protocol %d", statResponse.Version)+ return nil, fmt.Errorf("unsupported acfs protocol %d", statResponse.Version)}entry := statResponse.Entryif entry.IsSymlink {@@ -271,15 +270,15 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,}reader, size, err := s.startVolumeWorkspaceReadInternal(ctx, containerID, rel, previewLimit, func() {})if err != nil {- return nil, errors.WrapIf(err, "read volume workspace file")+ return nil, fmt.Errorf("read volume workspace file: %w", err)}content, readErr := io.ReadAll(reader)closeErr := reader.Close()if readErr != nil {- return nil, errors.WrapIf(readErr, "read volume workspace file content")+ return nil, fmt.Errorf("read volume workspace file content: %w", readErr)}if closeErr != nil {- return nil, errors.WrapIf(closeErr, "close volume workspace file content")+ return nil, fmt.Errorf("close volume workspace file content: %w", closeErr)}if size > maxFileSizeBytes {return volumeWorkspaceFileContentResponseInternal(rel, "regular", size, nil, maxFileSizeBytes)@@ -296,7 +295,7 @@ func (s *VolumeService) DownloadVolumeWorkspaceFile(ctx context.Context, volumeNrel, err := kit.NormalizeRelativePath(relativePath)if err != nil {unlock()- return nil, 0, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))+ return nil, 0, common.Classify(common.ErrVolumeWorkspaceForbidden, fmt.Errorf("invalid volume workspace path: %w", err))}containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)if err != nil {@@ -334,7 +333,7 @@ func (r *volumeWorkspaceReadStreamInternal) Read(buffer []byte) (int, error) {if closeErr != nil {return 0, closeErr}- return 0, kit.Ternary(readErr != nil && !stderrors.Is(readErr, io.EOF), readErr, io.EOF)+ return 0, kit.Ternary(readErr != nil && !errors.Is(readErr, io.EOF), readErr, io.EOF)}if int64(len(buffer)) > r.remaining {buffer = buffer[:r.remaining]@@ -344,7 +343,7 @@ func (r *volumeWorkspaceReadStreamInternal) Read(buffer []byte) (int, error) {if err != nil && r.remaining > 0 {closeErr := r.Close()if closeErr != nil {- return read, stderrors.Join(err, closeErr)+ return read, errors.Join(err, closeErr)}}return read, err@@ -379,7 +378,7 @@ func (s *VolumeService) startVolumeWorkspaceReadInternal(ctx context.Context, coCmd: cmd,}, pipeWriter, &stderr)if execErr == nil && exitCode != 0 {- execErr = errors.Errorf("acfs read exited with code %d", exitCode)+ execErr = fmt.Errorf("acfs read exited with code %d", exitCode)}if execErr != nil {execErr = classifyVolumeWorkspaceExecErrorInternal(execErr, stderr.String(), "read volume workspace file")@@ -396,7 +395,7 @@ func (s *VolumeService) startVolumeWorkspaceReadInternal(ctx context.Context, coif execErr != nil {return nil, 0, execErr}- return nil, 0, errors.WrapIf(err, "parse volume workspace read header")+ return nil, 0, fmt.Errorf("parse volume workspace read header: %w", err)}if payloadSize > uint64(1<<63-1) {_ = pipeReader.Close()@@ -416,11 +415,11 @@ func (s *VolumeService) startVolumeWorkspaceReadInternal(ctx context.Context, cofunc (s *VolumeService) validateVolumeHelperSupportInternal(ctx context.Context, volumeName string) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return errors.WrapIf(err, "failed to connect to Docker")+ return fmt.Errorf("failed to connect to Docker: %w", err)}result, err := dockerClient.VolumeInspect(ctx, volumeName, client.VolumeInspectOptions{})if err != nil {- return errors.WrapIf(err, "failed to inspect volume")+ return fmt.Errorf("failed to inspect volume: %w", err)}return dockerutil.ValidateVolumeWorkspaceHelperSupport(volumeName, result.Volume.Options)}@@ -474,7 +473,7 @@ func classifyVolumeWorkspaceExecErrorInternal(err error, stderr, fallbackContextcase acfstypes.ErrorSizeMismatch, acfstypes.ErrorRootRemoval:return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New(response.Message))case acfstypes.ErrorInternal:- return errors.WrapIf(err, fallbackContext)+ return fmt.Errorf("%s: %w", fallbackContext, err)}}@@ -495,7 +494,7 @@ func classifyVolumeWorkspaceExecErrorInternal(err error, stderr, fallbackContextcase strings.Contains(message, "ARCANE_DIRECTORY"):return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("path is a directory"))default:- return errors.WrapIf(err, fallbackContext)+ return fmt.Errorf("%s: %w", fallbackContext, err)}}@@ -779,7 +778,7 @@ type volumeWorkspaceStagedContentInternal struct {func (s *VolumeService) stageVolumeWorkspaceChangesInternal(ctx context.Context, dockerClient *client.Client, containerID string, changes []volumetypes.WorkspaceFileChange, uploads map[int][]byte, identity volumeWorkspaceWriteIdentityInternal) (map[int]volumeWorkspaceStagedFileInternal, error) {if _, _, err := s.execInContainerInternal(ctx, containerID, "", []string{"sh", "-c", "rm -rf -- /tmp/arcane-workspace && mkdir -p -- /tmp/arcane-workspace"}); err != nil {- return nil, errors.WrapIf(err, "prepare volume workspace staging directory")+ return nil, fmt.Errorf("prepare volume workspace staging directory: %w", err)}stagedFiles := make(map[int]volumeWorkspaceStagedFileInternal)@@ -827,7 +826,7 @@ func (s *VolumeService) applyVolumeWorkspaceChangesInternal() error {rollbackFailureInternal := func(applyErr error) error {if rollbackErr := rollback(); rollbackErr != nil {- return stderrors.Join(applyErr, errors.WrapIf(rollbackErr, "failed to roll back volume workspace"))+ return errors.Join(applyErr, fmt.Errorf("failed to roll back volume workspace: %w", rollbackErr))}return applyErr}@@ -877,7 +876,7 @@ func (s *VolumeService) executeVolumeWorkspaceACFSBatchInternal(Changes: applyChanges,})if err != nil {- return errors.WrapIf(err, "encode volume workspace apply manifest")+ return fmt.Errorf("encode volume workspace apply manifest: %w", err)}manifestName := fmt.Sprintf("manifest-%d.json", startIndex)if err := s.copyVolumeWorkspaceFilesToContainerInternal(ctx, dockerClient, containerID, []volumeWorkspaceStagedContentInternal{{@@ -896,7 +895,7 @@ func (s *VolumeService) executeVolumeWorkspaceACFSBatchInternal(}var response acfstypes.ApplyResponseif err := json.Unmarshal([]byte(stdout), &response); err != nil {- return errors.WrapIf(err, "parse volume workspace apply response")+ return fmt.Errorf("parse volume workspace apply response: %w", err)}if response.Version != acfstypes.ProtocolVersion || response.Applied != len(applyChanges) {return errors.New("invalid volume workspace apply response")@@ -944,14 +943,14 @@ func mapVolumeWorkspaceChangeToACFSInternal(change volumetypes.WorkspaceFileChancase volumetypes.FileOpDelete:result.Operation = acfstypes.ApplyDeletedefault:- return acfstypes.ApplyChange{}, errors.Errorf("unsupported volume workspace operation %q", change.Operation)+ return acfstypes.ApplyChange{}, fmt.Errorf("unsupported volume workspace operation %q", change.Operation)}return result, nil}func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileChange) error {if _, err := kit.NormalizeRelativePath(change.RelativePath); err != nil {- return errors.WrapIf(err, "invalid volume workspace path")+ return fmt.Errorf("invalid volume workspace path: %w", err)}hasUpload := change.UploadIndex != nilswitch change.Operation {@@ -968,7 +967,7 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileCreturn errors.New("rename does not accept file content")}if _, err := kit.ValidateFileName(change.NewName); err != nil {- return errors.WrapIf(err, "invalid volume workspace file name")+ return fmt.Errorf("invalid volume workspace file name: %w", err)}case volumetypes.FileOpMove:if hasUpload {@@ -976,7 +975,7 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileC}if strings.TrimSpace(change.NewParentPath) != "" {if _, err := kit.NormalizeRelativePath(change.NewParentPath); err != nil {- return errors.WrapIf(err, "invalid destination folder")+ return fmt.Errorf("invalid destination folder: %w", err)}}case volumetypes.FileOpRestoreFile:@@ -987,7 +986,7 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileCreturn errors.New("restore_file requires backupId")}default:- return errors.Errorf("unsupported volume workspace operation %q", change.Operation)+ return fmt.Errorf("unsupported volume workspace operation %q", change.Operation)}return nil}@@ -1019,10 +1018,10 @@ func (s *VolumeService) copyVolumeWorkspaceFilesToContainerInternal(ctx context._ = stagedContent.content.Close()}if copyErr != nil {- return errors.WrapIf(copyErr, "stage volume workspace files")+ return fmt.Errorf("stage volume workspace files: %w", copyErr)}if archiveErr != nil {- return errors.WrapIf(archiveErr, "create volume workspace staging archive")+ return fmt.Errorf("create volume workspace staging archive: %w", archiveErr)}return nil}@@ -1047,11 +1046,11 @@ func (s *VolumeService) createVolumeWorkspaceMutationContainerInternal(ctx contehostConfig := volumehelper.HostConfig(helperImage, []string{volumeName + ":/volume"}, []mount.Mount{backupStorage.mount})resp, err := dockerClient.ContainerCreate(ctx, client.ContainerCreateOptions{Config: config, HostConfig: hostConfig})if err != nil {- return "", nil, errors.WrapIf(err, "create volume workspace helper")+ return "", nil, fmt.Errorf("create volume workspace helper: %w", err)}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())- return "", nil, errors.WrapIf(err, "start volume workspace helper")+ return "", nil, fmt.Errorf("start volume workspace helper: %w", err)}return resp.ID, func() {_, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())@@ -1116,7 +1115,7 @@ type volumeWorkspaceBackupInternal struct {func (s *VolumeService) backupVolumeWorkspaceScopeInternal(ctx context.Context, containerID string, scope []string) (*volumeWorkspaceBackupInternal, error) {if _, _, err := s.execInContainerInternal(ctx, containerID, "", []string{"mkdir", "-p", "/tmp/arcane-workspace"}); err != nil {- return nil, errors.WrapIf(err, "prepare volume workspace backup directory")+ return nil, fmt.Errorf("prepare volume workspace backup directory: %w", err)}backup := &volumeWorkspaceBackupInternal{archives: make([]volumeWorkspaceBackupArchiveInternal, 0, len(scope)),diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.goindex 97a320d96..6257ae3ae 100644--- a/backend/internal/volume/workspace_handler.go+++ b/backend/internal/volume/workspace_handler.go@@ -2,12 +2,12 @@ package volumeimport ("context"+ "errors""mime/multipart""net/http""path""strings"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.goindex ed62a4f1f..1301ee115 100644--- a/backend/internal/vulnerability/handler.go+++ b/backend/internal/vulnerability/handler.go@@ -3,12 +3,12 @@ package vulnerabilityimport ("cmp""context"+ "errors""fmt""log/slog""net/http""time"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -323,7 +323,7 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInif errors.Is(err, common.ErrFeatureDisabled) {return nil, handlerutil.FeatureDisabledError(features.VulnerabilityManagement)}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())+ return nil, huma.Error500InternalServerError("Failed to scan image for vulnerabilities: " + err.Error())}return &handlerutil.Out[vulnerability.ScanResult]{@@ -353,7 +353,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetSif errors.Is(err, common.ErrFeatureDisabled) {return nil, handlerutil.FeatureDisabledError(features.VulnerabilityManagement)}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())+ return nil, huma.Error500InternalServerError("Failed to scan image for vulnerabilities: " + err.Error())}return &handlerutil.Out[vulnerability.ScanSummariesResponse]{@@ -370,7 +370,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetSfunc (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*handlerutil.Out[vulnerability.ScanResult], error) {result, err := h.vulnerabilityService.GetScanResult(ctx, input.EnvironmentID, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if result == nil {@@ -389,7 +389,7 @@ func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanfunc (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*handlerutil.Out[vulnerability.ScanSummary], error) {summary, err := h.vulnerabilityService.GetScanSummary(ctx, input.ImageID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if summary == nil {@@ -417,7 +417,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inpif errors.Is(err, common.ErrVulnerabilityScanNotFound) {return nil, huma.Error404NotFound("Vulnerability scan not found")}- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if items == nil {@@ -437,7 +437,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inpfunc (h *VulnerabilityHandler) GetRiskOverview(ctx context.Context, input *GetRiskOverviewInput) (*handlerutil.Out[vulnerability.RiskOverview], error) {overview, err := h.vulnerabilityService.GetRiskOverview(ctx, input.EnvironmentID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability risk overview").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability risk overview: " + err.Error())}return &handlerutil.Out[vulnerability.RiskOverview]{@@ -452,7 +452,7 @@ func (h *VulnerabilityHandler) GetRiskOverview(ctx context.Context, input *GetRifunc (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*handlerutil.Out[vulnerability.EnvironmentVulnerabilitySummary], error) {summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if summary == nil {@@ -489,7 +489,7 @@ func (input *ListAllVulnerabilitiesInput) queryParamsInternal() pagination.Queryfunc (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*handlerutil.Page[vulnerability.VulnerabilityWithImage], error) {items, paginationResp, err := h.vulnerabilityService.ListAllVulnerabilities(ctx, input.EnvironmentID, input.queryParamsInternal())if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if items == nil {@@ -519,7 +519,7 @@ func (h *VulnerabilityHandler) ExportVulnerabilities(ctx context.Context, input}).queryParamsInternal()items, err := h.vulnerabilityService.ExportVulnerabilities(ctx, input.EnvironmentID, params)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to export vulnerabilities").Error())+ return nil, huma.Error500InternalServerError("Failed to export vulnerabilities: " + err.Error())}filename := fmt.Sprintf("vulnerabilities-%s-%s.csv", input.EnvironmentID, time.Now().UTC().Format("2006-01-02T15-04-05Z"))@@ -538,7 +538,7 @@ func (h *VulnerabilityHandler) ExportVulnerabilities(ctx context.Context, inputfunc (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*handlerutil.Out[[]string], error) {items, err := h.vulnerabilityService.ListAllVulnerabilityImageOptions(ctx, input.Severity)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())+ return nil, huma.Error500InternalServerError("Failed to retrieve vulnerability scan: " + err.Error())}if items == nil {@@ -646,7 +646,7 @@ func (h *VulnerabilityHandler) BulkIgnoreVulnerabilities(ctx context.Context, inaffected, err := h.vulnerabilityService.BulkIgnoreVulnerabilities(ctx, input.EnvironmentID, &input.Body, user.ID)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to ignore vulnerabilities").Error())+ return nil, huma.Error500InternalServerError("Failed to ignore vulnerabilities: " + err.Error())}return &handlerutil.Out[vulnerability.BulkIgnoreResponse]{@@ -661,7 +661,7 @@ func (h *VulnerabilityHandler) BulkIgnoreVulnerabilities(ctx context.Context, infunc (h *VulnerabilityHandler) BulkUnignoreVulnerabilities(ctx context.Context, input *BulkIgnoreVulnerabilitiesInput) (*handlerutil.Out[vulnerability.BulkIgnoreResponse], error) {affected, err := h.vulnerabilityService.BulkUnignoreVulnerabilities(ctx, input.EnvironmentID, &input.Body)if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to restore vulnerabilities").Error())+ return nil, huma.Error500InternalServerError("Failed to restore vulnerabilities: " + err.Error())}return &handlerutil.Out[vulnerability.BulkIgnoreResponse]{diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex c43bfca5d..b367df70f 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -3,6 +3,7 @@ package vulnerabilityimport ("context""encoding/json"+ "errors""fmt""net/http""net/http/httptest"@@ -11,7 +12,6 @@ import ("testing""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/kv"diff --git a/backend/internal/vulnerability/vulnerability.go b/backend/internal/vulnerability/vulnerability.goindex 8739ff741..8618a7699 100644--- a/backend/internal/vulnerability/vulnerability.go+++ b/backend/internal/vulnerability/vulnerability.go@@ -19,6 +19,9 @@ import ()const (+ trivyCPUCapabilitiesCacheTTL = time.Hour+ trivyCPUCapabilitiesLookupTimeout = 5 * time.Second+trivyCacheVolumeName = "arcane-trivy-cache"trivyCacheSlotRootDir = vuln.CacheMountTarget + "/arcane-scan-slots"scanStaleTimeout = 30 * time.Minutediff --git a/backend/internal/vulnerability/vulnerability_capabilities.go b/backend/internal/vulnerability/vulnerability_capabilities.godeleted file mode 100644index ca85c65ef..000000000--- a/backend/internal/vulnerability/vulnerability_capabilities.go+++ /dev/null@@ -1,73 +0,0 @@-package vulnerability--import (- "context"- "encoding/json"- "log/slog"- "time"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln"- "github.com/moby/moby/client"- kit "go.getarcane.app/kit/pkg"-)--const (- trivyCPUCapabilitiesCacheTTL = time.Hour- trivyCPUCapabilitiesLookupTimeout = 5 * time.Second-)--type trivyCPUCapabilitiesInternal struct {- Quota bool `json:"quota"`- CPUSet bool `json:"cpuSet"`- CPUs int `json:"cpus"`- FetchedAt time.Time `json:"fetchedAt"`-}--func (s *VulnerabilityService) getTrivyCPUCapabilitiesInternal(ctx context.Context, dockerClient *client.Client) (trivyCPUCapabilitiesInternal, error) {- key := "trivy:cpu-capabilities:v1:" + kit.SHA256Hex(dockerClient.DaemonHost()+"\x00"+dockerClient.ClientVersion())- var cached trivyCPUCapabilitiesInternal- if s.kvService != nil {- raw, found, err := s.kvService.Get(ctx, key)- if err != nil {- slog.WarnContext(ctx, "failed to read cached Trivy CPU capabilities", "error", err)- } else if found {- if err := json.Unmarshal([]byte(raw), &cached); err != nil || cached.FetchedAt.IsZero() {- slog.WarnContext(ctx, "ignoring invalid cached Trivy CPU capabilities", "error", err)- cached = trivyCPUCapabilitiesInternal{}- } else if age := time.Since(cached.FetchedAt); age >= 0 && age < trivyCPUCapabilitiesCacheTTL {- return cached, nil- }- }- }-- infoCtx, cancel := context.WithTimeout(ctx, trivyCPUCapabilitiesLookupTimeout)- defer cancel()- info, err := dockerClient.Info(infoCtx, client.InfoOptions{})- if err != nil {- if ctx.Err() != nil {- return trivyCPUCapabilitiesInternal{}, ctx.Err()- }- if !cached.FetchedAt.IsZero() {- slog.WarnContext(ctx, "failed to refresh Trivy CPU capabilities; using cached capabilities", "error", err)- return cached, nil- }- return trivyCPUCapabilitiesInternal{}, err- }-- capabilities := trivyCPUCapabilitiesInternal{- Quota: info.Info.CPUCfsQuota && !vuln.IsSynologyDockerHost(info.Info.OperatingSystem),- CPUSet: info.Info.CPUSet,- CPUs: info.Info.NCPU,- FetchedAt: time.Now().UTC(),- }- if s.kvService != nil {- payload, err := json.Marshal(capabilities)- if err == nil {- err = s.kvService.Set(ctx, key, string(payload))- }- if err != nil {- slog.WarnContext(ctx, "failed to cache Trivy CPU capabilities", "error", err)- }- }- return capabilities, nil-}diff --git a/backend/internal/vulnerability/vulnerability_export.go b/backend/internal/vulnerability/vulnerability_export.godeleted file mode 100644index 673ad1f82..000000000--- a/backend/internal/vulnerability/vulnerability_export.go+++ /dev/null@@ -1,43 +0,0 @@-package vulnerability--import (- "cmp"- "encoding/csv"- "io"- "iter"- "strconv"- "strings"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/types/v2/vulnerability"- kit "go.getarcane.app/kit/pkg"-)--var vulnerabilityCSVHeaderInternal = []string{"CVE", "Severity", "Package", "Installed Version", "Fixed Version", "Image", "Ignored"}--// WriteVulnerabilitiesCSV streams items to w as a BOM-prefixed, CRLF-terminated CSV with formula-safe cells.-func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.VulnerabilityWithImage, error]) error {- if _, err := io.WriteString(w, "\xEF\xBB\xBF"); err != nil {- return errors.WrapIf(err, "failed to write csv")- }- writer := csv.NewWriter(w)- writer.UseCRLF = true- if err := writer.Write(vulnerabilityCSVHeaderInternal); err != nil {- return errors.WrapIf(err, "failed to write csv")- }- for item, err := range items {- if err != nil {- return err- }- image := cmp.Or(item.ImageName, item.ImageID)- record := []string{item.VulnerabilityID, string(item.Severity), item.PkgName, item.InstalledVersion, item.FixedVersion, image, strconv.FormatBool(item.Ignored)}- for j, value := range record {- record[j] = kit.Ternary(value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])), "'"+value, value)- }- if err := writer.Write(record); err != nil {- return errors.WrapIf(err, "failed to write csv")- }- }- writer.Flush()- return errors.WrapIf(writer.Error(), "failed to write csv")-}diff --git a/backend/internal/vulnerability/vulnerability_export_test.go b/backend/internal/vulnerability/vulnerability_export_test.goindex 1cb81f98d..c953c938d 100644--- a/backend/internal/vulnerability/vulnerability_export_test.go+++ b/backend/internal/vulnerability/vulnerability_export_test.go@@ -11,20 +11,15 @@ import (func TestWriteVulnerabilitiesCSV(t *testing.T) {items := []vulnerability.VulnerabilityWithImage{- {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0001", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest"},- {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0002", PkgName: "libc, glibc", Severity: vulnerability.SeverityHigh}, ImageID: "sha256:fallback"},- {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0003", PkgName: `pkg "quoted"`, InstalledVersion: "ünïcødé", FixedVersion: "line1\nline2", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest", Ignored: true},- {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: `=HYPERLINK("https://evil.example")`, PkgName: "+sum", InstalledVersion: "-1", FixedVersion: "@cmd", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest"},+ {VulnerabilityID: "CVE-2026-0001", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest"},+ {VulnerabilityID: "CVE-2026-0002", PkgName: "libc, glibc", Severity: vulnerability.SeverityHigh, ImageID: "sha256:fallback"},+ {VulnerabilityID: "CVE-2026-0003", PkgName: `pkg "quoted"`, InstalledVersion: "ünïcødé", FixedVersion: "line1\nline2", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest", Ignored: true},+ {VulnerabilityID: `=HYPERLINK("https://evil.example")`, PkgName: "+sum", InstalledVersion: "-1", FixedVersion: "@cmd", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest"},}var buf bytes.Bufferrequire.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(items)))- require.Equal(t, "\xEF\xBB\xBF"+- "CVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\n"+- "CVE-2026-0001,HIGH,openssl,3.0.0,3.0.1,example/security:latest,false\r\n"+- "CVE-2026-0002,HIGH,\"libc, glibc\",,,sha256:fallback,false\r\n"+- "CVE-2026-0003,HIGH,\"pkg \"\"quoted\"\"\",ünïcødé,\"line1\r\nline2\",example/security:latest,true\r\n"+- "\"'=HYPERLINK(\"\"https://evil.example\"\")\",HIGH,'+sum,'-1,'@cmd,example/security:latest,false\r\n", buf.String())+ require.Equal(t, "\ufeffCVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\nCVE-2026-0001,HIGH,openssl,3.0.0,3.0.1,example/security:latest,false\r\nCVE-2026-0002,HIGH,\"libc, glibc\",,,sha256:fallback,false\r\nCVE-2026-0003,HIGH,\"pkg \"\"quoted\"\"\",ünïcødé,\"line1\r\nline2\",example/security:latest,true\r\n\"'=HYPERLINK(\"\"https://evil.example\"\")\",HIGH,'+sum,'-1,'@cmd,example/security:latest,false\r\n", buf.String())buf.Reset()require.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(nil)))diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.goindex 5c3a40834..fdb96d5b7 100644--- a/backend/internal/vulnerability/vulnerability_ignores.go+++ b/backend/internal/vulnerability/vulnerability_ignores.go@@ -3,11 +3,12 @@ package vulnerabilityimport ("cmp""context"+ "errors"+ "fmt""log/slog""slices""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/vulnerability"@@ -72,7 +73,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st}if !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, errors.WrapIf(err, "failed to check existing ignore")+ return nil, fmt.Errorf("failed to check existing ignore: %w", err)}ignore := &VulnerabilityIgnore{@@ -86,7 +87,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st}if err := s.db.WithContext(ctx).Create(ignore).Error; err != nil {- return nil, errors.WrapIf(err, "failed to create ignore record")+ return nil, fmt.Errorf("failed to create ignore record: %w", err)}slog.InfoContext(ctx, "vulnerability ignored",@@ -109,7 +110,7 @@ func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID,if errors.Is(err, gorm.ErrRecordNotFound) {return errors.New("ignore record not found")}- return errors.WrapIf(err, "failed to load ignore record")+ return fmt.Errorf("failed to load ignore record: %w", err)}result := s.db.WithContext(ctx).Where(@@ -117,7 +118,7 @@ func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID,envID, ignore.ImageID, ignore.VulnerabilityID, ignore.PkgName, ignore.InstalledVersion,).Delete(&VulnerabilityIgnore{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete ignore record")+ return fmt.Errorf("failed to delete ignore record: %w", result.Error)}slog.InfoContext(ctx, "vulnerability unignored", "ignore_id", ignoreID)@@ -157,7 +158,7 @@ func (s *VulnerabilityService) BulkIgnoreVulnerabilities(ctx context.Context, en_, q := s.listAllVulnerabilitiesQueryInternal(ctx, tx, envID, ¶ms)var targets []VulnerabilityScanItemif err := q.Distinct("vulnerability_scan_items.image_id", "vulnerability_scan_items.vulnerability_id", "vulnerability_scan_items.pkg_name", "vulnerability_scan_items.installed_version").Scan(&targets).Error; err != nil {- return errors.WrapIf(err, "failed to resolve vulnerabilities to ignore")+ return fmt.Errorf("failed to resolve vulnerabilities to ignore: %w", err)}if len(targets) == 0 {return nil@@ -173,7 +174,10 @@ func (s *VulnerabilityService) BulkIgnoreVulnerabilities(ctx context.Context, enCreatedBy: createdBy,})}- return errors.WrapIf(tx.CreateInBatches(&ignores, bulkIgnoreBatchSizeInternal).Error, "failed to create ignore records")+ if err := tx.CreateInBatches(&ignores, bulkIgnoreBatchSizeInternal).Error; err != nil {+ return fmt.Errorf("failed to create ignore records: %w", err)+ }+ return nil})if err != nil {return 0, err@@ -195,12 +199,12 @@ func (s *VulnerabilityService) BulkUnignoreVulnerabilities(ctx context.Context,_, q := s.listAllVulnerabilitiesQueryInternal(ctx, tx, envID, ¶ms)var ignoreIDs []stringif err := q.Distinct("vulnerability_ignores.id").Pluck("vulnerability_ignores.id", &ignoreIDs).Error; err != nil {- return errors.WrapIf(err, "failed to resolve ignored vulnerabilities to restore")+ return fmt.Errorf("failed to resolve ignored vulnerabilities to restore: %w", err)}for batch := range slices.Chunk(ignoreIDs, bulkIgnoreBatchSizeInternal) {result := tx.Where("environment_id = ? AND id IN ?", envID, batch).Delete(&VulnerabilityIgnore{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete ignore records")+ return fmt.Errorf("failed to delete ignore records: %w", result.Error)}affected += result.RowsAffected}@@ -295,13 +299,13 @@ func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, e// Count totalvar total int64if err := query.Model(&VulnerabilityIgnore{}).Count(&total).Error; err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to count ignored vulnerabilities")+ return nil, pagination.Response{}, fmt.Errorf("failed to count ignored vulnerabilities: %w", err)}// Apply paginationoffset := params.Startif err := query.Offset(offset).Limit(params.Limit).Find(&ignores).Error; err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list ignored vulnerabilities")+ return nil, pagination.Response{}, fmt.Errorf("failed to list ignored vulnerabilities: %w", err)}result := mapIgnoredVulnerabilities(ignores)@@ -318,8 +322,7 @@ func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envvar ignores []VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ?", envID, imageID).Find(&ignores).Error; err != nil {- return nil, errors.WrapIf(err, "failed to get ignore records")+ return nil, fmt.Errorf("failed to get ignore records: %w", err)}-return ignores, nil}diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.goindex fdd085dab..9cfc5ab05 100644--- a/backend/internal/vulnerability/vulnerability_query.go+++ b/backend/internal/vulnerability/vulnerability_query.go@@ -3,16 +3,20 @@ package vulnerabilityimport ("cmp""context"+ "encoding/csv""encoding/json/v2"+ "errors"+ "fmt"+ "io""iter""log/slog""math""slices""sort"+ "strconv""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -34,7 +38,7 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, envID, imageIDvulns, err := s.filterIgnoredVulnerabilitiesForImage(ctx, envID, result.ImageID, result.Vulnerabilities)if err != nil {- return nil, errors.WrapIf(err, "failed to filter ignored vulnerabilities")+ return nil, fmt.Errorf("failed to filter ignored vulnerabilities: %w", err)}intel := map[string]vuln.ThreatIntel{}intelStatus := s.threatIntelStatusInternal(ctx)@@ -68,7 +72,7 @@ func (s *VulnerabilityService) loadScanResultInternal(ctx context.Context, imageif errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, errors.WrapIf(err, "failed to get scan result")+ return nil, fmt.Errorf("failed to get scan result: %w", err)}s.markStaleScanIfNeeded(ctx, &record)@@ -96,7 +100,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strinif errors.Is(err, gorm.ErrRecordNotFound) {return nil, nil}- return nil, errors.WrapIf(err, "failed to get scan summary")+ return nil, fmt.Errorf("failed to get scan summary: %w", err)}s.markStaleScanIfNeeded(ctx, &record)@@ -124,7 +128,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.loadScanResultInternal(ctx, imageID)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to get scan result")+ return nil, pagination.Response{}, fmt.Errorf("failed to get scan result: %w", err)}if result == nil {return nil, pagination.Response{}, common.ErrVulnerabilityScanNotFound@@ -236,7 +240,7 @@ func (s *VulnerabilityService) GetEnvironmentSummary(ctx context.Context) (*vuln}err := aggQuery.Scan(&agg).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to aggregate vulnerability summary")+ return nil, fmt.Errorf("failed to aggregate vulnerability summary: %w", err)}summary.ScannedImages = agg.Scanned@@ -283,7 +287,7 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.Contevar ignoreCount int64if err := s.db.WithContext(ctx).Model(&VulnerabilityIgnore{}).Count(&ignoreCount).Error; err != nil {- return 0, errors.WrapIf(err, "failed to count ignore records")+ return 0, fmt.Errorf("failed to count ignore records: %w", err)}currentImageIDs, haveCurrentImages := s.currentImageIDsInternal(ctx)@@ -297,7 +301,7 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.ContesumQuery = sumQuery.Where("id IN ?", currentImageIDs)}if err := sumQuery.Scan(&indexedCount).Error; err != nil {- return 0, errors.WrapIf(err, "failed to sum vulnerability counts")+ return 0, fmt.Errorf("failed to sum vulnerability counts: %w", err)}return int(indexedCount), nil}@@ -310,11 +314,10 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.ContecountQuery = countQuery.Where("vulnerability_scan_items.image_id IN ?", currentImageIDs)}var count int64- err := countQuery.- Where("NOT EXISTS (SELECT 1 FROM vulnerability_ignores WHERE vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version)").+ err := countQuery.Where("NOT EXISTS (SELECT 1 FROM vulnerability_ignores WHERE vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version)").Count(&count).Errorif err != nil {- return 0, errors.WrapIf(err, "failed to count actionable vulnerabilities")+ return 0, fmt.Errorf("failed to count actionable vulnerabilities: %w", err)}return int(count), nil}@@ -398,13 +401,13 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envIDvar totalAvailable int64if err := base.Count(&totalAvailable).Error; err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to count vulnerabilities")+ return nil, pagination.Response{}, fmt.Errorf("failed to count vulnerabilities: %w", err)}var rows []vulnerabilityScanItemRowInternalresponse, err := pagination.PaginateAndSortDB(params, q, &rows)if err != nil {- return nil, pagination.Response{}, errors.WrapIf(err, "failed to list vulnerabilities")+ return nil, pagination.Response{}, fmt.Errorf("failed to list vulnerabilities: %w", err)}response.GrandTotalItems = totalAvailable@@ -450,7 +453,7 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID_, q := s.listAllVulnerabilitiesQueryInternal(ctx, s.db.DB, envID, ¶ms)rows, err := q.Rows()if err != nil {- return nil, errors.WrapIf(err, "failed to export vulnerabilities")+ return nil, fmt.Errorf("failed to export vulnerabilities: %w", err)}return func(yield func(vulnerability.VulnerabilityWithImage, error) bool) {@@ -463,7 +466,7 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envIDfor rows.Next() {var row vulnerabilityScanItemRowInternalif err := q.ScanRows(rows, &row); err != nil {- yield(vulnerability.VulnerabilityWithImage{}, errors.WrapIf(err, "failed to export vulnerabilities"))+ yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", err))return}item := vulnerability.VulnerabilityWithImage{@@ -485,7 +488,7 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID}}if err := rows.Err(); err != nil {- yield(vulnerability.VulnerabilityWithImage{}, errors.WrapIf(err, "failed to export vulnerabilities"))+ yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", err))}}, nil}@@ -534,7 +537,7 @@ func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Contvar records []VulnerabilityScanRecordif err := query.Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list vulnerability image options")+ return nil, fmt.Errorf("failed to list vulnerability image options: %w", err)}options := make([]string, 0, len(records))@@ -626,7 +629,7 @@ func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, iWhere("id IN ?", imageIDs).Find(&records).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to get scan summaries")+ return nil, fmt.Errorf("failed to get scan summaries: %w", err)}result := make(map[string]*vulnerability.ScanSummary, len(records))@@ -965,7 +968,7 @@ func (s *VulnerabilityService) computeRiskInternal(ctx context.Context, envID st}var scannedIDs []stringif err := scanQuery.Pluck("id", &scannedIDs).Error; err != nil {- return nil, errors.WrapIf(err, "failed to list scanned images")+ return nil, fmt.Errorf("failed to list scanned images: %w", err)}var rows []riskFindingRowInternal@@ -982,7 +985,7 @@ func (s *VulnerabilityService) computeRiskInternal(ctx context.Context, envID st).Scan(&rows).Errorif err != nil {- return nil, errors.WrapIf(err, "failed to load vulnerability risk findings")+ return nil, fmt.Errorf("failed to load vulnerability risk findings: %w", err)}acc := &riskAccumulatorInternal{@@ -1040,7 +1043,7 @@ func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID stringWhere("snapshot_date >= ?", now.AddDate(0, 0, -(riskTrendDays-1)).Format(riskDateLayout)).Order("snapshot_date ASC").Find(&snapshots).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load risk snapshots")+ return nil, fmt.Errorf("failed to load risk snapshots: %w", err)}deltaDay := now.AddDate(0, 0, -riskDeltaDays).Format(riskDateLayout)@@ -1071,3 +1074,35 @@ func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID stringreturn overview, nil}++var vulnerabilityCSVHeaderInternal = []string{"CVE", "Severity", "Package", "Installed Version", "Fixed Version", "Image", "Ignored"}++// WriteVulnerabilitiesCSV streams items to w as a BOM-prefixed, CRLF-terminated CSV with formula-safe cells.+func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.VulnerabilityWithImage, error]) error {+ if _, err := io.WriteString(w, "\xEF\xBB\xBF"); err != nil {+ return fmt.Errorf("failed to write csv: %w", err)+ }+ writer := csv.NewWriter(w)+ writer.UseCRLF = true+ if err := writer.Write(vulnerabilityCSVHeaderInternal); err != nil {+ return fmt.Errorf("failed to write csv: %w", err)+ }+ for item, err := range items {+ if err != nil {+ return err+ }+ image := cmp.Or(item.ImageName, item.ImageID)+ record := []string{item.VulnerabilityID, string(item.Severity), item.PkgName, item.InstalledVersion, item.FixedVersion, image, strconv.FormatBool(item.Ignored)}+ for j, value := range record {+ record[j] = kit.Ternary(value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])), "'"+value, value)+ }+ if err := writer.Write(record); err != nil {+ return fmt.Errorf("failed to write csv: %w", err)+ }+ }+ writer.Flush()+ if err := writer.Error(); err != nil {+ return fmt.Errorf("failed to write csv: %w", err)+ }+ return nil+}diff --git a/backend/internal/vulnerability/vulnerability_scan.go b/backend/internal/vulnerability/vulnerability_scan.goindex b20b17eda..69e2d0253 100644--- a/backend/internal/vulnerability/vulnerability_scan.go+++ b/backend/internal/vulnerability/vulnerability_scan.go@@ -3,6 +3,7 @@ package vulnerabilityimport ("cmp""context"+ "errors""fmt""log/slog""strings"@@ -10,7 +11,6 @@ import ("sync/atomic""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -103,13 +103,13 @@ func (s *VulnerabilityService) ScanImage(ctx context.Context, envID, imageID str// Get Docker client to inspect the imagedockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}// Inspect the image to get detailsimageInspect, err := dockerClient.ImageInspect(scanCtx, imageID)if err != nil {- return nil, errors.WrapIf(err, "failed to inspect image")+ return nil, fmt.Errorf("failed to inspect image: %w", err)}// Determine image name to scan@@ -565,7 +565,7 @@ func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string,}images, err := s.dockerService.ListImages(ctx)if err != nil {- return 0, 0, errors.WrapIf(err, "failed to list images")+ return 0, 0, fmt.Errorf("failed to list images: %w", err)}targets := make([]scheduledScanTargetInternal, 0, len(images))@@ -634,7 +634,7 @@ func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string,}if featureStopped.Load() {- return scanned, failed, errors.WrapIff(common.ErrFeatureDisabled, "remaining scans stopped because feature %s was disabled", features.VulnerabilityManagement)+ return scanned, failed, fmt.Errorf("remaining scans stopped because feature %s was disabled: %w", features.VulnerabilityManagement, common.ErrFeatureDisabled)}s.sendScheduledVulnerabilitySummaryInternal(ctx, scanned, notificationSummary)@@ -656,7 +656,7 @@ func (s *VulnerabilityService) skipRecentlyScannedTargetsInternal(ctx context.CoSelect("id", "image_name", "status", "scan_time", "scanner_version", "scan_policy").Where("id IN ?", ids).Find(&records).Error; err != nil {- return nil, errors.WrapIf(err, "failed to load existing scan records")+ return nil, fmt.Errorf("failed to load existing scan records: %w", err)}cutoff := time.Now().Add(-scheduledScanMaxAge)diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex 985a396ca..8b5fa838a 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -3,6 +3,7 @@ package vulnerabilityimport ("context""encoding/json/v2"+ "errors""fmt""io""io/fs"@@ -13,7 +14,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"@@ -136,7 +136,7 @@ func buildScanItemsInternal(imageID string, vulns []vulnerability.Vulnerability)LastModifiedDate: v.LastModifiedDate,})if err != nil {- return nil, errors.WrapIf(err, "failed to marshal vulnerability details")+ return nil, fmt.Errorf("failed to marshal vulnerability details: %w", err)}item.Details = new(string(raw))}@@ -250,7 +250,7 @@ func (s *VulnerabilityService) CleanupOrphanedScanRecords(ctx context.Context) (images, err := s.dockerService.ListImages(ctx)if err != nil {- return 0, errors.WrapIf(err, "failed to list images")+ return 0, fmt.Errorf("failed to list images: %w", err)}currentIDs := make(map[string]struct{}, len(images))@@ -399,7 +399,7 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulneif len(result.Vulnerabilities) > 0 {vulnBytes, err := json.Marshal(result.Vulnerabilities)if err != nil {- return errors.WrapIf(err, "failed to marshal vulnerabilities")+ return fmt.Errorf("failed to marshal vulnerabilities: %w", err)}vulnJSON = database.StringSlice{string(vulnBytes)}}@@ -450,7 +450,7 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulnereturn err}if err := tx.Where("image_id = ?", result.ImageID).Delete(&VulnerabilityScanItem{}).Error; err != nil {- return errors.WrapIf(err, "failed to clear scan items")+ return fmt.Errorf("failed to clear scan items: %w", err)}if record.Status != ScanStatusCompleted || len(result.Vulnerabilities) == 0 {return nil@@ -459,7 +459,10 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulneif err != nil {return err}- return errors.WrapIf(tx.CreateInBatches(items, scanItemInsertBatchSizeInternal).Error, "failed to store scan items")+ if err := tx.CreateInBatches(items, scanItemInsertBatchSizeInternal).Error; err != nil {+ return fmt.Errorf("failed to store scan items: %w", err)+ }+ return nil})}@@ -561,7 +564,7 @@ func (s *VulnerabilityService) SyncThreatIntel(ctx context.Context, force bool)Where("known_exploited = ? AND NOT EXISTS (SELECT 1 FROM vulnerability_scan_items WHERE vulnerability_scan_items.vulnerability_id = vulnerability_threat_intel.cve_id)", false).Delete(&VulnerabilityThreatIntel{}).Error- syncErr := errors.Combine(kevErr, epssErr, pruneErr)+ syncErr := errors.Join(kevErr, epssErr, pruneErr)if syncErr == nil {state.LastSyncedAt = new(time.Now())state.LastError = ""@@ -584,21 +587,21 @@ func (s *VulnerabilityService) SyncThreatIntel(ctx context.Context, force bool)func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string) (string, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.kevFeedURL, nil)if err != nil {- return "", errors.WrapIf(err, "failed to build KEV request")+ return "", fmt.Errorf("failed to build KEV request: %w", err)}if etag != "" {req.Header.Set("If-None-Match", etag)}resp, err := s.httpClient.Do(req)if err != nil {- return "", errors.WrapIf(err, "failed to fetch KEV catalog")+ return "", fmt.Errorf("failed to fetch KEV catalog: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode == http.StatusNotModified {return etag, nil}if resp.StatusCode != http.StatusOK {- return "", errors.Errorf("KEV catalog returned HTTP %d", resp.StatusCode)+ return "", fmt.Errorf("KEV catalog returned HTTP %d", resp.StatusCode)}var feed struct {@@ -610,7 +613,7 @@ func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string)} `json:"vulnerabilities"`}if err := json.UnmarshalRead(io.LimitReader(resp.Body, kevFeedMaxBytes), &feed); err != nil {- return "", errors.WrapIf(err, "failed to decode KEV catalog")+ return "", fmt.Errorf("failed to decode KEV catalog: %w", err)}now := time.Now()@@ -632,10 +635,10 @@ func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string)// The catalog only grows, so an empty or much smaller feed is a bad response; keep the cached flags.var cached int64if err := s.db.WithContext(ctx).Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Count(&cached).Error; err != nil {- return "", errors.WrapIf(err, "failed to count cached KEV entries")+ return "", fmt.Errorf("failed to count cached KEV entries: %w", err)}if len(rows) == 0 || int64(len(rows)) < cached/2 {- return "", errors.Errorf("KEV catalog looks incomplete (%d entries, %d cached); keeping cached data", len(rows), cached)+ return "", fmt.Errorf("KEV catalog looks incomplete (%d entries, %d cached); keeping cached data", len(rows), cached)}err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {@@ -650,7 +653,7 @@ func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string)}).CreateInBatches(rows, threatIntelUpsertBatch).Error})if err != nil {- return "", errors.WrapIf(err, "failed to store KEV catalog")+ return "", fmt.Errorf("failed to store KEV catalog: %w", err)}return resp.Header.Get("ETag"), nil}@@ -666,7 +669,7 @@ func (s *VulnerabilityService) syncEPSSInternal(ctx context.Context) error {Where("vulnerability_threat_intel.epss_checked_at IS NULL OR vulnerability_threat_intel.epss_checked_at < ?", time.Now().Add(-threatIntelSyncInterval)).Limit(epssMaxCVEsPerSync).Pluck("vulnerability_scan_items.vulnerability_id", &cveIDs).Error; err != nil {- return errors.WrapIf(err, "failed to list CVEs for EPSS")+ return fmt.Errorf("failed to list CVEs for EPSS: %w", err)}for start := 0; start < len(cveIDs); {@@ -695,11 +698,11 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveIDfor attempt := 0; ; attempt++ {req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.epssAPIURL+"?cve="+strings.Join(cveIDs, ","), nil)if err != nil {- return errors.WrapIf(err, "failed to build EPSS request")+ return fmt.Errorf("failed to build EPSS request: %w", err)}resp, err = s.httpClient.Do(req)if err != nil {- return errors.WrapIf(err, "failed to fetch EPSS scores")+ return fmt.Errorf("failed to fetch EPSS scores: %w", err)}if resp.StatusCode != http.StatusTooManyRequests || attempt > 0 {break@@ -719,7 +722,7 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveID}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {- return errors.Errorf("EPSS API returned HTTP %d", resp.StatusCode)+ return fmt.Errorf("EPSS API returned HTTP %d", resp.StatusCode)}var payload struct {@@ -730,7 +733,7 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveID} `json:"data"`}if err := json.UnmarshalRead(resp.Body, &payload); err != nil {- return errors.WrapIf(err, "failed to decode EPSS scores")+ return fmt.Errorf("failed to decode EPSS scores: %w", err)}now := time.Now()@@ -754,10 +757,13 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveIDfor _, row := range rows {batch = append(batch, *row)}- return errors.WrapIf(s.db.WithContext(ctx).Clauses(clause.OnConflict{+ if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "cve_id"}},DoUpdates: clause.AssignmentColumns([]string{"epss_score", "epss_percentile", "epss_checked_at", "updated_at"}),- }).Create(&batch).Error, "failed to store EPSS scores")+ }).Create(&batch).Error; err != nil {+ return fmt.Errorf("failed to store EPSS scores: %w", err)+ }+ return nil}// threatIntelStatusInternal reports whether threat intelligence is enabled and when it last synced.@@ -809,9 +815,12 @@ func (s *VulnerabilityService) RecordRiskSnapshot(ctx context.Context) error {Columns: []clause.Column{{Name: "snapshot_date"}},DoUpdates: clause.AssignmentColumns([]string{"scoring_version", "risk_score", "risk_band", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "findings_count", "known_exploited_count", "overdue_known_exploited_count", "high_epss_count", "exposed_critical_high_count", "fixable_count", "images_scanned", "images_total", "scored_images", "updated_at"}),}).Create(&snapshot).Error; err != nil {- return errors.WrapIf(err, "failed to store risk snapshot")+ return fmt.Errorf("failed to store risk snapshot: %w", err)+ }+ if err := tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).+ Delete(&VulnerabilityRiskSnapshot{}).Error; err != nil {+ return fmt.Errorf("failed to prune risk snapshots: %w", err)}- return errors.WrapIf(tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).- Delete(&VulnerabilityRiskSnapshot{}).Error, "failed to prune risk snapshots")+ return nil})}diff --git a/backend/internal/vulnerability/vulnerability_trivy.go b/backend/internal/vulnerability/vulnerability_trivy.goindex b3b43ffef..d620f3224 100644--- a/backend/internal/vulnerability/vulnerability_trivy.go+++ b/backend/internal/vulnerability/vulnerability_trivy.go@@ -3,6 +3,8 @@ package vulnerabilityimport ("cmp""context"+ "encoding/json"+ "errors""fmt""io""log/slog"@@ -11,7 +13,6 @@ import ("sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -169,12 +170,12 @@ func (s *VulnerabilityService) setupTrivyBatchContainersInternal(ctx context.Con}dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, nil, nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, nil, nil, fmt.Errorf("failed to connect to Docker: %w", err)}scannerImage, err := s.ensureTrivyImageInternal(ctx)if err != nil {- return nil, nil, nil, errors.WrapIf(err, "trivy scanner not available")+ return nil, nil, nil, fmt.Errorf("trivy scanner not available: %w", err)}serverURL, _ := s.getTrivyServerConfig()@@ -182,7 +183,7 @@ func (s *VulnerabilityService) setupTrivyBatchContainersInternal(ctx context.Conif serverURL == "" {cacheVolume, err = s.ensureTrivyCacheVolumeInternal(ctx)if err != nil {- return nil, nil, nil, errors.WrapIf(err, "failed to ensure trivy cache volume")+ return nil, nil, nil, fmt.Errorf("failed to ensure trivy cache volume: %w", err)}}@@ -198,7 +199,7 @@ func (s *VulnerabilityService) setupTrivyBatchContainersInternal(ctx context.ConcontainerID, createErr := s.createBatchTrivyContainer(ctx, scannerImage, cacheVolume, files)if createErr != nil {cleanup()- return nil, nil, nil, errors.WrapIf(createErr, "failed to create batch trivy container")+ return nil, nil, nil, fmt.Errorf("failed to create batch trivy container: %w", createErr)}containerIDs = append(containerIDs, containerID)}@@ -236,7 +237,7 @@ func (s *VulnerabilityService) scanSingleImage(func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, scannerImage, cacheVolume string, files map[string][]byte) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}runtimeOptions, err := s.resolveTrivyRuntimeOptionsInternal(ctx, dockerClient)@@ -285,18 +286,18 @@ func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, scfunc (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, containerID, imageName, imageID, scannerVersion string, slotID int, files map[string][]byte) (*vulnerability.ScanResult, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}stdoutFile, err := vuln.CreateLogTempFile("trivy-exec-stdout-*")if err != nil {- return nil, errors.WrapIf(err, "failed to create trivy exec stdout temp file")+ return nil, fmt.Errorf("failed to create trivy exec stdout temp file: %w", err)}stderrFile, err := vuln.CreateLogTempFile("trivy-exec-stderr-*")if err != nil {vuln.CleanupLogTempFiles(ctx, stdoutFile)- return nil, errors.WrapIf(err, "failed to create trivy exec stderr temp file")+ return nil, fmt.Errorf("failed to create trivy exec stderr temp file: %w", err)}defer vuln.CleanupLogTempFiles(ctx, stdoutFile, stderrFile)@@ -369,7 +370,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, con"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.Errorf("trivy scan failed: %s", errMsg)+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)}slog.WarnContext(ctx,@@ -381,7 +382,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, con"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.WrapIf(err, "failed to parse trivy output")+ return nil, fmt.Errorf("failed to parse trivy output: %w", err)}if trivyReport == nil {@@ -395,7 +396,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, con"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.Errorf("trivy scan failed: %s", errMsg)+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)}result := vulnerability.ConvertTrivyReportToScanResult(trivyReport, imageID, time.Now(), 0)@@ -593,7 +594,7 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.CodockerHost := s.getEffectiveDockerHostInternal()scheme, socketPath, err := vuln.ParseDockerHost(dockerHost)if err != nil {- return vuln.RuntimeOptions{}, errors.WrapIf(err, "failed to resolve trivy docker host")+ return vuln.RuntimeOptions{}, fmt.Errorf("failed to resolve trivy docker host: %w", err)}options.ContainerEnv = vuln.BuildDockerHostEnv(dockerHost)@@ -616,7 +617,7 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.Co},)if err != nil {- return vuln.RuntimeOptions{}, errors.WrapIf(err, "failed to resolve trivy docker host")+ return vuln.RuntimeOptions{}, fmt.Errorf("failed to resolve trivy docker host: %w", err)}options.Mounts = append(options.Mounts, mounttypes.Mount{@@ -667,7 +668,7 @@ func (s *VulnerabilityService) getTrivySingleScanCacheDirForSlotInternal(slotIDfunc (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return "", errors.WrapIf(err, "failed to connect to Docker")+ return "", fmt.Errorf("failed to connect to Docker: %w", err)}scannerImage := s.getTrivyImageRef()@@ -686,13 +687,13 @@ func (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (stpullReader, err := dockerClient.ImagePull(pullCtx, scannerImage, client.ImagePullOptions{})if err != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- return "", errors.Errorf("scanner image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", scannerImage)+ return "", fmt.Errorf("scanner image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", scannerImage)}- return "", errors.WrapIff(err, "pull scanner image %s", scannerImage)+ return "", fmt.Errorf("pull scanner image %s: %w", scannerImage, err)}if err := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); err != nil {_ = pullReader.Close()- return "", errors.WrapIf(err, "failed to complete scanner image pull")+ return "", fmt.Errorf("failed to complete scanner image pull: %w", err)}_ = pullReader.Close()@@ -716,7 +717,7 @@ func (s *VulnerabilityService) ensureTrivyCacheVolumeInternal(ctx context.Contex},})if err != nil {- return "", errors.WrapIf(err, "failed to create trivy cache volume")+ return "", fmt.Errorf("failed to create trivy cache volume: %w", err)}return trivyCacheVolumeName, nil@@ -820,13 +821,13 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal(})if err != nil {slog.WarnContext(ctx, "failed to create trivy container", "scope", scope, "error", err)- return "", errors.WrapIf(err, "failed to create container")+ return "", fmt.Errorf("failed to create container: %w", err)}if err := vuln.CopyFilesToContainer(ctx, dockerClient, resp.ID, vuln.ContainerFilesDir, files); err != nil {if files[vuln.TrivyConfigFile] != nil || files[vuln.TrivyIgnoreFile] != nil {vuln.RemoveContainer(ctx, dockerClient, resp.ID, "failed to cleanup trivy container after file copy failure")- return "", errors.WrapIf(err, "failed to copy scan files into container")+ return "", fmt.Errorf("failed to copy scan files into container: %w", err)}// DOCKER_CONFIG may still point at the target directory. When the// config file is absent, Trivy falls back to anonymous registry access.@@ -853,7 +854,7 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal()vuln.RemoveContainer(ctx, dockerClient, resp.ID, "failed to cleanup trivy container after start failure")- return "", errors.WrapIf(err, "failed to start container")+ return "", fmt.Errorf("failed to start container: %w", err)}return resp.ID, nil@@ -874,7 +875,7 @@ func (s *VulnerabilityService) getTrivyContainerResourceOptionsInternal(ctx contreturn resources, "", applyLimits, nil}if dockerClient == nil {- return containertypes.Resources{}, "", false, errors.New("Docker client is required to determine Trivy CPU limits")+ return containertypes.Resources{}, "", false, errors.New("Docker client is required to determine Trivy CPU limits") //nolint:staticcheck // Preserve the existing error message.}if err := ctx.Err(); err != nil {return containertypes.Resources{}, "", false, err@@ -952,13 +953,13 @@ func (s *VulnerabilityService) runTrivyContainer() (*os.File, *os.File, int64, int64, string, error) {stdoutFile, err := vuln.CreateLogTempFile("trivy-stdout-*")if err != nil {- return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to create trivy stdout temp file")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stdout temp file: %w", err)}stderrFile, err := vuln.CreateLogTempFile("trivy-stderr-*")if err != nil {vuln.CleanupLogTempFiles(ctx, stdoutFile)- return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to create trivy stderr temp file")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stderr temp file: %w", err)}success := false@@ -972,7 +973,7 @@ func (s *VulnerabilityService) runTrivyContainer(containerID, err = s.createAndStartTrivyContainerInternal(ctx, dockerClient, "single-scan", config, hostConfig, files)if err != nil {- return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to prepare trivy scan container")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to prepare trivy scan container: %w", err)}slog.DebugContext(ctx, "started trivy scan container", "containerId", containerID)@@ -986,7 +987,7 @@ func (s *VulnerabilityService) runTrivyContainer(})if err != nil {logsCancel()- return nil, nil, 0, 0, "", errors.WrapIf(err, "failed to stream trivy logs")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to stream trivy logs: %w", err)}var closeLogsOnce sync.Once@@ -1033,14 +1034,14 @@ func (s *VulnerabilityService) runTrivyContainer(case logErr := <-logDone:closeLogs() // clean up context / connectionif logErr != nil && !dockerutils.IsExpectedStreamEndError(logErr) {- return nil, nil, 0, 0, "", errors.WrapIf(logErr, "failed to read trivy logs")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)}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 := dockerutils.WaitStdCopy(logDone); logErr != nil {- return nil, nil, 0, 0, "", errors.WrapIf(logErr, "failed to read trivy logs")+ return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)}}@@ -1059,12 +1060,12 @@ func (s *VulnerabilityService) waitForTrivyContainer(statusCode, err := vuln.AwaitContainerWaitResponse(ctx, waitResult.Result, waitResult.Error)if err != nil {if errors.Is(err, context.DeadlineExceeded) {- return 0, errors.WrapIf(err, "trivy container wait timed out")+ return 0, fmt.Errorf("trivy container wait timed out: %w", err)}if errors.Is(err, context.Canceled) {- return 0, errors.WrapIf(err, "scan cancelled")+ return 0, fmt.Errorf("scan cancelled: %w", err)}- return 0, errors.WrapIf(err, "trivy container wait failed")+ return 0, fmt.Errorf("trivy container wait failed: %w", err)}return statusCode, nil@@ -1080,7 +1081,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scannerdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- return nil, errors.WrapIf(err, "failed to connect to Docker")+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}serverURL, serverToken := s.getTrivyServerConfig()@@ -1195,7 +1196,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.Errorf("trivy scan failed: %s", errMsg)+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)}slog.WarnContext(ctx,@@ -1207,7 +1208,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.WrapIf(err, "failed to parse trivy output")+ return nil, fmt.Errorf("failed to parse trivy output: %w", err)}if trivyReport == nil {@@ -1221,7 +1222,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner"stdoutBytes", vuln.TempFileSize(stdoutFile),"stderrBytes", vuln.TempFileSize(stderrFile),)- return nil, errors.Errorf("trivy scan failed: %s", errMsg)+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)}// Convert Trivy report to our ScanResult format@@ -1244,3 +1245,59 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scannerreturn result, nil}++type trivyCPUCapabilitiesInternal struct {+ Quota bool `json:"quota"`+ CPUSet bool `json:"cpuSet"`+ CPUs int `json:"cpus"`+ FetchedAt time.Time `json:"fetchedAt"`+}++func (s *VulnerabilityService) getTrivyCPUCapabilitiesInternal(ctx context.Context, dockerClient *client.Client) (trivyCPUCapabilitiesInternal, error) {+ key := "trivy:cpu-capabilities:v1:" + kit.SHA256Hex(dockerClient.DaemonHost()+"\x00"+dockerClient.ClientVersion())+ var cached trivyCPUCapabilitiesInternal+ if s.kvService != nil {+ raw, found, err := s.kvService.Get(ctx, key)+ if err != nil {+ slog.WarnContext(ctx, "failed to read cached Trivy CPU capabilities", "error", err)+ } else if found {+ if err := json.Unmarshal([]byte(raw), &cached); err != nil || cached.FetchedAt.IsZero() {+ slog.WarnContext(ctx, "ignoring invalid cached Trivy CPU capabilities", "error", err)+ cached = trivyCPUCapabilitiesInternal{}+ } else if age := time.Since(cached.FetchedAt); age >= 0 && age < trivyCPUCapabilitiesCacheTTL {+ return cached, nil+ }+ }+ }++ infoCtx, cancel := context.WithTimeout(ctx, trivyCPUCapabilitiesLookupTimeout)+ defer cancel()+ info, err := dockerClient.Info(infoCtx, client.InfoOptions{})+ if err != nil {+ if ctx.Err() != nil {+ return trivyCPUCapabilitiesInternal{}, ctx.Err()+ }+ if !cached.FetchedAt.IsZero() {+ slog.WarnContext(ctx, "failed to refresh Trivy CPU capabilities; using cached capabilities", "error", err)+ return cached, nil+ }+ return trivyCPUCapabilitiesInternal{}, err+ }++ capabilities := trivyCPUCapabilitiesInternal{+ Quota: info.Info.CPUCfsQuota && !vuln.IsSynologyDockerHost(info.Info.OperatingSystem),+ CPUSet: info.Info.CPUSet,+ CPUs: info.Info.NCPU,+ FetchedAt: time.Now().UTC(),+ }+ if s.kvService != nil {+ payload, err := json.Marshal(capabilities)+ if err == nil {+ err = s.kvService.Set(ctx, key, string(payload))+ }+ if err != nil {+ slog.WarnContext(ctx, "failed to cache Trivy CPU capabilities", "error", err)+ }+ }+ return capabilities, nil+}diff --git a/backend/internal/webhook/handler.go b/backend/internal/webhook/handler.goindex 983290dd8..a02554c25 100644--- a/backend/internal/webhook/handler.go+++ b/backend/internal/webhook/handler.go@@ -2,9 +2,9 @@ package webhookimport ("context"+ "errors""net/http"- "emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"diff --git a/backend/internal/webhook/webhook.go b/backend/internal/webhook/webhook.goindex 8801e791f..6010bc70a 100644--- a/backend/internal/webhook/webhook.go+++ b/backend/internal/webhook/webhook.go@@ -6,6 +6,7 @@ import ("crypto/rand""encoding/base64""encoding/hex"+ "errors""fmt""log/slog""net/http"@@ -14,8 +15,6 @@ import ("sync""time"- "emperror.dev/emperror"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -36,13 +35,6 @@ import ()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")-webhookTokenPrefix = "arc_wh_"webhookTokenLength = 32 // raw bytes → 64 hex charswebhookTokenPrefixLen = 8 // chars of the hex portion used as lookup prefix@@ -50,6 +42,15 @@ const (webhookTokenHexLen = 2 * (12 + webhookTokenLength*2 + 16))+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")+)+type WebhookService struct {tokenWriteMu sync.MutextokenMu sync.RWMutex@@ -90,16 +91,16 @@ func isRemoteWebhookEnvironmentInternal(environmentID string) bool {func generateWebhookTokenInternal() (raw, hash, prefix string, err error) {b := make([]byte, webhookTokenLength)if _, err = rand.Read(b); err != nil {- return "", "", "", errors.WrapIf(err, "failed to generate webhook token")+ return "", "", "", fmt.Errorf("failed to generate webhook token: %w", err)}secretHex := hex.EncodeToString(b)encrypted, err := libcrypto.Encrypt(secretHex)if err != nil {- return "", "", "", errors.WrapIf(err, "failed to encrypt webhook token")+ return "", "", "", fmt.Errorf("failed to encrypt webhook token: %w", err)}encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)if err != nil {- return "", "", "", errors.WrapIf(err, "failed to decode encrypted webhook token")+ return "", "", "", fmt.Errorf("failed to decode encrypted webhook token: %w", err)}tokenHex := hex.EncodeToString(encryptedBytes)raw = webhookTokenPrefix + tokenHex@@ -124,7 +125,7 @@ func (s *WebhookService) LoadTokenHashes(ctx context.Context) error {var hashes []stringif err := s.db.WithContext(ctx).Model(&Webhook{}).Pluck("token_hash", &hashes).Error; err != nil {- return errors.WrapIf(err, "failed to load webhook token hashes")+ return fmt.Errorf("failed to load webhook token hashes: %w", err)}s.tokenMu.Lock()defer s.tokenMu.Unlock()@@ -259,7 +260,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, acs.tokenWriteMu.Lock()defer s.tokenWriteMu.Unlock()if err := s.db.WithContext(ctx).Create(wh).Error; err != nil {- return nil, "", errors.WrapIf(err, "failed to create webhook")+ return nil, "", fmt.Errorf("failed to create webhook: %w", err)}s.tokenMu.Lock()@@ -294,7 +295,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, errors.WrapIf(err, "failed to list webhooks")+ return nil, fmt.Errorf("failed to list webhooks: %w", err)}return webhooks, nil}@@ -386,7 +387,7 @@ func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID sreturn nil, ErrWebhookNotFound}if err != nil {- return nil, errors.WrapIf(err, "failed to get webhook")+ return nil, fmt.Errorf("failed to get webhook: %w", err)}return &wh, nil}@@ -404,7 +405,7 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID stWhere("id = ? AND environment_id = ?", id, environmentID).Delete(&Webhook{})if result.Error != nil {- return errors.WrapIf(result.Error, "failed to delete webhook")+ return fmt.Errorf("failed to delete webhook: %w", result.Error)}if result.RowsAffected == 0 {return ErrWebhookNotFound@@ -442,11 +443,11 @@ func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID streturn nil, ErrWebhookNotFound}if err != nil {- return nil, errors.WrapIf(err, "failed to get webhook")+ return nil, fmt.Errorf("failed to get webhook: %w", err)}if err := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; err != nil {- return nil, errors.WrapIf(err, "failed to update webhook")+ return nil, fmt.Errorf("failed to update webhook: %w", err)}if s.eventService != nil {@@ -482,7 +483,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) erif err := s.db.WithContext(ctx).Where("token_prefix = ?", prefix).Find(&candidates).Error; err != nil {- return errors.WrapIf(err, "failed to look up webhook")+ return fmt.Errorf("failed to look up webhook: %w", err)}hash := kit.SHA256Hex(rawToken)@@ -512,7 +513,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) erexecCtx := context.WithoutCancel(ctx)s.actions.Go(func() {defer func() {- if panicErr := emperror.Recover(recover()); panicErr != nil {+ if panicErr := utils.PanicToError(recover()); panicErr != nil {slog.ErrorContext(execCtx, "webhook action panicked", "webhookID", wh.ID, "webhookName", wh.Name, "actionType", actionType, "error", panicErr)}}()@@ -671,7 +672,7 @@ func (s *WebhookService) resolveContainerWebhookTargetRefInternal(ctx context.CocontainerName, err := s.containerService.GetContainerNameByReference(ctx, targetID)if err != nil {- return "", errors.WrapIf(err, "failed to resolve container target reference")+ return "", fmt.Errorf("failed to resolve container target reference: %w", err)}return containerName, nil@@ -783,7 +784,10 @@ func (s *WebhookService) executeGitOpsWebhookActionInternal(ctx context.Context,func (s *WebhookService) wrapWebhookActionErrorInternal(ctx context.Context, wh *Webhook, targetKind, actionType string, err error) error {msg := fmt.Sprintf("%s %s failed: %s", targetKind, actionType, err)s.logWebhookEventInternal(ctx, wh, actionType, event.EventSeverityError, msg)- return errors.WrapIff(err, "%s %s failed", targetKind, actionType)+ if err != nil {+ return fmt.Errorf("%s %s failed: %w", targetKind, actionType, err)+ }+ return nil}func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *Webhook, actionType string, severity event.EventSeverity, errMsg string) {diff --git a/backend/pkg/authz/permission_matcher.go b/backend/pkg/authz/permission_matcher.goindex 03ef7fe27..5f13c8c74 100644--- a/backend/pkg/authz/permission_matcher.go+++ b/backend/pkg/authz/permission_matcher.go@@ -3,7 +3,10 @@ package authzimport ("strings"+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")// PermissionMatcher maps an HTTP method and environment-relative resource path@@ -129,3 +132,42 @@ func isParamSegmentInternal(s string) bool {}return strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")}++// UploadKindPermission maps an upload-session kind to the permission required+// to create, write to, inspect, or delete sessions of that kind. The boolean+// is false for unknown kinds so callers (and remote proxies) fail closed.+func UploadKindPermission(kind string) (string, bool) {+ switch kind {+ case uploadtypes.KindImage:+ return PermImagesUpload, true+ case uploadtypes.KindVolumeBackup:+ return PermVolumesUpload, true+ case uploadtypes.KindBuildWorkspace:+ return PermBuildWorkspacesManage, true+ }+ return "", false+}++// VolumeWorkspaceRequiredPermissions returns the distinct mutation permissions+// required by a Volume Workspace manifest. The boolean is false when a change+// uses an unknown operation so remote proxies can fail closed.+func VolumeWorkspaceRequiredPermissions(changes []volumetypes.WorkspaceFileChange) ([]string, bool) {+ required := make([]string, 0, 3)++ for _, change := range changes {+ switch change.Operation {+ case volumetypes.FileOpCreateFile, volumetypes.FileOpCreateFolder, volumetypes.FileOpUpdateFile:+ required = append(required, PermVolumesUpload)+ case volumetypes.FileOpRename, volumetypes.FileOpMove:+ required = append(required, PermVolumesUpload)+ required = append(required, PermVolumesDelete)+ case volumetypes.FileOpDelete:+ required = append(required, PermVolumesDelete)+ case volumetypes.FileOpRestoreFile:+ required = append(required, PermVolumesBackup)+ default:+ return nil, false+ }+ }+ return kit.Unique(required), true+}diff --git a/backend/pkg/authz/upload.go b/backend/pkg/authz/upload.godeleted file mode 100644index 244fab7f6..000000000--- a/backend/pkg/authz/upload.go+++ /dev/null@@ -1,18 +0,0 @@-package authz--import uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"--// UploadKindPermission maps an upload-session kind to the permission required-// to create, write to, inspect, or delete sessions of that kind. The boolean-// is false for unknown kinds so callers (and remote proxies) fail closed.-func UploadKindPermission(kind string) (string, bool) {- switch kind {- case uploadtypes.KindImage:- return PermImagesUpload, true- case uploadtypes.KindVolumeBackup:- return PermVolumesUpload, true- case uploadtypes.KindBuildWorkspace:- return PermBuildWorkspacesManage, true- }- return "", false-}diff --git a/backend/pkg/authz/volume_workspace.go b/backend/pkg/authz/volume_workspace.godeleted file mode 100644index 47f284ebf..000000000--- a/backend/pkg/authz/volume_workspace.go+++ /dev/null@@ -1,30 +0,0 @@-package authz--import (- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"- kit "go.getarcane.app/kit/pkg"-)--// VolumeWorkspaceRequiredPermissions returns the distinct mutation permissions-// required by a Volume Workspace manifest. The boolean is false when a change-// uses an unknown operation so remote proxies can fail closed.-func VolumeWorkspaceRequiredPermissions(changes []volumetypes.WorkspaceFileChange) ([]string, bool) {- required := make([]string, 0, 3)-- for _, change := range changes {- switch change.Operation {- case volumetypes.FileOpCreateFile, volumetypes.FileOpCreateFolder, volumetypes.FileOpUpdateFile:- required = append(required, PermVolumesUpload)- case volumetypes.FileOpRename, volumetypes.FileOpMove:- required = append(required, PermVolumesUpload)- required = append(required, PermVolumesDelete)- case volumetypes.FileOpDelete:- required = append(required, PermVolumesDelete)- case volumetypes.FileOpRestoreFile:- required = append(required, PermVolumesBackup)- default:- return nil, false- }- }- return kit.Unique(required), true-}diff --git a/backend/pkg/dockerutil/exec.go b/backend/pkg/dockerutil/exec.goindex 626eacfef..817da5d7a 100644--- a/backend/pkg/dockerutil/exec.go+++ b/backend/pkg/dockerutil/exec.go@@ -2,11 +2,12 @@ package dockerimport ("context"+ "errors"+ "fmt""io""net""strings"- "emperror.dev/errors""github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"kit "go.getarcane.app/kit/pkg"@@ -54,22 +55,22 @@ func WaitStdCopy(done <-chan error) error {func ExecInContainer(ctx context.Context, dockerClient *client.Client, containerID string, opts client.ExecCreateOptions, stdout, stderr io.Writer) (int, error) {execResp, err := dockerClient.ExecCreate(ctx, containerID, opts)if err != nil {- return 0, errors.WrapIf(err, "failed to create exec")+ return 0, fmt.Errorf("failed to create exec: %w", err)}attachResp, err := dockerClient.ExecAttach(ctx, execResp.ID, client.ExecAttachOptions{})if err != nil {- return 0, errors.WrapIf(err, "failed to attach to exec")+ return 0, fmt.Errorf("failed to attach to exec: %w", err)}defer attachResp.Close()if err := WaitStdCopy(StartStdCopy(attachResp.Reader, stdout, stderr)); err != nil {- return 0, errors.WrapIf(err, "failed to read exec output")+ return 0, fmt.Errorf("failed to read exec output: %w", err)}inspect, err := dockerClient.ExecInspect(ctx, execResp.ID, client.ExecInspectOptions{})if err != nil {- return 0, errors.WrapIf(err, "failed to inspect exec")+ return 0, fmt.Errorf("failed to inspect exec: %w", err)}return inspect.ExitCode, nildiff --git a/backend/pkg/dockerutil/log_stream.go b/backend/pkg/dockerutil/log_stream.goindex 873fd941b..fb9b2408b 100644--- a/backend/pkg/dockerutil/log_stream.go+++ b/backend/pkg/dockerutil/log_stream.go@@ -3,12 +3,13 @@ package dockerimport ("bufio""context"+ "errors"+ "fmt""io""log/slog""strings""sync"- "emperror.dev/errors""github.com/moby/moby/api/pkg/stdcopy"kit "go.getarcane.app/kit/pkg")@@ -115,7 +116,7 @@ func ReadAllLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- stringif ctxErr := ctx.Err(); ctxErr != nil {return ctxErr}- return errors.WrapIf(err, "failed to demultiplex logs")+ return fmt.Errorf("failed to demultiplex logs: %w", err)}if ctxErr := ctx.Err(); ctxErr != nil {return ctxErrdiff --git a/backend/pkg/dockerutil/mount_utils.go b/backend/pkg/dockerutil/mount_utils.goindex 63526cb32..21ceadabe 100644--- a/backend/pkg/dockerutil/mount_utils.go+++ b/backend/pkg/dockerutil/mount_utils.go@@ -2,12 +2,12 @@ package dockerimport ("context"+ "fmt""log/slog""path""slices""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"@@ -228,7 +228,7 @@ func PreserveVolumeMounts(binds []string, mounts []mount.Mount, mountPoints []codestination := path.Clean(mp.Destination)volumeName := strings.TrimSpace(mp.Name)if volumeName == "" {- return nil, nil, errors.Errorf("volume mounted at %s has no volume name", destination)+ return nil, nil, fmt.Errorf("volume mounted at %s has no volume name", destination)}mountIndex := slices.IndexFunc(mounts, func(m mount.Mount) bool {@@ -260,7 +260,7 @@ func PreserveVolumeMounts(binds []string, mounts []mount.Mount, mountPoints []coexplicit := MountForDestination(mountPoints, mp.Destination, mp.Destination)if explicit == nil {- return nil, nil, errors.Errorf("cannot build explicit mount for volume %s at %s", volumeName, destination)+ return nil, nil, fmt.Errorf("cannot build explicit mount for volume %s at %s", volumeName, destination)}mounts = append(mounts, *explicit)slog.Info("Preserving image-declared volume", "destination", destination, "volume", volumeName)diff --git a/backend/pkg/dockerutil/progress.go b/backend/pkg/dockerutil/progress.goindex 9ef6583db..0111de06f 100644--- a/backend/pkg/dockerutil/progress.go+++ b/backend/pkg/dockerutil/progress.go@@ -6,6 +6,8 @@ import ("io""strings""sync"++ "github.com/moby/moby/client/pkg/jsonmessage")// ProgressWriterKey can be set on a context to stream operation output to the@@ -80,3 +82,13 @@ func (w *logLineWriter) emitLine(line string) {f.Flush()}}++// RenderJSONMessageStream renders a Docker JSON message stream (image pull,+// push, build, load) as the raw text the docker CLI prints in non-TTY mode,+// writing it to out. Any daemon-reported error is returned verbatim.+func RenderJSONMessageStream(reader io.Reader, out io.Writer) error {+ if out == nil {+ out = io.Discard+ }+ return jsonmessage.DisplayJSONMessagesStream(reader, out, 0, false, nil)+}diff --git a/backend/pkg/dockerutil/render.go b/backend/pkg/dockerutil/render.godeleted file mode 100644index 548c29f72..000000000--- a/backend/pkg/dockerutil/render.go+++ /dev/null@@ -1,17 +0,0 @@-package docker--import (- "io"-- "github.com/moby/moby/client/pkg/jsonmessage"-)--// RenderJSONMessageStream renders a Docker JSON message stream (image pull,-// push, build, load) as the raw text the docker CLI prints in non-TTY mode,-// writing it to out. Any daemon-reported error is returned verbatim.-func RenderJSONMessageStream(reader io.Reader, out io.Writer) error {- if out == nil {- out = io.Discard- }- return jsonmessage.DisplayJSONMessagesStream(reader, out, 0, false, nil)-}diff --git a/backend/pkg/dockerutil/render_test.go b/backend/pkg/dockerutil/render_test.goindex 2dddda0b1..81acc906e 100644--- a/backend/pkg/dockerutil/render_test.go+++ b/backend/pkg/dockerutil/render_test.go@@ -10,11 +10,7 @@ import (func TestRenderJSONMessageStream(t *testing.T) {t.Run("renders docker CLI text for pull messages", func(t *testing.T) {- stream := strings.NewReader(- `{"status":"Pulling from library/nginx","id":"stable-alpine"}` + "\n" +- `{"status":"Pull complete","id":"abc123"}` + "\n" +- `{"status":"Status: Downloaded newer image for nginx:stable-alpine"}` + "\n",- )+ stream := strings.NewReader("{\"status\":\"Pulling from library/nginx\",\"id\":\"stable-alpine\"}\n{\"status\":\"Pull complete\",\"id\":\"abc123\"}\n{\"status\":\"Status: Downloaded newer image for nginx:stable-alpine\"}\n")var out strings.Builder{@@ -23,16 +19,14 @@ func TestRenderJSONMessageStream(t *testing.T) {"expected nil error, got %v", err)}- want := "stable-alpine: Pulling from library/nginx\n" +- "abc123: Pull complete\n" +- "Status: Downloaded newer image for nginx:stable-alpine\n"+ want := "stable-alpine: Pulling from library/nginx\nabc123: Pull complete\nStatus: Downloaded newer image for nginx:stable-alpine\n"require.Equal(t, want, out.String(),"expected CLI-parity output %q, got %q", want, out.String())})t.Run("returns daemon errorDetail verbatim", func(t *testing.T) {- stream := strings.NewReader(`{"errorDetail":{"code":401,"message":"unauthorized"}}` + "\n")+ stream := strings.NewReader("{\"errorDetail\":{\"code\":401,\"message\":\"unauthorized\"}}\n")err := RenderJSONMessageStream(stream, nil)require.False(t, err == nil || !strings.Contains(err.Error(), "unauthorized"),@@ -89,9 +83,7 @@ func TestLogLineWriter(t *testing.T) {_, _ = w.Write([]byte("-test Created\npartial"))_ = w.Close()- want := `{"log":"Container arcane-test Creating"}` + "\n" +- `{"log":"Container arcane-test Created"}` + "\n" +- `{"log":"partial"}` + "\n"+ want := "{\"log\":\"Container arcane-test Creating\"}\n{\"log\":\"Container arcane-test Created\"}\n{\"log\":\"partial\"}\n"require.Equal(t, want, out.String(),"expected framed lines %q, got %q", want, out.String())diff --git a/backend/pkg/dockerutil/volume_utils.go b/backend/pkg/dockerutil/volume_utils.goindex 1b0da1530..8d0b1177a 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"+ "strings""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"@@ -163,7 +164,7 @@ func fetchVolumeUsageDataInternal(ctx context.Context, dockerClient *client.ClieVerbose: true,})if err != nil {- return nil, errors.WrapIf(err, "failed to get disk usage")+ return nil, fmt.Errorf("failed to get disk usage: %w", err)}slog.DebugContext(ctx, "disk usage returned volumes", "volume_count", len(diskUsage.Volumes.Items))@@ -191,10 +192,19 @@ 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, errors.WrapIf(err, "failed to list containers")+ return nil, fmt.Errorf("failed to list containers: %w", err)}containerIDs := FilterContainersUsingVolume(containerList.Items, volumeName)slog.DebugContext(ctx, "found containers using volume", "volume", volumeName, "container_count", len(containerIDs))return containerIDs, nil}++// ValidateVolumeWorkspaceHelperSupport rejects Docker volume configurations+// that cannot be mounted safely inside Arcane's reusable workspace helper.+func ValidateVolumeWorkspaceHelperSupport(volumeName string, options map[string]string) error {+ if options["type"] == "none" || strings.Contains(options["o"], "bind") {+ return fmt.Errorf("volume %q uses a custom mount configuration and cannot be accessed through the workspace helper", volumeName)+ }+ return nil+}diff --git a/backend/pkg/dockerutil/volume_workspace.go b/backend/pkg/dockerutil/volume_workspace.godeleted file mode 100644index 16596c25f..000000000--- a/backend/pkg/dockerutil/volume_workspace.go+++ /dev/null@@ -1,16 +0,0 @@-package docker--import (- "strings"-- "emperror.dev/errors"-)--// ValidateVolumeWorkspaceHelperSupport rejects Docker volume configurations-// that cannot be mounted safely inside Arcane's reusable workspace helper.-func ValidateVolumeWorkspaceHelperSupport(volumeName string, options map[string]string) error {- if options["type"] == "none" || strings.Contains(options["o"], "bind") {- return errors.Errorf("volume %q uses a custom mount configuration and cannot be accessed through the workspace helper", volumeName)- }- return nil-}diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.goindex abd059ea4..dee21bdbd 100644--- a/backend/pkg/fswatch/watcher.go+++ b/backend/pkg/fswatch/watcher.go@@ -6,6 +6,7 @@ package fswatchimport ("cmp""context"+ "errors""log/slog""os""path/filepath"@@ -14,7 +15,6 @@ 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 ee80fae95..2541baa38 100644--- a/backend/pkg/gitutil/git.go+++ b/backend/pkg/gitutil/git.go@@ -3,7 +3,8 @@ package gitimport ("cmp""context"- stderrors "errors"+ "errors"+ "fmt""io""io/fs""log/slog"@@ -18,7 +19,6 @@ 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"@@ -136,18 +136,18 @@ func (c *Client) getAuthInternal(url string, config AuthConfig) (transport.AuthMif config.SSHKey != "" {endpoint, err := transport.NewEndpoint(url)if err != nil {- return nil, errors.WrapIf(err, "failed to parse SSH repository URL")+ return nil, fmt.Errorf("failed to parse SSH repository URL: %w", err)}username := cmp.Or(endpoint.User, "git")publicKeys, err := ssh.NewPublicKeys(username, []byte(config.SSHKey), "")if err != nil {- return nil, errors.WrapIf(err, "failed to create ssh auth")+ return nil, fmt.Errorf("failed to create ssh auth: %w", err)}// Configure host key verification based on modehostKeyCallback, err := c.getSSHHostKeyCallback(config.SSHHostKeyVerification)if err != nil {- return nil, errors.WrapIf(err, "failed to configure SSH host key verification")+ return nil, fmt.Errorf("failed to configure SSH host key verification: %w", err)}publicKeys.HostKeyCallbackHelper = ssh.HostKeyCallbackHelper{HostKeyCallback: hostKeyCallback,@@ -190,14 +190,14 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)// confinement root), and acfs has no append/flock API for the writes below.dir := filepath.Dir(knownHostsPath)if err := os.MkdirAll(dir, 0o700); err != nil {- return nil, errors.WrapIf(err, "failed to create known_hosts directory")+ return nil, fmt.Errorf("failed to create known_hosts directory: %w", err)}// 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, errors.WrapIf(err, "failed to create known_hosts file")+ return nil, fmt.Errorf("failed to create known_hosts file: %w", err)}if err := file.Close(); err != nil {slog.Warn("Failed to close known_hosts file", "path", knownHostsPath, "error", err)@@ -218,9 +218,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 := stderrors.AsType[*knownhosts.KeyError](err); ok && len(keyErr.Want) > 0 {+ if keyErr, ok := errors.AsType[*knownhosts.KeyError](err); ok && len(keyErr.Want) > 0 {// Host is known but key doesn't match - this is a security concern- return errors.WrapIff(err, "host key mismatch for %s (possible MITM attack)", hostname)+ return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, err)}// Otherwise, host is unknown - we'll add it}@@ -271,11 +271,11 @@ 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 errors.WrapIf(err, "failed to acquire lock on known_hosts file")+ return fmt.Errorf("failed to acquire lock on known_hosts file: %w", err)}defer func() {if unlockErr := fileLock.Unlock(); unlockErr != nil && err == nil {- err = errors.WrapIf(unlockErr, "failed to release lock on known_hosts file")+ err = fmt.Errorf("failed to release lock on known_hosts file: %w", unlockErr)}}()@@ -284,16 +284,16 @@ func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error// the user home rather than an arcane confinement root.file, err := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)if err != nil {- return errors.WrapIf(err, "failed to open known_hosts file")+ return fmt.Errorf("failed to open known_hosts file: %w", err)}defer func() {if cerr := file.Close(); cerr != nil && err == nil {- err = errors.WrapIf(cerr, "failed to close known_hosts file")+ err = fmt.Errorf("failed to close known_hosts file: %w", cerr)}}()if _, err := file.WriteString(line + "\n"); err != nil {- return errors.WrapIf(err, "failed to write to known_hosts file")+ return fmt.Errorf("failed to write to known_hosts file: %w", err)}return nil@@ -320,11 +320,11 @@ func (c *Client) Clone(ctx context.Context, url, branch string, auth AuthConfig)// os.* rather than acfs: this creates the clone staging root itself (under the// system temp dir by default), which has to exist before acfs could open it.if err := os.MkdirAll(workDir, 0o755); err != nil {- return "", errors.WrapIf(err, "failed to create work dir")+ return "", fmt.Errorf("failed to create work dir: %w", err)}tmpDir, err := os.MkdirTemp(workDir, cloneScratchPrefix+"*")if err != nil {- return "", errors.WrapIf(err, "failed to create temp dir")+ return "", fmt.Errorf("failed to create temp dir: %w", err)}url, err = normalizeURL(url)@@ -356,7 +356,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 "", errors.WrapIf(err, "failed to clone repository")+ return "", fmt.Errorf("failed to clone repository: %w", err)}return tmpDir, nil@@ -369,12 +369,12 @@ func (c *Client) GetCurrentCommit(ctx context.Context, repoPath string) (string,}repo, err := git.PlainOpen(repoPath)if err != nil {- return "", errors.WrapIf(err, "failed to open repository")+ return "", fmt.Errorf("failed to open repository: %w", err)}ref, err := repo.Head()if err != nil {- return "", errors.WrapIf(err, "failed to get HEAD")+ return "", fmt.Errorf("failed to get HEAD: %w", err)}return ref.Hash().String(), nil@@ -478,7 +478,7 @@ func (c *Client) listRemoteReferences(ctx context.Context, url string, auth Authrefs, err := rem.ListContext(listCtx, listOptions)if err != nil {- return nil, errors.WrapIf(err, "failed to list remote references")+ return nil, fmt.Errorf("failed to list remote references: %w", err)}return refs, nil@@ -493,7 +493,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 errors.WrapIf(err, "invalid path")+ return fmt.Errorf("invalid path: %w", err)}if strings.HasPrefix(rel, "..") || strings.Contains(rel, string(filepath.Separator)+".."+string(filepath.Separator)) {return errors.New("path traversal attempt detected")@@ -513,7 +513,7 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([logicalPath := path.Join("/", filepath.ToSlash(targetPath))entry, err := acfs.Stat(ctx, repoPath, logicalPath, true)if err != nil {- return nil, errors.WrapIf(err, "path not found")+ return nil, fmt.Errorf("path not found: %w", err)}if !entry.IsDirectory {return nil, errors.New("path is not a directory")@@ -521,7 +521,7 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([entries, err := acfs.List(ctx, repoPath, logicalPath)if err != nil {- return nil, errors.WrapIf(err, "failed to read directory")+ return nil, fmt.Errorf("failed to read directory: %w", err)}var nodes []gitops.FileTreeNode@@ -574,7 +574,7 @@ func (c *Client) PurgeScratchDirs(ctx context.Context, maxAge time.Duration) (inif errors.Is(err, fs.ErrNotExist) {return 0, nil}- return 0, errors.WrapIff(err, "failed to read git work dir %s", root)+ return 0, fmt.Errorf("failed to read git work dir %s: %w", root, err)}removed := 0@@ -645,7 +645,7 @@ func (c *Client) ReadFile(ctx context.Context, repoPath, filePath string) (strin}content, err := acfs.ReadFile(ctx, repoPath, path.Join("/", filepath.ToSlash(filePath)))if err != nil {- return "", errors.WrapIf(err, "failed to read file")+ return "", fmt.Errorf("failed to read file: %w", err)}return string(content), nil}@@ -690,7 +690,7 @@ func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath string// Validate compose pathif err := ValidatePath(repoPath, composePath); err != nil {- return nil, errors.WrapIf(err, "invalid compose path")+ return nil, fmt.Errorf("invalid compose path: %w", err)}// Get the directory containing the compose file@@ -737,13 +737,13 @@ func (c *Client) walkSyncEntry(ctx context.Context, syncDir string, entry acfstyfunc (c *Client) appendSyncFile(ctx context.Context, syncDir string, entry acfstypes.Entry, result *DirectoryWalkResult, limits syncWalkLimits) error {relativePath := strings.TrimPrefix(entry.Path, "/")if limits.maxFiles > 0 && result.TotalFiles >= limits.maxFiles {- return errors.Errorf("file count limit exceeded (max %d files)", limits.maxFiles)+ return fmt.Errorf("file count limit exceeded (max %d files)", limits.maxFiles)}if limits.maxBinarySize > 0 && entry.Size > limits.maxBinarySize {isBinary, err := c.isBinarySyncFile(ctx, syncDir, entry.Path)if err != nil {- return errors.WrapIff(err, "failed to inspect file %s", relativePath)+ return fmt.Errorf("failed to inspect file %s: %w", relativePath, err)}if isBinary {result.SkippedBinaries++@@ -753,7 +753,7 @@ func (c *Client) appendSyncFile(ctx context.Context, syncDir string, entry acfstcontent, err := acfs.ReadFile(ctx, syncDir, entry.Path)if err != nil {- return errors.WrapIff(err, "failed to read file %s", relativePath)+ return fmt.Errorf("failed to read file %s: %w", relativePath, err)}fileSize := int64(len(content))@@ -765,7 +765,7 @@ func (c *Client) appendSyncFile(ctx context.Context, syncDir string, entry acfst}if limits.maxTotalSize > 0 && result.TotalSize+fileSize > limits.maxTotalSize {- return errors.Errorf("total size limit exceeded (max %d bytes)", limits.maxTotalSize)+ return fmt.Errorf("total size limit exceeded (max %d bytes)", limits.maxTotalSize)}executable := os.FileMode(entry.UnixMode)&0o111 != 0diff --git a/backend/pkg/gitutil/git_write.go b/backend/pkg/gitutil/git_write.goindex cd265d66c..0f2a653cf 100644--- a/backend/pkg/gitutil/git_write.go+++ b/backend/pkg/gitutil/git_write.go@@ -3,6 +3,8 @@ package gitimport ("bytes""context"+ "errors"+ "fmt""io""io/fs""os"@@ -12,7 +14,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/ProtonMail/go-crypto/openpgp""github.com/go-git/go-git/v5""github.com/go-git/go-git/v5/config"@@ -27,11 +28,11 @@ import (var (// ErrPushRejected reports that the remote branch advanced between checkout and push.- ErrPushRejected = errors.Sentinel("push rejected: remote branch was updated by another writer")- ErrInvalidCommit = errors.Sentinel("invalid commit hash")- ErrSelectionUnreadable = errors.Sentinel("selection is unreadable")- ErrSelectionLimits = errors.Sentinel("selection exceeds limits")- ErrSelectionInvalid = errors.Sentinel("selection is invalid")+ ErrPushRejected = errors.New("push rejected: remote branch was updated by another writer")+ ErrInvalidCommit = errors.New("invalid commit hash")+ ErrSelectionUnreadable = errors.New("selection is unreadable")+ ErrSelectionLimits = errors.New("selection exceeds limits")+ ErrSelectionInvalid = errors.New("selection is invalid"))// WriteCheckout is a scratch clone prepared for committing to one branch.@@ -78,12 +79,12 @@ func CollectFiles(ctx context.Context, root string, selection []string, opts Colentry, err := acfs.Stat(ctx, root, logical, false)if err != nil {if errors.Is(err, fs.ErrNotExist) {- return nil, errors.WrapIff(ErrSelectionUnreadable, "selected path %s does not exist", selected)+ return nil, fmt.Errorf("selected path %s does not exist: %w", selected, ErrSelectionUnreadable)}- return nil, errors.WrapIff(ErrSelectionUnreadable, "cannot inspect %s: %v", selected, err)+ return nil, fmt.Errorf("cannot inspect %s: %v: %w", selected, err.Error(), ErrSelectionUnreadable)}if entry.IsSymlink {- return nil, errors.WrapIff(ErrSelectionInvalid, "%s is a symbolic link", selected)+ return nil, fmt.Errorf("%s is a symbolic link: %w", selected, ErrSelectionInvalid)}if !entry.IsDirectory {if err := c.addInternal(ctx, entry); err != nil {@@ -93,14 +94,14 @@ func CollectFiles(ctx context.Context, root string, selection []string, opts Col}err = acfs.Walk(ctx, root, logical, func(child acfstypes.Entry) error { return c.visitInternal(ctx, child) })if err != nil && !errors.Is(err, ErrSelectionUnreadable) && !errors.Is(err, ErrSelectionLimits) && !errors.Is(err, ErrSelectionInvalid) {- return nil, errors.WrapIff(ErrSelectionUnreadable, "cannot walk %s: %v", selected, err)+ return nil, fmt.Errorf("cannot walk %s: %v: %w", selected, err.Error(), ErrSelectionUnreadable)}if err != nil {return nil, err}}if len(c.files) == 0 {- return nil, errors.WrapIf(ErrSelectionInvalid, "the selection contains no files")+ return nil, fmt.Errorf("the selection contains no files: %w", ErrSelectionInvalid)}sort.Slice(c.files, func(i, j int) bool { return c.files[i].Path < c.files[j].Path })return c.files, nil@@ -122,15 +123,15 @@ func (c *fileCollectorInternal) addInternal(ctx context.Context, entry acfstypesreturn nil}if c.opts.MaxFiles > 0 && len(c.files) >= c.opts.MaxFiles {- return errors.WrapIff(ErrSelectionLimits, "file count limit exceeded (max %d files)", c.opts.MaxFiles)+ return fmt.Errorf("file count limit exceeded (max %d files): %w", c.opts.MaxFiles, ErrSelectionLimits)}content, err := acfs.ReadFile(ctx, c.root, entry.Path)if err != nil {- return errors.WrapIff(ErrSelectionUnreadable, "cannot read %s: %v", relative, err)+ return fmt.Errorf("cannot read %s: %v: %w", relative, err.Error(), ErrSelectionUnreadable)}c.totalSize += int64(len(content))if c.opts.MaxTotalSize > 0 && c.totalSize > c.opts.MaxTotalSize {- return errors.WrapIff(ErrSelectionLimits, "total size limit exceeded (max %d bytes)", c.opts.MaxTotalSize)+ return fmt.Errorf("total size limit exceeded (max %d bytes): %w", c.opts.MaxTotalSize, ErrSelectionLimits)}c.seen[relative] = struct{}{}c.files = append(c.files, CommitFile{Path: relative, Content: content, Executable: os.FileMode(entry.UnixMode)&0o111 != 0})@@ -159,7 +160,7 @@ type CommitIdentity struct {func ParseSigningKey(armored, passphrase string) (*openpgp.Entity, error) {entities, err := openpgp.ReadArmoredKeyRing(strings.NewReader(armored))if err != nil {- return nil, errors.WrapIf(err, "signing key is not an armored OpenPGP key")+ return nil, fmt.Errorf("signing key is not an armored OpenPGP key: %w", err)}for _, entity := range entities {if entity.PrivateKey == nil {@@ -170,7 +171,7 @@ func ParseSigningKey(armored, passphrase string) (*openpgp.Entity, error) {return nil, errors.New("signing key is protected by a passphrase")}if err := entity.PrivateKey.Decrypt([]byte(passphrase)); err != nil {- return nil, errors.WrapIf(err, "signing key passphrase is incorrect")+ return nil, fmt.Errorf("signing key passphrase is incorrect: %w", err)}}for _, subkey := range entity.Subkeys {@@ -178,7 +179,7 @@ func ParseSigningKey(armored, passphrase string) (*openpgp.Entity, error) {continue}if err := subkey.PrivateKey.Decrypt([]byte(passphrase)); err != nil {- return nil, errors.WrapIf(err, "signing key passphrase is incorrect")+ return nil, fmt.Errorf("signing key passphrase is incorrect: %w", err)}}return entity, nil@@ -219,12 +220,12 @@ func (c *Client) CheckoutForWrite(ctx context.Context, url, branch string, authrepo, openErr := git.PlainOpen(repoPath)if openErr != nil {_ = c.Cleanup(repoPath)- return nil, errors.WrapIf(openErr, "failed to open checkout")+ return nil, fmt.Errorf("failed to open checkout: %w", openErr)}head, headErr := repo.Head()if headErr != nil {_ = c.Cleanup(repoPath)- return nil, errors.WrapIf(headErr, "failed to resolve checkout head")+ return nil, fmt.Errorf("failed to resolve checkout head: %w", headErr)}return &WriteCheckout{RepoPath: repoPath, Branch: branch, HeadCommit: head.Hash().String(), BranchExists: true, url: normalized, repo: repo}, nil}@@ -245,24 +246,24 @@ func (c *Client) initEmptyCheckoutInternal(url, branch string) (*WriteCheckout,workDir = os.TempDir()}if err := os.MkdirAll(workDir, 0o755); err != nil {- return nil, errors.WrapIf(err, "failed to create work dir")+ return nil, fmt.Errorf("failed to create work dir: %w", err)}repoPath, err := os.MkdirTemp(workDir, cloneScratchPrefix+"*")if err != nil {- return nil, errors.WrapIf(err, "failed to create temp dir")+ return nil, fmt.Errorf("failed to create temp dir: %w", err)}repo, err := git.PlainInit(repoPath, false)if err != nil {_ = os.RemoveAll(repoPath)- return nil, errors.WrapIf(err, "failed to initialize checkout")+ return nil, fmt.Errorf("failed to initialize checkout: %w", err)}if _, err := repo.CreateRemote(&config.RemoteConfig{Name: "origin", URLs: []string{url}}); err != nil {_ = os.RemoveAll(repoPath)- return nil, errors.WrapIf(err, "failed to configure remote")+ return nil, fmt.Errorf("failed to configure remote: %w", err)}if err := repo.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName(branch))); err != nil {_ = os.RemoveAll(repoPath)- return nil, errors.WrapIf(err, "failed to select branch")+ return nil, fmt.Errorf("failed to select branch: %w", err)}return &WriteCheckout{RepoPath: repoPath, Branch: branch, url: url, repo: repo}, nil}@@ -275,16 +276,16 @@ func (c *Client) checkoutNewBranchInternal(ctx context.Context, url, branch strirepo, err := git.PlainOpen(repoPath)if err != nil {_ = c.Cleanup(repoPath)- return nil, errors.WrapIf(err, "failed to open checkout")+ return nil, fmt.Errorf("failed to open checkout: %w", err)}worktree, err := repo.Worktree()if err != nil {_ = c.Cleanup(repoPath)- return nil, errors.WrapIf(err, "failed to open worktree")+ return nil, fmt.Errorf("failed to open worktree: %w", err)}if err := worktree.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(branch), Create: true}); err != nil {_ = c.Cleanup(repoPath)- return nil, errors.WrapIff(err, "failed to create branch %s", branch)+ return nil, fmt.Errorf("failed to create branch %s: %w", branch, err)}return &WriteCheckout{RepoPath: repoPath, Branch: branch, url: url, repo: repo}, nil}@@ -299,7 +300,7 @@ func (c *Client) CommitAndPush(ctx context.Context, checkout *WriteCheckout, req}worktree, err := checkout.repo.Worktree()if err != nil {- return "", false, errors.WrapIf(err, "failed to open worktree")+ return "", false, fmt.Errorf("failed to open worktree: %w", err)}if err := stageCommitFilesInternal(ctx, checkout, worktree, req); err != nil {return "", false, err@@ -311,7 +312,7 @@ func (c *Client) CommitAndPush(ctx context.Context, checkout *WriteCheckout, reqif errors.Is(err, git.ErrEmptyCommit) {return checkout.HeadCommit, false, nil}- return "", false, errors.WrapIf(err, "failed to commit")+ return "", false, fmt.Errorf("failed to commit: %w", err)}if err := c.pushBranchInternal(ctx, checkout, hash.String(), auth); err != nil {return "", false, err@@ -330,14 +331,14 @@ func stageCommitFilesInternal(ctx context.Context, checkout *WriteCheckout, work}logical := path.Join("/", filepath.ToSlash(file.Path))if err := acfs.MkdirAll(ctx, checkout.RepoPath, path.Dir(logical), 0o755); err != nil {- return errors.WrapIff(err, "failed to create directory for %s", file.Path)+ return fmt.Errorf("failed to create directory for %s: %w", file.Path, err)}mode := kit.Ternary(file.Executable, 0o755, os.FileMode(0o644))if _, err := acfs.WriteFrom(ctx, checkout.RepoPath, logical, bytes.NewReader(file.Content), int64(len(file.Content)), mode); err != nil {- return errors.WrapIff(err, "failed to write %s", file.Path)+ return fmt.Errorf("failed to write %s: %w", file.Path, err)}if _, err := worktree.Add(file.Path); err != nil {- return errors.WrapIff(err, "failed to stage %s", file.Path)+ return fmt.Errorf("failed to stage %s: %w", file.Path, err)}}for _, removed := range req.Remove {@@ -348,10 +349,10 @@ func stageCommitFilesInternal(ctx context.Context, checkout *WriteCheckout, workif errors.Is(err, fs.ErrNotExist) {continue}- return errors.WrapIff(err, "failed to inspect %s", removed)+ return fmt.Errorf("failed to inspect %s: %w", removed, err)}if _, err := worktree.Remove(removed); err != nil {- return errors.WrapIff(err, "failed to remove %s", removed)+ return fmt.Errorf("failed to remove %s: %w", removed, err)}}return nil@@ -374,17 +375,17 @@ func (c *Client) pushBranchInternal(ctx context.Context, checkout *WriteCheckout}if err := checkout.repo.PushContext(ctx, pushOptions); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {if isPushRejectedInternal(err) {- return errors.WrapIf(ErrPushRejected, err.Error())+ return fmt.Errorf("%s: %w", err.Error(), ErrPushRejected)}- return errors.WrapIf(err, "failed to push")+ return fmt.Errorf("failed to push: %w", err)}remoteHead, exists, err := c.RemoteBranchHead(ctx, checkout.url, checkout.Branch, auth)if err != nil {- return errors.WrapIf(err, "failed to verify pushed commit")+ return fmt.Errorf("failed to verify pushed commit: %w", err)}if !exists || remoteHead != commit {- return errors.WrapIf(ErrPushRejected, "remote branch does not point at the pushed commit")+ return fmt.Errorf("remote branch does not point at the pushed commit: %w", ErrPushRejected)}return nil}@@ -419,19 +420,19 @@ func (c *Client) DirectoryHistory(ctx context.Context, repoPath, directory strin}repo, err := git.PlainOpen(repoPath)if err != nil {- return nil, errors.WrapIf(err, "failed to open repository")+ return nil, fmt.Errorf("failed to open repository: %w", err)}head, err := repo.Head()if err != nil {if errors.Is(err, plumbing.ErrReferenceNotFound) {return nil, nil}- return nil, errors.WrapIf(err, "failed to resolve head")+ return nil, fmt.Errorf("failed to resolve head: %w", err)}prefix := directoryPrefixInternal(directory)iter, err := repo.Log(&git.LogOptions{From: head.Hash(), PathFilter: func(p string) bool { return strings.HasPrefix(p, prefix) }})if err != nil {- return nil, errors.WrapIf(err, "failed to read history")+ return nil, fmt.Errorf("failed to read history: %w", err)}defer iter.Close()@@ -445,7 +446,7 @@ func (c *Client) DirectoryHistory(ctx context.Context, repoPath, directory strinif errors.Is(err, io.EOF) {break}- return nil, errors.WrapIf(err, "failed to iterate history")+ return nil, fmt.Errorf("failed to iterate history: %w", err)}files, err := commitDirectoryFilesInternal(commit, prefix)if err != nil {@@ -469,15 +470,15 @@ func (c *Client) CommitDiff(ctx context.Context, repoPath, commitHash, directory}repo, err := git.PlainOpen(repoPath)if err != nil {- return HistoryEntry{}, nil, errors.WrapIf(err, "failed to open repository")+ return HistoryEntry{}, nil, fmt.Errorf("failed to open repository: %w", err)}hash, err := repo.ResolveRevision(plumbing.Revision(commitHash))if err != nil {- return HistoryEntry{}, nil, errors.WrapIf(err, "commit not found")+ return HistoryEntry{}, nil, fmt.Errorf("commit not found: %w", err)}commit, err := repo.CommitObject(*hash)if err != nil {- return HistoryEntry{}, nil, errors.WrapIf(err, "commit not found")+ return HistoryEntry{}, nil, fmt.Errorf("commit not found: %w", err)}prefix := directoryPrefixInternal(directory)patch, err := commitPatchInternal(commit)@@ -527,20 +528,20 @@ func commitPatchInternal(commit *object.Commit) (*object.Patch, error) {if commit.NumParents() > 0 {parent, err := commit.Parent(0)if err != nil {- return nil, errors.WrapIf(err, "failed to load parent commit")+ return nil, fmt.Errorf("failed to load parent commit: %w", err)}parentTree, err = parent.Tree()if err != nil {- return nil, errors.WrapIf(err, "failed to load parent tree")+ return nil, fmt.Errorf("failed to load parent tree: %w", err)}}tree, err := commit.Tree()if err != nil {- return nil, errors.WrapIf(err, "failed to load commit tree")+ return nil, fmt.Errorf("failed to load commit tree: %w", err)}patch, err := parentTree.Patch(tree)if err != nil {- return nil, errors.WrapIf(err, "failed to diff commit")+ return nil, fmt.Errorf("failed to diff commit: %w", err)}return patch, nil}@@ -579,20 +580,20 @@ func commitFilePatchInternal(commit *object.Commit, name string) (string, error)if commit.NumParents() > 0 {parent, err := commit.Parent(0)if err != nil {- return "", errors.WrapIf(err, "failed to load parent commit")+ return "", fmt.Errorf("failed to load parent commit: %w", err)}parentTree, err = parent.Tree()if err != nil {- return "", errors.WrapIf(err, "failed to load parent tree")+ return "", fmt.Errorf("failed to load parent tree: %w", err)}}tree, err := commit.Tree()if err != nil {- return "", errors.WrapIf(err, "failed to load commit tree")+ return "", fmt.Errorf("failed to load commit tree: %w", err)}changes, err := object.DiffTree(parentTree, tree)if err != nil {- return "", errors.WrapIf(err, "failed to diff commit")+ return "", fmt.Errorf("failed to diff commit: %w", err)}for _, change := range changes {if change.From.Name != name && change.To.Name != name {@@ -600,7 +601,7 @@ func commitFilePatchInternal(commit *object.Commit, name string) (string, error)}patch, err := change.Patch()if err != nil {- return "", errors.WrapIff(err, "failed to build patch for %s", name)+ return "", fmt.Errorf("failed to build patch for %s: %w", name, err)}return patch.String(), nil}diff --git a/backend/pkg/gitutil/git_write_test.go b/backend/pkg/gitutil/git_write_test.goindex 9a877cb15..a125f4efc 100644--- a/backend/pkg/gitutil/git_write_test.go+++ b/backend/pkg/gitutil/git_write_test.go@@ -2,13 +2,13 @@ package gitimport ("context"+ "errors""os""path/filepath""sync""testing""time"- "emperror.dev/errors""github.com/go-git/go-billy/v5/osfs"gogit "github.com/go-git/go-git/v5""github.com/go-git/go-git/v5/plumbing/object"diff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.goindex 7ca8f2fcf..6381fb669 100644--- a/backend/pkg/libarcane/activity/handler.go+++ b/backend/pkg/libarcane/activity/handler.go@@ -3,13 +3,13 @@ package activityimport ("context""encoding/json/v2"+ "errors""fmt""io""log/slog""net/http""strings"- "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/pkg/scheduler/jobcontext"@@ -23,12 +23,13 @@ const (// 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.- ErrCanceled = errors.Sentinel("activity cancelled by user")// cancelledMessage is the latest-message recorded when work is cancelled.cancelledMessage = "Cancelled by user")+var ErrCanceled = errors.New("activity cancelled by user")+type handlerActivityIDContextKey struct{}func IDFromContext(ctx context.Context) string {@@ -213,7 +214,7 @@ func WriteDoneLine(writer io.Writer) {if writer == nil {return}- _, _ = io.WriteString(writer, `{"done":true}`+"\n")+ _, _ = io.WriteString(writer, "{\"done\":true}\n")if flusher, ok := writer.(http.Flusher); ok {flusher.Flush()}@@ -229,7 +230,7 @@ func WriteStartedLine(writer io.Writer, activityID string) {"activityId": activityID,}if err := json.MarshalWrite(writer, payload); err != nil {- _, _ = fmt.Fprintf(writer, `{"activityId":%q}`+"\n", activityID)+ _, _ = fmt.Fprintf(writer, "{\"activityId\":%q}\n", activityID)return}_, _ = io.WriteString(writer, "\n")diff --git a/backend/pkg/libarcane/activity/writer_test.go b/backend/pkg/libarcane/activity/writer_test.goindex e0c78e11b..33bbec54f 100644--- a/backend/pkg/libarcane/activity/writer_test.go+++ b/backend/pkg/libarcane/activity/writer_test.go@@ -68,7 +68,7 @@ func TestWriterRecordsLogAndErrorFramesVerbatimInternal(t *testing.T) {appender := &recordingAppender{}writer := NewWriter(context.Background(), appender, "activity-1", io.Discard, "Deploying project")- _, err := writer.Write([]byte(`{"log":"Container web-1 Created"}` + "\n" + `{"error":"Error response from daemon: conflict"}` + "\n"))+ _, err := writer.Write([]byte("{\"log\":\"Container web-1 Created\"}\n{\"error\":\"Error response from daemon: conflict\"}\n"))require.NoError(t, err)FlushWriter(writer)diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.goindex 2fa6e6bdf..d54757ba2 100644--- a/backend/pkg/libarcane/edge/client.go+++ b/backend/pkg/libarcane/edge/client.go@@ -3,6 +3,8 @@ package edgeimport ("bytes""context"+ "crypto/tls"+ "errors""fmt""io""log/slog"@@ -13,7 +15,6 @@ import ("time""uuid"- "emperror.dev/errors""github.com/cenkalti/backoff/v5""github.com/coder/websocket"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"@@ -57,10 +58,16 @@ const (// errTunnelRegistrationTimeout marks a registration attempt where the manager// accepted the connection but never answered the register message.- errTunnelRegistrationTimeout = errors.Sentinel("timed out waiting for tunnel registration response")+// errEstablishedTunnelSessionEnded marks a session that the manager accepted// and later dropped, as opposed to a transport that never connected.- errEstablishedTunnelSessionEnded = errors.Sentinel("established edge tunnel session ended")++)++var (+ errTunnelRegistrationTimeout = errors.New("timed out waiting for tunnel registration response")++ errEstablishedTunnelSessionEnded = errors.New("established edge tunnel session ended"))func (t *commandRequestTransfer) stopInternal() {@@ -216,7 +223,7 @@ func (c *TunnelClient) connectAndServeManagedTunnelInternal(ctx context.Context)"grpc_failure_streak", c.grpcFailureStreakInternal(),"manager_ws_url", c.managerWebSocketURLInternal(),)- return c.connectAndServeWebSocket(ctx)+ return c.connectAndServeWebSocketInternal(ctx)}sessionStart := time.Now()@@ -238,7 +245,7 @@ func (c *TunnelClient) connectAndServeManagedTunnelInternal(ctx context.Context)"manager_grpc_addr", c.managerGRPCAddr,"manager_ws_url", managerWSURL,)- if wsErr := c.connectAndServeWebSocket(ctx); wsErr != nil {+ if wsErr := c.connectAndServeWebSocketInternal(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)}@@ -249,7 +256,7 @@ func (c *TunnelClient) connectAndServeManagedTunnelInternal(ctx context.Context)return nil}if transports.websocket {- return c.connectAndServeWebSocket(ctx)+ return c.connectAndServeWebSocketInternal(ctx)}return errors.New("no edge tunnel transport is available")}@@ -435,19 +442,19 @@ func (c *TunnelClient) awaitRegistrationInternal(ctx context.Context, conn Tunnereturn nil, ctx.Err()case <-timer.C:_ = conn.Close()- return nil, errors.WrapIff(errTunnelRegistrationTimeout, "after %s", timeout)+ return nil, fmt.Errorf("after %s: %w", timeout, errTunnelRegistrationTimeout)case result := <-recvCh:if result.err != nil {- return nil, errors.WrapIf(result.err, "failed to receive tunnel registration response")+ return nil, fmt.Errorf("failed to receive tunnel registration response: %w", result.err)}if result.msg == nil {return nil, errors.New("received empty tunnel registration response")}if result.msg.Type != MessageTypeRegisterResponse {- return nil, errors.Errorf("unexpected first tunnel message: %s", result.msg.Type)+ return nil, fmt.Errorf("unexpected first tunnel message: %s", result.msg.Type)}if !result.msg.Accepted {- return nil, errors.Errorf("manager rejected tunnel registration: %s", result.msg.Error)+ return nil, fmt.Errorf("manager rejected tunnel registration: %s", result.msg.Error)}c.registration.Store(clientRegistrationInternal{sessionID: result.msg.SessionID})return result.msg, nil@@ -481,7 +488,7 @@ func (c *TunnelClient) serveTunnelSessionInternal(ctx context.Context, conn Tunnif err := conn.Send(c.registerMessageInternal()); err != nil {// A rejected gRPC stream can report EOF from Send; Recv carries the RPC status.if conn.Transport() != EdgeTransportGRPC || !errors.Is(err, io.EOF) {- return errors.WrapIff(err, "failed to send %s tunnel register message", conn.Transport())+ return fmt.Errorf("failed to send %s tunnel register message: %w", conn.Transport(), err)}}@@ -547,7 +554,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context, conn TunnelConnection, wdefault:msg, err := conn.Receive()if err != nil {- return errors.WrapIf(err, "failed to receive message")+ return fmt.Errorf("failed to receive message: %w", err)}switch msg.Type {@@ -581,7 +588,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context, conn TunnelConnection, wslog.DebugContext(ctx, "Received heartbeat ack")case MessageTypeRegisterResponse:if !msg.Accepted {- return errors.Errorf("manager rejected tunnel registration: %s", msg.Error)+ return fmt.Errorf("manager rejected tunnel registration: %s", msg.Error)}slog.InfoContext(ctx, "Edge tunnel re-registered","transport", conn.Transport(),@@ -1482,3 +1489,46 @@ func StartTunnelClient(ctx context.Context, cfg *Config, handler http.Handler) (return nil})}++func (c *TunnelClient) connectAndServeWebSocketInternal(ctx context.Context) error {+ managerWSURL := c.managerWebSocketURLInternal()+ if managerWSURL == "" {+ return errors.New("manager WebSocket URL is empty")+ }+ transport := &http.Transport{Proxy: http.ProxyFromEnvironment}+ 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)+ }+ if tlsConfig == nil {+ tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}+ }+ transport.TLSClientConfig = tlsConfig+ }++ headers := http.Header{}+ for header, value := range agentAuthCredentialsInternal(c.cfg.AgentToken) {+ headers.Set(header, value)+ }++ slog.DebugContext(ctx, "Dialing manager for websocket edge tunnel", "url", managerWSURL)++ // The dial context bounds only the handshake; the connection outlives it.+ dialCtx, dialCancel := context.WithTimeout(ctx, 30*time.Second)+ defer dialCancel()+ conn, resp, err := websocket.Dial(dialCtx, managerWSURL, &websocket.DialOptions{+ HTTPClient: &http.Client{Transport: transport},+ HTTPHeader: headers,+ })+ if err != nil {+ if resp != nil && resp.Body != nil {+ defer func() { _ = resp.Body.Close() }()+ body, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("failed to connect to manager websocket endpoint (status: %d, body: %s): %w", resp.StatusCode, string(body), err)+ }+ return fmt.Errorf("failed to connect to manager websocket endpoint: %w", err)+ }++ return c.serveTunnelSessionInternal(ctx, NewTunnelConn(conn), managerWSURL)+}diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.goindex 09585d0ef..e8b618b12 100644--- a/backend/pkg/libarcane/edge/client_test.go+++ b/backend/pkg/libarcane/edge/client_test.go@@ -2411,7 +2411,7 @@ func TestConnectAndServeWebSocket_CancelUnblocksMessageLoop(t *testing.T) {ctx, cancel := context.WithCancel(t.Context())done := make(chan error, 1)- go func() { done <- client.connectAndServeWebSocket(ctx) }()+ go func() { done <- client.connectAndServeWebSocketInternal(ctx) }()select {case <-registered:diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.goindex 7fe568fd0..0e98d83cd 100644--- a/backend/pkg/libarcane/edge/client_transport_grpc.go+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go@@ -3,12 +3,13 @@ package edgeimport ("context""crypto/tls"+ "errors"+ "fmt""log/slog""net/url""strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1""google.golang.org/grpc"@@ -50,7 +51,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {if c.useTLSForManagerGRPC() {tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)if err != nil {- return errors.WrapIf(err, "failed to configure edge gRPC TLS")+ return fmt.Errorf("failed to configure edge gRPC TLS: %w", err)}if tlsConfig == nil {tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}@@ -64,12 +65,12 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {conn, err := grpc.NewClient(managerAddr, dialOpts...)if err != nil {- return errors.WrapIf(err, "failed to dial manager gRPC endpoint")+ return fmt.Errorf("failed to dial manager gRPC endpoint: %w", err)}defer func() { _ = conn.Close() }()if err := c.waitForGRPCReadyInternal(ctx, conn); err != nil {- return errors.WrapIf(err, "manager gRPC endpoint is not ready")+ return fmt.Errorf("manager gRPC endpoint is not ready: %w", err)}// metadata.New lowercases the keys itself.@@ -80,16 +81,14 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {method := c.grpcConnectMethodInternal()stream, err := c.openTunnelConnectStreamInternal(streamCtx, conn, method)if err != nil {- return errors.WrapIf(err, "failed to open tunnel stream")+ return fmt.Errorf("failed to open tunnel stream: %w", err)}if err := c.serveTunnelSessionInternal(ctx, NewGRPCAgentTunnelConn(stream, streamCancel), managerAddr); err != nil {if errors.Is(err, errTunnelRegistrationTimeout) {// The channel already reached Ready, so TCP/TLS works but gRPC// framing was never answered end to end.- return errors.WrapIf(err,- "manager accepted the TCP/TLS connection but never answered gRPC tunnel registration; "+- "if a reverse proxy (Traefik/Pangolin/Nginx) fronts the manager, it is likely not forwarding gRPC (HTTP/2 with trailers) on /api/tunnel/connect")+ return fmt.Errorf("%s: %w", "manager accepted the TCP/TLS connection but never answered gRPC tunnel registration; if a reverse proxy (Traefik/Pangolin/Nginx) fronts the manager, it is likely not forwarding gRPC (HTTP/2 with trailers) on /api/tunnel/connect", err)}return err}@@ -117,7 +116,7 @@ func (c *TunnelClient) waitForGRPCReadyInternal(ctx context.Context, conn *grpc.if !conn.WaitForStateChange(readyCtx, state) {if errors.Is(readyCtx.Err(), context.DeadlineExceeded) {- return errors.Errorf("timed out waiting for manager gRPC endpoint after %s", timeout)+ return fmt.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 88d1f920e..fd24aafb6 100644--- a/backend/pkg/libarcane/edge/client_transport_poll.go+++ b/backend/pkg/libarcane/edge/client_transport_poll.go@@ -4,13 +4,14 @@ import ("bytes""context""encoding/json/v2"+ "errors"+ "fmt""io""log/slog""net/http""strings""time"- "emperror.dev/errors""github.com/cenkalti/backoff/v5""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx")@@ -19,7 +20,7 @@ const defaultTunnelPollRequestTimeout = 15 * time.Secondvar defaultPollManagedSessionStopTimeout = 5 * time.Second-var errPollManagedSessionStopTimeout = errors.Sentinel("timed out waiting for poll-managed websocket session to stop")+var errPollManagedSessionStopTimeout = errors.New("timed out waiting for poll-managed websocket session to stop")func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {if c.cfg == nil {@@ -31,7 +32,7 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {}httpClient, err := NewManagerHTTPClient(c.cfg, 0)if err != nil {- return errors.WrapIf(err, "failed to configure edge poll client")+ return fmt.Errorf("failed to configure edge poll client: %w", err)}pollURL := managerBaseURL + "/api/tunnel/poll"interval := DefaultTunnelPollInterval@@ -117,7 +118,7 @@ func consumePollManagedSessionInternal(session *pollManagedTunnelSession) (*pollselect {case err := <-session.done:if err != nil {- return nil, errors.WrapIf(err, "poll-managed websocket session ended")+ return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)}return nil, nildefault:@@ -175,7 +176,7 @@ func waitForNextPollCycleInternal(ctx context.Context, session *pollManagedTunnereturn session, ctx.Err()case err := <-sessionDone:if err != nil {- return nil, errors.WrapIf(err, "poll-managed websocket session ended")+ return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)}return nil, nilcase <-waitTimer.C:@@ -191,7 +192,7 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, httpClientbody, err := json.Marshal(pollReq)if err != nil {- return nil, errors.WrapIf(err, "failed to marshal poll request")+ return nil, fmt.Errorf("failed to marshal poll request: %w", err)}reqCtx, cancel := context.WithTimeout(ctx, defaultTunnelPollRequestTimeout)@@ -199,7 +200,7 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, httpClientreq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pollURL, bytes.NewReader(body))if err != nil {- return nil, errors.WrapIf(err, "failed to create poll request")+ return nil, fmt.Errorf("failed to create poll request: %w", err)}req.Header.Set("Content-Type", "application/json")for header, value := range agentAuthCredentialsInternal(c.cfg.AgentToken) {@@ -208,18 +209,18 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, httpClientresp, err := httpClient.Do(req)if err != nil {- return nil, errors.WrapIf(err, "poll request failed")+ return nil, fmt.Errorf("poll request failed: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {respBody, _ := io.ReadAll(resp.Body)- return nil, errors.Errorf("poll request failed with status %d: %s", resp.StatusCode, string(respBody))+ return nil, fmt.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, errors.WrapIf(err, "failed to decode poll response")+ return nil, fmt.Errorf("failed to decode poll response: %w", err)}return &pollResp, nil}diff --git a/backend/pkg/libarcane/edge/client_transport_websocket.go b/backend/pkg/libarcane/edge/client_transport_websocket.godeleted file mode 100644index 122b890b6..000000000--- a/backend/pkg/libarcane/edge/client_transport_websocket.go+++ /dev/null@@ -1,57 +0,0 @@-package edge--import (- "context"- "crypto/tls"- "io"- "log/slog"- "net/http"- "strings"- "time"-- "emperror.dev/errors"- "github.com/coder/websocket"-)--func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {- managerWSURL := c.managerWebSocketURLInternal()- if managerWSURL == "" {- return errors.New("manager WebSocket URL is empty")- }- transport := &http.Transport{Proxy: http.ProxyFromEnvironment}- if strings.HasPrefix(strings.ToLower(managerWSURL), "wss://") {- tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)- if err != nil {- return errors.WrapIf(err, "failed to configure edge websocket TLS")- }- if tlsConfig == nil {- tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}- }- transport.TLSClientConfig = tlsConfig- }-- headers := http.Header{}- for header, value := range agentAuthCredentialsInternal(c.cfg.AgentToken) {- headers.Set(header, value)- }-- slog.DebugContext(ctx, "Dialing manager for websocket edge tunnel", "url", managerWSURL)-- // The dial context bounds only the handshake; the connection outlives it.- dialCtx, dialCancel := context.WithTimeout(ctx, 30*time.Second)- defer dialCancel()- conn, resp, err := websocket.Dial(dialCtx, managerWSURL, &websocket.DialOptions{- HTTPClient: &http.Client{Transport: transport},- HTTPHeader: headers,- })- if err != nil {- if resp != nil && resp.Body != nil {- defer func() { _ = resp.Body.Close() }()- body, _ := io.ReadAll(resp.Body)- return errors.WrapIff(err, "failed to connect to manager websocket endpoint (status: %d, body: %s)", resp.StatusCode, string(body))- }- return errors.WrapIf(err, "failed to connect to manager websocket endpoint")- }-- return c.serveTunnelSessionInternal(ctx, NewTunnelConn(conn), managerWSURL)-}diff --git a/backend/pkg/libarcane/edge/command_client.go b/backend/pkg/libarcane/edge/command_client.goindex 3ef73fdca..b5d3383e6 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""uuid"-- "emperror.dev/errors")const (@@ -39,7 +39,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, errors.Errorf("unsupported edge command for %s %s", req.Method, req.Path)+ return nil, fmt.Errorf("unsupported edge command for %s %s", req.Method, req.Path)}commandName = resolved}@@ -82,7 +82,7 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *C}if err := tunnel.Conn.Send(msg); err != nil {- return nil, errors.WrapIf(err, "tunnel request failed")+ return nil, fmt.Errorf("tunnel request failed: %w", err)}if chunkRequestBody {transferID := msg.Metadata[bodyTransferMetadataKey]@@ -95,7 +95,7 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *CSequence: sequence,EOF: end == len(req.Body),}); err != nil {- return nil, errors.WrapIf(err, "tunnel request body transfer failed")+ return nil, fmt.Errorf("tunnel request body transfer failed: %w", err)}offset = end}@@ -131,7 +131,7 @@ func (c *CommandClient) OpenStream(ctx context.Context, tunnel *AgentTunnel, reqif commandName == "" {resolved, ok := ResolveEdgeCommandName(http.MethodGet, req.Path, true).Get()if !ok {- return errors.Errorf("unsupported edge stream target %q", req.Path)+ return fmt.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 020ade99e..cd0bc122a 100644--- a/backend/pkg/libarcane/edge/event_sync.go+++ b/backend/pkg/libarcane/edge/event_sync.go@@ -1,16 +1,14 @@package edgeimport (+ "errors""strings""sync""uuid"-- "emperror.dev/errors")const (// ErrNoActiveAgentTunnel is returned when no active agent tunnel exists for outbound event sync.- ErrNoActiveAgentTunnel = errors.Sentinel("no active edge agent tunnel")// TunnelEventTypeNotificationDispatch marks a tunnel event that carries a// notification dispatch request in MetadataJSON instead of an event-log entry.@@ -19,6 +17,8 @@ const (TunnelEventTypeNotificationDispatch = "notification.dispatch")+var ErrNoActiveAgentTunnel = errors.New("no active edge agent tunnel")+var agentTunnelState struct {mu sync.RWMutexconn TunnelConnectiondiff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.goindex fd89f8ea5..9cfb4867b 100644--- a/backend/pkg/libarcane/edge/poll_control.go+++ b/backend/pkg/libarcane/edge/poll_control.go@@ -2,13 +2,13 @@ package edgeimport ("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/v5""github.com/samber/mo"diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.goindex ea2b2eb99..88eacc16b 100644--- a/backend/pkg/libarcane/edge/proxy.go+++ b/backend/pkg/libarcane/edge/proxy.go@@ -3,12 +3,13 @@ package edgeimport ("bytes""context"+ "errors"+ "fmt""io""log/slog""net/http""time"- "emperror.dev/errors""github.com/labstack/echo/v5""github.com/samber/mo")@@ -68,7 +69,7 @@ func collectCommandResponseInternal(ctx context.Context, tunnel *AgentTunnel, peif done, status, headers, body, err := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {return status, headers, body, err}- return 0, nil, nil, errors.WrapIf(ErrTunnelConnectionClosed, "edge tunnel closed while waiting for response")+ return 0, nil, nil, fmt.Errorf("edge tunnel closed while waiting for response: %w", ErrTunnelConnectionClosed)case err := <-pending.failureCh:if done, status, headers, body, err := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {return status, headers, body, err@@ -76,7 +77,7 @@ func collectCommandResponseInternal(ctx context.Context, tunnel *AgentTunnel, pereturn 0, nil, nil, errcase incoming, ok := <-pending.ResponseCh:if !ok {- return 0, nil, nil, errors.WrapIf(ErrTunnelConnectionClosed, "edge tunnel response channel closed before a response was received")+ return 0, nil, nil, fmt.Errorf("edge tunnel response channel closed before a response was received: %w", ErrTunnelConnectionClosed)}if done, status, headers, body, err := state.handleTunnelMessageInternal(method, incoming); done {return status, headers, body, err@@ -125,7 +126,7 @@ func (s *grpcResponseState) drainTerminalResponseInternal(respCh <-chan *TunnelMselect {case incoming, ok := <-respCh:if !ok {- return true, 0, nil, nil, errors.WrapIf(ErrTunnelConnectionClosed, "edge tunnel response channel closed before a response was received")+ return true, 0, nil, nil, fmt.Errorf("edge tunnel response channel closed before a response was received: %w", ErrTunnelConnectionClosed)}if done, status, headers, body, err := s.handleTunnelMessageInternal(method, incoming); done {return true, status, headers, body, err@@ -361,10 +362,10 @@ func DoRequest(ctx context.Context, envID, method, path string, body []byte) (intunnel, ok := GetRegistry().Get(envID).Get()if !ok {- return 0, nil, errors.Errorf("no active tunnel for environment %s", envID)+ return 0, nil, fmt.Errorf("no active tunnel for environment %s", envID)}if tunnel.Conn.IsClosed() {- return 0, nil, errors.Errorf("tunnel for environment %s is closed", envID)+ return 0, nil, fmt.Errorf("tunnel for environment %s is closed", envID)}headers := make(map[string]string)diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.goindex dc72ed97a..2b9c88f9b 100644--- a/backend/pkg/libarcane/edge/registry.go+++ b/backend/pkg/libarcane/edge/registry.go@@ -2,11 +2,11 @@ package edgeimport ("context"+ "errors""log/slog""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/concurrency""github.com/samber/mo")@@ -269,7 +269,7 @@ func (r *TunnelRegistry) Stop(ctx context.Context) error {}for _, tunnel := range removed {if tunnel != nil {- err = errors.Combine(err, tunnel.CloseWithReason("edge tunnel registry stopped"))+ err = errors.Join(err, tunnel.CloseWithReason("edge tunnel registry stopped"))}}return errdiff --git a/backend/pkg/libarcane/edge/request_context.go b/backend/pkg/libarcane/edge/request_context.godeleted file mode 100644index b996a99c7..000000000--- a/backend/pkg/libarcane/edge/request_context.go+++ /dev/null@@ -1,13 +0,0 @@-package edge--import "context"--// IsInternalTunnelRequest reports whether a request is being dispatched by the-// in-process edge tunnel client instead of a real network listener.-func IsInternalTunnelRequest(ctx context.Context) bool {- if ctx == nil {- return false- }- isInternal, _ := ctx.Value(internalTunnelRequestContextKey{}).(bool)- return isInternal-}diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.goindex 506ae91be..a9f4cd038 100644--- a/backend/pkg/libarcane/edge/server.go+++ b/backend/pkg/libarcane/edge/server.go@@ -3,6 +3,8 @@ package edgeimport ("context""crypto/tls"+ "errors"+ "fmt""io""log/slog""net/http"@@ -11,10 +13,9 @@ import ("time""uuid"- "emperror.dev/emperror"- "emperror.dev/errors"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate""github.com/labstack/echo/v5"@@ -517,7 +518,7 @@ func (s *TunnelServer) deliverResponse(ctx context.Context, tunnel *AgentTunnel,select {case pending.ResponseCh <- msg:default:- err := errors.Errorf("response delivery failed because pending request %s is not consuming messages", msg.ID)+ err := fmt.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)@@ -544,7 +545,7 @@ func (s *TunnelServer) deliverStream(ctx context.Context, tunnel *AgentTunnel, mcase <-ctx.Done():returncase <-deliveryTimer.C:- err := errors.Errorf("stream delivery timed out for pending request %s", msg.ID)+ err := fmt.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",@@ -667,7 +668,7 @@ 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 panicErr := emperror.Recover(recover()); panicErr != nil {+ if panicErr := utils.PanicToError(recover()); panicErr != nil {slog.ErrorContext(ss.Context(), "panic in gRPC tunnel stream","method", info.FullMethod,"error", panicErr,@@ -752,3 +753,13 @@ func securityModeFromGRPCContextInternal(ctx context.Context) string {}return grpcContextSecurityModeInternal(*p)}++// IsInternalTunnelRequest reports whether a request is being dispatched by the+// in-process edge tunnel client instead of a real network listener.+func IsInternalTunnelRequest(ctx context.Context) bool {+ if ctx == nil {+ return false+ }+ isInternal, _ := ctx.Value(internalTunnelRequestContextKey{}).(bool)+ return isInternal+}diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.goindex ff9ced99e..bc8d297f8 100644--- a/backend/pkg/libarcane/edge/tls.go+++ b/backend/pkg/libarcane/edge/tls.go@@ -13,6 +13,7 @@ import ("crypto/x509""encoding/json/v2""encoding/pem"+ "errors""fmt""io""io/fs"@@ -28,7 +29,6 @@ import ("syscall""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"@@ -76,7 +76,7 @@ func BuildManagerServerTLSConfig(cfg *Config) (*tls.Config, error) {caPool, err := loadCertPoolInternal(strings.TrimSpace(cfg.EdgeMTLSCAFile))if err != nil {- return nil, errors.WrapIf(err, "failed to load edge mTLS CA file")+ return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)}// ClientAuth is intentionally VerifyClientCertIfGiven even when@@ -162,12 +162,12 @@ func AvailableManagerMTLSCAPath(cfg *Config) (string, error) {caPath, err := generatedManagerMTLSCAPathInternal(cfg)if err != nil {- return "", errors.WrapIf(err, "resolve edge mTLS CA path")+ return "", fmt.Errorf("resolve edge mTLS CA path: %w", err)}// os.* rather than acfs: the assets dir may be user-configured to anywhere on// the host, so no confinement root handle is in scope for this probe.if _, err := os.Stat(caPath); err != nil {- return "", errors.WrapIf(err, "stat edge mTLS CA")+ return "", fmt.Errorf("stat edge mTLS CA: %w", err)}return caPath, nil}@@ -197,15 +197,15 @@ func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *ConfigcaPEM, err := readGeneratedAssetInternal(ctx, assetsDir, caCertPath)if err != nil {- return nil, errors.WrapIf(err, "failed to read generated CA certificate")+ return nil, fmt.Errorf("failed to read generated CA certificate: %w", err)}clientCertPEM, err := readGeneratedAssetInternal(ctx, assetsDir, clientCertPath)if err != nil {- return nil, errors.WrapIf(err, "failed to read generated client certificate")+ return nil, fmt.Errorf("failed to read generated client certificate: %w", err)}clientKeyPEM, err := readGeneratedAssetInternal(ctx, assetsDir, clientKeyPath)if err != nil {- return nil, errors.WrapIf(err, "failed to read generated client key")+ return nil, fmt.Errorf("failed to read generated client key: %w", err)}return &GeneratedMTLSAssets{@@ -284,7 +284,7 @@ func readMTLSEnrollmentMarkerInternal(path string) (time.Time, error) {}enrolledAt, err := time.Parse(time.RFC3339Nano, trimmed)if err != nil {- return time.Time{}, errors.WrapIff(err, "failed to parse edge mTLS enrollment marker %s", path)+ return time.Time{}, fmt.Errorf("failed to parse edge mTLS enrollment marker %s: %w", path, err)}return enrolledAt, nil}@@ -325,7 +325,7 @@ func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error {if !needsEnrollment {if !fileExistsInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName)) {if err := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {- return errors.WrapIf(err, "failed to write edge mTLS enrollment marker")+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)}}setAgentMTLSAssetPathsInternal(cfg, assetsDir)@@ -358,12 +358,12 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,httpClient, err := NewManagerHTTPClient(cfg, 30*time.Second)if err != nil {- return errors.WrapIf(err, "failed to configure edge mTLS enrollment client")+ return fmt.Errorf("failed to configure edge mTLS enrollment client: %w", err)}req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerBaseURL+"/api/tunnel/mtls/enroll", nil)if err != nil {- return errors.WrapIf(err, "failed to create edge mTLS enrollment request")+ return fmt.Errorf("failed to create edge mTLS enrollment request: %w", err)}req.Header.Set(HeaderAgentToken, cfg.AgentToken)req.Header.Set(HeaderAPIKey, cfg.AgentToken)@@ -371,18 +371,18 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,resp, err := httpClient.Do(req)if err != nil {- return errors.WrapIf(err, "edge mTLS enrollment request failed")+ return fmt.Errorf("edge mTLS enrollment request failed: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(io.LimitReader(resp.Body, maxEnrollResponseBytes))- return errors.Errorf("edge mTLS enrollment failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return fmt.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 errors.WrapIf(err, "failed to decode edge mTLS enrollment response")+ return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", err)}if len(enrollResp.Files) == 0 {return errors.New("edge mTLS enrollment response did not include any files")@@ -391,20 +391,20 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,// The assets dir is the confinement root for the writes below, so it is// created through os before acfs opens it.if err := os.MkdirAll(assetsDir, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create edge mTLS asset dir")+ return fmt.Errorf("failed to create edge mTLS asset dir: %w", err)}for _, file := range enrollResp.Files {perm := kit.Ternary(strings.TrimSpace(file.Permissions) == "0600", 0o600, utils.FilePerm)if err := acfs.Write(ctx, assetsDir, "/"+filepath.Base(file.Name), []byte(file.Content), acfs.WriteOptions{Mode: perm}); err != nil {- return errors.WrapIff(err, "failed to write edge mTLS asset %s", file.Name)+ return fmt.Errorf("failed to write edge mTLS asset %s: %w", file.Name, err)}}needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())if needsEnrollment {- return errors.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)+ return fmt.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)}if err := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {- return errors.WrapIf(err, "failed to write edge mTLS enrollment marker")+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)}setAgentMTLSAssetPathsInternal(cfg, assetsDir)@@ -427,7 +427,7 @@ func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {if caFile := strings.TrimSpace(cfg.EdgeMTLSCAFile); caFile != "" {pool, err := loadSystemOrCustomCertPoolInternal(caFile)if err != nil {- return nil, errors.WrapIf(err, "failed to load edge mTLS CA file")+ return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)}tlsConfig.RootCAs = pool}@@ -438,7 +438,7 @@ func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {keyPath := strings.TrimSpace(cfg.EdgeMTLSKeyFile)needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())if needsEnrollment {- err := errors.Errorf("edge mTLS client certificate is unusable: %s", reason)+ err := fmt.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@@ -451,7 +451,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, errors.WrapIf(err, "failed to load edge mTLS client certificate")+ return nil, fmt.Errorf("failed to load edge mTLS client certificate: %w", err)}if cert.Leaf != nil {if _, ok := cert.Leaf.PublicKey.(*mldsa.PublicKey); ok {@@ -502,7 +502,7 @@ func ValidateManagerMTLSConfig(cfg *Config) error {_, err := loadCertPoolInternal(cfg.EdgeMTLSCAFile)if err != nil {- return errors.WrapIf(err, "failed to load edge mTLS CA file")+ return fmt.Errorf("failed to load edge mTLS CA file: %w", err)}return nil}@@ -666,7 +666,7 @@ func verifiedPeerCertificateEnvironmentIDMatchesInternal(state *tls.ConnectionStreturn nil}}- return errors.Errorf("verified edge mTLS client certificate does not match environment %s", strings.TrimSpace(envID))+ return fmt.Errorf("verified edge mTLS client certificate does not match environment %s", strings.TrimSpace(envID))}func edgeMTLSAppURLInternal(cfg *Config) string {@@ -701,7 +701,7 @@ func edgeMTLSAssetsDirInternal(cfg *Config) (string, error) {resolved, err := filepath.Abs(baseDir)if err != nil {- return "", errors.WrapIf(err, "failed to resolve edge mTLS assets dir")+ return "", fmt.Errorf("failed to resolve edge mTLS assets dir: %w", err)}return resolved, nil}@@ -722,7 +722,7 @@ func edgeAgentMTLSAssetsDirInternal(cfg *Config) (string, error) {resolved, err := filepath.Abs(baseDir)if err != nil {- return "", errors.WrapIf(err, "failed to resolve edge agent mTLS assets dir")+ return "", fmt.Errorf("failed to resolve edge agent mTLS assets dir: %w", err)}return resolved, nil}@@ -731,7 +731,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, str// The assets dir is the confinement root for everything below, so it is// created through os before acfs opens it.if err := os.MkdirAll(assetsDir, utils.DirPerm); err != nil {- return "", "", false, errors.WrapIf(err, "failed to create edge mTLS assets dir")+ return "", "", false, fmt.Errorf("failed to create edge mTLS assets dir: %w", err)}unlock, err := lockEdgeMTLSPathInternal(ctx, assetsDir, ".ca.lock")@@ -750,7 +750,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, strprivateKey, err := certgen.GenerateMLDSA87PrivateKey()if err != nil {- return "", "", false, errors.WrapIf(err, "failed to generate CA private key")+ return "", "", false, fmt.Errorf("failed to generate CA private key: %w", err)}template, err := certgen.NewEdgeMTLSCATemplate()@@ -760,7 +760,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, errors.WrapIf(err, "failed to create CA certificate")+ return "", "", false, fmt.Errorf("failed to create CA certificate: %w", err)}if err := writePEMFileInternal(caCertPath, "CERTIFICATE", certDER, utils.FilePerm); err != nil {@@ -768,7 +768,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, str}caKeyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)if err != nil {- return "", "", false, errors.WrapIf(err, "failed to marshal CA private key")+ return "", "", false, fmt.Errorf("failed to marshal CA private key: %w", err)}if err := writeCAKeyFileInternal(caKeyPath, caKeyDER); err != nil {return "", "", false, err@@ -796,7 +796,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envNcaCertPEM, err := readGeneratedAssetInternal(ctx, assetsDir, caCertPath)if err != nil {- return "", "", false, errors.WrapIf(err, "failed to read CA certificate")+ return "", "", false, fmt.Errorf("failed to read CA certificate: %w", err)}caKeyPEM, err := readCAKeyPEMInternal(caKeyPath)if err != nil {@@ -809,7 +809,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envN}caCert, err := x509.ParseCertificate(caCertBlock.Bytes)if err != nil {- return "", "", false, errors.WrapIf(err, "failed to parse CA certificate")+ return "", "", false, fmt.Errorf("failed to parse CA certificate: %w", err)}caKey, err := parsePrivateKeyPEMInternal(caKeyPEM, "CA")@@ -820,7 +820,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envNsafeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")clientDir := filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID)if err := acfs.MkdirAll(ctx, assetsDir, path.Join("/", generatedClientMTLSSubdir, safeEnvID), utils.DirPerm); err != nil {- return "", "", false, errors.WrapIf(err, "failed to create client cert dir")+ return "", "", false, fmt.Errorf("failed to create client cert dir: %w", err)}unlock, err := lockEdgeMTLSPathInternal(ctx, clientDir, ".client.lock")if err != nil {@@ -844,7 +844,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envNprivateKey, err := generateKeyLikeInternal(caKey)if err != nil {- return "", "", false, errors.WrapIf(err, "failed to generate client private key")+ return "", "", false, fmt.Errorf("failed to generate client private key: %w", err)}uriSAN, dnsSANs := buildGeneratedClientSANsInternal(envName, safeEnvID, appURL)template, err := certgen.NewEdgeMTLSClientTemplate(expectedCommonName, uriSAN, dnsSANs)@@ -854,7 +854,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envNcertDER, err := x509.CreateCertificate(rand.Reader, template, caCert, privateKey.Public(), caKey)if err != nil {- return "", "", false, errors.WrapIf(err, "failed to create client certificate")+ return "", "", false, fmt.Errorf("failed to create client certificate: %w", err)}if err := writePEMFileInternal(clientCertPath, "CERTIFICATE", certDER, utils.FilePerm); err != nil {@@ -871,7 +871,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envNclientKeyDER, err = x509.MarshalPKCS8PrivateKey(privateKey)}if err != nil {- return "", "", false, errors.WrapIf(err, "failed to marshal client private key")+ return "", "", false, fmt.Errorf("failed to marshal client private key: %w", err)}if err := writePEMFileInternal(clientKeyPath, keyPEMType, clientKeyDER, 0o600); err != nil {return "", "", false, err@@ -966,10 +966,10 @@ func validateGeneratedClientCertificateInternal(certPath, keyPath, expectedCommoreturn errors.New("generated client certificate is not currently valid")}if strings.TrimSpace(expectedCommonName) != "" && cert.Subject.CommonName != expectedCommonName {- return errors.Errorf("generated client certificate common name %q does not match expected %q", cert.Subject.CommonName, expectedCommonName)+ return fmt.Errorf("generated client certificate common name %q does not match expected %q", cert.Subject.CommonName, expectedCommonName)}if expectedURISAN != nil && !certificateHasURISANInternal(cert, expectedURISAN) {- return errors.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())+ return fmt.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())}if err := validateGeneratedKeyTypeInternal(cert.PublicKey, "generated client certificate"); err != nil {return err@@ -1033,22 +1033,22 @@ func agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath string, now time.Tifunc validateCertificateKeyPairInternal(cert *x509.Certificate, privateKey crypto.Signer, label string) error {if cert == nil {- return errors.Errorf("%s certificate is required", label)+ return fmt.Errorf("%s certificate is required", label)}if privateKey == nil {- return errors.Errorf("%s private key is required", label)+ return fmt.Errorf("%s private key is required", label)}certPublicKeyDER, err := x509.MarshalPKIXPublicKey(cert.PublicKey)if err != nil {- return errors.WrapIff(err, "failed to marshal %s certificate public key", label)+ return fmt.Errorf("failed to marshal %s certificate public key: %w", label, err)}privatePublicKeyDER, err := x509.MarshalPKIXPublicKey(privateKey.Public())if err != nil {- return errors.WrapIff(err, "failed to marshal %s private key public key", label)+ return fmt.Errorf("failed to marshal %s private key public key: %w", label, err)}if !bytes.Equal(certPublicKeyDER, privatePublicKeyDER) {- return errors.Errorf("%s certificate public key does not match private key", label)+ return fmt.Errorf("%s certificate public key does not match private key", label)}return nil@@ -1065,7 +1065,7 @@ func validateGeneratedKeyTypeInternal(publicKey any, label string) error {return nil}}- return errors.Errorf("%s is not ECDSA P-384 or ML-DSA-87", label)+ return fmt.Errorf("%s is not ECDSA P-384 or ML-DSA-87", label)}func generateKeyLikeInternal(caKey crypto.Signer) (crypto.Signer, error) {@@ -1078,18 +1078,18 @@ func generateKeyLikeInternal(caKey crypto.Signer) (crypto.Signer, error) {func parsePrivateKeyPEMInternal(pemBytes []byte, label string) (crypto.Signer, error) {block, _ := pem.Decode(pemBytes)if block == nil {- return nil, errors.Errorf("failed to parse %s private key PEM", label)+ return nil, fmt.Errorf("failed to parse %s private key PEM", label)}if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {signer, ok := key.(crypto.Signer)if !ok {- return nil, errors.Errorf("%s private key is not a signer", label)+ return nil, fmt.Errorf("%s private key is not a signer", label)}return signer, nil}key, err := x509.ParseECPrivateKey(block.Bytes)if err != nil {- return nil, errors.WrapIff(err, "failed to parse %s private key", label)+ return nil, fmt.Errorf("failed to parse %s private key: %w", label, err)}return key, nil}@@ -1099,15 +1099,15 @@ func readCertificateInternal(path string) (*x509.Certificate, error) {// user-configured absolute cert paths, so no single confinement root exists.pemBytes, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIff(err, "failed to read certificate %s", path)+ return nil, fmt.Errorf("failed to read certificate %s: %w", path, err)}block, _ := pem.Decode(pemBytes)if block == nil {- return nil, errors.Errorf("failed to parse certificate PEM %s", path)+ return nil, fmt.Errorf("failed to parse certificate PEM %s", path)}cert, err := x509.ParseCertificate(block.Bytes)if err != nil {- return nil, errors.WrapIff(err, "failed to parse certificate %s", path)+ return nil, fmt.Errorf("failed to parse certificate %s: %w", path, err)}return cert, nil}@@ -1117,7 +1117,7 @@ func readPrivateKeyInternal(path string) (crypto.Signer, error) {// user-configured absolute key paths, so no single confinement root exists.pemBytes, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIff(err, "failed to read private key %s", path)+ return nil, fmt.Errorf("failed to read private key %s: %w", path, err)}return parsePrivateKeyPEMInternal(pemBytes, path)}@@ -1125,7 +1125,7 @@ func readPrivateKeyInternal(path string) (crypto.Signer, error) {func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func(), error) {absDir, err := filepath.Abs(dir)if err != nil {- return nil, errors.WrapIf(err, "failed to resolve edge mTLS lock dir")+ return nil, fmt.Errorf("failed to resolve edge mTLS lock dir: %w", err)}lockName = cmp.Or(strings.TrimSpace(lockName), ".lock")@@ -1153,7 +1153,7 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func()}if !os.IsExist(err) {unlock()- return nil, errors.WrapIf(err, "failed to acquire edge mTLS CA lock")+ return nil, fmt.Errorf("failed to acquire edge mTLS CA lock: %w", err)}if time.Now().After(deadline) {if removeStaleEdgeMTLSLockInternal(lockPath) {@@ -1165,7 +1165,7 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func()continue}unlock()- return nil, errors.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)+ return nil, fmt.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)}unlock()if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {@@ -1180,7 +1180,7 @@ func waitForEdgeMTLSLockPollInternal(ctx context.Context) error {select {case <-ctx.Done():- return errors.WrapIf(ctx.Err(), "cancelled waiting for edge mTLS CA lock")+ return fmt.Errorf("cancelled waiting for edge mTLS CA lock: %w", ctx.Err())case <-timer.C:return nil}@@ -1211,7 +1211,7 @@ func readEdgeMTLSLockInfoInternal(lockPath string) (*edgeMTLSLockInfo, error) {}pid, err := strconv.Atoi(fields[0])if err != nil {- return nil, errors.WrapIf(err, "parse edge mTLS lock PID")+ return nil, fmt.Errorf("parse edge mTLS lock PID: %w", err)}if pid <= 0 {return nil, errors.New("edge mTLS lock PID must be positive")@@ -1245,7 +1245,7 @@ func edgeMTLSLockPIDAliveInternal(pid int) bool {func writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})if pemBytes == nil {- return errors.Errorf("failed to encode PEM file %s", path)+ return fmt.Errorf("failed to encode PEM file %s", path)}return atomic.WriteFile(path, pemBytes, perm)}@@ -1262,7 +1262,7 @@ func writeCAKeyFileInternal(path string, derBytes []byte) error {ciphertext, err := caKeyEncryptInternal(string(pemBytes))if err != nil {- return errors.WrapIf(err, "failed to encrypt edge mTLS CA private key")+ return fmt.Errorf("failed to encrypt edge mTLS CA private key: %w", err)}if ciphertext == "" {return errors.New("failed to encrypt edge mTLS CA private key: encrypted payload is empty")@@ -1278,16 +1278,16 @@ func writeCAKeyFileInternal(path string, derBytes []byte) error {func readCAKeyPEMInternal(path string) ([]byte, error) {raw, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIff(err, "failed to read CA private key %s", path)+ return nil, fmt.Errorf("failed to read CA private key %s: %w", path, err)}trimmed := strings.TrimSpace(string(raw))if !strings.HasPrefix(trimmed, caKeyEncryptedPrefix) {- return nil, errors.Errorf("CA private key %s is not in the expected encrypted envelope format", path)+ return nil, fmt.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, errors.WrapIff(err, "failed to decrypt CA private key %s", path)+ return nil, fmt.Errorf("failed to decrypt CA private key %s: %w", path, err)}return []byte(plaintext), nil}diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.goindex ef03653ca..491738218 100644--- a/backend/pkg/libarcane/edge/tunnel.go+++ b/backend/pkg/libarcane/edge/tunnel.go@@ -3,11 +3,11 @@ package edgeimport ("context""encoding/json/v2"+ "errors""io""log/slog""net"- "emperror.dev/errors""github.com/coder/websocket"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1"@@ -27,7 +27,6 @@ const (// ErrTunnelConnectionClosed is returned by Send and Receive on every transport// once the tunnel connection is closed.- ErrTunnelConnectionClosed = errors.Sentinel("edge tunnel connection is closed")// MessageTypeRequest is sent from manager to agent to initiate a request.MessageTypeRequest TunnelMessageType = "request"@@ -71,6 +70,8 @@ const (MessageTypeCancelRequest TunnelMessageType = "cancel_request")+var ErrTunnelConnectionClosed = errors.New("edge tunnel connection is closed")+// tunnelReadWait bounds how long a websocket tunnel read may sit idle. Both// peers see traffic at least every DefaultHeartbeatInterval (agent heartbeat,// manager heartbeat_ack), so 3x tolerates transient stalls while stilldiff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter.goindex ba285e1da..e2ba97d1a 100644--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter.go@@ -1,10 +1,11 @@package edgeimport (+ "errors"+ "fmt""maps""math"- "emperror.dev/errors"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1")@@ -12,7 +13,7 @@ import (// a oneof case added by a newer peer. Receivers skip such messages instead of// killing the stream, mirroring how unknown JSON message types are ignored on// the websocket transport.-const errUnknownTunnelPayload = errors.Sentinel("unknown tunnel payload type")+var errUnknownTunnelPayload = errors.New("unknown tunnel payload type")// tunnelMessageToManagerProto encodes a manager->agent message. parity is true// once the agent advertised tunnelCapabilityProtoParity; without it, legacy@@ -72,7 +73,7 @@ func tunnelMessageToManagerProto(msg *TunnelMessage, parity bool) (*tunnelpb.Manif parity {return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_StreamEnd{StreamEnd: &tunnelpb.StreamEnd{RequestId: msg.ID}}}, nil}- return nil, errors.Errorf("unsupported manager message type: %s", msg.Type)+ return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)case MessageTypeWebSocketClose:return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_WsClose{WsClose: &tunnelpb.WebSocketClose{StreamId: msg.ID}}}, nilcase MessageTypeRegisterResponse:@@ -133,9 +134,9 @@ func tunnelMessageToManagerProto(msg *TunnelMessage, parity bool) (*tunnelpb.ManMessageTypeCommandAck,MessageTypeCommandOutput,MessageTypeCommandComplete:- return nil, errors.Errorf("unsupported manager message type: %s", msg.Type)+ return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)default:- return nil, errors.Errorf("unsupported manager message type: %s", msg.Type)+ return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)}}@@ -243,7 +244,7 @@ func managerProtoToTunnelMessage(msg *tunnelpb.ManagerMessage) (*TunnelMessage,case *tunnelpb.ManagerMessage_StreamEnd:return &TunnelMessage{ID: payload.StreamEnd.GetRequestId(), Type: MessageTypeStreamEnd}, nildefault:- return nil, errors.WrapIff(errUnknownTunnelPayload, "manager payload %T", payload)+ return nil, fmt.Errorf("manager payload %T: %w", payload, errUnknownTunnelPayload)}}@@ -299,7 +300,7 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erro}}}, nilcase MessageTypeEvent:if msg.Event == nil {- return nil, errors.Errorf("event payload is required for message type: %s", msg.Type)+ return nil, fmt.Errorf("event payload is required for message type: %s", msg.Type)}return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Event{Event: &tunnelpb.EventLog{Id: msg.ID,@@ -362,9 +363,9 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erroMessageTypeRegisterResponse,MessageTypeCommandRequest,MessageTypeStreamOpen:- return nil, errors.Errorf("unsupported agent message type: %s", msg.Type)+ return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)default:- return nil, errors.Errorf("unsupported agent message type: %s", msg.Type)+ return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)}}@@ -467,7 +468,7 @@ func agentProtoToTunnelMessage(msg *tunnelpb.AgentMessage) (*TunnelMessage, erroType: MessageTypeCancelRequest,}, nildefault:- return nil, errors.WrapIff(errUnknownTunnelPayload, "agent payload %T", payload)+ return nil, fmt.Errorf("agent payload %T: %w", payload, errUnknownTunnelPayload)}}@@ -482,7 +483,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, errors.Errorf("%s value %d is out of int32 range", field, value)+ return 0, fmt.Errorf("%s value %d is out of int32 range", field, value)}return int32(value), nil}diff --git a/backend/pkg/libarcane/internal_resource.go b/backend/pkg/libarcane/internal_resource.goindex cf5fd8c1c..14c57d093 100644--- a/backend/pkg/libarcane/internal_resource.go+++ b/backend/pkg/libarcane/internal_resource.go@@ -3,11 +3,12 @@ package libarcaneimport ("cmp""context"+ "errors"+ "fmt""log/slog""os""strings"- "emperror.dev/errors""github.com/moby/moby/api/types/container""github.com/moby/moby/client""go.getarcane.app/docker/compat"@@ -87,7 +88,7 @@ func InspectCurrentArcaneContainer(ctx context.Context, dockerClient *client.Cliif containerID := FindArcaneContainerIDByLabel(ctx, dockerClient); containerID != "" {inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {- return nil, errors.WrapIf(err, "inspect Arcane container")+ return nil, fmt.Errorf("inspect Arcane container: %w", err)}// An unlabeled derived hit is only overridden by the labeled match when// that match shares the derived container's network namespace — i.e. thediff --git a/backend/pkg/libarcane/internal_resource_test.go b/backend/pkg/libarcane/internal_resource_test.goindex 62a70a760..bd468e1bc 100644--- a/backend/pkg/libarcane/internal_resource_test.go+++ b/backend/pkg/libarcane/internal_resource_test.go@@ -2,12 +2,12 @@ package libarcaneimport ("context"+ "errors""net/http""net/http/httptest""strings""testing"- "emperror.dev/errors""github.com/moby/moby/client""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"diff --git a/backend/pkg/libarcane/registryauth/helpers.go b/backend/pkg/libarcane/registryauth/helpers.goindex fab854a6e..501d6b30c 100644--- a/backend/pkg/libarcane/registryauth/helpers.go+++ b/backend/pkg/libarcane/registryauth/helpers.go@@ -1,11 +1,11 @@package registryauthimport (+ "fmt""maps""slices""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"@@ -76,7 +76,7 @@ func EncodeAuthHeader(username, password, serverAddress string) (string, error)ServerAddress: serverAddress,})if err != nil {- return "", errors.WrapIf(err, "encode registry auth header")+ return "", fmt.Errorf("encode registry auth header: %w", err)}return auth, nil}@@ -84,7 +84,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{}, errors.WrapIf(err, "decode registry auth header")+ return dockerregistry.AuthConfig{}, fmt.Errorf("decode registry auth header: %w", err)}if cfg == nil {return dockerregistry.AuthConfig{}, nildiff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.goindex d9cecffb4..a128e3116 100644--- a/backend/pkg/libarcane/startup/runtime_identity.go+++ b/backend/pkg/libarcane/startup/runtime_identity.go@@ -3,6 +3,7 @@ package startupimport ("cmp""context"+ "fmt""log/slog""net/url""os"@@ -10,7 +11,6 @@ import ("strconv""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo"kit "go.getarcane.app/kit/pkg"@@ -104,7 +104,7 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConfif inContainer {mountpoints, err := loadMountpointsInternal(mountInfoPath)if err != nil {- return errors.WrapIf(err, "load mountpoints")+ return fmt.Errorf("load mountpoints: %w", err)}if err := prepareWritablePathsWithRootsInternal(runtimeUID, runtimeGID, mountpoints, projectsDir, defaultDataDirectory, defaultBuildsDirectory); err != nil {@@ -139,12 +139,12 @@ func loadRuntimeIdentityRequestInternal(cfg *RuntimeIdentityConfig, inContaineruid, credentialUID, err := parseRuntimeIdentityValueInternal(puid, "PUID")if err != nil {- return runtimeIdentityRequest{}, "", errors.WrapIff(err, "invalid PUID %q", puid)+ return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PUID %q: %w", puid, err)}gid, credentialGID, err := parseRuntimeIdentityValueInternal(pgid, "PGID")if err != nil {- return runtimeIdentityRequest{}, "", errors.WrapIff(err, "invalid PGID %q", pgid)+ return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PGID %q: %w", pgid, err)}return runtimeIdentityRequest{@@ -203,12 +203,12 @@ func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(s}if err := os.MkdirAll(configDir, utils.DirPerm); err != nil {- return errors.WrapIf(err, "create docker config directory")+ return fmt.Errorf("create docker config directory: %w", err)}if configDir == defaultDockerConfigDir && os.Geteuid() == 0 {if err := os.Chown(configDir, uid, gid); err != nil {- return errors.WrapIf(err, "chown docker config directory")+ return fmt.Errorf("chown docker config directory: %w", err)}}@@ -237,7 +237,7 @@ func configureRuntimeDockerConfigEnvInternal(cfg *RuntimeIdentityConfig, setenvconfigDir = defaultDockerConfigDircfg.DockerConfig = configDirif err := setenv("DOCKER_CONFIG", configDir); err != nil {- return "", errors.WrapIf(err, "set DOCKER_CONFIG")+ return "", fmt.Errorf("set DOCKER_CONFIG: %w", err)}return configDir, nil@@ -289,40 +289,40 @@ func dockerSocketPathInternal(raw string) mo.Option[string] {func prepareWritablePathsWithRootsInternal(uid, gid int, mountpoints map[string]struct{}, projectsDir, dataDirectory, buildsDirectory string) error {if err := os.MkdirAll(dataDirectory, utils.DirPerm); err != nil {- return errors.WrapIf(err, "create data directory")+ return fmt.Errorf("create data directory: %w", err)}if err := os.Chown(dataDirectory, uid, gid); err != nil {- return errors.WrapIf(err, "chown data directory")+ return fmt.Errorf("chown data directory: %w", err)}entries, err := os.ReadDir(dataDirectory)if err != nil {- return errors.WrapIf(err, "read data directory")+ return fmt.Errorf("read data directory: %w", err)}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 errors.WrapIff(err, "chown mounted %s", entryPath)+ return fmt.Errorf("chown mounted %s: %w", entryPath, err)}continue}if projectsDir != "" && filepath.Clean(entryPath) == projectsDir {if err := lchownFn(entryPath, uid, gid); err != nil {- return errors.WrapIff(err, "chown %s", entryPath)+ return fmt.Errorf("chown %s: %w", entryPath, err)}continue}if err := chownRecursiveInternal(entryPath, uid, gid, mountpoints, projectsDir); err != nil {- return errors.WrapIff(err, "chown %s", entryPath)+ return fmt.Errorf("chown %s: %w", entryPath, err)}}if _, mounted := mountpoints[buildsDirectory]; mounted {if err := os.Lchown(buildsDirectory, uid, gid); err != nil {- return errors.WrapIf(err, "chown mounted builds directory")+ return fmt.Errorf("chown mounted builds directory: %w", err)}return nil}@@ -331,11 +331,11 @@ func prepareWritablePathsWithRootsInternal(uid, gid int, mountpoints map[string]if os.IsNotExist(err) {return nil}- return errors.WrapIf(err, "stat builds directory")+ return fmt.Errorf("stat builds directory: %w", err)}if err := chownRecursiveInternal(buildsDirectory, uid, gid, mountpoints, projectsDir); err != nil {- return errors.WrapIf(err, "chown builds directory")+ return fmt.Errorf("chown builds directory: %w", err)}return nil@@ -356,16 +356,16 @@ func ensureSQLiteFilesExistInternal(databaseURL string) error {dir := filepath.Dir(sqlitePath)if dir != "" && dir != "." {if err := os.MkdirAll(dir, utils.DirPerm); err != nil {- return errors.WrapIff(err, "create sqlite directory %s", dir)+ return fmt.Errorf("create sqlite directory %s: %w", dir, err)}}file, err := os.OpenFile(sqlitePath, os.O_CREATE|os.O_RDWR, utils.FilePerm)if err != nil {- return errors.WrapIff(err, "create sqlite file %s", sqlitePath)+ return fmt.Errorf("create sqlite file %s: %w", sqlitePath, err)}if err := file.Close(); err != nil {- return errors.WrapIff(err, "close sqlite file %s", sqlitePath)+ return fmt.Errorf("close sqlite file %s: %w", sqlitePath, err)}return nil@@ -379,7 +379,7 @@ func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {parsed, err := url.Parse(value)if err != nil {- return "", false, errors.WrapIf(err, "parse sqlite database url")+ return "", false, fmt.Errorf("parse sqlite database url: %w", err)}// 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 672a4d5f2..8ca6eed95 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go@@ -3,19 +3,18 @@package startupimport (+ "fmt""strconv"-- "emperror.dev/errors")func parseRuntimeIdentityValueInternal(raw, key string) (int, uint32, error) {value, err := strconv.ParseInt(raw, 10, 32)if err != nil {- return 0, 0, errors.WrapIff(err, "parse %s", key)+ return 0, 0, fmt.Errorf("parse %s: %w", key, err)}if value < 0 {- return 0, 0, errors.Errorf("%s must be >= 0", key)+ return 0, 0, fmt.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 cf5e76018..9bc3015e3 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go@@ -3,24 +3,23 @@package startupimport (+ "fmt""math""strconv"-- "emperror.dev/errors")func parseRuntimeIdentityValueInternal(raw, key string) (int, uint32, error) {value, err := strconv.Atoi(raw)if err != nil {- return 0, 0, errors.WrapIff(err, "parse %s", key)+ return 0, 0, fmt.Errorf("parse %s: %w", key, err)}if value < 0 {- return 0, 0, errors.Errorf("%s must be >= 0", key)+ return 0, 0, fmt.Errorf("%s must be >= 0", key)}if value > math.MaxUint32 {- return 0, 0, errors.Errorf("%s value %d exceeds max uint32", key, value)+ return 0, 0, fmt.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 1d242ac5d..e1c5b50aa 100644--- a/backend/pkg/libarcane/startup/runtime_identity_linux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_linux.go@@ -4,19 +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 errors.WrapIf(err, "resolve executable")+ return fmt.Errorf("resolve executable: %w", err)}groups := runtimeIdentitySupplementaryGroupsInternal(req.DockerHost, resolveSocketGroupInternal)@@ -35,7 +36,7 @@ func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityR}if err := cmd.Start(); err != nil {- return errors.WrapIf(err, "start runtime identity child")+ return fmt.Errorf("start runtime identity child: %w", err)}sigCh := make(chan os.Signal, 2)@@ -58,8 +59,7 @@ func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityRos.Exit(0)}- var exitErr *exec.ExitError- if errors.As(err, &exitErr) {+ if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {if status.Signaled() {os.Exit(128 + int(status.Signal()))@@ -69,7 +69,7 @@ func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityRos.Exit(exitErr.ExitCode())}- return errors.WrapIf(err, "wait for runtime identity child")+ return fmt.Errorf("wait for runtime identity child: %w", err)}}}diff --git a/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.goindex cfed7b073..2146784c7 100644--- a/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go@@ -4,9 +4,8 @@ package startupimport ("context"+ "fmt""runtime"-- "emperror.dev/errors")var (@@ -15,5 +14,5 @@ var ()func reexecWithRuntimeIdentityInternal(_ context.Context, req runtimeIdentityRequest) error {- return errors.Errorf("runtime identity switching is only supported on linux, current platform is %s", runtime.GOOS)+ return fmt.Errorf("runtime identity switching is only supported on linux, current platform is %s", runtime.GOOS)}diff --git a/backend/pkg/libarcane/swarm/cleanup.go b/backend/pkg/libarcane/swarm/cleanup.goindex 4a565b055..153023c9a 100644--- a/backend/pkg/libarcane/swarm/cleanup.go+++ b/backend/pkg/libarcane/swarm/cleanup.go@@ -2,13 +2,12 @@ package swarmimport ("context"- stderrors "errors"+ "errors""fmt""sort""strings""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"dockerclient "github.com/moby/moby/client"@@ -116,7 +115,7 @@ func cleanupStaleManagedResourcesInternal(if err := removeStaleSwarmResourceInternal(ctx, tolerateInUse, func(ctx context.Context) error {return adapter.Remove(ctx, resource.ID)}); err != nil {- return errors.WrapIff(err, "failed to remove stale stack %s %s", adapter.ResourceType, resource.Name)+ return fmt.Errorf("failed to remove stale stack %s %s: %w", adapter.ResourceType, resource.Name, err)}}@@ -145,7 +144,7 @@ func removeStaleSwarmResourceInternal(ctx context.Context, tolerateInUse bool, r}select {case <-ctx.Done():- return stderrors.Join(ctx.Err(), err)+ return errors.Join(ctx.Err(), err)case <-time.After(staleSwarmResourceRemoveBackoffInternal):}}@@ -171,7 +170,7 @@ func RemoveStackResources(ctx context.Context, dockerClient *dockerclient.Clientfilters := make(dockerclient.Filters).Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))networksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{Filters: filters})if err != nil {- return errors.WrapIf(err, "failed to list stack networks")+ return fmt.Errorf("failed to list stack networks: %w", err)}networks := networksResult.Itemssort.Slice(networks, func(i, j int) bool {@@ -185,7 +184,7 @@ func RemoveStackResources(ctx context.Context, dockerClient *dockerclient.Client_, err := dockerClient.NetworkRemove(ctx, stackNetwork.ID, dockerclient.NetworkRemoveOptions{})return err}); err != nil {- return errors.WrapIff(err, "failed to remove stack network %s", stackNetwork.Name)+ return fmt.Errorf("failed to remove stack network %s: %w", stackNetwork.Name, err)}}diff --git a/backend/pkg/libarcane/swarm/convert_mounts.go b/backend/pkg/libarcane/swarm/convert_mounts.goindex 02daef237..52925c703 100644--- a/backend/pkg/libarcane/swarm/convert_mounts.go+++ b/backend/pkg/libarcane/swarm/convert_mounts.go@@ -2,12 +2,13 @@ package swarmimport ("cmp"+ "errors"+ "fmt""math""os""sort""strings"- "emperror.dev/errors"composegotypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/moby/moby/api/types/mount"@@ -91,7 +92,7 @@ func resolveServiceMountSourceInternal(projectVolume, ok := projectVolumes[source]if !ok {- return "", composegotypes.VolumeConfig{}, errors.Errorf("undefined volume %q", source)+ return "", composegotypes.VolumeConfig{}, fmt.Errorf("undefined volume %q", source)}return ns.Resolve(source, projectVolume.Name), projectVolume, nil}@@ -113,12 +114,12 @@ func resolveServiceFileReferencesInternal(for _, reference := range references {meta, ok := metaByKey[reference.Source]if !ok {- return nil, errors.Errorf("undefined %s %q", resourceType, reference.Source)+ return nil, fmt.Errorf("undefined %s %q", resourceType, reference.Source)}target := cmp.Or(reference.Target, reference.Source)mode, err := fileModeOrDefaultInternal(reference.Mode)if err != nil {- return nil, errors.WrapIff(err, "invalid %s %q mode", resourceType, reference.Source)+ return nil, fmt.Errorf("invalid %s %q mode: %w", resourceType, reference.Source, err)}resolved = append(resolved, resolvedFileReferenceInternal{meta: meta,@@ -197,7 +198,7 @@ func resolveFileObjectContentInternal(if fileConfig.Environment != "" {value, ok := environment.Resolve(fileConfig.Environment)if !ok {- return nil, errors.Errorf("environment variable %s not set", fileConfig.Environment)+ return nil, fmt.Errorf("environment variable %s not set", fileConfig.Environment)}return []byte(value), nil}@@ -216,7 +217,7 @@ func fileModeOrDefaultInternal(mode *composegotypes.FileMode) (os.FileMode, erroreturn 0o444, nil}if *mode < 0 || *mode > composegotypes.FileMode(math.MaxUint32) {- return 0, errors.Errorf("file mode %d is outside the uint32 range", *mode)+ return 0, fmt.Errorf("file mode %d is outside the uint32 range", *mode)}return os.FileMode(uint32(*mode)), nil}diff --git a/backend/pkg/libarcane/swarm/convert_service.go b/backend/pkg/libarcane/swarm/convert_service.goindex e0d89589a..192221b19 100644--- a/backend/pkg/libarcane/swarm/convert_service.go+++ b/backend/pkg/libarcane/swarm/convert_service.go@@ -2,6 +2,7 @@ package swarmimport ("cmp"+ "errors""fmt""log/slog""maps"@@ -13,7 +14,6 @@ import ("strings""time"- "emperror.dev/errors"composegotypes "github.com/compose-spec/compose-go/v2/types"dockeropts "github.com/docker/cli/opts""github.com/moby/moby/api/types/container"@@ -169,7 +169,7 @@ func convertHealthcheckInternal(healthcheck *composegotypes.HealthCheckConfig) (}if healthcheck.Retries != nil {if *healthcheck.Retries > uint64(math.MaxInt) {- return nil, errors.Errorf("healthcheck retries %d exceeds the platform int range", *healthcheck.Retries)+ return nil, fmt.Errorf("healthcheck retries %d exceeds the platform int range", *healthcheck.Retries)}result.Retries = int(*healthcheck.Retries)}@@ -242,7 +242,7 @@ func convertCredentialSpecInternal(meta, ok := configMetaByKey[credentialSpec.Config]if !ok {- return nil, nil, errors.Errorf("undefined config %q for credential spec", credentialSpec.Config)+ return nil, nil, fmt.Errorf("undefined config %q for credential spec", credentialSpec.Config)}converted.Config = meta.IDreturn converted, &swarm.ConfigReference{@@ -270,7 +270,7 @@ func applySecurityOptionInternal(privileges *swarm.Privileges, securityOption stif found && value != "" {parsed, err := strconv.ParseBool(value)if err != nil {- return false, errors.WrapIff(err, "invalid no-new-privileges value %q", value)+ return false, fmt.Errorf("invalid no-new-privileges value %q: %w", value, err)}enabled = parsed}@@ -282,7 +282,7 @@ func applySecurityOptionInternal(privileges *swarm.Privileges, securityOption stcase "unconfined":privileges.Seccomp = &swarm.SeccompOpts{Mode: swarm.SeccompModeUnconfined}default:- return false, errors.Errorf("custom seccomp profile %q is not supported for swarm stacks", value)+ return false, fmt.Errorf("custom seccomp profile %q is not supported for swarm stacks", value)}case "apparmor":switch strings.ToLower(value) {@@ -291,14 +291,14 @@ func applySecurityOptionInternal(privileges *swarm.Privileges, securityOption stcase "unconfined", "disabled":privileges.AppArmor = &swarm.AppArmorOpts{Mode: swarm.AppArmorModeDisabled}default:- return false, errors.Errorf("custom AppArmor profile %q is not supported for swarm stacks", value)+ return false, fmt.Errorf("custom AppArmor profile %q is not supported for swarm stacks", value)}case "label":if err := applySELinuxOptionInternal(privileges, value, securityOption); err != nil {return false, err}default:- return false, errors.Errorf("unsupported swarm security option %q", securityOption)+ return false, fmt.Errorf("unsupported swarm security option %q", securityOption)}return true, nil}@@ -322,10 +322,10 @@ func applySELinuxOptionInternal(privileges *swarm.Privileges, value, securityOptcase "level":selinux.Level = labelValuedefault:- return errors.Errorf("invalid SELinux security option %q", securityOption)+ return fmt.Errorf("invalid SELinux security option %q", securityOption)}if strings.ToLower(labelKey) != "disable" && !hasLabelValue {- return errors.Errorf("invalid SELinux security option %q", securityOption)+ return fmt.Errorf("invalid SELinux security option %q", securityOption)}return nil}@@ -472,7 +472,7 @@ func convertRestartPolicyInternal(restart string, deployPolicy *composegotypes.RmaxAttempts := uint64(policy.MaximumRetryCount)return &swarm.RestartPolicy{Condition: swarm.RestartPolicyConditionOnFailure, MaxAttempts: &maxAttempts}, nildefault:- return nil, errors.Errorf("invalid restart policy %q", policy.Name)+ return nil, fmt.Errorf("invalid restart policy %q", policy.Name)}}@@ -506,7 +506,7 @@ func applyServiceModeInternal(spec *swarm.ServiceSpec, mode string, replicas *in}spec.Mode = swarm.ServiceMode{Replicated: &swarm.ReplicatedService{Replicas: &replicaCount}}default:- return errors.Errorf("unknown service mode %q", mode)+ return fmt.Errorf("unknown service mode %q", mode)}return nil}@@ -544,7 +544,7 @@ func applyServicePortsInternal(spec *swarm.ServiceSpec, ports []composegotypes.Sif port.Published != "" {published, err := strconv.ParseUint(port.Published, 10, 32)if err != nil {- return errors.WrapIff(err, "invalid published port %q", port.Published)+ return fmt.Errorf("invalid published port %q: %w", port.Published, err)}entry.PublishedPort = uint32(published)}@@ -573,7 +573,7 @@ func buildServiceNetworksInternal(service composegotypes.ServiceConfig, networkNfor name, cfg := range service.Networks {networkName, ok := networkNameByKey[name]if !ok {- return nil, errors.Errorf("undefined network %q", name)+ return nil, fmt.Errorf("undefined network %q", name)}aliases := []string{service.Name}if cfg == nil {diff --git a/backend/pkg/libarcane/swarm/deploy.go b/backend/pkg/libarcane/swarm/deploy.goindex 3e493fe2f..04bd1cb6f 100644--- a/backend/pkg/libarcane/swarm/deploy.go+++ b/backend/pkg/libarcane/swarm/deploy.go@@ -8,7 +8,6 @@ import ("slices""strings"- "emperror.dev/errors"composegotypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"@@ -141,7 +140,7 @@ func DeployStack(ctx context.Context, dockerClient *dockerclient.Client, opts Stcontinue}if _, err := dockerClient.ServiceRemove(ctx, svc.ID, dockerclient.ServiceRemoveOptions{}); err != nil {- return errors.WrapIff(err, "failed to remove swarm service %s", name)+ return fmt.Errorf("failed to remove swarm service %s: %w", name, err)}}}@@ -173,7 +172,7 @@ func reconcileStackServicesInternal(service.Name = cmp.Or(service.Name, key)spec, err := buildServiceSpecInternal(service, ns, stackLabels, networkNameByKey, configMetaByKey, secretMetaByKey, project.Volumes)if err != nil {- return nil, invalidStackErrorInternal(errors.WrapIff(err, "service %s", service.Name))+ return nil, invalidStackErrorInternal(fmt.Errorf("service %s: %w", service.Name, err))}desiredServices[spec.Name] = struct{}{}@@ -196,7 +195,7 @@ func listStackServicesInternal(ctx context.Context, dockerClient *dockerclient.Cfilter := 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, errors.WrapIf(err, "failed to list swarm services")+ return nil, fmt.Errorf("failed to list swarm services: %w", err)}services := servicesResult.Items@@ -226,7 +225,7 @@ func createSwarmServiceInternal(}opts.EncodedRegistryAuth = cmp.Or(encodedRegistryAuth, opts.EncodedRegistryAuth)if _, err := dockerClient.ServiceCreate(ctx, opts); err != nil {- return errors.WrapIff(err, "failed to create swarm service %s", spec.Name)+ return fmt.Errorf("failed to create swarm service %s: %w", spec.Name, err)}return nil}@@ -267,11 +266,11 @@ func updateSwarmServiceInternal(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 errors.WrapIff(retryErr, "failed to update swarm service %s", spec.Name)+ return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, retryErr)}return nil}- return errors.WrapIff(err, "failed to update swarm service %s", spec.Name)+ return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, err)}return nil}@@ -285,7 +284,7 @@ func normalizeResolveImageModeInternal(value string) (string, error) {case resolveImageAlways, resolveImageChanged, resolveImageNever:return mode, nildefault:- return "", errors.Errorf("invalid resolve image mode %q: expected always, changed, or never", value)+ return "", fmt.Errorf("invalid resolve image mode %q: expected always, changed, or never", value)}}@@ -344,7 +343,7 @@ func resolveRegistryAuthForSpecInternal(encodedRegistryAuth, err := registryAuthForImage(ctx, image)if err != nil {- return "", errors.WrapIff(err, "failed to resolve registry auth for image %s", image)+ return "", fmt.Errorf("failed to resolve registry auth for image %s: %w", image, err)}return encodedRegistryAuth, nildiff --git a/backend/pkg/libarcane/swarm/namespace.go b/backend/pkg/libarcane/swarm/namespace.goindex 9f9728790..688b61b2e 100644--- a/backend/pkg/libarcane/swarm/namespace.go+++ b/backend/pkg/libarcane/swarm/namespace.go@@ -3,13 +3,13 @@ package swarmimport ("crypto/sha256""encoding/hex"+ "errors""fmt""maps""regexp""slices""strings"- "emperror.dev/errors"composegotypes "github.com/compose-spec/compose-go/v2/types"kit "go.getarcane.app/kit/pkg")@@ -29,7 +29,7 @@ var (stackNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)// ErrInvalidStack identifies invalid stack source or conversion input.- ErrInvalidStack = errors.Sentinel("invalid swarm stack")+ ErrInvalidStack = errors.New("invalid swarm stack"))type namespace struct {@@ -59,7 +59,7 @@ func validateStackNameInternal(stackName string) error {case stackName == "":return errors.New("stack name is required")case !stackNamePattern.MatchString(stackName):- return errors.Errorf("invalid stack name %q: use lowercase letters, numbers, hyphens, and underscores, starting with a letter or number", stackName)+ return fmt.Errorf("invalid stack name %q: use lowercase letters, numbers, hyphens, and underscores, starting with a letter or number", stackName)default:return nil}diff --git a/backend/pkg/libarcane/swarm/render.go b/backend/pkg/libarcane/swarm/render.goindex 2a4952a12..37c99d285 100644--- a/backend/pkg/libarcane/swarm/render.go+++ b/backend/pkg/libarcane/swarm/render.go@@ -3,11 +3,11 @@ package swarmimport ("cmp""context"+ "fmt""maps""slices""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"projecttypes "github.com/getarcaneapp/arcane/types/v2/project")@@ -77,7 +77,7 @@ func RenderStackConfig(ctx context.Context, opts StackRenderOptions) (*StackRendrendered, err := project.MarshalYAML()if err != nil {- return nil, errors.WrapIf(err, "failed to render compose project")+ return nil, fmt.Errorf("failed to render compose project: %w", err)}serviceNames := make([]string, 0, len(project.Services))diff --git a/backend/pkg/libarcane/swarm/resources.go b/backend/pkg/libarcane/swarm/resources.goindex 923f8a86b..288126879 100644--- a/backend/pkg/libarcane/swarm/resources.go+++ b/backend/pkg/libarcane/swarm/resources.go@@ -3,11 +3,11 @@ package swarmimport ("cmp""context"+ "fmt""maps""slices""strings"- "emperror.dev/errors"composegotypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs""github.com/moby/moby/api/types/swarm"@@ -101,14 +101,14 @@ func planManagedFileResourcesInternal(continue}if resourceType == "config" && resource.Driver != "" {- return nil, errors.Errorf("config driver %q is not supported by the Docker swarm API", resource.Driver)+ return nil, fmt.Errorf("config driver %q is not supported by the Docker swarm API", resource.Driver)}var data []byteif resource.Driver == "" {resolvedData, err := resolveFileObjectContentInternal(resource, workingDir, environment)if err != nil {- return nil, errors.WrapIff(err, "failed to load %s %s", resourceType, baseName)+ return nil, fmt.Errorf("failed to load %s %s: %w", resourceType, baseName, err)}data = resolvedData}@@ -132,10 +132,10 @@ func ensureSwarmNetworksInternal(ctx context.Context, dockerClient *dockerclient}inspected, err := dockerClient.NetworkInspect(ctx, networkName, dockerclient.NetworkInspectOptions{Scope: "swarm"})if err != nil {- return nil, invalidStackErrorInternal(errors.WrapIff(err, "external network %s is unavailable", networkName))+ return nil, invalidStackErrorInternal(fmt.Errorf("external network %s is unavailable: %w", networkName, err))}if inspected.Network.Scope != "swarm" {- return nil, invalidStackErrorInternal(errors.Errorf("external network %q has scope %q, expected swarm", networkName, inspected.Network.Scope))+ return nil, invalidStackErrorInternal(fmt.Errorf("external network %q has scope %q, expected swarm", networkName, inspected.Network.Scope))}continue}@@ -145,7 +145,7 @@ func ensureSwarmNetworksInternal(ctx context.Context, dockerClient *dockerclientcontinue}if !cerrdefs.IsNotFound(err) {- return nil, errors.WrapIff(err, "failed to inspect network %s", networkName)+ return nil, fmt.Errorf("failed to inspect network %s: %w", networkName, err)}driver := cmp.Or(strings.TrimSpace(cfg.Driver), "overlay")@@ -164,7 +164,7 @@ func ensureSwarmNetworksInternal(ctx context.Context, dockerClient *dockerclient}if _, err := dockerClient.NetworkCreate(ctx, networkName, createOpts); err != nil {- return nil, errors.WrapIff(err, "failed to create network %s", networkName)+ return nil, fmt.Errorf("failed to create network %s: %w", networkName, err)}}@@ -195,7 +195,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 errors.WrapIff(err, "failed to inspect volume %s", name)+ return fmt.Errorf("failed to inspect volume %s: %w", name, err)}driver := cmp.Or(cfg.Driver, "local")@@ -206,7 +206,7 @@ func ensureSwarmVolumesInternal(ctx context.Context, dockerClient *dockerclient.DriverOpts: cfg.DriverOpts,Labels: labels,}); err != nil {- return errors.WrapIff(err, "failed to create volume %s", name)+ return fmt.Errorf("failed to create volume %s: %w", name, err)}}return nil@@ -233,14 +233,14 @@ func configFileResourceAdapterInternal(dockerClient *dockerclient.Client) fileRe}response, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})if err != nil {- return resourceMeta{}, errors.WrapIff(err, "failed to create config %s", resource.Name)+ return resourceMeta{}, fmt.Errorf("failed to create config %s: %w", resource.Name, err)}return resourceMeta{ID: response.ID, Name: resource.Name}, nil},List: func(ctx context.Context, filters dockerclient.Filters) ([]staleManagedResourceInternal, error) {configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{Filters: filters})if err != nil {- return nil, errors.WrapIf(err, "failed to list stack configs")+ return nil, fmt.Errorf("failed to list stack configs: %w", err)}return collectStaleManagedResourcesInternal(configsResult.Items, func(cfg swarm.Config) staleManagedResourceInternal {return staleManagedResourceInternal{ID: cfg.ID, Name: cfg.Spec.Name}@@ -277,14 +277,14 @@ func secretFileResourceAdapterInternal(dockerClient *dockerclient.Client) fileRe}response, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})if err != nil {- return resourceMeta{}, errors.WrapIff(err, "failed to create secret %s", resource.Name)+ return resourceMeta{}, fmt.Errorf("failed to create secret %s: %w", resource.Name, err)}return resourceMeta{ID: response.ID, Name: resource.Name}, nil},List: func(ctx context.Context, filters dockerclient.Filters) ([]staleManagedResourceInternal, error) {secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{Filters: filters})if err != nil {- return nil, errors.WrapIf(err, "failed to list stack secrets")+ return nil, fmt.Errorf("failed to list stack secrets: %w", err)}return collectStaleManagedResourcesInternal(secretsResult.Items, func(secret swarm.Secret) staleManagedResourceInternal {return staleManagedResourceInternal{ID: secret.ID, Name: secret.Spec.Name}@@ -309,12 +309,9 @@ func ensurePlannedFileResourcesInternal(if plan.IsExternal {meta, err := adapter.Inspect(ctx, plan.Meta.Name)if err != nil {- return nil, invalidStackErrorInternal(errors.WrapIff(- err,- "external %s %s is unavailable",- adapter.ResourceType,- plan.Meta.Name,- ))+ return nil, invalidStackErrorInternal(fmt.Errorf("external %s %s is unavailable: %w", adapter.ResourceType,+ plan.Meta.Name, err),+ )}result[key] = metacontinue@@ -338,7 +335,7 @@ func ensureManagedFileResourceInternal(if meta, err := adapter.Inspect(ctx, plan.Meta.Name); err == nil {return meta, nil} else if !cerrdefs.IsNotFound(err) {- return resourceMeta{}, errors.WrapIff(err, "failed to inspect %s %s", adapter.ResourceType, plan.Meta.Name)+ return resourceMeta{}, fmt.Errorf("failed to inspect %s %s: %w", adapter.ResourceType, plan.Meta.Name, err)}resourceLabels := mergeLabelsInternal(plan.Labels, stackLabels)diff --git a/backend/pkg/libarcane/system/gpu.go b/backend/pkg/libarcane/system/gpu.goindex 93eb94fc6..b53d497be 100644--- a/backend/pkg/libarcane/system/gpu.go+++ b/backend/pkg/libarcane/system/gpu.go@@ -4,6 +4,7 @@ import ("bytes""context""encoding/csv"+ "errors""fmt""log/slog""os"@@ -14,7 +15,6 @@ import ("sync/atomic""time"- "emperror.dev/errors"systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/samber/hot")@@ -234,7 +234,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, errors.WrapIf(err, "nvidia-smi execution failed")+ return nil, fmt.Errorf("nvidia-smi execution failed: %w", err)}reader := csv.NewReader(bytes.NewReader(output))@@ -242,7 +242,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, errors.WrapIf(err, "failed to parse nvidia-smi output")+ return nil, fmt.Errorf("failed to parse nvidia-smi output: %w", err)}var stats []systemtypes.GPUStats@@ -286,7 +286,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, errors.WrapIf(err, "failed to read sysfs")+ return nil, fmt.Errorf("failed to read sysfs: %w", err)}var stats []systemtypes.GPUStatsdiff --git a/backend/pkg/libarcane/volumehelper/container_files.go b/backend/pkg/libarcane/volumehelper/container_files.goindex 82050fe5d..8c72c9569 100644--- a/backend/pkg/libarcane/volumehelper/container_files.go+++ b/backend/pkg/libarcane/volumehelper/container_files.go@@ -3,9 +3,10 @@ package volumehelperimport ("archive/tar""context"+ "errors"+ "fmt""io"- "emperror.dev/errors""github.com/moby/moby/client")@@ -34,7 +35,7 @@ func DownloadFileFromContainer(})if err != nil {cleanup()- return nil, 0, errors.WrapIf(err, "failed to download")+ return nil, 0, fmt.Errorf("failed to download: %w", err)}reader := copyResult.Content@@ -43,7 +44,7 @@ func DownloadFileFromContainer(if err != nil {_ = reader.Close()cleanup()- return nil, 0, errors.WrapIf(err, "failed to read tar stream")+ return nil, 0, fmt.Errorf("failed to read tar stream: %w", err)}if err := validateDownloadHeaderInternal(hdr); err != nil {_ = reader.Close()diff --git a/backend/pkg/libarcane/volumehelper/helper.go b/backend/pkg/libarcane/volumehelper/helper.goindex 5a957779b..af531a56a 100644--- a/backend/pkg/libarcane/volumehelper/helper.go+++ b/backend/pkg/libarcane/volumehelper/helper.go@@ -2,12 +2,13 @@ package volumehelperimport ("context"+ "errors"+ "fmt""io""os""runtime""strings"- "emperror.dev/errors"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/moby/moby/api/types/container"@@ -85,7 +86,7 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client, toolsI} else {defer func() { _ = pullReader.Close() }()if _, err := io.Copy(io.Discard, pullReader); err != nil {- pullErr = errors.WrapIf(err, "read helper image pull response")+ pullErr = fmt.Errorf("read helper image pull response: %w", err)} else {return toolsImage, nil}@@ -96,7 +97,7 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client, toolsIreturn fallback.Image, nil}- return "", errors.WrapIf(pullErr, "failed to resolve helper image: tools image unavailable and arcane fallback not found")+ return "", fmt.Errorf("failed to resolve helper image: tools image unavailable and arcane fallback not found: %w", pullErr)}// ResolveArcaneRuntimeImage resolves the current Arcane or Arcane agent imagediff --git a/backend/pkg/libarcane/volumehelper/helper_test.go b/backend/pkg/libarcane/volumehelper/helper_test.goindex e39523d28..a1dc314f2 100644--- a/backend/pkg/libarcane/volumehelper/helper_test.go+++ b/backend/pkg/libarcane/volumehelper/helper_test.go@@ -64,7 +64,7 @@ func TestResolveHelperImage_PullsToolsImageWhenMissing(t *testing.T) {return}w.Header().Set("Content-Type", "application/json")- _, err := w.Write([]byte(`{"status":"pulled"}` + "\n"))+ _, err := w.Write([]byte("{\"status\":\"pulled\"}\n"))if !assert.NoError(t, err) {return}diff --git a/backend/pkg/libarcane/volumes/volume_rename.go b/backend/pkg/libarcane/volumes/volume_rename.goindex f3adea09a..2dcdd83b4 100644--- a/backend/pkg/libarcane/volumes/volume_rename.go+++ b/backend/pkg/libarcane/volumes/volume_rename.go@@ -2,7 +2,8 @@ package volumesimport ("context"- stderrors "errors"+ "errors"+ "fmt""log/slog""maps""slices"@@ -10,7 +11,6 @@ import ("syscall""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -70,7 +70,7 @@ func PlanRename(ctx context.Context, dockerClient *client.Client, oldName, newNaoldVolume, err := dockerClient.VolumeInspect(ctx, oldName, client.VolumeInspectOptions{})if err != nil {- return nil, errors.WrapIff(err, "inspect source volume %s", oldName)+ return nil, fmt.Errorf("inspect source volume %s: %w", oldName, err)}if err := EnsureRenameSourceDetached(ctx, dockerClient, oldName); err != nil {return nil, err@@ -111,15 +111,12 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Apply(ctx context.Context)for _, entry := range m.entries {if err := createProjectRenamedVolumeInternal(ctx, dockerClient, entry); err != nil {- return stderrors.Join(err, m.rollbackCreatedTargetsInternal(ctx, dockerClient))+ return errors.Join(err, m.rollbackCreatedTargetsInternal(ctx, dockerClient))}m.createdNew = append(m.createdNew, entry)if err := copyProjectVolumeDataInternal(ctx, dockerClient, copyRuntime, entry.OldName, entry.NewName); err != nil {- return stderrors.Join(- errors.- WrapIff(err, "copy volume data from %s to %s", entry.OldName, entry.NewName), m.rollbackCreatedTargetsInternal(ctx, dockerClient),- )+ return errors.Join(fmt.Errorf("copy volume data from %s to %s: %w", entry.OldName, entry.NewName, err), m.rollbackCreatedTargetsInternal(ctx, dockerClient))}}@@ -187,7 +184,7 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.Contexcontinue}preservedTargets[entry.NewName] = struct{}{}- rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{+ rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{OldName: entry.OldName,NewName: entry.NewName,}, errors.New("source volume was already removed")))@@ -200,10 +197,10 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.ContexsourceExists, err := VolumeExists(ctx, dockerClient, entry.OldName)if err != nil {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{+ rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{OldName: entry.OldName,NewName: entry.NewName,- }, errors.WrapIff(err, "inspect source rollback volume %s", entry.OldName)))+ }, fmt.Errorf("inspect source rollback volume %s: %w", entry.OldName, err)))continue}if sourceExists {@@ -213,24 +210,24 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Rollback(ctx context.ContextargetExists, err := VolumeExists(ctx, dockerClient, entry.NewName)if err != nil {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{+ rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{OldName: entry.OldName,NewName: entry.NewName,- }, errors.WrapIff(err, "inspect target rollback volume %s", entry.NewName)))+ }, fmt.Errorf("inspect target rollback volume %s: %w", entry.NewName, err)))continue}if targetExists {preservedTargets[entry.NewName] = struct{}{}- rollbackErr = stderrors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{+ rollbackErr = errors.Join(rollbackErr, NewTargetPreservedDuringRollbackError(volumetypes.JournalVolume{OldName: entry.OldName,NewName: entry.NewName,}, errProjectRenameRollbackSourceMissingInternal))} else {- 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, fmt.Errorf("source volume %s and target volume %s are missing during rollback", entry.OldName, entry.NewName))}}- rollbackErr = stderrors.Join(rollbackErr, m.rollbackCreatedTargetsPreservingInternal(ctx, dockerClient, preservedTargets))+ rollbackErr = errors.Join(rollbackErr, m.rollbackCreatedTargetsPreservingInternal(ctx, dockerClient, preservedTargets))if rollbackErr == nil {dockerutil.InvalidateVolumeUsageCache(dockerClient)}@@ -250,12 +247,12 @@ func (m *dockerProjectVolumeRenameMigrationInternal) rollbackCreatedTargetsPresecontinue}if err := removeProjectVolumeHelperContainersInternal(ctx, dockerClient, entry.NewName); err != nil {- rollbackErr = stderrors.Join(rollbackErr, errors.WrapIff(err, "remove helper containers for target volume %s", entry.NewName))+ rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove helper containers for target volume %s: %w", entry.NewName, err))remainingCreated = append(remainingCreated, entry)continue}if err := removeProjectVolumeWithRetryInternal(ctx, dockerClient, entry.NewName, client.VolumeRemoveOptions{Force: true}); err != nil {- rollbackErr = stderrors.Join(rollbackErr, errors.WrapIff(err, "remove target volume %s", entry.NewName))+ rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove target volume %s: %w", entry.NewName, err))remainingCreated = append(remainingCreated, entry)}}@@ -270,7 +267,7 @@ func EnsureRenameTargetAbsent(ctx context.Context, dockerClient *client.Client,if cerrdefs.IsNotFound(err) {return nil}- return errors.WrapIff(err, "inspect target volume %s", newName)+ return fmt.Errorf("inspect target volume %s: %w", newName, err)}return &volumetypes.ProjectVolumeRenameConflictError{VolumeName: newName}}@@ -278,7 +275,7 @@ func EnsureRenameTargetAbsent(ctx context.Context, dockerClient *client.Client,func EnsureRenameSourceDetached(ctx context.Context, dockerClient *client.Client, oldName string) error {containerIDs, err := dockerutil.GetContainersUsingVolume(ctx, dockerClient, oldName)if err != nil {- return errors.WrapIff(err, "inspect containers using source volume %s", oldName)+ return fmt.Errorf("inspect containers using source volume %s: %w", oldName, err)}if len(containerIDs) > 0 {return &volumetypes.ProjectVolumeRenameInUseError{VolumeName: oldName, ContainerIDs: containerIDs}@@ -288,7 +285,7 @@ func EnsureRenameSourceDetached(ctx context.Context, dockerClient *client.Clientfunc createProjectRenamedVolumeInternal(ctx context.Context, dockerClient *client.Client, entry volumetypes.RenameEntry) error {if _, err := dockerClient.VolumeCreate(ctx, entry.CreateOptions); err != nil {- return errors.WrapIff(err, "create target volume %s", entry.NewName)+ return fmt.Errorf("create target volume %s: %w", entry.NewName, err)}return nil}@@ -296,7 +293,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 errors.WrapIf(err, "list containers for helper cleanup")+ return fmt.Errorf("list containers for helper cleanup: %w", err)}var removeErr error@@ -305,7 +302,7 @@ func removeProjectVolumeHelperContainersInternal(ctx context.Context, dockerCliecontinue}if _, err := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); err != nil && !cerrdefs.IsNotFound(err) {- removeErr = stderrors.Join(removeErr, errors.WrapIff(err, "remove helper container %s", c.ID))+ removeErr = errors.Join(removeErr, fmt.Errorf("remove helper container %s: %w", c.ID, err))}}return removeErr@@ -343,7 +340,7 @@ func removeProjectVolumeWithRetryInternal(ctx context.Context, dockerClient *cli}select {case <-ctx.Done():- return stderrors.Join(ctx.Err(), err)+ return errors.Join(ctx.Err(), err)case <-time.After(200 * time.Millisecond):}}@@ -367,7 +364,7 @@ func copyProjectVolumeDataInternal(ctx context.Context, dockerClient *client.CliSourcePath: projectVolumeCopyMountPathInternal + "/.",})if err != nil {- return errors.WrapIf(err, "read source volume archive")+ return fmt.Errorf("read source volume archive: %w", err)}defer func() { _ = copyResult.Content.Close() }()@@ -383,7 +380,7 @@ func copyProjectVolumeDataInternal(ctx context.Context, dockerClient *client.CliDetail: err.Error(),}}- return errors.WrapIf(err, "write target volume archive")+ return fmt.Errorf("write target volume archive: %w", err)}return nil@@ -410,7 +407,7 @@ func createProjectVolumeCopyHolderContainerInternal(ctx context.Context, dockerCHostConfig: hostConfig,})if err != nil {- return "", nil, errors.WrapIf(err, "create volume copy holder")+ return "", nil, fmt.Errorf("create volume copy holder: %w", err)}cleanup := func() {@@ -506,7 +503,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 = stderrors.Join(rollbackErr, err)+ rollbackErr = errors.Join(rollbackErr, err)}}if len(volumes) > 0 {@@ -518,11 +515,11 @@ func RollbackVolumes(ctx context.Context, dockerClient *client.Client, volumes [func RollbackVolume(ctx context.Context, dockerClient *client.Client, vol volumetypes.JournalVolume) error {oldExists, err := VolumeExists(ctx, dockerClient, vol.OldName)if err != nil {- return NewTargetPreservedDuringRollbackError(vol, errors.WrapIff(err, "inspect source rollback volume %s", vol.OldName))+ return NewTargetPreservedDuringRollbackError(vol, fmt.Errorf("inspect source rollback volume %s: %w", vol.OldName, err))}newExists, err := VolumeExists(ctx, dockerClient, vol.NewName)if err != nil {- return NewTargetPreservedDuringRollbackError(vol, errors.WrapIff(err, "inspect target rollback volume %s", vol.NewName))+ return NewTargetPreservedDuringRollbackError(vol, fmt.Errorf("inspect target rollback volume %s: %w", vol.NewName, err))}switch {@@ -540,7 +537,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 = stderrors.Join(cleanupErr, err)+ cleanupErr = errors.Join(cleanupErr, err)}}return cleanupErr@@ -549,11 +546,11 @@ func CleanupRollbackTargetVolumes(ctx context.Context, dockerClient *client.Cliefunc cleanupProjectRenameRollbackTargetVolumeInternal(ctx context.Context, dockerClient *client.Client, vol volumetypes.JournalVolume) error {oldExists, err := VolumeExists(ctx, dockerClient, vol.OldName)if err != nil {- return errors.WrapIff(err, "inspect source cleanup volume %s", vol.OldName)+ return fmt.Errorf("inspect source cleanup volume %s: %w", vol.OldName, err)}newExists, err := VolumeExists(ctx, dockerClient, vol.NewName)if err != nil {- return errors.WrapIff(err, "inspect target cleanup volume %s", vol.NewName)+ return fmt.Errorf("inspect target cleanup volume %s: %w", vol.NewName, err)}switch {@@ -576,7 +573,7 @@ func removeProjectRenameJournalTargetVolumeInternal(ctx context.Context, dockerCreturn err}if err := removeProjectVolumeWithRetryInternal(ctx, dockerClient, newName, client.VolumeRemoveOptions{Force: true}); err != nil {- return errors.WrapIff(err, "remove rollback target volume %s", newName)+ return fmt.Errorf("remove rollback target volume %s: %w", newName, err)}return nil}@@ -589,7 +586,7 @@ func VolumeExists(ctx context.Context, dockerClient *client.Client, name string)if cerrdefs.IsNotFound(err) {return false, nil}- return false, errors.WrapIff(err, "inspect volume %s", name)+ return false, fmt.Errorf("inspect volume %s: %w", name, err)}func NewSourceCleanupError(sourceVolume string, err error) error {diff --git a/backend/pkg/libarcane/vuln/driver.go b/backend/pkg/libarcane/vuln/driver.goindex 58cd27008..043c20b42 100644--- a/backend/pkg/libarcane/vuln/driver.go+++ b/backend/pkg/libarcane/vuln/driver.go@@ -7,6 +7,7 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""log/slog"@@ -18,7 +19,6 @@ import ("strings""time"- "emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"@@ -78,12 +78,12 @@ func ResolveUnixSocketSource(return strings.TrimSpace(hostPath), nil}if err != nil && (isRunningInDocker == nil || isRunningInDocker()) {- return "", errors.WrapIff(err, "failed to resolve socket path %q", socketPath)+ return "", fmt.Errorf("failed to resolve socket path %q: %w", socketPath, err)}}if isRunningInDocker != nil && isRunningInDocker() {- return "", errors.Errorf("failed to resolve socket path %q to a daemon-visible host path", socketPath)+ return "", fmt.Errorf("failed to resolve socket path %q to a daemon-visible host path", socketPath)}return socketPath, nil@@ -189,15 +189,15 @@ func CreateLogTempFile(prefix string) (*os.File, error) {// per-user cache directory so Trivy scans can still run.cacheDir, err := os.UserCacheDir()if err != nil {- return nil, errors.WrapIff(err, "failed to create trivy temp file (primary: %s) and user cache dir unavailable", primaryErr.Error())+ return nil, fmt.Errorf("failed to create trivy temp file (primary: %s) and user cache dir unavailable: %w", primaryErr.Error(), err)}fallbackDir := filepath.Join(cacheDir, "arcane", "trivy-tmp")if err := os.MkdirAll(fallbackDir, 0o700); err != nil {- return nil, errors.WrapIff(err, "failed to create trivy fallback temp dir %s (primary: %s)", fallbackDir, primaryErr.Error())+ return nil, fmt.Errorf("failed to create trivy fallback temp dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), err)}fallbackFile, err := os.CreateTemp(fallbackDir, prefix)if err != nil {- return nil, errors.WrapIff(err, "failed to create trivy temp file in fallback dir %s (primary: %s)", fallbackDir, primaryErr.Error())+ return nil, fmt.Errorf("failed to create trivy temp file in fallback dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), err)}return fallbackFile, nil}@@ -491,7 +491,7 @@ func ReadOutputFromContainerFile(ctx context.Context, dockerClient *client.CliencopyResult, err := dockerClient.CopyFromContainer(copyCtx, containerID, client.CopyFromContainerOptions{SourcePath: outputPath})if err != nil {- return nil, errors.WrapIf(err, "copy trivy output file")+ return nil, fmt.Errorf("copy trivy output file: %w", err)}archiveReader := copyResult.Contentdefer func() {@@ -507,7 +507,7 @@ func ReadOutputFromContainerFile(ctx context.Context, dockerClient *client.ClienrawOutput, err := extractFileFromContainerArchiveInternal(archiveReader)if err != nil {- return nil, errors.WrapIf(err, "extract trivy output file")+ return nil, fmt.Errorf("extract trivy output file: %w", err)}if len(bytes.TrimSpace(rawOutput)) == 0 {@@ -561,7 +561,7 @@ func extractFileFromContainerArchiveInternal(archiveReader io.Reader) ([]byte, ebreak}if err != nil {- return nil, errors.WrapIf(err, "read tar header")+ return nil, fmt.Errorf("read tar header: %w", err)}if header == nil || header.Typeflag == tar.TypeDir {@@ -574,7 +574,7 @@ func extractFileFromContainerArchiveInternal(archiveReader io.Reader) ([]byte, edata, err := io.ReadAll(tarReader)if err != nil {- return nil, errors.WrapIf(err, "read tar file content")+ return nil, fmt.Errorf("read tar file content: %w", err)}return data, nil@@ -589,12 +589,12 @@ func DecodeReportFromFile(file *os.File) (*vulnerability.TrivyReport, error) {}if _, err := file.Seek(0, io.SeekStart); err != nil {- return nil, errors.WrapIf(err, "failed to seek trivy output file")+ return nil, fmt.Errorf("failed to seek trivy output file: %w", err)}rawOutput, err := io.ReadAll(file)if err != nil {- return nil, errors.WrapIf(err, "failed to read trivy output file")+ return nil, fmt.Errorf("failed to read trivy output file: %w", err)}return DecodeReportFromBytes(rawOutput)@@ -735,16 +735,16 @@ func FormatExitError(exitCode int64, errMsg, imageName string) error {if exitCode == 137 {if errMsg == "" || errMsg == fmt.Sprintf("exit status %d", exitCode) {- 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: process killed with exit status 137 (likely out of memory while scanning %s)", imageName)}- return errors.Errorf("trivy scan failed: %s (process killed with exit status 137; likely out of memory)", errMsg)+ return fmt.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 errors.Errorf("trivy scan timed out for %s (increase TRIVY_SCAN_TIMEOUT or trivyScanTimeout setting)", imageName)+ return fmt.Errorf("trivy scan timed out for %s (increase TRIVY_SCAN_TIMEOUT or trivyScanTimeout setting)", imageName)}- return errors.Errorf("trivy scan failed: %s", errMsg)+ return fmt.Errorf("trivy scan failed: %s", errMsg)}func AwaitContainerWaitResponse(diff --git a/backend/pkg/libarcane/vuln/driver_test.go b/backend/pkg/libarcane/vuln/driver_test.goindex 1fd64a61b..b33686571 100644--- a/backend/pkg/libarcane/vuln/driver_test.go+++ b/backend/pkg/libarcane/vuln/driver_test.go@@ -3,13 +3,13 @@ package vulnimport ("context""encoding/json"+ "errors""fmt""os""strings""testing""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/types/v2/vulnerability"containertypes "github.com/moby/moby/api/types/container"@@ -122,7 +122,7 @@ func TestDecodeTrivyReportFromFileInternal_SelectsReportFromMultipleJSONObjects(reportBytes, err := json.Marshal(report)require.NoError(t, err)- _, err = tmpFile.WriteString(`{"action":"vulnerability_scan","success":false}` + "\n")+ _, err = tmpFile.WriteString("{\"action\":\"vulnerability_scan\",\"success\":false}\n")require.NoError(t, err)_, err = tmpFile.Write(reportBytes)require.NoError(t, err)diff --git a/backend/pkg/libarcane/vuln/trivy.go b/backend/pkg/libarcane/vuln/trivy.goindex cc5f48098..f3e98d5fc 100644--- a/backend/pkg/libarcane/vuln/trivy.go+++ b/backend/pkg/libarcane/vuln/trivy.go@@ -9,11 +9,11 @@ import ("cmp""encoding/base64""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"@@ -74,7 +74,7 @@ func ParseDockerHost(dockerHost string) (scheme, socketPath string, err error) {parsed, err := url.Parse(dockerHost)if err != nil {- return "", "", errors.WrapIff(err, "parse docker host %q", dockerHost)+ return "", "", fmt.Errorf("parse docker host %q: %w", dockerHost, err)}scheme = strings.ToLower(strings.TrimSpace(parsed.Scheme))@@ -82,13 +82,13 @@ func ParseDockerHost(dockerHost string) (scheme, socketPath string, err error) {case "unix":socketPath = strings.TrimSpace(parsed.Path)if socketPath == "" {- return "", "", errors.Errorf("docker host %q is missing a unix socket path", dockerHost)+ return "", "", fmt.Errorf("docker host %q is missing a unix socket path", dockerHost)}return scheme, socketPath, nilcase "tcp", "http", "https":return scheme, "", nildefault:- return "", "", errors.Errorf("unsupported docker host scheme %q", scheme)+ return "", "", fmt.Errorf("unsupported docker host scheme %q", scheme)}}diff --git a/backend/pkg/libarcane/ws/accept.go b/backend/pkg/libarcane/ws/accept.goindex e7a4fe878..7d52472fa 100644--- a/backend/pkg/libarcane/ws/accept.go+++ b/backend/pkg/libarcane/ws/accept.go@@ -1,9 +1,9 @@package wsimport (+ "errors""net/http"- "emperror.dev/errors""github.com/coder/websocket")diff --git a/backend/pkg/libarcane/ws/goroutine_leak_test.go b/backend/pkg/libarcane/ws/goroutine_leak_test.goindex f20184d9f..b5c181d7a 100644--- a/backend/pkg/libarcane/ws/goroutine_leak_test.go+++ b/backend/pkg/libarcane/ws/goroutine_leak_test.go@@ -257,9 +257,7 @@ func TestLeak_RepeatedConnectDisconnect(t *testing.T) {actual := waitForGoroutineCount(t, baseline, 0, 3*time.Second)leaked := actual - baseline- assert.Equal(t, 0, leaked,- "after %d connect/disconnect cycles, global goroutine delta must be 0; "+- "baseline=%d, final=%d", iterations, baseline, actual)+ assert.Equal(t, 0, leaked, "after %d connect/disconnect cycles, global goroutine delta must be 0; baseline=%d, final=%d", iterations, baseline, actual)t.Logf("goroutine leak check: baseline=%d, final=%d, delta=%d, ws_workers=%d (after %d cycles)",baseline, actual, leaked, wsWorkers, iterations)}@@ -556,9 +554,7 @@ func TestLeak_RepeatedStatsHubCycles(t *testing.T) {actual := waitForGoroutineCount(t, baseline, 0, 3*time.Second)leaked := actual - baseline- assert.Equal(t, 0, leaked,- "after %d stats hub cycles, global goroutine delta must be 0; "+- "baseline=%d, final=%d", iterations, baseline, actual)+ assert.Equal(t, 0, leaked, "after %d stats hub cycles, global goroutine delta must be 0; baseline=%d, final=%d", iterations, baseline, actual)t.Logf("stats hub leak check: baseline=%d, final=%d, delta=%d, ws_workers=%d (after %d cycles)",baseline, actual, leaked, wsWorkers, iterations)}diff --git a/backend/pkg/libarcane/ws/proxy.go b/backend/pkg/libarcane/ws/proxy.goindex 591850536..9d1cf4b7e 100644--- a/backend/pkg/libarcane/ws/proxy.go+++ b/backend/pkg/libarcane/ws/proxy.go@@ -2,12 +2,12 @@ package wsimport ("context"+ "errors""io""log/slog""net/http""time"- "emperror.dev/errors""github.com/coder/websocket")diff --git a/backend/pkg/pagination/db_utils.go b/backend/pkg/pagination/db_utils.goindex 858ccb91f..395432cdf 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"kit "go.getarcane.app/kit/pkg""go.getarcane.app/kit/pkg/mapping""gorm.io/gorm"@@ -43,12 +43,12 @@ func ApplyLikeSearch(q *gorm.DB, search, condition string) *gorm.DB {func (params QueryParams) PaginateSortAndMapDB[M, D any](query *gorm.DB, records *[]M) ([]D, Response, error) {paginationResp, err := PaginateAndSortDB(params, query, records)if err != nil {- return nil, Response{}, errors.WrapIf(err, "paginate db records")+ return nil, Response{}, fmt.Errorf("paginate db records: %w", err)}out, err := mapping.MapSlice[M, D](*records)if err != nil {- return nil, Response{}, errors.WrapIf(err, "map db records")+ return nil, Response{}, fmt.Errorf("map db records: %w", err)}return out, paginationResp, nildiff --git a/backend/pkg/projects/build.go b/backend/pkg/projects/build.goindex b14e6f028..2745d3481 100644--- a/backend/pkg/projects/build.go+++ b/backend/pkg/projects/build.go@@ -2,13 +2,13 @@ package projectsimport ("cmp"+ "errors""fmt""maps""path/filepath""strconv""strings"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"@@ -24,13 +24,13 @@ func ResolveBuildContext(workingDir string, svc composetypes.ServiceConfig, servif contextDir == "" {contextDir = workingDir} else if _, isGitContext, err := contextsource.ParseGitBuildContextSource(contextDir); err != nil {- return "", errors.WrapIff(err, "invalid build context for service %s", serviceName)+ return "", fmt.Errorf("invalid build context for service %s: %w", serviceName, err)} else if !isGitContext && !filepath.IsAbs(contextDir) {contextDir = filepath.Join(workingDir, contextDir)}if contextDir == "" {- return "", errors.Errorf("build context not set for service %s", serviceName)+ return "", fmt.Errorf("build context not set for service %s", serviceName)}return contextDir, nil@@ -170,10 +170,10 @@ func PrepareServiceBuildRequest(effectiveProvider := resolveEffectiveBuildProviderInternal(options.Provider, defaultProvider)if updated && effectiveProvider == "depot" {- return buildtypes.BuildRequest{}, updatedSvc, updated, errors.Errorf("service %s must define an image when using depot build provider", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.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, errors.Errorf("service %s must define an image when push is enabled", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.Errorf("service %s must define an image when push is enabled", serviceName)}// Build providers read the context from Arcane's filesystem, so keep@@ -185,7 +185,7 @@ func PrepareServiceBuildRequest(dockerfileInline := updatedSvc.Build.DockerfileInlineif strings.TrimSpace(updatedSvc.Build.Dockerfile) != "" && strings.TrimSpace(dockerfileInline) != "" {- return buildtypes.BuildRequest{}, updatedSvc, updated, errors.Errorf("service %s cannot define both dockerfile and dockerfile_inline", serviceName)+ return buildtypes.BuildRequest{}, updatedSvc, updated, fmt.Errorf("service %s cannot define both dockerfile and dockerfile_inline", serviceName)}dockerfilePath := ""diff --git a/backend/pkg/projects/cache.go b/backend/pkg/projects/cache.goindex aab78ace1..910cdd53c 100644--- a/backend/pkg/projects/cache.go+++ b/backend/pkg/projects/cache.go@@ -8,7 +8,6 @@ import ("strings""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/samber/hot"@@ -67,7 +66,7 @@ func (c *composeCacheInternal[T]) Set(projectID, fingerprint, projectPath, proje}info, err := os.Stat(path)if err != nil {- return errors.WrapIff(err, "stat compose file %s", path)+ return fmt.Errorf("stat compose file %s: %w", path, err)}mtimes[path] = info.ModTime()}@@ -86,7 +85,7 @@ func (c *composeCacheInternal[T]) Set(projectID, fingerprint, projectPath, projecontinue}if !os.IsNotExist(err) {- return errors.WrapIff(err, "stat compose dependency %s", path)+ return fmt.Errorf("stat compose dependency %s: %w", path, err)}mtimes[path] = time.Time{}}diff --git a/backend/pkg/projects/coordinator.go b/backend/pkg/projects/coordinator.goindex 16d89a841..b343e32f6 100644--- a/backend/pkg/projects/coordinator.go+++ b/backend/pkg/projects/coordinator.go@@ -3,6 +3,8 @@ package projectsimport ("cmp""context"+ "errors"+ "fmt""io""log/slog""maps"@@ -10,7 +12,6 @@ import ("strings""time"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/compose/v5/pkg/api"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"@@ -44,16 +45,16 @@ func (c *composeCoordinatorInternal) Deploy(ctx context.Context, request project}()if request.PreDeploy != nil {if err := request.PreDeploy(ctx); err != nil {- return nil, errors.WrapIf(err, "pre-deploy lifecycle hook failed")+ return nil, fmt.Errorf("pre-deploy lifecycle hook failed: %w", err)}}model, err := request.Load(ctx)if err != nil {- return nil, errors.WrapIff(err, "failed to load compose project in %s", request.ProjectPath)+ return nil, fmt.Errorf("failed to load compose project in %s: %w", request.ProjectPath, err)}operations, err := request.ResolveImages(ctx)if err != nil {- return nil, errors.WrapIf(err, "resolve registry credentials")+ return nil, fmt.Errorf("resolve registry credentials: %w", err)}pullPolicy := ""forceRecreate, recreateVolumes := false, false@@ -66,16 +67,16 @@ func (c *composeCoordinatorInternal) Deploy(ctx context.Context, request project}pullPolicy = cmp.Or(pullPolicy, "missing")if err := c.PrepareImagesForDeploy(ctx, request.ProjectID, model, request.Progress, operations, pullPolicy); err != nil {- return nil, errors.WrapIf(err, "failed to prepare project images for deploy")+ return nil, fmt.Errorf("failed to prepare project images for deploy: %w", err)}removeOrphans := ResolveRemoveOrphans(request.GitOpsManaged, request.Options)slog.InfoContext(ctx, "starting compose up with health check support", "projectID", request.ProjectID, "projectName", model.Name, "services", len(model.Services), "removeOrphans", removeOrphans)if err := c.commands.Up(ctx, model, nil, removeOrphans, forceRecreate, recreateVolumes, request.AuthConfigs, request.WaitTimeout); err != nil {slog.ErrorContext(ctx, "compose up failed", "projectName", model.Name, "projectID", request.ProjectID, "error", err)if strings.Contains(err.Error(), "timeout") || strings.Contains(err.Error(), "context deadline exceeded") {- return nil, errors.WrapIf(err, "deployment timed out waiting for services - long-running 'service_healthy'/'service_completed_successfully' dependencies may need a higher Deploy Wait Timeout setting, and 'service_healthy' requires a healthcheck")+ return nil, fmt.Errorf("deployment timed out waiting for services - long-running 'service_healthy'/'service_completed_successfully' dependencies may need a higher Deploy Wait Timeout setting, and 'service_healthy' requires a healthcheck: %w", err)}- return nil, errors.WrapIf(err, "failed to deploy project")+ return nil, fmt.Errorf("failed to deploy project: %w", err)}slog.InfoContext(ctx, "compose up completed successfully", "projectID", request.ProjectID, "projectName", model.Name)return model, nil@@ -100,7 +101,7 @@ func (c *composeCoordinatorInternal) UpdateServices(ctx context.Context, requestif request.RestoreBeforeMutation != nil {request.RestoreBeforeMutation(ctx)}- return errors.WrapIf(err, "pull updated service images")+ return fmt.Errorf("pull updated service images: %w", err)}if err := c.commands.Stop(ctx, selected, scope); err != nil {slog.WarnContext(ctx, "compose stop failed, continuing", "error", err)@@ -109,7 +110,7 @@ func (c *composeCoordinatorInternal) UpdateServices(ctx context.Context, requestif request.Recover != nil {request.Recover(ctx)}- return errors.WrapIf(err, "failed to up services")+ return fmt.Errorf("failed to up services: %w", err)}// Stopped dependents are recreated after the up so they resolve the new// provider containers, and are left stopped.@@ -118,7 +119,7 @@ func (c *composeCoordinatorInternal) UpdateServices(ctx context.Context, requestif request.Recover != nil {request.Recover(ctx)}- return errors.WrapIf(err, "failed to recreate stopped dependents")+ return fmt.Errorf("failed to recreate stopped dependents: %w", err)}}return nil@@ -222,7 +223,7 @@ func (c *composeCoordinatorInternal) EnsureImagesPresent(ctx context.Context, mocontinue}if !exists {- return errors.Errorf("image %s is not available locally and pull_policy is 'never'", img)+ return fmt.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@@ -324,7 +325,7 @@ func (c *composeCoordinatorInternal) ensureDeployServiceImageReadyInternal(if decision.RequireLocalOnly {if !exists {- return errors.Errorf("image %s is not available locally and pull_policy is set to never", imageName)+ return fmt.Errorf("image %s is not available locally and pull_policy is set to never", imageName)}return nil}@@ -351,7 +352,7 @@ func (c *composeCoordinatorInternal) ensureDeployServiceImageReadyInternal(slog.WarnContext(ctx, "image pull failed, falling back to build", "service", serviceName, "image", imageName, "error", err)return c.buildServiceImageForDeployInternal(ctx, projectID, project, serviceName, svc, progressWriter, operations)}- return errors.WrapIff(err, "failed to pull image %s", imageName)+ return fmt.Errorf("failed to pull image %s: %w", imageName, err)}func (c *composeCoordinatorInternal) buildServiceImageForDeployInternal(@@ -364,7 +365,7 @@ func (c *composeCoordinatorInternal) buildServiceImageForDeployInternal(operations projecttypes.ComposeImageOperations,) error {if operations.Build == nil {- return errors.Errorf("build service not available for service %s", serviceName)+ return fmt.Errorf("build service not available for service %s", serviceName)}buildReq, updatedSvc, updated, err := PrepareServiceBuildRequest(projectID, project, serviceName, svc, projecttypes.BuildOptions{}, operations.BuildProvider)@@ -416,7 +417,7 @@ func (c *composeCoordinatorInternal) BuildServices(ctx context.Context, projectI}if buildCount == 0 && len(selected) > 0 {- return errors.Errorf("no build-enabled services matched: %s", strings.Join(options.Services, ", "))+ return fmt.Errorf("no build-enabled services matched: %s", strings.Join(options.Services, ", "))}return nildiff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.goindex 87350d4ea..6b89120dd 100644--- a/backend/pkg/projects/custom_labels.go+++ b/backend/pkg/projects/custom_labels.go@@ -3,7 +3,7 @@ package projectsimport ("cmp""context"- stderrors "errors"+ "errors""fmt""log/slog""maps"@@ -14,7 +14,6 @@ import ("strings""unicode"- "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/libarcane"@@ -82,7 +81,7 @@ func ParseArcaneComposeMetadata(ctx context.Context, composeFilePath, projectsDienvLoader := NewEnvLoader(projectsDirectory, workdir, autoInjectEnv)loaded, _, err := envLoader.LoadEnvironment(ctx)if err != nil {- return emptyArcaneComposeMetadataInternal(), errors.WrapIf(err, "load project environment")+ return emptyArcaneComposeMetadataInternal(), fmt.Errorf("load project environment: %w", err)}envMap = loaded}@@ -133,7 +132,7 @@ func parseArcaneComposeMetadataFromFileInternal(ctx context.Context, composeFileproject, err := loadComposeProjectForMetadataFromFileInternal(ctx, absPath, mergedEnv)if err != nil {- return meta, errors.WrapIf(err, "load compose metadata")+ return meta, fmt.Errorf("load compose metadata: %w", err)}meta = extractArcaneComposeMetadata(project)@@ -159,7 +158,7 @@ func parseArcaneComposeMetadataFromFileInternal(ctx context.Context, composeFile}includedMeta, err := parseArcaneComposeMetadataFromFileInternal(ctx, resolvedPath, mergedEnv, visited)if err != nil {- return meta, errors.WrapIff(err, "load included Compose metadata %s", resolvedPath)+ return meta, fmt.Errorf("load included Compose metadata %s: %w", resolvedPath, err)}mergeArcaneComposeMetadata(&meta, includedMeta)}@@ -408,12 +407,12 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {// outside any confinement root, including imported projects.content, err := os.ReadFile(composeFilePath)if err != nil {- return nil, errors.WrapIf(err, "read compose file")+ return nil, fmt.Errorf("read compose file: %w", err)}composeData := map[string]any{}if err := yaml.Unmarshal(content, &composeData); err != nil {- return nil, errors.WrapIf(err, "parse compose file")+ return nil, fmt.Errorf("parse compose file: %w", err)}rawIncludes, ok := composeData["include"]@@ -534,17 +533,17 @@ var projectTagColorsInternal = map[projecttypes.TagColor]struct{}{func NormalizeProjectTag(name string) (string, error) {normalized := strings.ToLower(strings.TrimSpace(name))if normalized == "" {- return "", stderrors.New("tag name cannot be empty")+ return "", errors.New("tag name cannot be empty")}if len([]rune(normalized)) > ProjectTagMaxLength {return "", fmt.Errorf("tag name cannot exceed %d characters", ProjectTagMaxLength)}if strings.ContainsRune(normalized, ',') {- return "", stderrors.New("tag name cannot contain commas")+ return "", errors.New("tag name cannot contain commas")}for _, char := range normalized {if unicode.IsControl(char) {- return "", stderrors.New("tag name cannot contain control characters")+ return "", errors.New("tag name cannot contain control characters")}}return normalized, nil@@ -588,11 +587,11 @@ func NormalizeProjectTagColor(color projecttypes.TagColor) (projecttypes.TagColofunc applyServiceLabelMetadataInternal(project *composetypes.Project) error {defaults, err := updaterMetadataLabelsInternal(project.Extensions[arcaneBlockKey])if err != nil {- return errors.WrapIf(err, "x-arcane.updater")+ return fmt.Errorf("x-arcane.updater: %w", err)}hiddenDefaults, err := hiddenMetadataLabelInternal(project.Extensions[arcaneBlockKey])if err != nil {- return errors.WrapIf(err, "x-arcane.hidden")+ return fmt.Errorf("x-arcane.hidden: %w", err)}if defaults == nil {defaults = map[string]string{}@@ -601,12 +600,12 @@ func applyServiceLabelMetadataInternal(project *composetypes.Project) error {for name, service := range project.Services {overrides, err := updaterMetadataLabelsInternal(service.Extensions[arcaneBlockKey])if err != nil {- return errors.WrapIff(err, "service %s x-arcane.updater", name)+ return fmt.Errorf("service %s x-arcane.updater: %w", name, err)}effective := maps.Clone(defaults)hiddenOverrides, err := hiddenMetadataLabelInternal(service.Extensions[arcaneBlockKey])if err != nil {- return errors.WrapIff(err, "service %s x-arcane.hidden", name)+ return fmt.Errorf("service %s x-arcane.hidden: %w", name, err)}maps.Copy(effective, overrides)maps.Copy(effective, hiddenOverrides)@@ -659,15 +658,15 @@ func updaterMetadataLabelsInternal(block any) (map[string]string, error) {case "tag-pattern":label = updaterlabels.LabelUpdateTagPatterndefault:- return nil, errors.Errorf("unknown updater option %q", key)+ return nil, fmt.Errorf("unknown updater option %q", key)}text, ok := value.(string)if !ok {- return nil, errors.Errorf("updater %s must be a string", key)+ return nil, fmt.Errorf("updater %s must be a string", key)}text = strings.TrimSpace(text)if key == "strategy" && text != "auto" && text != "tag" && text != "digest" {- return nil, errors.Errorf("unknown updater strategy %q", text)+ return nil, fmt.Errorf("unknown updater strategy %q", text)}result[label] = text}diff --git a/backend/pkg/projects/discovery.go b/backend/pkg/projects/discovery.goindex a05dd205b..5d7e13836 100644--- a/backend/pkg/projects/discovery.go+++ b/backend/pkg/projects/discovery.go@@ -2,6 +2,8 @@ package projectsimport ("context"+ "errors"+ "fmt""log/slog""os""path/filepath"@@ -9,7 +11,6 @@ import ("slices""strings"- "emperror.dev/errors""github.com/compose-spec/compose-go/v2/loader""github.com/getarcaneapp/arcane/backend/v2/internal/common"kit "go.getarcane.app/kit/pkg"@@ -77,7 +78,7 @@ func DiscoverProjectDirectories(ctx context.Context, root string, followSymlinksisDir, err := IsProjectDirectoryPath(root, followSymlinks)if err == nil && !isDir {- return nil, errors.Errorf("project root is not a directory: %s", root)+ return nil, fmt.Errorf("project root is not a directory: %s", root)}discovered := make([]DiscoveredProjectDir, 0)@@ -91,7 +92,7 @@ func DiscoverProjectDirectories(ctx context.Context, root string, followSymlinks// when the container was started as root, so a root-only projects// directory is genuinely unreadable (#3489).if errors.Is(err, os.ErrPermission) {- return nil, errors.WrapIff(err, "projects directory is not readable by the runtime user (uid %d): fix its permissions or set PUID/PGID to an owner that can read it", os.Geteuid())+ return nil, fmt.Errorf("projects directory is not readable by the runtime user (uid %d): fix its permissions or set PUID/PGID to an owner that can read it: %w", os.Geteuid(), err)}return nil, err}diff --git a/backend/pkg/projects/env.go b/backend/pkg/projects/env.goindex d3e091dd7..55cb16d79 100644--- a/backend/pkg/projects/env.go+++ b/backend/pkg/projects/env.go@@ -2,6 +2,8 @@ package projectsimport ("context"+ "errors"+ "fmt""log/slog""maps""os"@@ -13,7 +15,6 @@ import ("syscall""time"- "emperror.dev/errors""github.com/compose-spec/compose-go/v2/consts""github.com/compose-spec/compose-go/v2/dotenv""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -142,7 +143,7 @@ func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap, injectionVarscase errors.Is(err, os.ErrNotExist):slog.DebugContext(ctx, "Project .env file does not exist", "path", projectEnvPath)case errors.Is(err, os.ErrPermission):- return envMap, injectionVars, common.Classify(common.ErrProjectEnvUnreadable, errors.WrapIff(err, "%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it", projectEnvPath, os.Geteuid(), os.Getegid()))+ return envMap, injectionVars, common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w", projectEnvPath, os.Geteuid(), os.Getegid(), err))default:slog.WarnContext(ctx, "Failed to load project env", "path", projectEnvPath, "error", err)}@@ -232,12 +233,12 @@ func loadCachedEnvFileInternal(_ context.Context, envCache *hot.HotCache[string,return nil, err}if info.IsDir() {- return nil, errors.Errorf("path is a directory: %s", path)+ return nil, fmt.Errorf("path is a directory: %s", path)}parsed, err := parseProjectEnvFileExistingInternal(path, contextEnv)if err != nil {- return nil, errors.WrapIf(err, "parse env file")+ return nil, fmt.Errorf("parse env file: %w", err)}entry.exists = trueentry.mtime = info.ModTime()@@ -277,7 +278,7 @@ func validEnvFileCacheEntryInternal(entry envFileCacheEntry) bool {func parseProjectEnvFileExistingInternal(path string, contextEnv EnvMap) (EnvMap, error) {content, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIf(err, "read file")+ return nil, fmt.Errorf("read file: %w", err)}return ParseProjectEnvContent(string(content), contextEnv)}@@ -308,7 +309,7 @@ func ParseProjectEnvContent(content string, contextEnv EnvMap) (EnvMap, error) {envMap, err := dotenv.ParseWithLookup(strings.NewReader(content), lookupFn)if err != nil {- return nil, errors.WrapIf(err, "parse env")+ return nil, fmt.Errorf("parse env: %w", err)}return envMap, nil@@ -324,7 +325,7 @@ func WithTransientValidationEnvFile(ctx context.Context, projectPath string, efforiginalExists := readErr == nilif readErr != nil && !os.IsNotExist(readErr) {if !errors.Is(readErr, os.ErrPermission) && !errors.Is(readErr, syscall.EISDIR) {- return errors.WrapIf(readErr, "prepare env file for compose validation")+ return fmt.Errorf("prepare env file for compose validation: %w", readErr)}// The path exists but is permission-locked (e.g. chmod 000, foreign-owned) or a directory.// Its contents can't be verified or safely overwritten, so leave it@@ -345,7 +346,7 @@ func WithTransientValidationEnvFile(ctx context.Context, projectPath string, effcontent = *effectiveEnvContent}if writeErr := WriteProjectFile(ctx, projectPath, projectPath, ".env", content); writeErr != nil {- return errors.WrapIf(writeErr, "prepare env file for compose validation")+ return fmt.Errorf("prepare env file for compose validation: %w", writeErr)}defer func() {@@ -359,7 +360,7 @@ func WithTransientValidationEnvFile(ctx context.Context, projectPath string, effif restoreErr != nil && !os.IsNotExist(restoreErr) {if err == nil {- err = errors.WrapIf(restoreErr, "restore env file after compose validation")+ err = fmt.Errorf("restore env file after compose validation: %w", restoreErr)}}}()@@ -383,13 +384,13 @@ func BuildEffectiveEnvContent(gitContent, overrideContent string) (string, errorgitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse git env content")+ return "", fmt.Errorf("parse git env content: %w", err)}maps.Copy(contextEnv, gitEnv)overrideEnv, err := ParseProjectEnvContent(overrideContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse override env content")+ return "", fmt.Errorf("parse override env content: %w", err)}switch {@@ -519,13 +520,13 @@ func BuildAdditiveOverrideEnvContent(gitContent, localContent string) (string, egitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse git env content")+ return "", fmt.Errorf("parse git env content: %w", err)}maps.Copy(contextEnv, gitEnv)localEnv, err := ParseProjectEnvContent(localContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse local env content")+ return "", fmt.Errorf("parse local env content: %w", err)}override := make(EnvMap)@@ -546,13 +547,13 @@ func BuildOverrideEnvContent(gitContent, effectiveContent string) (string, errorgitEnv, err := ParseProjectEnvContent(gitContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse git env content")+ return "", fmt.Errorf("parse git env content: %w", err)}maps.Copy(contextEnv, gitEnv)effectiveEnv, err := ParseProjectEnvContent(effectiveContent, contextEnv)if err != nil {- return "", errors.WrapIf(err, "parse effective env content")+ return "", fmt.Errorf("parse effective env content: %w", err)}override := make(EnvMap)@@ -695,7 +696,7 @@ func WriteManagedEnvFile(ctx context.Context, projectsDirectory, projectPath, fi}return WriteProjectFile(ctx, projectsDirectory, projectPath, OverrideEnvFileName, content)default:- return errors.Errorf("write managed env file: unsupported file name %q", fileName)+ return fmt.Errorf("write managed env file: unsupported file name %q", fileName)}}@@ -719,7 +720,7 @@ func readOptionalProjectFileInternal(projectPath, fileName string) (content striif errors.Is(readErr, os.ErrPermission) || errors.Is(readErr, syscall.EISDIR) {return "", false, true, nil}- return "", false, false, errors.WrapIff(readErr, "read %s", fileName)+ return "", false, false, fmt.Errorf("read %s: %w", fileName, readErr)}// formatEnvMapInternal serializes env maps into Arcane's canonical generated@@ -807,7 +808,7 @@ func ParseComposeEnvOptions(workdir string, env EnvMap) (ComposeEnvOptions, errofor _, entry := range ComposeEnvFileEntriesFromEnv(env) {resolved, resErr := ResolvePathWithinDir(workdir, entry)if resErr != nil {- return ComposeEnvOptions{}, common.Classify(common.ErrComposeFileEnvInvalid, errors.WrapIff(resErr, "COMPOSE_ENV_FILES entry %q", entry))+ return ComposeEnvOptions{}, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("COMPOSE_ENV_FILES entry %q: %w", entry, resErr))}opts.EnvFiles = append(opts.EnvFiles, resolved)}@@ -850,7 +851,7 @@ func ComposeFileEnvSelection(ctx context.Context, projectsDir, dir string) ([]stprojectEnv, err := ParseProjectEnvFile(projectEnvPath, envMap)if err != nil {if errors.Is(err, os.ErrPermission) {- return nil, common.Classify(common.ErrProjectEnvUnreadable, errors.WrapIff(err, "%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it", projectEnvPath, os.Geteuid(), os.Getegid()))+ return nil, common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w", projectEnvPath, os.Geteuid(), os.Getegid(), err))}return nil, err}@@ -903,22 +904,22 @@ func resolveComposeFileSelectionInternal(workdir string, env EnvMap) ([]string,absWorkdir, err := filepath.Abs(filepath.Clean(workdir))if err != nil {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.WrapIf(err, "resolve project directory"))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("resolve project directory: %w", err))}files := make([]string, 0, len(entries))for i, entry := range entries {if filepath.IsAbs(entry) {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.Errorf("COMPOSE_FILE entry %q must be relative to the project directory", entry))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("COMPOSE_FILE entry %q must be relative to the project directory", entry))}resolved, resErr := ResolvePathWithinDir(absWorkdir, entry)if resErr != nil {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.WrapIff(resErr, "COMPOSE_FILE entry %q", entry))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("COMPOSE_FILE entry %q: %w", entry, resErr))}if i == 0 && filepath.Dir(resolved) != absWorkdir {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.Errorf("the first COMPOSE_FILE entry %q must be in the project directory", entry))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("the first COMPOSE_FILE entry %q must be in the project directory", entry))}// os.Stat rather than acfs: compose files may be symlinks resolving@@ -926,10 +927,10 @@ func resolveComposeFileSelectionInternal(workdir string, env EnvMap) ([]string,// living outside the projects directory.info, statErr := os.Stat(resolved)if statErr != nil {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.WrapIff(statErr, "COMPOSE_FILE entry %q", entry))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("COMPOSE_FILE entry %q: %w", entry, statErr))}if info.IsDir() {- return nil, common.Classify(common.ErrComposeFileEnvInvalid, errors.Errorf("COMPOSE_FILE entry %q is a directory", entry))+ return nil, common.Classify(common.ErrComposeFileEnvInvalid, fmt.Errorf("COMPOSE_FILE entry %q is a directory", entry))}files = append(files, resolved)diff --git a/backend/pkg/projects/env_test.go b/backend/pkg/projects/env_test.goindex 25621a492..cff1b00d4 100644--- a/backend/pkg/projects/env_test.go+++ b/backend/pkg/projects/env_test.go@@ -2,13 +2,12 @@ package projectsimport ("context"- stderrors "errors"+ "errors""os""path/filepath""runtime""testing"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/stretchr/testify/assert"@@ -109,7 +108,7 @@ func TestWithTransientValidationEnvFile_PreservesExternalSymlink(t *testing.T) {originalLinkTarget, err := os.Readlink(envPath)require.NoError(t, err)- validationErr := stderrors.New("validation failed")+ validationErr := errors.New("validation failed")updatedContent := "VALUE=validation\n"err = WithTransientValidationEnvFile(t.Context(), projectDir, &updatedContent, func() error {content, readErr := os.ReadFile(targetPath)diff --git a/backend/pkg/projects/env_unix_test.go b/backend/pkg/projects/env_unix_test.goindex 97ea08c97..9a7b5940c 100644--- a/backend/pkg/projects/env_unix_test.go+++ b/backend/pkg/projects/env_unix_test.go@@ -3,7 +3,7 @@package projectsimport (- stderrors "errors"+ "errors""os""path/filepath""testing"@@ -80,7 +80,7 @@ func TestWithTransientValidationEnvFile_LeavesEnvDirectoryUntouched(t *testing.Trequire.NoError(t, os.WriteFile(nested, []byte("x"), utils.FilePerm))content := "FOO=bar\n"- runErr := stderrors.New("validation failed")+ runErr := errors.New("validation failed")called := falseerr := WithTransientValidationEnvFile(t.Context(), projectDir, &content, func() error {called = truediff --git a/backend/pkg/projects/env_validation.go b/backend/pkg/projects/env_validation.goindex cbeda00df..482a93b21 100644--- a/backend/pkg/projects/env_validation.go+++ b/backend/pkg/projects/env_validation.go@@ -3,12 +3,12 @@ package projectsimport ("bufio""context"+ "fmt""maps""os""path/filepath""strings"- "emperror.dev/errors""github.com/compose-spec/compose-go/v2/consts""github.com/compose-spec/compose-go/v2/dotenv""github.com/getarcaneapp/arcane/types/v2/env"@@ -28,7 +28,7 @@ func BuildValidationEnvironment(ctx context.Context, projectsDirectory, projectPglobalEnvPath := filepath.Join(projectsDirectory, GlobalEnvFileName)globalEnv, err := ParseValidationEnvFile(globalEnvPath, fullEnvMap)if err != nil {- return nil, errors.WrapIf(err, "parse global env file")+ return nil, fmt.Errorf("parse global env file: %w", err)}maps.Copy(fullEnvMap, globalEnv)@@ -38,13 +38,13 @@ func BuildValidationEnvironment(ctx context.Context, projectsDirectory, projectPif effectiveEnvContent != nil {projectEnv, err := ParseValidationEnvContent(*effectiveEnvContent, fullEnvMap)if err != nil {- return nil, errors.WrapIf(err, "parse provided env content")+ return nil, fmt.Errorf("parse provided env content: %w", err)}maps.Copy(fullEnvMap, projectEnv)} else {projectEnv, err := ParseValidationEnvFile(filepath.Join(projectPath, ".env"), fullEnvMap)if err != nil {- return nil, errors.WrapIf(err, "parse project env file")+ return nil, fmt.Errorf("parse project env file: %w", err)}maps.Copy(fullEnvMap, projectEnv)}@@ -66,7 +66,7 @@ func ParseValidationEnvFile(path string, contextEnv EnvMap) (EnvMap, error) {if os.IsNotExist(err) {return nil, nil}- return nil, errors.WrapIf(err, "stat file")+ return nil, fmt.Errorf("stat file: %w", err)}if info.IsDir() {return nil, nil@@ -74,7 +74,7 @@ func ParseValidationEnvFile(path string, contextEnv EnvMap) (EnvMap, error) {content, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIf(err, "read file")+ return nil, fmt.Errorf("read file: %w", err)}return ParseValidationEnvContent(string(content), contextEnv)@@ -90,7 +90,7 @@ func ParseValidationEnvContent(content string, contextEnv EnvMap) (EnvMap, errorenvMap, err := dotenv.ParseWithLookup(strings.NewReader(content), lookupFn)if err != nil {- return nil, errors.WrapIf(err, "parse env")+ return nil, fmt.Errorf("parse env: %w", err)}return envMap, nildiff --git a/backend/pkg/projects/fs_backup.go b/backend/pkg/projects/fs_backup.goindex f33578f66..380d1a3bf 100644--- a/backend/pkg/projects/fs_backup.go+++ b/backend/pkg/projects/fs_backup.go@@ -2,6 +2,8 @@ package projectsimport ("context"+ "errors"+ "fmt""log/slog""os""path"@@ -9,7 +11,6 @@ import ("slices""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""go.getarcane.app/acfs""go.getarcane.app/acfs/atomic"@@ -67,13 +68,13 @@ type ProjectUpdateBackup struct {func BackupProjectUpdateScope(ctx context.Context, projectDir, backupDir string, scope ProjectUpdateBackupScope) (*ProjectUpdateBackup, error) {projRoot, err := os.OpenRoot(projectDir)if err != nil {- return nil, errors.WrapIf(err, "open project directory")+ return nil, fmt.Errorf("open project directory: %w", err)}defer func() { _ = projRoot.Close() }()backupRoot, err := os.OpenRoot(backupDir)if err != nil {- return nil, errors.WrapIf(err, "open backup directory")+ return nil, fmt.Errorf("open backup directory: %w", err)}defer func() { _ = backupRoot.Close() }()@@ -116,7 +117,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 errors.WrapIf(err, "read project directory")+ return fmt.Errorf("read project directory: %w", err)}for _, entry := range entries {name := entry.Name()@@ -147,18 +148,18 @@ func backupScopePathInternal(ctx context.Context, projRoot, backupRoot *os.Root,return nil}if err != nil {- return errors.WrapIff(err, "inspect project path %s", rel)+ return fmt.Errorf("inspect project path %s: %w", rel, err)}switch {case info.IsDir():destDir := filepath.Join(backupDir, filepath.FromSlash(rel))if err := os.MkdirAll(destDir, 0o755); err != nil {- return errors.WrapIf(err, "create backup directory")+ return fmt.Errorf("create backup directory: %w", err)}copied, err := acfs.CopyDir(ctx, filepath.Join(projectDir, filepath.FromSlash(rel)), destDir, acfstypes.CopyOptions{TolerateUnreadable: true})if err != nil {- return errors.WrapIff(err, "backup project directory %s", rel)+ return fmt.Errorf("backup project directory %s: %w", rel, err)}for _, sub := range copied.Skipped {backup.Skipped = append(backup.Skipped, path.Join(rel, filepath.ToSlash(sub)))@@ -187,7 +188,7 @@ func shallowestAbsentAncestorInternal(projRoot *os.Root, rel string) (string, erif errors.Is(err, os.ErrNotExist) {return current, nil}- return "", errors.WrapIff(err, "inspect project path %s", current)+ return "", fmt.Errorf("inspect project path %s: %w", current, err)}}return rel, nil@@ -196,7 +197,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 errors.WrapIff(err, "inspect project file %s", rel)+ return fmt.Errorf("inspect project file %s: %w", rel, err)}content, err := projRoot.ReadFile(rel)if err != nil {@@ -204,15 +205,15 @@ func copyBackupFileInternal(projRoot, backupRoot *os.Root, rel string, backup *Pbackup.Skipped = append(backup.Skipped, rel)return nil}- return errors.WrapIff(err, "read project file %s", rel)+ return fmt.Errorf("read project file %s: %w", rel, err)}if dir := path.Dir(rel); dir != "." {if err := backupRoot.MkdirAll(dir, 0o755); err != nil {- return errors.WrapIf(err, "create backup directory")+ return fmt.Errorf("create backup directory: %w", err)}}if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); err != nil {- return errors.WrapIff(err, "write backup file %s", rel)+ return fmt.Errorf("write backup file %s: %w", rel, err)}backup.FileEntries = append(backup.FileEntries, rel)return nil@@ -226,7 +227,7 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bacbackup.Skipped = append(backup.Skipped, rel)return nil}- return errors.WrapIff(err, "read project env symlink %s", rel)+ return fmt.Errorf("read project env symlink %s: %w", rel, err)}resolvedPath, perm, isSymlink, err := resolveEnvFileWriteTargetInternal(envPath)@@ -239,10 +240,10 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bac// Dangling link: env writes leave it untouched, so there is nothing to restore.return nil}- return errors.WrapIff(err, "resolve project env symlink %s", rel)+ return fmt.Errorf("resolve project env symlink %s: %w", rel, err)}if !isSymlink {- return errors.Errorf("project env file %s is no longer a symlink", rel)+ return fmt.Errorf("project env file %s is no longer a symlink", rel)}content, err := os.ReadFile(resolvedPath)@@ -251,10 +252,10 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bacbackup.Skipped = append(backup.Skipped, rel)return nil}- return errors.WrapIff(err, "read project env symlink target %s", rel)+ return fmt.Errorf("read project env symlink target %s: %w", rel, err)}if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, perm); err != nil {- return errors.WrapIff(err, "write backup file %s", rel)+ return fmt.Errorf("write backup file %s: %w", rel, err)}backup.FileEntries = append(backup.FileEntries, rel)@@ -290,7 +291,7 @@ func dedupeCoveredBackupEntriesInternal(backup *ProjectUpdateBackup) {func RestoreProjectUpdateBackup(ctx context.Context, projectDir string, backup *ProjectUpdateBackup) error {projRoot, err := os.OpenRoot(projectDir)if err != nil {- return errors.WrapIf(err, "open project directory")+ return fmt.Errorf("open project directory: %w", err)}defer func() { _ = projRoot.Close() }()@@ -305,23 +306,23 @@ func RestoreProjectUpdateBackup(ctx context.Context, projectDir string, backup *for _, rel := range backup.DirEntries {if live, err := projRoot.Lstat(rel); err == nil && !live.IsDir() {if err := projRoot.Remove(rel); err != nil {- return errors.WrapIff(err, "remove conflicting file %s", rel)+ return fmt.Errorf("remove conflicting file %s: %w", rel, err)}}if err := projRoot.MkdirAll(rel, 0o755); err != nil {- return errors.WrapIff(err, "recreate project directory %s", rel)+ return fmt.Errorf("recreate project directory %s: %w", rel, err)}preserve := skippedUnderInternal(backup.Skipped, rel)src := filepath.Join(backup.BackupDir, filepath.FromSlash(rel))dest := filepath.Join(projectDir, filepath.FromSlash(rel))if err := acfs.MirrorDir(ctx, src, dest, acfstypes.MirrorOptions{Preserve: preserve}); err != nil {- return errors.WrapIff(err, "restore project directory %s", rel)+ return fmt.Errorf("restore project directory %s: %w", rel, err)}}backupRoot, err := os.OpenRoot(backup.BackupDir)if err != nil {- return errors.WrapIf(err, "open backup directory")+ return fmt.Errorf("open backup directory: %w", err)}defer func() { _ = backupRoot.Close() }()@@ -365,12 +366,12 @@ func undoRenamedDirsAndDebrisInternal(projRoot *os.Root, backup *ProjectUpdateBacontinue}if err := projRoot.RemoveAll(src); err != nil {- return errors.WrapIff(err, "remove recreated path %s", src)+ return fmt.Errorf("remove recreated path %s: %w", src, err)}handledAbsent[src] = true}if err := projRoot.Rename(dest, src); err != nil {- return errors.WrapIff(err, "undo rename of %s", src)+ return fmt.Errorf("undo rename of %s: %w", src, err)}}@@ -381,7 +382,7 @@ func undoRenamedDirsAndDebrisInternal(projRoot *os.Root, backup *ProjectUpdateBacontinue}if err := projRoot.RemoveAll(rel); err != nil {- return errors.WrapIff(err, "remove created path %s", rel)+ return fmt.Errorf("remove created path %s: %w", rel, err)}}return nil@@ -401,11 +402,11 @@ func skippedUnderInternal(skipped []string, rel string) []string {func restoreBackupFileInternal(ctx context.Context, backupRoot, projRoot *os.Root, backup *ProjectUpdateBackup, rel string) error {info, err := backupRoot.Lstat(rel)if err != nil {- return errors.WrapIff(err, "inspect backup file %s", rel)+ return fmt.Errorf("inspect backup file %s: %w", rel, err)}content, err := backupRoot.ReadFile(rel)if err != nil {- return errors.WrapIff(err, "read backup file %s", rel)+ return fmt.Errorf("read backup file %s: %w", rel, err)}if backup.envSymlink != nil && backup.envSymlink.relativePath == rel {return restoreBackupEnvSymlinkInternal(projRoot, backup.envSymlink, content, info.Mode().Perm())@@ -414,24 +415,24 @@ func restoreBackupFileInternal(ctx context.Context, backupRoot, projRoot *os.Rooif liveErr == nil && live.Mode().IsRegular() {// In place: the inode survives so container bind mounts of the file stay valid.if err := acfs.Write(ctx, projRoot.Name(), "/"+rel, content, acfs.WriteOptions{Mode: info.Mode().Perm(), InPlace: true}); err != nil {- return errors.WrapIff(err, "restore project file %s", rel)+ return fmt.Errorf("restore project file %s: %w", rel, err)}return nil}if liveErr == nil && live.IsDir() {if err := projRoot.RemoveAll(rel); err != nil {- return errors.WrapIff(err, "remove conflicting directory %s", rel)+ return fmt.Errorf("remove conflicting directory %s: %w", rel, err)}}if dir := path.Dir(rel); dir != "." {if err := projRoot.MkdirAll(dir, 0o755); err != nil {- return errors.WrapIff(err, "recreate parent directory of %s", rel)+ return fmt.Errorf("recreate parent directory of %s: %w", rel, err)}}// Atomic create: a crash mid-restore leaves either nothing 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 errors.WrapIff(err, "restore project file %s", rel)+ return fmt.Errorf("restore project file %s: %w", rel, err)}return nil}@@ -440,30 +441,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 errors.WrapIf(err, "inspect project env symlink during restore")+ return fmt.Errorf("inspect project env symlink during restore: %w", err)}if info.Mode()&os.ModeSymlink == 0 {- return errors.Errorf("refusing to restore project env file %s: destination is no longer a symlink", envBackup.relativePath)+ return fmt.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 errors.WrapIf(err, "read project env symlink during restore")+ return fmt.Errorf("read project env symlink during restore: %w", err)}if linkTarget != envBackup.linkTarget {- return errors.Errorf("refusing to restore project env file %s: symlink target changed", envBackup.relativePath)+ return fmt.Errorf("refusing to restore project env file %s: symlink target changed", envBackup.relativePath)}resolvedPath, _, isSymlink, err := resolveEnvFileWriteTargetInternal(envPath)if err != nil {- return errors.WrapIf(err, "resolve project env symlink during restore")+ return fmt.Errorf("resolve project env symlink during restore: %w", err)}if !isSymlink || filepath.Clean(resolvedPath) != envBackup.resolvedPath {- return errors.Errorf("refusing to restore project env file %s: resolved symlink target changed", envBackup.relativePath)+ return fmt.Errorf("refusing to restore project env file %s: resolved symlink target changed", envBackup.relativePath)}if err := atomic.WriteFile(resolvedPath, content, perm); err != nil {- return errors.WrapIff(err, "restore project env symlink target %s", envBackup.relativePath)+ return fmt.Errorf("restore project env symlink target %s: %w", envBackup.relativePath, err)}return nil}@@ -471,7 +472,7 @@ func restoreBackupEnvSymlinkInternal(projRoot *os.Root, envBackup *projectUpdatefunc restoreTopLevelFilesInternal(ctx context.Context, backupRoot, projRoot *os.Root, backup *ProjectUpdateBackup) error {backupEntries, err := os.ReadDir(backupRoot.Name())if err != nil {- return errors.WrapIf(err, "read backup directory")+ return fmt.Errorf("read backup directory: %w", err)}inBackup := make(map[string]bool, len(backupEntries))for _, entry := range backupEntries {@@ -488,7 +489,7 @@ func restoreTopLevelFilesInternal(ctx context.Context, backupRoot, projRoot *os.liveEntries, err := os.ReadDir(projRoot.Name())if err != nil {- return errors.WrapIf(err, "read project directory")+ return fmt.Errorf("read project directory: %w", err)}for _, entry := range liveEntries {name := entry.Name()@@ -496,7 +497,7 @@ func restoreTopLevelFilesInternal(ctx context.Context, backupRoot, projRoot *os.continue}if err := projRoot.Remove(name); err != nil {- return errors.WrapIff(err, "prune created file %s", name)+ return fmt.Errorf("prune created file %s: %w", name, err)}}@@ -525,7 +526,7 @@ func BackupProjectDirectory(ctx context.Context, projectsDirectory, projectPath,backupLogical, err := acfs.MkdirTemp(ctx, rootAbs, "/", pattern)if err != nil {- return nil, nil, errors.WrapIf(err, "failed to create project backup directory")+ return nil, nil, fmt.Errorf("failed to create project backup directory: %w", err)}backupPath := filepath.Join(rootAbs, filepath.FromSlash(strings.TrimPrefix(backupLogical, "/")))cleanupCtx := context.WithoutCancel(ctx)@@ -537,7 +538,7 @@ func BackupProjectDirectory(ctx context.Context, projectsDirectory, projectPath,backup, err := BackupProjectUpdateScope(ctx, projectAbs, backupPath, scope)if err != nil {cleanup()- return nil, nil, errors.WrapIf(err, "failed to backup project files")+ return nil, nil, fmt.Errorf("failed to backup project files: %w", err)}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)@@ -555,15 +556,15 @@ func RestoreProjectDirectoryBackup(ctx context.Context, projectsDirectory, projeprojectLogical, err := acfs.LogicalPath(rootAbs, projectAbs)if err != nil {- return errors.WrapIf(err, "failed to resolve project directory")+ return fmt.Errorf("failed to resolve project directory: %w", err)}slog.DebugContext(ctx, "restoring project directory backup", "path", projectAbs, "backup", backup.BackupDir)if err := acfs.MkdirAll(ctx, rootAbs, projectLogical, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to recreate project directory")+ return fmt.Errorf("failed to recreate project directory: %w", err)}if err := RestoreProjectUpdateBackup(ctx, projectAbs, backup); err != nil {- return errors.WrapIf(err, "failed to restore project backup")+ return fmt.Errorf("failed to restore project backup: %w", err)}return nil}@@ -571,13 +572,13 @@ func RestoreProjectDirectoryBackup(ctx context.Context, projectsDirectory, projefunc resolveProjectUnderRootInternal(projectsDirectory, projectPath string) (projectAbs, rootAbs string, err error) {projectAbs, err = filepath.Abs(projectPath)if err != nil {- return "", "", errors.WrapIf(err, "failed to resolve project path")+ return "", "", fmt.Errorf("failed to resolve project path: %w", err)}projectAbs = filepath.Clean(projectAbs)rootAbs, err = filepath.Abs(projectsDirectory)if err != nil {- return "", "", errors.WrapIf(err, "failed to resolve projects directory")+ return "", "", fmt.Errorf("failed to resolve projects directory: %w", err)}rootAbs = filepath.Clean(rootAbs)if !IsSafeSubdirectory(rootAbs, projectAbs) || projectAbs == rootAbs {diff --git a/backend/pkg/projects/fs_templates.go b/backend/pkg/projects/fs_templates.goindex ea114d5bb..43267be62 100644--- a/backend/pkg/projects/fs_templates.go+++ b/backend/pkg/projects/fs_templates.go@@ -2,13 +2,14 @@ package projectsimport ("context"+ "errors"+ "fmt""log/slog""os""path/filepath""regexp""strings"- "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"@@ -27,12 +28,12 @@ func ReadFolderComposeTemplate(ctx context.Context, baseDir, folder string) (strif errors.Is(err, common.ErrComposeFileNotFound) {return "", nil, "", false, nil}- return "", nil, "", false, errors.WrapIf(err, "detect compose file")+ return "", nil, "", false, fmt.Errorf("detect compose file: %w", err)}b, err := os.ReadFile(composePath)if err != nil {- return "", nil, "", false, errors.WrapIff(err, "read compose %s", composePath)+ return "", nil, "", false, fmt.Errorf("read compose %s: %w", composePath, err)}var envPtr *string@@ -67,15 +68,15 @@ 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 "", "", "", errors.WrapIf(derr, "ensure templates dir")+ return "", "", "", fmt.Errorf("ensure templates dir: %w", derr)}dir = filepath.Join(baseDir, base)dirLogical, err := acfs.LogicalPath(baseDir, dir)if err != nil {- return "", "", "", errors.WrapIf(err, "template directory is outside the templates root")+ return "", "", "", fmt.Errorf("template directory is outside the templates root: %w", err)}if err := acfs.MkdirAll(ctx, baseDir, dirLogical, utils.DirPerm); err != nil {- return "", "", "", errors.WrapIf(err, "failed to create template directory")+ return "", "", "", fmt.Errorf("failed to create template directory: %w", err)}composePath = filepath.Join(dir, "compose.yaml")envPath = filepath.Join(dir, ".env.example")@@ -101,42 +102,42 @@ func WriteTemplateFiles(composePath, envPath, composeContent, envContent string)func EnsureDefaultTemplates(ctx context.Context, configuredTemplatesDir string) error {templatesDir, err := GetTemplatesDirectory(ctx, configuredTemplatesDir)if err != nil {- return errors.WrapIf(err, "get templates directory")+ return fmt.Errorf("get templates directory: %w", err)}// Write default compose template if it doesn't existif exists, err := acfs.Exists(ctx, templatesDir, "/.compose.template"); err != nil {- return errors.WrapIf(err, "write default compose template")+ return fmt.Errorf("write default compose template: %w", err)} else if !exists {if err := acfs.Write(ctx, templatesDir, "/.compose.template", []byte(getDefaultComposeTemplate()), acfs.WriteOptions{Mode: utils.FilePerm}); err != nil {- return errors.WrapIf(err, "write default compose template")+ return fmt.Errorf("write default compose template: %w", err)}}// Write default swarm stack template if it doesn't existif exists, err := acfs.Exists(ctx, templatesDir, "/.swarm-stack.template"); err != nil {- return errors.WrapIf(err, "write default swarm stack template")+ return fmt.Errorf("write default swarm stack template: %w", err)} else if !exists {if err := acfs.Write(ctx, templatesDir, "/.swarm-stack.template", []byte(DefaultSwarmStackTemplate()), acfs.WriteOptions{Mode: utils.FilePerm}); err != nil {- return errors.WrapIf(err, "write default swarm stack template")+ return fmt.Errorf("write default swarm stack template: %w", err)}}// Write default swarm stack env template if it doesn't existif exists, err := acfs.Exists(ctx, templatesDir, "/.swarm-stack.env.template"); err != nil {- return errors.WrapIf(err, "write default swarm stack env template")+ return fmt.Errorf("write default swarm stack env template: %w", err)} else if !exists {if err := acfs.Write(ctx, templatesDir, "/.swarm-stack.env.template", []byte(DefaultSwarmStackEnvTemplate()), acfs.WriteOptions{Mode: utils.FilePerm}); err != nil {- return errors.WrapIf(err, "write default swarm stack env template")+ return fmt.Errorf("write default swarm stack env template: %w", err)}}// Write default env template if it doesn't existif exists, err := acfs.Exists(ctx, templatesDir, "/.env.template"); err != nil {- return errors.WrapIf(err, "write default env template")+ return fmt.Errorf("write default env template: %w", err)} else if !exists {if err := acfs.Write(ctx, templatesDir, "/.env.template", []byte(getDefaultEnvTemplate()), acfs.WriteOptions{Mode: utils.FilePerm}); err != nil {- return errors.WrapIf(err, "write default env template")+ return fmt.Errorf("write default env template: %w", err)}}diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.goindex ebaadb896..8a672d290 100644--- a/backend/pkg/projects/fs_util.go+++ b/backend/pkg/projects/fs_util.go@@ -4,6 +4,7 @@ import ("bytes""cmp""context"+ "errors""fmt""io/fs""log/slog"@@ -12,7 +13,6 @@ import ("slices""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/pkg/utils"@@ -115,7 +115,7 @@ func ReadProjectFiles(ctx context.Context, projectPath, composePath string) (comif strings.TrimSpace(composePath) != "" {content, rerr := os.ReadFile(composePath)if rerr != nil {- return "", "", errors.WrapIff(rerr, "failed to read compose file %s", composePath)+ return "", "", fmt.Errorf("failed to read compose file %s: %w", composePath, rerr)}composeContent = string(content)}@@ -215,7 +215,7 @@ func DirectorySyncContentsChanged(ctx context.Context, projectPath string, syncF}return false, err} else if !info.IsDir() {- return false, errors.Errorf("project path is not a directory: %s", projectPath)+ return false, fmt.Errorf("project path is not a directory: %s", projectPath)}newFileSet := make(map[string]struct{}, len(syncFiles))@@ -335,7 +335,7 @@ func CreateUniqueDir(ctx context.Context, projectsRoot, basePath, name string, pfor counter := 1; ; counter++ {logicalPath, logicalErr := acfs.LogicalPath(projectsRoot, candidate)if logicalErr != nil {- return "", "", errors.WrapIf(logicalErr, "project directory would be outside allowed projects root")+ return "", "", fmt.Errorf("project directory would be outside allowed projects root: %w", logicalErr)}mkErr := acfs.Mkdir(ctx, projectsRoot, logicalPath, perm)@@ -355,7 +355,7 @@ func CreateUniqueDir(ctx context.Context, projectsRoot, basePath, name string, p// 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.-const ErrProjectDirExists = errors.Sentinel("project directory already exists")+var ErrProjectDirExists = errors.New("project directory already exists")// CreateExactDir creates basePath (the sanitized project directory) under// projectsRoot WITHOUT any "-N" collision suffixing. It returns ErrProjectDirExists@@ -368,7 +368,7 @@ func CreateExactDir(ctx context.Context, projectsRoot, basePath, name string, pelogicalPath, err := acfs.LogicalPath(projectsRoot, basePath)if err != nil {- return "", "", errors.WrapIf(err, "project directory would be outside allowed projects root")+ return "", "", fmt.Errorf("project directory would be outside allowed projects root: %w", err)}if err := acfs.Mkdir(ctx, projectsRoot, logicalPath, perm); err != nil {@@ -416,7 +416,7 @@ func IsSafeSubdirectory(baseDir, subdir string) bool {func ResolvePathWithinDir(baseDir, path string) (string, error) {resolvedBase, err := filepath.Abs(filepath.Clean(baseDir))if err != nil {- return "", errors.WrapIff(err, "failed to resolve base directory %q", baseDir)+ return "", fmt.Errorf("failed to resolve base directory %q: %w", baseDir, err)}resolvedPath := path@@ -425,10 +425,10 @@ func ResolvePathWithinDir(baseDir, path string) (string, error) {}resolvedPath, err = filepath.Abs(filepath.Clean(resolvedPath))if err != nil {- return "", errors.WrapIff(err, "failed to resolve path %q", path)+ return "", fmt.Errorf("failed to resolve path %q: %w", path, err)}if !IsSafeSubdirectory(resolvedBase, resolvedPath) {- return "", errors.Errorf("path %q escapes directory %q", path, baseDir)+ return "", fmt.Errorf("path %q escapes directory %q", path, baseDir)}return resolvedPath, nildiff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.goindex e40b42ca2..ac6c50a32 100644--- a/backend/pkg/projects/fs_writer.go+++ b/backend/pkg/projects/fs_writer.go@@ -2,6 +2,7 @@ package projectsimport ("context"+ "errors""fmt""io/fs""log/slog"@@ -12,7 +13,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/compose-spec/compose-go/v2/cli""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""go.getarcane.app/acfs"@@ -67,13 +67,13 @@ func detectExistingComposeFileInternal(ctx context.Context, projectsRoot, dir st// projectsRoot is the allowed root directory to prevent path traversal attacksfunc WriteComposeFile(ctx context.Context, projectsRoot, dirPath, content string) error {if _, err := acfs.LogicalPath(projectsRoot, dirPath); err != nil {- return errors.WrapIf(err, "refusing to write compose file: path outside projects root")+ return fmt.Errorf("refusing to write compose file: path outside projects root: %w", err)}// The project directory is the confinement root for the write itself, so it// has to exist before acfs can open it.if err := os.MkdirAll(dirPath, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create directory")+ return fmt.Errorf("failed to create directory: %w", err)}composeFileName := DefaultComposeFileName@@ -86,7 +86,7 @@ func WriteComposeFile(ctx context.Context, projectsRoot, dirPath, content string}if err := acfs.Write(ctx, dirPath, "/"+composeFileName, []byte(content), acfs.WriteOptions{Mode: mode, InPlace: true}); err != nil {- return errors.WrapIf(err, "failed to write compose file")+ return fmt.Errorf("failed to write compose file: %w", err)}return nil@@ -94,21 +94,21 @@ func WriteComposeFile(ctx context.Context, projectsRoot, dirPath, content stringfunc WriteProjectFile(ctx context.Context, projectsRoot, dirPath, fileName, content string) error {if _, err := acfs.LogicalPath(projectsRoot, dirPath); err != nil {- return errors.WrapIf(err, "refusing to write project file: path outside projects root")+ return fmt.Errorf("refusing to write project file: path outside projects root: %w", err)}if fileName == "" || filepath.Base(fileName) != fileName || strings.Contains(fileName, string(filepath.Separator)) {- return errors.Errorf("invalid project file name %q", fileName)+ return fmt.Errorf("invalid project file name %q", fileName)}if err := os.MkdirAll(dirPath, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create directory")+ return fmt.Errorf("failed to create directory: %w", err)}if fileName == EffectiveEnvFileName {written, err := writeEnvThroughSymlinkInternal(filepath.Join(dirPath, fileName), content)if err != nil {- return errors.WrapIff(err, "failed to write project file %s", fileName)+ return fmt.Errorf("failed to write project file %s: %w", fileName, err)}if written {return nil@@ -121,9 +121,9 @@ func WriteProjectFile(ctx context.Context, projectsRoot, dirPath, fileName, contcase statErr == nil && entry.IsSymlink:// Only .env is written through a symlink (handled above); every other// project file refuses one rather than clobbering an unknown target.- return errors.Errorf("refusing to write project file %s: destination is a symlink", fileName)+ return fmt.Errorf("refusing to write project file %s: destination is a symlink", fileName)case statErr != nil && !errors.Is(statErr, fs.ErrNotExist):- return errors.WrapIff(statErr, "failed to inspect project file %s", fileName)+ return fmt.Errorf("failed to inspect project file %s: %w", fileName, statErr)}mode := utils.FilePerm@@ -133,13 +133,13 @@ func WriteProjectFile(ctx context.Context, projectsRoot, dirPath, fileName, contreturn nil}if readErr != nil && !errors.Is(readErr, fs.ErrNotExist) {- return errors.WrapIff(readErr, "failed to read project file %s", fileName)+ return fmt.Errorf("failed to read project file %s: %w", fileName, readErr)}mode = os.FileMode(entry.UnixMode).Perm()}if err := acfs.Write(ctx, dirPath, logicalPath, []byte(content), acfs.WriteOptions{Mode: mode, InPlace: true}); err != nil {- return errors.WrapIff(err, "failed to write project file %s", fileName)+ return fmt.Errorf("failed to write project file %s: %w", fileName, err)}return nil@@ -155,7 +155,7 @@ func WriteProjectFile(ctx context.Context, projectsRoot, dirPath, fileName, contfunc writeEnvThroughSymlinkInternal(envPath, content string) (bool, error) {resolvedPath, resolvedPerm, isSymlink, err := resolveEnvFileWriteTargetInternal(envPath)if err != nil {- return false, errors.WrapIf(err, "resolve write target")+ return false, fmt.Errorf("resolve write target: %w", err)}if !isSymlink {return false, nil@@ -166,7 +166,7 @@ func writeEnvThroughSymlinkInternal(envPath, content string) (bool, error) {return true, nil}if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {- return true, errors.WrapIf(readErr, "read existing content")+ return true, fmt.Errorf("read existing content: %w", readErr)}return true, atomic.WriteFile(resolvedPath, []byte(content), resolvedPerm)}@@ -177,7 +177,7 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm oif errors.Is(err, os.ErrNotExist) {return envPath, utils.FilePerm, false, nil}- return "", 0, false, errors.WrapIf(err, "inspect env file")+ return "", 0, false, fmt.Errorf("inspect env file: %w", err)}if info.Mode()&os.ModeSymlink == 0 {return envPath, utils.FilePerm, false, nil@@ -185,14 +185,14 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm oresolvedPath, err := filepath.EvalSymlinks(envPath)if err != nil {- return "", 0, false, errors.WrapIf(err, "resolve env file symlink")+ return "", 0, false, fmt.Errorf("resolve env file symlink: %w", err)}targetInfo, err := os.Stat(resolvedPath)if err != nil {- return "", 0, false, errors.WrapIf(err, "inspect env file symlink target")+ return "", 0, false, fmt.Errorf("inspect env file symlink target: %w", err)}if !targetInfo.Mode().IsRegular() {- return "", 0, false, errors.Errorf("env file symlink target is not a regular file: %s", resolvedPath)+ return "", 0, false, fmt.Errorf("env file symlink target is not a regular file: %s", resolvedPath)}return resolvedPath, targetInfo.Mode().Perm(), true, nil@@ -200,15 +200,15 @@ func resolveEnvFileWriteTargetInternal(envPath string) (writePath string, perm ofunc RemoveProjectFile(ctx context.Context, projectsRoot, dirPath, fileName string) error {if _, err := acfs.LogicalPath(projectsRoot, dirPath); err != nil {- return errors.WrapIf(err, "refusing to remove project file: path outside projects root")+ return fmt.Errorf("refusing to remove project file: path outside projects root: %w", err)}if fileName == "" || filepath.Base(fileName) != fileName || strings.Contains(fileName, string(filepath.Separator)) {- return errors.Errorf("invalid project file name %q", fileName)+ return fmt.Errorf("invalid project file name %q", fileName)}if err := acfs.Remove(ctx, dirPath, "/"+fileName); err != nil && !errors.Is(err, fs.ErrNotExist) {- return errors.WrapIff(err, "failed to remove project file %s", fileName)+ return fmt.Errorf("failed to remove project file %s: %w", fileName, err)}return nil@@ -216,12 +216,12 @@ func RemoveProjectFile(ctx context.Context, projectsRoot, dirPath, fileName strifunc EnsureEnvFile(ctx context.Context, projectsRoot, dirPath string) error {if _, err := acfs.LogicalPath(projectsRoot, dirPath); err != nil {- return errors.WrapIf(err, "refusing to create env file: path outside projects root")+ return fmt.Errorf("refusing to create env file: path outside projects root: %w", err)}exists, err := acfs.Exists(ctx, dirPath, "/.env")if err != nil {- return errors.WrapIf(err, "failed to stat env file")+ return fmt.Errorf("failed to stat env file: %w", err)}if exists {return nil@@ -259,11 +259,11 @@ func WriteProjectFiles(ctx context.Context, projectsRoot, dirPath, composeContenfunc WriteTemplateFile(filePath, content string) error {dir := filepath.Dir(filePath)if err := os.MkdirAll(dir, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create template directory")+ return fmt.Errorf("failed to create template directory: %w", err)}if err := atomic.WriteFile(filePath, []byte(content), utils.FilePerm); err != nil {- return errors.WrapIf(err, "failed to write template file")+ return fmt.Errorf("failed to write template file: %w", err)}return nil@@ -273,11 +273,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, utils.DirPerm); err != nil {- return errors.WrapIf(err, "failed to create directory")+ return fmt.Errorf("failed to create directory: %w", err)}if err := atomic.WriteFile(filePath, []byte(content), perm); err != nil {- return errors.WrapIf(err, "failed to write file")+ return fmt.Errorf("failed to write file: %w", err)}return nil@@ -312,7 +312,7 @@ func RollbackRenamedProjectDirectory(ctx context.Context, oldPath, newPath strinrenameErr = os.Rename(newPath, oldPath)}if renameErr != nil {- return false, errors.WrapIf(renameErr, "rollback project directory rename")+ return false, fmt.Errorf("rollback project directory rename: %w", renameErr)}case !oldExists:pathsMissing = true@@ -328,16 +328,16 @@ func relocateRenameConflictDirectoryInternal(ctx context.Context, path string) (for attempt := range 10 {conflictName := fmt.Sprintf(".%s.rename-conflict-%d-%d", base, now, attempt)if exists, err := acfs.Exists(ctx, parent, "/"+conflictName); err != nil {- return "", errors.WrapIf(err, "check conflict path")+ return "", fmt.Errorf("check conflict path: %w", err)} else if exists {continue}if err := acfs.Rename(ctx, parent, "/"+base, "/"+conflictName); err != nil {- return "", errors.WrapIf(err, "relocate project rename target path")+ return "", fmt.Errorf("relocate project rename target path: %w", err)}return filepath.Join(parent, conflictName), nil}- return "", errors.Errorf("relocate project rename target path: no available conflict path for %s", path)+ return "", fmt.Errorf("relocate project rename target path: no available conflict path for %s", path)}// SyncFile represents a file to be written during directory sync@@ -354,13 +354,13 @@ type SyncFile struct {// subdirectories as needed. Returns the list of written file paths.func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string, files []SyncFile) ([]string, error) {if _, err := acfs.LogicalPath(projectsRoot, projectPath); err != nil {- return nil, errors.WrapIf(err, "project path is outside projects root")+ return nil, fmt.Errorf("project path is outside projects root: %w", err)}// The project directory is the confinement root for every write below, so// it has to exist before acfs can open it.if err := os.MkdirAll(projectPath, utils.DirPerm); err != nil {- return nil, errors.WrapIf(err, "failed to create project directory")+ return nil, fmt.Errorf("failed to create project directory: %w", err)}writtenPaths := make([]string, 0, len(files))@@ -368,28 +368,28 @@ func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string,for _, file := range files {logicalPath, err := acfs.LogicalPath(projectPath, filepath.Join(projectPath, file.RelativePath))if err != nil {- return nil, errors.Errorf("file path %s would escape project directory", file.RelativePath)+ return nil, fmt.Errorf("file path %s would escape project directory", file.RelativePath)}if err := acfs.MkdirAll(ctx, projectPath, path.Dir(logicalPath), utils.DirPerm); err != nil {- return nil, errors.WrapIff(err, "failed to create directory for %s", file.RelativePath)+ return nil, fmt.Errorf("failed to create directory for %s: %w", file.RelativePath, err)}entry, statErr := acfs.Stat(ctx, projectPath, logicalPath, false)switch {case statErr == nil && entry.IsDirectory:if err := acfs.RemoveAll(ctx, projectPath, logicalPath); err != nil {- return nil, errors.WrapIff(err, "failed to replace directory at %s", file.RelativePath)+ return nil, fmt.Errorf("failed to replace directory at %s: %w", file.RelativePath, err)}case statErr != nil && !errors.Is(statErr, fs.ErrNotExist):- return nil, errors.WrapIff(statErr, "failed to inspect target path for %s", file.RelativePath)+ return nil, fmt.Errorf("failed to inspect target path for %s: %w", file.RelativePath, statErr)}// Write the file. Honor the source's executable bit so scripts arrive// runnable for lifecycle hooks and similar consumers.perm := kit.Ternary(file.Executable, 0o755, utils.FilePerm)if err := acfs.Write(ctx, projectPath, logicalPath, file.Content, acfs.WriteOptions{Mode: perm, InPlace: true}); err != nil {- return nil, errors.WrapIff(err, "failed to write file %s", file.RelativePath)+ return nil, fmt.Errorf("failed to write file %s: %w", file.RelativePath, err)}writtenPaths = append(writtenPaths, file.RelativePath)@@ -404,7 +404,7 @@ func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string,// This is a best-effort operation - errors are logged but don't cause failure.func CleanupRemovedFiles(ctx context.Context, projectsRoot, projectPath string, oldFiles, newFiles []string) error {if _, err := acfs.LogicalPath(projectsRoot, projectPath); err != nil {- return errors.WrapIf(err, "project path is outside projects root")+ return fmt.Errorf("project path is outside projects root: %w", err)}// Build set of new files for quick lookupdiff --git a/backend/pkg/projects/includes.go b/backend/pkg/projects/includes.goindex 6b1e9c0df..90274ba61 100644--- a/backend/pkg/projects/includes.go+++ b/backend/pkg/projects/includes.go@@ -2,12 +2,13 @@ package projectsimport ("context"+ "errors"+ "fmt""os""path""path/filepath""strings"- "emperror.dev/errors""github.com/samber/mo""go.getarcane.app/acfs""go.yaml.in/yaml/v4"@@ -58,7 +59,7 @@ func (l *MissingIncludeStubLoader) Accept(path string) bool {func (l *MissingIncludeStubLoader) Load(ctx context.Context, filePath string) (string, error) {validatedPath, ok := l.resolveMissingIncludeInternal(filePath).Get()if !ok {- return "", errors.Errorf("include file is not eligible for validation stub: %s", filePath)+ return "", fmt.Errorf("include file is not eligible for validation stub: %s", filePath)}if l.stubs == nil {@@ -72,7 +73,7 @@ func (l *MissingIncludeStubLoader) Load(ctx context.Context, filePath string) (s// System temp scratch dir: no acfs root exists for it.tempDir, err := os.MkdirTemp("", "arcane-compose-include-*")if err != nil {- return "", errors.WrapIf(err, "create validation include temp dir")+ return "", fmt.Errorf("create validation include temp dir: %w", err)}l.tempDir = tempDir}@@ -84,13 +85,13 @@ func (l *MissingIncludeStubLoader) Load(ctx context.Context, filePath string) (sstubPath := filepath.Join(l.tempDir, relPath)stubLogical, err := acfs.LogicalPath(l.tempDir, stubPath)if err != nil {- return "", errors.WrapIf(err, "resolve validation include stub path")+ return "", fmt.Errorf("resolve validation include stub path: %w", err)}if err := acfs.MkdirAll(ctx, l.tempDir, path.Dir(stubLogical), 0o755); err != nil {- return "", errors.WrapIf(err, "create validation include directory")+ return "", fmt.Errorf("create validation include directory: %w", err)}if err := acfs.Write(ctx, l.tempDir, stubLogical, []byte("services: {}\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {- return "", errors.WrapIf(err, "write validation include stub")+ return "", fmt.Errorf("write validation include stub: %w", err)}l.stubs[validatedPath] = stubPath@@ -133,7 +134,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, errors.WrapIf(err, "failed to read compose file")+ return nil, fmt.Errorf("failed to read compose file: %w", err)}return ParseIncludesFromContent(composeFilePath, content, envMap, includeContent)@@ -143,7 +144,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, errors.WrapIf(err, "failed to parse compose file")+ return nil, fmt.Errorf("failed to parse compose file: %w", err)}// Look for include at root level only (per Docker Compose spec)@@ -218,13 +219,13 @@ func extractIncludePathsFromMapInternal(v map[string]any) ([]string, error) {for _, entry := range p {s, ok := entry.(string)if !ok {- return nil, errors.Errorf("invalid include path entry: expected string, got %T", entry)+ return nil, fmt.Errorf("invalid include path entry: expected string, got %T", entry)}paths = append(paths, s)}return paths, nildefault:- return nil, errors.Errorf("invalid include path type: %T", v["path"])+ return nil, fmt.Errorf("invalid include path type: %T", v["path"])}}@@ -281,7 +282,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 "", errors.WrapIff(err, "failed to read include file %s", includePath)+ return "", fmt.Errorf("failed to read include file %s: %w", includePath, err)}// ValidateIncludePathForWrite ensures the include path is safe for write operations@@ -295,7 +296,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 "", errors.WrapIf(err, "invalid project directory")+ return "", fmt.Errorf("invalid project directory: %w", err)}absProjectDir = filepath.Clean(absProjectDir)@@ -312,7 +313,7 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)absFullPath, err := filepath.Abs(fullPath)if err != nil {- return "", errors.WrapIf(err, "invalid include path")+ return "", fmt.Errorf("invalid include path: %w", err)}absFullPath = filepath.Clean(absFullPath)@@ -323,12 +324,12 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)case err == nil:evalPath = evalFullPathcase !errors.Is(err, os.ErrNotExist):- return "", errors.WrapIf(err, "failed to resolve include path")+ return "", fmt.Errorf("failed to resolve include path: %w", err)default:// File doesn't exist yet - evaluate parent directory symlinksevalDir, dirErr := filepath.EvalSymlinks(filepath.Dir(absFullPath))if dirErr != nil && !errors.Is(dirErr, os.ErrNotExist) {- return "", errors.WrapIf(dirErr, "failed to resolve parent directory")+ return "", fmt.Errorf("failed to resolve parent directory: %w", dirErr)}if dirErr == nil {evalPath = filepath.Join(evalDir, filepath.Base(absFullPath))diff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.goindex 67f9cd58e..f0b9a2311 100644--- a/backend/pkg/projects/load.go+++ b/backend/pkg/projects/load.go@@ -3,6 +3,8 @@ package projectsimport ("cmp""context"+ "errors"+ "fmt""log/slog""maps""math"@@ -13,8 +15,6 @@ 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"@@ -23,6 +23,7 @@ import ("github.com/docker/compose/v5/pkg/api""github.com/docker/go-units""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/samber/mo")@@ -149,20 +150,20 @@ func DetectComposeFile(ctx context.Context, projectsDir, dir string) (string, ercase len(dirMatchedCandidates) == 1:return dirMatchedCandidates[0], envErrcase len(dirMatchedCandidates) > 1:- return "", errors.Errorf("multiple custom compose files found in %q", dir)+ return "", fmt.Errorf("multiple custom compose files found in %q", dir)case len(composeNamedCandidates) == 1:return composeNamedCandidates[0], envErrcase len(composeNamedCandidates) > 1:- return "", errors.Errorf("multiple custom compose files found in %q", dir)+ return "", fmt.Errorf("multiple custom compose files found in %q", dir)case len(customCandidates) == 1:return customCandidates[0], envErrcase len(customCandidates) > 1:- return "", errors.Errorf("multiple custom compose files found in %q", dir)+ return "", fmt.Errorf("multiple custom compose files found in %q", dir)default:- return "", common.Classify(common.ErrComposeFileNotFound, errors.Errorf("no compose file found in %q", dir))+ return "", common.Classify(common.ErrComposeFileNotFound, fmt.Errorf("no compose file found in %q", dir))}}@@ -187,7 +188,7 @@ func LoadComposeProjectFromContent(ctx context.Context, opts projecttypes.Composif strings.TrimSpace(opts.EnvContent) != "" {parsedEnv, parseErr := ParseProjectEnvContent(opts.EnvContent, envMap)if parseErr != nil {- return nil, errors.WrapIf(parseErr, "failed to parse env content")+ return nil, fmt.Errorf("failed to parse env content: %w", parseErr)}maps.Copy(envMap, parsedEnv)}@@ -214,7 +215,7 @@ func LoadComposeProjectFromContent(ctx context.Context, opts projecttypes.Composproject, err = loader.LoadWithContext(ctx, configDetails, loaderOptions...)if err != nil {- return nil, errors.WrapIf(err, "failed to load compose project")+ return nil, fmt.Errorf("failed to load compose project: %w", err)}var rawSources map[string]string@@ -276,7 +277,7 @@ func lenientCastSizeInternal(value string) (any, error) {n = b}if n > math.MaxInt || n < math.MinInt {- return nil, errors.Errorf("size %d out of range for platform int", n)+ return nil, fmt.Errorf("size %d out of range for platform int", n)}return int(n), nil}@@ -454,7 +455,7 @@ func LoadComposeProject(project, err = loader.LoadWithContext(ctx, cfg, loaderOptions...)if err != nil {- return nil, errors.WrapIf(err, "load compose project")+ return nil, fmt.Errorf("load compose project: %w", err)}recordComposeDependenciesInternal(project, dependencies)@@ -488,13 +489,13 @@ func finishLoadedProjectInternal(ctx context.Context, project *composetypes.Proj// them for the Docker daemon and they would no longer be usable locally.if prepare != nil {if err := prepare(ctx, project); err != nil {- return nil, errors.WrapIf(err, "prepare compose project")+ return nil, fmt.Errorf("prepare compose project: %w", err)}}if !isNilVolumeSourcePathMapperInternal(pathMapper) {if err := pathMapper.TranslateVolumeSources(project, translateFileResources); err != nil {- return nil, errors.WrapIf(err, "failed to translate paths for docker host")+ return nil, fmt.Errorf("failed to translate paths for docker host: %w", err)}RemapEscapedRelativeSources(ctx, pathMapper, project, workingDir, rawSources, translateFileResources)}@@ -515,7 +516,7 @@ func finishLoadedProjectInternal(ctx context.Context, project *composetypes.Proj// reasons this cannot be fatal.func harvestRawSourcesInternal(ctx context.Context, cfg composetypes.ConfigDetails, loaderOptions ...func(*loader.Options)) (rawSources map[string]string) {defer func() {- if panicErr := emperror.Recover(recover()); panicErr != nil {+ if panicErr := utils.PanicToError(recover()); panicErr != nil {slog.DebugContext(ctx, "panic while harvesting raw compose paths", "error", panicErr)rawSources = nil}@@ -570,13 +571,13 @@ func isNilVolumeSourcePathMapperInternal(pathMapper projecttypes.VolumeSourcePat}func recoverComposeLoadPanicInternal(ctx context.Context, source string, project **composetypes.Project, err *error) {- if panicErr := emperror.Recover(recover()); panicErr != nil {+ if panicErr := utils.PanicToError(recover()); panicErr != nil {slog.WarnContext(ctx,"panic while loading compose project; compose file may contain invalid syntax","path", source,"error", panicErr,)- *err = errors.WrapIff(panicErr, "load compose project panic for %s", source)+ *err = fmt.Errorf("load compose project panic for %s: %w", source, panicErr)*project = nil}}@@ -685,8 +686,8 @@ func recordComposeDependenciesInternal(project *composetypes.Project, dependenci// Missing includes are tolerated here; deployment uses strict executable loading.func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, projectPath, projectName, composeContent string, effectiveEnvContent, overrideContent *string, overrideFileName string, lenient bool) (err error) {defer func() {- if panicErr := emperror.Recover(recover()); panicErr != nil {- err = errors.WrapIf(panicErr, "compose file contains invalid syntax")+ if panicErr := utils.PanicToError(recover()); panicErr != nil {+ err = fmt.Errorf("compose file contains invalid syntax: %w", panicErr)}}()diff --git a/backend/pkg/projects/logs_demux_test.go b/backend/pkg/projects/logs_demux_test.goindex 189388fbc..07bb66198 100644--- a/backend/pkg/projects/logs_demux_test.go+++ b/backend/pkg/projects/logs_demux_test.go@@ -44,14 +44,10 @@ func TestDemultiplexedLogStreamWithStderrMarking(t *testing.T) {resp := io.NopCloser(bytes.NewReader(source))stream := &stderrMarkedDemuxedStreamInternal{upstream: resp, src: bufio.NewReader(resp)}- require.Equal(t,- "line-one\n"+- "[STDERR] boom\n"+- "partial\n"+- "[STDERR] "+longRun[:maxLogEntryBytesInternal]+"\n"+- "[STDERR] "+longRun[maxLogEntryBytesInternal:]+"\n"+- "[STDERR] final\n",- decodeDemuxedStreamInternal(t, stream))+ require.Equal(t, "line-one\n[STDERR] boom\npartial\n[STDERR] "++ longRun[:maxLogEntryBytesInternal]+"\n"++ "[STDERR] "+longRun[maxLogEntryBytesInternal:]+"\n"++ "[STDERR] final\n", decodeDemuxedStreamInternal(t, stream))}type fakeResponseBodyInternal struct {diff --git a/backend/pkg/projects/path_mapper.go b/backend/pkg/projects/path_mapper.goindex d79b72881..d149004e2 100644--- a/backend/pkg/projects/path_mapper.go+++ b/backend/pkg/projects/path_mapper.go@@ -3,12 +3,12 @@ package projectsimport ("cmp""context"+ "fmt""log/slog""path""path/filepath""strings"- "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"@@ -184,7 +184,7 @@ func (pm *PathMapper) ContainerToHost(containerPath string) (string, bool, error// Calculate relative pathrelPath, err := filepath.Rel(pm.containerPrefix, cleaned)if err != nil {- return "", false, errors.WrapIf(err, "failed to calculate relative path")+ return "", false, fmt.Errorf("failed to calculate relative path: %w", err)}// Only translate paths within container prefix@@ -225,7 +225,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project, tranhostPath, _, err := pm.ContainerToHost(volume.Source)if err != nil {- return errors.WrapIff(err, "failed to translate volume source %q", volume.Source)+ return fmt.Errorf("failed to translate volume source %q: %w", volume.Source, err)}volume.Source = hostPath@@ -243,7 +243,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project, tranif secret.File != "" {hostPath, _, err := pm.ContainerToHost(secret.File)if err != nil {- return errors.WrapIff(err, "failed to translate secret file %q", secret.File)+ return fmt.Errorf("failed to translate secret file %q: %w", secret.File, err)}secret.File = hostPathproject.Secrets[name] = secret@@ -255,7 +255,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project, tranif config.File != "" {hostPath, _, err := pm.ContainerToHost(config.File)if err != nil {- return errors.WrapIff(err, "failed to translate config file %q", config.File)+ return fmt.Errorf("failed to translate config file %q: %w", config.File, err)}config.File = hostPathproject.Configs[name] = config@@ -275,7 +275,7 @@ func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project, tranhostPath, _, err := pm.ContainerToHost(device)if err != nil {- return errors.WrapIff(err, "failed to translate volume device %q", device)+ return fmt.Errorf("failed to translate volume device %q: %w", device, err)}volume.DriverOpts["device"] = hostPathproject.Volumes[name] = volumediff --git a/backend/pkg/projects/volume_migration.go b/backend/pkg/projects/volume_migration.goindex c33d686f1..1024c605d 100644--- a/backend/pkg/projects/volume_migration.go+++ b/backend/pkg/projects/volume_migration.go@@ -2,13 +2,13 @@ package projectsimport ("context"- stderrors "errors"+ "errors"+ "fmt""log/slog""maps""os""strings"- "emperror.dev/errors"composetemplate "github.com/compose-spec/compose-go/v2/template"composetypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs"@@ -35,7 +35,7 @@ func PlanVolumeMigration(ctx context.Context, dockerClient *client.Client, compoexplicitVolumeNames, err := composeVolumeKeysWithExplicitNameInternal(composeProject.ComposeFiles)if err != nil {- return nil, errors.WrapIf(err, "failed to parse compose volume names")+ return nil, fmt.Errorf("failed to parse compose volume names: %w", err)}entries, err := collectProjectRenameVolumeEntriesInternal(ctx, dockerClient, composeProject.Volumes, explicitVolumeNames, oldComposeName, newComposeName)@@ -84,7 +84,7 @@ func inspectProjectRenameVolumeEntryInternal(ctx context.Context, dockerClient *if cerrdefs.IsNotFound(err) {return volumetypes.RenameEntry{}, false, nil}- return volumetypes.RenameEntry{}, false, errors.WrapIff(err, "inspect source volume %s", oldName)+ return volumetypes.RenameEntry{}, false, fmt.Errorf("inspect source volume %s: %w", oldName, err)}if err := volumes.EnsureRenameSourceDetached(ctx, dockerClient, oldName); err != nil {return volumetypes.RenameEntry{}, false, err@@ -122,7 +122,7 @@ func renamedVolumeCreateOptionsInternal(config composetypes.VolumeConfig, oldLabmaps.Copy(labels, config.CustomLabels)hash, err := composepkg.VolumeHash(config)if err != nil {- return client.VolumeCreateOptions{}, errors.WrapIff(err, "hash target volume %s", config.Name)+ return client.VolumeCreateOptions{}, fmt.Errorf("hash target volume %s: %w", config.Name, err)}labels[api.ConfigHashLabel] = hashreturn client.VolumeCreateOptions{Name: config.Name, Driver: config.Driver, DriverOpts: config.DriverOpts, Labels: labels}, nil@@ -151,12 +151,12 @@ func composeVolumeKeysWithExplicitNameInFileInternal(path string) (map[string]st// directory (e.g. via include), so no single confinement root covers them.content, err := os.ReadFile(path)if err != nil {- return nil, errors.WrapIf(err, "read compose file")+ return nil, fmt.Errorf("read compose file: %w", err)}composeData := map[string]any{}if err := yaml.Unmarshal(content, &composeData); err != nil {- return nil, errors.WrapIf(err, "parse compose file")+ return nil, fmt.Errorf("parse compose file: %w", err)}rawVolumes, ok := composeData["volumes"]@@ -197,7 +197,7 @@ func ApplyRenameVolumeMigration(ctx context.Context, operations projecttypes.Renreturn nil}if err := volumeMigration.Apply(ctx); err != nil {- return errors.WrapIf(err, "failed to rename project volumes")+ return fmt.Errorf("failed to rename project volumes: %w", err)}*applied = truereturn operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseTargetsCopied)@@ -213,8 +213,7 @@ func FinalizeRenameAfterCommit(ctx context.Context, operations projecttypes.Renaif committer, ok := volumeMigration.(volumetypes.Committer); ok {if err := committer.Commit(ctx); err != nil {slog.WarnContext(ctx, "failed to clean up project source volumes after committed rename", "projectID", projectID, "error", err)- var cleanupErr *volumetypes.SourceCleanupError- if errors.As(err, &cleanupErr) {+ if _, ok := errors.AsType[*volumetypes.SourceCleanupError](err); ok {if writeErr := operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseSourceCleanupPending); writeErr != nil {slog.WarnContext(ctx, "failed to mark project rename source cleanup pending", "projectID", projectID, "error", writeErr)}@@ -268,13 +267,11 @@ func cleanupRenameJournalSourcesInternal(ctx context.Context, operations project}if err := volumes.EnsureTargetsReadyForCleanup(ctx, dockerClient, journal.Volumes); err != nil {- var missingWithSource *volumetypes.TargetMissingWithSourceError- if errors.As(err, &missingWithSource) {+ if missingWithSource, ok := errors.AsType[*volumetypes.TargetMissingWithSourceError](err); ok {slog.WarnContext(ctx, "rolling back project rename because target volume is missing and source volume remains", "projectID", journal.ProjectID, "sourceVolume", missingWithSource.SourceVolume, "targetVolume", missingWithSource.TargetVolume)return rollbackRenameJournalInternal(ctx, operations, journal)}- var externallyRemoved *volumetypes.VolumesExternallyRemovedError- if errors.As(err, &externallyRemoved) {+ if externallyRemoved, ok := errors.AsType[*volumetypes.VolumesExternallyRemovedError](err); ok {slog.WarnContext(ctx, "project rename cleanup found source and target volumes externally removed", "projectID", journal.ProjectID, "volumeCount", len(externallyRemoved.Volumes), "error", externallyRemoved)} else {return err@@ -290,7 +287,7 @@ func rollbackRenameJournalInternal(ctx context.Context, operations projecttypes.volumeErr := rollbackRenameJournalVolumesInternal(ctx, operations, journal)if err := operations.RestoreState(ctx, journal); err != nil {- return stderrors.Join(directoryErr, volumeErr, errors.WrapIf(err, "restore project database state"))+ return errors.Join(directoryErr, volumeErr, fmt.Errorf("restore project database state: %w", err))}if directoryErr != nil {@@ -302,7 +299,7 @@ func rollbackRenameJournalInternal(ctx context.Context, operations projecttypes.slog.WarnContext(ctx, "clearing project rename journal after preserving target volume data", "projectID", journal.ProjectID, "pathsMissing", pathsMissing, "error", volumeErr)} else {if cleanupErr := operations.WriteRollbackCleanup(ctx, journal); cleanupErr != nil {- return stderrors.Join(directoryErr, volumeErr, cleanupErr)+ return errors.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)}@@ -333,10 +330,9 @@ func RecoverRenameJournal(ctx context.Context, journal *projecttypes.RenameJournreturn operations.ClearJournal(ctx, journal.ProjectID)}if err := cleanupRenameJournalSourcesInternal(ctx, operations, journal); err != nil {- var cleanupErr *volumetypes.SourceCleanupError- if errors.As(err, &cleanupErr) {+ if _, ok := errors.AsType[*volumetypes.SourceCleanupError](err); ok {if writeErr := operations.WriteJournal(ctx, journal, projecttypes.RenameJournalPhaseSourceCleanupPending); writeErr != nil {- return stderrors.Join(err, writeErr)+ return errors.Join(err, writeErr)}}return errdiff --git a/backend/pkg/projects/workspace.go b/backend/pkg/projects/workspace.goindex f98446f0e..e5da1e696 100644--- a/backend/pkg/projects/workspace.go+++ b/backend/pkg/projects/workspace.go@@ -4,6 +4,8 @@ import ("bytes""crypto/sha256""encoding/hex"+ "errors"+ "fmt""hash""io""io/fs"@@ -14,7 +16,6 @@ import ("slices""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"@@ -25,11 +26,13 @@ import (const (ProjectWorkspaceUseScanDepth = -1+)- ErrProjectWorkspaceRevisionConflict = errors.Sentinel("project workspace changed; refresh it and try again")- ErrProjectWorkspaceOutsideProjectDirectory = errors.Sentinel("path is outside project directory")- ErrProjectWorkspaceProtectedPath = errors.Sentinel("protected project configuration cannot be modified through the workspace")- ErrProjectWorkspaceSymlinkPath = errors.Sentinel("symlink workspace paths are not supported")+var (+ ErrProjectWorkspaceRevisionConflict = errors.New("project workspace changed; refresh it and try again")+ ErrProjectWorkspaceOutsideProjectDirectory = errors.New("path is outside project directory")+ ErrProjectWorkspaceProtectedPath = errors.New("protected project configuration cannot be modified through the workspace")+ ErrProjectWorkspaceSymlinkPath = errors.New("symlink workspace paths are not supported"))type ProjectWorkspaceApplyOptions struct {@@ -54,7 +57,7 @@ func ReadProjectWorkspace(projectPath string, maxDepth int, skipDirectories, comprojectAbs, err := filepath.Abs(projectPath)if err != nil {- return nil, "", false, errors.WrapIf(err, "resolve project path")+ return nil, "", false, fmt.Errorf("resolve project path: %w", err)}projectAbs = filepath.Clean(projectAbs)@@ -64,7 +67,7 @@ func ReadProjectWorkspace(projectPath string, maxDepth int, skipDirectories, com// and mass-invalidate open editor drafts with false 409s.root, err := os.OpenRoot(projectAbs)if err != nil {- return nil, "", false, errors.WrapIf(err, "open project directory")+ return nil, "", false, fmt.Errorf("open project directory: %w", err)}defer func() { _ = root.Close() }()@@ -245,7 +248,7 @@ func ApplyProjectWorkspaceChanges(projectPath string, changes []project.Workspacif opts.ExpectedRevision != "" {_, currentRevision, _, err := ReadProjectWorkspace(projectPath, opts.MaxDepth, opts.SkipDirectories, opts.ComposeFileName, opts.MaxEntries, opts.MaxFileSizeBytes)if err != nil {- return errors.WrapIf(err, "read project workspace revision")+ return fmt.Errorf("read project workspace revision: %w", err)}if currentRevision != opts.ExpectedRevision {return ErrProjectWorkspaceRevisionConflict@@ -254,7 +257,7 @@ func ApplyProjectWorkspaceChanges(projectPath string, changes []project.Workspacroot, err := os.OpenRoot(projectPath)if err != nil {- return errors.WrapIf(err, "open project directory")+ return fmt.Errorf("open project directory: %w", err)}defer func() { _ = root.Close() }()@@ -304,7 +307,7 @@ func ProtectedProjectFilePaths(composeFileName string) map[string]bool {func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool, change project.WorkspaceFileChange, uploads map[int][]byte, maxFileSizeBytes int64) error {rel, err := kit.NormalizeRelativePath(change.RelativePath)if err != nil {- return errors.WrapIf(err, "invalid project workspace path")+ return fmt.Errorf("invalid project workspace path: %w", err)}switch change.Operation {@@ -321,7 +324,7 @@ func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool,case project.FileOpRename:newName, err := kit.ValidateFileName(change.NewName)if err != nil {- return errors.WrapIf(err, "invalid project workspace file name")+ return fmt.Errorf("invalid project workspace file name: %w", err)}return renameProjectWorkspacePathInternal(root, protected, rel, newName)case project.FileOpMove:@@ -329,7 +332,7 @@ func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool,case project.FileOpDelete:return deleteProjectWorkspacePathInternal(root, protected, rel, change.Recursive)default:- return errors.Errorf("unsupported project workspace operation %q", change.Operation)+ return fmt.Errorf("unsupported project workspace operation %q", change.Operation)}}@@ -345,7 +348,7 @@ func createProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool}if err := root.MkdirAll(path.Dir(rel), utils.DirPerm); err != nil {- return errors.WrapIf(err, "create parent directory")+ return fmt.Errorf("create parent directory: %w", err)}// O_EXCL makes the exists-check-and-create atomic; os.Root confines the@@ -353,16 +356,16 @@ func createProjectWorkspaceFileInternal(root *os.Root, protected map[string]boolf, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, utils.FilePerm)if err != nil {if errors.Is(err, os.ErrExist) {- return errors.Errorf("project workspace file already exists: %s", rel)+ return fmt.Errorf("project workspace file already exists: %s", rel)}- return errors.WrapIf(err, "create project workspace file")+ return fmt.Errorf("create project workspace file: %w", err)}_, writeErr := f.Write(content)if closeErr := f.Close(); writeErr == nil {writeErr = closeErr}if writeErr != nil {- return errors.WrapIf(writeErr, "create project workspace file")+ return fmt.Errorf("create project workspace file: %w", writeErr)}return nil}@@ -376,12 +379,12 @@ func createProjectWorkspaceFolderInternal(root *os.Root, protected map[string]bo}if _, err := root.Lstat(rel); err == nil {- return errors.Errorf("project workspace folder already exists: %s", rel)+ return fmt.Errorf("project workspace folder already exists: %s", rel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project workspace folder")+ return fmt.Errorf("inspect project workspace folder: %w", err)}if err := root.MkdirAll(rel, utils.DirPerm); err != nil {- return errors.WrapIf(err, "create project workspace folder")+ return fmt.Errorf("create project workspace folder: %w", err)}return nil}@@ -400,15 +403,15 @@ func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]boolinfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project workspace file not found: %s", rel)+ return fmt.Errorf("project workspace file not found: %s", rel)}- return errors.WrapIf(err, "inspect project workspace file")+ return fmt.Errorf("inspect project workspace file: %w", err)}if info.IsDir() {- return errors.Errorf("path is a folder: %s", rel)+ return fmt.Errorf("path is a folder: %s", rel)}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink files are not supported")+ return fmt.Errorf("symlink files are not supported: %w", ErrProjectWorkspaceSymlinkPath)}// The workspace revision is structural only, so an external edit to this@@ -421,15 +424,15 @@ func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]boolif baselineSet {current, err := readProjectWorkspaceFileLimitedInternal(root, rel, int64(len(baseline))+1)if err != nil {- return errors.WrapIf(err, "read project workspace file")+ return fmt.Errorf("read project workspace file: %w", err)}if !bytes.Equal(current, baseline) {- return errors.WrapIf(ErrProjectWorkspaceRevisionConflict, "file content changed since it was loaded")+ return fmt.Errorf("file content changed since it was loaded: %w", ErrProjectWorkspaceRevisionConflict)}}if err := root.WriteFile(rel, content, utils.FilePerm); err != nil {- return errors.WrapIf(err, "update project workspace file")+ return fmt.Errorf("update project workspace file: %w", err)}return nil}@@ -454,12 +457,12 @@ func renameProjectWorkspacePathInternal(root *os.Root, protected map[string]boolinfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project workspace path not found: %s", rel)+ return fmt.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectWorkspaceSymlinkPath)}targetRel := path.Join(path.Dir(rel), newName)@@ -470,13 +473,13 @@ func renameProjectWorkspacePathInternal(root *os.Root, protected map[string]boolreturn err}if _, err := root.Lstat(targetRel); err == nil {- return errors.Errorf("project workspace path already exists: %s", targetRel)+ return fmt.Errorf("project workspace path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if err := root.Rename(rel, targetRel); err != nil {- return errors.WrapIf(err, "rename project workspace path")+ return fmt.Errorf("rename project workspace path: %w", err)}return nil}@@ -498,7 +501,7 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,parentRel, err := normalizeOptionalProjectParentPathInternal(newParentPath)if err != nil {- return errors.WrapIf(err, "invalid project workspace parent path")+ return fmt.Errorf("invalid project workspace parent path: %w", err)}if parentRel != "" {if err := ensureWritableProjectRelPathInternal(protected, parentRel); err != nil {@@ -509,12 +512,12 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,sourceInfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project workspace path not found: %s", rel)+ return fmt.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if sourceInfo.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectWorkspaceSymlinkPath)}if sourceInfo.IsDir() && parentRel != "" && kit.FilePathMatches(parentRel, rel) {return errors.New("folder cannot be moved into itself or a descendant")@@ -538,13 +541,13 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,return err}if _, err := root.Lstat(targetRel); err == nil {- return errors.Errorf("project workspace path already exists: %s", targetRel)+ return fmt.Errorf("project workspace path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if err := root.Rename(rel, targetRel); err != nil {- return errors.WrapIf(err, "move project workspace path")+ return fmt.Errorf("move project workspace path: %w", err)}return nil}@@ -560,15 +563,15 @@ func validateProjectMoveParentInternal(root *os.Root, parentRel string) error {parentInfo, err := root.Lstat(parentRel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("destination folder not found: %s", parentRel)+ return fmt.Errorf("destination folder not found: %s", parentRel)}- return errors.WrapIf(err, "inspect destination folder")+ return fmt.Errorf("inspect destination folder: %w", err)}if parentInfo.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink destination folders are not supported")+ return fmt.Errorf("symlink destination folders are not supported: %w", ErrProjectWorkspaceSymlinkPath)}if !parentInfo.IsDir() {- return errors.Errorf("destination path is not a folder: %s", parentRel)+ return fmt.Errorf("destination path is not a folder: %s", parentRel)}return nil}@@ -584,12 +587,12 @@ func deleteProjectWorkspacePathInternal(root *os.Root, protected map[string]boolinfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project workspace path not found: %s", rel)+ return fmt.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectWorkspaceSymlinkPath)}if info.IsDir() && !recursive {empty, err := isDirectoryEmptyInternal(root, rel)@@ -603,12 +606,12 @@ func deleteProjectWorkspacePathInternal(root *os.Root, protected map[string]boolif info.IsDir() {if err := root.RemoveAll(rel); err != nil {- return errors.WrapIf(err, "delete project workspace folder")+ return fmt.Errorf("delete project workspace folder: %w", err)}return nil}if err := root.Remove(rel); err != nil {- return errors.WrapIf(err, "delete project workspace file")+ return fmt.Errorf("delete project workspace file: %w", err)}return nil}@@ -632,10 +635,10 @@ func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {if errors.Is(err, os.ErrNotExist) {return nil}- return errors.WrapIf(err, "inspect project workspace path")+ return fmt.Errorf("inspect project workspace path: %w", err)}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectWorkspaceSymlinkPath)}}return nil@@ -647,7 +650,7 @@ func ensureWritableProjectRelPathInternal(protected map[string]bool, rel string)}rootName, _, _ := strings.Cut(rel, "/")if protected[rel] || protected[rootName] {- return errors.WrapIff(ErrProjectWorkspaceProtectedPath, "%s", rel)+ return fmt.Errorf("%s: %w", rel, ErrProjectWorkspaceProtectedPath)}return nil}@@ -655,7 +658,7 @@ func ensureWritableProjectRelPathInternal(protected map[string]bool, rel string)func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {f, err := root.Open(rel)if err != nil {- return false, errors.WrapIf(err, "open folder")+ return false, fmt.Errorf("open folder: %w", err)}defer func() { _ = f.Close() }()@@ -664,7 +667,7 @@ func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {return true, nil}if err != nil {- return false, errors.WrapIf(err, "read folder")+ return false, fmt.Errorf("read folder: %w", err)}return false, nil}diff --git a/backend/pkg/remenv/client.go b/backend/pkg/remenv/client.goindex 417c9ad16..c996e9d1c 100644--- a/backend/pkg/remenv/client.go+++ b/backend/pkg/remenv/client.go@@ -3,6 +3,7 @@ package remenvimport ("bytes""context"+ "errors""fmt""io""maps"@@ -10,18 +11,17 @@ import ("net/http""strings""time"-- "emperror.dev/errors")const (- ErrEnvironmentUnavailable = errors.Sentinel("edge agent is not connected")- HeaderAPIKey = "X-Api-Key" // #nosec G101: header name, not a credential- HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential- HeaderAuthorization = "Authorization"- bearerScheme = "Bearer "+ HeaderAPIKey = "X-Api-Key" // #nosec G101: header name, not a credential+ HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential+ HeaderAuthorization = "Authorization"+ bearerScheme = "Bearer ")+var ErrEnvironmentUnavailable = errors.New("edge agent is not connected")+// ExtractBearerToken returns the token portion of an "Authorization: Bearer <token>"// header value. It is case-insensitive on the scheme and trims surrounding whitespace.// Returns an empty string if the header is empty or does not use the Bearer scheme.@@ -136,7 +136,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: errors.WrapIf(err, "failed to create request")}+ return nil, &TransportError{Err: fmt.Errorf("failed to create request: %w", err)}}for key, value := range req.Headers {@@ -151,7 +151,7 @@ func (c *Client) doDirectHTTPInternal(ctx context.Context, req Request) (*ResponrespBody, err := io.ReadAll(resp.Body)if err != nil {- return nil, &TransportError{Err: errors.WrapIf(err, "failed to read response body")}+ return nil, &TransportError{Err: fmt.Errorf("failed to read response body: %w", err)}}return &Response{diff --git a/backend/pkg/scheduler/analytics_job.go b/backend/pkg/scheduler/analytics_job.goindex 90a412d32..9ad79a7b4 100644--- a/backend/pkg/scheduler/analytics_job.go+++ b/backend/pkg/scheduler/analytics_job.go@@ -4,6 +4,8 @@ import ("bytes""context""encoding/json/v2"+ "errors"+ "fmt""io""log/slog""net/http"@@ -11,7 +13,6 @@ 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/kv"@@ -129,13 +130,13 @@ func (j *AnalyticsJob) Run(ctx context.Context) (schedulertypes.Outcome, error)req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, j.heartbeatURL, bytes.NewReader(body))if err != nil {- return struct{}{}, errors.WrapIf(err, "failed to create request")+ return struct{}{}, fmt.Errorf("failed to create request: %w", err)}req.Header.Set("Content-Type", "application/json")resp, err := j.httpClient.Do(req)if err != nil {- return struct{}{}, errors.WrapIf(err, "failed to send request")+ return struct{}{}, fmt.Errorf("failed to send request: %w", err)}defer func() { _ = resp.Body.Close() }()@@ -156,7 +157,7 @@ func (j *AnalyticsJob) Run(ctx context.Context) (schedulertypes.Outcome, error)if bodyText != "" {details = append(details, "response="+bodyText)}- return struct{}{}, errors.Errorf("analytics heartbeat request failed: %s", strings.Join(details, "; "))+ return struct{}{}, fmt.Errorf("analytics heartbeat request failed: %s", strings.Join(details, "; "))}return struct{}{}, nil},@@ -203,7 +204,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, errors.WrapIf(err, "failed to load analytics heartbeat attempt state")+ return false, fmt.Errorf("failed to load analytics heartbeat attempt state: %w", err)}if ok {@@ -241,7 +242,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, errors.WrapIf(err, "failed to persist analytics heartbeat attempt state")+ return false, fmt.Errorf("failed to persist analytics heartbeat attempt state: %w", err)}return true, nildiff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.goindex 21c757345..88bdcd052 100644--- a/backend/pkg/scheduler/auto_heal_job.go+++ b/backend/pkg/scheduler/auto_heal_job.go@@ -4,13 +4,13 @@ import ("cmp""context""encoding/json/v2"+ "errors""log/slog""slices""strings""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"diff --git a/backend/pkg/scheduler/auto_patch_job.go b/backend/pkg/scheduler/auto_patch_job.goindex 8aeef400f..3fb556070 100644--- a/backend/pkg/scheduler/auto_patch_job.go+++ b/backend/pkg/scheduler/auto_patch_job.go@@ -3,9 +3,9 @@ package schedulerimport ("cmp""context"+ "errors""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/imagepatch""github.com/getarcaneapp/arcane/backend/v2/internal/settings"diff --git a/backend/pkg/scheduler/auto_update_job.go b/backend/pkg/scheduler/auto_update_job.goindex 8a7923895..dbff8a6aa 100644--- a/backend/pkg/scheduler/auto_update_job.go+++ b/backend/pkg/scheduler/auto_update_job.go@@ -3,10 +3,10 @@ package schedulerimport ("cmp""context"+ "errors""log/slog""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/updater""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"@@ -212,8 +212,7 @@ func autoUpdateOutcomeInternal(ctx context.Context, result *updatertypes.Result,outcome.Status = schedulertypes.NeedsAttentionoutcome.Message = "Unconfirmed targets remain; review this run's results"}- var outcomeErr *schedulertypes.OutcomeError- if errors.As(err, &outcomeErr) {+ if outcomeErr, ok := errors.AsType[*schedulertypes.OutcomeError](err); ok {outcome.Status = outcomeErr.Outcome.Statusoutcome.Message = outcomeErr.Outcome.Messageoutcome.Targets = nildiff --git a/backend/pkg/scheduler/entityjobs/entityjobs.go b/backend/pkg/scheduler/entityjobs/entityjobs.goindex 0e9604f26..cc7a9a9ea 100644--- a/backend/pkg/scheduler/entityjobs/entityjobs.go+++ b/backend/pkg/scheduler/entityjobs/entityjobs.go@@ -6,9 +6,9 @@ package entityjobsimport ("context"+ "fmt""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")@@ -42,7 +42,7 @@ func New(jobPrefix, admissionScope string) *Registry {// so they outlive the request or bootstrap goroutine that registered them.func (r *Registry) SetScheduler(ctx context.Context, scheduler schedulertypes.DynamicScheduler, admissionGate *runs.Admission) error { //nolint:contextcheck // scheduled runs must capture the app lifecycle context, not request contextsif scheduler == nil || admissionGate == nil {- return errors.Errorf("%s scheduler dependencies unavailable", r.admissionScope)+ return fmt.Errorf("%s scheduler dependencies unavailable", r.admissionScope)}if ctx == nil {ctx = context.Background()diff --git a/backend/pkg/scheduler/filesystem_watcher_job.go b/backend/pkg/scheduler/filesystem_watcher_job.goindex b684ee99b..aa7672c5b 100644--- a/backend/pkg/scheduler/filesystem_watcher_job.go+++ b/backend/pkg/scheduler/filesystem_watcher_job.go@@ -2,12 +2,12 @@ package schedulerimport ("context"+ "errors""log/slog""runtime""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/template"@@ -54,7 +54,7 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {j.projectsWatcher = nilj.mu.Unlock()if watcher != nil {- return errors.Combine(err, watcher.Stop())+ return errors.Join(err, watcher.Stop())}return err}@@ -75,10 +75,10 @@ func (j *FilesystemWatcherJob) Stop(ctx context.Context) error {err = projectsWatcher.Stop()}if templatesWatcher != nil {- err = errors.Combine(err, templatesWatcher.Stop())+ err = errors.Join(err, templatesWatcher.Stop())}for _, watcher := range retired {- err = errors.Combine(err, watcher.Stop())+ err = errors.Join(err, watcher.Stop())}return err}diff --git a/backend/pkg/scheduler/image_update_watcher.go b/backend/pkg/scheduler/image_update_watcher.goindex 8edfd3b0a..ce920f22d 100644--- a/backend/pkg/scheduler/image_update_watcher.go+++ b/backend/pkg/scheduler/image_update_watcher.go@@ -2,12 +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/docker"@@ -378,7 +379,7 @@ func (w *ImageUpdateWatcher) executeScanInternal(ctx context.Context) error {results, err := w.imageUpdateService.CheckAllImages(ctx, 0, creds)if err != nil {- return errors.WrapIf(err, "image scan failed")+ return fmt.Errorf("image scan failed: %w", err)}updates := 0diff --git a/backend/pkg/scheduler/image_update_watcher_test.go b/backend/pkg/scheduler/image_update_watcher_test.goindex c714a630f..c5d8dc028 100644--- a/backend/pkg/scheduler/image_update_watcher_test.go+++ b/backend/pkg/scheduler/image_update_watcher_test.go@@ -3,6 +3,7 @@ package schedulerimport ("bytes""context"+ "errors""fmt""log/slog""sync"@@ -10,7 +11,6 @@ import ("testing/synctest""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/types/v2/containerregistry"diff --git a/backend/pkg/scheduler/runs/activity_test.go b/backend/pkg/scheduler/runs/activity_test.goindex 6f80597b3..52fa7dd55 100644--- a/backend/pkg/scheduler/runs/activity_test.go+++ b/backend/pkg/scheduler/runs/activity_test.go@@ -2,11 +2,11 @@ package runsimport ("context"+ "errors""sync/atomic""testing""time"- "emperror.dev/errors"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/stretchr/testify/require")diff --git a/backend/pkg/scheduler/runs/actors.go b/backend/pkg/scheduler/runs/actors.goindex 1f4f95ef2..9470297e8 100644--- a/backend/pkg/scheduler/runs/actors.go+++ b/backend/pkg/scheduler/runs/actors.go@@ -3,13 +3,13 @@ package runsimport ("context""encoding/json/v2"+ "errors""fmt""log/slog""strings""time""uuid"- "emperror.dev/errors"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis"st "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -118,7 +118,7 @@ func (a *coordinatorActorInternal) Invoke(ctx context.Context, method string, dastate.Revision = 1return true, a.q.service.SetState(ctx, coordinatorTypeInternal, a.id, state, nil)default:- return nil, errors.Errorf("unknown coordinator command: %s", method)+ return nil, fmt.Errorf("unknown coordinator command: %s", method)}}@@ -369,7 +369,7 @@ func (q *Coordinator) importLegacyInternal(ctx context.Context) error {}var record st.QueueRecordif err := json.Unmarshal([]byte(entry.Value), &record); err != nil {- return errors.WrapIf(err, "decode legacy job record")+ return fmt.Errorf("decode legacy job record: %w", err)}id := kit.SHA256Hex(record.EnvironmentID + "\x00" + record.JobID)if entry.Key != queuePrefixInternal+id {@@ -417,7 +417,7 @@ func (a *executorActorInternal) Job(ctx context.Context, _ string, data actor.En}var command st.ExecutionCommandif err := data.Decode(&command); err != nil {- return errors.Combine(err, actor.ErrJobPermanentFailure)+ return errors.Join(err, actor.ErrJobPermanentFailure)}claim, err := q.claimExecutionInternal(ctx, command)if err != nil {diff --git a/backend/pkg/scheduler/runs/actors_test.go b/backend/pkg/scheduler/runs/actors_test.goindex f3aea251b..9fcffe92e 100644--- a/backend/pkg/scheduler/runs/actors_test.go+++ b/backend/pkg/scheduler/runs/actors_test.go@@ -37,7 +37,7 @@ func TestLegacyImportSurvivesRestartAndDeduplicates(t *testing.T) {legacy := st.QueueRecord{JobID: "legacy", EnvironmentID: "0", Runs: []st.Run{{ID: uuid.New().String(), JobID: "legacy", EnvironmentID: "0", Trigger: "manual", Status: st.Succeeded, CreatedAt: time.Now().UTC()}}}encoded, err := json.Marshal(legacy)require.NoError(t, err)- key := queuePrefixInternal + kit.SHA256Hex("0"+"\x00"+legacy.JobID)+ key := queuePrefixInternal + kit.SHA256Hex("0\x00"+legacy.JobID)require.NoError(t, store.Set(t.Context(), key, string(encoded)))databaseURL := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "actors.db"))first := francistest.New(t, databaseURL)@@ -96,7 +96,7 @@ func TestAlarmIgnoresStaleGeneration(t *testing.T) {require.NoError(t, err)q.enabled.Store(true)defer q.enabled.Store(false)- coordinator := &coordinatorActorInternal{id: kit.SHA256Hex("0" + "\x00" + "schedule"), q: q}+ coordinator := &coordinatorActorInternal{id: kit.SHA256Hex("0\x00schedule"), q: q}require.NoError(t, coordinator.Alarm(t.Context(), "old", occurrenceEnvelopeInternal{st.ScheduleOccurrence{Generation: before.Generation - 1, Sequence: before.Sequence}}))after, err := q.ScheduleState(t.Context(), "schedule")require.NoError(t, err)@@ -121,7 +121,7 @@ func TestDuplicateDispatchAndCanceledDelivery(t *testing.T) {}, nil)run, err := q.Submit(t.Context(), st.Request{JobID: "dispatch", Trigger: "manual"})require.NoError(t, err)- id := kit.SHA256Hex("0" + "\x00" + run.JobID)+ id := kit.SHA256Hex("0\x00" + run.JobID)command := st.ExecutionCommand{EnvironmentID: "0", JobID: run.JobID, RunID: run.ID, Attempt: 1}jobID, created, err := q.service.Dispatch(t.Context(), executorTypeInternal, id, "execute", command, actor.WithIdempotencyKey(run.ID+"-1"))require.NoError(t, err)@@ -209,7 +209,7 @@ func TestReconciliationRepairsMissingAlarm(t *testing.T) {defer q.enabled.Store(false)record, err := q.ScheduleState(t.Context(), "repair")require.NoError(t, err)- id := kit.SHA256Hex("0" + "\x00" + "repair")+ id := kit.SHA256Hex("0\x00repair")err = q.repairInternal(t.Context())require.NoError(t, err)require.NoError(t, q.service.DeleteAlarm(t.Context(), coordinatorTypeInternal, id, fmt.Sprintf("schedule-%d-%d", record.Generation, record.Sequence)))@@ -289,7 +289,7 @@ func TestLostDispatchAcknowledgementRetainsOneExecution(t *testing.T) {case <-time.After(5 * time.Second):t.Fatal("execution did not start")}- id := kit.SHA256Hex("0" + "\x00" + run.JobID)+ id := kit.SHA256Hex("0\x00" + run.JobID)var state st.CoordinatorStaterequire.NoError(t, q.service.GetState(t.Context(), coordinatorTypeInternal, id, &state))key := run.ID + "-1"diff --git a/backend/pkg/scheduler/runs/admission.go b/backend/pkg/scheduler/runs/admission.goindex b176066c5..6e908f04a 100644--- a/backend/pkg/scheduler/runs/admission.go+++ b/backend/pkg/scheduler/runs/admission.go@@ -2,12 +2,12 @@ package runsimport ("context"+ "errors""log/slog""sync""time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/italypaleale/francis/actor"diff --git a/backend/pkg/scheduler/runs/coordinator.go b/backend/pkg/scheduler/runs/coordinator.goindex 9d49fa483..d5e485d32 100644--- a/backend/pkg/scheduler/runs/coordinator.go+++ b/backend/pkg/scheduler/runs/coordinator.go@@ -5,6 +5,8 @@ import ("cmp""context""crypto/rand"+ "errors"+ "fmt""io""log/slog""strings"@@ -13,7 +15,6 @@ import ("time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/kv"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/italypaleale/francis/actor"@@ -297,7 +298,7 @@ func (q *Coordinator) invokeInternal(ctx context.Context, run st.Run, reconciledefer func() {if recovered := recover(); recovered != nil {outcome = st.Outcome{Status: st.NeedsAttention, Message: "Job panicked; inspect logs before retrying"}- err = errors.Errorf("job panic: %v", recovered)+ err = fmt.Errorf("job panic: %v", recovered)slog.ErrorContext(ctx, "Job panicked", "runId", run.ID, "error", err)}}()@@ -421,3 +422,36 @@ func mergeTargetProgressInternal(previous, outcome st.Outcome) st.Outcome {}func (q *Coordinator) Active() bool { return q.enabled.Load() }++// Resolve releases reviewed, inactive work without discarding its execution evidence.+func (q *Coordinator) Resolve(ctx context.Context, environmentID, jobID, runID, resolvedBy string) (st.Run, error) {+ run, err := q.Get(ctx, environmentID, jobID, runID)+ if err != nil {+ return run, err+ }+ err = q.UpdateRun(ctx, run, func(current *st.Run) error {+ if current.Status == st.Canceled && current.Resolution != nil {+ run = *current+ return nil+ }+ if current.Status != st.NeedsAttention {+ return errors.New("only runs needing attention can be resolved")+ }+ if current.EnvironmentID != "0" && (current.RemoteDeliveryAttempted || current.RemoteAccepted) && !current.RemoteSettled {+ return errors.New("remote execution must be confirmed and acknowledged before resolution")+ }+ now := time.Now().UTC()+ current.Status = st.Canceled+ current.Resolution = &st.RunResolution{ResolvedBy: resolvedBy, ResolvedAt: now, Reason: "resolved_after_review"}+ current.UpdatedAt = now+ current.FinishedAt = &now+ current.NextAttempt = nil+ current.Owner = ""+ run = *current+ return nil+ })+ if err == nil {+ q.signalInternal()+ }+ return run, err+}diff --git a/backend/pkg/scheduler/runs/coordinator_store.go b/backend/pkg/scheduler/runs/coordinator_store.goindex 5a598671f..a31670e2c 100644--- a/backend/pkg/scheduler/runs/coordinator_store.go+++ b/backend/pkg/scheduler/runs/coordinator_store.go@@ -4,12 +4,12 @@ import ("bytes""context""encoding/json/v2"+ "errors""slices""sort""time""uuid"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/kv"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/italypaleale/francis/actor"@@ -264,10 +264,10 @@ func pruneRunsInternal(record *st.QueueRecord, now time.Time) {}// ErrRunNotFound indicates that neither a run nor its receipt exists.-var ErrRunNotFound = errors.Sentinel("job run not found")+var ErrRunNotFound = errors.New("job run not found")// ErrRunConflict indicates that execution ownership or state changed.-var ErrRunConflict = errors.Sentinel("job run state changed")+var ErrRunConflict = errors.New("job run state changed")func New(store *kv.KVService, service *actor.Service, location *time.Location) *Coordinator {if location == nil {@@ -283,7 +283,7 @@ func (q *Coordinator) SetExecutor(execute, reconcile func(context.Context, st.Rufunc (q *Coordinator) ScheduleState(ctx context.Context, jobID string) (st.QueueRecord, error) {var state st.CoordinatorState- err := q.service.GetState(ctx, coordinatorTypeInternal, kit.SHA256Hex("0"+"\x00"+jobID), &state)+ err := q.service.GetState(ctx, coordinatorTypeInternal, kit.SHA256Hex("0\x00"+jobID), &state)normalizeRecordTimesInternal(&state.Record)return state.Record, err}diff --git a/backend/pkg/scheduler/runs/resolution.go b/backend/pkg/scheduler/runs/resolution.godeleted file mode 100644index fea90a1e4..000000000--- a/backend/pkg/scheduler/runs/resolution.go+++ /dev/null@@ -1,42 +0,0 @@-package runs--import (- "context"- "time"-- "emperror.dev/errors"- st "github.com/getarcaneapp/arcane/types/v2/scheduler"-)--// Resolve releases reviewed, inactive work without discarding its execution evidence.-func (q *Coordinator) Resolve(ctx context.Context, environmentID, jobID, runID, resolvedBy string) (st.Run, error) {- run, err := q.Get(ctx, environmentID, jobID, runID)- if err != nil {- return run, err- }- err = q.UpdateRun(ctx, run, func(current *st.Run) error {- if current.Status == st.Canceled && current.Resolution != nil {- run = *current- return nil- }- if current.Status != st.NeedsAttention {- return errors.New("only runs needing attention can be resolved")- }- if current.EnvironmentID != "0" && (current.RemoteDeliveryAttempted || current.RemoteAccepted) && !current.RemoteSettled {- return errors.New("remote execution must be confirmed and acknowledged before resolution")- }- now := time.Now().UTC()- current.Status = st.Canceled- current.Resolution = &st.RunResolution{ResolvedBy: resolvedBy, ResolvedAt: now, Reason: "resolved_after_review"}- current.UpdatedAt = now- current.FinishedAt = &now- current.NextAttempt = nil- current.Owner = ""- run = *current- return nil- })- if err == nil {- q.signalInternal()- }- return run, err-}diff --git a/backend/pkg/scheduler/schedule/cron.go b/backend/pkg/scheduler/schedule/cron.goindex bbeb05963..b074bef1d 100644--- a/backend/pkg/scheduler/schedule/cron.go+++ b/backend/pkg/scheduler/schedule/cron.go@@ -2,9 +2,9 @@package scheduleimport (+ "fmt""strings"- "emperror.dev/errors""github.com/robfig/cron/v3")@@ -12,15 +12,15 @@ import (func NormalizeSixField(value, subject string) (string, error) {fields := strings.Fields(value)if len(fields) == 0 {- return "", errors.Errorf("%s schedule is required", subject)+ return "", fmt.Errorf("%s schedule is required", subject)}if len(fields) != 6 {- return "", errors.Errorf("invalid %s schedule %q: expected six fields", subject, strings.TrimSpace(value))+ return "", fmt.Errorf("invalid %s schedule %q: expected six fields", subject, strings.TrimSpace(value))}normalized := strings.Join(fields, " ")parser := Parser()if _, err := parser.Parse(normalized); err != nil {- return "", errors.WrapIff(err, "invalid %s schedule %q", subject, normalized)+ return "", fmt.Errorf("invalid %s schedule %q: %w", subject, normalized, err)}return normalized, nil}diff --git a/backend/pkg/scheduler/scheduler.go b/backend/pkg/scheduler/scheduler.goindex 93105596c..ea0e92329 100644--- a/backend/pkg/scheduler/scheduler.go+++ b/backend/pkg/scheduler/scheduler.go@@ -2,11 +2,12 @@ package schedulerimport ("context"+ "errors"+ "fmt""log/slog""sync""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"st "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -14,7 +15,7 @@ import (var (cronScheduleParser = scheduleutil.Parser()- errJobSchedulerStoppedInternal = errors.Sentinel("job scheduler stopped")+ errJobSchedulerStoppedInternal = errors.New("job scheduler stopped"))type watcherRegistrationInternal struct {@@ -138,7 +139,7 @@ func (js *jobSchedulerInternal) StartScheduler() error {var schedulingErr errorfor _, job := range js.ListRegisteredJobs() {if err := js.installInternal(js.context, job); err != nil {- schedulingErr = errors.Combine(schedulingErr, errors.WrapIf(err, "schedule "+job.Name()))+ schedulingErr = errors.Join(schedulingErr, fmt.Errorf("%s: %w", "schedule "+job.Name(), err))}}return schedulingErr@@ -207,10 +208,10 @@ func (js *jobSchedulerInternal) Stop(ctx context.Context) error {select {case <-w.done:case <-ctx.Done():- return errors.Combine(err, ctx.Err())+ return errors.Join(err, ctx.Err())}if stop, ok := w.watcher.(st.StoppableBusWatcher); ok {- err = errors.Combine(err, stop.Stop(ctx))+ err = errors.Join(err, stop.Stop(ctx))}}return errdiff --git a/backend/pkg/scheduler/scheduler_test.go b/backend/pkg/scheduler/scheduler_test.goindex 1205fac7b..e40be8d0c 100644--- a/backend/pkg/scheduler/scheduler_test.go+++ b/backend/pkg/scheduler/scheduler_test.go@@ -2,11 +2,11 @@ package schedulerimport ("context"+ "errors""sync""testing""time"- "emperror.dev/errors"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/stretchr/testify/require")diff --git a/backend/pkg/scheduler/supervision.go b/backend/pkg/scheduler/supervision.goindex 2af61d7a4..20deab93a 100644--- a/backend/pkg/scheduler/supervision.go+++ b/backend/pkg/scheduler/supervision.go@@ -3,11 +3,12 @@ package schedulerimport ("context""crypto/rand"+ "errors"+ "fmt""math/big""sync""time"- "emperror.dev/errors"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")@@ -76,7 +77,7 @@ func (s *watcherSupervisorInternal) runInternal(ctx context.Context) error {}jitter, jitterErr := rand.Int(rand.Reader, big.NewInt(int64(delay/2)))if jitterErr != nil {- return errors.WrapIf(jitterErr, "generate watcher retry delay")+ return fmt.Errorf("generate watcher retry delay: %w", jitterErr)}next := time.Now().Add(delay/2 + time.Duration(jitter.Int64()))s.setHealthInternal("retrying", err, &next)@@ -98,7 +99,7 @@ func (s *watcherSupervisorInternal) runInternal(ctx context.Context) error {func (s *watcherSupervisorInternal) startInternal(ctx context.Context) (panicked bool, err error) {defer func() {if recovered := recover(); recovered != nil {- err = errors.Errorf("worker panic: %v", recovered)+ err = fmt.Errorf("worker panic: %v", recovered)panicked = true}}()diff --git a/backend/pkg/scheduler/vulnerability_scan_job.go b/backend/pkg/scheduler/vulnerability_scan_job.goindex d3c735772..3f3fb00d3 100644--- a/backend/pkg/scheduler/vulnerability_scan_job.go+++ b/backend/pkg/scheduler/vulnerability_scan_job.go@@ -3,9 +3,9 @@ package schedulerimport ("cmp""context"+ "errors""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"diff --git a/backend/pkg/utils/backupbrowser/browser.go b/backend/pkg/utils/backupbrowser/browser.goindex 2d6263615..fcc69c77a 100644--- a/backend/pkg/utils/backupbrowser/browser.go+++ b/backend/pkg/utils/backupbrowser/browser.go@@ -4,13 +4,13 @@ package backupbrowserimport ("cmp"+ "errors""fmt""path""slices""sort""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"kit "go.getarcane.app/kit/pkg"diff --git a/backend/pkg/utils/backupbrowser/browser_test.go b/backend/pkg/utils/backupbrowser/browser_test.goindex aa1f8fac6..41cd50735 100644--- a/backend/pkg/utils/backupbrowser/browser_test.go+++ b/backend/pkg/utils/backupbrowser/browser_test.go@@ -31,7 +31,7 @@ func TestBrowseWalkReachesEveryEntryInternal(t *testing.T) {var walked []backuptypes.BackupFileEntrystart := 0for {- items, page := Browse(entries, pagination.QueryParams{Params: pagination.Params{Start: start, Limit: 2}})+ items, page := Browse(entries, pagination.QueryParams{Start: start, Limit: 2})walked = append(walked, items...)start += len(items)if int64(start) >= page.TotalItems {@@ -49,8 +49,8 @@ func TestBrowseSearchOrderingAndPaginationInternal(t *testing.T) {{Path: "alpha/first.txt", Name: "first.txt"},}params := pagination.QueryParams{- SearchQuery: pagination.SearchQuery{Search: "ALPHA"},- Params: pagination.Params{Start: 1, Limit: 1},+ Search: "ALPHA",+ Start: 1, Limit: 1,}items, page := Browse(entries, params)require.Equal(t, []backuptypes.BackupFileEntry{{Path: "alpha/first.txt", Name: "first.txt"}}, items)@@ -59,7 +59,7 @@ func TestBrowseSearchOrderingAndPaginationInternal(t *testing.T) {require.Equal(t, 2, page.CurrentPage)require.Equal(t, 1, page.ItemsPerPage)- items, page = Browse(entries, pagination.QueryParams{Params: pagination.Params{Start: 10, Limit: 2}})+ items, page = Browse(entries, pagination.QueryParams{Start: 10, Limit: 2})require.Empty(t, items)require.Equal(t, int64(4), page.TotalItems)}diff --git a/backend/pkg/utils/concurrency/background.go b/backend/pkg/utils/concurrency/background.godeleted file mode 100644index fce6e3807..000000000--- a/backend/pkg/utils/concurrency/background.go+++ /dev/null@@ -1,73 +0,0 @@-package concurrency--import (- "context"- "crypto/rand"- "log/slog"- "math/big"- "time"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"-)--// StartSupervised starts a background operation and returns its cancel-and-join function.-func StartSupervised(ctx context.Context, label string, run func(context.Context) error) (func(context.Context) error, error) {- if ctx == nil || run == nil {- return nil, errors.New("background operation dependencies unavailable")- }- runCtx, cancel := context.WithCancel(ctx)- done := make(chan struct{})- go func() {- defer close(done)- delay := 5 * time.Second- unexpected := 0- for runCtx.Err() == nil {- started := time.Now()- var runErr error- panicked := true- func() { defer utils.RecoverToError(&runErr, label); runErr = run(runCtx); panicked = false }()- if runCtx.Err() != nil {- return- }- if panicked || runErr == nil {- unexpected++- }- if runErr == nil {- runErr = errors.New("background operation exited unexpectedly")- }- if time.Since(started) > 5*time.Minute {- delay = 5 * time.Second- unexpected = 0- }- if unexpected >= 3 {- slog.ErrorContext(runCtx, "Background operation requires attention", "label", label, "error", runErr)- return- }- jitter, err := rand.Int(rand.Reader, big.NewInt(int64(delay/2)))- if err != nil {- slog.ErrorContext(runCtx, "Failed to schedule background retry", "label", label, "error", err)- return- }- wait := delay/2 + time.Duration(jitter.Int64())- slog.WarnContext(runCtx, "Background operation failed; retrying", "label", label, "error", runErr, "retryIn", wait)- timer := time.NewTimer(wait)- select {- case <-runCtx.Done():- timer.Stop()- return- case <-timer.C:- }- delay = min(delay*2, 5*time.Minute)- }- }()- return func(stopCtx context.Context) error {- cancel()- select {- case <-done:- return nil- case <-stopCtx.Done():- return stopCtx.Err()- }- }, nil-}diff --git a/backend/pkg/utils/concurrency/signal.go b/backend/pkg/utils/concurrency/signal.goindex edfee0279..c434e311f 100644--- a/backend/pkg/utils/concurrency/signal.go+++ b/backend/pkg/utils/concurrency/signal.go@@ -1,8 +1,14 @@package concurrencyimport (+ "context"+ "crypto/rand"+ "errors"+ "log/slog"+ "math/big""sync""sync/atomic"+ "time""github.com/getarcaneapp/arcane/backend/v2/pkg/utils")@@ -60,3 +66,64 @@ func (s *Signal[T]) Publish(value T) {}()}}++// StartSupervised starts a background operation and returns its cancel-and-join function.+func StartSupervised(ctx context.Context, label string, run func(context.Context) error) (func(context.Context) error, error) {+ if ctx == nil || run == nil {+ return nil, errors.New("background operation dependencies unavailable")+ }+ runCtx, cancel := context.WithCancel(ctx)+ done := make(chan struct{})+ go func() {+ defer close(done)+ delay := 5 * time.Second+ unexpected := 0+ for runCtx.Err() == nil {+ started := time.Now()+ var runErr error+ panicked := true+ func() { defer utils.RecoverToError(&runErr, label); runErr = run(runCtx); panicked = false }()+ if runCtx.Err() != nil {+ return+ }+ if panicked || runErr == nil {+ unexpected+++ }+ if runErr == nil {+ runErr = errors.New("background operation exited unexpectedly")+ }+ if time.Since(started) > 5*time.Minute {+ delay = 5 * time.Second+ unexpected = 0+ }+ if unexpected >= 3 {+ slog.ErrorContext(runCtx, "Background operation requires attention", "label", label, "error", runErr)+ return+ }+ jitter, err := rand.Int(rand.Reader, big.NewInt(int64(delay/2)))+ if err != nil {+ slog.ErrorContext(runCtx, "Failed to schedule background retry", "label", label, "error", err)+ return+ }+ wait := delay/2 + time.Duration(jitter.Int64())+ slog.WarnContext(runCtx, "Background operation failed; retrying", "label", label, "error", runErr, "retryIn", wait)+ timer := time.NewTimer(wait)+ select {+ case <-runCtx.Done():+ timer.Stop()+ return+ case <-timer.C:+ }+ delay = min(delay*2, 5*time.Minute)+ }+ }()+ return func(stopCtx context.Context) error {+ cancel()+ select {+ case <-done:+ return nil+ case <-stopCtx.Done():+ return stopCtx.Err()+ }+ }, nil+}diff --git a/backend/pkg/utils/concurrency/state_map.go b/backend/pkg/utils/concurrency/state_map.goindex 3f2e3e57a..6e5ff18af 100644--- a/backend/pkg/utils/concurrency/state_map.go+++ b/backend/pkg/utils/concurrency/state_map.go@@ -2,11 +2,10 @@ package concurrencyimport ("context"+ "errors""maps""sync""sync/atomic"-- "emperror.dev/errors")// StateMap owns mutable keyed state while publishing immutable snapshots for readers.diff --git a/backend/pkg/utils/concurrency/state_map_test.go b/backend/pkg/utils/concurrency/state_map_test.goindex 7b27c4951..85bf3498b 100644--- a/backend/pkg/utils/concurrency/state_map_test.go+++ b/backend/pkg/utils/concurrency/state_map_test.go@@ -1,9 +1,9 @@package concurrencyimport (+ "errors""testing"- "emperror.dev/errors""github.com/stretchr/testify/require")diff --git a/backend/pkg/utils/dbutil/dbutil.go b/backend/pkg/utils/dbutil/dbutil.goindex 7507caf26..a096f4a33 100644--- a/backend/pkg/utils/dbutil/dbutil.go+++ b/backend/pkg/utils/dbutil/dbutil.go@@ -4,9 +4,10 @@ package dbutilimport ("context"+ "errors"+ "fmt""strings"- "emperror.dev/errors""gorm.io/gorm")@@ -38,7 +39,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, errors.WrapIff(err, "failed to query %T", out)+ return nil, fmt.Errorf("failed to query %T: %w", out, err)}return &out, nil}diff --git a/backend/pkg/utils/env_util.go b/backend/pkg/utils/env_util.godeleted file mode 100644index f944865ac..000000000--- a/backend/pkg/utils/env_util.go+++ /dev/null@@ -1,32 +0,0 @@-package utils--import (- "log/slog"- "os"- "strings"-)--// LookupEnvOrFile is os.LookupEnv with Docker secret support: when NAME__FILE-// or NAME_FILE (checked in that order) names a readable file, its trimmed-// contents stand in for NAME. An unreadable file falls back to NAME.-// The booleans report whether a value was found and whether it came from a file.-func LookupEnvOrFile(name string) (value string, found, fromFile bool) {- for _, suffix := range []string{"__FILE", "_FILE"} {- filePath := os.Getenv(name + suffix)- if filePath == "" {- continue- }-- // Secret paths are arbitrary host paths, so there is no acfs root to confine them to.- content, err := os.ReadFile(filePath) //nolint:gosec // path intentionally comes from a *_FILE env var- if err != nil {- slog.Warn("Failed to read secret file, falling back to direct env var", "env", name+suffix, "error", err)- break- }-- return strings.TrimSpace(string(content)), true, true- }-- value, found = os.LookupEnv(name)- return value, found, false-}diff --git a/backend/pkg/utils/handlerutil/download.go b/backend/pkg/utils/handlerutil/download.godeleted file mode 100644index 4ad284d04..000000000--- a/backend/pkg/utils/handlerutil/download.go+++ /dev/null@@ -1,22 +0,0 @@-package handlerutil--import (- "io"- "strconv"-- "github.com/danielgtaylor/huma/v2"-)--// DownloadResponse streams an attachment and closes its reader when streaming-// ends. A negative size means unknown and omits Content-Length.-func DownloadResponse(reader io.ReadCloser, size int64, filename string) *huma.StreamResponse {- return &huma.StreamResponse{Body: func(ctx huma.Context) {- defer func() { _ = reader.Close() }()- ctx.SetHeader("Content-Type", "application/octet-stream")- ctx.SetHeader("Content-Disposition", "attachment; filename="+filename)- if size >= 0 {- ctx.SetHeader("Content-Length", strconv.FormatInt(size, 10))- }- _, _ = io.Copy(ctx.BodyWriter(), reader)- }}-}diff --git a/backend/pkg/utils/handlerutil/feature.go b/backend/pkg/utils/handlerutil/feature.godeleted file mode 100644index 828bf6330..000000000--- a/backend/pkg/utils/handlerutil/feature.go+++ /dev/null@@ -1,20 +0,0 @@-package handlerutil--import (- "fmt"- "net/http"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/types/v2/features"-)--// FeatureDisabledError identifies a disabled runtime feature in problem details.-func FeatureDisabledError(id features.ID) *features.DisabledError {- return &features.DisabledError{- Status: http.StatusForbidden,- Title: http.StatusText(http.StatusForbidden),- Detail: fmt.Sprintf("feature %s is disabled", id),- Code: string(common.APIErrorCodeFeatureDisabled),- Feature: id,- }-}diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.goindex 667e6c334..a645f8fb7 100644--- a/backend/pkg/utils/handlerutil/handlerutil.go+++ b/backend/pkg/utils/handlerutil/handlerutil.go@@ -7,6 +7,7 @@ import ("io""mime/multipart""net/http"+ "strconv""strings""github.com/danielgtaylor/huma/v2"@@ -15,6 +16,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base"+ "github.com/getarcaneapp/arcane/types/v2/features""go.getarcane.app/kit/pkg/mapping")@@ -198,3 +200,28 @@ func SessionMetaFromContext(ctx context.Context, userAgent string) auth.SessionMIPAddress: middleware.GetRemoteAddrFromContext(ctx),}}++// DownloadResponse streams an attachment and closes its reader when streaming+// ends. A negative size means unknown and omits Content-Length.+func DownloadResponse(reader io.ReadCloser, size int64, filename string) *huma.StreamResponse {+ return &huma.StreamResponse{Body: func(ctx huma.Context) {+ defer func() { _ = reader.Close() }()+ ctx.SetHeader("Content-Type", "application/octet-stream")+ ctx.SetHeader("Content-Disposition", "attachment; filename="+filename)+ if size >= 0 {+ ctx.SetHeader("Content-Length", strconv.FormatInt(size, 10))+ }+ _, _ = io.Copy(ctx.BodyWriter(), reader)+ }}+}++// FeatureDisabledError identifies a disabled runtime feature in problem details.+func FeatureDisabledError(id features.ID) *features.DisabledError {+ return &features.DisabledError{+ Status: http.StatusForbidden,+ Title: http.StatusText(http.StatusForbidden),+ Detail: fmt.Sprintf("feature %s is disabled", id),+ Code: string(common.APIErrorCodeFeatureDisabled),+ Feature: id,+ }+}diff --git a/backend/pkg/utils/handlerutil/remote_proxy.go b/backend/pkg/utils/handlerutil/remote_proxy.goindex 015f8da98..747307911 100644--- a/backend/pkg/utils/handlerutil/remote_proxy.go+++ b/backend/pkg/utils/handlerutil/remote_proxy.go@@ -3,7 +3,7 @@ package handlerutilimport ("context""encoding/json/v2"- stderrors "errors"+ "errors""net/http""github.com/danielgtaylor/huma/v2"@@ -47,18 +47,18 @@ func marshalRemoteRequestBodyInternal(requestBody any) ([]byte, error) {// TranslateRemoteProxyError converts environment transport failures into Huma errors.func TranslateRemoteProxyError(err error) error {- if transportErr, ok := stderrors.AsType[*remenv.TransportError](err); ok {+ if transportErr, ok := errors.AsType[*remenv.TransportError](err); ok {return huma.Error502BadGateway("failed to proxy request to environment: " + transportErr.Error())}- if statusErr, ok := stderrors.AsType[*remenv.StatusError](err); ok {+ if statusErr, ok := errors.AsType[*remenv.StatusError](err); ok {if statusErr.StatusCode == http.StatusUnauthorized {return huma.Error502BadGateway("Remote environment rejected the manager's credentials")}return huma.NewError(statusErr.StatusCode, "environment returned error: "+string(statusErr.Body), nil)}- if decodeErr, ok := stderrors.AsType[*remenv.DecodeError](err); ok {+ if decodeErr, ok := errors.AsType[*remenv.DecodeError](err); ok {return huma.Error500InternalServerError("failed to decode environment response: " + decodeErr.Error())}diff --git a/backend/pkg/utils/httpx/base_url.go b/backend/pkg/utils/httpx/base_url.goindex b6f90766d..9eb4aa252 100644--- a/backend/pkg/utils/httpx/base_url.go+++ b/backend/pkg/utils/httpx/base_url.go@@ -1,6 +1,8 @@package httpximport (+ "errors"+ "fmt""net""net/url""strings"@@ -56,3 +58,34 @@ func ManagerGRPCAddr(rawURL string) string {return net.JoinHostPort(host, port)}++// ValidateOutboundHTTPURL parses and validates an outbound HTTP(S) target URL.+// It intentionally performs syntactic hardening (scheme/host/credentials)+// without restricting private network ranges, because environment agents may be+// deployed on trusted private subnets.+func ValidateOutboundHTTPURL(rawURL string) (*url.URL, error) {+ trimmed := strings.TrimSpace(rawURL)+ if trimmed == "" {+ return nil, errors.New("URL is required")+ }++ parsed, err := url.Parse(trimmed)+ if err != nil {+ return nil, fmt.Errorf("failed to parse URL: %w", err)+ }++ scheme := strings.ToLower(parsed.Scheme)+ if scheme != "http" && scheme != "https" {+ return nil, fmt.Errorf("unsupported scheme %q", parsed.Scheme)+ }++ if parsed.User != nil {+ return nil, errors.New("embedded credentials are not allowed")+ }++ if parsed.Host == "" || parsed.Hostname() == "" {+ return nil, errors.New("URL host is required")+ }++ return parsed, nil+}diff --git a/backend/pkg/utils/httpx/client.go b/backend/pkg/utils/httpx/client.godeleted file mode 100644index e531a3caf..000000000--- a/backend/pkg/utils/httpx/client.go+++ /dev/null@@ -1,24 +0,0 @@-package httpx--import (- "net/http"- "time"-- httpxtypes "github.com/getarcaneapp/arcane/types/v2/httpx"-)--// NewHTTPClient builds a client with its own transport and the supplied timeouts.-func NewHTTPClient(options httpxtypes.ClientOptions) *http.Client {- transport := &http.Transport{- Proxy: http.ProxyFromEnvironment,- MaxIdleConns: 100,- IdleConnTimeout: 90 * time.Second,- TLSHandshakeTimeout: options.TLSHandshakeTimeout,- ExpectContinueTimeout: 1 * time.Second,- ForceAttemptHTTP2: true,- }- return &http.Client{- Transport: transport,- Timeout: options.Timeout,- }-}diff --git a/backend/pkg/utils/httpx/outbound_url.go b/backend/pkg/utils/httpx/outbound_url.godeleted file mode 100644index 1b0ad6452..000000000--- a/backend/pkg/utils/httpx/outbound_url.go+++ /dev/null@@ -1,39 +0,0 @@-package httpx--import (- "net/url"- "strings"-- "emperror.dev/errors"-)--// ValidateOutboundHTTPURL parses and validates an outbound HTTP(S) target URL.-// It intentionally performs syntactic hardening (scheme/host/credentials)-// without restricting private network ranges, because environment agents may be-// deployed on trusted private subnets.-func ValidateOutboundHTTPURL(rawURL string) (*url.URL, error) {- trimmed := strings.TrimSpace(rawURL)- if trimmed == "" {- return nil, errors.New("URL is required")- }-- parsed, err := url.Parse(trimmed)- if err != nil {- return nil, errors.WrapIf(err, "failed to parse URL")- }-- scheme := strings.ToLower(parsed.Scheme)- if scheme != "http" && scheme != "https" {- return nil, errors.Errorf("unsupported scheme %q", parsed.Scheme)- }-- if parsed.User != nil {- return nil, errors.New("embedded credentials are not allowed")- }-- if parsed.Host == "" || parsed.Hostname() == "" {- return nil, errors.New("URL host is required")- }-- return parsed, nil-}diff --git a/backend/pkg/utils/httpx/request.go b/backend/pkg/utils/httpx/request.goindex d11c3b962..1186f29ca 100644--- a/backend/pkg/utils/httpx/request.go+++ b/backend/pkg/utils/httpx/request.go@@ -7,8 +7,9 @@ import ("net/url""strconv""strings"+ "time"- "emperror.dev/errors"+ httpxtypes "github.com/getarcaneapp/arcane/types/v2/httpx")type HeaderSetter interface {@@ -95,13 +96,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, errors.Errorf("missing numeric query parameter %s", name)+ return 0, fmt.Errorf("missing numeric query parameter %s", name)}return 0, nil}n, err := strconv.Atoi(q.Get(name))if err != nil {- return 0, errors.WrapIff(err, "invalid numeric query parameter %s", name)+ return 0, fmt.Errorf("invalid numeric query parameter %s: %w", name, err)}return n, nil}@@ -136,3 +137,19 @@ func GetClientBaseURL(origin, forwardedHost, forwardedProto, host, appURL string// 4. Fallbackreturn strings.TrimSuffix(appURL, "/")}++// NewHTTPClient builds a client with its own transport and the supplied timeouts.+func NewHTTPClient(options httpxtypes.ClientOptions) *http.Client {+ transport := &http.Transport{+ Proxy: http.ProxyFromEnvironment,+ MaxIdleConns: 100,+ IdleConnTimeout: 90 * time.Second,+ TLSHandshakeTimeout: options.TLSHandshakeTimeout,+ ExpectContinueTimeout: 1 * time.Second,+ ForceAttemptHTTP2: true,+ }+ return &http.Client{+ Transport: transport,+ Timeout: options.Timeout,+ }+}diff --git a/backend/pkg/utils/httpx/safe_remote.go b/backend/pkg/utils/httpx/safe_remote.goindex fff398de9..2053530fb 100644--- a/backend/pkg/utils/httpx/safe_remote.go+++ b/backend/pkg/utils/httpx/safe_remote.go@@ -2,6 +2,8 @@ package httpximport ("context"+ "errors"+ "fmt""net""net/http""net/netip"@@ -9,7 +11,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common")@@ -52,21 +53,21 @@ func ValidateSafeRemoteURL(ctx context.Context, rawURL string, lookupIP LookupIPparsed, err := url.Parse(rawURL)if err != nil {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", err)) //nolint:staticcheck // Preserve the existing error message.}scheme := strings.ToLower(parsed.Scheme)if scheme != "http" && scheme != "https" {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("unsupported URL scheme %q", scheme), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("unsupported URL scheme %q", scheme))) //nolint:staticcheck // Preserve the existing error message.}if parsed.User != nil {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("URL credentials are not allowed"), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("URL credentials are not allowed"))) //nolint:staticcheck // Preserve the existing error message.}host := parsed.Hostname()if host == "" || isBlockedHostnameInternal(host) {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("missing or blocked hostname"), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("missing or blocked hostname"))) //nolint:staticcheck // Preserve the existing error message.}ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)@@ -74,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.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", err)) //nolint:staticcheck // Preserve the existing error message.}return parsed, nil@@ -105,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.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(err, "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", err)) //nolint:staticcheck // Preserve the existing error message.}ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)@@ -157,14 +158,14 @@ func cloneHTTPTransportInternal(base http.RoundTripper) (*http.Transport, error)case *http.Transport:return t.Clone(), nildefault:- return nil, errors.Errorf("unsupported HTTP transport type %T", base)+ return nil, fmt.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.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("blocked IP address %s", parsedIP), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("blocked IP address %s", parsedIP))) //nolint:staticcheck // Preserve the existing error message.}return []net.IP{parsedIP}, nil}@@ -180,13 +181,13 @@ func resolveAllowedIPsInternal(ctx context.Context, host string, lookupIP Lookupcontinue}if isBlockedIPInternal(ip) {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.Errorf("blocked IP address %s", ip), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("blocked IP address %s", ip))) //nolint:staticcheck // Preserve the existing error message.}allowed = append(allowed, ip)}if len(allowed) == 0 {- return nil, common.Classify(common.ErrUnsafeRemoteURL, errors.WrapIf(errors.New("host did not resolve to an allowed IP"), "Remote URL is not allowed"))+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("host did not resolve to an allowed IP"))) //nolint:staticcheck // Preserve the existing error message.}return allowed, nildiff --git a/backend/pkg/utils/logging/error_handler.go b/backend/pkg/utils/logging/error_handler.godeleted file mode 100644index 2a145dfd5..000000000--- a/backend/pkg/utils/logging/error_handler.go+++ /dev/null@@ -1,34 +0,0 @@-package logging--import (- "context"- "log/slog"-- "emperror.dev/emperror"- "emperror.dev/errors"-)--var (- _ emperror.ErrorHandler = (*SlogErrorHandler)(nil)- _ 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...)-}diff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.goindex 6e0133f9e..6760a5812 100644--- a/backend/pkg/utils/notifications/config_credentials.go+++ b/backend/pkg/utils/notifications/config_credentials.go@@ -3,9 +3,10 @@ package notificationsimport ("encoding/base64""encoding/json/v2"+ "errors"+ "fmt""log/slog"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database""go.getarcane.app/sys/crypto")@@ -15,10 +16,10 @@ func DecodeConfig[T any](config database.JSON, providerName string) (T, error) {var out TconfigBytes, err := json.Marshal(config)if err != nil {- return out, errors.WrapIff(err, "failed to marshal %s config", providerName)+ return out, fmt.Errorf("failed to marshal %s config: %w", providerName, err)}if err := json.Unmarshal(configBytes, &out); err != nil {- return out, errors.WrapIff(err, "failed to unmarshal %s config", providerName)+ return out, fmt.Errorf("failed to unmarshal %s config: %w", providerName, err)}return out, nil}@@ -33,7 +34,7 @@ func DecryptStringCredential(value *string) error {decrypted, err := crypto.Decrypt(*value)if err != nil {if isPlausibleEncryptedCredentialInternal(*value) {- return errors.WrapIf(err, "failed to decrypt notification credential")+ return fmt.Errorf("failed to decrypt notification credential: %w", err)}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 19c594a1c..10187ebf5 100644--- a/backend/pkg/utils/notifications/deliver.go+++ b/backend/pkg/utils/notifications/deliver.go@@ -3,9 +3,10 @@ package notificationsimport ("cmp""context"+ "errors"+ "fmt""net/mail"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database")@@ -78,7 +79,7 @@ func deliverDiscord(ctx context.Context, config database.JSON, c Content) errorreturn err}if err := SendDiscord(ctx, discordConfig, c.Text[MessageFormatMarkdown]); err != nil {- return errors.WrapIf(err, "failed to send Discord notification")+ return fmt.Errorf("failed to send Discord notification: %w", err)}return nil}@@ -95,11 +96,11 @@ func deliverEmail(ctx context.Context, config database.JSON, c Content) error {return errors.New("no recipient email addresses configured")}if _, err := mail.ParseAddress(emailConfig.FromAddress); err != nil {- return errors.WrapIf(err, "invalid from address")+ return fmt.Errorf("invalid from address: %w", err)}for _, addr := range emailConfig.ToAddresses {if _, err := mail.ParseAddress(addr); err != nil {- return errors.WrapIff(err, "invalid to address %s", addr)+ return fmt.Errorf("invalid to address %s: %w", addr, err)}}if err := DecryptStringCredential(&emailConfig.SMTPPassword); err != nil {@@ -113,7 +114,7 @@ func deliverEmail(ctx context.Context, config database.JSON, c Content) error {return err}if err := SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {- return errors.WrapIf(err, "failed to send email")+ return fmt.Errorf("failed to send email: %w", err)}return nil}@@ -134,7 +135,7 @@ func deliverTelegram(ctx context.Context, config database.JSON, c Content) error}telegramConfig.ParseMode = cmp.Or(telegramConfig.ParseMode, "HTML")if err := SendTelegram(ctx, telegramConfig, c.Text[MessageFormatHTML]); err != nil {- return errors.WrapIf(err, "failed to send Telegram notification")+ return fmt.Errorf("failed to send Telegram notification: %w", err)}return nil}@@ -162,7 +163,7 @@ func deliverSignal(ctx context.Context, config database.JSON, c Content) error {return err}if err := SendSignal(ctx, signalConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Signal notification")+ return fmt.Errorf("failed to send Signal notification: %w", err)}return nil}@@ -173,7 +174,7 @@ func deliverSlack(ctx context.Context, config database.JSON, c Content) error {return err}if err := SendSlack(ctx, slackConfig, c.Text[MessageFormatSlack]); err != nil {- return errors.WrapIf(err, "failed to send Slack notification")+ return fmt.Errorf("failed to send Slack notification: %w", err)}return nil}@@ -184,7 +185,7 @@ func deliverNtfy(ctx context.Context, config database.JSON, c Content) error {return err}if err := SendNtfy(ctx, ntfyConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Ntfy notification")+ return fmt.Errorf("failed to send Ntfy notification: %w", err)}return nil}@@ -206,7 +207,7 @@ func deliverPushover(ctx context.Context, config database.JSON, c Content) errorpushoverConfig.Title = c.DefaultTitle}if err := SendPushover(ctx, pushoverConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Pushover notification")+ return fmt.Errorf("failed to send Pushover notification: %w", err)}return nil}@@ -220,7 +221,7 @@ func deliverGotify(ctx context.Context, config database.JSON, c Content) error {gotifyConfig.Title = c.DefaultTitle}if err := SendGotify(ctx, gotifyConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Gotify notification")+ return fmt.Errorf("failed to send Gotify notification: %w", err)}return nil}@@ -231,7 +232,7 @@ func deliverMatrix(ctx context.Context, config database.JSON, c Content) error {return err}if err := SendMatrix(ctx, matrixConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Matrix notification")+ return fmt.Errorf("failed to send Matrix notification: %w", err)}return nil}@@ -248,7 +249,7 @@ func deliverGoogleChat(ctx context.Context, config database.JSON, c Content) errreturn err}if err := SendGoogleChat(ctx, googleChatConfig, c.Text[MessageFormatPlain]); err != nil {- return errors.WrapIf(err, "failed to send Google Chat notification")+ return fmt.Errorf("failed to send Google Chat notification: %w", err)}return nil}@@ -262,7 +263,7 @@ func deliverGeneric(ctx context.Context, config database.JSON, c Content) errorreturn errors.New("webhook URL not configured")}if err := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain], c.Vars); err != nil {- return errors.WrapIf(err, "failed to send Generic webhook notification")+ return fmt.Errorf("failed to send Generic webhook notification: %w", err)}return nil}diff --git a/backend/pkg/utils/notifications/discord_sender.go b/backend/pkg/utils/notifications/discord_sender.goindex 0face41c8..ff036432c 100644--- a/backend/pkg/utils/notifications/discord_sender.go+++ b/backend/pkg/utils/notifications/discord_sender.go@@ -2,8 +2,9 @@ package notificationsimport ("context"+ "errors"+ "fmt"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord")@@ -31,7 +32,7 @@ func SendDiscord(ctx context.Context, config DiscordConfig, message string) erroshoutrrrURL, err := BuildDiscordURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Discord URL")+ return fmt.Errorf("failed to build shoutrrr Discord URL: %w", err)}return sendShoutrrrInternal("Discord", shoutrrrURL, message, nil)diff --git a/backend/pkg/utils/notifications/email_sender.go b/backend/pkg/utils/notifications/email_sender.goindex b924aa48d..d092e35c1 100644--- a/backend/pkg/utils/notifications/email_sender.go+++ b/backend/pkg/utils/notifications/email_sender.go@@ -3,9 +3,10 @@ package notificationsimport ("context""crypto/tls"+ "errors"+ "fmt""time"- "emperror.dev/errors""github.com/wneessen/go-mail"kit "go.getarcane.app/kit/pkg")@@ -62,7 +63,7 @@ func buildMailClientInternal(config EmailConfig, options smtpBuildOptions) (*maireturn nil, errors.New("SMTP host is empty")}if config.SMTPPort < 1 || config.SMTPPort > 65535 {- return nil, errors.Errorf("invalid SMTP port: %d", config.SMTPPort)+ return nil, fmt.Errorf("invalid SMTP port: %d", config.SMTPPort)}opts := []mail.Option{@@ -98,7 +99,7 @@ func buildMailClientInternal(config EmailConfig, options smtpBuildOptions) (*maiclient, err := mail.NewClient(config.SMTPHost, opts...)if err != nil {- return nil, errors.WrapIf(err, "failed to construct SMTP client")+ return nil, fmt.Errorf("failed to construct SMTP client: %w", err)}return client, nil@@ -114,7 +115,7 @@ func sendEmailInternal(ctx context.Context, config EmailConfig, subject, htmlBodreturn errors.New("email send context is required")}if err := ctx.Err(); err != nil {- return errors.WrapIf(err, "email send canceled")+ return fmt.Errorf("email send canceled: %w", err)}if config.FromAddress == "" {@@ -126,21 +127,21 @@ func sendEmailInternal(ctx context.Context, config EmailConfig, subject, htmlBodclient, err := buildMailClientInternal(config, options)if err != nil {- return errors.WrapIf(err, "failed to build SMTP client")+ return fmt.Errorf("failed to build SMTP client: %w", err)}msg := mail.NewMsg()if err := msg.From(config.FromAddress); err != nil {- return errors.WrapIff(err, "invalid from address %q", config.FromAddress)+ return fmt.Errorf("invalid from address %q: %w", config.FromAddress, err)}if err := msg.To(config.ToAddresses...); err != nil {- return errors.WrapIf(err, "invalid recipient address(es)")+ return fmt.Errorf("invalid recipient address(es): %w", err)}msg.Subject(subject)msg.SetBodyString(mail.TypeTextHTML, htmlBody)if err := client.DialAndSendWithContext(ctx, msg); err != nil {- return errors.WrapIf(err, "failed to send email")+ return fmt.Errorf("failed to send email: %w", err)}return nildiff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.goindex 5f6081d4c..52c957213 100644--- a/backend/pkg/utils/notifications/generic_sender.go+++ b/backend/pkg/utils/notifications/generic_sender.go@@ -6,6 +6,7 @@ import ("context""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""net/http"@@ -14,7 +15,6 @@ import ("text/template""time"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"kit "go.getarcane.app/kit/pkg"@@ -41,7 +41,7 @@ func resolveWebhookURLInternal(config GenericConfig) (*url.URL, error) {parsed, err := url.Parse(config.WebhookURL)if err != nil {- return nil, errors.WrapIf(err, "invalid webhook URL")+ return nil, fmt.Errorf("invalid webhook URL: %w", err)}hasScheme := strings.Contains(config.WebhookURL, "://")@@ -50,7 +50,7 @@ func resolveWebhookURLInternal(config GenericConfig) (*url.URL, error) {normalized := strings.TrimPrefix(config.WebhookURL, "//")parsed, err = url.Parse(fmt.Sprintf("%s://%s", scheme, normalized))if err != nil {- return nil, errors.WrapIf(err, "invalid webhook URL")+ return nil, fmt.Errorf("invalid webhook URL: %w", err)}}@@ -61,7 +61,7 @@ func resolveWebhookURLInternal(config GenericConfig) (*url.URL, error) {switch strings.ToLower(parsed.Scheme) {case "http", "https":default:- return nil, errors.Errorf("invalid webhook URL scheme: %s", parsed.Scheme)+ return nil, fmt.Errorf("invalid webhook URL scheme: %s", parsed.Scheme)}return parsed, nil@@ -193,12 +193,12 @@ func genericTemplateDataInternal(config GenericConfig, title, message string, vafunc RenderGenericPayloadTemplate(config GenericConfig, title, message string, vars map[string]string) (string, error) {tmpl, err := template.New(genericPayloadTemplateID).Parse(config.PayloadTemplate)if err != nil {- return "", errors.WrapIf(err, "invalid webhook payload template")+ return "", fmt.Errorf("invalid webhook payload template: %w", err)}var rendered bytes.Bufferif err := tmpl.Execute(&rendered, genericTemplateDataInternal(config, title, message, vars)); err != nil {- return "", errors.WrapIf(err, "failed to render webhook payload template")+ return "", fmt.Errorf("failed to render webhook payload template: %w", err)}return rendered.String(), nil}@@ -256,7 +256,7 @@ func SendGenericWithTitle(ctx context.Context, config GenericConfig, title, messshoutrrrURL, err := BuildGenericURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Generic URL")+ return fmt.Errorf("failed to build shoutrrr Generic URL: %w", err)}senderOptions := shoutrrrTypes.SenderOptions{HTTPClient: genericHTTPClient}@@ -274,7 +274,7 @@ func SendGenericWithTitle(ctx context.Context, config GenericConfig, title, messsender, err := shoutrrr.CreateSenderWithOptions(senderOptions, shoutrrrURL)if err != nil {- return errors.WrapIf(err, "failed to create shoutrrr Generic sender")+ return fmt.Errorf("failed to create shoutrrr Generic sender: %w", err)}// Build params with title. Always use "title" as the param key — Shoutrrr's@@ -285,7 +285,7 @@ func SendGenericWithTitle(ctx context.Context, config GenericConfig, title, messerrs := sender.Send(message, ¶ms)for _, err := range errs {if err != nil {- return errors.WrapIf(err, "failed to send Generic webhook message with title via shoutrrr")+ return fmt.Errorf("failed to send Generic webhook message with title via shoutrrr: %w", err)}}return nil@@ -315,16 +315,16 @@ func effectiveGenericTemplateIDInternal(shoutrrrURL string) string {func sendGenericTemplatedInternal(config GenericConfig, shoutrrrURL, templateID string, opts shoutrrrTypes.SenderOptions, title, message string, vars map[string]string) error {sender, err := shoutrrr.CreateSenderWithOptions(opts)if err != nil {- return errors.WrapIf(err, "failed to create shoutrrr Generic sender")+ return fmt.Errorf("failed to create shoutrrr Generic sender: %w", err)}service, err := sender.Locate(shoutrrrURL)if err != nil {- return errors.WrapIf(err, "failed to initialize shoutrrr Generic service")+ return fmt.Errorf("failed to initialize shoutrrr Generic service: %w", err)}if err := service.SetTemplateString(templateID, config.PayloadTemplate); err != nil {- return errors.WrapIf(err, "invalid webhook payload template")+ return fmt.Errorf("invalid webhook payload template: %w", err)}// Shoutrrr renders the registered template over the send params, remapping@@ -338,7 +338,7 @@ func sendGenericTemplatedInternal(config GenericConfig, shoutrrrURL, templateID}if err := service.Send(jsonEscapeString(message), ¶ms); err != nil {- return errors.WrapIf(err, "failed to send Generic webhook message via shoutrrr")+ return fmt.Errorf("failed to send Generic webhook message via shoutrrr: %w", err)}return nil}@@ -370,7 +370,7 @@ func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title,body, err = json.Marshal(payload)if err != nil {- return errors.WrapIf(err, "failed to marshal webhook payload")+ return fmt.Errorf("failed to marshal webhook payload: %w", err)}}@@ -378,7 +378,7 @@ func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title,req, err := http.NewRequestWithContext(ctx, method, webhookURL.String(), bytes.NewReader(body))if err != nil {- return errors.WrapIf(err, "failed to create webhook request")+ return fmt.Errorf("failed to create webhook request: %w", err)}contentType := cmp.Or(config.ContentType, "application/json")@@ -390,21 +390,21 @@ func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title,resp, err := genericHTTPClient.Do(req)if err != nil {- return errors.WrapIf(err, "failed to send webhook request")+ return fmt.Errorf("failed to send webhook request: %w", err)}defer func() { _ = resp.Body.Close() }()respBody, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read webhook response body")+ return fmt.Errorf("failed to read webhook response body: %w", err)}if resp.StatusCode >= http.StatusBadRequest {- return errors.Errorf("webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))+ return fmt.Errorf("webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))}if !strings.Contains(string(respBody), config.SuccessBodyContains) {- return errors.Errorf("webhook response did not contain expected success indicator %q: %s", config.SuccessBodyContains, string(respBody))+ return fmt.Errorf("webhook response did not contain expected success indicator %q: %s", config.SuccessBodyContains, string(respBody))}return nildiff --git a/backend/pkg/utils/notifications/googlechat_sender.go b/backend/pkg/utils/notifications/googlechat_sender.goindex 0523f86c8..df8bf7208 100644--- a/backend/pkg/utils/notifications/googlechat_sender.go+++ b/backend/pkg/utils/notifications/googlechat_sender.go@@ -2,10 +2,11 @@ package notificationsimport ("context"+ "errors"+ "fmt""net/url""strings"- "emperror.dev/errors"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -19,7 +20,7 @@ func BuildGoogleChatURL(config GoogleChatConfig) (string, error) {parsed, err := url.Parse(config.WebhookURL)if err != nil {- return "", errors.WrapIf(err, "invalid google chat webhook URL")+ return "", fmt.Errorf("invalid google chat webhook URL: %w", err)}// Accept a bare host without scheme, mirroring the generic webhook's URL@@ -28,7 +29,7 @@ func BuildGoogleChatURL(config GoogleChatConfig) (string, error) {normalized := strings.TrimPrefix(config.WebhookURL, "//")parsed, err = url.Parse("https://" + normalized)if err != nil {- return "", errors.WrapIf(err, "invalid google chat webhook URL")+ return "", fmt.Errorf("invalid google chat webhook URL: %w", err)}}@@ -39,7 +40,7 @@ func BuildGoogleChatURL(config GoogleChatConfig) (string, error) {switch strings.ToLower(parsed.Scheme) {case "http", "https":default:- return "", errors.Errorf("invalid google chat webhook URL scheme: %s", parsed.Scheme)+ return "", fmt.Errorf("invalid google chat webhook URL scheme: %s", parsed.Scheme)}shoutrrrURL := &url.URL{@@ -58,7 +59,7 @@ func BuildGoogleChatURL(config GoogleChatConfig) (string, error) {func SendGoogleChat(ctx context.Context, config GoogleChatConfig, message string) error {shoutrrrURL, err := BuildGoogleChatURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Google Chat URL")+ return fmt.Errorf("failed to build shoutrrr Google Chat URL: %w", err)}return sendShoutrrrInternal("Google Chat", shoutrrrURL, message, &shoutrrrTypes.Params{})diff --git a/backend/pkg/utils/notifications/gotify_sender.go b/backend/pkg/utils/notifications/gotify_sender.goindex 85e5d5996..61324263b 100644--- a/backend/pkg/utils/notifications/gotify_sender.go+++ b/backend/pkg/utils/notifications/gotify_sender.go@@ -2,12 +2,12 @@ package notificationsimport ("context"+ "errors""fmt""net/url""strconv""strings"- "emperror.dev/errors"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -65,7 +65,7 @@ func BuildGotifyURL(config GotifyConfig) (string, error) {func SendGotify(ctx context.Context, config GotifyConfig, message string) error {shoutrrrURL, err := BuildGotifyURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Gotify URL")+ return fmt.Errorf("failed to build shoutrrr Gotify URL: %w", err)}return sendShoutrrrInternal("Gotify", shoutrrrURL, message, &shoutrrrTypes.Params{})diff --git a/backend/pkg/utils/notifications/matrix_sender.go b/backend/pkg/utils/notifications/matrix_sender.goindex 6f7adb38c..195308926 100644--- a/backend/pkg/utils/notifications/matrix_sender.go+++ b/backend/pkg/utils/notifications/matrix_sender.go@@ -2,11 +2,11 @@ package notificationsimport ("context"+ "errors""fmt""net/url""strings"- "emperror.dev/errors"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -58,7 +58,7 @@ func BuildMatrixURL(config MatrixConfig) (string, error) {func SendMatrix(ctx context.Context, config MatrixConfig, message string) error {shoutrrrURL, err := BuildMatrixURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Matrix URL")+ return fmt.Errorf("failed to build shoutrrr Matrix URL: %w", err)}return sendShoutrrrInternal("Matrix", shoutrrrURL, message, &shoutrrrTypes.Params{})diff --git a/backend/pkg/utils/notifications/ntfy_sender.go b/backend/pkg/utils/notifications/ntfy_sender.goindex 9c33cbc20..1bf56df45 100644--- a/backend/pkg/utils/notifications/ntfy_sender.go+++ b/backend/pkg/utils/notifications/ntfy_sender.go@@ -3,11 +3,11 @@ package notificationsimport ("cmp""context"+ "errors""fmt""net/url""strings"- "emperror.dev/errors"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -93,7 +93,7 @@ func SendNtfy(ctx context.Context, config NtfyConfig, message string) error {shoutrrrURL, err := BuildNtfyURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Ntfy URL")+ return fmt.Errorf("failed to build shoutrrr Ntfy URL: %w", err)}return sendShoutrrrInternal("Ntfy", shoutrrrURL, message, &shoutrrrTypes.Params{})diff --git a/backend/pkg/utils/notifications/pushover_sender.go b/backend/pkg/utils/notifications/pushover_sender.goindex 47ab6645e..d1e4b7ae5 100644--- a/backend/pkg/utils/notifications/pushover_sender.go+++ b/backend/pkg/utils/notifications/pushover_sender.go@@ -2,11 +2,11 @@ package notificationsimport ("context"+ "errors"+ "fmt""net/url""strconv""strings"-- "emperror.dev/errors")// BuildPushoverURL converts PushoverConfig to Shoutrrr URL format.@@ -67,7 +67,7 @@ func SendPushover(ctx context.Context, config PushoverConfig, message string) ershoutrrrURL, err := BuildPushoverURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Pushover URL")+ return fmt.Errorf("failed to build shoutrrr Pushover URL: %w", err)}return sendShoutrrrInternal("Pushover", shoutrrrURL, message, nil)diff --git a/backend/pkg/utils/notifications/signal_sender.go b/backend/pkg/utils/notifications/signal_sender.goindex 2a8bad9eb..1d4ce2bea 100644--- a/backend/pkg/utils/notifications/signal_sender.go+++ b/backend/pkg/utils/notifications/signal_sender.go@@ -2,8 +2,9 @@ package notificationsimport ("context"+ "errors"+ "fmt"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/signal")@@ -51,7 +52,7 @@ func SendSignal(ctx context.Context, config SignalConfig, message string) errorshoutrrrURL, err := BuildSignalURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Signal URL")+ return fmt.Errorf("failed to build shoutrrr Signal URL: %w", err)}return sendShoutrrrInternal("Signal", shoutrrrURL, message, nil)diff --git a/backend/pkg/utils/notifications/slack_sender.go b/backend/pkg/utils/notifications/slack_sender.goindex 46c2c14f7..baaaeb48c 100644--- a/backend/pkg/utils/notifications/slack_sender.go+++ b/backend/pkg/utils/notifications/slack_sender.go@@ -2,8 +2,9 @@ package notificationsimport ("context"+ "errors"+ "fmt"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/slack")@@ -16,7 +17,7 @@ func BuildSlackURL(config SlackConfig) (string, error) {// Parse the token to get the token objecttoken, err := slack.ParseToken(config.Token)if err != nil {- return "", errors.WrapIf(err, "invalid Slack token format (expected format: xoxb-... or xoxp-...)")+ return "", fmt.Errorf("invalid Slack token format (expected format: xoxb-... or xoxp-...): %w", err)}slackConfig := &slack.Config{@@ -41,7 +42,7 @@ func SendSlack(ctx context.Context, config SlackConfig, message string) error {shoutrrrURL, err := BuildSlackURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Slack URL")+ return fmt.Errorf("failed to build shoutrrr Slack URL: %w", err)}return sendShoutrrrInternal("Slack", shoutrrrURL, message, nil)diff --git a/backend/pkg/utils/notifications/telegram_sender.go b/backend/pkg/utils/notifications/telegram_sender.goindex df878205c..828fb9893 100644--- a/backend/pkg/utils/notifications/telegram_sender.go+++ b/backend/pkg/utils/notifications/telegram_sender.go@@ -2,8 +2,9 @@ package notificationsimport ("context"+ "errors"+ "fmt"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/telegram")@@ -28,7 +29,7 @@ func BuildTelegramURL(config TelegramConfig) (string, error) {q.Set("parsemode", config.ParseMode)url.RawQuery = q.Encode()default:- return "", errors.Errorf("invalid parse mode: %s (must be Markdown, HTML, MarkdownV2, or None)", config.ParseMode)+ return "", fmt.Errorf("invalid parse mode: %s (must be Markdown, HTML, MarkdownV2, or None)", config.ParseMode)}}@@ -46,7 +47,7 @@ func SendTelegram(ctx context.Context, config TelegramConfig, message string) ershoutrrrURL, err := BuildTelegramURL(config)if err != nil {- return errors.WrapIf(err, "failed to build shoutrrr Telegram URL")+ return fmt.Errorf("failed to build shoutrrr Telegram URL: %w", err)}return sendShoutrrrInternal("Telegram", shoutrrrURL, message, nil)diff --git a/backend/pkg/utils/notifications/utils.go b/backend/pkg/utils/notifications/utils.goindex f27b3f3c0..0a9b474d7 100644--- a/backend/pkg/utils/notifications/utils.go+++ b/backend/pkg/utils/notifications/utils.go@@ -1,9 +1,9 @@package notificationsimport (+ "fmt""strings"- "emperror.dev/errors""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -22,11 +22,11 @@ func SanitizeForEmail(text string) string {func sendShoutrrrInternal(provider, destinationURL, message string, params *shoutrrrTypes.Params) error {sender, err := shoutrrr.CreateSenderWithOptions(shoutrrrTypes.SenderOptions{}, destinationURL)if err != nil {- return errors.WrapIff(err, "failed to create shoutrrr %s sender", provider)+ return fmt.Errorf("failed to create shoutrrr %s sender: %w", provider, err)}for _, err := range sender.Send(message, params) {if err != nil {- return errors.WrapIff(err, "failed to send %s message via shoutrrr", provider)+ return fmt.Errorf("failed to send %s message via shoutrrr: %w", provider, err)}}return nildiff --git a/backend/pkg/utils/oidcjwk/keyset.go b/backend/pkg/utils/oidcjwk/keyset.goindex 3eb6f599b..6543277a0 100644--- a/backend/pkg/utils/oidcjwk/keyset.go+++ b/backend/pkg/utils/oidcjwk/keyset.go@@ -2,11 +2,12 @@ package oidcjwkimport ("context"+ "errors"+ "fmt""slices""sync/atomic""time"- "emperror.dev/errors""github.com/jwx-go/jwkfetch/v4""github.com/lestrrat-go/jwx/v4/jwk""github.com/lestrrat-go/jwx/v4/jws"@@ -15,7 +16,7 @@ import (const forcedRefreshInterval = 30 * time.Second-var errForcedRefreshThrottled = errors.Sentinel("oidcjwk: forced refresh throttled")+var errForcedRefreshThrottled = errors.New("oidcjwk: forced refresh throttled")type keySet struct {cache *jwkfetch.Cache@@ -45,7 +46,7 @@ func (k *keySet) VerifySignature(ctx context.Context, rawToken string) ([]byte,defer cancel()_, refreshErr := k.cache.Refresh(refreshCtx, k.jwksURL)if refreshErr != nil {- return nil, errors.WrapIf(refreshErr, "failed to refresh JWKS")+ return nil, fmt.Errorf("failed to refresh JWKS: %w", refreshErr)}return nil, nil})@@ -92,7 +93,7 @@ func (k *keySet) reserveForcedRefreshInternal(now time.Time) bool {func validateTokenAlgorithmInternal(rawToken string) error {message, err := jws.Parse([]byte(rawToken), jws.WithCompact())if err != nil {- return errors.WrapIf(err, "malformed JWT")+ return fmt.Errorf("malformed JWT: %w", err)}signatures := message.Signatures()if len(signatures) != 1 {diff --git a/backend/pkg/utils/oidcjwk/manager.go b/backend/pkg/utils/oidcjwk/manager.goindex ee96f7413..62c45b911 100644--- a/backend/pkg/utils/oidcjwk/manager.go+++ b/backend/pkg/utils/oidcjwk/manager.go@@ -2,13 +2,13 @@ package oidcjwkimport ("context"+ "errors""fmt""net/http""sync""sync/atomic""time"- "emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc""github.com/jwx-go/jwkfetch/v4""github.com/lestrrat-go/httprc/v3"@@ -26,7 +26,7 @@ const (maximumRefreshInterval = time.Hour)-var ErrManagerShutdown = errors.Sentinel("oidcjwk: key set manager is shut down")+var ErrManagerShutdown = errors.New("oidcjwk: key set manager is shut down")type managedCache struct {cache *jwkfetch.Cache@@ -144,7 +144,7 @@ func (m *managedCache) initializeKeySetInternal(ctx context.Context, jwksURL strjwkfetch.WithMinInterval(minimumRefreshInterval),jwkfetch.WithMaxInterval(maximumRefreshInterval),); registerErr != nil {- return nil, errors.WrapIf(registerErr, "failed to register JWKS URL")+ return nil, fmt.Errorf("failed to register JWKS URL: %w", registerErr)}// Refresh returns fetch and parse errors that the background readiness wait hides.if _, refreshErr := m.cache.Refresh(registerCtx, jwksURL); refreshErr != nil {@@ -153,7 +153,7 @@ func (m *managedCache) initializeKeySetInternal(ctx context.Context, jwksURL strset, setErr := m.cache.CachedSet(jwksURL)if setErr != nil {- return nil, errors.WrapIf(setErr, "failed to create cached JWK set")+ return nil, fmt.Errorf("failed to create cached JWK set: %w", setErr)}keySet := &keySet{cache: m.cache,@@ -177,7 +177,7 @@ func (m *KeySetManager) createManagedCacheLockedInternal(client *http.Client) (*),)if err != nil {- return nil, errors.WrapIf(err, "failed to create JWKS cache")+ return nil, fmt.Errorf("failed to create JWKS cache: %w", err)}managed := &managedCache{cache: cache, keySets: make(map[string]*keySet)}m.caches.Set(client, managed)@@ -207,5 +207,5 @@ func (m *KeySetManager) Shutdown(ctx context.Context) error {for _, cache := range caches {shutdownErrors = append(shutdownErrors, cache.Shutdown(ctx))}- return errors.Combine(shutdownErrors...)+ return errors.Join(shutdownErrors...)}diff --git a/backend/pkg/utils/recover.go b/backend/pkg/utils/recover.goindex fea0a0387..9c8eb820d 100644--- a/backend/pkg/utils/recover.go+++ b/backend/pkg/utils/recover.go@@ -1,10 +1,11 @@package utilsimport (+ "context"+ "errors"+ "fmt""log/slog"-- "emperror.dev/emperror"- "emperror.dev/errors"+ "sync")// RecoverToError converts a panic in the calling goroutine into an error and@@ -21,14 +22,47 @@ import (// report into (e.g. a fire-and-forget goroutine); the panic is still logged.// args are extra slog attributes appended to the log record.func RecoverToError(errPtr *error, label string, args ...any) {- panicErr := emperror.Recover(recover())+ panicErr := PanicToError(recover())if panicErr == nil {return}- err := errors.WrapIf(panicErr, label+" panicked")+ err := fmt.Errorf("%s: %w", label+" panicked", panicErr)slog.Error(label+" panicked", append([]any{"error", err}, args...)...)if errPtr != nil {*errPtr = err}}++// PanicToError converts a recovered panic value into an error.+func PanicToError(r any) error {+ switch value := r.(type) {+ case nil:+ return nil+ case error:+ return value+ case string:+ return errors.New(value)+ default:+ return fmt.Errorf("unknown panic, received: %v", r)+ }+}++// WaitGroup waits for all work or returns when ctx ends. After a timeout, its+// waiter goroutine remains until the group eventually completes.+func WaitGroup(ctx context.Context, group *sync.WaitGroup) error {+ if ctx == nil || group == nil {+ return errors.New("wait group context unavailable")+ }+ done := make(chan struct{})+ go func() {+ group.Wait()+ close(done)+ }()+ select {+ case <-done:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}diff --git a/backend/pkg/utils/s3/s3.go b/backend/pkg/utils/s3/s3.goindex 58d98aae1..95f2cd50c 100644--- a/backend/pkg/utils/s3/s3.go+++ b/backend/pkg/utils/s3/s3.go@@ -7,6 +7,7 @@ import ("bytes""cmp""context"+ "errors""fmt""io""net/url"@@ -15,7 +16,6 @@ import ("strings""uuid"- "emperror.dev/errors""github.com/aws/aws-sdk-go-v2/aws"awsconfig "github.com/aws/aws-sdk-go-v2/config""github.com/aws/aws-sdk-go-v2/credentials"@@ -185,7 +185,7 @@ func TestConnection(ctx context.Context, configuration Configuration) (err errorreturn}if cleanupErr := deleteObjectInternal(context.WithoutCancel(ctx), client, configuration.Bucket, remoteKey); cleanupErr != nil {- err = errors.Combine(err, fmt.Errorf("failed to clean up S3 connection test object: %w", cleanupErr))+ err = errors.Join(err, fmt.Errorf("failed to clean up S3 connection test object: %w", cleanupErr))}}()@@ -331,7 +331,7 @@ func getObjectInternal(ctx context.Context, client *awss3.Client, bucket, key stpayload, readErr := io.ReadAll(output.Body)closeErr := output.Body.Close()if readErr != nil {- return nil, errors.Combine(readErr, closeErr)+ return nil, errors.Join(readErr, closeErr)}if closeErr != nil {return nil, closeErrdiff --git a/backend/pkg/utils/update_value_util.go b/backend/pkg/utils/update_value_util.goindex 9826ca5cb..a55702ebe 100644--- a/backend/pkg/utils/update_value_util.go+++ b/backend/pkg/utils/update_value_util.go@@ -1,9 +1,13 @@package utilsimport (+ "fmt"+ "log/slog"+ "os""slices"+ "strings"- "emperror.dev/errors"+ "github.com/go-webauthn/webauthn/protocol""github.com/samber/mo""go.getarcane.app/sys/crypto")@@ -60,8 +64,49 @@ func ApplyEncrypted(field *string, plaintext string) (bool, error) {}encrypted, err := crypto.Encrypt(plaintext)if err != nil {- return false, errors.WrapIf(err, "failed to encrypt credential")+ return false, fmt.Errorf("failed to encrypt credential: %w", err)}*field = encryptedreturn true, nil}++// LookupEnvOrFile is os.LookupEnv with Docker secret support: when NAME__FILE+// or NAME_FILE (checked in that order) names a readable file, its trimmed+// contents stand in for NAME. An unreadable file falls back to NAME.+// The booleans report whether a value was found and whether it came from a file.+func LookupEnvOrFile(name string) (value string, found, fromFile bool) {+ for _, suffix := range []string{"__FILE", "_FILE"} {+ filePath := os.Getenv(name + suffix)+ if filePath == "" {+ continue+ }++ // Secret paths are arbitrary host paths, so there is no acfs root to confine them to.+ content, err := os.ReadFile(filePath) //nolint:gosec // path intentionally comes from a *_FILE env var+ if err != nil {+ slog.Warn("Failed to read secret file, falling back to direct env var", "env", name+suffix, "error", err)+ break+ }++ return strings.TrimSpace(string(content)), true, true+ }++ value, found = os.LookupEnv(name)+ return value, found, false+}++// NormalizePasskeyAssertionExtensions drops an unrequested appid=false output, which Safari+// reports even though it means the legacy AppID was not used.+func NormalizePasskeyAssertionExtensions(session protocol.SessionExtensions, assertion *protocol.ParsedCredentialAssertionData) {+ if assertion == nil {+ return+ }+ appID := assertion.ClientExtensionResults.AppID+ if appID == nil || *appID {+ return+ }+ if session.AppID != "" || slices.Contains(session.Requested, protocol.ExtensionAppID) {+ return+ }+ assertion.ClientExtensionResults.AppID = nil+}diff --git a/backend/pkg/utils/validation/credential_target.go b/backend/pkg/utils/validation/credential_target.godeleted file mode 100644index 335f3836d..000000000--- a/backend/pkg/utils/validation/credential_target.go+++ /dev/null@@ -1,58 +0,0 @@-package validation--import (- "fmt"- "net/http"- "slices"- "strings"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-)--// ValidateCredentialTargetChange prevents stored credentials from being reused-// against a changed target unless the update explicitly handles them.-func ValidateCredentialTargetChange(- targetName string,- currentTarget string,- nextTarget *string,- normalize func(string) string,- storedCredentials map[string]bool,- updatedCredentials map[string]bool,-) error {- if nextTarget == nil {- return nil- }- if strings.TrimSpace(*nextTarget) == "" {- return nil- }-- if normalize == nil {- normalize = func(value string) string { return value }- }- if normalize(currentTarget) == normalize(*nextTarget) {- return nil- }-- missingFields := make([]string, 0, len(storedCredentials))- for field, stored := range storedCredentials {- if stored && !updatedCredentials[field] {- missingFields = append(missingFields, field)- }- }- if len(missingFields) == 0 {- return nil- }-- slices.Sort(missingFields)- if len(missingFields) == 1 {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Changing %s requires re-entering the %s", targetName, missingFields[0]), "field", missingFields[0]))- }-- return common.NewAPIErrorWithDetails(- fmt.Sprintf("Changing %s requires updating all stored credentials", targetName),- common.APIErrorCodeValidationError,- http.StatusBadRequest,- map[string]any{"fields": missingFields},- )-}diff --git a/backend/pkg/utils/validation/credential_target_test.go b/backend/pkg/utils/validation/credential_target_test.goindex e2e163d92..686db42c9 100644--- a/backend/pkg/utils/validation/credential_target_test.go+++ b/backend/pkg/utils/validation/credential_target_test.go@@ -1,11 +1,12 @@package validationimport (+ "errors""strings""testing"- "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/types/v2/base""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -98,7 +99,9 @@ func TestValidateCredentialTargetChange(t *testing.T) {switch {case tt.wantField != "":require.ErrorIs(t, err, common.ErrValidation)- assert.Contains(t, errors.GetDetails(err), tt.wantField)+ fieldErr, ok := errors.AsType[*base.FieldError](err)+ require.True(t, ok)+ assert.Equal(t, tt.wantField, fieldErr.Field)assert.Equal(t, "Changing credential target requires re-entering the token", err.Error())case len(tt.wantFields) > 0:var apiErr *common.APIErrordiff --git a/backend/pkg/utils/validation/email.go b/backend/pkg/utils/validation/email.goindex 3c6172abd..c6b7d744b 100644--- a/backend/pkg/utils/validation/email.go+++ b/backend/pkg/utils/validation/email.go@@ -8,7 +8,7 @@ import ("golang.org/x/net/idna")-var localPartPattern = regexp.MustCompile(`^[A-Za-z0-9!#$%&'*+/=?^_` + "`" + `{|}~.-]+$`)+var localPartPattern = regexp.MustCompile("^[A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+$")func IsValidUserEmail(email string) bool {trimmedEmail := strings.TrimSpace(email)diff --git a/backend/pkg/utils/validation/password.go b/backend/pkg/utils/validation/password.goindex 34c7aeb57..e478594f1 100644--- a/backend/pkg/utils/validation/password.go+++ b/backend/pkg/utils/validation/password.go@@ -1,9 +1,15 @@package validationimport (+ "errors"+ "fmt"+ "net/http"+ "slices"+ "strings""unicode"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/types/v2/base")const (@@ -60,3 +66,50 @@ func ValidatePasswordPolicy(password, policy string) error {}return nil}++// ValidateCredentialTargetChange prevents stored credentials from being reused+// against a changed target unless the update explicitly handles them.+func ValidateCredentialTargetChange(+ targetName string,+ currentTarget string,+ nextTarget *string,+ normalize func(string) string,+ storedCredentials map[string]bool,+ updatedCredentials map[string]bool,+) error {+ if nextTarget == nil {+ return nil+ }+ if strings.TrimSpace(*nextTarget) == "" {+ return nil+ }++ if normalize == nil {+ normalize = func(value string) string { return value }+ }+ if normalize(currentTarget) == normalize(*nextTarget) {+ return nil+ }++ missingFields := make([]string, 0, len(storedCredentials))+ for field, stored := range storedCredentials {+ if stored && !updatedCredentials[field] {+ missingFields = append(missingFields, field)+ }+ }+ if len(missingFields) == 0 {+ return nil+ }++ slices.Sort(missingFields)+ if len(missingFields) == 1 {+ return common.Classify(common.ErrValidation, &base.FieldError{Field: missingFields[0], Err: fmt.Errorf("Changing %s requires re-entering the %s", targetName, missingFields[0])}) //nolint:staticcheck // Preserve the existing error message.+ }++ return common.NewAPIErrorWithDetails(+ fmt.Sprintf("Changing %s requires updating all stored credentials", targetName),+ common.APIErrorCodeValidationError,+ http.StatusBadRequest,+ map[string]any{"fields": missingFields},+ )+}diff --git a/backend/pkg/utils/waitgroup.go b/backend/pkg/utils/waitgroup.godeleted file mode 100644index 29ce376e9..000000000--- a/backend/pkg/utils/waitgroup.go+++ /dev/null@@ -1,27 +0,0 @@-package utils--import (- "context"- "sync"-- "emperror.dev/errors"-)--// WaitGroup waits for all work or returns when ctx ends. After a timeout, its-// waiter goroutine remains until the group eventually completes.-func WaitGroup(ctx context.Context, group *sync.WaitGroup) error {- if ctx == nil || group == nil {- return errors.New("wait group context unavailable")- }- done := make(chan struct{})- go func() {- group.Wait()- close(done)- }()- select {- case <-done:- return nil- case <-ctx.Done():- return ctx.Err()- }-}diff --git a/backend/pkg/utils/webauthn.go b/backend/pkg/utils/webauthn.godeleted file mode 100644index 4f7cd2389..000000000--- a/backend/pkg/utils/webauthn.go+++ /dev/null@@ -1,23 +0,0 @@-package utils--import (- "slices"-- "github.com/go-webauthn/webauthn/protocol"-)--// NormalizePasskeyAssertionExtensions drops an unrequested appid=false output, which Safari-// reports even though it means the legacy AppID was not used.-func NormalizePasskeyAssertionExtensions(session protocol.SessionExtensions, assertion *protocol.ParsedCredentialAssertionData) {- if assertion == nil {- return- }- appID := assertion.ClientExtensionResults.AppID- if appID == nil || *appID {- return- }- if session.AppID != "" || slices.Contains(session.Requested, protocol.ExtensionAppID) {- return- }- assertion.ClientExtensionResults.AppID = nil-}diff --git a/backend/pkg/workspace/workspace.go b/backend/pkg/workspace/workspace.goindex 134edc9f4..9bfd86f20 100644--- a/backend/pkg/workspace/workspace.go+++ b/backend/pkg/workspace/workspace.go@@ -2,10 +2,11 @@ package workspaceimport ("bytes"+ "errors"+ "fmt""strings""unicode/utf8"- "emperror.dev/errors"kit "go.getarcane.app/kit/pkg")@@ -30,7 +31,7 @@ func ValidateUpdateManifest(fileTreeRevision string, fileChangeCount, maxFileChareturn errors.New("workspace revision is required")}if fileChangeCount == 0 || fileChangeCount > maxFileChanges {- return errors.Errorf("fileChanges must contain between 1 and %d changes", maxFileChanges)+ return fmt.Errorf("fileChanges must contain between 1 and %d changes", maxFileChanges)}return nil}@@ -39,7 +40,7 @@ func ValidateUpdateManifest(fileTreeRevision string, fileChangeCount, maxFileCha// may be any bytes: text and binary files are both allowed.func ValidateContentSize(content []byte, maxBytes int64) error {if int64(len(content)) > maxBytes {- return errors.Errorf("file exceeds %d MiB limit", maxBytes/(1024*1024))+ return fmt.Errorf("file exceeds %d MiB limit", maxBytes/(1024*1024))}return nil}@@ -53,20 +54,20 @@ func ValidateUploadIndices(changes []UploadReference, uploadCount int, createFilfor _, change := range changes {requiresUpload := change.Operation == createFileOperation || change.Operation == updateFileOperationif requiresUpload && change.UploadIndex == nil {- return errors.Errorf("uploadIndex is required for %s", change.Operation)+ return fmt.Errorf("uploadIndex is required for %s", change.Operation)}if !requiresUpload && change.UploadIndex != nil {- return errors.Errorf("uploadIndex is not allowed for %s", change.Operation)+ return fmt.Errorf("uploadIndex is not allowed for %s", change.Operation)}if change.UploadIndex == nil {continue}index := *change.UploadIndexif index < 0 || index >= uploadCount {- return errors.Errorf("uploadIndex %d is out of range", index)+ return fmt.Errorf("uploadIndex %d is out of range", index)}if _, exists := used[index]; exists {- return errors.Errorf("uploadIndex %d is duplicated", index)+ return fmt.Errorf("uploadIndex %d is duplicated", index)}used[index] = struct{}{}}@@ -75,14 +76,14 @@ func ValidateUploadIndices(changes []UploadReference, uploadCount int, createFilcontinue}if change.Operation != updateFileOperation {- return errors.Errorf("baselineIndex is not allowed for %s", change.Operation)+ return fmt.Errorf("baselineIndex is not allowed for %s", change.Operation)}index := *change.BaselineIndexif index < 0 || index >= uploadCount {- return errors.Errorf("baselineIndex %d is out of range", index)+ return fmt.Errorf("baselineIndex %d is out of range", index)}if _, exists := used[index]; exists {- return errors.Errorf("baselineIndex %d is duplicated", index)+ return fmt.Errorf("baselineIndex %d is duplicated", index)}used[index] = struct{}{}}diff --git a/cli/go.mod b/cli/go.modindex b5fc6a590..7526d25d0 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -10,7 +10,6 @@ require (charm.land/fang/v2 v2.0.1charm.land/lipgloss/v2 v2.0.6charm.land/log/v2 v2.0.1- emperror.dev/errors v0.8.1github.com/charmbracelet/x/term v0.2.2github.com/getarcaneapp/arcane/types/v2 v2.14.0github.com/go-viper/mapstructure/v2 v2.5.0@@ -67,7 +66,6 @@ require (github.com/opencontainers/go-digest v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.1.1 // indirectgithub.com/pelletier/go-toml/v2 v2.4.3 // indirect- github.com/pkg/errors v0.9.1 // indirectgithub.com/prometheus/client_golang v1.24.1 // indirectgithub.com/prometheus/client_model v0.6.3 // indirectgithub.com/prometheus/common v0.71.0 // indirect@@ -89,7 +87,6 @@ require (go.opentelemetry.io/otel v1.46.0 // indirectgo.opentelemetry.io/otel/metric v1.46.0 // indirectgo.opentelemetry.io/otel/trace v1.46.0 // indirect- go.uber.org/multierr v1.11.0 // indirectgo.yaml.in/yaml/v3 v3.0.5 // indirectgo.yaml.in/yaml/v4 v4.0.0-rc.6 // indirectgolang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirectdiff --git a/cli/go.sum b/cli/go.sumindex 1456f2d1c..4446cca65 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -8,8 +8,6 @@ charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=charm.land/log/v2 v2.0.1 h1:uMk+t1hM/fomIqt7vn/Ub0AKo7IHvnDu6NK17nbOVx0=charm.land/log/v2 v2.0.1/go.mod h1:VXZNB8zoPPEIcvd7bRi2fpQpGCWweCSfWOwczA9dibs=-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=@@ -51,8 +49,6 @@ 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/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M=@@ -119,9 +115,6 @@ 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.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=github.com/pelletier/go-toml/v2 v2.4.3/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/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=@@ -156,8 +149,6 @@ 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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=@@ -188,12 +179,8 @@ go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=-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.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.goindex 5958a4354..c63e3f30d 100644--- a/cli/internal/ci/ci_detect.go+++ b/cli/internal/ci/ci_detect.go@@ -3,13 +3,14 @@ package ciimport ("context""encoding/json/v2"+ "errors"+ "fmt""io""net/http""net/url""strings""time"- "emperror.dev/errors"kit "go.getarcane.app/kit/pkg")@@ -54,7 +55,7 @@ func DetectToken(ctx context.Context, provider, audience string, getenv func(strcase ProviderGeneric:return "", "", errors.New("generic provider requires --token, --token-file, or --token-stdin")default:- return "", "", errors.Errorf("unsupported federated provider %q", provider)+ return "", "", fmt.Errorf("unsupported federated provider %q", provider)}}@@ -67,7 +68,7 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenvparsedURL, err := url.Parse(requestURL)if err != nil {- return "", errors.WrapIf(err, "invalid GitHub Actions OIDC request URL")+ return "", fmt.Errorf("invalid GitHub Actions OIDC request URL: %w", err)}if strings.TrimSpace(audience) != "" {q := parsedURL.Query()@@ -77,30 +78,30 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenvreq, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)if err != nil {- return "", errors.WrapIf(err, "failed to create GitHub Actions OIDC request")+ return "", fmt.Errorf("failed to create GitHub Actions OIDC request: %w", err)}req.Header.Set("Authorization", "Bearer "+requestToken)req.Header.Set("Accept", "application/json")resp, err := httpClient.Do(req)if err != nil {- return "", errors.WrapIf(err, "failed to request GitHub Actions OIDC token")+ return "", fmt.Errorf("failed to request GitHub Actions OIDC token: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))if err != nil {- return "", errors.WrapIf(err, "failed to read GitHub Actions OIDC response")+ return "", fmt.Errorf("failed to read GitHub Actions OIDC response: %w", err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", errors.Errorf("GitHub Actions OIDC request failed with status %d", resp.StatusCode)+ return "", fmt.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 "", errors.WrapIf(err, "failed to parse GitHub Actions OIDC response")+ return "", fmt.Errorf("failed to parse GitHub Actions OIDC response: %w", err)}token := strings.TrimSpace(payload.Value)if token == "" {diff --git a/cli/internal/client/client.go b/cli/internal/client/client.goindex 16c959710..9df4d92e2 100644--- a/cli/internal/client/client.go+++ b/cli/internal/client/client.go@@ -28,7 +28,8 @@ import ("context""encoding/json/jsontext""encoding/json/v2"- stderrors "errors"+ "errors"+ "fmt""io""maps""net"@@ -38,7 +39,6 @@ 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"@@ -88,7 +88,7 @@ func New(cfg *types.Config) (*Client, error) {}parsedURL, err := url.Parse(cfg.ServerURL)if err != nil {- return nil, errors.WrapIf(err, "invalid server_url")+ return nil, fmt.Errorf("invalid server_url: %w", err)}envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)@@ -115,7 +115,7 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {}parsedURL, err := url.Parse(cfg.ServerURL)if err != nil {- return nil, errors.WrapIf(err, "invalid server_url")+ return nil, fmt.Errorf("invalid server_url: %w", err)}envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)@@ -152,7 +152,7 @@ func newHTTPClientInternal() *http.Client {func NewFromConfig() (*Client, error) {cfg, err := config.Load()if err != nil {- return nil, errors.WrapIf(err, "failed to load config")+ return nil, fmt.Errorf("failed to load config: %w", err)}state := runstate.Get()if strings.TrimSpace(state.EnvOverride) != "" {@@ -177,7 +177,7 @@ func NewFromConfig() (*Client, error) {func NewFromConfigUnauthenticated() (*Client, error) {cfg, err := config.Load()if err != nil {- return nil, errors.WrapIf(err, "failed to load config")+ return nil, fmt.Errorf("failed to load config: %w", err)}state := runstate.Get()if strings.TrimSpace(state.EnvOverride) != "" {@@ -257,7 +257,7 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hea// Streaming bodies cannot be replayed, so skip auto-refresh.req, err := http.NewRequestWithContext(ctx, method, fullURL, v)if err != nil {- return nil, errors.WrapIf(err, "failed to create request")+ return nil, fmt.Errorf("failed to create request: %w", err)}c.applyAuth(req)req.Header.Set("Content-Type", "application/json")@@ -271,14 +271,14 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hearesp, 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, errors.WrapIf(err, "request failed")+ return nil, fmt.Errorf("request failed: %w", err)}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, errors.WrapIf(err, "failed to marshal request body")+ return nil, fmt.Errorf("failed to marshal request body: %w", err)}bodyBytes = jsonBody}@@ -299,7 +299,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, errors.WrapIf(err, "failed to create request")+ return nil, fmt.Errorf("failed to create request: %w", err)}c.applyAuth(req)@@ -314,7 +314,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, errors.WrapIf(err, "request failed")+ return nil, fmt.Errorf("request failed: %w", err)}logger.GetLogger().Debug("Raw response received", "method", method, "url", fullURL, "env_id", c.envID, "status", resp.Status, "duration", time.Since(start).String())@@ -327,13 +327,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 "", errors.WrapIf(err, "invalid path")+ return "", fmt.Errorf("invalid path: %w", err)}return path, nil}rel, err := url.Parse(path)if err != nil {- return "", errors.WrapIf(err, "invalid path")+ return "", fmt.Errorf("invalid path: %w", err)}if c.baseURLParsed == nil {return "", errors.New("invalid base URL")@@ -352,7 +352,7 @@ func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string,req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)if err != nil {- return nil, errors.WrapIf(err, "failed to create request")+ return nil, fmt.Errorf("failed to create request: %w", err)}c.applyAuth(req)@@ -374,7 +374,7 @@ func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string,}continue}- return nil, errors.WrapIf(err, "request failed")+ return nil, fmt.Errorf("request failed: %w", err)}logger.GetLogger().Debug("Response received", "method", method, "url", fullURL, "env_id", c.envID, "attempt", attempt, "status", resp.Status, "duration", time.Since(start).String())@@ -401,7 +401,7 @@ func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string,return resp, nil}- return nil, errors.Errorf("request failed after %d attempts", attempts)+ return nil, fmt.Errorf("request failed after %d attempts", attempts)}func (c *Client) shouldRetry(method string, status int, err error) bool {@@ -417,7 +417,7 @@ func (c *Client) shouldRetry(method string, status int, err error) bool {return false}- if netErr, ok := stderrors.AsType[net.Error](err); ok {+ if netErr, ok := errors.AsType[net.Error](err); ok {return netErr.Timeout()}return true@@ -474,7 +474,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {bodyBytes, err := json.Marshal(map[string]string{"refreshToken": c.refreshToken})if err != nil {- return errors.WrapIf(err, "failed to marshal refresh request")+ return fmt.Errorf("failed to marshal refresh request: %w", err)}if c.baseURLParsed == nil {@@ -485,7 +485,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {req, err := http.NewRequestWithContext(ctx, http.MethodPost, refreshURL, bytes.NewReader(bodyBytes))if err != nil {- return errors.WrapIf(err, "failed to create refresh request")+ return fmt.Errorf("failed to create refresh request: %w", err)}req.Header.Set("Content-Type", "application/json")req.Header.Set("Accept", "application/json")@@ -494,23 +494,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 errors.WrapIf(err, "token refresh failed")+ return fmt.Errorf("token refresh failed: %w", err)}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 errors.WrapIf(err, "failed to read refresh response")+ return fmt.Errorf("failed to read refresh response: %w", err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return errors.Errorf("token refresh failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(respBody)))+ return fmt.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 errors.WrapIf(err, "failed to parse refresh response")+ return fmt.Errorf("failed to parse refresh response: %w", err)}if !result.Success || result.Data.Token == "" {return errors.New("token refresh failed: unexpected response from server")@@ -527,13 +527,13 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}cfg.JWTToken = result.Data.Tokencfg.APIKey = ""cfg.RefreshToken = newRefreshif err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save refreshed token")+ return fmt.Errorf("failed to save refreshed token: %w", err)}return nil@@ -583,11 +583,11 @@ func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body anif resp.StatusCode < 200 || resp.StatusCode >= 300 {b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))- return out, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ return out, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))}if err := json.UnmarshalRead(resp.Body, &out); err != nil {- return out, errors.WrapIf(err, "failed to decode response")+ return out, fmt.Errorf("failed to decode response: %w", err)}return out, nil}@@ -624,12 +624,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, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))}b, err := io.ReadAll(resp.Body)if err != nil {- return nil, errors.WrapIf(err, "failed to read response body")+ return nil, fmt.Errorf("failed to read response body: %w", err)}return b, nil}@@ -663,22 +663,22 @@ func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*APIResponfunc decodeResponseStrictInternal[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, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, errors.WrapIf(err, "failed to read response body")+ return nil, fmt.Errorf("failed to read response body: %w", err)}var result APIResponse[T]if err := json.Unmarshal(body, &result); err != nil {- return nil, errors.WrapIff(err, "failed to decode response (body: %s)", string(body))+ return nil, fmt.Errorf("failed to decode response (body: %s): %w", string(body), err)}if !result.Success {if strings.TrimSpace(result.Error) != "" {- return &result, errors.Errorf("API error: %s", result.Error)+ return &result, fmt.Errorf("API error: %s", result.Error)}return &result, errors.New("API error: request was not successful")}@@ -698,7 +698,7 @@ func (c *Client) TestConnection(ctx context.Context) error {if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(resp.Body)- return errors.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))+ return fmt.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.godeleted file mode 100644index 950ec0a74..000000000--- a/cli/internal/cmdutil/confirm.go+++ /dev/null@@ -1,31 +0,0 @@-package cmdutil--import (- "fmt"- "io"- "strings"-- "emperror.dev/errors"- "github.com/spf13/cobra"-)--// Confirm prompts the user unless --yes is enabled.-func Confirm(cmd *cobra.Command, prompt string) (bool, error) {- if AssumeYes(cmd) {- return true, nil- }-- fmt.Printf("%s (y/N): ", strings.TrimSpace(prompt))- var response string- if _, 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, errors.WrapIf(err, "failed to read confirmation input")- }-- switch strings.ToLower(strings.TrimSpace(response)) {- case "y", "yes":- return true, nil- default:- return false, nil- }-}diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.goindex 30028047e..e90952d64 100644--- a/cli/internal/cmdutil/context.go+++ b/cli/internal/cmdutil/context.go@@ -1,7 +1,11 @@package cmdutilimport (- "emperror.dev/errors"+ "errors"+ "fmt"+ "io"+ "strings"+"github.com/getarcaneapp/arcane/cli/v2/internal/client"runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime""github.com/spf13/cobra"@@ -54,3 +58,24 @@ func AssumeYes(cmd *cobra.Command) bool {}return false}++// Confirm prompts the user unless --yes is enabled.+func Confirm(cmd *cobra.Command, prompt string) (bool, error) {+ if AssumeYes(cmd) {+ return true, nil+ }++ fmt.Printf("%s (y/N): ", strings.TrimSpace(prompt))+ var response string+ if _, 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)+ }++ switch strings.ToLower(strings.TrimSpace(response)) {+ case "y", "yes":+ return true, nil+ default:+ return false, nil+ }+}diff --git a/cli/internal/cmdutil/limit.go b/cli/internal/cmdutil/limit.godeleted file mode 100644index f394cc44e..000000000--- a/cli/internal/cmdutil/limit.go+++ /dev/null@@ -1,46 +0,0 @@-package cmdutil--import (- "context"-- "github.com/getarcaneapp/arcane/cli/v2/internal/config"- runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"- clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"- "github.com/spf13/cobra"- kit "go.getarcane.app/kit/pkg"-)--// EffectiveLimit resolves the final list limit with precedence:-// explicit flag > per-resource config > global config > fallback default.-// A limit of ShowAllLimit is passed straight through so that `--limit -1`-// reaches the server as the documented "return everything" sentinel.-func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int {- if cmd != nil {- if flag := cmd.Flags().Lookup(flagName); flag != nil && flag.Changed {- return kit.Ternary(flagValue > 0 || flagValue == ShowAllLimit, flagValue, 0)- }- }-- resource = clitypes.NormalizePaginatedResource(resource)-- var ctx context.Context- if cmd != nil {- ctx = cmd.Context()- }- if app, ok := runtimectx.From(ctx); ok {- if cfg := app.Config(); cfg != nil {- if v := cfg.LimitFor(resource); v != 0 {- return v- }- }- } else if cfg, err := config.Load(); err == nil && cfg != nil {- if v := cfg.LimitFor(resource); v != 0 {- return v- }- }-- if fallbackDefault > 0 {- return fallbackDefault- }- return kit.Ternary(flagValue > 0, flagValue, 0)-}diff --git a/cli/internal/cmdutil/pagination.go b/cli/internal/cmdutil/pagination.goindex 0792db530..cf35d3ff3 100644--- a/cli/internal/cmdutil/pagination.go+++ b/cli/internal/cmdutil/pagination.go@@ -1,11 +1,17 @@package cmdutilimport (+ "context"+ "errors"+ "fmt""net/url""strconv"- "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/cli/v2/internal/config"+ runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"+ clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")const (@@ -63,7 +69,7 @@ type ListParams struct {func ApplyPaginationParams(cmd *cobra.Command, path string, p ListParams) (string, error) {parsed, err := url.Parse(path)if err != nil {- return "", errors.WrapIf(err, "failed to parse path")+ return "", fmt.Errorf("failed to parse path: %w", err)}query := parsed.Query()@@ -89,3 +95,38 @@ func ApplyPaginationParams(cmd *cobra.Command, path string, p ListParams) (strinparsed.RawQuery = query.Encode()return parsed.String(), nil}++// EffectiveLimit resolves the final list limit with precedence:+// explicit flag > per-resource config > global config > fallback default.+// A limit of ShowAllLimit is passed straight through so that `--limit -1`+// reaches the server as the documented "return everything" sentinel.+func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int {+ if cmd != nil {+ if flag := cmd.Flags().Lookup(flagName); flag != nil && flag.Changed {+ return kit.Ternary(flagValue > 0 || flagValue == ShowAllLimit, flagValue, 0)+ }+ }++ resource = clitypes.NormalizePaginatedResource(resource)++ var ctx context.Context+ if cmd != nil {+ ctx = cmd.Context()+ }+ if app, ok := runtimectx.From(ctx); ok {+ if cfg := app.Config(); cfg != nil {+ if v := cfg.LimitFor(resource); v != 0 {+ return v+ }+ }+ } else if cfg, err := config.Load(); err == nil && cfg != nil {+ if v := cfg.LimitFor(resource); v != 0 {+ return v+ }+ }++ if fallbackDefault > 0 {+ return fallbackDefault+ }+ return kit.Ternary(flagValue > 0, flagValue, 0)+}diff --git a/cli/internal/cmdutil/resolve.go b/cli/internal/cmdutil/resolve.goindex 8d37d70a3..498eaf75e 100644--- a/cli/internal/cmdutil/resolve.go+++ b/cli/internal/cmdutil/resolve.go@@ -9,7 +9,6 @@ import ("net/url""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/prompt""github.com/getarcaneapp/arcane/types/v2/base"@@ -69,7 +68,7 @@ type ResourceRef[D any, S any] struct {func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, bool, error) {trimmed := strings.TrimSpace(identifier)if trimmed == "" {- return nil, false, errors.Errorf("%s identifier is required", ref.Singular)+ return nil, false, fmt.Errorf("%s identifier is required", ref.Singular)}details, found, err := ref.fetchByIdentifierInternal(ctx, c, trimmed)@@ -128,25 +127,25 @@ func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, iden}}- return nil, false, errors.Errorf("%s %q not found; use %s or run `%s`", ref.Singular, trimmed, ref.IDHint, ref.ListCmd)+ return nil, false, fmt.Errorf("%s %q not found; use %s or run `%s`", ref.Singular, trimmed, ref.IDHint, ref.ListCmd)}func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *client.Client, identifier string) (*D, bool, error) {resp, err := c.Get(ctx, ref.GetPath(c.EnvID(), identifier))if err != nil {- return nil, false, errors.WrapIff(err, "failed to resolve %s %q", ref.Singular, identifier)+ return nil, false, fmt.Errorf("failed to resolve %s %q: %w", ref.Singular, identifier, err)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, false, errors.WrapIff(err, "failed to read %s response", ref.Singular)+ return nil, false, fmt.Errorf("failed to read %s response: %w", ref.Singular, err)}if resp.StatusCode == http.StatusOK {var result base.ApiResponse[D]if err := json.Unmarshal(body, &result); err != nil {- return nil, false, errors.WrapIff(err, "failed to parse %s response", ref.Singular)+ return nil, false, fmt.Errorf("failed to parse %s response: %w", ref.Singular, err)}if ref.Validate != nil {if err := ref.Validate(result.Data, identifier); err != nil {@@ -157,7 +156,7 @@ func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *c}if resp.StatusCode != http.StatusNotFound {- return nil, false, errors.Errorf("failed to resolve %s %q (status %d): %s", ref.Singular, identifier, resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, false, fmt.Errorf("failed to resolve %s %q (status %d): %s", ref.Singular, identifier, resp.StatusCode, strings.TrimSpace(string(body)))}return nil, false, nil@@ -196,10 +195,10 @@ func (ref ResourceRef[D, S]) selectMatchInternal(matches []S, identifier string,}if !allowPrompt {- return nil, errors.Errorf("multiple %s match %q; use %s or run `%s`", ref.Plural, identifier, ref.IDHint, ref.ListCmd)+ return nil, fmt.Errorf("multiple %s match %q; use %s or run `%s`", ref.Plural, identifier, ref.IDHint, ref.ListCmd)}if len(matches) > MaxPromptOptions {- return nil, errors.Errorf("multiple %s match %q (%d results); refine your query or use %s", ref.Plural, identifier, len(matches), ref.IDHint)+ return nil, fmt.Errorf("multiple %s match %q (%d results); refine your query or use %s", ref.Plural, identifier, len(matches), ref.IDHint)}options := make([]string, 0, len(matches))@@ -230,22 +229,22 @@ func (ref ResourceRef[D, S]) fallbackByIDPrefixInternal(ctx context.Context, c *func (ref ResourceRef[D, S]) listItemsInternal(ctx context.Context, c *client.Client, path string) ([]S, error) {resp, err := c.Get(ctx, path)if err != nil {- return nil, errors.WrapIff(err, "failed to search %s", ref.Plural)+ return nil, fmt.Errorf("failed to search %s: %w", ref.Plural, err)}body, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err != nil {- return nil, errors.WrapIff(err, "failed to read %s response", ref.Plural)+ return nil, fmt.Errorf("failed to read %s response: %w", ref.Plural, err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, errors.Errorf("failed to search %s (status %d): %s", ref.Plural, resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, fmt.Errorf("failed to search %s (status %d): %s", ref.Plural, resp.StatusCode, strings.TrimSpace(string(body)))}var result base.Paginated[S]if err := json.Unmarshal(body, &result); err != nil {- return nil, errors.WrapIff(err, "failed to parse %s response", ref.Plural)+ return nil, fmt.Errorf("failed to parse %s response: %w", ref.Plural, err)}return result.Data, nil}diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.goindex b004c6699..aa6d3dfa4 100644--- a/cli/internal/cmdutil/response.go+++ b/cli/internal/cmdutil/response.go@@ -4,12 +4,11 @@ import ("bytes""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""net/http""strings"-- "emperror.dev/errors")const maxErrorBodyBytes = 4096@@ -52,7 +51,7 @@ func DecodeJSON[T any](resp *http.Response, out *T) error {return errors.New("nil decode target")}if err := json.UnmarshalRead(resp.Body, out); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}return nil}@@ -68,7 +67,7 @@ func ReadJSONBody(resp *http.Response) ([]byte, error) {}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, errors.WrapIf(err, "failed to read response")+ return nil, fmt.Errorf("failed to read response: %w", err)}return body, nil}@@ -89,7 +88,7 @@ func PrintRawJSON(body []byte) error {func PrintJSON(v any) error {b, err := json.Marshal(v, jsontext.WithIndent(" "))if err != nil {- return errors.WrapIf(err, "failed to marshal JSON")+ return fmt.Errorf("failed to marshal JSON: %w", err)}fmt.Println(string(b))return nildiff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.goindex a5893cf8c..61ce256df 100644--- a/cli/internal/cmdutil/run.go+++ b/cli/internal/cmdutil/run.go@@ -2,10 +2,10 @@ package cmdutilimport ("encoding/json/v2"+ "fmt""net/url""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/types/v2/base"@@ -36,7 +36,7 @@ type ListSpec[T any] struct {func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) error {path, err := ApplyPaginationParams(cmd, spec.Endpoint, spec.Params)if err != nil {- return errors.WrapIf(err, "failed to build pagination query")+ return fmt.Errorf("failed to build pagination query: %w", err)}if len(spec.Query) > 0 {path = AppendQuery(path, spec.Query)@@ -44,13 +44,13 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erroresp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIff(err, "failed to list %s", spec.Resource)+ return fmt.Errorf("failed to list %s: %w", spec.Resource, err)}defer func() { _ = resp.Body.Close() }()body, err := ReadJSONBody(resp)if err != nil {- return errors.WrapIff(err, "failed to list %s", spec.Resource)+ return fmt.Errorf("failed to list %s: %w", spec.Resource, err)}if spec.JSON {@@ -59,7 +59,7 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) errovar result base.Paginated[T]if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}rows := make([][]string, len(result.Data))@@ -97,7 +97,7 @@ func RunPostAction[T any](cmd *cobra.Command, c *client.Client, spec PostActionSresult, err := c.PostJSON[T](cmd.Context(), spec.Path, spec.Body)if err != nil {- return errors.WrapIff(err, "%s", spec.FailureMessage)+ return fmt.Errorf("%s: %w", spec.FailureMessage, err)}if spec.JSON {diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.goindex b192baa4c..95ce33786 100644--- a/cli/internal/cmdutil/upload.go+++ b/cli/internal/cmdutil/upload.go@@ -3,13 +3,13 @@ package cmdutilimport ("bytes""context"+ "fmt""io""net/http""os""path/filepath""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -30,12 +30,12 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stfile, err := os.Open(filePath)if err != nil {- return "", errors.WrapIf(err, "failed to open file")+ return "", fmt.Errorf("failed to open file: %w", err)}defer func() { _ = file.Close() }()fileInfo, err := file.Stat()if err != nil {- return "", errors.WrapIf(err, "failed to stat file")+ return "", fmt.Errorf("failed to stat file: %w", err)}created, err := c.PostJSON[uploadtypes.Session](ctx, types.UploadSessions(c.EnvID(), kind), uploadtypes.CreateSessionRequest{@@ -43,7 +43,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stSize: fileInfo.Size(),})if err != nil {- return "", errors.WrapIf(err, "failed to create upload session")+ return "", fmt.Errorf("failed to create upload session: %w", err)}session := created.Data@@ -66,7 +66,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stexpected := kit.Ternary(index == session.TotalChunks-1, session.Size-int64(index)*session.ChunkSize, session.ChunkSize)if _, err := io.ReadFull(file, buf[:expected]); err != nil {deleteSession()- return "", errors.WrapIf(err, "failed to read file")+ return "", fmt.Errorf("failed to read file: %w", err)}chunkPath := types.UploadSessionChunk(c.EnvID(), kind, session.ID, index)@@ -76,7 +76,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stok := resp.StatusCode >= 200 && resp.StatusCode < 300if !ok {errorBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- chunkErr = errors.Errorf("chunk %d failed (status %d): %s", index, resp.StatusCode, strings.TrimSpace(string(errorBody)))+ chunkErr = fmt.Errorf("chunk %d failed (status %d): %s", index, resp.StatusCode, strings.TrimSpace(string(errorBody)))}_ = resp.Body.Close()if ok {@@ -85,7 +85,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st}if attempt >= uploadChunkAttempts {deleteSession()- return "", errors.WrapIf(chunkErr, "failed to upload file")+ return "", fmt.Errorf("failed to upload file: %w", chunkErr)}log.Debugf("Retrying chunk %d after error: %v", index, chunkErr)}diff --git a/cli/internal/config/config.go b/cli/internal/config/config.goindex 81ac1810e..617ecc8dc 100644--- a/cli/internal/config/config.go+++ b/cli/internal/config/config.go@@ -27,7 +27,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/go-viper/mapstructure/v2""github.com/samber/hot"@@ -97,7 +96,7 @@ func ConfigPath() (string, error) {home, err := os.UserHomeDir()if err != nil {- return "", errors.WrapIf(err, "failed to get home directory")+ return "", fmt.Errorf("failed to get home directory: %w", err)}return filepath.Join(home, ".config", configFileName), nil@@ -116,7 +115,7 @@ func SetConfigPath(path string) error {if path == "~" || strings.HasPrefix(path, "~/") {home, err := os.UserHomeDir()if err != nil {- return errors.WrapIf(err, "failed to expand config path")+ return fmt.Errorf("failed to expand config path: %w", err)}rel := strings.TrimPrefix(path, "~")path = filepath.Join(home, strings.TrimPrefix(rel, string(os.PathSeparator)))@@ -124,7 +123,7 @@ func SetConfigPath(path string) error {absPath, err := filepath.Abs(path)if err != nil {- return errors.WrapIf(err, "failed to resolve config path")+ return fmt.Errorf("failed to resolve config path: %w", err)}customConfigPath = absPath@@ -152,7 +151,7 @@ func Load() (*types.Config, error) {configCache.Set(path, def)return def, nil}- return nil, errors.WrapIf(err, "failed to read config file")+ return nil, fmt.Errorf("failed to read config file: %w", err)}_ = data@@ -164,7 +163,7 @@ func Load() (*types.Config, error) {v.SetDefault("federated_audience", "")v.SetDefault("log_level", "info")if err := v.ReadInConfig(); err != nil {- return nil, errors.WrapIf(err, "failed to parse config file")+ return nil, fmt.Errorf("failed to parse config file: %w", err)}var cfg types.Config@@ -172,7 +171,7 @@ func Load() (*types.Config, error) {dc.TagName = "mapstructure"dc.WeaklyTypedInput = true}); err != nil {- return nil, errors.WrapIf(err, "failed to unmarshal config")+ return nil, fmt.Errorf("failed to unmarshal config: %w", err)}normalized := normalizeConfig(&cfg)@@ -193,7 +192,7 @@ func Save(c *types.Config) error {// Ensure the config directory existsdir := filepath.Dir(path)if err := os.MkdirAll(dir, 0o700); err != nil {- return errors.WrapIf(err, "failed to create config directory")+ return fmt.Errorf("failed to create config directory: %w", err)}cfg := normalizeConfig(c)@@ -235,10 +234,10 @@ func Save(c *types.Config) error {}if err := v.WriteConfigAs(path); err != nil {- return errors.WrapIf(err, "failed to write config file")+ return fmt.Errorf("failed to write config file: %w", err)}if err := os.Chmod(path, 0o600); err != nil {- return errors.WrapIf(err, "failed to set config permissions")+ return fmt.Errorf("failed to set config permissions: %w", err)}configCache.Set(path, cfg)@@ -259,18 +258,18 @@ func InitDefaultFile() (bool, error) {switch {case err == nil:if info.IsDir() {- return false, errors.Errorf("config path is a directory: %s", path)+ return false, fmt.Errorf("config path is a directory: %s", path)}return false, nilcase os.IsNotExist(err):// Continue and create the file below.default:- return false, errors.WrapIf(err, "failed to stat config path")+ return false, fmt.Errorf("failed to stat config path: %w", err)}dir := filepath.Dir(path)if err := os.MkdirAll(dir, 0o700); err != nil {- return false, errors.WrapIf(err, "failed to create config directory")+ return false, fmt.Errorf("failed to create config directory: %w", err)}v := viper.New()@@ -289,10 +288,10 @@ func InitDefaultFile() (bool, error) {}if err := v.WriteConfigAs(path); err != nil {- return false, errors.WrapIf(err, "failed to write config file")+ return false, fmt.Errorf("failed to write config file: %w", err)}if err := os.Chmod(path, 0o600); err != nil {- return false, errors.WrapIf(err, "failed to set config permissions")+ return false, fmt.Errorf("failed to set config permissions: %w", err)}invalidateCache()@@ -313,28 +312,28 @@ func BackupFile() (backupPath string, moved bool, err error) {switch {case err == nil:if info.IsDir() {- return "", false, errors.Errorf("config path is a directory: %s", path)+ return "", false, fmt.Errorf("config path is a directory: %s", path)}case os.IsNotExist(err):return backupPath, false, nildefault:- return "", false, errors.WrapIf(err, "failed to stat config path")+ return "", false, fmt.Errorf("failed to stat config path: %w", err)}if existingBackup, backupErr := os.Stat(backupPath); backupErr == nil {if existingBackup.IsDir() {- return "", false, errors.Errorf("backup path is a directory: %s", backupPath)+ return "", false, fmt.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, errors.WrapIff(err, "failed to rotate existing backup %s", backupPath)+ return "", false, fmt.Errorf("failed to rotate existing backup %s: %w", backupPath, err)}} else if !os.IsNotExist(backupErr) {- return "", false, errors.WrapIf(backupErr, "failed to stat backup path")+ return "", false, fmt.Errorf("failed to stat backup path: %w", backupErr)}if err := os.Rename(path, backupPath); err != nil {- return "", false, errors.WrapIf(err, "failed to move config to backup")+ return "", false, fmt.Errorf("failed to move config to backup: %w", err)}invalidateCache()diff --git a/cli/internal/output/output.go b/cli/internal/output/output.goindex 5f8c6813b..b78646b28 100644--- a/cli/internal/output/output.go+++ b/cli/internal/output/output.go@@ -251,8 +251,7 @@ func Table(headers []string, rows [][]string) {t := table.New().Border(lipgloss.NormalBorder()).Headers(headers...)if shouldColor() {- t = t.- BorderStyle(tableBorder).+ t = t.BorderStyle(tableBorder).StyleFunc(func(row, col int) lipgloss.Style {switch {case row == table.HeaderRow:diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.goindex 1185b6b2b..f07347b43 100644--- a/cli/internal/prompt/prompt.go+++ b/cli/internal/prompt/prompt.go@@ -1,12 +1,12 @@package promptimport (+ "errors""fmt""os""charm.land/bubbles/v2/list"tea "charm.land/bubbletea/v2"- "emperror.dev/errors""github.com/charmbracelet/x/term")@@ -18,7 +18,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, errors.Errorf("no %s options available", label)+ return -1, fmt.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 2adc5cca8..b2504a7cd 100644--- a/cli/internal/runtime/context.go+++ b/cli/internal/runtime/context.go@@ -3,11 +3,11 @@ package runtimeimport ("cmp""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"@@ -54,14 +54,14 @@ type AppContext struct {func New(opts Options) (*AppContext, error) {cfg, err := config.Load()if err != nil {- return nil, errors.WrapIf(err, "failed to load config")+ return nil, fmt.Errorf("failed to load config: %w", err)}mode := cmp.Or(opts.OutputMode, OutputModeText)switch mode {case OutputModeText, OutputModeJSON:default:- return nil, errors.Errorf("invalid output mode %q (expected text or json)", mode)+ return nil, fmt.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 d1952814c..9513d1d2c 100644--- a/cli/internal/types/config.go+++ b/cli/internal/types/config.go@@ -1,10 +1,9 @@package typesimport (+ "errors""maps""strings"-- "emperror.dev/errors")// PaginationResourceConfig defines pagination options for a specific resource.diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.goindex 1ea33f394..5bb718806 100644--- a/cli/pkg/activities/cmd.go+++ b/cli/pkg/activities/cmd.go@@ -8,7 +8,6 @@ import ("strconv""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"@@ -96,7 +95,7 @@ var getCmd = &cobra.Command{)result, err := c.GetJSON[activitytypes.Detail](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get activity")+ return fmt.Errorf("failed to get activity: %w", err)}if jsonOutput {@@ -169,7 +168,7 @@ var cancelCmd = &cobra.Command{result, err := c.PostJSON[activitytypes.Activity](cmd.Context(), types.ActivityCancel(c.EnvID(), args[0]), nil)if err != nil {- return errors.WrapIf(err, "failed to cancel activity")+ return fmt.Errorf("failed to cancel activity: %w", err)}if jsonOutput {@@ -204,7 +203,7 @@ var clearCmd = &cobra.Command{result, err := c.DeleteJSON[activitytypes.ClearHistoryResult](cmd.Context(), types.ActivitiesHistory(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to clear activity history")+ return fmt.Errorf("failed to clear activity history: %w", err)}if jsonOutput {diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.goindex a2abbad0a..ac21dd05c 100644--- a/cli/pkg/admin/apikeys/cmd.go+++ b/cli/pkg/admin/apikeys/cmd.go@@ -1,12 +1,12 @@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"@@ -61,14 +61,14 @@ func parsePermissionGrantsInternal(tokens []string) ([]apikey.PermissionGrant, ecase 3:env := parts[2]if parts[0] == "" || parts[1] == "" || env == "" {- return nil, errors.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)+ return nil, fmt.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, errors.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)+ return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)}}return out, nil@@ -150,14 +150,14 @@ var createCmd = &cobra.Command{if expiresAtRaw, _ := cmd.Flags().GetString("expires-at"); expiresAtRaw != "" {parsed, err := time.Parse(time.RFC3339, expiresAtRaw)if err != nil {- return errors.WrapIf(err, "invalid --expires-at format (use RFC3339)")+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)}createReq.ExpiresAt = &parsed}result, err := c.PostJSON[apikey.ApiKeyCreatedDto](cmd.Context(), types.ApiKeys(), createReq)if err != nil {- return errors.WrapIf(err, "failed to create API key")+ return fmt.Errorf("failed to create API key: %w", err)}if jsonOutput {@@ -200,7 +200,7 @@ var deleteCmd = &cobra.Command{result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.ApiKey(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete API key")+ return fmt.Errorf("failed to delete API key: %w", err)}if jsonOutput {@@ -225,7 +225,7 @@ var getCmd = &cobra.Command{result, err := c.GetJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get API key")+ return fmt.Errorf("failed to get API key: %w", err)}if jsonOutput {@@ -283,7 +283,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("expires-at") && apikeyUpdateExpiresAt != "" {parsedTime, err := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)if err != nil {- return errors.WrapIf(err, "invalid expires-at format (use RFC3339)")+ return fmt.Errorf("invalid expires-at format (use RFC3339): %w", err)}req.ExpiresAt = &parsedTime}@@ -299,7 +299,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update API key")+ return fmt.Errorf("failed to update API key: %w", err)}if jsonOutput {diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.goindex 8634b03b0..2edaa0609 100644--- a/cli/pkg/admin/events/cmd.go+++ b/cli/pkg/admin/events/cmd.go@@ -3,7 +3,6 @@ package eventsimport ("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"@@ -102,7 +101,7 @@ var deleteCmd = &cobra.Command{}if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Event(args[0])); err != nil {- return errors.WrapIf(err, "failed to delete event")+ return fmt.Errorf("failed to delete event: %w", err)}output.Success("Event deleted successfully")@@ -130,7 +129,7 @@ var statsCmd = &cobra.Command{Error int64 `json:"error"`}](cmd.Context(), types.EventsStats())if err != nil {- return errors.WrapIf(err, "failed to get event stats")+ return fmt.Errorf("failed to get event stats: %w", err)}if jsonOutput {diff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.goindex f9dc633fa..7e7857dca 100644--- a/cli/pkg/admin/federatedcredentials/cmd.go+++ b/cli/pkg/admin/federatedcredentials/cmd.go@@ -6,10 +6,10 @@ package federatedcredentialsimport ("cmp"+ "errors""fmt""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"@@ -102,7 +102,7 @@ var getCmd = &cobra.Command{result, err := c.GetJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get federated credential")+ return fmt.Errorf("failed to get federated credential: %w", err)}if jsonOutput {@@ -148,14 +148,14 @@ var createCmd = &cobra.Command{if createExpiresAt != "" {parsed, err := time.Parse(time.RFC3339, createExpiresAt)if err != nil {- return errors.WrapIf(err, "invalid --expires-at format (use RFC3339)")+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)}req.ExpiresAt = &parsed}result, err := c.PostJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredentials(), req)if err != nil {- return errors.WrapIf(err, "failed to create federated credential")+ return fmt.Errorf("failed to create federated credential: %w", err)}if jsonOutput {@@ -226,14 +226,14 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("expires-at") && updateExpiresAt != "" {parsed, err := time.Parse(time.RFC3339, updateExpiresAt)if err != nil {- return errors.WrapIf(err, "invalid --expires-at format (use RFC3339)")+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)}req.ExpiresAt = &parsed}result, err := c.PutJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update federated credential")+ return fmt.Errorf("failed to update federated credential: %w", err)}if jsonOutput {@@ -270,7 +270,7 @@ var deleteCmd = &cobra.Command{}if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.FederatedCredential(args[0])); err != nil {- return errors.WrapIf(err, "failed to delete federated credential")+ return fmt.Errorf("failed to delete federated credential: %w", err)}output.Success("Federated credential deleted")diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.goindex 0e25a725c..496bd3e6e 100644--- a/cli/pkg/admin/notifications/cmd.go+++ b/cli/pkg/admin/notifications/cmd.go@@ -2,12 +2,12 @@ package notificationsimport ("encoding/json/v2"+ "errors""fmt""net/http""os""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"@@ -46,7 +46,7 @@ var settingsGetCmd = &cobra.Command{result, err := c.DoJSON[[]notification.Response](cmd.Context(), http.MethodGet, types.NotificationsSettings(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to get settings")+ return fmt.Errorf("failed to get settings: %w", err)}if jsonOutput {@@ -93,7 +93,7 @@ var settingsDeleteCmd = &cobra.Command{result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.NotificationSettingsProvider(c.EnvID(), args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete notification settings")+ return fmt.Errorf("failed to delete notification settings: %w", err)}if jsonOutput {@@ -121,10 +121,10 @@ var settingsSetCmd = &cobra.Command{if setFile != "" {data, err := os.ReadFile(setFile)if err != nil {- return errors.WrapIf(err, "failed to read settings file")+ return fmt.Errorf("failed to read settings file: %w", err)}if err := json.Unmarshal(data, &req); err != nil {- return errors.WrapIf(err, "failed to parse settings file")+ return fmt.Errorf("failed to parse settings file: %w", err)}}@@ -136,7 +136,7 @@ var settingsSetCmd = &cobra.Command{}if cmd.Flags().Changed("config") {if err := json.Unmarshal([]byte(setConfig), &req.Config); err != nil {- return errors.WrapIf(err, "failed to parse --config JSON")+ return fmt.Errorf("failed to parse --config JSON: %w", err)}}@@ -154,7 +154,7 @@ var settingsSetCmd = &cobra.Command{result, err := c.DoJSON[notification.Response](cmd.Context(), http.MethodPost, types.NotificationsSettings(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to save notification settings")+ return fmt.Errorf("failed to save notification settings: %w", err)}if jsonOutput {diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.goindex 1dee97731..af593aad7 100644--- a/cli/pkg/admin/oidcmappings/cmd.go+++ b/cli/pkg/admin/oidcmappings/cmd.go@@ -6,7 +6,6 @@ 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"@@ -36,10 +35,7 @@ var OidcMappingsCmd = &cobra.Command{Use: "oidc",Aliases: []string{"oidc-mappings", "oidc-mapping"},Short: "Manage OIDC group → role mappings",- Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane " +- "looks up the user's groups claim and applies the matching mappings " +- "as source='oidc' role assignments. The groups claim itself is " +- "configured via the oidcGroupsClaim setting (default `groups`).",+ Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane looks up the user's groups claim and applies the matching mappings as source='oidc' role assignments. The groups claim itself is configured via the oidcGroupsClaim setting (default `groups`).",}var listCmd = &cobra.Command{@@ -54,7 +50,7 @@ var listCmd = &cobra.Command{}result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())if err != nil {- return errors.WrapIf(err, "failed to list OIDC mappings")+ return fmt.Errorf("failed to list OIDC mappings: %w", err)}if jsonOutput {@@ -100,7 +96,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings(), req)if err != nil {- return errors.WrapIf(err, "failed to create OIDC mapping")+ return fmt.Errorf("failed to create OIDC mapping: %w", err)}if jsonOutput {@@ -158,11 +154,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.OidcRoleMapping(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update OIDC mapping")+ return fmt.Errorf("failed to update OIDC mapping: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to update OIDC mapping")+ return fmt.Errorf("failed to update OIDC mapping: %w", err)}output.Success("OIDC mapping updated")return nil@@ -192,11 +188,11 @@ var deleteCmd = &cobra.Command{}resp, err := c.Delete(cmd.Context(), types.OidcRoleMapping(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete OIDC mapping")+ return fmt.Errorf("failed to delete OIDC mapping: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete OIDC mapping")+ return fmt.Errorf("failed to delete OIDC mapping: %w", err)}output.Success("OIDC mapping deleted")return nil@@ -213,14 +209,14 @@ func fetchMappingInternal(cmd *cobra.Command, id string) (*roletypes.OidcRoleMap}result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())if err != nil {- return nil, errors.WrapIf(err, "failed to load current mapping")+ return nil, fmt.Errorf("failed to load current mapping: %w", err)}for i := range result.Data {if result.Data[i].ID == id {return &result.Data[i], nil}}- return nil, errors.Errorf("OIDC mapping %q not found", id)+ return nil, fmt.Errorf("OIDC mapping %q not found", id)}func init() {diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.goindex 8e0699deb..5c994e038 100644--- a/cli/pkg/admin/roles/cmd.go+++ b/cli/pkg/admin/roles/cmd.go@@ -6,11 +6,11 @@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"@@ -99,7 +99,7 @@ var getCmd = &cobra.Command{}result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get role")+ return fmt.Errorf("failed to get role: %w", err)}if jsonOutput {@@ -152,7 +152,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[roletypes.Role](cmd.Context(), types.Roles(), req)if err != nil {- return errors.WrapIf(err, "failed to create role")+ return fmt.Errorf("failed to create role: %w", err)}if jsonOutput {@@ -201,11 +201,11 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.Role(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update role")+ return fmt.Errorf("failed to update role: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to update role")+ return fmt.Errorf("failed to update role: %w", err)}output.Success("Role updated")@@ -236,11 +236,11 @@ var deleteCmd = &cobra.Command{}resp, err := c.Delete(cmd.Context(), types.Role(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete role")+ return fmt.Errorf("failed to delete role: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete role")+ return fmt.Errorf("failed to delete role: %w", err)}output.Success("Role deleted")return nil@@ -261,7 +261,7 @@ var permissionsCmd = &cobra.Command{}result, err := c.GetJSON[roletypes.PermissionsManifest](cmd.Context(), types.RolesAvailablePermissions())if err != nil {- return errors.WrapIf(err, "failed to load permission manifest")+ return fmt.Errorf("failed to load permission manifest: %w", err)}if jsonOutput {@@ -294,7 +294,7 @@ var assignmentsCmd = &cobra.Command{}result, err := c.GetJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]))if err != nil {- return errors.WrapIf(err, "failed to list assignments")+ return fmt.Errorf("failed to list assignments: %w", err)}if jsonOutput {@@ -321,13 +321,8 @@ var assignmentsCmd = &cobra.Command{var assignCmd = &cobra.Command{Use: "assign <user-id>",Short: "Replace a user's manual role assignments",- Long: "Replace every MANUAL role assignment on the user with the set " +- "passed via --role. OIDC-sourced assignments are left untouched — " +- "manage those via OIDC role mappings.\n\n" +- "Each --role flag accepts `<roleId>[:<envId>]`. Omit the env id for " +- "a global assignment. Pass --role multiple times to assign more than " +- "one role. Pass --role \"\" (empty) once to clear every manual " +- "assignment.",+ Long: "Replace every MANUAL role assignment on the user with the set passed via --role. OIDC-sourced assignments are left untouched — manage those via OIDC role mappings.\n\nEach --role flag accepts `<roleId>[:<envId>]`. Omit the env id for a global assignment. Pass --role multiple times to assign more than one role. Pass --role \"\" (empty) once to clear every manual assignment.",+Example: ` arcane admin roles assign u_123 --role role_editor:env_prod --role role_viewerarcane admin roles assign u_123 --role role_adminarcane admin roles assign u_123 --role "" # clear all manual assignments`,@@ -343,7 +338,7 @@ var assignCmd = &cobra.Command{}result, err := c.PutJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to set assignments")+ return fmt.Errorf("failed to set assignments: %w", err)}if jsonOutput {return cmdutil.PrintJSON(result.Data)@@ -385,7 +380,7 @@ func fetchRoleInternal(cmd *cobra.Command, id string) (*roletypes.Role, error) {}result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(id))if err != nil {- return nil, errors.WrapIf(err, "failed to load current role")+ return nil, fmt.Errorf("failed to load current role: %w", err)}return &result.Data, nil}diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.goindex 622b2257d..24580bd6d 100644--- a/cli/pkg/admin/users/cmd.go+++ b/cli/pkg/admin/users/cmd.go@@ -5,7 +5,6 @@ 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"@@ -41,9 +40,7 @@ var UsersCmd = &cobra.Command{Use: "users",Aliases: []string{"user", "usr"},Short: "Manage users",- Long: "Manage users. Role assignments are managed separately via " +- "`arcane admin roles assign` — the legacy `--role` flag has been " +- "removed alongside the binary admin/user model.",+ Long: "Manage users. Role assignments are managed separately via `arcane admin roles assign` — the legacy `--role` flag has been removed alongside the binary admin/user model.",}// summarizeRoleAssignments turns a user's role-assignment list into a short@@ -130,9 +127,8 @@ var listCmd = &cobra.Command{var createCmd = &cobra.Command{Use: "create",Short: "Create a new user",- Long: "Create a new user. The user is created without any role " +- "assignments — grant them via `arcane admin roles assign <userId>` " +- "after creation.",+ Long: "Create a new user. The user is created without any role assignments — grant them via `arcane admin roles assign <userId>` after creation.",+SilenceUsage: true,RunE: func(cmd *cobra.Command, args []string) error {c, err := client.NewFromConfig()@@ -144,7 +140,7 @@ var createCmd = &cobra.Command{fmt.Print("Password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return errors.WrapIf(err, "failed to read password")+ return fmt.Errorf("failed to read password: %w", err)}userCreatePassword = string(bytePassword)fmt.Println()@@ -163,7 +159,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[user.User](cmd.Context(), types.Users(), req)if err != nil {- return errors.WrapIf(err, "failed to create user")+ return fmt.Errorf("failed to create user: %w", err)}if jsonOutput {@@ -191,7 +187,7 @@ var getCmd = &cobra.Command{result, err := c.GetJSON[user.User](cmd.Context(), types.User(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get user")+ return fmt.Errorf("failed to get user: %w", err)}if jsonOutput {@@ -248,7 +244,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[user.User](cmd.Context(), types.User(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update user")+ return fmt.Errorf("failed to update user: %w", err)}if jsonOutput {@@ -285,11 +281,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.User(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete user")+ return fmt.Errorf("failed to delete user: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete user")+ return fmt.Errorf("failed to delete user: %w", err)}output.Success("User deleted successfully")diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.goindex 961e713eb..7d88c26a3 100644--- a/cli/pkg/auth/apikeys.go+++ b/cli/pkg/auth/apikeys.go@@ -4,7 +4,6 @@ import ("fmt""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"@@ -25,9 +24,7 @@ var apiKeysCmd = &cobra.Command{Use: "keys",Aliases: []string{"apikeys", "key"},Short: "Manage your own API keys",- Long: "Manage the current user's personal API keys. Personal keys inherit " +- "the owner's role permissions. Creating and deleting them requires a " +- "session login (an API key cannot mint or remove other keys).",+ Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and deleting them requires a session login (an API key cannot mint or remove other keys).",}var apiKeysListCmd = &cobra.Command{@@ -43,7 +40,7 @@ var apiKeysListCmd = &cobra.Command{result, err := c.GetJSON[[]apikeytypes.ApiKey](cmd.Context(), types.AuthMeApiKeys())if err != nil {- return errors.WrapIf(err, "failed to list API keys")+ return fmt.Errorf("failed to list API keys: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -99,14 +96,14 @@ var apiKeysCreateCmd = &cobra.Command{if apiKeyCreateExpiresAt != "" {parsed, err := time.Parse(time.RFC3339, apiKeyCreateExpiresAt)if err != nil {- return errors.WrapIf(err, "invalid --expires-at format (use RFC3339)")+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)}req.ExpiresAt = &parsed}result, err := c.PostJSON[apikeytypes.ApiKeyCreatedDto](cmd.Context(), types.AuthMeApiKeys(), req)if err != nil {- return errors.WrapIf(err, "failed to create API key")+ return fmt.Errorf("failed to create API key: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -147,11 +144,11 @@ var apiKeysDeleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.AuthMeApiKey(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete API key")+ return fmt.Errorf("failed to delete API key: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete API key")+ return fmt.Errorf("failed to delete API key: %w", err)}output.Success("API key deleted")diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.goindex ab349db25..33b0fbffb 100644--- a/cli/pkg/auth/cmd.go+++ b/cli/pkg/auth/cmd.go@@ -2,6 +2,7 @@ package authimport ("encoding/json/v2"+ "errors""fmt""io""net/http"@@ -10,7 +11,6 @@ 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"@@ -43,27 +43,27 @@ var loginCmd = &cobra.Command{reqBody, err := json.Marshal(auth.OidcDeviceAuthRequest{})if err != nil {- return errors.WrapIf(err, "failed to marshal request")+ return fmt.Errorf("failed to marshal request: %w", err)}resp, err := c.Post(cmd.Context(), types.OIDCDeviceCode(), reqBody)if err != nil {- return errors.WrapIf(err, "device authorization failed")+ return fmt.Errorf("device authorization failed: %w", err)}defer func() { _ = resp.Body.Close() }()bodyBytes, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read response")+ return fmt.Errorf("failed to read response: %w", err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return errors.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))+ return fmt.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 errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Header("Device Login")@@ -82,7 +82,7 @@ var loginCmd = &cobra.Command{tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})if err != nil {- return errors.WrapIf(err, "failed to marshal token request")+ return fmt.Errorf("failed to marshal token request: %w", err)}ticker := time.NewTicker(pollInterval)@@ -101,13 +101,13 @@ var loginCmd = &cobra.Command{tokenResp, err := c.Post(cmd.Context(), types.OIDCDeviceToken(), tokenReqBody)if err != nil {- return errors.WrapIf(err, "device token exchange failed")+ return fmt.Errorf("device token exchange failed: %w", err)}tokenBody, err := io.ReadAll(tokenResp.Body)_ = tokenResp.Body.Close()if err != nil {- return errors.WrapIf(err, "failed to read token response")+ return fmt.Errorf("failed to read token response: %w", err)}if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {@@ -126,13 +126,13 @@ var loginCmd = &cobra.Command{case "mfa_required":return errors.New("this account has MFA enabled, which browser-based CLI login cannot complete; create a personal API key in Arcane (Account -> API keys) and run: arcane config set api-key <key>")default:- return errors.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))+ return fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))}}var tokenResult auth.AuthenticationResponseif err := json.Unmarshal(tokenBody, &tokenResult); err != nil {- return errors.WrapIf(err, "failed to parse token response")+ return fmt.Errorf("failed to parse token response: %w", err)}if !tokenResult.Success || tokenResult.Token == "" {return errors.New("device token exchange failed: unexpected response from server")@@ -150,13 +150,13 @@ var loginCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}cfg.JWTToken = tokenResult.Tokencfg.RefreshToken = tokenResult.RefreshTokencfg.APIKey = ""if err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save token")+ return fmt.Errorf("failed to save token: %w", err)}output.Success("Login successful")@@ -179,18 +179,18 @@ var logoutCmd = &cobra.Command{result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthLogout(), nil)if err != nil {- return errors.WrapIf(err, "logout failed")+ return fmt.Errorf("logout failed: %w", err)}// Clear token from config after successful API logout.cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}cfg.JWTToken = ""cfg.RefreshToken = ""if err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to clear token")+ return fmt.Errorf("failed to clear token: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -216,7 +216,7 @@ var meCmd = &cobra.Command{result, err := c.GetJSON[user.User](cmd.Context(), types.AuthMe())if err != nil {- return errors.WrapIf(err, "failed to get user info")+ return fmt.Errorf("failed to get user info: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -240,7 +240,7 @@ var passwordCmd = &cobra.Command{fmt.Print("Current password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return errors.WrapIf(err, "failed to read current password")+ return fmt.Errorf("failed to read current password: %w", err)}currentPassword = string(bytePassword)fmt.Println()@@ -250,7 +250,7 @@ var passwordCmd = &cobra.Command{fmt.Print("New password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return errors.WrapIf(err, "failed to read new password")+ return fmt.Errorf("failed to read new password: %w", err)}newPassword = string(bytePassword)fmt.Println()@@ -268,12 +268,12 @@ var passwordCmd = &cobra.Command{reqBody, err := json.Marshal(changeReq)if err != nil {- return errors.WrapIf(err, "failed to marshal request")+ return fmt.Errorf("failed to marshal request: %w", err)}result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthPassword(), reqBody)if err != nil {- return errors.WrapIf(err, "password change failed")+ return fmt.Errorf("password change failed: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -294,7 +294,7 @@ var refreshCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}if refreshToken == "" {@@ -303,7 +303,7 @@ var refreshCmd = &cobra.Command{if refreshToken == "" {fmt.Print("Refresh token: ")if _, err := fmt.Scanln(&refreshToken); err != nil {- return errors.WrapIf(err, "failed to read refresh token")+ return fmt.Errorf("failed to read refresh token: %w", err)}}@@ -314,12 +314,12 @@ var refreshCmd = &cobra.Command{reqBody, err := json.Marshal(map[string]string{"refreshToken": refreshToken})if err != nil {- return errors.WrapIf(err, "failed to marshal request")+ return fmt.Errorf("failed to marshal request: %w", err)}result, err := c.PostJSON[auth.TokenRefreshResponse](cmd.Context(), types.AuthRefresh(), reqBody)if err != nil {- return errors.WrapIf(err, "token refresh failed")+ return fmt.Errorf("token refresh failed: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {@@ -337,7 +337,7 @@ var refreshCmd = &cobra.Command{cfg.RefreshToken = result.Data.RefreshToken}if err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save token")+ return fmt.Errorf("failed to save token: %w", err)}output.Success("Token refreshed successfully")@@ -367,7 +367,7 @@ var oidcStatusCmd = &cobra.Command{}result, err := c.DoJSON[oidcStatusResult](cmd.Context(), http.MethodGet, types.OIDCStatus(), nil)if err != nil {- return errors.WrapIf(err, "failed to get OIDC status")+ return fmt.Errorf("failed to get OIDC status: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.goindex 209a51510..4146dceb5 100644--- a/cli/pkg/auth/federated.go+++ b/cli/pkg/auth/federated.go@@ -2,6 +2,7 @@ package authimport ("encoding/json/v2"+ "errors""fmt""io""net/http"@@ -10,7 +11,6 @@ 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"@@ -54,7 +54,7 @@ GitHub Actions example:cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}if strings.TrimSpace(server) != "" {cfg.ServerURL = strings.TrimSpace(server)@@ -88,7 +88,7 @@ GitHub Actions example:cfg.APIKey = ""cfg.RefreshToken = ""if err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save federated token")+ return fmt.Errorf("failed to save federated token: %w", err)}}@@ -146,7 +146,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audienceif strings.TrimSpace(tokenFile) != "" {data, err := os.ReadFile(strings.TrimSpace(tokenFile))if err != nil {- return "", "", errors.WrapIf(err, "failed to read token file")+ return "", "", fmt.Errorf("failed to read token file: %w", err)}token = strings.TrimSpace(string(data))if token == "" {@@ -159,7 +159,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audienceif tokenStdin || stdinHasDataInternal() {data, err := io.ReadAll(os.Stdin)if err != nil {- return "", "", errors.WrapIf(err, "failed to read token from stdin")+ return "", "", fmt.Errorf("failed to read token from stdin: %w", err)}token = strings.TrimSpace(string(data))if token == "" {@@ -185,23 +185,23 @@ func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjec"Content-Type": "application/x-www-form-urlencoded",})if err != nil {- return nil, errors.WrapIf(err, "federated token exchange failed")+ return nil, fmt.Errorf("federated token exchange failed: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFederatedErrorBody))- return nil, errors.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, redactedFederatedExchangeMessageInternal(body))+ return nil, fmt.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, redactedFederatedExchangeMessageInternal(body))}body, err := io.ReadAll(io.LimitReader(resp.Body, maxFederatedResponseBody))if err != nil {- return nil, errors.WrapIf(err, "failed to read federated token response")+ return nil, fmt.Errorf("failed to read federated token response: %w", err)}var tokenResp federatedtypes.FederatedTokenResponseif err := json.Unmarshal(body, &tokenResp); err != nil {- return nil, errors.WrapIf(err, "failed to parse federated token response")+ return nil, fmt.Errorf("failed to parse federated token response: %w", err)}return &tokenResp, nil}diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.goindex 2af525369..45e397bea 100644--- a/cli/pkg/backups/cmd.go+++ b/cli/pkg/backups/cmd.go@@ -2,13 +2,13 @@ package backupsimport ("encoding/json/v2"+ "errors""fmt""io""net/http""os""strconv"- "emperror.dev/errors""github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -130,7 +130,7 @@ alone stores it in S3, and --local together with --s3-destination stores it in bswitch destination {case backup.SystemBackupDestinationLocal, backup.SystemBackupDestinationS3, backup.SystemBackupDestinationLocalS3:default:- return errors.Errorf("invalid --destination %q: must be local, s3, or local_s3", createDestination)+ return fmt.Errorf("invalid --destination %q: must be local, s3, or local_s3", createDestination)}} else {switch {@@ -143,7 +143,7 @@ alone stores it in S3, and --local together with --s3-destination stores it in b}}if (destination == backup.SystemBackupDestinationS3 || destination == backup.SystemBackupDestinationLocalS3) && s3DestinationID == "" {- return errors.Errorf("--destination %s requires --s3-destination", destination)+ return fmt.Errorf("--destination %s requires --s3-destination", destination)}req := backup.CreateSystemBackupRequest{@@ -155,7 +155,7 @@ alone stores it in S3, and --local together with --s3-destination stores it in brun, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.Backups(), req)if err != nil {- return errors.WrapIf(err, "failed to create backup")+ return fmt.Errorf("failed to create backup: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -201,7 +201,7 @@ var deleteCmd = &cobra.Command{result, err := c.DoJSON[base.ApiResponse[base.MessageResponse]](cmd.Context(), http.MethodDelete, types.Backup(args[0]), backup.DeleteSystemBackupRequest{RecoveryKey: deleteRecoveryKey})if err != nil {- return errors.WrapIf(err, "failed to delete backup")+ return fmt.Errorf("failed to delete backup: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -240,7 +240,7 @@ var restoreCmd = &cobra.Command{fmt.Print("Recovery key: ")byteKey, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return errors.WrapIf(err, "failed to read recovery key")+ return fmt.Errorf("failed to read recovery key: %w", err)}key = string(byteKey)fmt.Println()@@ -256,7 +256,7 @@ var restoreCmd = &cobra.Command{result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.BackupRestore(args[0]), backup.RestoreSystemBackupRequest{RecoveryKey: key})if err != nil {- return errors.WrapIf(err, "failed to restore backup")+ return fmt.Errorf("failed to restore backup: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -292,7 +292,7 @@ var uploadCmd = &cobra.Command{run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.BackupUpload(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to upload backup")+ return fmt.Errorf("failed to upload backup: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -332,7 +332,7 @@ var discoverCmd = &cobra.Command{result, err := c.PostJSON[int](cmd.Context(), types.BackupsDiscover(), req)if err != nil {- return errors.WrapIf(err, "failed to discover backups")+ return fmt.Errorf("failed to discover backups: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -357,7 +357,7 @@ var policiesCmd = &cobra.Command{result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)if err != nil {- return errors.WrapIf(err, "failed to get backup policies")+ return fmt.Errorf("failed to get backup policies: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -413,7 +413,7 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,if policiesUpdateFile != "" {for _, name := range []string{"policy-id", "enabled", "disabled", "schedule", "retention", "local", "s3", "s3-destination"} {if cmd.Flags().Changed(name) {- return errors.Errorf("--file cannot be combined with --%s", name)+ return fmt.Errorf("--file cannot be combined with --%s", name)}}@@ -421,21 +421,21 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,if policiesUpdateFile == "-" {data, err = io.ReadAll(os.Stdin)if err != nil {- return errors.WrapIf(err, "failed to read policies from stdin")+ return fmt.Errorf("failed to read policies from stdin: %w", err)}} else {data, err = os.ReadFile(policiesUpdateFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", policiesUpdateFile)+ return fmt.Errorf("failed to read file %s: %w", policiesUpdateFile, err)}}if err := json.Unmarshal(data, &req); err != nil {- return errors.WrapIf(err, "failed to parse policies file")+ return fmt.Errorf("failed to parse policies file: %w", err)}} else {current, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)if err != nil {- return errors.WrapIf(err, "failed to get current backup policies")+ return fmt.Errorf("failed to get current backup policies: %w", err)}req.Policies = make([]backup.UpdateSystemBackupPolicy, len(current.Policies))@@ -457,9 +457,9 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,switch {case policiesUpdateID != "" && targetIndex == -1:- return errors.Errorf("policy %q not found; run `arcane backups policies`", policiesUpdateID)+ return fmt.Errorf("policy %q not found; run `arcane backups policies`", policiesUpdateID)case policiesUpdateID == "" && len(req.Policies) > 1:- return errors.Errorf("%d backup policies exist; select one with --policy-id", len(req.Policies))+ return fmt.Errorf("%d backup policies exist; select one with --policy-id", len(req.Policies))case policiesUpdateID == "" && len(req.Policies) == 1:targetIndex = 0case targetIndex == -1:@@ -504,7 +504,7 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodPut, types.BackupsPolicies(), req)if err != nil {- return errors.WrapIf(err, "failed to update backup policies")+ return fmt.Errorf("failed to update backup policies: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -535,7 +535,7 @@ var recoveryKeyGenerateCmd = &cobra.Command{result, err := c.DoJSON[backup.SystemBackupRecoveryKey](cmd.Context(), http.MethodPost, types.BackupsRecoveryKeyGenerate(), nil)if err != nil {- return errors.WrapIf(err, "failed to generate recovery key")+ return fmt.Errorf("failed to generate recovery key: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -584,7 +584,7 @@ var recoveryKeySetCmd = &cobra.Command{fmt.Print("Recovery key: ")byteKey, err := term.ReadPassword(os.Stdin.Fd())if err != nil {- return errors.WrapIf(err, "failed to read recovery key")+ return fmt.Errorf("failed to read recovery key: %w", err)}key = string(byteKey)fmt.Println()@@ -600,7 +600,7 @@ var recoveryKeySetCmd = &cobra.Command{status, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})if err != nil {- return errors.WrapIf(err, "failed to set recovery key")+ return fmt.Errorf("failed to set recovery key: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -614,7 +614,10 @@ var recoveryKeySetCmd = &cobra.Command{func storeRecoveryKey(cmd *cobra.Command, c *client.Client, key string) error {_, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})- return errors.WrapIf(err, "failed to store recovery key")+ if err != nil {+ return fmt.Errorf("failed to store recovery key: %w", err)+ }+ return nil}func init() {diff --git a/cli/pkg/backups/resolve.go b/cli/pkg/backups/resolve.goindex d25067f27..82f3ad264 100644--- a/cli/pkg/backups/resolve.go+++ b/cli/pkg/backups/resolve.go@@ -6,7 +6,6 @@ import ("net/http""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/types"@@ -25,7 +24,7 @@ var s3DestinationRef = cmdutil.ResourceRef[backup.S3Destination, backup.S3DestinSearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]backup.S3Destination, error) {destinations, err := c.DoJSON[[]backup.S3Destination](ctx, http.MethodGet, types.BackupsS3Options(), nil)if err != nil {- return nil, errors.WrapIf(err, "failed to list S3 destinations")+ return nil, fmt.Errorf("failed to list S3 destinations: %w", err)}matches := make([]backup.S3Destination, 0)for _, dest := range destinations {diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.goindex 29cca45bb..ef83267bb 100644--- a/cli/pkg/backups/s3.go+++ b/cli/pkg/backups/s3.go@@ -1,11 +1,11 @@package backupsimport (+ "errors""fmt""net/http""strconv"- "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/prompt"@@ -99,7 +99,7 @@ var s3GetCmd = &cobra.Command{InUse bool `json:"inUse"`}](cmd.Context(), http.MethodGet, types.BackupsS3DestinationInUse(resolved.ID), nil)if err != nil {- return errors.WrapIf(err, "failed to check S3 destination usage")+ return fmt.Errorf("failed to check S3 destination usage: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -162,7 +162,7 @@ var s3CreateCmd = &cobra.Command{dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPost, types.BackupsS3(), s3DestinationFromFlags())if err != nil {- return errors.WrapIf(err, "failed to create S3 destination")+ return fmt.Errorf("failed to create S3 destination: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -193,7 +193,7 @@ var s3UpdateCmd = &cobra.Command{dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPut, types.BackupsS3Destination(resolved.ID), s3DestinationFromFlags())if err != nil {- return errors.WrapIf(err, "failed to update S3 destination")+ return fmt.Errorf("failed to update S3 destination: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -236,7 +236,7 @@ var s3DeleteCmd = &cobra.Command{result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.BackupsS3Destination(resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to delete S3 destination")+ return fmt.Errorf("failed to delete S3 destination: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -286,7 +286,7 @@ passing the connection flags (--name, --bucket, --region, ...) with no argument.result, err := c.PostJSON[base.MessageResponse](cmd.Context(), testPath, testBody)if err != nil {- return errors.WrapIf(err, "failed to test S3 destination")+ return fmt.Errorf("failed to test S3 destination: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {diff --git a/cli/pkg/completion/cmd.go b/cli/pkg/completion/cmd.goindex fbf5747ae..aeee61b83 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 errors.Errorf("unsupported shell %q", args[0])+ return fmt.Errorf("unsupported shell %q", args[0])}},}diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.goindex 482a666b0..dae1518fc 100644--- a/cli/pkg/config/cmd.go+++ b/cli/pkg/config/cmd.go@@ -2,6 +2,7 @@ package configimport ("cmp"+ "errors""fmt""io""net/http"@@ -11,9 +12,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/getarcaneapp/arcane/cli/v2/internal/types""github.com/spf13/cobra")@@ -40,7 +40,7 @@ var configShowCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}path, _ := config.ConfigPath()@@ -57,7 +57,7 @@ var configShowCmd = &cobra.Command{fmt.Println("\nPagination Resources:")printed := 0- for _, resource := range clitypes.KnownPaginatedResources {+ for _, resource := range types.KnownPaginatedResources {limit := cfg.LimitFor(resource)explicit := cfg.Pagination.Resources != nil && cfg.Pagination.Resources[resource].Limit > 0label := "(inherit)"@@ -72,7 +72,7 @@ var configShowCmd = &cobra.Command{if cfg.Pagination.Resources != nil {extras := make([]string, 0)for k, v := range cfg.Pagination.Resources {- known := slices.Contains(clitypes.KnownPaginatedResources, k)+ known := slices.Contains(types.KnownPaginatedResources, k)if !known && v.Limit > 0 {extras = append(extras, k)}@@ -119,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 errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}updated := false@@ -140,7 +140,7 @@ Legacy flag syntax (flags shown below) is still supported:}if err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save config")+ return fmt.Errorf("failed to save config: %w", err)}path, _ := config.ConfigPath()@@ -169,7 +169,7 @@ var configTestCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}if err := cfg.Validate(); err != nil {@@ -182,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 errors.WrapIf(err, "failed to create request")+ return fmt.Errorf("failed to create request: %w", err)}// Prefer JWT bearer if present, else API key.if cfg.JWTToken != "" {@@ -193,13 +193,13 @@ var configTestCmd = &cobra.Command{resp, err := httpClient.Do(req)if err != nil {- return errors.WrapIf(err, "connection test failed")+ return fmt.Errorf("connection test failed: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode != http.StatusOK {body, _ := io.ReadAll(resp.Body)- return errors.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))+ return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))}fmt.Println("✓ Connection successful!")@@ -223,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 errors.WrapIf(err, "failed to initialize config")+ return fmt.Errorf("failed to initialize config: %w", err)}if !created {fmt.Printf("Config file already exists at %s (no changes made)\n", path)@@ -252,7 +252,7 @@ This removes the original config file from its previous path.`,backupPath, moved, err := config.BackupFile()if err != nil {- return errors.WrapIf(err, "failed to backup config")+ return fmt.Errorf("failed to backup config: %w", err)}if !moved {fmt.Printf("No config file found at %s (no changes made)\n", path)@@ -298,11 +298,11 @@ func parseResourceLimitPair(pair string) (resource string, limit int, ok bool) {if !found {return "", 0, false}- resource = clitypes.NormalizePaginatedResource(left)+ resource = types.NormalizePaginatedResource(left)if resource == "" {return "", 0, false}- known := slices.Contains(clitypes.KnownPaginatedResources, resource)+ known := slices.Contains(types.KnownPaginatedResources, resource)if !known {return "", 0, false}@@ -313,7 +313,7 @@ func parseResourceLimitPair(pair string) (resource string, limit int, ok bool) {return resource, parsed, true}-func applyConfigSetFlags(cmd *cobra.Command, cfg *clitypes.Config) (bool, error) {+func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {updated := falseif setServerURL != "" {@@ -374,10 +374,10 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *clitypes.Config) (bool, error)for _, pair := range setResourceLimit {resource, limit, ok := parseResourceLimitPair(pair)if !ok {- return false, errors.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, fmt.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(types.KnownPaginatedResources, ", "))}if limit < 0 {- return false, errors.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)+ return false, fmt.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)}cfg.SetResourceLimit(resource, limit)if limit == 0 {@@ -391,12 +391,12 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *clitypes.Config) (bool, error)return updated, nil}-func applyConfigSetArgs(cfg *clitypes.Config, args []string) (bool, error) {+func applyConfigSetArgs(cfg *types.Config, args []string) (bool, error) {if len(args) == 0 {return false, nil}if len(args)%2 != 0 {- 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))+ 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))}updated := false@@ -410,7 +410,7 @@ func applyConfigSetArgs(cfg *clitypes.Config, args []string) (bool, error) {return updated, nil}-func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {+func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {normalized := normalizeConfigKey(key)switch normalized {case "server-url", "server", "serverurl", "server_url":@@ -446,7 +446,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, errors.Errorf("invalid cli update channel %q (expected stable or next)", value)+ return false, fmt.Errorf("invalid cli update channel %q (expected stable or next)", value)}cfg.CLIUpdateChannel = channelfmt.Printf("Set cli_update_channel = %s\n", channel)@@ -466,10 +466,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, errors.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, fmt.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(types.KnownPaginatedResources, ", "))}if limit < 0 {- return false, errors.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)+ return false, fmt.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)}cfg.SetResourceLimit(resource, limit)if limit == 0 {@@ -489,13 +489,13 @@ func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {return applyResourceLimitByKey(cfg, key, resource, value)}- 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)+ 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)}-func applyResourceLimitByKey(cfg *clitypes.Config, key, resourceValue, limitValue string) (bool, error) {- resource := clitypes.NormalizePaginatedResource(resourceValue)+func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue string) (bool, error) {+ resource := types.NormalizePaginatedResource(resourceValue)if resource == "" || !isKnownPaginatedResource(resource) {- return false, errors.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(clitypes.KnownPaginatedResources, ", "))+ return false, fmt.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(types.KnownPaginatedResources, ", "))}limit, err := parseLimitValue(key, limitValue)if err != nil {@@ -511,16 +511,16 @@ func applyResourceLimitByKey(cfg *clitypes.Config, key, resourceValue, limitValu}func isKnownPaginatedResource(resource string) bool {- return slices.Contains(clitypes.KnownPaginatedResources, resource)+ return slices.Contains(types.KnownPaginatedResources, resource)}func parseLimitValue(key, value string) (int, error) {parsed, err := strconv.Atoi(strings.TrimSpace(value))if err != nil {- return 0, errors.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)+ return 0, fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)}if parsed < 0 {- return 0, errors.Errorf("invalid value %q for key %q (must be >= 0)", value, key)+ return 0, fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, key)}return parsed, nil}diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.goindex 6c4aa33c7..2afd86c07 100644--- a/cli/pkg/containers/actions.go+++ b/cli/pkg/containers/actions.go@@ -8,7 +8,6 @@ import ("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"@@ -135,7 +134,7 @@ var containersCommitCmd = &cobra.Command{result, err := c.PostJSON[container.CommitResult](cmd.Context(), types.ContainerCommit(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to commit container")+ return fmt.Errorf("failed to commit container: %w", err)}if jsonOutput {@@ -168,7 +167,7 @@ var containersEditCmd = &cobra.Command{if editFile == "" {result, err := c.GetJSON[container.EditConfig](cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get container edit config")+ return fmt.Errorf("failed to get container edit config: %w", err)}return cmdutil.PrintJSON(result.Data)@@ -176,18 +175,18 @@ var containersEditCmd = &cobra.Command{data, err := os.ReadFile(editFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", editFile)+ return fmt.Errorf("failed to read file %s: %w", editFile, err)}var body container.Editif err := json.Unmarshal(data, &body); err != nil {- return errors.WrapIf(err, "failed to parse edit payload")+ return fmt.Errorf("failed to parse edit payload: %w", err)}c.SetTimeout(30 * time.Minute)result, err := c.PostJSON[container.Details](cmd.Context(), types.ContainerEdit(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to edit container")+ return fmt.Errorf("failed to edit container: %w", err)}if jsonOutput {@@ -222,7 +221,7 @@ var containersAutoUpdateCmd = &cobra.Command{result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.ContainerAutoUpdate(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to set container auto-update")+ return fmt.Errorf("failed to set container auto-update: %w", err)}if jsonOutput {diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.goindex a0c1259bc..2ed674bf1 100644--- a/cli/pkg/containers/cmd.go+++ b/cli/pkg/containers/cmd.go@@ -3,6 +3,7 @@ package containersimport ("cmp""encoding/json/v2"+ "errors""fmt""net/url""os"@@ -10,7 +11,6 @@ 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"@@ -189,7 +189,7 @@ var containersGetCmd = &cobra.Command{if !complete {result, err := c.GetJSON[container.Details](cmd.Context(), types.Container(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get container")+ return fmt.Errorf("failed to get container: %w", err)}resolved = &result.Data}@@ -373,7 +373,7 @@ var containersDeleteCmd = &cobra.Command{path := types.Container(c.EnvID(), resolved.ID) + "?" + query.Encode()result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to delete container")+ return fmt.Errorf("failed to delete container: %w", err)}if jsonOutput {@@ -397,7 +397,7 @@ var containersCountsCmd = &cobra.Command{result, err := c.GetJSON[container.StatusCounts](cmd.Context(), types.ContainersCounts(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get container counts")+ return fmt.Errorf("failed to get container counts: %w", err)}if jsonOutput {@@ -430,10 +430,10 @@ var containersCreateCmd = &cobra.Command{if containerCreateFile != "" {data, err := os.ReadFile(containerCreateFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", containerCreateFile)+ return fmt.Errorf("failed to read file %s: %w", containerCreateFile, err)}if err := json.Unmarshal(data, &req); err != nil {- return errors.WrapIf(err, "failed to parse config file")+ return fmt.Errorf("failed to parse config file: %w", err)}}@@ -510,7 +510,7 @@ var containersCreateCmd = &cobra.Command{result, err := c.PostJSON[container.Created](cmd.Context(), types.Containers(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to create container")+ return fmt.Errorf("failed to create container: %w", err)}if jsonOutput {diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.goindex affedcfa2..58f03e4e4 100644--- a/cli/pkg/doctor/cmd.go+++ b/cli/pkg/doctor/cmd.go@@ -1,13 +1,14 @@package doctorimport (+ "errors"+ "fmt""strings"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""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"+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime""github.com/spf13/cobra")@@ -30,9 +31,9 @@ var DoctorCmd = &cobra.Command{Short: "Run CLI diagnostics",SilenceUsage: true,RunE: func(cmd *cobra.Command, args []string) error {- app, ok := runtimectx.From(cmd.Context())+ app, ok := runtime.From(cmd.Context())if !ok {- created, err := runtimectx.New(runtimectx.Options{})+ created, err := runtime.New(runtime.Options{})if err != nil {return err}@@ -104,7 +105,7 @@ var DoctorCmd = &cobra.Command{if jsonOutput || app.IsJSON() {if err := cmdutil.PrintJSON(rep); err != nil {- return errors.WrapIf(err, "failed to marshal doctor output")+ return fmt.Errorf("failed to marshal doctor output: %w", err)}} else {output.Header("Arcane CLI Diagnostics")diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.goindex 328a95228..b4cb30efb 100644--- a/cli/pkg/environments/cmd.go+++ b/cli/pkg/environments/cmd.go@@ -2,6 +2,7 @@ package environmentsimport ("cmp"+ "errors""fmt""net/http""sort"@@ -9,7 +10,6 @@ import ("strings""charm.land/lipgloss/v2"- "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/config"@@ -118,7 +118,7 @@ var deleteCmd = &cobra.Command{}if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Environment(args[0])); err != nil {- return errors.WrapIf(err, "failed to delete environment")+ return fmt.Errorf("failed to delete environment: %w", err)}output.Success("Environment deleted successfully")@@ -139,7 +139,7 @@ var getCmd = &cobra.Command{result, err := c.GetJSON[environment.Environment](cmd.Context(), types.Environment(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get environment")+ return fmt.Errorf("failed to get environment: %w", err)}if jsonOutput {@@ -188,7 +188,7 @@ var switchCmd = &cobra.Command{cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}c, err := client.NewFromConfig()@@ -199,7 +199,7 @@ var switchCmd = &cobra.Command{path := fmt.Sprintf("%s?limit=%d", types.Environments(), cmdutil.ShowAllLimit)result, err := c.DoJSON[base.Paginated[environment.Environment]](cmd.Context(), http.MethodGet, path, nil)if err != nil {- return errors.WrapIf(err, "failed to list environments")+ return fmt.Errorf("failed to list environments: %w", err)}if len(result.Data) == 0 {@@ -268,7 +268,7 @@ var switchCmd = &cobra.Command{cfg.DefaultEnvironment = selected.IDif err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save config")+ return fmt.Errorf("failed to save config: %w", err)}output.Success("Default environment set to %s", selected.ID)@@ -310,7 +310,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[environment.Environment](cmd.Context(), types.Environment(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update environment")+ return fmt.Errorf("failed to update environment: %w", err)}if jsonOutput {@@ -355,7 +355,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[environment.Environment](cmd.Context(), types.Environments(), req)if err != nil {- return errors.WrapIf(err, "failed to create environment")+ return fmt.Errorf("failed to create environment: %w", err)}if jsonOutput {@@ -388,7 +388,7 @@ var versionCmd = &cobra.Command{result, err := c.GetJSON[version.Info](cmd.Context(), types.EnvironmentVersion(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get environment version")+ return fmt.Errorf("failed to get environment version: %w", err)}if jsonOutput {diff --git a/cli/pkg/generate/api_key.go b/cli/pkg/generate/api_key.goindex 640a46c8c..e20f89fed 100644--- a/cli/pkg/generate/api_key.go+++ b/cli/pkg/generate/api_key.go@@ -1,11 +1,10 @@package generateimport (- crand "crypto/rand"+ "crypto/rand""encoding/hex""fmt"- "emperror.dev/errors""github.com/spf13/cobra")@@ -30,8 +29,8 @@ func init() {func GenerateAPIKey() (string, error) {keyBytes := make([]byte, apiKeyLength)- if _, err := crand.Read(keyBytes); err != nil {- return "", errors.WrapIf(err, "failed to generate API key")+ if _, err := rand.Read(keyBytes); err != nil {+ return "", fmt.Errorf("failed to generate API key: %w", err)}return apiKeyPrefix + hex.EncodeToString(keyBytes), nildiff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.goindex 287e3de2f..af72e624a 100644--- a/cli/pkg/generate/certs.go+++ b/cli/pkg/generate/certs.go@@ -5,10 +5,11 @@ import ("crypto/ecdsa""crypto/elliptic""crypto/mldsa"- crand "crypto/rand"+ "crypto/rand""crypto/x509""crypto/x509/pkix""encoding/pem"+ "errors""fmt""math/big""net"@@ -18,7 +19,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/spf13/cobra""go.getarcane.app/acfs/atomic")@@ -74,7 +74,7 @@ func init() {func generateMTLSOutputInternal() error {outDir, err := filepath.Abs(strings.TrimSpace(mtlsOutDir))if err != nil {- return errors.WrapIf(err, "failed to resolve output directory")+ return fmt.Errorf("failed to resolve output directory: %w", err)}paths, err := generateEdgeMTLSBundleInternal(outDir, strings.TrimSpace(mtlsEnvID), strings.TrimSpace(mtlsAppURL))@@ -99,7 +99,7 @@ func generateMTLSOutputInternal() error {func generateTLSOutputInternal() error {outDir, err := filepath.Abs(strings.TrimSpace(tlsOutDir))if err != nil {- return errors.WrapIf(err, "failed to resolve output directory")+ return fmt.Errorf("failed to resolve output directory: %w", err)}paths, err := generateServerTLSBundleInternal(outDir, strings.TrimSpace(tlsCommonName), tlsHosts, strings.TrimSpace(tlsCertName), strings.TrimSpace(tlsKeyName))@@ -133,26 +133,26 @@ func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPathreturn nil, errors.New("env ID is required")}if err := os.MkdirAll(outDir, 0o755); err != nil {- return nil, errors.WrapIf(err, "failed to create output directory")+ return nil, fmt.Errorf("failed to create output directory: %w", err)}caKey, err := GenerateMLDSA87PrivateKey()if err != nil {- return nil, errors.WrapIf(err, "failed to generate CA private key")+ return nil, fmt.Errorf("failed to generate CA private key: %w", err)}caTemplate, err := NewEdgeMTLSCATemplate()if err != nil {return nil, err}- caDER, err := x509.CreateCertificate(crand.Reader, caTemplate, caTemplate, caKey.PublicKey(), caKey)+ caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, caKey.PublicKey(), caKey)if err != nil {- return nil, errors.WrapIf(err, "failed to create CA certificate")+ return nil, fmt.Errorf("failed to create CA certificate: %w", err)}clientKey, err := GenerateMLDSA87PrivateKey()if err != nil {- return nil, errors.WrapIf(err, "failed to generate client private key")+ return nil, fmt.Errorf("failed to generate client private key: %w", err)}trustDomain := EdgeMTLSTrustDomain(appURL)dnsSANs := []string{"arcane-agent"}@@ -166,11 +166,11 @@ func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPathcaCert, err := x509.ParseCertificate(caDER)if err != nil {- return nil, errors.WrapIf(err, "failed to parse generated CA certificate")+ return nil, fmt.Errorf("failed to parse generated CA certificate: %w", err)}- clientDER, err := x509.CreateCertificate(crand.Reader, clientTemplate, caCert, clientKey.PublicKey(), caKey)+ clientDER, err := x509.CreateCertificate(rand.Reader, clientTemplate, caCert, clientKey.PublicKey(), caKey)if err != nil {- return nil, errors.WrapIf(err, "failed to create client certificate")+ return nil, fmt.Errorf("failed to create client certificate: %w", err)}paths := &edgeMTLSPaths{@@ -202,12 +202,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, errors.WrapIf(err, "failed to create output directory")+ return nil, fmt.Errorf("failed to create output directory: %w", err)}privateKey, err := GenerateP384PrivateKey()if err != nil {- return nil, errors.WrapIf(err, "failed to generate server private key")+ return nil, fmt.Errorf("failed to generate server private key: %w", err)}template, err := NewServerTLSTemplate(commonName, hosts)@@ -215,9 +215,9 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,return nil, err}- certDER, err := x509.CreateCertificate(crand.Reader, template, template, &privateKey.PublicKey, privateKey)+ certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)if err != nil {- return nil, errors.WrapIf(err, "failed to create server certificate")+ return nil, fmt.Errorf("failed to create server certificate: %w", err)}paths := &serverTLSPaths{@@ -232,7 +232,7 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,// GenerateP384PrivateKey generates an ECDSA P-384 private key.func GenerateP384PrivateKey() (*ecdsa.PrivateKey, error) {- return ecdsa.GenerateKey(elliptic.P384(), crand.Reader)+ return ecdsa.GenerateKey(elliptic.P384(), rand.Reader)}// GenerateMLDSA87PrivateKey generates an ML-DSA-87 private key.@@ -360,9 +360,9 @@ func newCertificateTemplateInternal(commonName string) (*x509.Certificate, errorfunc randomSerialInternal() (*big.Int, error) {limit := new(big.Int).Lsh(big.NewInt(1), 128)- serial, err := crand.Int(crand.Reader, limit)+ serial, err := rand.Int(rand.Reader, limit)if err != nil {- return nil, errors.WrapIf(err, "failed to generate certificate serial")+ return nil, fmt.Errorf("failed to generate certificate serial: %w", err)}return serial, nil}@@ -370,7 +370,7 @@ func randomSerialInternal() (*big.Int, error) {func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, privateKey crypto.PrivateKey) error {keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)if err != nil {- return errors.WrapIf(err, "failed to marshal private key")+ return fmt.Errorf("failed to marshal private key: %w", err)}if err := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); err != nil {return err@@ -384,7 +384,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 errors.Errorf("failed to encode PEM file %s", path)+ return fmt.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 7955a491b..271e58d52 100644--- a/cli/pkg/generate/secret.go+++ b/cli/pkg/generate/secret.go@@ -6,7 +6,6 @@ import ("encoding/hex""fmt"- "emperror.dev/errors""github.com/spf13/cobra")@@ -33,7 +32,7 @@ func init() {func generateSecrets() error {encryptionKey := make([]byte, secretLength)if _, err := rand.Read(encryptionKey); err != nil {- return errors.WrapIf(err, "failed to generate encryption key")+ return fmt.Errorf("failed to generate encryption key: %w", err)}switch secretFormat {@@ -48,7 +47,7 @@ func generateSecrets() error {case "all":printAllFormats(encryptionKey)default:- return errors.Errorf("unknown format: %s (supported: base64, hex, env, docker, all)", secretFormat)+ return fmt.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 d4d4fde59..f33804d73 100644--- a/cli/pkg/gitops/cmd.go+++ b/cli/pkg/gitops/cmd.go@@ -5,7 +5,6 @@ import ("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"@@ -117,7 +116,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSyncs(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to create gitops sync")+ return fmt.Errorf("failed to create gitops sync: %w", err)}if jsonOutput {@@ -149,7 +148,7 @@ var getCmd = &cobra.Command{if !complete {result, err := c.GetJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get gitops sync")+ return fmt.Errorf("failed to get gitops sync: %w", err)}resolved = &result.Data}@@ -220,12 +219,12 @@ var updateCmd = &cobra.Command{resp, err := c.Put(cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID), req)if err != nil {- return errors.WrapIf(err, "failed to update gitops sync")+ return fmt.Errorf("failed to update gitops sync: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to update gitops sync")+ return fmt.Errorf("failed to update gitops sync: %w", err)}output.Success("GitOps sync %s updated successfully", resolved.Name)@@ -267,11 +266,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to delete gitops sync")+ return fmt.Errorf("failed to delete gitops sync: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete gitops sync")+ return fmt.Errorf("failed to delete gitops sync: %w", err)}output.Success("GitOps sync %s deleted successfully", resolved.Name)@@ -297,7 +296,7 @@ var statusCmd = &cobra.Command{result, err := c.GetJSON[gitops.SyncStatus](cmd.Context(), types.GitOpsSyncStatus(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get gitops sync status")+ return fmt.Errorf("failed to get gitops sync status: %w", err)}if jsonOutput {@@ -344,7 +343,7 @@ var syncCmd = &cobra.Command{result, err := c.PostJSON[gitops.SyncResult](cmd.Context(), types.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)if err != nil {- return errors.WrapIf(err, "failed to trigger gitops sync")+ return fmt.Errorf("failed to trigger gitops sync: %w", err)}if jsonOutput {@@ -360,7 +359,7 @@ var syncCmd = &cobra.Command{if result.Data.Error != nil {errMsg = *result.Data.Error}- return errors.Errorf("sync failed: %s %s", result.Data.Message, errMsg)+ return fmt.Errorf("sync failed: %s %s", result.Data.Message, errMsg)},}@@ -387,7 +386,7 @@ var filesCmd = &cobra.Command{result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), filesPath)if err != nil {- return errors.WrapIf(err, "failed to get gitops sync files")+ return fmt.Errorf("failed to get gitops sync files: %w", err)}files := result.Data.Files@@ -434,7 +433,7 @@ var importCmd = &cobra.Command{// in an array.result, err := c.PostJSON[gitops.ImportGitOpsSyncResponse](cmd.Context(), types.GitOpsSyncsImport(c.EnvID()), []gitops.ImportGitOpsSyncRequest{req})if err != nil {- return errors.WrapIf(err, "failed to import gitops sync")+ return fmt.Errorf("failed to import gitops sync: %w", err)}if jsonOutput {diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.goindex 68bea08b2..4ecbe1be9 100644--- a/cli/pkg/images/cmd.go+++ b/cli/pkg/images/cmd.go@@ -1,39 +1,10 @@-// Package images provides CLI commands for managing Docker images on Arcane servers.-//-// This package implements the "arcane images" command group, which includes-// subcommands for listing, inspecting, pulling, removing, pruning, and uploading-// Docker images.-//-// # Available Commands-//-// - list: List all images with optional filtering and pagination-// - get: Get detailed information about a specific image-// - pull: Pull an image from a container registry-// - remove: Remove an image from the server-// - prune: Remove unused images to reclaim disk space-// - counts: Display image usage statistics-// - upload: Upload a Docker image from a tar archive-// - updates: Check for image updates-//-// # Example Usage-//-// # List all images-// arcane images list-//-// # Pull an image-// arcane images pull nginx:latest-//-// # Get image details-// arcane images get sha256:abc123...-//-// # Remove unused images-// arcane images prunepackage imagesimport ("context""encoding/json/jsontext""encoding/json/v2"+ "errors""fmt""io""net/http"@@ -42,7 +13,6 @@ 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/logger"@@ -164,13 +134,13 @@ var imagesGetCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get image")+ return fmt.Errorf("failed to get image: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read response")+ return fmt.Errorf("failed to read response: %w", err)}log.Debugf("Response body: %s", string(body))@@ -186,7 +156,7 @@ var imagesGetCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Header("Image Details")@@ -259,7 +229,7 @@ var imagesRemoveCmd = &cobra.Command{if removeForce {u, err := url.Parse(path)if err != nil {- return errors.WrapIf(err, "failed to parse path")+ return fmt.Errorf("failed to parse path: %w", err)}q := u.Query()q.Set("force", "true")@@ -271,17 +241,17 @@ var imagesRemoveCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to remove image")+ return fmt.Errorf("failed to remove image: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return errors.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return fmt.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))}body, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read response")+ return fmt.Errorf("failed to read response: %w", err)}log.Debugf("Response body: %s", string(body))@@ -299,7 +269,7 @@ var imagesRemoveCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Success("%s", result.Data.Message)@@ -334,19 +304,19 @@ var imagesPullCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), path, requestBody)if err != nil {- return errors.WrapIf(err, "failed to pull image")+ return fmt.Errorf("failed to pull image: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return errors.Errorf("failed to pull image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return fmt.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 errors.WrapIf(err, "failed to read pull stream")+ return fmt.Errorf("failed to read pull stream: %w", err)}return nil}@@ -373,7 +343,7 @@ var imagesPullCmd = &cobra.Command{if errors.Is(err, io.EOF) {break}- return errors.WrapIf(err, "failed to decode stream")+ return fmt.Errorf("failed to decode stream: %w", err)}// The stream opens with an activity frame that carries no Docker@@ -386,7 +356,9 @@ var imagesPullCmd = &cobra.Command{if progressUI != nil {progressUI.Stop()}- return errors.Errorf("pull error: %s", event.Error)++ return fmt.Errorf("pull error: %s", event.Error)+}if event.Status == "Downloading" && event.ProgressDetail.Total > 0 {@@ -467,17 +439,17 @@ var imagesPruneCmd = &cobra.Command{}if err != nil {- return errors.WrapIf(err, "failed to prune images")+ return fmt.Errorf("failed to prune images: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return errors.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))+ return fmt.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))}body, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read response")+ return fmt.Errorf("failed to read response: %w", err)}log.Debugf("Response body: %s", string(body))@@ -496,7 +468,7 @@ var imagesPruneCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Success("Pruned %d images, reclaimed %s", len(result.Data.ImagesDeleted), output.Bytes(result.Data.SpaceReclaimed))@@ -522,13 +494,13 @@ var imagesCountsCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get image counts")+ return fmt.Errorf("failed to get image counts: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := io.ReadAll(resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read response")+ return fmt.Errorf("failed to read response: %w", err)}log.Debugf("Response body: %s", string(body))@@ -544,7 +516,7 @@ var imagesCountsCmd = &cobra.Command{}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Header("Image Usage Counts")@@ -584,7 +556,7 @@ var imagesUploadCmd = &cobra.Command{respBody, err := c.DoRaw(cmd.Context(), http.MethodPost, types.ImagesUpload(c.EnvID()), uploadtypes.ConsumeRequest{UploadID: sessionID})if err != nil {cmdutil.AbortUploadSession(cmd.Context(), c, uploadtypes.KindImage, sessionID)- return errors.WrapIf(err, "failed to upload image")+ return fmt.Errorf("failed to upload image: %w", err)}log.Debugf("Response body: %s", string(respBody))@@ -600,11 +572,11 @@ var imagesUploadCmd = &cobra.Command{}if err := json.Unmarshal(respBody, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}if !result.Success {- return errors.Errorf("upload failed: %s", string(respBody))+ return fmt.Errorf("upload failed: %s", string(respBody))}output.Success("Image uploaded successfully")@@ -671,7 +643,7 @@ var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{IDOf: func(match image.Summary) string { return match.ID },Validate: func(details image.DetailSummary, identifier string) error {if details.ID == "" {- return errors.Errorf("image lookup for %q returned empty ID", identifier)+ return fmt.Errorf("image lookup for %q returned empty ID", identifier)}return nil},@@ -693,7 +665,7 @@ func searchImageCandidatesInternal(ctx context.Context, c *client.Client, identisearchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Images(c.EnvID()), url.QueryEscape(term), cmdutil.ShowAllLimit)result, err := c.GetJSON[[]image.Summary](ctx, searchPath)if err != nil {- return nil, errors.WrapIf(err, "failed to search images")+ return nil, fmt.Errorf("failed to search images: %w", err)}identifierLower := strings.ToLower(identifier)diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.goindex f87544f83..930335c05 100644--- a/cli/pkg/images/extra.go+++ b/cli/pkg/images/extra.go@@ -4,6 +4,7 @@ import ("bufio""cmp""encoding/json/v2"+ "errors""fmt""io""net/http"@@ -13,7 +14,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -42,7 +42,7 @@ var imagesSearchCmd = &cobra.Command{result, err := c.GetJSON[[]image.SearchResult](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to search images")+ return fmt.Errorf("failed to search images: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -92,13 +92,13 @@ var imagesHistoryCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get image history")+ return fmt.Errorf("failed to get image history: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := cmdutil.ReadJSONBody(resp)if err != nil {- return errors.WrapIf(err, "failed to get image history")+ return fmt.Errorf("failed to get image history: %w", err)}if jsonOutput {@@ -110,7 +110,7 @@ var imagesHistoryCmd = &cobra.Command{Data []image.HistoryItem `json:"data"`}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}headers := []string{"CREATED", "CREATED BY", "SIZE", "COMMENT"}@@ -161,13 +161,13 @@ var imagesTagCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), path, image.TagRequest{Repository: repository, Tag: tag})if err != nil {- return errors.WrapIf(err, "failed to tag image")+ return fmt.Errorf("failed to tag image: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := cmdutil.ReadJSONBody(resp)if err != nil {- return errors.WrapIf(err, "failed to tag image")+ return fmt.Errorf("failed to tag image: %w", err)}if jsonOutput {@@ -179,7 +179,7 @@ var imagesTagCmd = &cobra.Command{Data base.MessageResponse `json:"data"`}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Success("%s", result.Data.Message)@@ -222,16 +222,16 @@ var imagesExportCmd = &cobra.Command{resp, err := c.RequestRaw(cmd.Context(), http.MethodGet, path, nil, nil)if err != nil {- return errors.WrapIf(err, "failed to export image")+ return fmt.Errorf("failed to export image: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to export image")+ return fmt.Errorf("failed to export image: %w", err)}file, err := os.Create(outputFile)if err != nil {- return errors.WrapIf(err, "failed to create output file")+ return fmt.Errorf("failed to create output file: %w", err)}written, err := io.Copy(file, resp.Body)@@ -240,7 +240,7 @@ var imagesExportCmd = &cobra.Command{}if err != nil {_ = os.Remove(outputFile)- return errors.WrapIf(err, "failed to write image archive")+ return fmt.Errorf("failed to write image archive: %w", err)}output.Success("Saved %s (%s)", outputFile, output.Bytes(written))@@ -291,7 +291,7 @@ var imagesAttestationsCmd = &cobra.Command{u, err := url.Parse(types.ImageAttestations(c.EnvID(), imageName))if err != nil {- return errors.WrapIf(err, "failed to parse endpoint path")+ return fmt.Errorf("failed to parse endpoint path: %w", err)}q := u.Query()if attestationsPlatform != "" {@@ -310,13 +310,13 @@ var imagesAttestationsCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get image attestations")+ return fmt.Errorf("failed to get image attestations: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := cmdutil.ReadJSONBody(resp)if err != nil {- return errors.WrapIf(err, "failed to get image attestations")+ return fmt.Errorf("failed to get image attestations: %w", err)}if cmdutil.JSONOutputEnabled(cmd) || attestationsStatement {@@ -328,7 +328,7 @@ var imagesAttestationsCmd = &cobra.Command{Data image.AttestationList `json:"data"`}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}output.Header("Image Attestations")@@ -380,7 +380,7 @@ var imagesBuildCmd = &cobra.Command{if buildInlineFile != "" {content, err := os.ReadFile(buildInlineFile)if err != nil {- return errors.WrapIf(err, "failed to read Dockerfile")+ return fmt.Errorf("failed to read Dockerfile: %w", err)}requestBody["dockerfileInline"] = string(content)}@@ -395,7 +395,7 @@ var imagesBuildCmd = &cobra.Command{for _, arg := range buildArgs {key, value, ok := strings.Cut(arg, "=")if !ok || key == "" {- return errors.Errorf("invalid build arg %q; expected KEY=VALUE", arg)+ return fmt.Errorf("invalid build arg %q; expected KEY=VALUE", arg)}parsed[key] = value}@@ -429,17 +429,17 @@ var imagesBuildCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), path, requestBody)if err != nil {- return errors.WrapIf(err, "failed to build image")+ return fmt.Errorf("failed to build image: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to build image")+ return fmt.Errorf("failed to build image: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {_, err = io.Copy(cmd.OutOrStdout(), resp.Body)if err != nil {- return errors.WrapIf(err, "failed to read build stream")+ return fmt.Errorf("failed to read build stream: %w", err)}return nil}@@ -471,7 +471,7 @@ func streamBuildOutput(body io.Reader) error {}if json.Unmarshal([]byte(trimmed), &frame) == nil {if frame.Error != "" {- return errors.Errorf("build error: %s", frame.Error)+ return fmt.Errorf("build error: %s", frame.Error)}if frame.Done {done = true@@ -485,7 +485,7 @@ func streamBuildOutput(body io.Reader) error {fmt.Println(line)}if err := scanner.Err(); err != nil {- return errors.WrapIf(err, "failed to read build stream")+ return fmt.Errorf("failed to read build stream: %w", err)}if !done {return errors.New("build stream ended without completion frame")@@ -549,13 +549,13 @@ var imagesBuildsGetCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get image build")+ return fmt.Errorf("failed to get image build: %w", err)}defer func() { _ = resp.Body.Close() }()body, err := cmdutil.ReadJSONBody(resp)if err != nil {- return errors.WrapIf(err, "failed to get image build")+ return fmt.Errorf("failed to get image build: %w", err)}if cmdutil.JSONOutputEnabled(cmd) {@@ -567,7 +567,7 @@ var imagesBuildsGetCmd = &cobra.Command{Data image.BuildRecord `json:"data"`}if err := json.Unmarshal(body, &result); err != nil {- return errors.WrapIf(err, "failed to parse response")+ return fmt.Errorf("failed to parse response: %w", err)}record := result.Datadiff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.goindex 9d0c22d12..94ebd4be6 100644--- a/cli/pkg/images/updates/cmd.go+++ b/cli/pkg/images/updates/cmd.go@@ -1,12 +1,12 @@package updatesimport (+ "errors""fmt""maps""slices""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"@@ -44,7 +44,7 @@ var checkCmd = &cobra.Command{result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})if err != nil {- return errors.WrapIf(err, "failed to check all updates")+ return fmt.Errorf("failed to check all updates: %w", err)}return printBatchResultsInternal(result.Data)}@@ -56,14 +56,14 @@ var checkCmd = &cobra.Command{if len(args) > 1 {result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})if err != nil {- return errors.WrapIf(err, "failed to check updates")+ return fmt.Errorf("failed to check updates: %w", err)}return printBatchResultsInternal(result.Data)}result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))if err != nil {- return errors.WrapIf(err, "failed to check updates")+ return fmt.Errorf("failed to check updates: %w", err)}if jsonOutput {@@ -98,7 +98,7 @@ var checkAllCmd = &cobra.Command{// The handler declares a non-pointer Body, so an empty body is a 400.result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})if err != nil {- return errors.WrapIf(err, "failed to check all updates")+ return fmt.Errorf("failed to check all updates: %w", err)}if jsonOutput {@@ -133,7 +133,7 @@ var checkImageCmd = &cobra.Command{result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheckById(c.EnvID(), args[0]))if err != nil {- return errors.WrapIf(err, "failed to check image update")+ return fmt.Errorf("failed to check image update: %w", err)}if jsonOutput {@@ -165,7 +165,7 @@ var summaryCmd = &cobra.Command{result, err := c.GetJSON[imageupdate.Summary](cmd.Context(), types.ImageUpdatesSummary(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get summary")+ return fmt.Errorf("failed to get summary: %w", err)}if jsonOutput {diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.goindex 77284ea6d..626cbebdc 100644--- a/cli/pkg/jobs/cmd.go+++ b/cli/pkg/jobs/cmd.go@@ -2,12 +2,12 @@ package jobsimport ("crypto/rand"+ "errors""fmt""net/http""strconv""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"@@ -40,7 +40,7 @@ var getCmd = &cobra.Command{cfg, err := c.DoJSON[jobschedule.Config](cmd.Context(), http.MethodGet, types.JobSchedules(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to get job schedules")+ return fmt.Errorf("failed to get job schedules: %w", err)}if jsonOutput {@@ -88,7 +88,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[jobschedule.Config](cmd.Context(), types.JobSchedules(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to update job schedules")+ return fmt.Errorf("failed to update job schedules: %w", err)}if jsonOutput {@@ -116,7 +116,7 @@ var listCmd = &cobra.Command{result, err := c.DoJSON[jobschedule.JobListResponse](cmd.Context(), http.MethodGet, types.Jobs(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to list jobs")+ return fmt.Errorf("failed to list jobs: %w", err)}if jsonOutput {@@ -167,7 +167,7 @@ var runCmd = &cobra.Command{}result, err := c.DoJSON[jobschedule.JobRunResponse](cmd.Context(), http.MethodPost, types.JobRun(c.EnvID(), args[0]), nil, http.Header{"Idempotency-Key": []string{id}})if err != nil {- return errors.WrapIff(err, "failed to queue job (reuse --request-id %s if delivery is uncertain)", id)+ return fmt.Errorf("failed to queue job (reuse --request-id %s if delivery is uncertain): %w", id, err)}if jsonOutput {@@ -175,7 +175,7 @@ var runCmd = &cobra.Command{}if !result.Success {- return errors.Errorf("job %s failed: %s", args[0], result.Message)+ return fmt.Errorf("job %s failed: %s", args[0], result.Message)}output.Success("%s", result.Message)output.KeyValue("Run ID", result.RunID)diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.goindex 434faaabc..e34d11c23 100644--- a/cli/pkg/networks/cmd.go+++ b/cli/pkg/networks/cmd.go@@ -1,11 +1,11 @@package networksimport (+ "errors""fmt""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"@@ -129,7 +129,7 @@ var getCmd = &cobra.Command{if !complete {result, err := c.GetJSON[network.Inspect](cmd.Context(), types.Network(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get network")+ return fmt.Errorf("failed to get network: %w", err)}resolved = &result.Data}@@ -187,7 +187,7 @@ var deleteCmd = &cobra.Command{result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Network(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to delete network")+ return fmt.Errorf("failed to delete network: %w", err)}if jsonOutput {@@ -211,7 +211,7 @@ var countsCmd = &cobra.Command{result, err := c.GetJSON[network.UsageCounts](cmd.Context(), types.NetworksCounts(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get network counts")+ return fmt.Errorf("failed to get network counts: %w", err)}if jsonOutput {@@ -249,7 +249,7 @@ var pruneCmd = &cobra.Command{result, err := c.PostJSON[network.PruneReport](cmd.Context(), types.NetworksPrune(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to prune networks")+ return fmt.Errorf("failed to prune networks: %w", err)}if jsonOutput {@@ -315,7 +315,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[network.CreateResponse](cmd.Context(), types.Networks(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to create network")+ return fmt.Errorf("failed to create network: %w", err)}if jsonOutput {@@ -357,7 +357,7 @@ var connectCmd = &cobra.Command{result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkConnect(c.EnvID(), resolved.ID), req)if err != nil {- return errors.WrapIf(err, "failed to connect container to network")+ return fmt.Errorf("failed to connect container to network: %w", err)}if jsonOutput {@@ -397,7 +397,7 @@ var disconnectCmd = &cobra.Command{result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkDisconnect(c.EnvID(), resolved.ID), req)if err != nil {- return errors.WrapIf(err, "failed to disconnect container from network")+ return fmt.Errorf("failed to disconnect container from network: %w", err)}if jsonOutput {@@ -425,7 +425,7 @@ var topologyCmd = &cobra.Command{result, err := c.GetJSON[network.Topology](cmd.Context(), types.NetworksTopology(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get network topology")+ return fmt.Errorf("failed to get network topology: %w", err)}if jsonOutput {diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.goindex be42b340f..c8d783a6a 100644--- a/cli/pkg/projects/actions.go+++ b/cli/pkg/projects/actions.go@@ -1,6 +1,7 @@package projectsimport (+ "errors""fmt""io""net/http"@@ -10,7 +11,6 @@ import ("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"@@ -43,7 +43,7 @@ var tagsCmd = &cobra.Command{result, err := c.GetJSON[[]project.TagOption](cmd.Context(), types.ProjectsTags(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to list project tags")+ return fmt.Errorf("failed to list project tags: %w", err)}if jsonOutput {@@ -95,7 +95,7 @@ var tagCmd = &cobra.Command{result, err := c.DoJSON[base.ApiResponse[project.UpdateTagResponse]](cmd.Context(), http.MethodPatch, types.ProjectTags(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to update project tag")+ return fmt.Errorf("failed to update project tag: %w", err)}if jsonOutput {@@ -191,15 +191,15 @@ var buildCmd = &cobra.Command{resp, err := c.Post(cmd.Context(), types.ProjectBuild(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to build project images")+ return fmt.Errorf("failed to build project images: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to build project images")+ return fmt.Errorf("failed to build project images: %w", err)}if err := printOperationStreamInternal(resp.Body); err != nil {- return errors.WrapIf(err, "failed to build project images")+ return fmt.Errorf("failed to build project images: %w", err)}output.Success("Images built successfully for project %s", resolved.Name)@@ -231,7 +231,7 @@ var updateServicesCmd = &cobra.Command{result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.ProjectUpdateServices(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to update project services")+ return fmt.Errorf("failed to update project services: %w", err)}if jsonOutput {@@ -267,7 +267,7 @@ var workspaceCatCmd = &cobra.Command{reqPath := types.ProjectWorkspaceFile(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])result, err := c.GetJSON[workspacetypes.FileContent](cmd.Context(), reqPath)if err != nil {- return errors.WrapIf(err, "failed to get workspace file")+ return fmt.Errorf("failed to get workspace file: %w", err)}if jsonOutput {@@ -275,7 +275,7 @@ var workspaceCatCmd = &cobra.Command{}if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {- return errors.Errorf("file %s has no inline content (%s); use `arcane projects workspace download` instead", args[1], result.Data.ReadOnlyReason)+ return fmt.Errorf("file %s has no inline content (%s); use `arcane projects workspace download` instead", args[1], result.Data.ReadOnlyReason)}fmt.Print(result.Data.Content)return nil@@ -301,11 +301,11 @@ var workspaceDownloadCmd = &cobra.Command{reqPath := types.ProjectWorkspaceFileDownload(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])resp, err := c.Get(cmd.Context(), reqPath)if err != nil {- return errors.WrapIf(err, "failed to download workspace file")+ return fmt.Errorf("failed to download workspace file: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to download workspace file")+ return fmt.Errorf("failed to download workspace file: %w", err)}outputFile := path.Base(args[1])@@ -315,15 +315,15 @@ var workspaceDownloadCmd = &cobra.Command{file, err := os.Create(outputFile)if err != nil {- return errors.WrapIff(err, "failed to create file %s", outputFile)+ return fmt.Errorf("failed to create file %s: %w", outputFile, err)}written, copyErr := io.Copy(file, resp.Body)closeErr := file.Close()if copyErr != nil {- return errors.WrapIf(copyErr, "failed to write workspace file")+ return fmt.Errorf("failed to write workspace file: %w", copyErr)}if closeErr != nil {- return errors.WrapIf(closeErr, "failed to write workspace file")+ return fmt.Errorf("failed to write workspace file: %w", closeErr)}output.Success("Downloaded %s (%d bytes) to %s", args[1], written, outputFile)diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.goindex 5f8b0379a..d64514370 100644--- a/cli/pkg/projects/cmd.go+++ b/cli/pkg/projects/cmd.go@@ -4,6 +4,7 @@ import ("bufio""bytes""encoding/json/v2"+ "errors""fmt""io""mime/multipart"@@ -15,7 +16,6 @@ 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"@@ -191,11 +191,11 @@ var destroyCmd = &cobra.Command{RemoveVolumes: destroyRemoveVolumes,})if err != nil {- return errors.WrapIf(err, "failed to destroy project")+ return fmt.Errorf("failed to destroy project: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to destroy project")+ return fmt.Errorf("failed to destroy project: %w", err)}output.Success("Project %s destroyed successfully", resolved.Name)@@ -223,7 +223,7 @@ var getCmd = &cobra.Command{if !complete {result, err := c.GetJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get project")+ return fmt.Errorf("failed to get project: %w", err)}resolved = &result.Data}@@ -357,15 +357,15 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectStresp, err := c.Post(cmd.Context(), cfg.endpoint(c.EnvID(), resolved.ID), nil)if err != nil {- return errors.WrapIff(err, "%s", cfg.failureMessage)+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIff(err, "%s", cfg.failureMessage)+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)}if err := printOperationStreamInternal(resp.Body); err != nil {- return errors.WrapIff(err, "%s", cfg.failureMessage)+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)}output.Success(cfg.successMessage, resolved.Name)@@ -419,7 +419,7 @@ var createCmd = &cobra.Command{composeBytes, err := os.ReadFile(createFile)if err != nil {- return errors.WrapIf(err, "failed to read compose file")+ return fmt.Errorf("failed to read compose file: %w", err)}body := project.CreateProject{@@ -430,7 +430,7 @@ var createCmd = &cobra.Command{if createEnvFile != "" {envBytes, err := os.ReadFile(createEnvFile)if err != nil {- return errors.WrapIf(err, "failed to read env file")+ return fmt.Errorf("failed to read env file: %w", err)}body.EnvContent = new(string(envBytes))}@@ -440,31 +440,31 @@ var createCmd = &cobra.Command{projectJSON, err := json.Marshal(body)if err != nil {- return errors.WrapIf(err, "failed to encode project configuration")+ return fmt.Errorf("failed to encode project configuration: %w", err)}manifestJSON, err := json.Marshal(project.CreateProjectWorkspaceManifest{FileChanges: []project.WorkspaceFileChange{}})if err != nil {- return errors.WrapIf(err, "failed to encode project workspace manifest")+ return fmt.Errorf("failed to encode project workspace manifest: %w", err)}var requestBody bytes.Bufferwriter := multipart.NewWriter(&requestBody)if err := writer.WriteField("project", string(projectJSON)); err != nil {- return errors.WrapIf(err, "failed to write project configuration")+ return fmt.Errorf("failed to write project configuration: %w", err)}if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {- return errors.WrapIf(err, "failed to write project workspace manifest")+ return fmt.Errorf("failed to write project workspace manifest: %w", err)}if err := writer.Close(); err != nil {- return errors.WrapIf(err, "failed to finalize project request")+ return fmt.Errorf("failed to finalize project request: %w", err)}resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, types.Projects(c.EnvID()), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})if err != nil {- return errors.WrapIf(err, "failed to create project")+ return fmt.Errorf("failed to create project: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to create project")+ return fmt.Errorf("failed to create project: %w", err)}var result base.ApiResponse[project.CreateReponse]@@ -511,7 +511,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("file") {composeBytes, err := os.ReadFile(updateFile)if err != nil {- return errors.WrapIf(err, "failed to read compose file")+ return fmt.Errorf("failed to read compose file: %w", err)}body.ComposeContent = new(string(composeBytes))}@@ -519,14 +519,14 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("env-file") {envBytes, err := os.ReadFile(updateEnvFile)if err != nil {- return errors.WrapIf(err, "failed to read env file")+ return fmt.Errorf("failed to read env file: %w", err)}body.EnvContent = new(string(envBytes))}result, err := c.PutJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID), body)if err != nil {- return errors.WrapIf(err, "failed to update project")+ return fmt.Errorf("failed to update project: %w", err)}if jsonOutput {@@ -557,12 +557,12 @@ var updateIncludesCmd = &cobra.Command{content, err := os.ReadFile(includesFile)if err != nil {- return errors.WrapIf(err, "failed to read include file")+ return fmt.Errorf("failed to read include file: %w", err)}current, err := c.GetJSON[workspacetypes.Workspace](cmd.Context(), types.ProjectWorkspace(c.EnvID(), resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to get project workspace")+ return fmt.Errorf("failed to get project workspace: %w", err)}relativePath := filepath.ToSlash(filepath.Base(includesFile))@@ -580,31 +580,31 @@ var updateIncludesCmd = &cobra.Command{}manifestJSON, err := json.Marshal(manifest)if err != nil {- return errors.WrapIf(err, "failed to encode workspace manifest")+ return fmt.Errorf("failed to encode workspace manifest: %w", err)}var requestBody bytes.Bufferwriter := multipart.NewWriter(&requestBody)if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {- return errors.WrapIf(err, "failed to write workspace manifest")+ return fmt.Errorf("failed to write workspace manifest: %w", err)}filePart, err := writer.CreateFormFile("files", filepath.Base(includesFile))if err != nil {- return errors.WrapIf(err, "failed to create workspace upload")+ return fmt.Errorf("failed to create workspace upload: %w", err)}if _, err := filePart.Write(content); err != nil {- return errors.WrapIf(err, "failed to write workspace upload")+ return fmt.Errorf("failed to write workspace upload: %w", err)}if err := writer.Close(); err != nil {- return errors.WrapIf(err, "failed to finalize workspace upload")+ return fmt.Errorf("failed to finalize workspace upload: %w", err)}resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.ProjectWorkspace(c.EnvID(), resolved.ID), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})if err != nil {- return errors.WrapIf(err, "failed to update include file")+ return fmt.Errorf("failed to update include file: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to update include file")+ return fmt.Errorf("failed to update include file: %w", err)}if jsonOutput {@@ -632,7 +632,7 @@ var countsCmd = &cobra.Command{result, err := c.GetJSON[map[string]any](cmd.Context(), types.ProjectsCounts(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get project counts")+ return fmt.Errorf("failed to get project counts: %w", err)}if jsonOutput {diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.goindex b83e2295a..7c61bc3d5 100644--- a/cli/pkg/registries/cmd.go+++ b/cli/pkg/registries/cmd.go@@ -1,10 +1,10 @@package registriesimport (+ "errors""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"@@ -122,7 +122,7 @@ var getCmd = &cobra.Command{result, err := c.GetJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get registry")+ return fmt.Errorf("failed to get registry: %w", err)}if jsonOutput {@@ -170,7 +170,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistries(), req)if err != nil {- return errors.WrapIf(err, "failed to create registry")+ return fmt.Errorf("failed to create registry: %w", err)}if jsonOutput {@@ -247,7 +247,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update registry")+ return fmt.Errorf("failed to update registry: %w", err)}if jsonOutput {@@ -284,11 +284,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.ContainerRegistry(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete registry")+ return fmt.Errorf("failed to delete registry: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete registry")+ return fmt.Errorf("failed to delete registry: %w", err)}output.Success("Registry deleted successfully")@@ -309,7 +309,7 @@ var usageCmd = &cobra.Command{result, err := c.GetJSON[containerregistry.PullUsageResponse](cmd.Context(), types.ContainerRegistriesPullUsage())if err != nil {- return errors.WrapIf(err, "failed to get registry pull usage")+ return fmt.Errorf("failed to get registry pull usage: %w", err)}if jsonOutput {diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.goindex 6ce3e91f5..f281b04dd 100644--- a/cli/pkg/repos/cmd.go+++ b/cli/pkg/repos/cmd.go@@ -7,7 +7,6 @@ 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"@@ -133,7 +132,7 @@ var createCmd = &cobra.Command{if cmd.Flags().Changed("ssh-key") {sshKeyData, err := os.ReadFile(repoCreateSSHKey)if err != nil {- return errors.WrapIf(err, "failed to read SSH key file")+ return fmt.Errorf("failed to read SSH key file: %w", err)}req.SSHKey = string(sshKeyData)}@@ -149,7 +148,7 @@ var createCmd = &cobra.Command{if cmd.Flags().Changed("signing-key") {signingKeyData, err := os.ReadFile(repoCreateSigningKey)if err != nil {- return errors.WrapIf(err, "failed to read signing key file")+ return fmt.Errorf("failed to read signing key file: %w", err)}req.SigningKey = string(signingKeyData)}@@ -165,7 +164,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[gitops.GitRepository](cmd.Context(), types.GitRepositories(), req)if err != nil {- return errors.WrapIf(err, "failed to create repository")+ return fmt.Errorf("failed to create repository: %w", err)}if jsonOutput {@@ -263,7 +262,7 @@ var updateCmd = &cobra.Command{if cmd.Flags().Changed("ssh-key") {sshKeyData, err := os.ReadFile(repoUpdateSSHKey)if err != nil {- return errors.WrapIf(err, "failed to read SSH key file")+ return fmt.Errorf("failed to read SSH key file: %w", err)}req.SSHKey = new(string(sshKeyData))}@@ -281,7 +280,7 @@ var updateCmd = &cobra.Command{if repoUpdateSigningKey != "" {signingKeyData, err := os.ReadFile(repoUpdateSigningKey)if err != nil {- return errors.WrapIf(err, "failed to read signing key file")+ return fmt.Errorf("failed to read signing key file: %w", err)}signingKey = string(signingKeyData)}@@ -299,7 +298,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[gitops.GitRepository](cmd.Context(), types.GitRepository(resolved.ID), req)if err != nil {- return errors.WrapIf(err, "failed to update repository")+ return fmt.Errorf("failed to update repository: %w", err)}if jsonOutput {@@ -346,11 +345,11 @@ var deleteCmd = &cobra.Command{resp, err := c.Delete(cmd.Context(), types.GitRepository(resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to delete repository")+ return fmt.Errorf("failed to delete repository: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete repository")+ return fmt.Errorf("failed to delete repository: %w", err)}output.Success("Repository deleted successfully")@@ -401,7 +400,7 @@ var branchesCmd = &cobra.Command{result, err := c.GetJSON[gitops.BranchesResponse](cmd.Context(), types.GitRepositoryBranches(resolved.ID))if err != nil {- return errors.WrapIf(err, "failed to list branches")+ return fmt.Errorf("failed to list branches: %w", err)}if jsonOutput {@@ -457,7 +456,7 @@ var filesCmd = &cobra.Command{result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to list files")+ return fmt.Errorf("failed to list files: %w", err)}files := result.Data.Filesdiff --git a/cli/pkg/root.go b/cli/pkg/root.goindex da9e33e9d..399225268 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -43,7 +43,6 @@ import ("charm.land/fang/v2""charm.land/lipgloss/v2"- "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/output"@@ -110,7 +109,7 @@ var rootCmd = &cobra.Command{outputMode = string(runtimectx.OutputModeText)}if outputMode != string(runtimectx.OutputModeText) && outputMode != string(runtimectx.OutputModeJSON) {- return errors.Errorf("invalid --output value %q (expected text or json)", outputMode)+ return fmt.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 23c7eacc1..4af35df7f 100644--- a/cli/pkg/selfupdate/cmd.go+++ b/cli/pkg/selfupdate/cmd.go@@ -7,6 +7,7 @@ import ("crypto/sha256""encoding/hex""encoding/json/v2"+ "errors""fmt""io""net/http"@@ -18,7 +19,6 @@ import ("strings""time"- "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -123,7 +123,7 @@ func newSelfUpdateChannelValueCmdInternal(channel string) *cobra.Command {func setCLIUpdateChannelAndRunInternal(cmd *cobra.Command, channel string) error {channel = strings.ToLower(strings.TrimSpace(channel))if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return errors.Errorf("invalid update channel %q (expected stable or next)", channel)+ return fmt.Errorf("invalid update channel %q (expected stable or next)", channel)}if err := saveCLIUpdateChannelInternal(channel); err != nil {return err@@ -189,7 +189,7 @@ func buildCLIUpdatePlanInternal(ctx context.Context, overrideChannel string) (*cchannel = inferCLIUpdateChannelInternal(config.Version)}if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return nil, errors.Errorf("invalid update channel %q (expected next or stable)", channel)+ return nil, fmt.Errorf("invalid update channel %q (expected next or stable)", channel)}verboseCLIUpdateInternal("channel=%s target=%s platform=%s/%s", channel, targetPath, runtime.GOOS, runtime.GOARCH)@@ -212,14 +212,14 @@ func buildCLIUpdatePlanInternal(ctx context.Context, overrideChannel string) (*cfunc configuredCLIUpdateChannelInternal() (string, error) {cfg, err := config.Load()if err != nil {- return "", errors.WrapIf(err, "failed to load config")+ return "", fmt.Errorf("failed to load config: %w", err)}channel := strings.ToLower(strings.TrimSpace(cfg.CLIUpdateChannel))if channel == "" {return "", nil}if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {- return "", errors.Errorf("invalid configured CLI update channel %q (expected stable or next)", cfg.CLIUpdateChannel)+ return "", fmt.Errorf("invalid configured CLI update channel %q (expected stable or next)", cfg.CLIUpdateChannel)}return channel, nil}@@ -227,11 +227,11 @@ func configuredCLIUpdateChannelInternal() (string, error) {func saveCLIUpdateChannelInternal(channel string) error {cfg, err := config.Load()if err != nil {- return errors.WrapIf(err, "failed to load config")+ return fmt.Errorf("failed to load config: %w", err)}cfg.CLIUpdateChannel = channelif err := config.Save(cfg); err != nil {- return errors.WrapIf(err, "failed to save config")+ return fmt.Errorf("failed to save config: %w", err)}return nil}@@ -243,13 +243,13 @@ func resolveCLIUpdateTargetInternal() (string, error) {if pathTarget, err := exec.LookPath("arcane-cli"); err == nil {absTarget, err := filepath.Abs(pathTarget)if err != nil {- return "", errors.WrapIf(err, "failed to resolve arcane-cli from PATH")+ return "", fmt.Errorf("failed to resolve arcane-cli from PATH: %w", err)}return filepath.EvalSymlinks(absTarget)}exe, err := os.Executable()if err != nil {- return "", errors.WrapIf(err, "failed to resolve current executable")+ return "", fmt.Errorf("failed to resolve current executable: %w", err)}return filepath.EvalSymlinks(exe)}@@ -382,16 +382,16 @@ func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return "", errors.WrapIf(err, "failed to fetch latest GitHub release")+ return "", fmt.Errorf("failed to fetch latest GitHub release: %w", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", errors.Errorf("failed to fetch latest GitHub release: HTTP %s", resp.Status)+ return "", fmt.Errorf("failed to fetch latest GitHub release: HTTP %s", resp.Status)}var latest githubLatestReleaseif err := json.UnmarshalRead(resp.Body, &latest); err != nil {- return "", errors.WrapIf(err, "failed to fetch latest GitHub release")+ return "", fmt.Errorf("failed to fetch latest GitHub release: %w", err)}return strings.TrimSpace(latest.TagName), nil}@@ -427,14 +427,14 @@ func cliArtifactArchInternal() (string, error) {case "arm":return "armv7", nildefault:- return "", errors.Errorf("unsupported CLI update architecture %s/%s", runtime.GOOS, runtime.GOARCH)+ return "", fmt.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 errors.WrapIf(err, "failed to create update temp dir")+ return fmt.Errorf("failed to create update temp dir: %w", err)}defer func() { _ = os.RemoveAll(tmpDir) }()@@ -445,7 +445,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 errors.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)+ return fmt.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)}binaryPath := downloadPath@@ -458,7 +458,7 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {}if err := os.Chmod(binaryPath, 0o755); err != nil {- return errors.WrapIf(err, "failed to make downloaded binary executable")+ return fmt.Errorf("failed to make downloaded binary executable: %w", err)}return replaceExecutableInternal(binaryPath, plan.TargetPath)}@@ -467,7 +467,7 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {targetDir := filepath.Dir(targetPath)tmpTarget, err := os.CreateTemp(targetDir, filepath.Base(targetPath)+".update-*")if err != nil {- return errors.WrapIff(err, "failed to create replacement file in %s", targetDir)+ return fmt.Errorf("failed to create replacement file in %s: %w", targetDir, err)}tmpTargetPath := tmpTarget.Name()cleanup := func() { _ = os.Remove(tmpTargetPath) }@@ -476,41 +476,41 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {if err != nil {_ = tmpTarget.Close()cleanup()- return errors.WrapIf(err, "failed to open downloaded binary")+ return fmt.Errorf("failed to open downloaded binary: %w", err)}defer func() { _ = source.Close() }()if _, err := io.Copy(tmpTarget, source); err != nil {_ = tmpTarget.Close()cleanup()- return errors.WrapIf(err, "failed to write replacement binary")+ return fmt.Errorf("failed to write replacement binary: %w", err)}if err := tmpTarget.Chmod(0o755); err != nil {_ = tmpTarget.Close()cleanup()- return errors.WrapIf(err, "failed to chmod replacement binary")+ return fmt.Errorf("failed to chmod replacement binary: %w", err)}if err := tmpTarget.Sync(); err != nil {_ = tmpTarget.Close()cleanup()- return errors.WrapIf(err, "failed to sync replacement binary")+ return fmt.Errorf("failed to sync replacement binary: %w", err)}if err := tmpTarget.Close(); err != nil {cleanup()- return errors.WrapIf(err, "failed to close replacement binary")+ return fmt.Errorf("failed to close replacement binary: %w", err)}if err := os.Rename(tmpTargetPath, targetPath); err != nil {cleanup()- return errors.WrapIff(err, "failed to replace %s", targetPath)+ return fmt.Errorf("failed to replace %s: %w", targetPath, err)}dirFile, err := os.Open(targetDir)if err != nil {- return errors.WrapIf(err, "failed to open target directory for sync")+ return fmt.Errorf("failed to open target directory for sync: %w", err)}defer func() { _ = dirFile.Close() }()if err := dirFile.Sync(); err != nil {- return errors.WrapIf(err, "failed to sync target directory")+ return fmt.Errorf("failed to sync target directory: %w", err)}return nil}@@ -518,13 +518,13 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {func extractCLIFromTarGzInternal(archivePath, outputPath string) error {file, err := os.Open(archivePath)if err != nil {- return errors.WrapIf(err, "failed to open archive")+ return fmt.Errorf("failed to open archive: %w", err)}defer func() { _ = file.Close() }()gzipReader, err := gzip.NewReader(file)if err != nil {- return errors.WrapIf(err, "failed to read gzip archive")+ return fmt.Errorf("failed to read gzip archive: %w", err)}defer func() { _ = gzipReader.Close() }()@@ -535,7 +535,7 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {break}if err != nil {- return errors.WrapIf(err, "failed to read tar archive")+ return fmt.Errorf("failed to read tar archive: %w", err)}if header.Typeflag != tar.TypeReg {continue@@ -544,19 +544,19 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {continue}if header.Size < 0 || header.Size > maxCLIExtractSize {- return errors.Errorf("arcane-cli archive entry has invalid size %d", header.Size)+ return fmt.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 errors.WrapIf(err, "failed to create extracted binary")+ return fmt.Errorf("failed to create extracted binary: %w", err)}if _, err := io.CopyN(out, tarReader, header.Size); err != nil {_ = out.Close()- return errors.WrapIf(err, "failed to extract CLI binary")+ return fmt.Errorf("failed to extract CLI binary: %w", err)}if err := out.Close(); err != nil {- return errors.WrapIf(err, "failed to close extracted binary")+ return fmt.Errorf("failed to close extracted binary: %w", err)}return nil}@@ -573,19 +573,19 @@ func fetchTextInternal(ctx context.Context, url string) (string, error) {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return "", errors.WrapIff(err, "failed to fetch %s", url)+ return "", fmt.Errorf("failed to fetch %s: %w", url, err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return "", errors.Errorf("failed to fetch %s: HTTP %s", url, resp.Status)+ return "", fmt.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 "", errors.WrapIff(err, "failed to read %s", url)+ return "", fmt.Errorf("failed to read %s: %w", url, err)}if len(body) > maxCLIChecksumSize {- return "", errors.Errorf("failed to read %s: checksum response exceeds maximum size of %d bytes", url, maxCLIChecksumSize)+ return "", fmt.Errorf("failed to read %s: checksum response exceeds maximum size of %d bytes", url, maxCLIChecksumSize)}return string(body), nil}@@ -599,29 +599,29 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {client := &http.Client{Timeout: cliUpdateHTTPTimeout}resp, err := client.Do(req)if err != nil {- return errors.WrapIff(err, "failed to download %s", url)+ return fmt.Errorf("failed to download %s: %w", url, err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return errors.Errorf("failed to download %s: HTTP %s", url, resp.Status)+ return fmt.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 errors.WrapIf(err, "failed to create download file")+ return fmt.Errorf("failed to create download file: %w", err)}limitedBody := &io.LimitedReader{R: resp.Body, N: maxCLIDownloadSize + 1}written, err := io.Copy(out, limitedBody)if err != nil {_ = out.Close()- return errors.WrapIf(err, "failed to write download file")+ return fmt.Errorf("failed to write download file: %w", err)}if written > maxCLIDownloadSize {_ = out.Close()- return errors.Errorf("downloaded artifact exceeds maximum size of %d bytes", maxCLIDownloadSize)+ return fmt.Errorf("downloaded artifact exceeds maximum size of %d bytes", maxCLIDownloadSize)}if err := out.Close(); err != nil {- return errors.WrapIf(err, "failed to close download file")+ return fmt.Errorf("failed to close download file: %w", err)}return nil}@@ -637,13 +637,13 @@ func verboseCLIUpdateInternal(format string, args ...any) {func sha256FileInternal(path string) (string, error) {file, err := os.Open(path)if err != nil {- return "", errors.WrapIff(err, "failed to open %s for SHA-256", path)+ return "", fmt.Errorf("failed to open %s for SHA-256: %w", path, err)}defer func() { _ = file.Close() }()hash := sha256.New()if _, err := io.Copy(hash, file); err != nil {- return "", errors.WrapIff(err, "failed to hash %s", path)+ return "", fmt.Errorf("failed to hash %s: %w", path, err)}return hex.EncodeToString(hash.Sum(nil)), nil}@@ -667,7 +667,7 @@ func findChecksumInternal(checksums string, artifactNames ...string) (string, erreturn strings.ToLower(fields[0]), nil}}- return "", errors.Errorf("checksum for %s not found", strings.Join(artifactNames, " or "))+ return "", fmt.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 d12cc51a0..0294b7467 100644--- a/cli/pkg/settings/cmd.go+++ b/cli/pkg/settings/cmd.go@@ -6,7 +6,6 @@ import ("net/http""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"@@ -52,17 +51,17 @@ var updateCmd = &cobra.Command{data, err := os.ReadFile(settingsUpdateFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", settingsUpdateFile)+ return fmt.Errorf("failed to read file %s: %w", settingsUpdateFile, err)}var req settings.Updateif err := json.Unmarshal(data, &req); err != nil {- return errors.WrapIf(err, "failed to parse settings file")+ return fmt.Errorf("failed to parse settings file: %w", err)}result, err := c.PutJSON[[]settings.SettingDto](cmd.Context(), types.Settings(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to update settings")+ return fmt.Errorf("failed to update settings: %w", err)}if jsonOutput {@@ -101,7 +100,7 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {result, err := c.DoJSON[[]settings.PublicSetting](cmd.Context(), http.MethodGet, cfg.endpoint(c.EnvID()), nil)if err != nil {- return errors.WrapIff(err, "%s", cfg.failureMessage)+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)}if jsonOutput {diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.goindex f80452734..8a50e668f 100644--- a/cli/pkg/system/cmd.go+++ b/cli/pkg/system/cmd.go@@ -2,12 +2,12 @@ package systemimport ("cmp"+ "errors""fmt""net/http""strconv""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"@@ -45,7 +45,7 @@ var pruneCmd = &cobra.Command{result, err := c.PostJSON[system.PruneAllResult](cmd.Context(), types.SystemPrune(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to prune")+ return fmt.Errorf("failed to prune: %w", err)}if jsonOutput {@@ -73,7 +73,7 @@ var dockerInfoCmd = &cobra.Command{// ApiResponse envelope.result, err := c.DoJSON[dockerinfo.Info](cmd.Context(), http.MethodGet, types.SystemDockerInfo(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to get docker info")+ return fmt.Errorf("failed to get docker info: %w", err)}if jsonOutput {@@ -163,7 +163,7 @@ var convertCmd = &cobra.Command{req := map[string]string{"dockerRunCommand": args[0]}result, err := c.DoJSON[convertResult](cmd.Context(), http.MethodPost, types.SystemConvert(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to convert command")+ return fmt.Errorf("failed to convert command: %w", err)}if jsonOutput {@@ -254,7 +254,7 @@ func runUpgradeCheckInternal(cmd *cobra.Command) error {}result, err := c.DoJSON[upgradeCheckResult](cmd.Context(), http.MethodGet, types.SystemUpgradeCheck(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to check for upgrades")+ return fmt.Errorf("failed to check for upgrades: %w", err)}if jsonOutput {@@ -337,7 +337,7 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {if upgradeAllStatusFlag {result, err := c.GetJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get update-all status")+ return fmt.Errorf("failed to get update-all status: %w", err)}if jsonOutput {@@ -362,7 +362,7 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {result, err := c.PostJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAll(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to trigger update-all")+ return fmt.Errorf("failed to trigger update-all: %w", err)}if jsonOutput {diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.goindex ae5f43bff..38b67cad1 100644--- a/cli/pkg/templates/cmd.go+++ b/cli/pkg/templates/cmd.go@@ -2,6 +2,7 @@ package templatesimport ("context"+ "errors""fmt""net/url""os"@@ -12,7 +13,6 @@ 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"@@ -93,7 +93,7 @@ var listCmd = &cobra.Command{result, err := c.GetJSON[[]template.Template](cmd.Context(), types.TemplatesAll())if err != nil {- return errors.WrapIf(err, "failed to list templates")+ return fmt.Errorf("failed to list templates: %w", err)}if jsonOutput {@@ -132,7 +132,7 @@ var defaultCmd = &cobra.Command{result, err := c.GetJSON[template.DefaultTemplatesResponse](cmd.Context(), types.TemplatesDefault())if err != nil {- return errors.WrapIf(err, "failed to get default templates")+ return fmt.Errorf("failed to get default templates: %w", err)}if jsonOutput {@@ -159,7 +159,7 @@ var contentCmd = &cobra.Command{result, err := c.GetJSON[template.TemplateContent](cmd.Context(), types.TemplateContent(args[0]))if err != nil {- return errors.WrapIf(err, "failed to get template content")+ return fmt.Errorf("failed to get template content: %w", err)}if jsonOutput {@@ -194,7 +194,7 @@ var registriesCmd = &cobra.Command{result, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())if err != nil {- return errors.WrapIf(err, "failed to list registries")+ return fmt.Errorf("failed to list registries: %w", err)}if jsonOutput {@@ -241,7 +241,7 @@ func runTemplateDeleteInternal(cmd *cobra.Command, label, path string) error {result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)if err != nil {- return errors.WrapIff(err, "failed to delete %s", label)+ return fmt.Errorf("failed to delete %s: %w", label, err)}if jsonOutput {return cmdutil.PrintJSON(result.Data)@@ -327,7 +327,7 @@ var templateRef = cmdutil.ResourceRef[template.Template, template.Template]{func searchTemplateCandidatesInternal(ctx context.Context, c *client.Client, identifier string) ([]template.Template, error) {result, err := c.GetJSON[[]template.Template](ctx, types.TemplatesAll())if err != nil {- return nil, errors.WrapIf(err, "failed to search templates")+ return nil, fmt.Errorf("failed to search templates: %w", err)}identifierLower := strings.ToLower(identifier)@@ -376,7 +376,7 @@ func selectTemplateCandidateInternal(matches []template.Template, identifier strreturn &matches[0], nil}if !allowPrompt || len(matches) > cmdutil.MaxPromptOptions {- return nil, errors.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidatesInternal(matches))+ return nil, fmt.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidatesInternal(matches))}ordered := slices.Clone(matches)@@ -589,7 +589,7 @@ var createCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {content, err := os.ReadFile(templateCreateFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", templateCreateFile)+ return fmt.Errorf("failed to read file %s: %w", templateCreateFile, err)}req := template.CreateRequest{@@ -601,7 +601,7 @@ var createCmd = &cobra.Command{if templateCreateEnvFile != "" {envContent, err := os.ReadFile(templateCreateEnvFile)if err != nil {- return errors.WrapIff(err, "failed to read env file %s", templateCreateEnvFile)+ return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, err)}req.EnvContent = string(envContent)}@@ -613,7 +613,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[template.Template](cmd.Context(), types.Templates(), req)if err != nil {- return errors.WrapIf(err, "failed to create template")+ return fmt.Errorf("failed to create template: %w", err)}if jsonOutput {@@ -664,7 +664,7 @@ var updateCmd = &cobra.Command{if templateUpdateFile != "" {content, err := os.ReadFile(templateUpdateFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", templateUpdateFile)+ return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, err)}req.Content = string(content)}@@ -672,14 +672,14 @@ var updateCmd = &cobra.Command{if templateUpdateEnvFile != "" {envContent, err := os.ReadFile(templateUpdateEnvFile)if err != nil {- return errors.WrapIff(err, "failed to read env file %s", templateUpdateEnvFile)+ return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, err)}req.EnvContent = string(envContent)}result, err := c.PutJSON[template.Template](cmd.Context(), types.Template(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update template")+ return fmt.Errorf("failed to update template: %w", err)}if jsonOutput {@@ -706,16 +706,16 @@ var downloadCmd = &cobra.Command{result, err := c.PostJSON[template.Template](cmd.Context(), types.TemplateDownload(args[0]), nil)if err != nil {- return errors.WrapIf(err, "failed to download template")+ return fmt.Errorf("failed to download template: %w", err)}if templateDownloadOutput != "" {dir := filepath.Dir(templateDownloadOutput)if err := os.MkdirAll(dir, 0o755); err != nil {- return errors.WrapIff(err, "failed to create directory %s", dir)+ return fmt.Errorf("failed to create directory %s: %w", dir, err)}if err := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); err != nil {- return errors.WrapIff(err, "failed to write file %s", templateDownloadOutput)+ return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, err)}output.Success("Template downloaded to %s", templateDownloadOutput)return nil@@ -733,7 +733,7 @@ var defaultsSaveCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {content, err := os.ReadFile(templateDefaultsSaveFile)if err != nil {- return errors.WrapIff(err, "failed to read file %s", templateDefaultsSaveFile)+ return fmt.Errorf("failed to read file %s: %w", templateDefaultsSaveFile, err)}req := template.SaveDefaultTemplatesRequest{@@ -743,7 +743,7 @@ var defaultsSaveCmd = &cobra.Command{if templateDefaultsEnvFile != "" {envContent, err := os.ReadFile(templateDefaultsEnvFile)if err != nil {- return errors.WrapIff(err, "failed to read env file %s", templateDefaultsEnvFile)+ return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, err)}req.EnvContent = string(envContent)}@@ -811,7 +811,7 @@ var registriesUpdateCmd = &cobra.Command{// The handler answers with a plain message, not the updated registry.result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.TemplateRegistry(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update registry")+ return fmt.Errorf("failed to update registry: %w", err)}if jsonOutput {@@ -829,7 +829,7 @@ var registriesUpdateCmd = &cobra.Command{func fetchTemplateInternal(cmd *cobra.Command, c *client.Client, id string) (template.Template, error) {result, err := c.GetJSON[template.Template](cmd.Context(), types.Template(id))if err != nil {- return template.Template{}, errors.WrapIf(err, "failed to load template")+ return template.Template{}, fmt.Errorf("failed to load template: %w", err)}return result.Data, nil}@@ -839,7 +839,7 @@ func fetchTemplateInternal(cmd *cobra.Command, c *client.Client, id string) (temfunc fetchTemplateRegistryInternal(cmd *cobra.Command, c *client.Client, id string) (template.TemplateRegistry, error) {listed, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())if err != nil {- return template.TemplateRegistry{}, errors.WrapIf(err, "failed to load registry")+ return template.TemplateRegistry{}, fmt.Errorf("failed to load registry: %w", err)}for _, registry := range listed.Data {@@ -847,7 +847,7 @@ func fetchTemplateRegistryInternal(cmd *cobra.Command, c *client.Client, id strireturn registry, nil}}- return template.TemplateRegistry{}, errors.Errorf("template registry %q not found", id)+ return template.TemplateRegistry{}, fmt.Errorf("template registry %q not found", id)}var fetchCmd = &cobra.Command{@@ -863,7 +863,7 @@ var fetchCmd = &cobra.Command{path := cmdutil.AppendQuery(types.TemplateFetch(), url.Values{"url": []string{templateFetchURL}})result, err := c.GetJSON[template.RemoteRegistry](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to fetch templates")+ return fmt.Errorf("failed to fetch templates: %w", err)}if jsonOutput {diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.goindex 38eaf7d6e..88ca73d38 100644--- a/cli/pkg/updater/cmd.go+++ b/cli/pkg/updater/cmd.go@@ -6,7 +6,6 @@ import ("strconv""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"@@ -39,7 +38,7 @@ var statusCmd = &cobra.Command{result, err := c.GetJSON[updater.Status](cmd.Context(), types.UpdaterStatus(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get updater status")+ return fmt.Errorf("failed to get updater status: %w", err)}if jsonOutput {@@ -68,7 +67,7 @@ var runCmd = &cobra.Command{result, err := c.PostJSON[updater.Result](cmd.Context(), types.UpdaterRun(c.EnvID()), nil)if err != nil {- return errors.WrapIf(err, "failed to run updater")+ return fmt.Errorf("failed to run updater: %w", err)}if jsonOutput {@@ -119,7 +118,7 @@ var historyCmd = &cobra.Command{result, err := c.GetJSON[[]autoUpdateRecord](cmd.Context(), path)if err != nil {- return errors.WrapIf(err, "failed to get updater history")+ return fmt.Errorf("failed to get updater history: %w", err)}if jsonOutput {diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.goindex e5b96e6f8..e286742e4 100644--- a/cli/pkg/variables/cmd.go+++ b/cli/pkg/variables/cmd.go@@ -2,12 +2,12 @@ package variablesimport ("cmp"+ "errors""fmt""strconv""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"@@ -99,7 +99,7 @@ var listCmd = &cobra.Command{result, err := c.GetJSON[[]env.GlobalVariable](cmd.Context(), types.Variables())if err != nil {- return errors.WrapIf(err, "failed to list variables")+ return fmt.Errorf("failed to list variables: %w", err)}if jsonOutput {@@ -148,7 +148,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variables(), req)if err != nil {- return errors.WrapIf(err, "failed to create variable")+ return fmt.Errorf("failed to create variable: %w", err)}return printMutationResult(result.Data, fmt.Sprintf("Variable %s created successfully", createKey))@@ -189,7 +189,7 @@ var updateCmd = &cobra.Command{result, err := c.PutJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to update variable")+ return fmt.Errorf("failed to update variable: %w", err)}return printMutationResult(result.Data, "Variable updated successfully")@@ -221,7 +221,7 @@ var deleteCmd = &cobra.Command{result, err := c.DeleteJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]))if err != nil {- return errors.WrapIf(err, "failed to delete variable")+ return fmt.Errorf("failed to delete variable: %w", err)}return printMutationResult(result.Data, "Variable deleted successfully")@@ -247,7 +247,7 @@ var syncCmd = &cobra.Command{result, err = c.PostJSON[[]env.EnvironmentSyncStatus](cmd.Context(), types.VariablesSync(), nil)}if err != nil {- return errors.WrapIff(err, "%s", failureMessage)+ return fmt.Errorf("%s: %w", failureMessage, err)}if jsonOutput {diff --git a/cli/pkg/version/cmd.go b/cli/pkg/version/cmd.goindex c558cb4bc..7c39074cb 100644--- a/cli/pkg/version/cmd.go+++ b/cli/pkg/version/cmd.go@@ -1,9 +1,9 @@package versionimport (+ "fmt""net/http"- "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"@@ -32,7 +32,7 @@ var VersionCmd = &cobra.Command{logger.GetLogger().Debug("Sending request", "endpoint", clitypes.AppVersionEndpoint)result, err := c.DoJSON[version.Info](cmd.Context(), http.MethodGet, clitypes.AppVersionEndpoint, nil)if err != nil {- return errors.WrapIf(err, "failed to get version")+ return fmt.Errorf("failed to get version: %w", err)}logger.GetLogger().Debug("Parsed version data", "result", result)diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.goindex 90692cfa2..563d3fc72 100644--- a/cli/pkg/volumes/backup.go+++ b/cli/pkg/volumes/backup.go@@ -3,6 +3,7 @@ package volumesimport ("cmp""encoding/json/v2"+ "errors""fmt""io""mime"@@ -11,7 +12,6 @@ import ("strconv""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"@@ -81,7 +81,7 @@ var renameCmd = &cobra.Command{result, err := c.PostJSON[volume.Volume](cmd.Context(), types.VolumeRename(c.EnvID(), resolved.Name), volume.Rename{Name: args[1]})if err != nil {- return errors.WrapIf(err, "failed to rename volume")+ return fmt.Errorf("failed to rename volume: %w", err)}if jsonOutput {@@ -112,7 +112,7 @@ var backupsPolicyCmd = &cobra.Command{result, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name))if err != nil {- return errors.WrapIf(err, "failed to get backup policies")+ return fmt.Errorf("failed to get backup policies: %w", err)}if jsonOutput {@@ -145,10 +145,10 @@ var backupsPolicyUpdateCmd = &cobra.Command{if policyFile != "" {raw, err := os.ReadFile(policyFile)if err != nil {- return errors.WrapIf(err, "failed to read policy file")+ return fmt.Errorf("failed to read policy file: %w", err)}if err := json.Unmarshal(raw, &payload); err != nil {- return errors.WrapIf(err, "failed to parse policy file")+ return fmt.Errorf("failed to parse policy file: %w", err)}} else {payload, err = buildPolicyUpdate(cmd, c, resolved.Name)@@ -159,7 +159,7 @@ var backupsPolicyUpdateCmd = &cobra.Command{result, err := c.PutJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name), payload)if err != nil {- return errors.WrapIf(err, "failed to update backup policies")+ return fmt.Errorf("failed to update backup policies: %w", err)}if jsonOutput {@@ -180,7 +180,7 @@ func buildPolicyUpdate(cmd *cobra.Command, c *client.Client, volumeName string)current, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), volumeName))if err != nil {- return payload, errors.WrapIf(err, "failed to get current backup policies")+ return payload, fmt.Errorf("failed to get current backup policies: %w", err)}payload.Policies = make([]volume.UpdateBackupPolicy, len(current.Data.Policies))@@ -203,9 +203,9 @@ func buildPolicyUpdate(cmd *cobra.Command, c *client.Client, volumeName string)switch {case policyID != "" && targetIndex == -1:- return payload, errors.Errorf("policy %q not found for volume %q", policyID, volumeName)+ return payload, fmt.Errorf("policy %q not found for volume %q", policyID, volumeName)case policyID == "" && len(payload.Policies) > 1:- return payload, errors.Errorf("volume %q has %d backup policies; select one with --policy-id", volumeName, len(payload.Policies))+ return payload, fmt.Errorf("volume %q has %d backup policies; select one with --policy-id", volumeName, len(payload.Policies))case policyID == "" && len(payload.Policies) == 1:targetIndex = 0case targetIndex == -1:@@ -309,12 +309,12 @@ func runListBackups(cmd *cobra.Command, args []string) error {All: allFlag,})if err != nil {- return errors.WrapIf(err, "failed to build pagination query")+ return fmt.Errorf("failed to build pagination query: %w", err)}result, err := c.DoJSON[backupsListResponse](cmd.Context(), http.MethodGet, path, nil)if err != nil {- return errors.WrapIf(err, "failed to list backups")+ return fmt.Errorf("failed to list backups: %w", err)}if jsonOutput {@@ -368,7 +368,7 @@ var backupsCreateCmd = &cobra.Command{result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackups(c.EnvID(), resolved.Name), req)if err != nil {- return errors.WrapIf(err, "failed to create backup")+ return fmt.Errorf("failed to create backup: %w", err)}if jsonOutput {@@ -440,7 +440,7 @@ and restored instead (no backup ID).`,result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID), nil)if err != nil {- return errors.WrapIf(err, "failed to restore backup")+ return fmt.Errorf("failed to restore backup: %w", err)}if jsonOutput {@@ -470,7 +470,7 @@ func runRestorePaths(cmd *cobra.Command, c *client.Client, volumeName, backupIDresult, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestoreFiles(c.EnvID(), volumeName, backupID), body)if err != nil {- return errors.WrapIf(err, "failed to restore backup files")+ return fmt.Errorf("failed to restore backup files: %w", err)}if jsonOutput {@@ -504,7 +504,7 @@ func runUploadRestore(cmd *cobra.Command, c *client.Client, volumeName string) erespBody, err := c.DoRaw(cmd.Context(), http.MethodPost, types.VolumeBackupUploadRestore(c.EnvID(), volumeName), uploadtypes.ConsumeRequest{UploadID: sessionID})if err != nil {cmdutil.AbortUploadSession(cmd.Context(), c, uploadtypes.KindVolumeBackup, sessionID)- return errors.WrapIf(err, "failed to upload and restore backup")+ return fmt.Errorf("failed to upload and restore backup: %w", err)}if jsonOutput {@@ -540,7 +540,7 @@ var backupsDeleteCmd = &cobra.Command{}if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.VolumeBackup(c.EnvID(), args[0])); err != nil {- return errors.WrapIf(err, "failed to delete backup")+ return fmt.Errorf("failed to delete backup: %w", err)}output.Success("Backup %s deleted successfully", args[0])@@ -565,7 +565,7 @@ var backupsUploadCmd = &cobra.Command{req := volume.UploadBackupRequest{S3DestinationID: backupUploadS3Destination}result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackupUpload(c.EnvID(), args[0]), req)if err != nil {- return errors.WrapIf(err, "failed to upload backup")+ return fmt.Errorf("failed to upload backup: %w", err)}if jsonOutput {@@ -593,11 +593,11 @@ var backupsDownloadCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.VolumeBackupDownload(c.EnvID(), args[0]))if err != nil {- return errors.WrapIf(err, "failed to download backup")+ return fmt.Errorf("failed to download backup: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to download backup")+ return fmt.Errorf("failed to download backup: %w", err)}outputFile := ""@@ -631,14 +631,14 @@ func downloadFilename(resp *http.Response, fallback string) string {func writeResponseToFile(body io.Reader, path string) error {file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)if err != nil {- return errors.WrapIff(err, "failed to create file %s", path)+ return fmt.Errorf("failed to create file %s: %w", path, err)}if _, err := io.Copy(file, body); err != nil {_ = file.Close()- return errors.WrapIff(err, "failed to write file %s", path)+ return fmt.Errorf("failed to write file %s: %w", path, err)}if err := file.Close(); err != nil {- return errors.WrapIff(err, "failed to write file %s", path)+ return fmt.Errorf("failed to write file %s: %w", path, err)}return nil}@@ -656,7 +656,7 @@ var backupsFilesCmd = &cobra.Command{result, err := c.GetJSON[[]string](cmd.Context(), types.VolumeBackupFiles(c.EnvID(), args[0]))if err != nil {- return errors.WrapIf(err, "failed to list backup files")+ return fmt.Errorf("failed to list backup files: %w", err)}if jsonOutput {diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.goindex 104a096b6..937ee0bd6 100644--- a/cli/pkg/volumes/cmd.go+++ b/cli/pkg/volumes/cmd.go@@ -1,12 +1,12 @@package volumesimport (+ "errors""fmt""net/url""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"@@ -168,11 +168,11 @@ var deleteCmd = &cobra.Command{)resp, err := c.Delete(cmd.Context(), deletePath)if err != nil {- return errors.WrapIf(err, "failed to delete volume")+ return fmt.Errorf("failed to delete volume: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to delete volume")+ return fmt.Errorf("failed to delete volume: %w", err)}output.Success("Volume %s deleted successfully", resolved.Name)@@ -253,13 +253,16 @@ func runVolumeDataCommand(cmd *cobra.Command, cfg volumeDataCommandConfig) errorresult, err := c.GetJSON[any](cmd.Context(), cfg.endpoint(c.EnvID()))if err != nil {- return errors.WrapIff(err, "%s", cfg.failureMessage)+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)}if !jsonOutput {output.Header("%s", cfg.header)}- return errors.WrapIff(cmdutil.PrintJSON(result.Data), "%s", cfg.marshalMessage)+ if err := cmdutil.PrintJSON(result.Data); err != nil {+ return fmt.Errorf("%s: %w", cfg.marshalMessage, err)+ }+ return nil}var usageCmd = &cobra.Command{@@ -281,7 +284,7 @@ var usageCmd = &cobra.Command{result, err := c.GetJSON[any](cmd.Context(), types.VolumeUsage(c.EnvID(), resolved.Name))if err != nil {- return errors.WrapIf(err, "failed to get volume usage")+ return fmt.Errorf("failed to get volume usage: %w", err)}if jsonOutput {@@ -330,7 +333,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[volume.Volume](cmd.Context(), types.Volumes(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to create volume")+ return fmt.Errorf("failed to create volume: %w", err)}if jsonOutput {diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.goindex d02585ce1..be005731d 100644--- a/cli/pkg/volumes/workspace.go+++ b/cli/pkg/volumes/workspace.go@@ -3,6 +3,7 @@ package volumesimport ("bytes""encoding/json/v2"+ "errors""fmt""mime/multipart""net/http"@@ -13,7 +14,6 @@ import ("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/prompt"@@ -43,11 +43,11 @@ var workspaceCmd = &cobra.Command{resp, err := c.Get(cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))if err != nil {- return errors.WrapIf(err, "failed to get volume workspace")+ return fmt.Errorf("failed to get volume workspace: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to get volume workspace")+ return fmt.Errorf("failed to get volume workspace: %w", err)}var result base.ApiResponse[workspacetypes.Workspace]@@ -125,11 +125,11 @@ var workspaceCatCmd = &cobra.Command{)resp, err := c.Get(cmd.Context(), filePath)if err != nil {- return errors.WrapIf(err, "failed to get workspace file")+ return fmt.Errorf("failed to get workspace file: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to get workspace file")+ return fmt.Errorf("failed to get workspace file: %w", err)}var result base.ApiResponse[workspacetypes.FileContent]@@ -142,7 +142,7 @@ var workspaceCatCmd = &cobra.Command{}if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {- return errors.Errorf("file %s has no printable content (%s); use `arcane volumes workspace download` instead", args[1], result.Data.ReadOnlyReason)+ return fmt.Errorf("file %s has no printable content (%s); use `arcane volumes workspace download` instead", args[1], result.Data.ReadOnlyReason)}fmt.Print(result.Data.Content)@@ -176,11 +176,11 @@ var workspaceDownloadCmd = &cobra.Command{)resp, err := c.Get(cmd.Context(), downloadPath)if err != nil {- return errors.WrapIf(err, "failed to download workspace file")+ return fmt.Errorf("failed to download workspace file: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to download workspace file")+ return fmt.Errorf("failed to download workspace file: %w", err)}outputFile := ""@@ -219,7 +219,7 @@ var workspacePutCmd = &cobra.Command{content, err := os.ReadFile(args[1])if err != nil {- return errors.WrapIf(err, "failed to read local file")+ return fmt.Errorf("failed to read local file: %w", err)}relativePath := strings.Trim(filepath.ToSlash(args[2]), "/")@@ -240,11 +240,11 @@ var workspacePutCmd = &cobra.Command{workspaceResp, err := c.Get(cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))if err != nil {- return errors.WrapIf(err, "failed to get volume workspace")+ return fmt.Errorf("failed to get volume workspace: %w", err)}defer func() { _ = workspaceResp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(workspaceResp); err != nil {- return errors.WrapIf(err, "failed to get volume workspace")+ return fmt.Errorf("failed to get volume workspace: %w", err)}var current base.ApiResponse[workspacetypes.Workspace]if err := cmdutil.DecodeJSON(workspaceResp, ¤t); err != nil {@@ -270,32 +270,32 @@ var workspacePutCmd = &cobra.Command{}manifestJSON, err := json.Marshal(manifest)if err != nil {- return errors.WrapIf(err, "failed to encode workspace manifest")+ return fmt.Errorf("failed to encode workspace manifest: %w", err)}var requestBody bytes.Bufferwriter := multipart.NewWriter(&requestBody)if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {- return errors.WrapIf(err, "failed to write workspace manifest")+ return fmt.Errorf("failed to write workspace manifest: %w", err)}filePart, err := writer.CreateFormFile("files", path.Base(relativePath))if err != nil {- return errors.WrapIf(err, "failed to create workspace upload")+ return fmt.Errorf("failed to create workspace upload: %w", err)}if _, err := filePart.Write(content); err != nil {- return errors.WrapIf(err, "failed to write workspace upload")+ return fmt.Errorf("failed to write workspace upload: %w", err)}if err := writer.Close(); err != nil {- return errors.WrapIf(err, "failed to finalize workspace upload")+ return fmt.Errorf("failed to finalize workspace upload: %w", err)}resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.VolumeWorkspace(c.EnvID(), resolved.Name), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})if err != nil {- return errors.WrapIf(err, "failed to update volume workspace")+ return fmt.Errorf("failed to update volume workspace: %w", err)}defer func() { _ = resp.Body.Close() }()if err := cmdutil.EnsureSuccessStatus(resp); err != nil {- return errors.WrapIf(err, "failed to update volume workspace")+ return fmt.Errorf("failed to update volume workspace: %w", err)}if jsonOutput {diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.goindex c6a25ae45..d512688dc 100644--- a/cli/pkg/vulnerabilities/cmd.go+++ b/cli/pkg/vulnerabilities/cmd.go@@ -15,7 +15,6 @@ 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"@@ -63,7 +62,7 @@ var statusCmd = &cobra.Command{Version string `json:"version,omitempty"`}](cmd.Context(), types.VulnerabilitiesScannerStatus(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get scanner status")+ return fmt.Errorf("failed to get scanner status: %w", err)}if jsonOutput {@@ -91,7 +90,7 @@ var summaryCmd = &cobra.Command{result, err := c.GetJSON[vulnerability.EnvironmentVulnerabilitySummary](cmd.Context(), types.VulnerabilitiesSummary(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to get vulnerability summary")+ return fmt.Errorf("failed to get vulnerability summary: %w", err)}if jsonOutput {@@ -167,7 +166,7 @@ var scanCmd = &cobra.Command{result, err := c.PostJSON[vulnerability.ScanResult](cmd.Context(), types.ImageVulnerabilitiesScan(c.EnvID(), imageID), nil)if err != nil {- return errors.WrapIf(err, "failed to scan image")+ return fmt.Errorf("failed to scan image: %w", err)}if jsonOutput {@@ -239,7 +238,7 @@ var imageCmd = &cobra.Command{func runImageSummary(cmd *cobra.Command, c *client.Client, imageID string) error {result, err := c.GetJSON[vulnerability.ScanSummary](cmd.Context(), types.ImageVulnerabilitiesSummary(c.EnvID(), imageID))if err != nil {- return errors.WrapIf(err, "failed to get image vulnerability summary")+ return fmt.Errorf("failed to get image vulnerability summary: %w", err)}if jsonOutput {@@ -288,7 +287,7 @@ var ignoreCmd = &cobra.Command{result, err := c.PostJSON[vulnerability.IgnoredVulnerability](cmd.Context(), types.VulnerabilitiesIgnore(c.EnvID()), payload)if err != nil {- return errors.WrapIf(err, "failed to ignore vulnerability")+ return fmt.Errorf("failed to ignore vulnerability: %w", err)}if jsonOutput {@@ -358,7 +357,7 @@ var unignoreCmd = &cobra.Command{}if _, err := c.DeleteJSON[struct{}](cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0])); err != nil {- return errors.WrapIf(err, "failed to remove ignore record")+ return fmt.Errorf("failed to remove ignore record: %w", err)}output.Success("Ignore record %s removed", args[0])diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.goindex 45ecf5bdd..488edd399 100644--- a/cli/pkg/webhooks/cmd.go+++ b/cli/pkg/webhooks/cmd.go@@ -4,11 +4,11 @@ package webhooksimport ("cmp"+ "errors""fmt""net/http""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"@@ -47,7 +47,7 @@ var listCmd = &cobra.Command{result, err := c.GetJSON[[]webhook.Summary](cmd.Context(), types.Webhooks(c.EnvID()))if err != nil {- return errors.WrapIf(err, "failed to list webhooks")+ return fmt.Errorf("failed to list webhooks: %w", err)}if jsonOutput {@@ -101,7 +101,7 @@ var createCmd = &cobra.Command{result, err := c.PostJSON[webhook.Created](cmd.Context(), types.Webhooks(c.EnvID()), req)if err != nil {- return errors.WrapIf(err, "failed to create webhook")+ return fmt.Errorf("failed to create webhook: %w", err)}if jsonOutput {@@ -140,7 +140,7 @@ var updateCmd = &cobra.Command{req := webhook.UpdateInput{Enabled: updateEnabled}if _, err := c.DoJSON[base.ApiResponse[any]](cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req); err != nil {- return errors.WrapIf(err, "failed to update webhook")+ return fmt.Errorf("failed to update webhook: %w", err)}if jsonOutput {@@ -180,7 +180,7 @@ var deleteCmd = &cobra.Command{}if _, err := c.DeleteJSON[any](cmd.Context(), types.Webhook(c.EnvID(), args[0])); err != nil {- return errors.WrapIf(err, "failed to delete webhook")+ return fmt.Errorf("failed to delete webhook: %w", err)}output.Success("Webhook %s deleted successfully", args[0])@@ -202,7 +202,7 @@ var triggerCmd = &cobra.Command{body, err := c.DoRaw(cmd.Context(), http.MethodPost, types.WebhookTrigger(args[0]), nil)if err != nil {- return errors.WrapIf(err, "failed to trigger webhook")+ return fmt.Errorf("failed to trigger webhook: %w", err)}if jsonOutput {diff --git a/types/base/errors.go b/types/base/errors.gonew file mode 100644index 000000000..31d3ea35d--- /dev/null+++ b/types/base/errors.go@@ -0,0 +1,11 @@+package base++// FieldError identifies the input field associated with an error.+type FieldError struct {+ Field string+ Err error+}++func (e *FieldError) Error() string { return e.Err.Error() }++func (e *FieldError) Unwrap() error { return e.Err }diff --git a/types/go.mod b/types/go.modindex fe67b318d..17cf2bbbe 100644--- a/types/go.mod+++ b/types/go.mod@@ -3,7 +3,6 @@ module github.com/getarcaneapp/arcane/types/v2go 1.27require (- emperror.dev/errors v0.8.1github.com/compose-spec/compose-go/v2 v2.15.0github.com/docker/go-units v0.5.0github.com/moby/moby/api v1.56.0@@ -27,7 +26,6 @@ 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/sirupsen/logrus v1.10.2 // indirectgithub.com/xhit/go-str2duration/v2 v2.1.0 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirect@@ -35,7 +33,6 @@ require (go.opentelemetry.io/otel v1.46.0 // indirectgo.opentelemetry.io/otel/metric v1.46.0 // indirectgo.opentelemetry.io/otel/trace v1.46.0 // indirect- go.uber.org/multierr v1.11.0 // indirectgo.yaml.in/yaml/v3 v3.0.5 // indirectgo.yaml.in/yaml/v4 v4.0.0-rc.6 // indirectgolang.org/x/sync v0.23.0 // indirectdiff --git a/types/go.sum b/types/go.sumindex 2321ec409..83d2fe851 100644--- a/types/go.sum+++ b/types/go.sum@@ -1,5 +1,3 @@-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=@@ -10,8 +8,6 @@ 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/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M=@@ -43,13 +39,8 @@ 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/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=-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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=@@ -70,10 +61,6 @@ go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=-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/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=diff --git a/types/project/marshal_utils.go b/types/project/marshal_utils.goindex bbfbeed26..fa3301c19 100644--- a/types/project/marshal_utils.go+++ b/types/project/marshal_utils.go@@ -3,15 +3,15 @@ package projectimport ("encoding/json/jsontext""encoding/json/v2"+ "fmt""strconv""strings"- "emperror.dev/errors"- composetypes "github.com/compose-spec/compose-go/v2/types"+ compose "github.com/compose-spec/compose-go/v2/types""github.com/docker/go-units")-var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decoder, value *composetypes.UnitBytes) error {+var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decoder, value *compose.UnitBytes) error {token, err := decoder.ReadToken()if err != nil {return err@@ -25,7 +25,7 @@ var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decodeif err != nil {return err}- *value = composetypes.UnitBytes(parsed)+ *value = compose.UnitBytes(parsed)return nilcase jsontext.KindNumber:raw := token.String()@@ -37,18 +37,18 @@ var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decode}parsed = int64(floatValue)if floatValue != float64(parsed) {- return errors.Errorf("invalid UnitBytes value %q", raw)+ return fmt.Errorf("invalid UnitBytes value %q", raw)}}- *value = composetypes.UnitBytes(parsed)+ *value = compose.UnitBytes(parsed)return nilcase jsontext.KindInvalid, jsontext.KindFalse, jsontext.KindTrue,jsontext.KindBeginObject, jsontext.KindEndObject,jsontext.KindBeginArray, jsontext.KindEndArray:- 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())+ return fmt.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())})type runtimeServiceAlias RuntimeService