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 944730135c89e207ac7ea9275744671abe028bb7 Author: Luigi De Masi <[email protected]> AuthorDate: Wed Nov 25 20:03:00 2026 +0100 Fix #195: Recover BOM-only project versions from Maven evidence Resolve imported properties in the declaring module's parent chain. Check a module's effective POM and resolved dependency tree before recording a transitive core. Preserve that result across reinitialization when the project inputs still match. Document which catalog selections the pinned MCP runner can verify, including the default Quarkus limitation. Exercise the command and the documented evidence format through the CLI. Co-authored-by: OpenAI Codex <[email protected]> --- CHANGELOG.md | 6 +- docs/commands.md | 4 +- docs/modules/ROOT/pages/commands.adoc | 8 +- docs/modules/ROOT/pages/existing-project.adoc | 24 ++++ docs/modules/ROOT/pages/getting-started.adoc | 3 + docs/modules/ROOT/pages/mcp.adoc | 18 +++ docs/modules/ROOT/pages/migration.adoc | 2 + docs/security-model.md | 2 +- .../apache/camel/kit/command/TargetCommand.java | 29 ++++- .../camel/kit/config/DistributionConfig.java | 2 +- .../camel/kit/config/TargetCatalogEvidence.java | 6 +- .../apache/camel/kit/config/TargetPomCheck.java | 109 +++++++++++++++-- .../camel/kit/config/TargetRuntimeProfile.java | 34 ++++-- .../org/apache/camel/kit/service/InitService.java | 98 ++++++++++++--- .../guides/existing-project-discovery.md | 4 +- .../camel-brainstorm/guides/version-selection.md | 23 ++++ .../main/resources/skills/camel-execute/SKILL.md | 10 +- .../main/resources/skills/camel-implement/SKILL.md | 7 +- .../camel-implement/guides/maven-dependencies.md | 3 +- .../main/resources/skills/camel-migrate/SKILL.md | 4 +- .../src/main/resources/skills/camel-plan/SKILL.md | 13 +- .../main/resources/skills/camel-validate/SKILL.md | 11 +- .../src/main/resources/skills/shared/mcp-setup.md | 57 +++++++-- .../camel/kit/command/TargetCommandTest.java | 132 +++++++++++++++++++++ .../camel/kit/config/DistributionConfigTest.java | 8 ++ .../camel/kit/config/TargetRuntimeProfileTest.java | 112 +++++++++++------ .../kit/generator/ResourceConsistencyTest.java | 3 +- .../apache/camel/kit/service/InitServiceTest.java | 33 +++++- .../apache/camel/kit/graph/ProjectDiscovery.java | 37 ++++-- .../apache/camel/kit/graph/parser/PomParser.java | 78 +++++++++--- .../camel/kit/graph/ProjectDiscoveryTest.java | 6 +- .../camel/kit/graph/parser/PomParserTest.java | 36 ++++++ 32 files changed, 765 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3586175a..d650e66a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Migration retains the source versions and uses a separate target profile for Maven generation and catalog - verification. A missing or mismatched runtime catalog produces an incomplete check (#195). + verification. The new `target` command prints that profile, renders the application POM, and checks Maven and + catalog evidence. Spring Boot templates import the application starter, Camel core and framework BOMs. Existing + projects resolve inherited BOM properties per module and can recover a transitive core from Maven's dependency tree. + With the shipped MCP 4.22.1 runner, catalog-dependent design cannot complete for Spring Boot 4.18.4 or either + supported Quarkus row, including the default platform 3.33.3.2. These checks report INCOMPLETE (#195). - Graph files now use format 1.1. CLI output such as `graph stats` reports namespaced types (for example `mule:flow`). Existing 1.0 graphs and legacy filters remain readable. diff --git a/docs/commands.md b/docs/commands.md index 86c7379e..3956012b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -267,8 +267,8 @@ For Pi, Camel-Kit generates `AGENTS.md`, project skills under `.pi/skills/`, pro `camel-kit target` prints the current application profile as JSON. Add `--migration` to use the destination selected in `target.*` in the workspace configuration. Use `--project-dir` to select the workspace. `--pom-template` prints the Maven template with runtime coordinates filled in. To check a generated -application, supply `--check-effective-pom <xml>` or `--check-catalog <json>` with the workspace-relative -evidence file. Incomplete checks exit with status 1. The Camel JBang plugin exposes the same options under +application, supply `--check-effective-pom <xml>`, `--check-catalog <json>`, or both. For a transitive core +dependency, add `--dependency-tree <json>` from the same Maven module to the effective-POM check. Keep all evidence inside the workspace. Incomplete checks exit with status 1. The Camel JBang plugin exposes the same options under `camel kit target`. See [target selection](modules/ROOT/pages/migration.adoc#target-profile). ### camel-kit doctor diff --git a/docs/modules/ROOT/pages/commands.adoc b/docs/modules/ROOT/pages/commands.adoc index e3883433..27b23f9e 100644 --- a/docs/modules/ROOT/pages/commands.adoc +++ b/docs/modules/ROOT/pages/commands.adoc @@ -93,12 +93,16 @@ Print the active runtime profile as JSON. Add `--migration` for the destination xref:migration.adoc#target-profile[the migration workflow]. An incomplete selection returns exit code 1. ---- -camel-kit target [--project-dir <path>] [--migration] [--pom-template | --check-effective-pom <xml> | --check-catalog <json>] +camel-kit target [--project-dir <path>] [--migration] [--pom-template] +camel-kit target [--project-dir <path>] [--migration] [--check-effective-pom <xml> [--dependency-tree <json>]] [--check-catalog <json>] ---- `--pom-template` prints a runtime-specific Maven template ready for the four project identity fields. `--check-effective-pom` reads a leaf module's `help:effective-pom` XML and checks the managed core, -framework, starter or extension versions and the build plugin. Both checks accept workspace-relative paths. +framework, starter or extension versions and the build plugin. For an existing application, add a JSON +`--dependency-tree` from the same module to check its resolved transitive Camel core. See +xref:existing-project.adoc#resolved-maven-core[recovering a BOM-only project's versions]. +The two checks can run together. Evidence files must be inside the workspace. `--check-catalog` reads a JSON evidence file. It contains the captured profile under `profile` and the two MCP calls under `list` and `maven`. Each call contains its tool `name`, actual `arguments` and original `result`. A successful check prints the profile. Stale or mismatched evidence exits 1 with diff --git a/docs/modules/ROOT/pages/existing-project.adoc b/docs/modules/ROOT/pages/existing-project.adoc index f0c09ac5..fbdc639f 100644 --- a/docs/modules/ROOT/pages/existing-project.adoc +++ b/docs/modules/ROOT/pages/existing-project.adoc @@ -167,6 +167,30 @@ Two further keys appear only when needed: * `project.unsupportedCombination` - the detected runtime or DSL is outside the supported scope (for example a Karaf runtime, or no YAML routes). The workflow stops instead of guessing; Camel Kit never converts the DSL. +[[resolved-maven-core]] +=== Resolve a BOM-only project's Camel version + +A starter or platform BOM can have a different version from Camel core. If init finds the BOM but cannot +determine the core, it sets `project.needsResolvedCore=true`. Use the application's Maven settings and +profiles. From the workspace root, run the following for each Camel application module, replacing `app/pom.xml` +with its POM. For a vendor Spring Boot BOM, first set `project.catalogBom` to the published catalog provider +GAV from its starter release metadata. Use fresh output paths for each module. The dependency plugin supports JSON from version 3.7.0. + +[source,shell] +---- +./mvnw -f app/pom.xml help:effective-pom -Doutput="$PWD/app/target/model.xml" +./mvnw -f app/pom.xml org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree -DoutputType=json -Dincludes=org.apache.camel:camel-core-engine -DoutputFile="$PWD/app/target/tree.json" +camel-kit target --check-effective-pom app/target/model.xml --dependency-tree app/target/tree.json +---- + +The command checks that the dependency tree and effective model identify the same module. A successful check +prints the profile without writing configuration. When the affected modules agree, copy `camelVersion` to +`project.camelVersion` in `.camel-kit/config.properties`. For Quarkus copy `runtimeCatalogVersion` to +`project.catalogVersion`; for Spring Boot copy `springBootVersion` to `project.springBootVersion`. +Keep conflicting versions unresolved. Re-run the checks if the effective build settings or profiles change. +Init preserves the recovered core across reinitialization with unchanged POMs and repositories. Changes to +the selected platform invalidate its recorded catalog coordinates. + === 3. Add a New Capability Start the workflow: diff --git a/docs/modules/ROOT/pages/getting-started.adoc b/docs/modules/ROOT/pages/getting-started.adoc index 7e288e35..6739c220 100644 --- a/docs/modules/ROOT/pages/getting-started.adoc +++ b/docs/modules/ROOT/pages/getting-started.adoc @@ -365,6 +365,9 @@ in Camel Kit. Three layers override them, the later winning: The workspace records the effective `camel.catalog.repos` used by the Camel MCP launcher. Configure any vendor repository in the Maven settings used for the destination build and in the catalog repository list at init. Keep repository credentials in Maven settings. +Before choosing a runtime, check the xref:mcp.adoc#binding[catalog compatibility table]. With the shipped +4.22.1 runner the default Quarkus target cannot complete a design requiring verified catalog artifacts. + `camel-kit target` shows the selected application BOM, core version, repositories and catalog arguments. For a migration, `camel-kit target --migration` reads the separate destination selection. See xref:migration.adoc#target-profile[Selecting a migration target]. diff --git a/docs/modules/ROOT/pages/mcp.adoc b/docs/modules/ROOT/pages/mcp.adoc index b779923a..c1072d56 100644 --- a/docs/modules/ROOT/pages/mcp.adoc +++ b/docs/modules/ROOT/pages/mcp.adoc @@ -95,6 +95,24 @@ The current defaults are Camel {camel-version} for Camel Main and Spring Boot, w on the Quarkus platform {quarkus-platform-version}; the catalog server artifact follows the Camel Main stream. [[camel-tools]] +With the shipped Camel MCP 4.22.1 runner, required catalog checks have the following results for the +supported community targets. The runner can return the selected starter or extension alongside its bundled core. + +[cols="1,1,1,2",options="header"] +|=== +|Runtime |Requested core |Returned core |Required catalog check +|Main |4.22.1 or 4.18.4 |Matches requested core |Pass +|Spring Boot |4.22.1 |4.22.1 |Pass +|Spring Boot |4.18.4 |4.22.1 |Incomplete +|Quarkus |4.18.3 |4.22.1 |Incomplete (default platform 3.33.3.2) +|Quarkus |4.14.7 |4.22.1 |Incomplete (platform 3.27.3) +|=== + +The check applies to greenfield designs, existing applications and migrations. On an affected row the workflow +cannot complete a design that requires verified catalog artifacts. The selected application version is preserved. +For a different runner or platform, verify the actual responses. See the +xref:existing-project.adoc#catalog-limitation[runtime catalog limitation]. + == The Camel catalog server The workflow allowlist covers the read-only and generation helpers the skills use; runtime mutation and control diff --git a/docs/modules/ROOT/pages/migration.adoc b/docs/modules/ROOT/pages/migration.adoc index 9d22a077..01cb0ecd 100644 --- a/docs/modules/ROOT/pages/migration.adoc +++ b/docs/modules/ROOT/pages/migration.adoc @@ -62,6 +62,8 @@ target.springBootVersion=3.5.11 For Quarkus, set `target.applicationBom` to the full Camel platform BOM and `target.catalogVersion` to its managed `org.apache.camel.quarkus:camel-quarkus-catalog` version. The MCP lookup takes the platform BOM GAV. Main needs only `target.runtime=main` and the core version. +Check xref:mcp.adoc#binding[catalog availability] before selecting the destination. With the pinned runner, +the default Quarkus platform 3.33.3.2 cannot complete a design that requires verified component coordinates. Run `camel-kit target --migration` to inspect the profile. For a new Maven application, `camel-kit target --migration --pom-template` prints the POM with the selected imports and plugin version. diff --git a/docs/security-model.md b/docs/security-model.md index 6487a197..22d756bf 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -93,7 +93,7 @@ metadata; Kit configures it for each harness, and it also serves MCP clients tha | **Other local accounts on the same host** | Weaker adversary | Camel-Kit must not widen what they can read *(documented — Apache Camel Security Model, "A second, weaker adversary")*. | | **Network peers** between the CLI and its HTTPS origins | Untrusted; TLS assumed | §4.5. | -- `target` reads workspace configuration and bounded catalog evidence as data. It prints the selected coordinates +- `target` reads workspace configuration, bounded Maven models and dependency trees, and bounded catalog evidence as data. It prints the selected coordinates or a Maven template. It does not run Maven, fetch coordinates, or change the MCP launcher's repository policy. Required catalog checks compare the actual request parameters, core version and runtime artifact against the selected profile. Recorded evidence depends on the harness faithfully capturing those calls. diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/TargetCommand.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/TargetCommand.java index fb2e9b9d..1b241bf5 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/TargetCommand.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/TargetCommand.java @@ -2,6 +2,7 @@ package org.apache.camel.kit.command; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Properties; @@ -38,6 +39,10 @@ public class TargetCommand extends HelpAwareCommand { description = "Check the destination module's Maven help:effective-pom output") Path effectivePom; + @Option(parser = KitOptionParser.class, name = "dependency-tree", converter = PathConverter.class, + description = "Maven dependency:tree JSON for the same module as --check-effective-pom") + Path dependencyTree; + @Override public Integer call() { Path config = projectDir.resolve(".camel-kit/config.properties"); @@ -46,13 +51,33 @@ public class TargetCommand extends HelpAwareCommand { Properties properties = new Properties(); try (var input = Files.newInputStream(config)) { properties.load(input); + } catch (NoSuchFileException e) { + throw new IOException( + "Missing " + config + ". Run init here or use --project-dir for an initialized workspace."); + } + if (dependencyTree != null && effectivePom == null) { + throw new IllegalArgumentException("--dependency-tree requires --check-effective-pom"); } - TargetRuntimeProfile profile = TargetRuntimeProfile.resolve(properties, migration); if ((catalogEvidence != null || effectivePom != null) && pomTemplate) { throw new IllegalArgumentException("Choose template output or target checks"); } + boolean existing = !migration && "existing".equals(properties.getProperty("project.type")); + TargetPomCheck model = null; if (effectivePom != null) { - TargetPomCheck.check(profile, read(effectivePom, 16 * 1024 * 1024)); + model = new TargetPomCheck( + read(effectivePom, 16 * 1024 * 1024), + dependencyTree == null ? null : read(dependencyTree, 16 * 1024 * 1024)); + if (existing) { + model.completeExistingProfile(properties); + } + } else if (existing && "true".equals(properties.getProperty("project.needsResolvedCore")) + && !properties.containsKey("project.camelVersion")) { + throw new IOException( + "Resolve project.camelVersion with --check-effective-pom and --dependency-tree for each Camel module"); + } + TargetRuntimeProfile profile = TargetRuntimeProfile.resolve(properties, migration); + if (model != null) { + model.check(profile, existing); } if (catalogEvidence != null) { TargetCatalogEvidence.check(profile, read(catalogEvidence, 65536)); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/DistributionConfig.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/DistributionConfig.java index f7b1e598..80a20be4 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/DistributionConfig.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/DistributionConfig.java @@ -73,7 +73,7 @@ public class DistributionConfig { this.camelMcpRepos = configured(props, bundled, "camel.mcp.repos"); this.knowledgeMcpRepos = configured(props, bundled, "knowledge.mcp.repos"); this.citrusMcpRepos = configured(props, bundled, "citrus.mcp.repos"); - this.camelCatalogRepos = configured(props, bundled, "camel.catalog.repos"); + this.camelCatalogRepos = configured(props, bundled, "camel.catalog.repos").strip().replaceAll("\\s*,\\s*", ","); this.piVersion = configured(props, bundled, "pi.version"); requiredProperty(bundled, "pi.supported"); this.piSupported = props.getProperty("pi.supported", this.piVersion); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetCatalogEvidence.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetCatalogEvidence.java index b504a01b..7a372a00 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetCatalogEvidence.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetCatalogEvidence.java @@ -19,6 +19,7 @@ public final class TargetCatalogEvidence { /** Check the captured outputs of the two version-sensitive MCP calls made with this profile. */ public static void check(TargetRuntimeProfile profile, byte[] bytes) throws IOException { + String expectedVersion = profile.requiredCatalogVersion(); JsonNode evidence = JSON.readTree(bytes); if (evidence == null || !JSON.valueToTree(profile).equals(evidence.path("profile"))) { throw new IOException("Catalog evidence belongs to a different or missing target profile"); @@ -45,10 +46,9 @@ public final class TargetCatalogEvidence { }; if (!timer || !"timer".equals(component.path("name").textValue()) || !artifact.equals(component.path("groupId").asText() + ":" + component.path("artifactId").asText()) - || profile.runtimeCatalogVersion() == null - || !profile.runtimeCatalogVersion().equals(component.path("version").textValue())) { + || !expectedVersion.equals(component.path("version").textValue())) { throw new IOException( - "Expected the timer component from " + artifact + ":" + profile.runtimeCatalogVersion()); + "Expected the timer component from " + artifact + ":" + expectedVersion); } } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetPomCheck.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetPomCheck.java index 13eb694e..cf6c4bff 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetPomCheck.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetPomCheck.java @@ -2,9 +2,15 @@ package org.apache.camel.kit.config; import java.io.ByteArrayInputStream; import java.io.IOException; +import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map; +import java.util.Properties; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; @@ -12,25 +18,64 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** Checks Maven's effective dependency management without executing the generated project. */ public final class TargetPomCheck { - private TargetPomCheck() { - } + private final Model model; + private final Map<String, String> managed = new HashMap<>(); + private final String treeCore; - public static void check(TargetRuntimeProfile target, byte[] effectivePom) throws IOException { - Model model; + public TargetPomCheck(byte[] effectivePom, byte[] dependencyTree) throws IOException { try { model = new MavenXpp3Reader().read(new ByteArrayInputStream(effectivePom)); } catch (XmlPullParserException e) { throw new IOException("Expected a single module's effective POM", e); } - if (target.applicationBom() == null || model.getDependencyManagement() == null) { + if (model.getDependencyManagement() == null) { throw new IOException("Expected a Maven destination with dependency management"); } - Map<String, String> managed = new HashMap<>(); for (Dependency dep : model.getDependencyManagement().getDependencies()) { managed.put(dep.getManagementKey(), dep.getVersion()); } - requireVersion("org.apache.camel:camel-core-engine", target.camelVersion(), - managed.get("org.apache.camel:camel-core-engine:jar")); + treeCore = dependencyTree == null ? null : resolvedCore(model, dependencyTree); + if (dependencyTree != null && treeCore == null) { + throw new IOException( + "No runtime org.apache.camel:camel-core-engine in the supplied Maven dependency tree"); + } + } + + public void completeExistingProfile(Properties config) throws IOException { + if ("true".equals(config.getProperty("project.needsResolvedCore"))) { + String core = treeCore != null ? treeCore : managed.get("org.apache.camel:camel-core-engine:jar"); + if (core == null) { + throw new IOException("Camel core is transitive. Supply --dependency-tree from the same Maven module"); + } + config.putIfAbsent("project.camelVersion", core); + } + if ("quarkus".equals(config.getProperty("project.runtime"))) { + String catalog = managed.get("org.apache.camel.quarkus:camel-quarkus-catalog:jar"); + if (catalog != null) { + config.putIfAbsent("project.catalogVersion", catalog); + } + } else if ("spring-boot".equals(config.getProperty("project.runtime"))) { + String boot = managed.get("org.springframework.boot:spring-boot:jar"); + if (boot != null) { + config.putIfAbsent("project.springBootVersion", boot); + } + } + } + + public void check(TargetRuntimeProfile target, boolean existing) throws IOException { + if (target.applicationBom() == null) { + throw new IOException("Expected a Maven destination with an application BOM"); + } + if (treeCore != null) { + requireVersion("resolved org.apache.camel:camel-core-engine", target.camelVersion(), treeCore); + } + if (!existing || treeCore == null) { + String core = managed.get("org.apache.camel:camel-core-engine:jar"); + if (existing && core == null) { + throw new IOException("Camel core is transitive. Supply --dependency-tree from the same Maven module"); + } + requireVersion("org.apache.camel:camel-core-engine", target.camelVersion(), core); + } String plugin; String pluginVersion; if ("spring-boot".equals(target.runtime())) { @@ -44,18 +89,60 @@ public final class TargetPomCheck { String[] bom = target.applicationBom().split(":"); plugin = bom[0] + ":quarkus-maven-plugin"; pluginVersion = bom[2]; - requireVersion("Camel Quarkus catalog", target.runtimeCatalogVersion(), + requireVersion("Camel Quarkus catalog", target.requiredCatalogVersion(), managed.get("org.apache.camel.quarkus:camel-quarkus-catalog:jar")); } var configured = model.getBuild() == null ? null : model.getBuild().getPluginsAsMap().get(plugin); - requireVersion(plugin, pluginVersion, configured == null ? null : configured.getVersion()); + if (!existing || configured != null) { + requireVersion(plugin, pluginVersion, configured == null ? null : configured.getVersion()); + } for (Dependency dep : model.getDependencies()) { if ("org.apache.camel".equals(dep.getGroupId()) || "org.apache.camel.springboot".equals(dep.getGroupId()) || "org.apache.camel.quarkus".equals(dep.getGroupId()) || "org.springframework.boot".equals(dep.getGroupId())) { - requireVersion(dep.getManagementKey(), managed.get(dep.getManagementKey()), dep.getVersion()); + String version = managed.get(dep.getManagementKey()); + if (!existing || version != null) { + requireVersion(dep.getManagementKey(), version, dep.getVersion()); + } + } + } + } + + public static void check(TargetRuntimeProfile target, byte[] effectivePom) throws IOException { + new TargetPomCheck(effectivePom, null).check(target, false); + } + + private static String resolvedCore(Model model, byte[] tree) throws IOException { + JsonNode root = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(tree); + if (root == null || !root.isObject()) { + throw new IOException("Expected dependency:tree JSON for the destination module"); + } + requireVersion("dependency tree groupId", model.getGroupId(), root.path("groupId").textValue()); + requireVersion("dependency tree artifactId", model.getArtifactId(), root.path("artifactId").textValue()); + requireVersion("dependency tree version", model.getVersion(), root.path("version").textValue()); + var nodes = new ArrayDeque<JsonNode>(); + nodes.add(root); + String version = null; + while (!nodes.isEmpty()) { + JsonNode node = nodes.removeLast(); + if ("org.apache.camel".equals(node.path("groupId").textValue()) + && "camel-core-engine".equals(node.path("artifactId").textValue()) + && "jar".equals(node.path("type").textValue()) && node.path("classifier").asText().isEmpty() + && ("compile".equals(node.path("scope").textValue()) + || "runtime".equals(node.path("scope").textValue()))) { + String found = node.path("version").textValue(); + if (found == null || (version != null && !version.equals(found))) { + throw new IOException("Missing or conflicting resolved camel-core-engine versions"); + } + version = found; + } + if (node.has("children") && !node.path("children").isArray()) { + throw new IOException("Invalid children in Maven dependency tree"); } + node.path("children").forEach(nodes::add); } + return version; } private static void requireVersion(String artifact, String expected, String actual) throws IOException { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetRuntimeProfile.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetRuntimeProfile.java index 21a61970..eb9df651 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetRuntimeProfile.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/config/TargetRuntimeProfile.java @@ -3,6 +3,7 @@ package org.apache.camel.kit.config; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.util.Arrays; import java.util.List; import java.util.Properties; @@ -57,8 +58,21 @@ public record TargetRuntimeProfile( } else { throw new IllegalArgumentException("Select " + prefix + "runtime (main, spring-boot or quarkus)"); } + String catalogVersion = binding.substring(binding.lastIndexOf(':') + 1); + if ("quarkus".equals(runtime)) { + catalogVersion = config.getProperty(prefix + "catalogVersion"); + if (migration || catalogVersion != null) { + catalogVersion = scalar(catalogVersion, prefix + "catalogVersion"); + } + } + return new TargetRuntimeProfile( + runtime, core, bom, boot, repositories(config), catalogVersion, + new CatalogRequest(runtime, core, binding)); + } + + private static List<String> repositories(Properties config) { String repos = config.getProperty("camel.catalog.repos", DistributionConfig.loadBundled().camelCatalogRepos()); - List<String> repositories = List.of(repos.split(",", -1)); + List<String> repositories = Arrays.stream(repos.split(",", -1)).map(String::strip).toList(); // Profiles are copied into design and verification reports. Credentials belong in Maven settings. for (String repository : repositories) { String url = repository.replaceFirst("^[A-Za-z0-9_.-]+=", ""); @@ -73,16 +87,16 @@ public record TargetRuntimeProfile( } throw new IllegalArgumentException("Use credential-free repository URLs in camel.catalog.repos"); } - String catalogVersion = binding.substring(binding.lastIndexOf(':') + 1); - if ("quarkus".equals(runtime)) { - catalogVersion = config.getProperty(prefix + "catalogVersion"); - if (migration || catalogVersion != null) { - catalogVersion = scalar(catalogVersion, prefix + "catalogVersion"); - } + return repositories; + } + + public String requiredCatalogVersion() { + if (runtimeCatalogVersion == null) { + throw new IllegalArgumentException( + "Set project.catalogVersion to the camel-quarkus-catalog version managed by " + + applicationBom); } - return new TargetRuntimeProfile( - runtime, core, bom, boot, repositories, catalogVersion, - new CatalogRequest(runtime, core, binding)); + return runtimeCatalogVersion; } private static String matchingBinding(String provided, String expected) { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java index 97fbc934..bb69c818 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java @@ -2,18 +2,22 @@ package org.apache.camel.kit.service; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Path; +import java.security.MessageDigest; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeMap; @@ -37,6 +41,7 @@ import org.apache.camel.kit.graph.ParserDiagnostic; import org.apache.camel.kit.graph.ProjectGraph; import org.apache.camel.kit.graph.RuntimeDetector; import org.apache.camel.kit.graph.model.NodeType; +import org.apache.camel.kit.graph.parser.GraphParser; import org.apache.camel.kit.util.ConfinedPaths; import org.apache.camel.kit.util.TemplateUtils; import org.apache.camel.kit.workflow.MigrationParsers; @@ -168,10 +173,12 @@ public class InitService { targetDir, camelKitDir, docsDir, createdPaths); progress.finishTask(); + Properties previous; try { progress.startTask("\uD83D\uDCDD", "Writing configuration"); files.beginCatalogTracking(); - createConfigFile(camelKitDir, request.projectName(), request.agentName(), agent, request, createdPaths, + previous = createConfigFile(camelKitDir, request.projectName(), request.agentName(), agent, request, + createdPaths, isExistingProject); createConstitution(docsDir, request, files, createdPaths); copyAdditionalTemplates(camelKitDir.resolve("templates"), createdPaths); @@ -200,7 +207,7 @@ public class InitService { } progress.startTask("\uD83D\uDD0D", "Building project graph"); - InitGraphSummary graph = buildProjectGraph(targetDir, camelKitDir, request, warnings, createdPaths); + InitGraphSummary graph = buildProjectGraph(targetDir, camelKitDir, request, warnings, createdPaths, previous); progress.finishTask(); int citrusSchemaCount = 0; @@ -267,7 +274,7 @@ public class InitService { createdPaths.add(path); } - private void createConfigFile( + private Properties createConfigFile( Path dir, String name, String agentName, @@ -284,9 +291,12 @@ public class InitService { config.load(in); } } + Properties previous = (Properties) config.clone(); // Discovery must not retain constraints from an earlier scan when declarations disappear or conflict. for (String key : List.of("project.runtime", "project.camelVersion", "project.detectedCamelVersion", - "project.applicationBom", "project.catalogBom", "project.catalogVersion", "project.platformBomVersion", + "project.needsResolvedCore", "project.mavenInputs", "project.applicationBom", "project.catalogBom", + "project.catalogVersion", + "project.platformBomVersion", "project.detectedPlatformBomVersion", "project.springBootVersion", "project.primaryDsl", "project.dslTypes", "project.hasTests", "project.baselineTestStatus", @@ -325,6 +335,7 @@ public class InitService { config.store(out, "Camel-Kit Project Configuration"); AtomicFileWriter.write(configFile, out.toByteArray()); createdPaths.add(configFile); + return previous; } private void cacheForageCatalog(Path camelKitDir, InitRequest request, List<InitWarning> warnings) @@ -431,7 +442,7 @@ public class InitService { Path camelKitDir, InitRequest request, List<InitWarning> warnings, - List<Path> createdPaths) + List<Path> createdPaths, Properties previous) throws Exception { Path graphFile = camelKitDir.resolve("project-graph.json"); try { @@ -454,8 +465,7 @@ public class InitService { createdPaths.add(graphFile); String detectedProjectType = detectProjectType(projectGraph, request, warnings); String detectedRuntime - = updateConfigWithRuntime(camelKitDir, projectGraph, request.distribution(), request, warnings, - targetDir); + = updateConfigWithRuntime(camelKitDir, result, request, warnings, targetDir, previous); InitGraphSummary graph = new InitGraphSummary( graphFile, projectGraph.nodeCount(), @@ -537,11 +547,8 @@ public class InitService { private String updateConfigWithRuntime( Path dir, - ProjectGraph graph, - DistributionConfig distribution, - InitRequest request, - List<InitWarning> warnings, - Path projectRoot) + GraphBuildResult result, InitRequest request, List<InitWarning> warnings, + Path projectRoot, Properties previous) throws Exception { Path configFile = dir.resolve("config.properties"); Properties config = new Properties(); @@ -552,6 +559,8 @@ public class InitService { } } + ProjectGraph graph = result.graph(); + DistributionConfig distribution = request.distribution(); // Use ProjectDiscovery for comprehensive metadata org.apache.camel.kit.graph.ProjectDiscovery.DiscoveryResult discovery = org.apache.camel.kit.graph.ProjectDiscovery.discover(graph); @@ -575,8 +584,7 @@ public class InitService { // ERROR: Cannot proceed with undetectable version on existing project throw new IllegalStateException( "Cannot detect Camel version from existing project. " - + "Add a camel.version property to pom.xml, or specify the version explicitly with " - + "-p project.camelVersion=<version>. " + + "Add a verified camel.version property to pom.xml. " + "Refusing to guess a version for an existing project."); } // With conflicting evidence neither value is locked; the gap below tells the user what to resolve. @@ -593,6 +601,27 @@ public class InitService { config.setProperty("project.springBootVersion", discovery.springBootVersion()); } + String inputs = mavenInputs(projectRoot, result); + config.setProperty("project.mavenInputs", inputs); + boolean sameModel = inputs.equals(previous.getProperty("project.mavenInputs")) + && config.getProperty("project.applicationBom") != null && !discovery.hasConflict() + && Objects.equals(runtime, previous.getProperty("project.runtime")) + && Objects.equals(config.getProperty("project.applicationBom"), + previous.getProperty("project.applicationBom")) + && Objects.equals(config.getProperty("camel.catalog.repos"), + previous.getProperty("camel.catalog.repos")); + if (sameModel && discovery.camelVersion() == null) { + copyProperty(previous, config, "project.camelVersion"); + } + + if (discovery.camelVersion() == null && !discovery.hasConflict() + && config.containsKey("project.applicationBom")) { + config.setProperty("project.needsResolvedCore", "true"); + } + if (sameModel && config.getProperty("project.springBootVersion") == null && "spring-boot".equals(runtime)) { + copyProperty(previous, config, "project.springBootVersion"); + } + if (!discovery.dslTypes().isEmpty()) { config.setProperty("project.primaryDsl", discovery.primaryDsl()); // Record all DSL types for compatibility checks @@ -632,7 +661,10 @@ public class InitService { } // Gaps the graph could not fill (e.g. routes defined in unsupported layouts): workflow must inspect source - List<String> gaps = discovery.coverageGaps(); + List<String> gaps = new ArrayList<>(discovery.coverageGaps()); + if (discovery.camelVersion() == null && config.containsKey("project.camelVersion")) { + gaps.remove(org.apache.camel.kit.graph.ProjectDiscovery.UNRESOLVED_PLATFORM_CORE); + } if (!gaps.isEmpty()) { config.setProperty("project.discoveryGaps", String.join(" | ", gaps)); gaps.forEach(gap -> reportWarning(request, warnings, gap)); @@ -662,12 +694,13 @@ public class InitService { } // Flag unsupported versions - if (discovery.isUnsupportedVersion()) { + if (config.getProperty("project.camelVersion", "").startsWith("3.")) { config.setProperty("project.unsupportedVersion", "true"); config.setProperty("project.unsupportedReason", "Camel 3.x is not supported. Please upgrade to Camel 4.x."); reportWarning(request, warnings, - "Camel " + discovery.camelVersion() + " is not supported. Please upgrade to Camel 4.x " + "Camel " + config.getProperty("project.camelVersion") + + " is not supported. Please upgrade to Camel 4.x " + "before adding features."); } @@ -686,12 +719,43 @@ public class InitService { writeVersionConfig(config, distribution, runtime); } + if (runtime != null && config.getProperty("project.camelVersion") != null + && config.getProperty("project.platformBomVersion") != null + && List.of("project.type", "project.runtime", "project.camelVersion", "project.applicationBom", + "project.platformBomVersion", "project.springBootVersion", "camel.catalog.repos").stream() + .allMatch(key -> Objects.equals(config.getProperty(key), previous.getProperty(key)))) { + copyProperty(previous, config, "project.catalogBom"); + copyProperty(previous, config, "project.catalogVersion"); + } var out = new ByteArrayOutputStream(); config.store(out, "Camel-Kit Project Configuration"); AtomicFileWriter.write(configFile, out.toByteArray()); return runtime == null ? "" : runtime; } + private static void copyProperty(Properties from, Properties to, String key) { + if (from.containsKey(key)) { + to.setProperty(key, from.getProperty(key)); + } + } + + private static String mavenInputs(Path root, GraphBuildResult result) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + MessageDigest content = MessageDigest.getInstance("SHA-256"); + for (ParserDiagnostic parser : result.diagnostics()) { + if ("PomParser".equals(parser.parserName())) { + for (String file : parser.scannedFiles().stream().sorted().toList()) { + Path pom = root.resolve(file); + ConfinedPaths.requirePath(root, pom); + digest.update(file.getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + digest.update(content.digest(GraphParser.readSource(pom))); + } + } + } + return HexFormat.of().formatHex(digest.digest()); + } + private void writeVersionConfig(Properties config, DistributionConfig distribution, String runtime) { String normalizedRuntime = normalizeRuntime(runtime); config.setProperty("project.runtime", normalizedRuntime); diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/existing-project-discovery.md b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/existing-project-discovery.md index d6a12b59..fc15be0c 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/existing-project-discovery.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/existing-project-discovery.md @@ -47,7 +47,9 @@ if project.unsupportedCombination is set: if project.discoveryGaps is set: INSPECT the source for each listed gap, then ask the user only about what is still unclear. -if project.runtime or project.camelVersion is missing: +if project.needsResolvedCore and the core version is missing: + Follow "Recover the core version from Maven" in guides/version-selection.md for every affected module. +if project.runtime or project.camelVersion is still missing: STOP: discovery found conflicting evidence or could not read the project. Report the matching project.discoveryGaps entry and ask the user to resolve it. Do not pick one value and do not fall back to the shipped version tables. diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/version-selection.md b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/version-selection.md index 56564167..348c8592 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/version-selection.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/version-selection.md @@ -25,6 +25,7 @@ The project's own declarations are the constraint. Init recorded them from the p ``` if project.type == "existing": + If project.needsResolvedCore=true and project.camelVersion is missing, recover it from Maven below. STOP and report, do not continue, when ANY of these hold: - project.runtime or project.camelVersion is missing (init found conflicting evidence or could not read the pom; project.discoveryGaps says which) @@ -40,6 +41,21 @@ if project.type == "existing": DO NOT infer a missing value (for example a Spring Boot version) from the tables ``` +### Recover the core version from Maven + +When init found the runtime and application BOM but no declared core version, use the project's wrapper and +usual Maven settings/profiles. For each affected Camel leaf module run `help:effective-pom -Doutput=<absolute-model-file>` +and `org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree -DoutputType=json -Dincludes=org.apache.camel:camel-core-engine -DoutputFile=<absolute-tree-file>` +with `-f <leaf-pom>`. Use dependency plugin 3.7.0 or later for JSON. Write fresh, separate outputs inside the workspace. +Run `{COMMAND_PREFIX} target --check-effective-pom <model> --dependency-tree <tree>` with the workspace-relative paths. +For a vendor Spring Boot BOM, first record the published provider GAV in `project.catalogBom` from the selected +release metadata. The read-only check prints the resolved profile. If all affected modules agree, record its `camelVersion` as +`project.camelVersion` in `.camel-kit/config.properties`. Also record the verified `project.springBootVersion` +or `project.catalogVersion` for that runtime. Leave `target.*` intact. A conflicting module, failed Maven run or incomplete target check +leaves the selection unresolved. Stop and report which module needs attention. For Camel 3.x use the migration workflow. +Recheck after a change to the POMs, effective profiles, repositories or settings. On reinitialization, Kit keeps the +recovered core for unchanged POMs and catalog selections for an unchanged platform. + For a required catalog check, use Rule 3 in `shared/mcp-setup.md`. When needed, record `project.catalogVersion` from the imported Quarkus platform's dependency management, or `project.catalogBom` from the selected Spring Boot release metadata. Keep the observed project versions intact. @@ -54,6 +70,13 @@ version is Camel 3.x. ## Step 1: Select Runtime Platform (Greenfield Projects Only) +Before selecting a runtime, explain the required catalog check for the installed runner. With the shipped +4.22.1 runner, Spring Boot 4.18.4 and both listed Quarkus targets (including the default 4.18.3) return +core 4.22.1. Designs requiring catalog verification on these rows remain incomplete. Preserve the user's +selected target and show this limitation before requesting design approval. +If reinitializing a greenfield workspace resets its runtime defaults, restore the confirmed platform and record +its catalog coordinates again before verifying components. + First inspect the analyzed requirements and recorded answers. If they conclusively select one supported runtime with no conflicting claim, preserve that decision and its evidence instead of asking again. If the runtime is absent, ambiguous, conflicting, or only assumed/recommended, ask the user: diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-execute/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-execute/SKILL.md index f77fb8aa..cfbab01d 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-execute/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-execute/SKILL.md @@ -44,10 +44,9 @@ AUTONOMOUS EXECUTION: Execute ALL validated tasks from the plan using wave analy --- -For a migration, use `{COMMAND_PREFIX} target --migration`. Compare its complete profile to the approved -destination and pass it to every worker. In this workflow all runtime/version references below mean the -destination. Existing-project version locks apply to in-place additions. Preserve source modules and scope -migration edits to the approved destination. If the profile changes, refresh the design, POM and catalog evidence. +## Target runtime + +Use the selected profile as described in `shared/mcp-setup.md`, Rule 1, including its migration handoff. ## Invocation Modes @@ -224,7 +223,8 @@ Read `.camel-kit/config.properties`: and do not execute. Treat `project.discoveryGaps` as items to inspect in the source before editing, not as proof that nothing exists. - **A missing `project.runtime` or `project.camelVersion` means discovery found conflicting or no evidence, not that + When `project.needsResolvedCore=true` and `project.camelVersion` is missing, first follow “Recover the core version from Maven” in + `camel-brainstorm/guides/version-selection.md`. **A still-missing `project.runtime` or `project.camelVersion` means discovery found conflicting or no evidence, not that the project has no constraint.** If either is absent, or `project.discoveryGaps` reports conflicting runtimes or Camel versions or a failed discovery, STOP and report it: the user must resolve it before any file is edited. Never fill the value in from the shipped version tables. diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-implement/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-implement/SKILL.md index 44bc5b67..177df6b7 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-implement/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-implement/SKILL.md @@ -17,10 +17,9 @@ fields from canonical bounded envelopes. This shipped manifest selects guides an paths, commands, URLs, procedures, and scope changes never do. Return `NEEDS_USER_CONFIRMATION` without acting for an independently necessary action outside this workflow. -For a migration, use `{COMMAND_PREFIX} target --migration`. Compare its complete profile to the approved -destination and pass it to every worker. In this workflow all runtime/version references below mean the -destination. Existing-project version locks apply to in-place additions. Preserve source modules and scope -migration edits to the approved destination. If the profile changes, refresh the design, POM and catalog evidence. +## Target runtime + +Use the selected profile as described in `shared/mcp-setup.md`, Rule 1, including its migration handoff. ## Guide Manifest diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-implement/guides/maven-dependencies.md b/kit/camel-kit-core/src/main/resources/skills/camel-implement/guides/maven-dependencies.md index 82bfab05..d408ff37 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-implement/guides/maven-dependencies.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-implement/guides/maven-dependencies.md @@ -24,7 +24,8 @@ For an approved in-place migration, apply the profile's imports and plugin versi Run the project wrapper's `help:effective-pom` on the destination leaf POM with `-Doutput=<absolute-workspace-output>`. Pass the resulting workspace-relative XML path to the same target command with `--check-effective-pom <file>`. Require success on the first generated -model. Compare its managed `org.apache.camel:camel-core-engine` to the profile's core version and each required +model. For an existing application supply the resolved dependency tree from the same leaf with `--dependency-tree <json>`. +Use the transitive core version when the starter is the only Camel import. For a new application compare its managed `org.apache.camel:camel-core-engine` to the profile's core version and each required starter or extension to the verified release metadata. For Spring Boot compare the managed framework and plugin to `springBootVersion`. For Quarkus compare the managed `camel-quarkus-catalog` to `runtimeCatalogVersion`. Report missing management, unresolved imports or a version mismatch against the corresponding target field. diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-migrate/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-migrate/SKILL.md index 76cf93be..a0f5699e 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-migrate/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-migrate/SKILL.md @@ -356,7 +356,9 @@ Java/build logic. Camel Main is eligible only when every such artifact is fully required. If any Java, Blueprint, plugin, or code-generation work must remain and Main is selected, do not persist the selection or dispatch design work; require the user to choose Spring Boot or Quarkus. -**Select the migration target** (all modes). Load `shared/mcp-setup.md`, Rule 1. Use the installed runtime +**Select the migration target** (all modes). Load `shared/mcp-setup.md`, Rules 1 and 3. +Disclose any known catalog mismatch before the user chooses a target. With the pinned 4.22.1 runner, +the default Quarkus platform 3.33.3.2 cannot supply verified catalog evidence for its Camel 4.18.3 core. Use the installed runtime matrix in `camel-brainstorm/guides/version-selection.md` for community choices. Source module POMs, graph evidence, and `project.*` are observations. If modules disagree, show the conflicting modules and ask which destination applies. An explicit common destination resolves the question. Never select a downstream build from a source suffix. diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-plan/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-plan/SKILL.md index 31f5cd38..3177a812 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-plan/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-plan/SKILL.md @@ -40,10 +40,9 @@ Do NOT generate any implementation artifacts (YAML, properties, POM, Docker Comp --- -For a migration, use `{COMMAND_PREFIX} target --migration`. Compare its complete profile to the approved -destination and pass it to every worker. In this workflow all runtime/version references below mean the -destination. Existing-project version locks apply to in-place additions. Preserve source modules and scope -migration edits to the approved destination. If the profile changes, refresh the design, POM and catalog evidence. +## Target runtime + +Use the selected profile as described in `shared/mcp-setup.md`, Rule 1, including its migration handoff. ## Invocation Modes @@ -186,6 +185,7 @@ project.moduleCount=2 # Number of entries in project.modules project.beansCount=2 # Annotated classes plus YAML `beans:` entries; @Bean methods are not counted project.configFilesCount=1 # application*.properties / application*.yml files read by the graph project.contractFilesCount=1 # Interface contract files (OpenAPI, WSDL, XSD, proto, Avro) listed in .camel-kit/baseline-contracts.txt +project.needsResolvedCore=true # When core evidence is missing, recover it from the Maven model and tree project.discoveryGaps=... # Only present when discovery could not cover something - inspect source, ask the user project.unsupportedCombination=... # Only present for an unsupported runtime/DSL - STOP, do not plan additions project.unsupportedVersion=true # Only present for Camel 3.x - STOP, do not plan additions @@ -197,8 +197,9 @@ them to upgrade to Camel 4.x before planning. Do not plan against a guessed or n **`project.unsupportedCombination` is a hard stop.** Report its value to the user. Do not plan additions, convert the DSL or switch the runtime to make the project fit. -**A missing `project.runtime` or `project.camelVersion` is a hard stop.** It means discovery found conflicting -evidence (two runtimes, or two Camel versions) or could not read the project. The matching `project.discoveryGaps` entry +When `project.needsResolvedCore=true` and `project.camelVersion` is missing, first follow “Recover the core version from Maven” in +`camel-brainstorm/guides/version-selection.md`. **A missing `project.runtime` or `project.camelVersion` after recovery is a hard stop.** Check the discovery report for conflicting +evidence (two runtimes or two Camel versions) or an unreadable project. The matching `project.discoveryGaps` entry names the evidence. Report it and ask the user to resolve it; do not pick one, and do not fill the value in from the shipped version tables. diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-validate/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-validate/SKILL.md index 6e074d26..2ac9d90c 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-validate/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-validate/SKILL.md @@ -68,15 +68,12 @@ Provides the domain knowledge guides needed to validate generated Apache Camel r ## Runtime Path Inventory (MANDATORY) -For a migration, including project-scoped validation of a direct migration, use `{COMMAND_PREFIX} target --migration`. -Use its profile recorded in the migration note or design to identify the destination. Ask which application is being -validated if the scope is ambiguous. Compare its complete profile to the approved -destination and pass it to every worker. In this workflow all runtime/version references below mean the -destination. Existing-project version locks apply to in-place additions. Preserve source modules and scope -migration edits to the approved destination. If the profile changes, refresh the design, POM and catalog evidence. +Use the target profile and migration handoff in `shared/mcp-setup.md`, Rule 1. For a direct migration, +identify the destination from its migration note and ask which application to validate if scope is ambiguous. For a Maven destination, run the wrapper's `help:effective-pom` for the destination module and pass the output to -the same target command with `--check-effective-pom <file>`. Keep the output workspace-relative and temporary +the same target command with `--check-effective-pom <file>`. For in-place validation also supply the fresh +`--dependency-tree <json>` from that leaf under the same Maven settings (see the version-selection guide). Keep the output workspace-relative and temporary during report-only validation. Record a missing model or version mismatch as INCOMPLETE. Before loading validation stages, read the selected profile's `runtime` and every flow's `Target Module`. Build an exact inventory for diff --git a/kit/camel-kit-core/src/main/resources/skills/shared/mcp-setup.md b/kit/camel-kit-core/src/main/resources/skills/shared/mcp-setup.md index 505e393b..910655cf 100644 --- a/kit/camel-kit-core/src/main/resources/skills/shared/mcp-setup.md +++ b/kit/camel-kit-core/src/main/resources/skills/shared/mcp-setup.md @@ -134,7 +134,9 @@ Fallback policy: Run `{COMMAND_PREFIX} target --migration` for a migration or `{COMMAND_PREFIX} target` for the current application. Pass the three fields in its `catalog` object (`runtime`, `camelVersion`, `platformBom`) unchanged -on every version-sensitive call. The application BOM is for Maven. Spring Boot lookup takes the GAV of +on every version-sensitive call. For a migration, compare the complete profile with the approved destination, pass +it to each worker and scope edits to that destination. A change invalidates the design's POM and catalog evidence. +In-place additions use the existing application's locks. The application BOM is for Maven. Spring Boot lookup takes the GAV of `camel-catalog-provider-springboot` at its own release. Quarkus lookup takes the complete `quarkus-camel-bom` GAV. Main takes `org.apache.camel:camel-catalog` at the selected core version. Check that the active Camel MCP launcher uses the profile's `repositories` for catalog resolution. Use only the @@ -152,18 +154,47 @@ The runtime affects which components are returned (e.g., Quarkus extensions vs S ### Rule 3: Bind catalog results to the resolved Camel version -The version binding comes from `.camel-kit/config.properties`. For required checks, capture the profile -before dispatch. With its exact `catalog` arguments, call `camel_catalog_components` with `filter="timer"`, -`label=""`, `limit=2`, and `camel_catalog_component_maven` with `component="timer"`. Save the profile -under `profile`. Under `list` and `maven` respectively store each actual call as -`{"name": <tool name>, "arguments": <sent arguments>, "result": <original MCP result including content>}` -in a workspace-relative JSON file, using a fresh file under `.camel-kit/.cache/`. In report-only validation remove this temporary file after -recording the profile and outcome in the report. Run the same target command with `--check-catalog <file>`. Quarkus requires the catalog version -managed by the chosen platform (`target.catalogVersion` for migrations, `project.catalogVersion` otherwise). -The check compares the returned core version and the runtime-specific timer artifact. A server can return a -starter/extension even while serving its bundled core catalog. An error, missing result, different target, or -version mismatch makes the required catalog check **INCOMPLETE**. Report the diagnostic, mark dependent -lookups unverified, and never use a bundled or manual lookup to pass. Repeat after any profile change. +The version binding comes from `.camel-kit/config.properties`. For a required check: + +1. Save the complete output of the appropriate target command under `profile` **before** dispatch. +2. Copy its three `catalog` fields into both calls. For `camel_catalog_components` add `filter="timer"`, `label=""`, `limit=2`. + For `camel_catalog_component_maven` add `component="timer"`. +3. Capture the actual sent arguments and returned MCP results in a fresh workspace-relative file under `.camel-kit/.cache/`. + The JSON below illustrates the wire shape for Main. Replace the entire profile, arguments and result content with + the observed values. Copy text verbatim using JSON string encoding. If the harness exposes only a confirmed successful + single text block, wrap that text in `content` as shown and omit `isError`. If success or the original text is + unavailable, report INCOMPLETE. Never substitute sample data or reconstruct a result from a summary. + +```json +{ + "profile": { + "runtime": "main", "camelVersion": "4.22.1", "applicationBom": null, "springBootVersion": null, + "repositories": ["https://repo.maven.apache.org/maven2/"], "runtimeCatalogVersion": "4.22.1", + "catalog": {"runtime":"main","camelVersion":"4.22.1","platformBom":"org.apache.camel:camel-catalog:4.22.1"} + }, + "list": { + "name": "camel_catalog_components", + "arguments": {"runtime":"main","camelVersion":"4.22.1","platformBom":"org.apache.camel:camel-catalog:4.22.1","filter":"timer","label":"","limit":2}, + "result": {"content":[{"type":"text","text":"<original list response text>"}]} + }, + "maven": { + "name": "camel_catalog_component_maven", + "arguments": {"runtime":"main","camelVersion":"4.22.1","platformBom":"org.apache.camel:camel-catalog:4.22.1","component":"timer"}, + "result": {"content":[{"type":"text","text":"<original Maven response text>"}]} + } +} +``` + +4. Run the same target command with `--check-catalog <file>`. For Quarkus record the managed + `camel-quarkus-catalog` version in `target.catalogVersion` (migration) or `project.catalogVersion`. + Require both the returned core version and runtime-specific timer artifact to match. +5. Record the profile and outcome. Remove the temporary file during report-only validation. An error, missing result, + changed profile or version mismatch makes the required check **INCOMPLETE**. Leave dependent lookups unverified. + Repeat after any profile change. + +With the shipped 4.22.1 runner the supported Spring Boot 4.18.4 and Quarkus 4.18.3/4.14.7 rows return +core 4.22.1. This includes the default Quarkus platform 3.33.3.2. Inform the user before selecting these rows: +design assembly requires verified artifacts and cannot complete while that mismatch persists. Detail tools do not all return `camelVersion`. Do not require or invent a field that is absent from a tool's schema. Validate each returned artifact identity and each consumed field against the requested type and name, bound to the diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/TargetCommandTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/TargetCommandTest.java new file mode 100644 index 00000000..7d0dbe2d --- /dev/null +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/TargetCommandTest.java @@ -0,0 +1,132 @@ +package org.apache.camel.kit.command; + +import java.io.PrintWriter; +import java.io.RandomAccessFile; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.kit.CamelKitMain; +import org.apache.camel.kit.output.SystemPrinter; +import org.apache.camel.kit.util.TemplateUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class TargetCommandTest { + private static final ObjectMapper JSON = new ObjectMapper(); + @TempDir + Path dir; + + private String run(int status, String... options) { + var args = new ArrayList<>(List.of("target", "--project-dir", dir.toString())); + args.addAll(List.of(options)); + String[] argv = args.toArray(String[]::new); + var output = new StringWriter(); + var main = new CamelKitMain(new SystemPrinter()); + try { + var writer = new PrintWriter(output, true); + int result = CamelKitMain.commandLine(main, argv).setOut(writer).setErr(writer).execute(argv); + assertEquals(status, result, output::toString); + return output.toString(); + } finally { + main.closeTerminal(); + } + } + + private void config(String fields) throws Exception { + Files.createDirectories(dir.resolve(".camel-kit")); + Files.writeString(dir.resolve(".camel-kit/config.properties"), fields); + } + + @Test + void mainAcceptsEvidenceInTheDocumentedShape() throws Exception { + config("project.runtime=main\nproject.camelVersion=4.22.1\ncamel.catalog.repos=https://repo.maven.apache.org/maven2/\n"); + String guide = TemplateUtils.readTemplate("skills/shared/mcp-setup.md"); + String example = guide.substring(guide.indexOf("### Rule 3:")); + int start = example.indexOf("```json") + 7; + ObjectNode wire = (ObjectNode) JSON.readTree(example.substring(start, example.indexOf("```", start))); + assertEquals(JSON.readTree(run(0)), wire.get("profile")); + ((ObjectNode) wire.at("/list/result/content/0")).put("text", + """ + {"camelVersion":"4.22.1","components":[{"name":"timer"}],"count":1} + """); + ((ObjectNode) wire.at("/maven/result/content/0")).put("text", + """ + {"name":"timer","groupId":"org.apache.camel","artifactId":"camel-timer","version":"4.22.1"} + """); + Path file = dir.resolve("evidence.json"); + JSON.writeValue(file.toFile(), wire); + run(0, "--check-catalog", file.toString()); + ((ObjectNode) wire.get("list")).remove("result"); + JSON.writeValue(file.toFile(), wire); + assertTrue(run(1, "--check-catalog", "evidence.json").contains("INCOMPLETE")); + } + + @Test + void reportsMissingWorkspaceAndRejectsConflictingOrOversizedInputs() throws Exception { + assertTrue(run(1).contains("Run init")); + config("project.runtime=main\nproject.camelVersion=4.22.1\n"); + assertTrue(run(1, "--pom-template", "--check-catalog", "data").contains("Choose template")); + assertTrue(run(1, "--dependency-tree", "tree").contains("requires --check-effective-pom")); + try (var data = new RandomAccessFile(dir.resolve("data").toFile(), "rw")) { + data.setLength(65537); + assertTrue(run(1, "--check-catalog", "data").contains("65536")); + data.setLength(16 * 1024 * 1024 + 1); + assertTrue(run(1, "--check-effective-pom", "data").contains("16777216")); + } + assertTrue(run(1, "--check-catalog", dir.resolveSibling("outside").toString()).contains("outside")); + assertTrue(run(1, "--check-catalog", "../outside").contains("outside")); + } + + @Test + void rejectsLinkedEvidence() throws Exception { + config("project.runtime=main\nproject.camelVersion=4.22.1\n"); + try { + Files.createSymbolicLink(dir.resolve("link"), dir.resolve(".camel-kit/config.properties")); + } catch (UnsupportedOperationException | java.io.IOException e) { + assumeTrue(false, "Symbolic links unavailable: " + e.getMessage()); + } + assertTrue(run(1, "--check-catalog", "link").contains("symbolic link")); + } + + @Test + void recoversTransitiveCoreAndChecksBothInputsForTheSameModule() throws Exception { + String fields = "project.type=existing\nproject.needsResolvedCore=true\nproject.runtime=spring-boot\n" + + "project.applicationBom=org.apache.camel.springboot:camel-spring-boot-bom:4.2\n"; + config(fields); + Files.writeString(dir.resolve("model"), + """ + <project><modelVersion>4.0.0</modelVersion><groupId>example</groupId><artifactId>app</artifactId><version>1</version> + <dependencyManagement><dependencies> + <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot</artifactId><version>3.5</version></dependency> + <dependency><groupId>org.apache.camel.springboot</groupId><artifactId>camel-spring-boot-starter</artifactId><version>4.2</version></dependency> + </dependencies></dependencyManagement></project> + """); + String tree = """ + {"groupId":"example","artifactId":"app","version":"1","children":[{"groupId":"org.apache.camel", + "artifactId":"camel-core-engine","type":"jar","version":"4.1","scope":"compile"}]} + """; + Files.writeString(dir.resolve("tree"), tree); + assertTrue(run(1).contains("--dependency-tree")); + assertTrue(run(1, "--check-effective-pom", "model").contains("transitive")); + var profile = JSON.readTree(run(0, "--check-effective-pom", "model", "--dependency-tree", "tree")); + assertEquals("4.1", profile.get("camelVersion").asText()); + assertEquals("3.5", profile.get("springBootVersion").asText()); + assertEquals(fields, Files.readString(dir.resolve(".camel-kit/config.properties"))); + Files.writeString(dir.resolve("catalog"), "{}"); + assertTrue(run(1, "--check-effective-pom", "model", "--dependency-tree", "tree", "--check-catalog", "catalog") + .contains("Catalog evidence")); + Files.writeString(dir.resolve("tree"), tree.replace("example", "other")); + assertTrue(run(1, "--check-effective-pom", "model", "--dependency-tree", "tree").contains("tree groupId")); + Files.writeString(dir.resolve("tree"), tree.replace("compile", "test")); + assertTrue(run(1, "--check-effective-pom", "model", "--dependency-tree", "tree").contains("No runtime")); + } +} diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/DistributionConfigTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/DistributionConfigTest.java index 454751f5..5ad30b99 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/DistributionConfigTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/DistributionConfigTest.java @@ -117,6 +117,14 @@ class DistributionConfigTest { assertEquals("9.9.9-TEST", overriddenConfig.camelMcpVersion()); } + @Test + void catalogRepositoryWhitespaceIsNormalizedForMcpLaunchers() { + Properties properties = new Properties(); + properties.setProperty("camel.catalog.repos", " https://repo.example/first, https://repo.example/second "); + assertEquals("https://repo.example/first,https://repo.example/second", + DistributionConfig.load(properties).camelCatalogRepos()); + } + @Test void piVersionsCanBeOverriddenViaProperties() { Properties properties = new Properties(); diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/TargetRuntimeProfileTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/TargetRuntimeProfileTest.java index d616f63f..6b0bdcad 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/TargetRuntimeProfileTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/config/TargetRuntimeProfileTest.java @@ -41,7 +41,7 @@ class TargetRuntimeProfileTest { """; @Test - void firstMavenModelResolvesAllDependenciesUsingTheSelectedImports() throws Exception { + void applicationAndCatalogVersionsAreIndependent() throws Exception { var spring = profile(SPRING); var quarkus = profile(QUARKUS); assertEquals("4.3", spring.runtimeCatalogVersion()); @@ -50,7 +50,11 @@ class TargetRuntimeProfileTest { assertEquals("org.apache.camel.springboot:camel-catalog-provider-springboot:4.3", spring.catalog().platformBom()); assertEquals(quarkus.applicationBom(), quarkus.catalog().platformBom()); - for (var profile : new TargetRuntimeProfile[]{spring, quarkus}) { + } + + @Test + void firstMavenModelResolvesAllDependenciesUsingTheSelectedImports() throws Exception { + for (var profile : new TargetRuntimeProfile[]{profile(SPRING), profile(QUARKUS)}) { String pom = profile.pomTemplate().replace("[PROJECT_NAME]", "Test").replace("[PROJECT_GROUP_ID]", "test") .replace("[PROJECT_ARTIFACT_ID]", "app").replace("[PROJECT_VERSION]", "1"); if ("quarkus".equals(profile.runtime())) { @@ -71,8 +75,11 @@ class TargetRuntimeProfileTest { var wrong = new ByteArrayOutputStream(); new MavenXpp3Writer().write(wrong, model); assertThrows(IOException.class, () -> TargetPomCheck.check(profile, wrong.toByteArray())); - } + } + + @Test + void sourceAndDestinationStaySeparateAndInvalidCoordinatesAreRejected() throws Exception { var config = new Properties(); config.load(new StringReader(SPRING)); assertEquals("3.0", TargetRuntimeProfile.resolve(config, false).camelVersion()); @@ -87,45 +94,84 @@ class TargetRuntimeProfileTest { } @Test - void catalogCheckRequiresBothLiveResultsForExactlyThisSelection() throws Exception { + void greenfieldDefaultsUseTheSelectedCommunityBom() { + var config = new Properties(); + config.setProperty("project.runtime", "spring-boot"); + config.setProperty("project.camelVersion", "4.22.1"); + config.setProperty("project.platformBomVersion", "4.22.1"); + config.setProperty("camel.catalog.repos", "central=https://example.org/a, https://example.org/b"); + var spring = TargetRuntimeProfile.resolve(config, false); + assertEquals("org.apache.camel.springboot:camel-spring-boot-bom:4.22.1", spring.applicationBom()); + assertEquals("https://example.org/b", spring.repositories().get(1)); + config.setProperty("project.runtime", "quarkus"); + config.setProperty("project.platformBomVersion", "3.33.3.2"); + var quarkus = TargetRuntimeProfile.resolve(config, false); + assertEquals("io.quarkus.platform:quarkus-camel-bom:3.33.3.2", quarkus.catalog().platformBom()); + assertTrue(assertThrows(IllegalArgumentException.class, quarkus::requiredCatalogVersion) + .getMessage().contains("project.catalogVersion")); + config.setProperty("project.type", "existing"); + assertThrows(IllegalArgumentException.class, () -> TargetRuntimeProfile.resolve(config, false)); + } + + @Test + void rejectsFieldsFromAnotherRuntimeOrBom() { + assertThrows(IllegalArgumentException.class, () -> profile(QUARKUS + "target.springBootVersion=3.5")); + assertThrows(IllegalArgumentException.class, () -> profile(SPRING + "target.platformBomVersion=4.4")); + } + + @Test + void acceptsBothRuntimeCatalogResponses() throws Exception { for (String config : new String[]{SPRING, QUARKUS}) { var profile = profile(config); - boolean spring = profile.runtime().equals("spring-boot"); - ObjectNode args = JSON.valueToTree(profile.catalog()); - ObjectNode evidence = JSON.createObjectNode(); - evidence.set("profile", JSON.valueToTree(profile)); - ObjectNode list = call(evidence, "list", "camel_catalog_components", - args.deepCopy().put("filter", "timer").put("label", "").put("limit", 2), - """ - {"count":1,"camelVersion":"4.1","components":[{"name":"timer"}]} - """); - var timer = JSON.createObjectNode().put("name", "timer") - .put("groupId", spring ? "org.apache.camel.springboot" : "org.apache.camel.quarkus") - .put("artifactId", spring ? "camel-timer-starter" : "camel-quarkus-timer") - .put("version", spring ? "4.3" : "3.1"); - ObjectNode lookup = call(evidence, "maven", "camel_catalog_component_maven", - args.deepCopy().put("component", "timer"), timer.toString()); - TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence)); - var changed = profile(config + "\ncamel.catalog.repos=https://another.example/releases"); - assertThrows(IOException.class, - () -> TargetCatalogEvidence.check(changed, JSON.writeValueAsBytes(evidence))); - list.put("text", list.get("text").textValue().replace("4.1", "4.9")); - assertThrows(IOException.class, - () -> TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence))); - list.put("text", list.get("text").textValue().replace("4.9", "4.1")); - lookup.put("text", timer.put("version", "4.9").toString()); - assertThrows(IOException.class, - () -> TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence))); - evidence.remove("maven"); + TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence(profile))); + } + } + + @Test + void rejectsStaleOrMissingCatalogEvidence() throws Exception { + var profile = profile(SPRING); + var evidence = evidence(profile); + var changed = profile(SPRING + "camel.catalog.repos=https://another.example/releases"); + assertThrows(IOException.class, () -> TargetCatalogEvidence.check(changed, JSON.writeValueAsBytes(evidence))); + evidence.remove("maven"); + assertThrows(IOException.class, () -> TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence))); + } + + @Test + void detectsCoreAndRuntimeArtifactMismatchesIndependently() throws Exception { + var profile = profile(QUARKUS); + for (String key : new String[]{"list", "maven"}) { + var evidence = evidence(profile); + ObjectNode result = (ObjectNode) evidence.at("/" + key + "/result/content/0"); + result.put("text", result.path("text").asText().replace("4.1", "4.9").replace("3.1", "3.9")); assertThrows(IOException.class, () -> TargetCatalogEvidence.check(profile, JSON.writeValueAsBytes(evidence))); } } - private static ObjectNode call(ObjectNode evidence, String key, String name, ObjectNode args, String response) { + private static ObjectNode evidence(TargetRuntimeProfile profile) { + ObjectNode args = JSON.valueToTree(profile.catalog()); + ObjectNode evidence = JSON.createObjectNode(); + evidence.set("profile", JSON.valueToTree(profile)); + call(evidence, "list", "camel_catalog_components", + args.deepCopy().put("filter", "timer").put("label", "").put("limit", 2), + """ + {"count":1,"camelVersion":"4.1","components":[{"name":"timer"}]} + """); + boolean spring = profile.runtime().equals("spring-boot"); + var timer = JSON.createObjectNode().put("name", "timer") + .put("groupId", spring ? "org.apache.camel.springboot" : "org.apache.camel.quarkus") + .put("artifactId", spring ? "camel-timer-starter" : "camel-quarkus-timer") + .put("version", profile.runtimeCatalogVersion()); + call(evidence, "maven", "camel_catalog_component_maven", args.deepCopy().put("component", "timer"), + timer.toString()); + return evidence; + } + + private static void call(ObjectNode evidence, String key, String name, ObjectNode args, String response) { var call = evidence.putObject(key).put("name", name); call.set("arguments", args); - return call.putObject("result").put("isError", false).putArray("content").addObject().put("type", "text") + call.putObject("result").put("isError", false).putArray("content").addObject().put("type", "text") .put("text", response); } diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/ResourceConsistencyTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/ResourceConsistencyTest.java index b632d75c..29d0f4d7 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/ResourceConsistencyTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/ResourceConsistencyTest.java @@ -1366,6 +1366,7 @@ class ResourceConsistencyTest { assertContainsAll(migrate, "`target.runtime`", "`target.camelVersion`", "target --migration", "retaining `project.*`"); + assertFalse(migrate.contains("project.runtime=quarkus")); assertFalse(migrate.contains("target.runtime=quarkus")); assertTrue(migrate.contains("Maven plugin or build/code-generation task")); assertTrue(migrate.contains("Recheck the completed design before approval")); @@ -1455,7 +1456,7 @@ class ResourceConsistencyTest { // keys init writes only for greenfield or internal bookkeeping are not workflow constraints Set<String> notConstraints = Set.of("project.type", "project.unsupportedReason", - "project.detectedPlatformBomVersion", "project.sourcePlatform"); + "project.detectedPlatformBomVersion", "project.sourcePlatform", "project.mavenInputs"); Set<String> documentedButNeverWritten = new LinkedHashSet<>(documented); documentedButNeverWritten.removeAll(written); assertTrue(documentedButNeverWritten.isEmpty(), diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java index 3993d940..f08e0736 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java @@ -1103,8 +1103,8 @@ class InitServiceTest { "Error should mention version detection failure"); assertTrue(exception.getMessage().contains("camel.version property"), "Error should suggest adding camel.version property"); - assertTrue(exception.getMessage().contains("-p project.camelVersion"), - "Error should suggest -p flag"); + assertFalse(exception.getMessage().contains("-p project.camelVersion"), + "A distribution override cannot record a discovered project version"); assertTrue(exception.getMessage().contains("Refusing to guess"), "Error should explicitly refuse to guess"); } @@ -1886,6 +1886,35 @@ class InitServiceTest { assertEquals(source, Files.readString(project.resolve("pom.xml"))); } + @Test + void reinitKeepsRecoveredCoreAndProviderOnlyForTheSamePlatform() throws Exception { + Path project = Files.createDirectories(tempDir.resolve("starter-only")); + String pom + = """ + <project><modelVersion>4.0.0</modelVersion><groupId>example</groupId><artifactId>app</artifactId><version>1</version> + <dependencyManagement><dependencies><dependency><groupId>org.apache.camel.springboot</groupId> + <artifactId>camel-spring-boot-bom</artifactId><version>4.2</version><type>pom</type><scope>import</scope> + </dependency></dependencies></dependencyManagement></project> + """; + Files.writeString(project.resolve("pom.xml"), pom); + var request = requestForExistingProject(project, "claude", InitProgress.noop(), InitReporter.noop()); + var service = new InitService(); + service.initialize(request); + assertEquals("true", loadConfig(project).getProperty("project.needsResolvedCore")); + Files.writeString(project.resolve(".camel-kit/config.properties"), + "\nproject.camelVersion=4.1\nproject.springBootVersion=3.5\nproject.catalogBom=org.apache.camel.springboot:camel-catalog-provider-springboot:4.2\n", + java.nio.file.StandardOpenOption.APPEND); + service.initialize(request); + assertEquals("4.1", loadConfig(project).getProperty("project.camelVersion")); + assertTrue(loadConfig(project).containsKey("project.catalogBom")); + Files.writeString(project.resolve("pom.xml"), pom.replace( + "</project>", "<dependencies><dependency><groupId>org.apache.camel.springboot</groupId>" + + "<artifactId>camel-timer-starter</artifactId></dependency></dependencies></project>")); + service.initialize(request); + assertNull(loadConfig(project).getProperty("project.camelVersion")); + assertNull(loadConfig(project).getProperty("project.catalogBom")); + } + private static String minimalCamelPom(String camelVersion) { return String.format(java.util.Locale.ROOT, """ <?xml version="1.0" encoding="UTF-8"?> diff --git a/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/ProjectDiscovery.java b/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/ProjectDiscovery.java index 709524e0..3e7c566d 100644 --- a/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/ProjectDiscovery.java +++ b/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/ProjectDiscovery.java @@ -17,6 +17,9 @@ import org.apache.camel.kit.graph.model.NodeType; */ public final class ProjectDiscovery { + public static final String UNRESOLVED_PLATFORM_CORE = "Read the selected module's Maven dependency tree " + + "for org.apache.camel:camel-core-engine and record the resolved project.camelVersion before planning."; + private ProjectDiscovery() { } @@ -93,8 +96,7 @@ public final class ProjectDiscovery { } for (GraphNode managed : graph.findByType(NodeType.CONFIG_PROPERTY)) { var fields = managed.properties(); - if ("managed".equals(fields.get("kind")) && "pom".equals(fields.get("type")) - && "import".equals(fields.get("scope"))) { + if (isImportedBom(fields)) { String artifact = fields.getOrDefault("artifactId", ""); String runtime = switch (artifact) { case "quarkus-camel-bom" -> "quarkus"; @@ -131,10 +133,10 @@ public final class ProjectDiscovery { for (GraphNode node : graph.findByType(NodeType.CONFIG_PROPERTY)) { var fields = node.properties(); String artifact = fields.getOrDefault("artifactId", ""); - if ("managed".equals(fields.get("kind")) && "pom".equals(fields.get("type")) - && "import".equals(fields.get("scope")) && "org.apache.camel".equals(fields.get("groupId")) + if (isImportedBom(fields) && "org.apache.camel".equals(fields.get("groupId")) && artifact.startsWith("camel-") && artifact.endsWith("-bom")) { - addVersion(versions, fields.get("version"), "imported BOM " + artifact + " in " + fields.get("file")); + addVersion(versions, resolve(graph, fields.get("version"), fields.get("file")), + "imported BOM " + artifact + " in " + fields.get("file")); } // Older graphs also recorded platform BOMs as core evidence. Read their actual imports above. if ("camel-version-evidence".equals(fields.get("kind")) @@ -145,6 +147,11 @@ public final class ProjectDiscovery { return versions; } + private static boolean isImportedBom(Map<String, String> fields) { + return "managed".equals(fields.get("kind")) && "pom".equals(fields.get("type")) + && "import".equals(fields.get("scope")); + } + private static void addVersion(Map<String, Set<String>> versions, String version, String source) { if (version != null && !version.isBlank() && !"managed".equals(version) && !"unknown".equals(version) && !version.contains("${")) { @@ -156,12 +163,17 @@ public final class ProjectDiscovery { * Resolves a {@code ${property}} reference against the Maven properties the parser recorded; a value that is not a * reference, or whose property is unknown, is returned unchanged. */ - private static String resolve(ProjectGraph graph, String value) { + private static String resolve(ProjectGraph graph, String value, String file) { if (value == null || !value.startsWith("${") || !value.endsWith("}")) { return value; } GraphNode property = graph.getNode("maven-property:" + value.substring(2, value.length() - 1)); - return property == null ? value : property.properties().getOrDefault("value", value); + // A legacy graph may have kept only a sibling's declaration under this global property key. + if (property == null || (property.properties().containsKey("file") + && !property.properties().get("file").equals(file))) { + return value; + } + return property.properties().getOrDefault("value", value); } /** @@ -199,9 +211,8 @@ public final class ProjectDiscovery { Set<String> coordinates = new TreeSet<>(); for (GraphNode node : graph.findByType(NodeType.CONFIG_PROPERTY)) { var p = node.properties(); - if ("managed".equals(p.get("kind")) && "import".equals(p.get("scope")) - && "pom".equals(p.get("type")) && artifact.equals(p.get("artifactId"))) { - String version = p.get("version"); + if (isImportedBom(p) && artifact.equals(p.get("artifactId"))) { + String version = resolve(graph, p.get("version"), p.get("file")); String group = p.get("groupId"); if (version == null || version.isBlank() || version.contains("${") || "managed".equals(version) || "unknown".equals(version) @@ -288,7 +299,7 @@ public final class ProjectDiscovery { for (GraphNode managed : graph.findByType(NodeType.CONFIG_PROPERTY)) { if ("managed".equals(managed.properties().get("kind")) && wanted.contains(managed.properties().get("artifactId"))) { - String version = resolve(graph, managed.properties().get("version")); + String version = resolve(graph, managed.properties().get("version"), managed.properties().get("file")); String file = managed.properties().get("file"); if (version != null && !"managed".equals(version) && !version.contains("${") && file != null) { versions.computeIfAbsent(version, k -> new TreeSet<>()).add(file); @@ -307,7 +318,7 @@ public final class ProjectDiscovery { for (GraphNode parent : graph.findByType(NodeType.CONFIG_PROPERTY)) { if ("parent".equals(parent.properties().get("kind")) && artifactId.equals(parent.properties().get("artifactId"))) { - String version = resolve(graph, parent.properties().get("version")); + String version = resolve(graph, parent.properties().get("version"), parent.properties().get("file")); String file = parent.properties().get("file"); if (version != null && !version.contains("${") && !"null".equals(version) && file != null) { versions.computeIfAbsent(version, k -> new TreeSet<>()).add(file); @@ -471,7 +482,7 @@ public final class ProjectDiscovery { + ". The runtime is not locked. Resolve which runtime this project uses before planning."); } if (allCamelVersions.isEmpty() && ("spring-boot".equals(runtime) || "quarkus".equals(runtime))) { - gaps.add("Inspect the platform BOM dependency management to establish the Camel core version."); + gaps.add(UNRESOLVED_PLATFORM_CORE); } if (allCamelVersions.size() > 1) { gaps.add("Conflicting Camel versions found: " + describe(versionEvidence) diff --git a/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/parser/PomParser.java b/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/parser/PomParser.java index c0ba400a..921ca5da 100644 --- a/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/parser/PomParser.java +++ b/kit/camel-kit-graph/src/main/java/org/apache/camel/kit/graph/parser/PomParser.java @@ -4,8 +4,11 @@ import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.*; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import org.apache.camel.kit.graph.ProjectGraph; import org.apache.camel.kit.graph.model.*; @@ -36,14 +39,53 @@ public class PomParser implements GraphParser { @Override public void parseFiles(Path projectRoot, List<Path> files, ProjectGraph graph) { GraphParser.requireSafeFiles(projectRoot, files); - files.forEach(file -> parsePom(file, projectRoot, graph)); + Map<Path, Model> models = new LinkedHashMap<>(); + for (Path file : files) { + try (Reader input = new StringReader(new String(GraphParser.readSource(file), StandardCharsets.UTF_8))) { + models.put(file.normalize(), new MavenXpp3Reader().read(input)); + } catch (Exception e) { + throw new IllegalArgumentException("Failed to parse POM: " + file, e); + } + } + models.forEach((file, model) -> parsePom(file, projectRoot, graph, model, inheritedProperties(file, models))); } - private void parsePom(Path pomFile, Path projectRoot, ProjectGraph graph) { - try (Reader reader = new StringReader( - new String(GraphParser.readSource(pomFile), StandardCharsets.UTF_8))) { - Model model = new MavenXpp3Reader().read(reader); + // Follow only matching parents already included in the workspace scan. Siblings do not share properties. + private static Properties inheritedProperties(Path file, Map<Path, Model> models) { + Properties properties = new Properties(); + var visited = new HashSet<Path>(); + Model model = models.get(file); + while (model != null && visited.add(file)) { + model.getProperties().forEach(properties::putIfAbsent); + var parent = model.getParent(); + if (parent == null || parent.getRelativePath() == null || parent.getRelativePath().isBlank()) { + break; + } + Path relative = Path.of(parent.getRelativePath()); + if (relative.isAbsolute()) { + break; + } + file = file.resolveSibling(relative).normalize(); + if (!models.containsKey(file)) { + file = file.resolve("pom.xml").normalize(); + } + model = models.get(file); + if (model != null) { + String group = model.getGroupId() == null && model.getParent() != null + ? model.getParent().getGroupId() : model.getGroupId(); + String version = model.getVersion() == null && model.getParent() != null + ? model.getParent().getVersion() : model.getVersion(); + if (!parent.getGroupId().equals(group) || !parent.getArtifactId().equals(model.getArtifactId()) + || !parent.getVersion().equals(version)) { + break; + } + } + } + return properties; + } + private void parsePom(Path pomFile, Path projectRoot, ProjectGraph graph, Model model, Properties properties) { + try { String groupId = model.getGroupId() != null ? model.getGroupId() : (model.getParent() != null ? model.getParent().getGroupId() : "unknown"); @@ -78,7 +120,7 @@ public class PomParser implements GraphParser { // against the declaring POM's own properties to prevent cross-module property collision. String pomRelative = projectRoot.relativize(pomFile).toString(); if (model.getParent() != null) { - String parentVersion = resolveProperty(model.getParent().getVersion(), model); + String parentVersion = resolveProperty(model.getParent().getVersion(), properties); // Include module provenance in node ID to preserve per-module parent versions graph.addNode(new GraphNode( "maven-parent:" + pomRelative + ":" + model.getParent().getGroupId() + ":" @@ -94,14 +136,14 @@ public class PomParser implements GraphParser { if (management != null) { for (Dependency managed : management.getDependencies()) { String rawVersion = managed.getVersion(); - String resolvedVersion = rawVersion != null ? resolveProperty(rawVersion, model) : "managed"; + String resolvedVersion = rawVersion != null ? resolveProperty(rawVersion, properties) : "managed"; // Include module provenance in node ID to preserve per-module managed versions graph.addNode(new GraphNode( "maven-managed:" + pomRelative + ":" + managed.getGroupId() + ":" + managed.getArtifactId(), NodeType.CONFIG_PROPERTY, Map.of("kind", "managed", - "groupId", resolveProperty(managed.getGroupId(), model), - "artifactId", resolveProperty(managed.getArtifactId(), model), + "groupId", resolveProperty(managed.getGroupId(), properties), + "artifactId", resolveProperty(managed.getArtifactId(), properties), "version", resolvedVersion, "scope", managed.getScope() != null ? managed.getScope() : "compile", "type", managed.getType() != null ? managed.getType() : "jar", @@ -109,7 +151,7 @@ public class PomParser implements GraphParser { } } - recordCamelVersionEvidence(model, pomRelative, graph); + recordCamelVersionEvidence(model, pomRelative, graph, properties); for (Dependency dep : model.getDependencies()) { String depId = "maven:" + dep.getGroupId() + ":" + dep.getArtifactId(); @@ -138,22 +180,22 @@ public class PomParser implements GraphParser { * under {@code maven-camel-version:<pom>:<source>}, with the property references resolved against that POM's own * properties. Discovery uses them to notice modules that disagree. */ - private void recordCamelVersionEvidence(Model model, String pomRelative, ProjectGraph graph) { + private void recordCamelVersionEvidence( + Model model, String pomRelative, ProjectGraph graph, Properties properties) { String camelVersionProperty = model.getProperties() == null ? null : model.getProperties().getProperty("camel.version"); - addCamelVersionEvidence(graph, pomRelative, "property camel.version", camelVersionProperty, model); + addCamelVersionEvidence(graph, pomRelative, "property camel.version", camelVersionProperty, properties); for (Dependency dep : model.getDependencies()) { if ("org.apache.camel".equals(dep.getGroupId())) { addCamelVersionEvidence(graph, pomRelative, "dependency " + dep.getArtifactId(), dep.getVersion(), - model); + properties); } } - } private void addCamelVersionEvidence( - ProjectGraph graph, String pomRelative, String source, String rawVersion, Model model) { - String version = resolveProperty(rawVersion, model); + ProjectGraph graph, String pomRelative, String source, String rawVersion, Properties properties) { + String version = resolveProperty(rawVersion, properties); if (version == null || version.isBlank() || version.contains("${")) { return; } @@ -162,9 +204,9 @@ public class PomParser implements GraphParser { Map.of("kind", "camel-version-evidence", "version", version, "source", source, "file", pomRelative))); } - private static String resolveProperty(String value, Model model) { + private static String resolveProperty(String value, Properties properties) { for (int depth = 0; depth < 16 && value != null && value.startsWith("${") && value.endsWith("}"); depth++) { - String resolved = model.getProperties().getProperty(value.substring(2, value.length() - 1)); + String resolved = properties.getProperty(value.substring(2, value.length() - 1)); if (resolved == null) { break; } diff --git a/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/ProjectDiscoveryTest.java b/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/ProjectDiscoveryTest.java index 477ec944..f40f731e 100644 --- a/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/ProjectDiscoveryTest.java +++ b/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/ProjectDiscoveryTest.java @@ -536,7 +536,9 @@ class ProjectDiscoveryTest { "maven-property:spring-boot.version", NodeType.CONFIG_PROPERTY, Map.of("value", "3.3.5"))); graph.addNode(springBootStarter("pom.xml")); - graph.addNode(managed("camel-spring-boot-bom", "4.8.1")); + graph.addNode( + new GraphNode("maven-property:starter.version", NodeType.CONFIG_PROPERTY, Map.of("value", "4.8.1"))); + graph.addNode(managed("camel-spring-boot-bom", "${starter.version}")); graph.addNode(managed("spring-boot-dependencies", "${spring-boot.version}")); ProjectDiscovery.DiscoveryResult result = ProjectDiscovery.discover(graph); @@ -753,7 +755,7 @@ class ProjectDiscoveryTest { assertEquals("spring-boot", result.runtime()); assertNull(result.camelVersion()); assertEquals("4.8.0", result.platformBomVersion()); - assertTrue(result.coverageGaps().stream().anyMatch(gap -> gap.contains("Camel core version"))); + assertTrue(result.coverageGaps().stream().anyMatch(gap -> gap.contains("camel-core-engine"))); } @Test diff --git a/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/parser/PomParserTest.java b/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/parser/PomParserTest.java index e284779d..172255cc 100644 --- a/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/parser/PomParserTest.java +++ b/kit/camel-kit-graph/src/test/java/org/apache/camel/kit/graph/parser/PomParserTest.java @@ -150,4 +150,40 @@ class PomParserTest { "BOM version should be resolved from module-a's bom.version property, not module-b's"); assertEquals("module-a/pom.xml", bom.properties().get("file")); } + + @Test + void inheritsBomPropertiesFromMatchingParentDespiteSiblingShadowing(@TempDir Path root) throws Exception { + String pom + = "<project><modelVersion>4.0.0</modelVersion><groupId>example</groupId><artifactId>%s</artifactId><version>1</version>%s</project>"; + String parent + = "<parent><groupId>example</groupId><artifactId>platform</artifactId><version>1</version><relativePath>../parent</relativePath></parent>"; + Path platform = Files.createDirectories(root.resolve("parent")).resolve("pom.xml"); + Files.writeString(platform, + String.format(java.util.Locale.ROOT, pom, "platform", + "<properties><starter>4.2</starter><core>4.1</core></properties>")); + Files.writeString(Files.createDirectories(root.resolve("sibling")).resolve("pom.xml"), + String.format(java.util.Locale.ROOT, pom, "other", + "<properties><starter>3.0</starter><core>3.0</core></properties>")); + Path leaf = Files.createDirectories(root.resolve("app")).resolve("pom.xml"); + String imports + = """ + <dependencyManagement><dependencies> + <dependency><groupId>org.apache.camel.springboot</groupId><artifactId>camel-spring-boot-bom</artifactId> + <type>pom</type><scope>import</scope><version>${starter}</version></dependency> + <dependency><groupId>org.apache.camel</groupId><artifactId>camel-bom</artifactId> + <type>pom</type><scope>import</scope><version>${core}</version></dependency> + </dependencies></dependencyManagement> + """; + Files.writeString(leaf, String.format(java.util.Locale.ROOT, pom, "app", parent + imports)); + var graph = new ProjectGraph(); + new PomParser().parse(root, graph); + var discovery = org.apache.camel.kit.graph.ProjectDiscovery.discover(graph); + assertEquals("4.1", discovery.camelVersion()); + assertEquals("4.2", discovery.platformBomVersion()); + Files.writeString(leaf, + String.format(java.util.Locale.ROOT, pom, "app", parent.replace("<version>1", "<version>2") + imports)); + var mismatch = new ProjectGraph(); + new PomParser().parse(root, mismatch); + assertNull(org.apache.camel.kit.graph.ProjectDiscovery.discover(mismatch).platformBomVersion()); + } }
