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

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

commit e4d40e2332fa69958932a2eb4704f986431102ed
Author: Jinal Sarvaiya <[email protected]>
AuthorDate: Thu Nov 26 14:56:16 2026 +0000

    Fix #113: Address all reviewer feedback on OpenCode regeneration and 
validation
---
 docs/modules/ROOT/pages/agents.adoc                |   7 +-
 .../camel/kit/generator/OpenCodeConfigMerger.java  |  52 +++++++--
 .../apache/camel/kit/service/DoctorService.java    | 101 ++++++-----------
 .../camel/kit/generator/OpenCodeGeneratorTest.java | 123 ++++++++++++++++++++-
 .../camel/kit/service/DoctorServiceTest.java       |   2 +-
 5 files changed, 201 insertions(+), 84 deletions(-)

diff --git a/docs/modules/ROOT/pages/agents.adoc 
b/docs/modules/ROOT/pages/agents.adoc
index fdd8cc36..cc5ad3c6 100644
--- a/docs/modules/ROOT/pages/agents.adoc
+++ b/docs/modules/ROOT/pages/agents.adoc
@@ -216,8 +216,9 @@ The generated `opencode.json` uses OpenCode's permission 
model with rule-order p
 Wildcard fallbacks (`camel_*: "ask"`, `camel-knowledge_*: "ask"`, `citrus_*: 
"ask"` when enabled) ensure any unlisted tools require approval,
 while exact `"allow"` permissions for each MCP tool listed in the workflow 
