This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 93521afb106d CAMEL-26913: camel-jbang - fix CLI startup and config 
bugs (#29805)
93521afb106d is described below

commit 93521afb106db60a42b01735d007b3a3f024ac73
Author: Guillaume Nodet <[email protected]>
AuthorDate: Sat Nov 14 09:41:21 2026 +0100

    CAMEL-26913: camel-jbang - fix CLI startup and config bugs (#29805)
    
    Fixes four bugs in the Camel CLI startup and configuration handling:
    
    - A malformed ~/.camel-cli.properties (e.g. an unescaped Windows path) no
      longer breaks every command: read-only callers warn once and go on with
      defaults, and the write callers (config set/unset, version set, the TUI
      settings) refuse to write instead of wiping the file.
    - The plugin config is written atomically, and a corrupt or unreadable
      ~/.camel-jbang-plugins.json no longer stops camel run or --help, nor is it
      overwritten; camel plugin commands exit 1 with a clear message.
    - camel.sh and camel.bat add a hash of the install directory to the CDS
      archive path, so two installs of the same version no longer share one.
    - --version and -V no longer trigger plugin discovery.
---
 .github/workflows/camel-launcher-native-exe.yml    |   2 +-
 .../modules/ROOT/pages/camel-jbang-launcher.adoc   |   2 +-
 .../dsl/jbang/core/commands/CamelJBangMain.java    |  19 +--
 .../dsl/jbang/core/commands/config/ConfigSet.java  |  10 +-
 .../jbang/core/commands/config/ConfigUnset.java    |  10 +-
 .../core/commands/plugin/PluginBaseCommand.java    |  14 ++-
 .../jbang/core/commands/version/VersionSet.java    |  12 +-
 .../dsl/jbang/core/common/CommandLineHelper.java   |  53 ++++++++-
 .../camel/dsl/jbang/core/common/PluginHelper.java  | 127 +++++++++++++++++----
 .../core/commands/UserConfigDefaultsTest.java      |  85 ++++++++++++++
 .../core/commands/version/VersionSetTest.java      |  19 +++
 .../dsl/jbang/core/common/PluginFilteringTest.java |  29 +++++
 .../dsl/jbang/core/common/PluginHelperTest.java    | 104 +++++++++++++++++
 .../dsl/jbang/core/commands/tui/TuiUserConfig.java |  44 ++++++-
 .../src/main/resources/bin/camel.bat               |  17 ++-
 .../camel-launcher/src/main/resources/bin/camel.sh |  15 ++-
 .../dsl/jbang/launcher/CamelBatDiscoveryTest.java  |  13 ++-
 .../dsl/jbang/launcher/CamelShDiscoveryTest.java   |  38 +++++-
 .../apache/camel/dsl/jbang/launcher/FakeJava.java  |  66 +++++++++++
 19 files changed, 612 insertions(+), 67 deletions(-)

diff --git a/.github/workflows/camel-launcher-native-exe.yml 
b/.github/workflows/camel-launcher-native-exe.yml
index 62eb78680571..ab6fcfa5f94f 100644
--- a/.github/workflows/camel-launcher-native-exe.yml
+++ b/.github/workflows/camel-launcher-native-exe.yml
@@ -257,7 +257,7 @@ jobs:
           # the first run creates the CDS archive of the command, the second 
one starts with it
           sh "$CAMEL" version
           sh "$CAMEL" version | grep -q 'Camel CLI version'
-          ls -l "$XDG_CACHE_HOME"/camel-cli/cds/*/version.jsa
+          ls -l "$XDG_CACHE_HOME"/camel-cli/cds/*/*/version.jsa
       - name: Verify reproducible native executables and WinGet archive
         run: |
           HASH_FILE="$RUNNER_TEMP/winget-first-build.sha256"
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-launcher.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-jbang-launcher.adoc
index 80ec9294ad7c..ed9be5da58dc 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-launcher.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-launcher.adoc
@@ -43,7 +43,7 @@ starts faster than the fat JAR.
 === Class data sharing
 
 The scripts turn on class data sharing of the JVM: the classes that a command 
loads are kept in an archive, one per
-command and Camel version, so the command starts faster the next time. The 
first run of a command creates its archive,
+command, Camel version and install directory, so the command starts faster the 
next time. The first run of a command creates its archive,
 and takes longer, and the JVM creates it again when the JDK changes. The 
archives are in
 `${XDG_CACHE_HOME:-~/.cache}/camel-cli/cds` (`%LOCALAPPDATA%\camel-cli\cds` on 
Windows), and can be removed at any time.
 
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
index 06e2cc03b40e..b7b0efd7c3ea 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
@@ -167,7 +167,7 @@ public class CamelJBangMain implements 
Command<CommandInvocation> {
         withErrorHandling(commandLine);
 
         CommandLineHelper.migrateLegacyUserConfig(out);
-        CommandLineHelper.augmentWithUserConfiguration(commandLine);
+        CommandLineHelper.augmentWithUserConfiguration(commandLine, out);
         preExecute(commandLine, args);
         int exitCode = run(commandLine, args);
         if (isHelpRequest(args) && EnvironmentHelper.isInteractiveTerminal()) {
@@ -521,7 +521,7 @@ public class CamelJBangMain implements 
Command<CommandInvocation> {
             plugin.customize(answer, this);
         }
         withErrorHandling(answer);
-        CommandLineHelper.augmentWithUserConfiguration(answer);
+        CommandLineHelper.augmentWithUserConfiguration(answer, out);
         return answer;
     }
 
@@ -633,12 +633,17 @@ public class CamelJBangMain implements 
Command<CommandInvocation> {
         }
 
         Set<String> installed = new HashSet<>();
-        JsonObject config = PluginHelper.getPluginConfig();
-        if (config != null) {
-            JsonObject plugins = config.getMap("plugins");
-            if (plugins != null) {
-                installed.addAll(plugins.keySet());
+        try {
+            JsonObject config = PluginHelper.getPluginConfig();
+            if (config != null) {
+                JsonObject plugins = config.getMap("plugins");
+                if (plugins != null) {
+                    installed.addAll(plugins.keySet());
+                }
             }
+        } catch (Exception e) {
+            // corrupt plugin config — don't crash the help/banner output
+            PluginHelper.warnCorruptPluginConfig(out, e);
         }
         // also consider already registered subcommands as installed
         Set<String> registered = commandLine.getSubcommands().keySet();
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigSet.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigSet.java
index b71c848620b8..36006eebfc60 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigSet.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigSet.java
@@ -24,6 +24,7 @@ import org.aesh.command.option.Option;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
 import org.apache.camel.dsl.jbang.core.common.CliException;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.util.StringHelper;
 
@@ -56,13 +57,16 @@ public class ConfigSet extends CamelCommand {
         }
         CommandLineHelper.createPropertyFile(local);
 
-        CommandLineHelper.loadProperties(properties -> {
+        if (!CommandLineHelper.loadProperties(properties -> {
             String key = StringHelper.before(configuration, "=").trim();
             String value = StringHelper.after(configuration, "=").trim();
             properties.put(key, value);
             CommandLineHelper.storeProperties(properties, printer(), local);
-        }, local);
+        }, local, printer())) {
+            printer().printErr("Cannot set configuration: the configuration 
file is malformed. Fix it by hand first.");
+            return CliExitCode.FAILURE;
+        }
 
-        return 0;
+        return CliExitCode.OK;
     }
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigUnset.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigUnset.java
index 4ad683f97c70..44dc24584f97 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigUnset.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/config/ConfigUnset.java
@@ -21,6 +21,7 @@ import org.aesh.command.option.Argument;
 import org.aesh.command.option.Option;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 
 @CommandDefinition(name = "unset", description = "Remove user configuration 
value", generateHelp = true,
@@ -41,11 +42,14 @@ public class ConfigUnset extends CamelCommand {
 
     @Override
     public Integer doCall() throws Exception {
-        CommandLineHelper.loadProperties(properties -> {
+        if (!CommandLineHelper.loadProperties(properties -> {
             properties.remove(key);
             CommandLineHelper.storeProperties(properties, printer(), !global);
-        }, !global);
+        }, !global, printer())) {
+            printer().printErr("Cannot unset configuration: the configuration 
file is malformed. Fix it by hand first.");
+            return CliExitCode.FAILURE;
+        }
 
-        return 0;
+        return CliExitCode.OK;
     }
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/plugin/PluginBaseCommand.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/plugin/PluginBaseCommand.java
index ebf703a5dbc1..df5c8dbfa1b6 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/plugin/PluginBaseCommand.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/plugin/PluginBaseCommand.java
@@ -21,8 +21,10 @@ import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 
 import org.aesh.command.option.Option;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliException;
 import org.apache.camel.dsl.jbang.core.common.PluginHelper;
 import org.apache.camel.util.json.JsonObject;
 
@@ -56,11 +58,15 @@ abstract class PluginBaseCommand extends CamelCommand {
     }
 
     JsonObject loadConfig() {
-        Path path = pluginConfigPath();
-        if (path != null) {
-            return PluginHelper.getOrCreatePluginConfig(path);
+        try {
+            Path path = pluginConfigPath();
+            if (path != null) {
+                return PluginHelper.getOrCreatePluginConfig(path);
+            }
+            return PluginHelper.getOrCreatePluginConfig();
+        } catch (RuntimeCamelException e) {
+            throw CliException.failure(e.getMessage() + ". Fix the JSON by 
hand or delete the file.");
         }
-        return PluginHelper.getOrCreatePluginConfig();
     }
 
     void saveConfig(JsonObject plugins) {
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSet.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSet.java
index c361221c86ad..f006d8ebced9 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSet.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSet.java
@@ -21,6 +21,7 @@ import org.aesh.command.option.Argument;
 import org.aesh.command.option.Option;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.dsl.jbang.core.common.RuntimeCompletionCandidates;
 import org.apache.camel.dsl.jbang.core.common.RuntimeTypeConverter;
@@ -60,7 +61,7 @@ public class VersionSet extends CamelCommand {
         boolean local = !global;
         CommandLineHelper.createPropertyFile(local);
 
-        CommandLineHelper.loadProperties(properties -> {
+        boolean ok = CommandLineHelper.loadProperties(properties -> {
             if (reset) {
                 properties.remove("camel-version");
                 properties.remove("kamelets-version");
@@ -78,9 +79,14 @@ public class VersionSet extends CamelCommand {
                 }
             }
             CommandLineHelper.storeProperties(properties, printer(), local);
-        }, local);
+        }, local, printer());
+        if (!ok) {
+            printer().printErr(
+                    "Cannot set version: config file is malformed. Edit it by 
hand, escaping '\\' as '\\\\' or using '/'.");
+            return CliExitCode.FAILURE;
+        }
 
-        return 0;
+        return CliExitCode.OK;
     }
 
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
index 3df167dd3780..d7f87e1e4e8a 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
@@ -27,6 +27,8 @@ import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.Consumer;
 
 import org.aesh.command.DefaultValueProvider;
@@ -40,6 +42,9 @@ import org.apache.camel.util.OrderedProperties;
  */
 public final class CommandLineHelper {
 
+    /** Paths whose malformed-config warning has already been printed this JVM 
run, to avoid repeating it. */
+    private static final Set<String> WARNED_PATHS = 
ConcurrentHashMap.newKeySet();
+
     public static final String USER_CONFIG = ".camel-cli.properties";
     public static final String LOCAL_USER_CONFIG = "camel-cli.properties";
     public static final String LEGACY_USER_CONFIG = 
".camel-jbang-user.properties";
@@ -127,12 +132,25 @@ public final class CommandLineHelper {
     }
 
     public static void augmentWithUserConfiguration(CommandTree commandLine) {
+        augmentWithUserConfiguration(commandLine, new 
Printer.SystemOutPrinter());
+    }
+
+    public static void augmentWithUserConfiguration(CommandTree commandLine, 
Printer printer) {
         Path file = getUserConfigurationFile();
         if (Files.isRegularFile(file) && Files.exists(file)) {
             Properties properties = new Properties();
             try (Reader reader = Files.newBufferedReader(file, 
StandardCharsets.UTF_8)) {
                 properties.load(reader);
-            } catch (IOException e) {
+            } catch (Exception e) {
+                // best-effort: a malformed config file (e.g. malformed 
unicode escape) must never break the CLI;
+                // warn the user so they know to fix it, but let the command 
continue without defaults.
+                // Warn once per path: loadProperties may also warn for the 
same file, so we deduplicate here.
+                String key = file.toAbsolutePath().toString();
+                if (WARNED_PATHS.add(key)) {
+                    printer.printErr(
+                            "Warning: could not parse '" + 
file.toAbsolutePath() + "' (" + e.getMessage()
+                                     + "). Edit the file by hand, escaping 
'\\' as '\\\\' or using '/'.");
+                }
                 return;
             }
 
@@ -162,16 +180,43 @@ public final class CommandLineHelper {
     }
 
     public static void loadProperties(Consumer<Properties> consumer, boolean 
local) {
+        boolean ok = loadProperties(consumer, local, new 
Printer.SystemOutPrinter());
+        if (!ok) {
+            // Read-only callers get empty props so the command continues with 
defaults.
+            // Write callers (config set/unset) use the 3-arg overload and 
check the return value.
+            consumer.accept(new OrderedProperties());
+        }
+    }
+
+    /**
+     * Loads user properties from the configuration file. When the file exists 
but is malformed (e.g. a Windows-style
+     * path stored without escaping produces a malformed \\uXXXX sequence), 
the method warns via the given printer and
+     * returns {@code false} <b>without</b> calling the consumer. This lets 
callers that write back to the file (config
+     * set, config unset) detect the failure and refuse to overwrite a 
malformed file.
+     *
+     * @return {@code true} if the file was loaded successfully (or did not 
exist), {@code false} if the file exists but
+     *         could not be parsed.
+     */
+    public static boolean loadProperties(Consumer<Properties> consumer, 
boolean local, Printer printer) {
         Path file = getUserPropertyFile(local);
         if (Files.isRegularFile(file) && Files.exists(file)) {
+            Properties prop = new OrderedProperties();
             try (InputStream is = Files.newInputStream(file)) {
-                Properties prop = new OrderedProperties();
                 prop.load(is);
-                consumer.accept(prop);
             } catch (Exception e) {
-                throw new RuntimeException("Cannot load user configuration: " 
+ file);
+                // Warn once per path per JVM run: camel run calls 
loadProperties from multiple code paths
+                // (resolveRepos, augmentWithUserConfiguration, 
printConfigurationValues) and each would
+                // print the same message. Using the absolute path as the key 
deduplicates the warning.
+                String key = file.toAbsolutePath().toString();
+                if (WARNED_PATHS.add(key)) {
+                    printer.printErr("Warning: could not parse '" + 
file.toAbsolutePath() + "' (" + e.getMessage()
+                                     + "). Edit the file by hand, escaping 
'\\' as '\\\\' or using '/'.");
+                }
+                return false;
             }
+            consumer.accept(prop);
         }
+        return true;
     }
 
     public static void storeProperties(Properties properties, Printer printer, 
boolean local) {
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
index 06d11503d4c0..cc9826f67682 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
@@ -23,9 +23,11 @@ import java.net.URISyntaxException;
 import java.net.URL;
 import java.net.URLClassLoader;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
 import java.nio.file.Files;
 import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
 import java.nio.file.StandardOpenOption;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -84,6 +86,9 @@ public final class PluginHelper {
     // the plugins warned about by compatibilityCheck, to warn once
     private static final Set<String> COMPATIBILITY_WARNED = 
ConcurrentHashMap.newKeySet();
 
+    /** Plugin config paths whose corrupt-file warning has already been 
printed this JVM run. */
+    private static final Set<String> WARNED_PLUGIN_PATHS = 
ConcurrentHashMap.newKeySet();
+
     private static final FactoryFinder FACTORY_FINDER
             = new DefaultFactoryFinder(new DefaultClassResolver(), 
FactoryFinder.DEFAULT_PATH + "camel-jbang-plugin/");
 
@@ -156,6 +161,11 @@ public final class PluginHelper {
         // optimization is acceptable since this prefix-options pattern is 
uncommon.
         String target = args[0];
         if (target == null || target.isBlank() || target.startsWith("-")) {
+            // --version (-V) only prints the version string: no plugins 
needed.
+            // All other global flags (--help, etc.) still need plugins for 
the full listing.
+            if ("--version".equals(target) || "-V".equals(target)) {
+                return false;
+            }
             return true;
         }
         if (PLUGIN_CONSUMING_BUILTINS.contains(target)) {
@@ -187,16 +197,22 @@ public final class PluginHelper {
         if (Arrays.stream(PluginType.values()).anyMatch(p -> 
p.getCommand().equals(command))) {
             return true;
         }
-        JsonObject config = getPluginConfig();
-        if (config != null) {
-            JsonObject plugins = config.getMap("plugins");
-            for (String pluginKey : plugins.keySet()) {
-                JsonObject properties = plugins.getMap(pluginKey);
-                String name = properties.getOrDefault("name", 
pluginKey).toString();
-                if (command.equals(properties.getOrDefault("command", 
name).toString())) {
-                    return true;
+        try {
+            JsonObject config = getPluginConfig();
+            if (config != null) {
+                JsonObject plugins = config.getMap("plugins");
+                if (plugins != null) {
+                    for (String pluginKey : plugins.keySet()) {
+                        JsonObject properties = plugins.getMap(pluginKey);
+                        String name = properties.getOrDefault("name", 
pluginKey).toString();
+                        if (command.equals(properties.getOrDefault("command", 
name).toString())) {
+                            return true;
+                        }
+                    }
                 }
             }
+        } catch (Exception e) {
+            // corrupt plugin config — treat as no plugins configured; logged 
elsewhere via warnCorruptPluginConfig
         }
         return 
PluginHelper.class.getClassLoader().getResource(PLUGIN_SERVICE_DIR + 
"camel-jbang-plugin-" + command) != null;
     }
@@ -359,11 +375,21 @@ public final class PluginHelper {
     public static Map<String, Plugin> getActivePlugins(
             CamelJBangMain main, String repos, String target, boolean 
legacyContributors) {
         Map<String, Plugin> activePlugins = new HashMap<>();
-        JsonObject config = getPluginConfig();
+        JsonObject config;
+        try {
+            config = getPluginConfig();
+        } catch (RuntimeCamelException e) {
+            // corrupt plugin JSON — warn once and continue with no plugins
+            warnCorruptPluginConfig(main.getOut(), e);
+            return activePlugins;
+        }
         if (config != null) {
             CamelCatalog catalog = new DefaultCamelCatalog();
             String version = catalog.getCatalogVersion();
             JsonObject plugins = config.getMap("plugins");
+            if (plugins == null) {
+                return activePlugins;
+            }
 
             boolean configDirty = false;
             for (String pluginKey : plugins.keySet()) {
@@ -776,11 +802,19 @@ public final class PluginHelper {
     }
 
     public static JsonObject getOrCreatePluginConfig() {
-        return 
Optional.ofNullable(getPluginConfig()).orElseGet(PluginHelper::createPluginConfig);
+        JsonObject existing = getPluginConfig();
+        if (existing != null) {
+            return existing;
+        }
+        return createPluginConfig();
     }
 
     public static JsonObject getOrCreatePluginConfig(Path configPath) {
-        return Optional.ofNullable(getPluginConfig(configPath)).orElseGet(() 
-> PluginHelper.createPluginConfig(configPath));
+        JsonObject existing = getPluginConfig(configPath);
+        if (existing != null) {
+            return existing;
+        }
+        return createPluginConfig(configPath);
     }
 
     public static JsonObject getPluginConfig() {
@@ -795,7 +829,12 @@ public final class PluginHelper {
                 return (JsonObject) Jsoner.deserialize(text);
             }
         } catch (Exception e) {
-            // ignore
+            // The file exists but cannot be read (AccessDeniedException, 
MalformedInputException)
+            // or the JSON is corrupt — either way throw so the caller does 
not silently overwrite it.
+            throw new RuntimeCamelException(
+                    "Plugin configuration file exists but is corrupt or 
unreadable: "
+                                            + 
getCustomPluginConfigPath(configPath) + " (" + e.getMessage() + ")",
+                    e);
         }
 
         return null;
@@ -813,10 +852,7 @@ public final class PluginHelper {
             if (parent != null) {
                 Files.createDirectories(parent);
             }
-            Files.writeString(f, config.toJson(),
-                    StandardOpenOption.CREATE,
-                    StandardOpenOption.WRITE,
-                    StandardOpenOption.TRUNCATE_EXISTING);
+            atomicWriteJson(f, config.toJson());
         } catch (IOException e) {
             throw new RuntimeCamelException("Failed to create plugin 
configuration", e);
         }
@@ -824,6 +860,49 @@ public final class PluginHelper {
         return config;
     }
 
+    /**
+     * Writes {@code content} to {@code target} atomically: writes to a 
sibling temp file first, then moves it into
+     * place with {@link StandardCopyOption#REPLACE_EXISTING}. When atomic 
move is not supported by the underlying
+     * filesystem, falls back to a plain overwriting move (rename(2)), which 
is still safe — a reader never observes a
+     * half-written file.
+     */
+    private static void atomicWriteJson(Path target, String content) throws 
IOException {
+        // Resolve symlinks so the move replaces the target file, not the 
symlink itself.
+        Path realTarget;
+        try {
+            realTarget = target.toRealPath();
+        } catch (IOException e) {
+            // file does not exist yet — no symlink to resolve
+            realTarget = target;
+        }
+        Path dir = realTarget.getParent();
+        if (dir != null) {
+            Files.createDirectories(dir);
+        }
+        Path tmp = dir != null
+                ? Files.createTempFile(dir, "." + realTarget.getFileName(), 
".tmp")
+                : Files.createTempFile("." + realTarget.getFileName(), ".tmp");
+        try {
+            Files.writeString(tmp, content, StandardOpenOption.WRITE, 
StandardOpenOption.TRUNCATE_EXISTING);
+            try {
+                Files.move(tmp, realTarget, 
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
+                tmp = null; // moved successfully, nothing to delete
+            } catch (AtomicMoveNotSupportedException e) {
+                // fall back: non-atomic replace — still better than 
truncate-then-write
+                Files.move(tmp, realTarget, 
StandardCopyOption.REPLACE_EXISTING);
+                tmp = null;
+            }
+        } finally {
+            if (tmp != null) {
+                try {
+                    Files.deleteIfExists(tmp);
+                } catch (IOException ignored) {
+                    // best effort
+                }
+            }
+        }
+    }
+
     public static void savePluginConfig(JsonObject plugins) {
         savePluginConfig(plugins, null);
     }
@@ -831,15 +910,23 @@ public final class PluginHelper {
     public static void savePluginConfig(JsonObject plugins, Path configPath) {
         Path f = getCustomPluginConfigPath(configPath);
         try {
-            Files.writeString(f, plugins.toJson(),
-                    StandardOpenOption.CREATE,
-                    StandardOpenOption.WRITE,
-                    StandardOpenOption.TRUNCATE_EXISTING);
+            atomicWriteJson(f, plugins.toJson());
         } catch (IOException e) {
             throw new RuntimeCamelException("Failed to save plugin 
configuration", e);
         }
     }
 
+    /**
+     * Warns about a corrupt or unreadable plugin configuration file, once per 
path per JVM run, so multiple callers
+     * (e.g. {@code getActivePlugins} and {@code printAvailablePlugins}) do 
not repeat the message.
+     */
+    public static void warnCorruptPluginConfig(Printer printer, Exception e) {
+        String key = e.getMessage() != null ? e.getMessage() : 
"unknown-corrupt-plugin-config";
+        if (WARNED_PLUGIN_PATHS.add(key)) {
+            printer.printErr("Warning: " + e.getMessage() + ". Fix the JSON by 
hand or delete the file.");
+        }
+    }
+
     /**
      * Loads the list of known 3rd party plugins from the classpath resource 
known-plugins.json.
      */
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/UserConfigDefaultsTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/UserConfigDefaultsTest.java
index 6bbc035e322f..3724b8d83f0b 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/UserConfigDefaultsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/UserConfigDefaultsTest.java
@@ -78,6 +78,91 @@ class UserConfigDefaultsTest extends BaseConfigTestSupport {
         assertThat(run("echo")).isEqualTo("sort=age repos=null");
     }
 
+    @Test
+    void malformedUserConfigDoesNotCrashCli() throws Exception {
+        // A Windows-style path stored without escaping produces a malformed 
\\uXXXX sequence,
+        // which throws IllegalArgumentException from Properties.load — not 
IOException.
+        // The CLI must warn and continue instead of propagating the exception.
+        UserConfigHelper.createUserConfig("path=C:\\users\\name");
+
+        // The command must succeed (not throw); the option falls back to its 
own default.
+        assertThat(runCapturingWarning("echo")).isEqualTo("sort=pid 
repos=null");
+    }
+
+    @Test
+    void malformedConfigLoadPropertiesReturnsFalseAndWarns() throws Exception {
+        // loadProperties must not throw and must return false for a malformed 
config file
+        UserConfigHelper.createUserConfig("path=C:\\users\\name");
+
+        StringPrinter out = new StringPrinter();
+        boolean[] consumerCalled = { false };
+        boolean loaded = CommandLineHelper.loadProperties(props -> {
+            // should NOT be called since the 3-arg overload does not call 
consumer on failure
+            consumerCalled[0] = true;
+        }, false, out);
+
+        assertThat(loaded).as("loadProperties should return false for a 
malformed file").isFalse();
+        assertThat(consumerCalled[0]).as("consumer must not be called on 
failure").isFalse();
+        assertThat(out.getStderr()).contains("could not parse");
+        assertThat(out.getStderr()).contains("escaping");
+    }
+
+    @Test
+    void malformedConfigLoadPropertiesTwoArgCallsConsumerWithEmpty() throws 
Exception {
+        // The 2-arg overload (used by read-only callers) calls consumer with 
empty props
+        UserConfigHelper.createUserConfig("path=C:\\users\\name");
+
+        boolean[] consumerCalled = { false };
+        CommandLineHelper.loadProperties(props -> {
+            consumerCalled[0] = true;
+            assertThat(props).isEmpty();
+        }, false);
+
+        assertThat(consumerCalled[0]).as("2-arg overload should call consumer 
with empty props").isTrue();
+    }
+
+    @Test
+    void malformedConfigWarningIsOnlyPrintedOnce() throws Exception {
+        // When a command calls loadProperties multiple times for the same 
malformed file
+        // (e.g. resolveRepos, augmentWithUserConfiguration, 
printConfigurationValues all do so for camel run),
+        // the warning must only appear once to avoid flooding the terminal.
+        UserConfigHelper.createUserConfig("path=C:\\users\\name");
+
+        StringPrinter out = new StringPrinter();
+        // Simulate multiple calls that would each trigger the warning for the 
same file
+        CommandLineHelper.loadProperties(props -> {
+        }, false, out);
+        CommandLineHelper.loadProperties(props -> {
+        }, false, out);
+        CommandLineHelper.loadProperties(props -> {
+        }, false, out);
+
+        long warningCount = out.getStderr().lines()
+                .filter(l -> l.contains("could not parse"))
+                .count();
+        assertThat(warningCount).as("warning must appear exactly once, not 
once per loadProperties call").isOne();
+    }
+
+    private static String runCapturingWarning(String... args) {
+        StringPrinter out = new StringPrinter();
+        CamelJBangMain main = new CamelJBangMain().withPrinter(out);
+        CommandTree commandLine = new CommandTree(main)
+                .addSubcommand("echo", new CommandTree(new EchoCommand(main)))
+                .addSubcommand("other", new CommandTree(new EchoCommand(main)))
+                .addSubcommand("dev", new CommandTree(new DevCommand(main)))
+                .addSubcommand("plugin", new CommandTree(new 
PluginCommand(main))
+                        .addSubcommand("echo", new CommandTree(new 
EchoCommand(main))));
+        // augmentWithUserConfiguration must NOT throw for a malformed config
+        CommandLineHelper.augmentWithUserConfiguration(commandLine, out);
+
+        try {
+            assertThat(commandLine.execute(args).getResultValue()).isZero();
+        } catch (Exception e) {
+            throw new IllegalStateException(e);
+        }
+        return out.getStdout();
+    }
+
     @Test
     void pluginCommandsDoNotUseTheConfiguration() throws Exception {
         UserConfigHelper.createUserConfig("sort=name");
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSetTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSetTest.java
index 5930074a470f..5977c7e094bd 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSetTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/version/VersionSetTest.java
@@ -22,6 +22,7 @@ import java.nio.file.Paths;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
 import org.apache.camel.dsl.jbang.core.commands.UserConfigHelper;
 import org.apache.camel.dsl.jbang.core.commands.config.BaseConfigTestSupport;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.dsl.jbang.run.common.RuntimeType;
 import org.junit.jupiter.api.Test;
@@ -123,4 +124,22 @@ class VersionSetTest extends BaseConfigTestSupport {
         CommandLineHelper.loadProperties(properties -> assertEquals("4.10.0", 
properties.get("camel-version")), true);
     }
 
+    @Test
+    void malformedConfigRefusesWriteAndReturnsNonZero() throws Exception {
+        // A malformed config file (Windows-style path without escaping) must 
not be overwritten
+        UserConfigHelper.createUserConfig("path=C:\\users\\name");
+        String originalContent = Files.readString(
+                
CommandLineHelper.getHomeDir().resolve(CommandLineHelper.USER_CONFIG));
+
+        VersionSet command = new VersionSet(new 
CamelJBangMain().withPrinter(printer));
+        command.version = "4.10.0";
+        Integer exitCode = command.doCall();
+
+        // must return non-zero and leave the file untouched
+        assertEquals(CliExitCode.FAILURE, exitCode, "exit code must be 1 on 
malformed config");
+        String afterContent = Files.readString(
+                
CommandLineHelper.getHomeDir().resolve(CommandLineHelper.USER_CONFIG));
+        assertEquals(originalContent, afterContent, "malformed config file 
must not be overwritten");
+    }
+
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java
index f5890f140ada..d324d33017f7 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java
@@ -514,4 +514,33 @@ class PluginFilteringTest {
             return CommandResult.SUCCESS;
         }
     }
+
+    // --- CAMEL-26913: --version and -V must not trigger plugin discovery ---
+
+    @Test
+    void versionFlagDoesNotDiscoverPlugins() {
+        CamelJBangMain main = new CamelJBangMain().withPrinter(new 
StringPrinter());
+        CommandTree commandLine = new CommandTree(main);
+        commandLine.addSubcommand("version", new CommandTree(new 
NoOpCommand()));
+        commandLine.addSubcommand("get", new CommandTree(new NoOpCommand()));
+        assertThat(PluginHelper.shouldDiscoverPlugins(commandLine, 
"--version")).isFalse();
+        assertThat(PluginHelper.shouldDiscoverPlugins(commandLine, 
"-V")).isFalse();
+    }
+
+    @Test
+    void helpFlagStillDiscoverPlugins() {
+        CamelJBangMain main = new CamelJBangMain().withPrinter(new 
StringPrinter());
+        CommandTree commandLine = new CommandTree(main);
+        commandLine.addSubcommand("version", new CommandTree(new 
NoOpCommand()));
+        // --help needs all plugins for the full listing
+        assertThat(PluginHelper.shouldDiscoverPlugins(commandLine, 
"--help")).isTrue();
+        assertThat(PluginHelper.shouldDiscoverPlugins(commandLine, 
"-h")).isTrue();
+    }
+
+    @Test
+    void noArgDiscoverPlugins() {
+        CamelJBangMain main = new CamelJBangMain().withPrinter(new 
StringPrinter());
+        CommandTree commandLine = new CommandTree(main);
+        assertThat(PluginHelper.shouldDiscoverPlugins(commandLine)).isTrue();
+    }
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginHelperTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginHelperTest.java
index 280f8f63c271..dd539742aefd 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginHelperTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginHelperTest.java
@@ -35,6 +35,7 @@ import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -642,4 +643,107 @@ public class PluginHelperTest {
             return CommandResult.SUCCESS;
         }
     }
+
+    // --- CAMEL-26913: atomic write for savePluginConfig ---
+
+    @Test
+    void savePluginConfigWritesAtomically() throws Exception {
+        // create a valid plugin config
+        Path configPath = tempDir.resolve(PluginHelper.PLUGIN_CONFIG);
+        JsonObject config = PluginHelper.createPluginConfig(tempDir);
+
+        // add a fake plugin entry
+        JsonObject plugins = config.getMap("plugins");
+        JsonObject fakePlugin = new JsonObject();
+        fakePlugin.put("name", "fake");
+        fakePlugin.put("command", "fake");
+        plugins.put("fake", fakePlugin);
+
+        // save via the atomic path
+        PluginHelper.savePluginConfig(config, tempDir);
+
+        // the file must exist and have the expected content
+        assertTrue(Files.exists(configPath));
+        String content = Files.readString(configPath);
+        assertTrue(content.contains("\"fake\""));
+
+        // no temp files left behind
+        try (var stream = Files.list(tempDir)) {
+            long tmpCount = stream.filter(p -> 
p.getFileName().toString().endsWith(".tmp")).count();
+            assertEquals(0, tmpCount, "Stray .tmp files found in " + tempDir);
+        }
+    }
+
+    @Test
+    void savePluginConfigPreservesExistingFileOnWrite() throws Exception {
+        // start with a valid config
+        PluginHelper.createPluginConfig(tempDir);
+        Path configPath = tempDir.resolve(PluginHelper.PLUGIN_CONFIG);
+
+        // reading back produces the same object
+        JsonObject read = PluginHelper.getPluginConfig(tempDir);
+        assertNotNull(read);
+        PluginHelper.savePluginConfig(read, tempDir);
+
+        // content should be equivalent — round-trip must preserve the plugins 
map
+        String afterSave = Files.readString(configPath);
+        assertNotNull(afterSave);
+        assertTrue(afterSave.contains("\"plugins\""), "saved config must still 
contain the plugins key");
+        JsonObject reRead = PluginHelper.getPluginConfig(tempDir);
+        assertNotNull(reRead);
+        assertNotNull(reRead.getMap("plugins"), "plugins map must be preserved 
after save");
+    }
+
+    @Test
+    void emptyJsonObjectDoesNotCauseNpe() throws Exception {
+        // {} without a "plugins" key must not NPE — getActivePlugins should 
return empty
+        Path userConfig = 
CommandLineHelper.getHomeDir().resolve(PluginHelper.PLUGIN_CONFIG);
+        Files.writeString(userConfig, "{}", StandardOpenOption.CREATE);
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "version");
+        assertTrue(plugins.isEmpty());
+    }
+
+    @Test
+    void isPluginCommandHandlesEmptyJsonObject() throws Exception {
+        // {} without a "plugins" key must not NPE in isPluginCommand
+        Path userConfig = 
CommandLineHelper.getHomeDir().resolve(PluginHelper.PLUGIN_CONFIG);
+        Files.writeString(userConfig, "{}", StandardOpenOption.CREATE);
+
+        assertFalse(PluginHelper.isPluginCommand("fake"));
+    }
+
+    @Test
+    void truncatedJsonThrowsOnGetPluginConfig() throws Exception {
+        Path userConfig = 
CommandLineHelper.getHomeDir().resolve(PluginHelper.PLUGIN_CONFIG);
+        Files.writeString(userConfig, "{ \"plugins\": { \"foo\":", 
StandardOpenOption.CREATE);
+
+        assertThrows(RuntimeException.class, () -> 
PluginHelper.getPluginConfig());
+    }
+
+    @Test
+    void corruptPluginJsonDoesNotCrashGetActivePlugins() throws Exception {
+        // A truncated/corrupt plugin JSON must not crash camel run, camel 
--help, etc.
+        // getActivePlugins must warn and return empty map instead of throwing.
+        Path userConfig = 
CommandLineHelper.getHomeDir().resolve(PluginHelper.PLUGIN_CONFIG);
+        Files.writeString(userConfig, "{ \"plugins\": { \"foo\":", 
StandardOpenOption.CREATE);
+
+        StringPrinter out = new StringPrinter();
+        CamelJBangMain main = new CamelJBangMain().withPrinter(out);
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "run");
+
+        assertThat(plugins).isEmpty();
+        assertThat(out.getStderr()).contains("corrupt");
+    }
+
+    @Test
+    void getOrCreatePluginConfigRefusesToOverwriteCorruptFile() throws 
Exception {
+        Path userConfig = 
CommandLineHelper.getHomeDir().resolve(PluginHelper.PLUGIN_CONFIG);
+        Files.writeString(userConfig, "TRUNCATED GARBAGE", 
StandardOpenOption.CREATE);
+
+        assertThrows(RuntimeException.class, () -> 
PluginHelper.getOrCreatePluginConfig());
+        // the corrupt file must still exist (not overwritten)
+        assertEquals("TRUNCATED GARBAGE", Files.readString(userConfig));
+    }
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiUserConfig.java
 
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiUserConfig.java
index 9f9af4fa5fb4..c3eeac19fc73 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiUserConfig.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiUserConfig.java
@@ -40,6 +40,33 @@ import org.apache.camel.dsl.jbang.run.common.Printer;
  */
 final class TuiUserConfig {
 
+    /** A printer that discards everything — safe for TUI operations where 
stderr goes to the TUI screen. */
+    private static final Printer SILENT_PRINTER = new Printer() {
+        @Override
+        public void println() {
+        }
+
+        @Override
+        public void println(String line) {
+        }
+
+        @Override
+        public void print(String output) {
+        }
+
+        @Override
+        public void printf(String format, Object... args) {
+        }
+
+        @Override
+        public void printDiagnostic(String line) {
+        }
+
+        @Override
+        public void printErr(String message) {
+        }
+    };
+
     /** The settings of a session started with --defaults, kept in memory 
only; null for the files. */
     private static volatile Map<String, String> session;
 
@@ -73,7 +100,11 @@ final class TuiUserConfig {
         }
         boolean local = livesInLocal(key);
         String[] holder = { null };
-        CommandLineHelper.loadProperties(props -> holder[0] = 
props.getProperty(key), local);
+        boolean ok = CommandLineHelper.loadProperties(props -> holder[0] = 
props.getProperty(key), local,
+                SILENT_PRINTER);
+        if (!ok) {
+            throw new RuntimeException("Could not parse TUI user config file");
+        }
         return holder[0];
     }
 
@@ -100,15 +131,18 @@ final class TuiUserConfig {
             throw new UncheckedIOException(e);
         }
         String trimmed = trimToNull(value);
-        CommandLineHelper.loadProperties(props -> {
+        boolean ok = CommandLineHelper.loadProperties(props -> {
             if (trimmed == null) {
                 props.remove(key);
             } else {
                 props.setProperty(key, trimmed);
             }
-            CommandLineHelper.storeProperties(props,
-                    new Printer.QuietPrinter(new Printer.SystemOutPrinter()), 
local);
-        }, local);
+            CommandLineHelper.storeProperties(props, SILENT_PRINTER, local);
+        }, local, SILENT_PRINTER);
+        if (!ok) {
+            // malformed file — do not overwrite; throw so TUI callers (which 
catch RuntimeException) know
+            throw new RuntimeException("Could not update TUI preference '" + 
key + "': config file is malformed.");
+        }
     }
 
     private static boolean livesInLocal(String key) {
diff --git a/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.bat 
b/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.bat
index 9defc6d8caf0..28ea94c7a7ee 100644
--- a/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.bat
+++ b/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.bat
@@ -61,8 +61,8 @@ for %%i in ("%BASEDIR%\..\lib\camel-launcher-*.jar") do (
   if errorlevel 1 if not defined LAUNCHER_JAR set "LAUNCHER_JAR=%%~fi"
 )
 
-@REM Class data sharing: the JVM keeps the classes that a command loads in an 
archive (one per command and Camel
-@REM version, in %LOCALAPPDATA%\camel-cli\cds), which it creates when the 
command runs the first time, or again when
+@REM Class data sharing: the JVM keeps the classes that a command loads in an 
archive (one per command, Camel
+@REM version and install directory, in %LOCALAPPDATA%\camel-cli\cds), which it 
creates when the command runs the first time, or again when
 @REM the JDK changed, so the command starts faster from then on. 
CAMEL_CDS=false turns it off, and so do CDS or AOT
 @REM options of JAVA_OPTS. A JVM without CDS (OpenJ9) ignores the options.
 set "CDS_FILE="
@@ -87,7 +87,18 @@ if "!_CDS_REST!"=="." set "_CDS_CMD=!_CDS_ARG!"
 :cdsCommandDone
 for %%j in ("!LAUNCHER_JAR!") do set "_CDS_VERSION=%%~nj"
 set "_CDS_VERSION=!_CDS_VERSION:camel-launcher-=!"
-set "_CDS_DIR=!LOCALAPPDATA!\camel-cli\cds\!_CDS_VERSION!"
+@REM Include a hash of the install directory so two installs of the same 
version get separate archives.
+@REM Different install methods (SDKMAN, zip) place the launcher in different 
directories;
+@REM a shared archive from another install points at the wrong JAR or returns 
wrong install metadata.
+@REM Pass BASEDIR via environment to avoid trailing-backslash breaking 
PowerShell string quoting.
+set "_CDS_INSTALL_HASH="
+set "_CDS_PS_INPUT=!BASEDIR!"
+set "_CDS_PS_EXE=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
+if exist "!_CDS_PS_EXE!" (
+  for /f "delims=" %%h in ('!_CDS_PS_EXE! -NoProfile -NonInteractive -Command 
"$b=[System.Text.Encoding]::UTF8.GetBytes($env:_CDS_PS_INPUT);$h=[System.Security.Cryptography.SHA256]::Create().ComputeHash($b);($h[0..3]|ForEach-Object{$_.ToString(\"x2\")})
 -join \"\"" 2^>nul') do set "_CDS_INSTALL_HASH=%%h"
+)
+if not defined _CDS_INSTALL_HASH set "_CDS_INSTALL_HASH=default"
+set "_CDS_DIR=!LOCALAPPDATA!\camel-cli\cds\!_CDS_VERSION!\!_CDS_INSTALL_HASH!"
 @REM the JVM does not start when the directory of the archive is missing
 if not exist "!_CDS_DIR!\" mkdir "!_CDS_DIR!" 2> nul
 if not exist "!_CDS_DIR!\" goto cdsEnd
diff --git a/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.sh 
b/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.sh
index 22a26d496ac5..cacae1343145 100644
--- a/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.sh
+++ b/dsl/camel-jbang/camel-launcher/src/main/resources/bin/camel.sh
@@ -120,10 +120,10 @@ for f in "$LIBDIR"/camel-launcher-*.jar; do
   fi
 done
 
-# Class data sharing: the JVM keeps the classes that a command loads in an 
archive (one per command and Camel version,
-# in the cache directory of the user), which it creates when the command runs 
the first time, or again when the JDK
-# changed, so the command starts faster from then on. CAMEL_CDS=false turns it 
off, and so do CDS or AOT options of
-# JAVA_OPTS. A JVM without CDS (OpenJ9) ignores the options.
+# Class data sharing: the JVM keeps the classes that a command loads in an 
archive (one per command, Camel version
+# and install directory, in the cache directory of the user), which it creates 
when the command runs the first time,
+# or again when the JDK changed, so the command starts faster from then on. 
CAMEL_CDS=false turns it off, and so
+# do CDS or AOT options of JAVA_OPTS. A JVM without CDS (OpenJ9) ignores the 
options.
 CDS_FILE=
 camel_cds_file() {
   [ "$CAMEL_CDS" != "false" ] && [ -n "$LAUNCHER_JAR" ] || return 1
@@ -134,9 +134,14 @@ camel_cds_file() {
   esac
   _cds_version=`basename "$LAUNCHER_JAR" .jar`
   _cds_version=${_cds_version#camel-launcher-}
+  # Include a hash of the install directory so two installs of the same 
version get separate archives.
+  # Different install methods (SDKMAN, Homebrew, zip) place the launcher in 
different directories;
+  # a shared archive from another install points at the wrong JAR (child 
processes) or returns wrong
+  # install-method metadata (camel self-update, update notice).
+  _cds_install_hash=`printf '%s' "$BASEDIR" | cksum | cut -d' ' -f1`
   _cds_cache=${XDG_CACHE_HOME:-${HOME:+$HOME/.cache}}
   [ -n "$_cds_cache" ] || return 1
-  _cds_dir="$_cds_cache/camel-cli/cds/$_cds_version"
+  _cds_dir="$_cds_cache/camel-cli/cds/$_cds_version/$_cds_install_hash"
   # the JVM does not start when the directory of the archive is missing
   mkdir -p "$_cds_dir" 2>/dev/null && [ -w "$_cds_dir" ] || return 1
   CDS_FILE="$_cds_dir/$_cds_cmd.jsa"
diff --git 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelBatDiscoveryTest.java
 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelBatDiscoveryTest.java
index 3f79d4e7cf12..855f6628c174 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelBatDiscoveryTest.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelBatDiscoveryTest.java
@@ -66,7 +66,9 @@ class CamelBatDiscoveryTest {
         Path system32 = Path.of(systemRoot, "System32");
         assertTrue(Files.isDirectory(system32), "Windows test fixture requires 
SystemRoot\\System32: " + system32);
         Map<String, String> env = new HashMap<>();
-        env.put("PATH", system32.toString());
+        // Include System32 and PowerShell so camel.bat's CDS 
install-directory hash works.
+        Path powerShell = Path.of(systemRoot, "System32", "WindowsPowerShell", 
"v1.0");
+        env.put("PATH", system32 + ";" + powerShell);
         return env;
     }
 
@@ -107,7 +109,8 @@ class CamelBatDiscoveryTest {
 
         FakeJava.Result r = FakeJava.run(h.resolve("camel.bat"), env, 
"version");
 
-        Path archives = 
localAppData.resolve("camel-cli").resolve("cds").resolve("9.9.9");
+        String hash = FakeJava.batCdsHash(FakeJava.batBasedirString(h));
+        Path archives = 
localAppData.resolve("camel-cli").resolve("cds").resolve("9.9.9").resolve(hash);
         assertEquals(0, r.exitCode(), r.stderr());
         assertTrue(r.stdout().contains("-XX:+AutoCreateSharedArchive 
\"-XX:SharedArchiveFile="
                                        + archives.resolve("version.jsa") + "\" 
\"-Xlog:cds*=off\" -jar "),
@@ -126,8 +129,9 @@ class CamelBatDiscoveryTest {
 
         FakeJava.Result r = FakeJava.run(h.resolve("camel.bat"), env, 
"--help");
 
+        String hash = FakeJava.batCdsHash(FakeJava.batBasedirString(h));
         assertTrue(r.stdout().contains(
-                "-XX:SharedArchiveFile=" + 
localAppData.resolve("camel-cli\\cds\\9.9.9\\camel.jsa") + "\""),
+                "-XX:SharedArchiveFile=" + 
localAppData.resolve("camel-cli\\cds\\9.9.9\\" + hash + "\\camel.jsa") + "\""),
                 r.stdout());
     }
 
@@ -137,7 +141,8 @@ class CamelBatDiscoveryTest {
         Path h = home(base);
         Path java = FakeJava.writeFakeJava(base, "java", JAVA21, 0, "ARGS");
         Path localAppData = Files.createDirectories(base.resolve("lad"));
-        Path archive = 
Files.createDirectories(localAppData.resolve("camel-cli\\cds\\9.9.9")).resolve("version.jsa");
+        String hash = FakeJava.batCdsHash(FakeJava.batBasedirString(h));
+        Path archive = 
Files.createDirectories(localAppData.resolve("camel-cli\\cds\\9.9.9\\" + 
hash)).resolve("version.jsa");
         Files.createFile(archive);
         Map<String, String> env = isolatedEnvironment();
         env.put("JAVACMD", java.toString());
diff --git 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelShDiscoveryTest.java
 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelShDiscoveryTest.java
index f323abe0e62e..070089abbc58 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelShDiscoveryTest.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/CamelShDiscoveryTest.java
@@ -402,7 +402,8 @@ class CamelShDiscoveryTest {
 
         FakeJava.Result r = FakeJava.run(h.resolve("camel.sh"), env, 
"version");
 
-        Path archives = cache.resolve("camel-cli/cds/9.9.9");
+        String hash = FakeJava.cksumHash(FakeJava.basedir(h).toString());
+        Path archives = cache.resolve("camel-cli/cds/9.9.9/" + hash);
         assertEquals(0, r.exitCode(), r.stderr());
         
assertTrue(r.stdout().contains("|-XX:+AutoCreateSharedArchive|-XX:SharedArchiveFile="
 + archives.resolve("version.jsa")
                                        + "|-Xlog:cds*=off|-jar|"),
@@ -421,7 +422,10 @@ class CamelShDiscoveryTest {
 
         FakeJava.Result r = FakeJava.run(h.resolve("camel.sh"), env, "--help");
 
-        assertTrue(r.stdout().contains("-XX:SharedArchiveFile=" + 
cache.resolve("camel-cli/cds/9.9.9/camel.jsa") + "|"),
+        String hash = FakeJava.cksumHash(FakeJava.basedir(h).toString());
+        assertTrue(
+                r.stdout()
+                        .contains("-XX:SharedArchiveFile=" + 
cache.resolve("camel-cli/cds/9.9.9/" + hash + "/camel.jsa") + "|"),
                 r.stdout());
     }
 
@@ -436,7 +440,10 @@ class CamelShDiscoveryTest {
 
         FakeJava.Result r = FakeJava.run(h.resolve("camel.sh"), env, "get");
 
-        assertTrue(r.stdout().contains("-XX:SharedArchiveFile=" + 
userHome.resolve(".cache/camel-cli/cds/9.9.9/get.jsa")),
+        String hash = FakeJava.cksumHash(FakeJava.basedir(h).toString());
+        assertTrue(
+                r.stdout().contains(
+                        "-XX:SharedArchiveFile=" + 
userHome.resolve(".cache/camel-cli/cds/9.9.9/" + hash + "/get.jsa")),
                 r.stdout());
     }
 
@@ -446,7 +453,8 @@ class CamelShDiscoveryTest {
         Path h = home(base);
         Path java = FakeJava.writeFakeJava(base, "java", JAVA21, 0, "ARGS");
         Path cache = base.resolve("cache");
-        Path archive = 
Files.createDirectories(cache.resolve("camel-cli/cds/9.9.9")).resolve("version.jsa");
+        String hash = FakeJava.cksumHash(FakeJava.basedir(h).toString());
+        Path archive = 
Files.createDirectories(cache.resolve("camel-cli/cds/9.9.9/" + 
hash)).resolve("version.jsa");
         Files.createFile(archive);
         Map<String, String> env = new HashMap<>();
         env.put("JAVACMD", java.toString());
@@ -458,6 +466,28 @@ class CamelShDiscoveryTest {
         assertFalse(Files.exists(archive));
     }
 
+    @Test
+    void twoInstallDirectoriesGetDistinctArchives(@TempDir Path base) throws 
Exception {
+        // Two installs of the same version (e.g. SDKMAN + Homebrew) must get 
separate CDS archives
+        Path h1 = home(Files.createDirectories(base.resolve("install-a")));
+        Path h2 = home(Files.createDirectories(base.resolve("install-b")));
+        Path java = FakeJava.writeFakeJava(base, "java", JAVA21, 0, "ARGS");
+        Path cache = base.resolve("cache");
+        Map<String, String> env1 = new HashMap<>();
+        env1.put("JAVACMD", java.toString());
+        env1.put("XDG_CACHE_HOME", cache.toString());
+        Map<String, String> env2 = new HashMap<>(env1);
+
+        FakeJava.Result r1 = FakeJava.run(h1.resolve("camel.sh"), env1, 
"version");
+        FakeJava.Result r2 = FakeJava.run(h2.resolve("camel.sh"), env2, 
"version");
+
+        String hash1 = FakeJava.cksumHash(FakeJava.basedir(h1).toString());
+        String hash2 = FakeJava.cksumHash(FakeJava.basedir(h2).toString());
+        assertFalse(hash1.equals(hash2), "different install dirs must produce 
different hashes");
+        assertTrue(r1.stdout().contains("cds/9.9.9/" + hash1 + 
"/version.jsa"), r1.stdout());
+        assertTrue(r2.stdout().contains("cds/9.9.9/" + hash2 + 
"/version.jsa"), r2.stdout());
+    }
+
     @Test
     void noArchiveWhenTurnedOffOrJavaOptsHaveCdsOptions(@TempDir Path base) 
throws Exception {
         Path h = home(base);
diff --git 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/FakeJava.java
 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/FakeJava.java
index ebedcc35c331..3e68cb18f72b 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/FakeJava.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/FakeJava.java
@@ -20,7 +20,9 @@ import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.security.MessageDigest;
 import java.util.ArrayList;
+import java.util.HexFormat;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -234,4 +236,68 @@ final class FakeJava {
             }
         }
     }
+
+    /**
+     * Computes the POSIX cksum hash of the given string, matching the shell 
expression
+     * {@code printf '%s' "$str" | cksum | cut -d' ' -f1} used in camel.sh for 
CDS directory hashing.
+     */
+    static String cksumHash(String str) throws Exception {
+        ProcessBuilder pb = new ProcessBuilder(
+                "/bin/sh", "-c",
+                "printf '%s' '" + str.replace("'", "'\\''") + "' | cksum | cut 
-d' ' -f1");
+        pb.environment().clear();
+        pb.environment().put("PATH", "/usr/bin:/bin");
+        Process p = pb.start();
+        byte[] out = p.getInputStream().readAllBytes();
+        p.waitFor(10, TimeUnit.SECONDS);
+        return new String(out, StandardCharsets.UTF_8).trim();
+    }
+
+    /**
+     * Computes the Windows CDS install-directory hash of the given string, 
matching the PowerShell expression used in
+     * camel.bat: SHA-256 of the UTF-8 bytes, first 4 bytes as lowercase hex 
(8 chars). Falls back to {@code "default"}
+     * if the hash cannot be computed (should not happen on Windows JVM).
+     */
+    static String batCdsHash(String str) {
+        try {
+            byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
+            byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes);
+            return HexFormat.of().formatHex(digest, 0, 4);
+        } catch (Exception e) {
+            return "default";
+        }
+    }
+
+    /**
+     * Returns the Windows CDS BASEDIR string as computed by camel.bat: the 
{@code %~dp0} of the launcher script (the
+     * bin\ directory path with a trailing backslash), as cmd.exe resolves it. 
This may differ from
+     * {@code bin.toString() + "\\"} when Windows 8.3 short names are involved 
(e.g. {@code C:\\Users\\RUNNER~1\\} vs
+     * the full long path), so this method runs a helper batch to capture the 
actual {@code %~dp0} rather than inferring
+     * it from the Java Path.
+     */
+    static String batBasedirString(Path bin) throws Exception {
+        Path helper = Files.createTempFile(bin, "basedir-probe", ".bat");
+        try {
+            Files.writeString(helper, "@echo %~dp0\r\n", 
StandardCharsets.UTF_8);
+            String systemRoot = System.getenv("SystemRoot");
+            ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", 
helper.toString());
+            pb.environment().clear();
+            pb.environment().put("PATH", systemRoot + "\\System32");
+            pb.environment().put("SystemRoot", systemRoot);
+            pb.environment().put("OS", "Windows_NT");
+            Process p = pb.start();
+            String out = new String(p.getInputStream().readAllBytes(), 
StandardCharsets.UTF_8).strip();
+            p.waitFor(5, TimeUnit.SECONDS);
+            return out; // e.g. "D:\\a\\...\\bin\\" (trailing backslash 
included by %~dp0)
+        } finally {
+            Files.deleteIfExists(helper);
+        }
+    }
+
+    /**
+     * The BASEDIR of a launcher home as computed by camel.sh: the directory 
of the script (bin/).
+     */
+    static Path basedir(Path bin) {
+        return bin;
+    }
 }

Reply via email to