manifest follow
 (e.g., `camel_camel_catalog_component_doc`, 
`camel-knowledge_camel_docs_search`, `citrus_citrus_catalog_actions`).
-By default, 38 tools are granted (33 from `camel`, 5 from `camel-knowledge`); 
with `--with-citrus-mcp`, 46 tools are granted
-(adding 8 from `citrus`). These tools are read-only operations (catalog 
lookups, documentation search, route validation,
+By default, 38 tools are explicitly granted exact `"allow"` permissions (33 
from `camel`, 5 from `camel-knowledge`);
+with `--with-citrus-mcp`, 46 tools receive exact grants (adding 8 from 
`citrus`).
+These tools are read-only operations (catalog lookups, documentation search, 
route validation,
 migration analysis, test actions) with no file writes or shell execution, 
making them safe to allow without user approval.
 
 OpenCode matches permission rules in declaration order. Wildcard rules must 
appear first so that exact grants can override them.
@@ -308,7 +309,7 @@ v1 mode-rule files.
 
 == Claude MCP approvals
 
-Fresh and regenerated Claude workspaces pre-approve only the explicit MCP 
tools listed in the workflow manifest. Other server tools remain visible and 
require Claude Code permission. Regenerate older workspaces to replace 
server-wide wildcard grants; review user-level settings separately. The 
generated Read and Maven command grants retain their existing behavior.
+Fresh and regenerated Claude workspaces pre-approve only the explicit MCP 
tools listed in the workflow manifest. Other server tools remain visible and 
require Claude Code permission. Regenerate older workspaces to replace 
overly-broad wildcard grants; review user-level settings separately. The 
generated Read and Maven command grants retain their existing behavior.
 
 == Generated path checks
 
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java
index 811355c0..824289e4 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java
@@ -7,6 +7,7 @@ import java.nio.file.Path;
 import java.nio.file.StandardCopyOption;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import org.apache.camel.kit.config.OpenCodeProjectConfig;
@@ -46,7 +47,8 @@ final class OpenCodeConfigMerger {
 
         // Collect user restrictions from all files before removing managed 
entries
         // Traverse from lowest to highest precedence, so the last (highest) 
restriction wins
-        ObjectNode userRestrictions = JSON.createObjectNode();
+        // Use LinkedHashMap to preserve insertion order (which will be user's 
original order)
+        java.util.LinkedHashMap<String, JsonNode> userRestrictionsMap = new 
java.util.LinkedHashMap<>();
         ObjectNode generatedPermission = (ObjectNode) 
generated.path("permission");
 
         for (ExistingConfiguration config : configurations) {
@@ -56,27 +58,57 @@ final class OpenCodeConfigMerger {
             }
             ObjectNode permission = (ObjectNode) permissionNode;
 
-            generatedPermission.fieldNames().forEachRemaining(key -> {
+            // Check if wildcards appear after exact grants (user override for 
all-tools approval)
+            java.util.List<String> existingKeys = new java.util.ArrayList<>();
+            permission.fieldNames().forEachRemaining(existingKeys::add);
+
+            // Iterate in user's original order to preserve it
+            for (String key : existingKeys) {
                 JsonNode generatedValue = generatedPermission.get(key);
-                JsonNode existingValue = permission.get(key);
+                if (generatedValue == null) {
+                    continue; // Not a managed key
+                }
 
+                JsonNode existingValue = permission.get(key);
                 if (existingValue != null) {
                     if (existingValue.isTextual() && 
generatedValue.isTextual()) {
                         String existingAction = existingValue.asText();
                         String generatedAction = generatedValue.asText();
-                        // Preserve if stricter, OR if it's a wildcard with 
same value
-                        // (user may have placed it last to override exact 
grants)
-                        if (isStricterThan(existingAction, generatedAction)
-                                || (key.endsWith("_*") && 
existingAction.equals(generatedAction))) {
+
+                        boolean preserveWildcard = false;
+                        if (key.endsWith("_*") && 
existingAction.equals(generatedAction)) {
+                            // Check if wildcard appears AFTER any exact 
grants from same namespace
+                            // (user override for all-tools approval)
+                            String namespace = key.substring(0, key.length() - 
1); // Remove '*'
+                            int wildcardPos = existingKeys.indexOf(key);
+                            // Look for exact grants BEFORE the wildcard 
position
+                            for (int i = 0; i < wildcardPos; i++) {
+                                if (existingKeys.get(i).startsWith(namespace)
+                                        && 
!existingKeys.get(i).endsWith("_*")) {
+                                    // Found an exact grant before the 
wildcard - this is a user override
+                                    preserveWildcard = true;
+                                    break;
+                                }
+                            }
+                        }
+
+                        // Preserve if stricter OR if wildcard placed after 
exact grants
+                        if (isStricterThan(existingAction, generatedAction) || 
preserveWildcard) {
                             // Keep replacing to retain the highest-precedence 
restriction
-                            userRestrictions.put(key, existingAction);
+                            userRestrictionsMap.put(key, 
JSON.getNodeFactory().textNode(existingAction));
                         }
                     } else if (existingValue.isObject()) {
                         // Preserve object-valued rules (e.g., {env: 
"ALLOW_CAMEL_ROUTES"})
-                        userRestrictions.set(key, existingValue);
+                        userRestrictionsMap.put(key, existingValue);
                     }
                 }
-            });
+            }
+        }
+
+        // Convert map to ObjectNode preserving order
+        ObjectNode userRestrictions = JSON.createObjectNode();
+        for (Map.Entry<String, JsonNode> entry : 
userRestrictionsMap.entrySet()) {
+            userRestrictions.set(entry.getKey(), entry.getValue());
         }
 
         List<PendingWrite> writes = new ArrayList<>();
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java
index d44f4a11..f7cddd1a 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java
@@ -993,87 +993,43 @@ public class DoctorService {
                 continue;
             }
 
-            // Check exact tool permissions (OpenCode format: <server>_<tool>)
-            List<OpenCodePermissionResolution> exactResolutions = 
openCodeTools(pattern).stream()
+            List<OpenCodePermissionResolution> resolutions = 
openCodeTools(pattern).stream()
                     .map(tool -> openCodePermissionAction(permission, tool))
                     .toList();
-
-            // Check wildcard fallback permission (pattern like camel_*)
-            OpenCodePermissionResolution wildcardResolution = 
openCodePermissionAction(permission, pattern);
-
-            // Test multiple unlisted tool names to verify comprehensive 
namespace fallback coverage
-            // Different patterns might match different subsets of unlisted 
tools
-            java.util.List<String> unlistedProbes = java.util.List.of(
-                    pattern.replace("*", "unlisted_probe_1"),
-                    pattern.replace("*", "another_unlisted_tool"),
-                    pattern.replace("*", "runtime_control_tool"),
-                    pattern.replace("*", "diagram_renderer"));
-            java.util.List<OpenCodePermissionResolution> unlistedResolutions = 
unlistedProbes.stream()
-                    .map(probe -> openCodePermissionAction(permission, probe))
-                    .toList();
-
-            // Exact tools should be "allow", wildcard fallback should be "ask"
             Set<Path> wrongSources = new LinkedHashSet<>();
-
-            // Separate concerns: deliberate restrictions vs missing 
permissions vs broken fallbacks
-            List<String> restrictedTools = new ArrayList<>();
-            List<String> missingTools = new ArrayList<>();
-            Set<Path> brokenFallbackSources = new LinkedHashSet<>();
-
-            // Check exact tools: collect those deliberately restricted to 
"ask" vs truly missing
-            for (int i = 0; i < exactResolutions.size(); i++) {
-                OpenCodePermissionResolution resolution = 
exactResolutions.get(i);
-                String toolName = new 
ArrayList<>(openCodeTools(pattern)).get(i);
-                if (!resolution.matched()) {
-                    missingTools.add(toolName);
-                } else if ("ask".equals(resolution.action())) {
-                    // User deliberately set this tool to "ask" - this is 
intentional
-                    restrictedTools.add(toolName);
+            for (OpenCodePermissionResolution resolution : resolutions) {
+                // Skip manifest tools with 'allow' - these are intentional 
grants
+                if (resolution.matched() && !"ask".equals(resolution.action())
+                        && !"allow".equals(resolution.action())) {
+                    wrongSources.add(permissionSource(resolution.rule(), 
permissionSources, mcpFile));
                 }
-                // Tools with "allow" or "deny" are fine, no issue
             }
-
-            // Check that all unlisted tools fall back to "ask"
-            for (int i = 0; i < unlistedResolutions.size(); i++) {
-                OpenCodePermissionResolution resolution = 
unlistedResolutions.get(i);
-                if (resolution.matched() && 
!"ask".equals(resolution.action())) {
-                    Path source = permissionSource(resolution.rule(), 
permissionSources, mcpFile);
-                    brokenFallbackSources.add(source);
-                    break; // One broken fallback is enough to report the issue
+            boolean missing = resolutions.stream().anyMatch(resolution -> 
!resolution.matched());
+            if (wrongSources.isEmpty() && !missing) {
+                String overridingRule = 
unsafeOpenCodeNamespaceOverride(permission, pattern, openCodeTools(pattern));
+                if (overridingRule != null) {
+                    wrongSources.add(permissionSource(overridingRule, 
permissionSources, mcpFile));
                 }
             }
-
-            // Report issues
-            if (!brokenFallbackSources.isEmpty()) {
-                for (Path source : brokenFallbackSources) {
+            if (!wrongSources.isEmpty()) {
+                for (Path source : wrongSources) {
                     findings.add(DoctorFinding.fail("mcp", relativize(root, 
source),
                             "OpenCode permission namespace '" + pattern
-                                                                               
      + "' allows unlisted tools without approval",
-                            "Unlisted tools in this namespace will run in 
headless mode without prompts. "
-                                                                               
                                                    + "Add a namespace-wide 
'ask' fallback rule, or regenerate the OpenCode config."));
+                                                                               
      + "' must end with a namespace-wide 'ask' rule",
+                            "Add a final namespace-wide ask rule to retain MCP 
permission prompts, or regenerate the OpenCode config."));
                 }
                 valid = false;
-            }
-
-            if (!missingTools.isEmpty()) {
+            } else if (missing) {
                 if (server.path("autoApprove").isArray() || 
server.path("alwaysAllow").isArray()) {
                     findings.add(DoctorFinding.warn("mcp", relativize(root, 
mcpFile),
-                            "Legacy OpenCode config missing permissions for 
tools: "
-                                                                               
       + String.join(", ", missingTools),
-                            "Regenerate the OpenCode config to add explicit 
MCP permissions."));
+                            "Legacy OpenCode config has no supported 
permission for '" + pattern + "'",
+                            "Regenerate the OpenCode config to retain explicit 
MCP approval prompts."));
                 } else {
                     findings.add(DoctorFinding.fail("mcp", relativize(root, 
mcpFile),
-                            "OpenCode permissions missing for tools: " + 
String.join(", ", missingTools),
-                            "These tools will be auto-rejected in headless 
mode. "
-                                                                               
                           + "Add explicit permissions or regenerate the 
OpenCode config."));
-                    valid = false;
+                            "OpenCode permission '" + pattern + "' must be 
'ask'",
+                            "Restore the generated MCP permission prompts or 
regenerate the OpenCode config."));
                 }
-            }
-
-            if (!restrictedTools.isEmpty()) {
-                findings.add(DoctorFinding.info("mcp", relativize(root, 
mcpFile),
-                        "OpenCode tools require approval: " + String.join(", 
", restrictedTools),
-                        "These tools are deliberately restricted and will 
prompt for approval or be rejected in headless mode."));
+                valid = false;
             }
         }
         return valid;
@@ -1114,6 +1070,16 @@ public class DoctorService {
 
     /** Returns the overriding rule, {@code ""} when no namespace-wide ask 
rule exists, or {@code null} when safe. */
     private String unsafeOpenCodeNamespaceOverride(JsonNode permission, String 
managedPattern) {
+        return unsafeOpenCodeNamespaceOverride(permission, managedPattern, 
java.util.Collections.emptySet());
+    }
+
+    /**
+     * Returns the overriding rule, {@code ""} when no namespace-wide ask rule 
exists, or {@code null} when safe.
+     * Exempts manifest-listed tools from the override check.
+     */
+    private String unsafeOpenCodeNamespaceOverride(
+            JsonNode permission, String managedPattern,
+            java.util.Set<String> exemptTools) {
         if (permission == null || !permission.isObject()) {
             return "";
         }
@@ -1128,6 +1094,11 @@ public class DoctorService {
                 continue;
             }
 
+            // Exempt manifest-listed exact tools
+            if (exemptTools.contains(entry.getKey())) {
+                continue;
+            }
+
             if (openCodeGlobCoversPrefix(entry.getKey(), managedPrefix)) {
                 if ("ask".equals(resolution.action())) {
                     coveredByAsk = true;
diff --git 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java
 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java
index 8e687e87..2639ccd9 100644
--- 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java
+++ 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java
@@ -553,16 +553,47 @@ class OpenCodeGeneratorTest {
         Path configFile = tempDir.resolve("opencode.json");
         OpenCodeGenerator generator = new OpenCodeGenerator();
         generator.generate(createContext());
-        String current = Files.readString(configFile);
-        Files.writeString(configFile, current.replace(
-                "\"citrus_*\": \"allow\"",
-                "\"citrus_*\": \"allow\",\n    \"*\": \"deny\""));
+
+        // Build fixture structurally using JSON parsing
+        JsonNode config = readOpenCodeConfig(configFile);
+        com.fasterxml.jackson.databind.node.ObjectNode mutablePermission
+                = (com.fasterxml.jackson.databind.node.ObjectNode) 
config.path("permission");
+
+        // Insert user wildcard after citrus_*
+        // First, collect existing permission keys in order
+        java.util.List<String> keys = new java.util.ArrayList<>();
+        mutablePermission.fieldNames().forEachRemaining(keys::add);
+
+        // Rebuild permission object with "*": "deny" inserted after citrus_*
+        com.fasterxml.jackson.databind.node.ObjectNode newPermission = new 
ObjectMapper().createObjectNode();
+        for (String key : keys) {
+            newPermission.set(key, mutablePermission.get(key));
+            if ("citrus_*".equals(key)) {
+                newPermission.put("*", "deny");
+            }
+        }
+        ((com.fasterxml.jackson.databind.node.ObjectNode) 
config).set("permission", newPermission);
+
+        Files.writeString(configFile, new 
ObjectMapper().writerWithDefaultPrettyPrinter()
+                .writeValueAsString(config));
+
+        // Verify the fixture contains both keys
+        JsonNode fixture = readOpenCodeConfig(configFile);
+        assertTrue(fixture.path("permission").has("*"), "Fixture must contain 
user wildcard");
+        assertTrue(fixture.path("permission").has("camel_*"), "Fixture must 
contain camel wildcard");
 
         generator.generate(createContext());
         String reordered = Files.readString(configFile);
         generator.generate(createContext());
 
-        assertTrue(reordered.indexOf("\"*\"") < 
reordered.indexOf("\"camel_*\""), reordered);
+        // Verify order using string positions (both keys must exist)
+        assertTrue(reordered.contains("\"*\""), "Must contain user wildcard 
after generation");
+        assertTrue(reordered.contains("\"camel_*\""), "Must contain camel 
wildcard after generation");
+        int starPos = reordered.indexOf("\"*\"");
+        int camelStarPos = reordered.indexOf("\"camel_*\"");
+        assertTrue(starPos >= 0 && camelStarPos >= 0, "Both wildcards must be 
present");
+        assertTrue(starPos < camelStarPos, "User wildcard must come before 
camel wildcard");
+
         assertEquals(reordered, Files.readString(configFile));
         assertEquals("ask", 
readOpenCodeConfig(configFile).path("permission").path("camel_*").asText());
     }
@@ -1124,6 +1155,88 @@ class OpenCodeGeneratorTest {
                 "Non-restricted generated permission must be set to 'allow'");
     }
 
+    @Test
+    void regenerationWithEmptyHigherPrecedenceFile() throws Exception {
+        // Generate initial config with Citrus
+        new OpenCodeGenerator().generate(createContext("camel-kit", true));
+
+        // User creates an empty higher-precedence file
+        Path higherPrecedence = tempDir.resolve("opencode.jsonc");
+        Files.writeString(higherPrecedence, "{}");
+
+        // Regenerate with same options
+        new OpenCodeGenerator().generate(createContext("camel-kit", true));
+
+        // Verify headless lookups still work (wildcards before exact grants)
+        JsonNode higher = readOpenCodeConfig(higherPrecedence);
+        java.util.List<String> keys = new java.util.ArrayList<>();
+        higher.path("permission").fieldNames().forEachRemaining(keys::add);
+
+        // All wildcards should come before their exact grants
+        int camelWildcardPos = keys.indexOf("camel_*");
+        int camelExactPos = keys.indexOf("camel_camel_catalog_components");
+        assertTrue(camelWildcardPos < camelExactPos,
+                "camel_* wildcard must come before exact grants for headless 
mode");
+    }
+
+    @Test
+    void regenerationPreservesDeliberateTrailingWildcard() throws Exception {
+        // Generate initial config
+        new OpenCodeGenerator().generate(createContext("camel-kit", false));
+
+        // User deliberately puts wildcard AFTER exact grants for all-tools 
approval
+        Path higherPrecedence = tempDir.resolve("opencode.jsonc");
+        Files.writeString(higherPrecedence, """
+                {
+                  "permission": {
+                    "camel_camel_validate_route": "ask",
+                    "camel_camel_catalog_components": "ask",
+                    "camel_*": "ask"
+                  }
+                }
+                """);
+
+        // Regenerate with --force
+        new OpenCodeGenerator().generate(createContext("camel-kit", false));
+
+        // Verify wildcard is preserved at the end
+        JsonNode higher = readOpenCodeConfig(higherPrecedence);
+        java.util.List<String> keys = new java.util.ArrayList<>();
+        higher.path("permission").fieldNames().forEachRemaining(keys::add);
+
+        int camelWildcardPos = keys.indexOf("camel_*");
+        int camelExactPos = keys.indexOf("camel_camel_catalog_components");
+        assertTrue(camelWildcardPos > camelExactPos,
+                "Deliberately placed trailing wildcard must be preserved");
+    }
+
+    @Test
+    void regenerationPreservesObjectValuedPermissionRules() throws Exception {
+        // Generate initial config
+        new OpenCodeGenerator().generate(createContext("camel-kit", false));
+
+        // User creates a higher-precedence file with an object-valued "ask" 
rule
+        Path higherPrecedence = tempDir.resolve("opencode.jsonc");
+        Files.writeString(higherPrecedence, """
+                {
+                  "permission": {
+                    "camel_camel_validate_route": {"*": "ask"}
+                  }
+                }
+                """);
+
+        // Regenerate with --force (simulated by calling generate again)
+        new OpenCodeGenerator().generate(createContext("camel-kit", false));
+
+        // Verify object-valued rule is preserved and round-trips correctly
+        JsonNode higher = readOpenCodeConfig(higherPrecedence);
+        
assertTrue(higher.path("permission").path("camel_camel_validate_route").isObject(),
+                "Object-valued permission rule must be preserved");
+        assertEquals("ask",
+                
higher.path("permission").path("camel_camel_validate_route").path("*").asText(),
+                "Object-valued ask rule must round-trip correctly");
+    }
+
     @Test
     void shipWorkerDeniesServersFromAllProjectConfigLayers() throws Exception {
         InitContext ctx = createContext();
diff --git 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/DoctorServiceTest.java
 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/DoctorServiceTest.java
index 5bf4b401..83b705b6 100644
--- 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/DoctorServiceTest.java
+++ 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/DoctorServiceTest.java
@@ -553,7 +553,7 @@ class DoctorServiceTest {
                     "camel_*": "ask",
                     "camel-knowledge_*": "ask",
                     "citrus_*": "ask",
-                    "camel-knowledge_camel_docs_search": "allow"
+                    "camel-knowledge_future_tool": "allow"
                   },
                   "mcp": {
                     "camel": {"type": "local"},

Reply via email to