This is an automated email from the ASF dual-hosted git repository. luigidemasi pushed a commit to branch feature/192-skill-pack-manifests in repository https://gitbox.apache.org/repos/asf/camel-kit.git
commit bb1700ebc240f0f8fa7e8051c7d6430de1e579cd Author: Luigi De Masi <[email protected]> AuthorDate: Fri Nov 20 13:10:51 2026 +0100 Fix #192: Compose skill packs into the distribution workflow catalog Resolve selected pack descriptors, validate contribution contracts and bind instructions to named workflow steps before packaging. Use the resulting catalog for workspace installation, command generation, routing and Doctor. Document the manifest and include a runnable instructions-only distribution. Co-authored-by: Codex <[email protected]> --- CHANGELOG.md | 4 + docs/architecture.md | 6 +- docs/commands.md | 2 +- docs/modules/ROOT/examples/skill-pack/pom.xml | 39 +++ .../camel-kit/packs/report-review/pack.yaml | 7 + .../camel-kit/packs/report-review/review.md | 1 + docs/modules/ROOT/pages/architecture.adoc | 24 ++ docs/modules/ROOT/pages/contributing.adoc | 110 +++++++ docs/security-model.md | 7 +- docs/security-model.yaml | 5 +- kit/camel-kit-core/pom.xml | 25 ++ .../camel/kit/generator/AntigravityGenerator.java | 24 +- .../camel/kit/generator/DefaultGenerator.java | 10 +- .../kit/generator/SkillResourceInstaller.java | 157 ++-------- .../camel/kit/service/DoctorExpectations.java | 18 +- .../apache/camel/kit/service/DoctorService.java | 7 + .../apache/camel/kit/workflow/SkillCatalog.java | 148 +++++++++ .../org/apache/camel/kit/workflow/SkillPack.java | 187 +++++++++++ .../camel/kit/workflow/SkillPackCompiler.java | 343 +++++++++++++++++++++ .../camel/kit/workflow/WorkflowManifest.java | 10 +- .../camel/kit/workflow/WorkflowManifestLoader.java | 5 +- .../META-INF/camel-kit/packs/core/pack.yaml | 6 + .../camel-kit/packs/core/report-timestamp.md | 1 + .../src/main/resources/skills/camel-start/SKILL.md | 2 + .../main/resources/skills/camel-validate/SKILL.md | 2 +- .../resources/workflow/camel-kit-workflow.yaml | 4 + .../camel/kit/command/DoctorCommandTest.java | 6 + .../kit/generator/SkillResourceInstallerTest.java | 4 +- .../camel/kit/workflow/SkillPackCompilerTest.java | 293 ++++++++++++++++++ .../camel/kit/workflow/WorkflowManifestTest.java | 7 + 30 files changed, 1297 insertions(+), 167 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69f993b8..8eb4fea2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Build-time skill pack composition (#192). A distribution can add or replace skills, resources, Java provider + bindings and instructions at named workflow steps. Installation, command generation, routing and Doctor use the + assembled catalog. + - **Current documentation and ADR history (#182)** — shared lifecycle across design, execution, validation, migration, debug and Ship; documentation-only reconciliation through `camel-start`; neutral-context ADR guidance preserving accepted reasoning and supersession. Add source snapshots, review records and opt-in project-aware diff --git a/docs/architecture.md b/docs/architecture.md index d1b1ace8..a4def5e9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ Camel-Kit combines two mechanisms to give AI agents accurate, efficient access t Together they enable AI-powered integration development targeting Apache Camel. Skills carry the process knowledge (how to design a flow, how to generate YAML, how to validate a route), while MCP provides the data knowledge (which components exist, what options they accept, whether an endpoint URI or Citrus test action is valid). -The authoritative workflow contract lives in `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml`. It defines command names and aliases, generated command stubs, skill visibility, pipeline stages, artifacts, transitions, MCP servers, allowed tools, and documentation references. Generator code reads this manifest for command stubs and for tool filters where the target runtime supports them; tests validate skill frontmatter against it. When changing workflow behavior, u [...] +The core workflow contract lives in `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml`. It defines command names and aliases, generated command stubs, skill visibility, pipeline stages, artifacts, transitions, MCP servers, allowed tools, and documentation references. The build composes this manifest with the selected skill packs. Generator code reads the bundled catalog for command stubs and for tool filters where the target runtime supports them; tests validate ski [...] --- @@ -32,7 +32,9 @@ A skill is a directory containing a manifest file (`SKILL.md`) and an optional ` **Skill location:** `kit/camel-kit-core/src/main/resources/skills/{skill-name}/` -**Workflow manifest:** `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml` is the source of truth for skill visibility and generated slash-command stubs. The `SKILL.md` frontmatter must match the manifest. +The contributor guide includes the [pack descriptor and runnable example](modules/ROOT/pages/contributing.adoc#skill-packs). + +**Core workflow manifest:** `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml` is the source of truth for skill visibility and generated slash-command stubs. The `SKILL.md` frontmatter must match the manifest. ### SKILL.md Format diff --git a/docs/commands.md b/docs/commands.md index 2b8db926..4c3bf49d 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -579,7 +579,7 @@ camel-kit doc unstale docs/camel-kit/001-order-processing/implementation-plan.md These commands are used inside your AI coding assistant after project initialization. The entry point is `/camel-start`, which routes to the right pipeline skill. Skills are organized into tiers: -The machine-readable source of truth for command names, generated stubs, skill visibility, pipeline stages, transitions, artifacts, and MCP tool filters is `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml`. Generated command stubs and consistency tests read that manifest; update it before changing this reference text or any skill frontmatter. +The machine-readable source of truth for command names, generated stubs, skill visibility, pipeline stages, transitions, artifacts, and MCP tool filters is `kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml`. Command generation and Doctor read the effective workflow from the built skill catalog. The default catalog preserves those entries; update it before changing this reference text or any skill frontmatter. **Tier 1 — Pipeline:** `/camel-brainstorm`, `/camel-migrate`, `/camel-plan`, `/camel-execute`, `/camel-validate` — five skills implementing a four-stage pipeline, with brainstorm and migrate as alternative Design-stage entries. Invoke them via the `/camel-start` decision tree or directly via slash command. diff --git a/docs/modules/ROOT/examples/skill-pack/pom.xml b/docs/modules/ROOT/examples/skill-pack/pom.xml new file mode 100644 index 00000000..4462ee5b --- /dev/null +++ b/docs/modules/ROOT/examples/skill-pack/pom.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>example</groupId> + <artifactId>kit-with-report-review</artifactId> + <version>1.0-SNAPSHOT</version> + <dependencies> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-kit-core</artifactId> + <version>${camel-kit.version}</version> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>3.1.0</version> + <executions> + <execution> + <phase>process-classes</phase> + <goals><goal>run</goal></goals> + <configuration> + <target> + <java classname="org.apache.camel.kit.workflow.SkillPackCompiler" fork="true" failonerror="true"> + <classpath refid="maven.runtime.classpath"/> + <arg value="${project.build.outputDirectory}/META-INF/camel-kit/catalog.zip"/> + <arg value="report-review"/> + </java> + </target> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/pack.yaml b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/pack.yaml new file mode 100644 index 00000000..1ca7b6bf --- /dev/null +++ b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/pack.yaml @@ -0,0 +1,7 @@ +id: report-review +schema: 1 +requires: [core] +add: + step/validate/report/review: + contract: 1 + resource: review.md diff --git a/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/review.md b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/review.md new file mode 100644 index 00000000..9d13fb7c --- /dev/null +++ b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/review.md @@ -0,0 +1 @@ +List the routes that the validation run covered and record any routes that still need review. diff --git a/docs/modules/ROOT/pages/architecture.adoc b/docs/modules/ROOT/pages/architecture.adoc index 14259e8b..2f6821d9 100644 --- a/docs/modules/ROOT/pages/architecture.adoc +++ b/docs/modules/ROOT/pages/architecture.adoc @@ -58,6 +58,30 @@ front matter against it. See xref:skills.adoc[], xref:mcp.adoc[], xref:knowledge.adoc[], xref:graph.adoc[] and xref:forage.adoc[] for each layer. +[[skill-packs]] +=== Build-time skill packs + +A distribution selects pack modules when it builds Kit. The core workflow manifest supplies the existing commands, +stages, artifacts and MCP tools. The core pack supplies the thirteen shipped skills and their shared files. +Additional packs can supply skills, files, Java provider bindings and instructions for a named step. +An instructions-only pack needs a descriptor and its Markdown resource. + +During Maven's `process-classes` phase, the compiler reads the selected descriptors, checks their contracts and +dependencies, resolves explicit replacements and exclusions, then binds step instructions into the owning skill. +It records each effective contribution's ID, owner, contract, requirements and installed path or provider in +`catalog.json`. That manifest and the resolved skill files travel together in one archive. +The package and resource enumeration order has no precedence. + +`init` installs the catalog's files and generates host entry points from its workflow. The assistant reads the +composed instructions at the declared step. Public pack skills also appear in the installed `camel-start` decision +tree. Doctor checks the commands, skills and supporting files against the same catalog. The default selection exposes +the existing nine public commands and keeps the four internal skills available to their callers. +A provider entry identifies a Java service and implementation for consumers. Instructions at a step are read by +the assistant. Executable provider dispatch and result verification are tracked in +https://github.com/apache/camel-kit/issues/196[#196]. + +The xref:contributing.adoc#skill-packs[working report-review pack] adds one check where `camel-validate` prepares its report. + [[camel-yaml-guidance]] === Camel YAML DSL guidance diff --git a/docs/modules/ROOT/pages/contributing.adoc b/docs/modules/ROOT/pages/contributing.adoc index b35ef1da..fe85682b 100644 --- a/docs/modules/ROOT/pages/contributing.adoc +++ b/docs/modules/ROOT/pages/contributing.adoc @@ -90,6 +90,116 @@ guides under `skills/shared/` feed several skills, so check every caller before behaviour goes into trait files under `templates/traits/<agent>/`, which need no code registration. See xref:skills.adoc[] for the structure and the tiers. +[[skill-packs]] +== Contributing a skill pack + +Put a descriptor in `src/main/resources/META-INF/camel-kit/packs/<id>/pack.yaml`. +Resource paths in the descriptor are relative to that directory. Pack IDs and the names of skills, stages, +steps and providers start with a lowercase ASCII letter and continue with lowercase letters, digits or hyphens. +List selected pack IDs in the distribution build. The compiler always includes `core`. +A selected module can contain only instructions and resources. + +The example distribution adds a check to the validation report. These are its two pack files. + +.pack.yaml +[source,yaml] +---- +include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/pack.yaml[] +---- + +.review.md +[source,markdown] +---- +include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/review.md[] +---- + +=== Composition rules + +* `schema: 1` versions the pack descriptor. Each added or replaced entry declares `contract: 1` for its + contribution kind. A pack's optional `requires` lists other selected pack IDs. A contribution's optional + `requires` lists other contribution keys that must survive composition. +* `add` maps new keys to declarations. `replace` maps existing keys to new declarations. `exclude` lists existing keys. + Each key has one defining pack and at most one replacement or exclusion. A pack editing a key must declare a + direct dependency on its defining pack. A provider replacement keeps its service interface and a skill replacement + keeps its visibility. Separate guide entries survive an entry-file replacement. +* Removing a skill also removes its command, generated route and resources supplied under that skill by its owner. + Remaining consumers must still have their dependencies. For example, the core router declares the skills in its + decision tree. Core supplies host-specific Ship delegates. An explicit replacement owns the skill text for every host and must preserve delegation to the Ship controller. +* Resolve every requested module and single-origin resource on the build classpath. The compiler rejects duplicate + keys, competing edits, dependency cycles, unknown targets, missing files and unsupported contracts before packaging. + For example, if both `team-a` and `team-b` replace `step/validate/report/timestamp`, the diagnostic names both + packs and the key. Select one replacement in the distribution. + +[cols="2,4"] +|=== +| Contribution key | Declaration and effect + +| `skill/<name>` +| Set `resource` to a Markdown entry with matching `name`, a nonempty `description` and boolean `user_invocable` +in its YAML frontmatter. For a new skill, `true` creates a public entry and `false` creates an internal skill. +Kit generates the host visibility flags. + +| `resource/<skill-or-shared>/<path>` +| Set `resource` to the bundled file. Its key determines its destination beneath the assistant's skills directory. +Use `skill/<name>` for the top-level `SKILL.md`. + +| `step/<stage>/<step>/<name>` +| Set `resource` to Markdown guidance or a check. The stage comes from the workflow manifest. Its skill must +contain the line `<!-- camel-kit:step <step> -->` exactly once. The compiler inserts active contributions there in +key order. Core exposes `route/choose` before the router's decision tree and `validate/report` while preparing the report. + +| `provider/<name>` +| Set `provider.service` and `provider.implementation` to fully qualified Java names. The compiler checks the +public interface, a public concrete implementation and its public zero-argument constructor without initializing the class. +Keep the provider classes on the distribution's runtime classpath. +|=== + +For example, a validation pack can supply an alternate timestamp instruction and require a separately declared guide. + +[source,yaml] +---- +id: team-report +schema: 1 +requires: [core] +add: + resource/camel-validate/guides/report-format.md: + contract: 1 + resource: format.md +replace: + step/validate/report/timestamp: + contract: 1 + resource: timestamp.md + requires: [resource/camel-validate/guides/report-format.md] +---- + +=== Build and try the example + +From the repository root, build Kit and then package the example against the installed Kit version. +The example POM binds `org.apache.camel.kit.workflow.SkillPackCompiler` to `process-classes` on the Maven runtime +classpath. Its arguments are the output archive and a comma-separated list of selected IDs. In a multi-module +distribution, add the pack JARs as dependencies of the module running the compiler. + +[source,bash,subs="+attributes"] +---- +./mvnw -B clean install +example="$PWD/docs/modules/ROOT/examples/skill-pack" +./mvnw -B -f "$example/pom.xml" -Dcamel-kit.version={camel-kit-snapshot-version} \ + package dependency:build-classpath -Dmdep.outputFile="$example/target/classpath.txt" +classpath="$example/target/kit-with-report-review-1.0-SNAPSHOT.jar:$(cat "$example/target/classpath.txt")" +workspace=$(mktemp -d) +( + cd "$workspace" || exit 1 + java -cp "$classpath" org.apache.camel.kit.CamelKitMain init --here --ai bob2 --no-fetch + grep 'List the routes' .bob/skills/camel-validate/SKILL.md + java -cp "$classpath" org.apache.camel.kit.CamelKitMain doctor +) +---- + +The example ships `META-INF/camel-kit/catalog.zip` in its JAR. A custom distribution supplies exactly one archive +at that path. With the standard Kit alone, the loader uses `META-INF/camel-kit/default-catalog.zip`. +To select additional packs while building core itself, add the pack modules as build/runtime dependencies and set +`-Dcamel.kit.packs=pack-a,pack-b`. See xref:architecture.adoc#skill-packs[how the catalog reaches the assistant]. + [[docs]] == Documentation diff --git a/docs/security-model.md b/docs/security-model.md index 49678ef6..873ec04f 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -394,7 +394,12 @@ links), controller-owned state, caches and private temporary directories *(docum ## 4.5a Build-time and configuration variants -Camel-Kit is a family of postures. The knobs that move the security envelope: +Camel-Kit is a family of postures. Skill pack selection is a distribution build input. The maintainer selects modules +on the build classpath. The compiler checks provider types without initializing them. `init` reads installed skill +content from the bundled catalog and applies the existing generated-path checks. Pack descriptors in the project +being initialized do not participate in selection. See the [pack contract](modules/ROOT/pages/contributing.adoc#skill-packs). + +The knobs that move the security envelope: | Knob | Default | Effect on the model | Maintainer stance | | --- | --- | --- | --- | diff --git a/docs/security-model.yaml b/docs/security-model.yaml index e84a8e47..a5c72789 100644 --- a/docs/security-model.yaml +++ b/docs/security-model.yaml @@ -67,9 +67,10 @@ component_families: in_model: true reachability: Reachable from the contents of the analysed tree (file bodies, names, symbolic links) without building or running the project. - id: C - name: Kit skills, templates, traits, agent registry, workflow manifest - paths: [kit/camel-kit-core/src/main/resources/skills, kit/camel-kit-core/src/main/resources/templates, kit/camel-kit-core/src/main/resources/agents, kit/camel-kit-core/src/main/resources/workflow] + name: Kit skills, templates, traits, agent registry, workflow manifest and assembled skill catalog + paths: [kit/camel-kit-core/src/main/resources/skills, kit/camel-kit-core/src/main/resources/templates, kit/camel-kit-core/src/main/resources/agents, kit/camel-kit-core/src/main/resources/workflow, kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs] in_model: true + build_inputs: Distribution-selected pack modules. Provider types are checked without initialization. Init consumes the bundled catalog and uses its existing generated-path checks. reachability: Only when a shipped instruction or generated artifact itself crosses a boundary it documents holding (allow-list, worker tool list, hook or guard, MCP coordinate or repository). The model disobeying an instruction is not a finding. - id: D name: Ship controller (Technology Preview) diff --git a/kit/camel-kit-core/pom.xml b/kit/camel-kit-core/pom.xml index 90ddb36e..c259cf4c 100644 --- a/kit/camel-kit-core/pom.xml +++ b/kit/camel-kit-core/pom.xml @@ -12,6 +12,10 @@ <artifactId>camel-kit-core</artifactId> <name>Camel Kit :: Core</name> + <properties> + <camel.kit.packs></camel.kit.packs> + </properties> + <dependencies> <dependency> <groupId>org.aesh</groupId> @@ -181,6 +185,27 @@ <filtering>false</filtering> </resource> </resources> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>compose-skill-catalog</id> + <phase>process-classes</phase> + <goals><goal>run</goal></goals> + <configuration> + <target> + <java classname="org.apache.camel.kit.workflow.SkillPackCompiler" fork="true" failonerror="true"> + <classpath refid="maven.runtime.classpath"/> + <arg value="${project.build.outputDirectory}/META-INF/camel-kit/default-catalog.zip"/> + <arg value="${camel.kit.packs}"/> + </java> + </target> + </configuration> + </execution> + </executions> + </plugin> + </plugins> </build> <profiles> diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/AntigravityGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/AntigravityGenerator.java index 313c4310..5750a4f2 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/AntigravityGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/AntigravityGenerator.java @@ -1,7 +1,6 @@ package org.apache.camel.kit.generator; import java.io.IOException; -import java.net.JarURLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -9,6 +8,7 @@ import java.util.Map; import org.apache.camel.kit.config.AgentDescriptor; import org.apache.camel.kit.config.AgentRegistry; +import org.apache.camel.kit.workflow.SkillCatalog; /** * Installs Antigravity's native project skills, custom agents, and MCP configuration. @@ -44,23 +44,11 @@ public class AntigravityGenerator extends DefaultGenerator { requireType(parent, true); } } - if (Files.isDirectory(ctx.skillsDir())) { - try (var paths = Files.walk(ctx.skillsDir())) { - for (Path target : paths.toList()) { - String relative = ctx.skillsDir().relativize(target).toString().replace('\\', '/'); - if (!relative.isEmpty()) { - var loader = getClass().getClassLoader(); - var resource = loader.getResource("skills/" + relative); - if (resource == null) { - resource = loader.getResource("skills/" + relative + "/"); - } - if (resource != null) { - boolean directory = resource.openConnection() instanceof JarURLConnection jar - ? jar.getJarEntry().isDirectory() : Files.isDirectory(Path.of(resource.toURI())); - requireType(target, directory); - } - } - } + for (String path : SkillCatalog.bundled().paths()) { + Path target = ctx.skillsDir().resolve(path); + requireType(target, false); + for (Path parent = target.getParent(); !parent.equals(ctx.skillsDir()); parent = parent.getParent()) { + requireType(parent, true); } } McpConfigGenerator.readAntigravityConfig(ctx.projectDir().resolve(ctx.agent().mcpConfigPath())); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java index db1af6e3..8509b256 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java @@ -4,8 +4,8 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import org.apache.camel.kit.workflow.SkillCatalog; import org.apache.camel.kit.workflow.WorkflowManifest; -import org.apache.camel.kit.workflow.WorkflowManifestLoader; public class DefaultGenerator implements AgentGenerator { @@ -48,7 +48,7 @@ public class DefaultGenerator implements AgentGenerator { @Override public void generate(InitContext ctx) throws Exception { - WorkflowManifest workflow = loadWorkflowManifest(); + WorkflowManifest workflow = SkillCatalog.bundled().manifest().workflow(); skillResourceInstaller.removeRetiredShipGuides(ctx); for (WorkflowManifest.WorkflowCommand command : workflow.generatedCommandStubs()) { if (command.isSkillOnly(ctx.agentName())) { @@ -62,10 +62,6 @@ public class DefaultGenerator implements AgentGenerator { generateMcpConfig(ctx, workflow); } - private WorkflowManifest loadWorkflowManifest() throws IOException { - return WorkflowManifestLoader.loadDefault(); - } - protected void generateBaseAssets(InitContext ctx, WorkflowManifest workflow) throws Exception { Files.createDirectories(ctx.skillsDir()); agentsMdGenerator.generate(ctx); @@ -73,7 +69,7 @@ public class DefaultGenerator implements AgentGenerator { Files.createDirectories(ctx.commandsDir()); commandStubGenerator.generate(ctx, workflow); } - skillResourceInstaller.install(ctx, workflow); + skillResourceInstaller.install(ctx, SkillCatalog.bundled()); new PersonaResourceInstaller().install(ctx); } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java index 3941211b..d35c1be1 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java @@ -2,10 +2,6 @@ package org.apache.camel.kit.generator; import java.io.IOException; import java.io.InputStream; -import java.net.URI; -import java.nio.file.FileSystem; -import java.nio.file.FileSystemAlreadyExistsException; -import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; @@ -16,7 +12,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.camel.kit.config.AgentGeneratorStrategy; +import org.apache.camel.kit.doc.FrontmatterHandler; import org.apache.camel.kit.util.AnsiColors; +import org.apache.camel.kit.workflow.SkillCatalog; import org.apache.camel.kit.workflow.WorkflowManifest; class SkillResourceInstaller { @@ -36,12 +34,6 @@ class SkillResourceInstaller { AgentGeneratorStrategy.QWEN.descriptorValue(), AgentGeneratorStrategy.OPENCODE.descriptorValue()); - private static final Set<String> MODEL_HIDDEN_INTERNAL_SKILLS = Set.of( - "camel-design", - "camel-implement", - "camel-test", - "camel-verify"); - private final DispatchBlockAppender dispatchBlockAppender; private final VersionPlaceholderResolver versionPlaceholderResolver; @@ -56,104 +48,35 @@ class SkillResourceInstaller { this.versionPlaceholderResolver = versionPlaceholderResolver; } - void install(InitContext ctx, WorkflowManifest workflow) throws Exception { + void install(InitContext ctx, SkillCatalog catalog) throws Exception { Files.createDirectories(ctx.skillsDir()); - - var skillsResource = getClass().getClassLoader().getResource("skills"); - if (skillsResource == null) { - throw new IOException("Skills resource directory not found"); - } - - URI uri = skillsResource.toURI(); - FileSystem fileSystem = null; - boolean closeFileSystem = false; - try { - Path skillsSourceDir; - if ("jar".equals(uri.getScheme())) { - JarFileSystem jarFileSystem = openJarFileSystem(uri); - fileSystem = jarFileSystem.fileSystem(); - closeFileSystem = jarFileSystem.owned(); - skillsSourceDir = fileSystem.getPath("/skills"); - } else { - skillsSourceDir = Path.of(uri); - } - - int filesCopied = copySkills(ctx, skillsSourceDir, workflow); - int skillCount; - try (var stream = Files.list(ctx.skillsDir())) { - skillCount = (int) stream.filter(Files::isDirectory).count(); - } - - if (filesCopied > 0) { - ctx.printer().println(AnsiColors.green("✓") + " Copied " + filesCopied + " files in " + skillCount - + " skill folders"); - } else { - ctx.printer().println(AnsiColors - .yellow(" No skills copied (this is normal - skills are embedded in command files)")); - } - } finally { - if (fileSystem != null && closeFileSystem) { - try { - fileSystem.close(); - } catch (Exception e) { - // Ignore close errors. - } - } - } - } - - private JarFileSystem openJarFileSystem(URI uri) throws Exception { - try { - return new JarFileSystem(FileSystems.newFileSystem(uri, java.util.Collections.emptyMap()), true); - } catch (FileSystemAlreadyExistsException e) { - return new JarFileSystem(FileSystems.getFileSystem(uri), false); - } - } - - private int copySkills(InitContext ctx, Path skillsSourceDir, WorkflowManifest workflow) throws Exception { - int filesCopied = 0; List<String> failures = new ArrayList<>(); - try (var stream = Files.walk(skillsSourceDir)) { - for (Path source : stream.toList()) { - String relativePathStr = skillsSourceDir.relativize(source).toString(); - if (relativePathStr.isEmpty()) { - continue; - } - - Path destination = ctx.skillsDir().resolve(relativePathStr); - try { - if (Files.isDirectory(source)) { - Files.createDirectories(destination); - } else { - copySkillFile(ctx, source, destination, workflow); - filesCopied++; - } - } catch (Exception e) { - failures.add(relativePathStr + ": " + e.getMessage()); - } + for (String path : catalog.paths()) { + try (InputStream source = catalog.open(path)) { + copySkillFile(ctx, source, ctx.skillsDir().resolve(path), catalog.manifest()); + } catch (Exception e) { + failures.add(path + ": " + e.getMessage()); } } if (!failures.isEmpty()) { throw new IOException("Failed to copy skill resources: " + String.join("; ", failures)); } - return filesCopied; + try (var stream = Files.list(ctx.skillsDir())) { + ctx.printer().println(AnsiColors.green("✓") + " Copied " + catalog.paths().size() + " files in " + + stream.filter(Files::isDirectory).count() + " skill folders"); + } } - private void copySkillFile( - InitContext ctx, Path source, Path destination, WorkflowManifest workflow) + private void copySkillFile(InitContext ctx, InputStream source, Path destination, SkillCatalog.Manifest catalog) throws Exception { Files.createDirectories(destination.getParent()); - - // Ownership comes from the shipped source: copySkills() visits only files Camel Kit ships, so every file - // reaching this method is refreshed. User-owned files (custom skills, notes next to a SKILL.md) are never in - // the shipped tree, are never visited and therefore survive reinitialization untouched. - try (InputStream in = Files.newInputStream(source)) { - Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING); - } + Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); + WorkflowManifest workflow = catalog.workflow(); if (destination.getFileName().toString().equals("SKILL.md")) { String skillName = destination.getParent().getFileName().toString(); boolean shipDelegate = "camel-ship".equals(skillName); - if (shipDelegate && NATIVE_SHIP_AGENTS.contains(ctx.agentName())) { + if (shipDelegate && NATIVE_SHIP_AGENTS.contains(ctx.agentName()) + && "core".equals(catalog.contributions().get("skill/camel-ship").pack())) { try (InputStream nativeSkill = getClass() .getResourceAsStream("/templates/" + ctx.agentName() + "/camel-ship.md")) { if (nativeSkill == null) { @@ -171,14 +94,10 @@ class SkillResourceInstaller { && command.skill().equals(skillName)); addHyphenatedUserInvocableMetadata(destination, exposeCommand); } - if (AgentGeneratorStrategy.COPILOT.descriptorValue().equals(ctx.agentName())) { - addCopilotReadableInternalSkillMetadata(destination); - } - if (AgentGeneratorStrategy.CLAUDE.descriptorValue().equals(ctx.agentName())) { - addClaudeReadableInternalSkillMetadata(destination); - } - if (AgentGeneratorStrategy.PI.descriptorValue().equals(ctx.agentName())) { - addPiReadableInternalSkillMetadata(destination); + if (Set.of("copilot", "claude", "pi").contains(ctx.agentName()) + && workflow.skills().stream().anyMatch(skill -> skill.name().equals(skillName) + && "internal".equals(skill.status()))) { + addInternalSkillInvocationMetadata(destination, ctx.agentName()); } if (!shipDelegate) { dispatchBlockAppender.append(destination, ctx.agentName()); @@ -220,7 +139,8 @@ class SkillResourceInstaller { private void addHyphenatedUserInvocableMetadata(Path skillFile, boolean exposeCommand) throws Exception { String content = Files.readString(skillFile); String normalized = content.replace("\r\n", "\n"); - if (!normalized.startsWith("---\n") || normalized.contains("\nuser-invocable:")) { + String header = FrontmatterHandler.extractFrontmatterYaml(normalized); + if (header == null || ("\n" + header).contains("\nuser-invocable:")) { return; } @@ -249,38 +169,24 @@ class SkillResourceInstaller { } } - void addClaudeReadableInternalSkillMetadata(Path skillFile) throws Exception { - addInternalSkillInvocationMetadata(skillFile, "Claude"); - } - - void addCopilotReadableInternalSkillMetadata(Path skillFile) throws Exception { - addInternalSkillInvocationMetadata(skillFile, "Copilot"); - } - - void addPiReadableInternalSkillMetadata(Path skillFile) throws Exception { - addInternalSkillInvocationMetadata(skillFile, "Pi"); - } - - private void addInternalSkillInvocationMetadata(Path skillFile, String agentName) throws Exception { + void addInternalSkillInvocationMetadata(Path skillFile, String agentName) throws Exception { String skillName = skillFile.getParent().getFileName().toString(); - if (!MODEL_HIDDEN_INTERNAL_SKILLS.contains(skillName)) { - return; - } - String content = Files.readString(skillFile); String normalized = content.replace("\r\n", "\n"); - if (!normalized.startsWith("---\n")) { + String header = FrontmatterHandler.extractFrontmatterYaml(normalized); + if (header == null) { throw new IOException( "Internal " + agentName + " skill '" + skillName + "' must declare frontmatter so invocation metadata can be generated"); } - boolean hasUserInvocable = normalized.contains("\nuser-invocable:"); - boolean hasDisableModelInvocation = normalized.contains("\ndisable-model-invocation:"); + header = "\n" + header; + boolean hasUserInvocable = header.contains("\nuser-invocable:"); + boolean hasDisableModelInvocation = header.contains("\ndisable-model-invocation:"); if (hasUserInvocable && hasDisableModelInvocation) { return; } - boolean hasCamelKitUserInvocable = normalized.contains("\nuser_invocable:"); + boolean hasCamelKitUserInvocable = header.contains("\nuser_invocable:"); if (!hasCamelKitUserInvocable && !hasUserInvocable) { throw new IOException( "Internal " + agentName + " skill '" + skillName @@ -310,7 +216,4 @@ class SkillResourceInstaller { AtomicFileWriter.write(skillFile, updated.toString()); } } - - private record JarFileSystem(FileSystem fileSystem, boolean owned) { - } } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorExpectations.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorExpectations.java index c3d4bb45..f558a5d6 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorExpectations.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorExpectations.java @@ -7,8 +7,8 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import org.apache.camel.kit.workflow.SkillCatalog; import org.apache.camel.kit.workflow.WorkflowManifest; -import org.apache.camel.kit.workflow.WorkflowManifestLoader; /** * Expected generated workspace contract used by {@link DoctorService}. @@ -18,6 +18,7 @@ public final class DoctorExpectations { private final List<WorkflowManifest.WorkflowCommand> generatedStubs; private final List<String> requiredSkills; private final List<String> publicSkills; + private final List<String> resources; private final Set<String> camelMcpTools; private final Set<String> knowledgeMcpTools; private final Set<String> citrusMcpTools; @@ -26,12 +27,14 @@ public final class DoctorExpectations { List<WorkflowManifest.WorkflowCommand> generatedStubs, List<String> requiredSkills, List<String> publicSkills, + List<String> resources, Set<String> camelMcpTools, Set<String> knowledgeMcpTools, Set<String> citrusMcpTools) { this.generatedStubs = List.copyOf(generatedStubs); this.requiredSkills = List.copyOf(requiredSkills); this.publicSkills = List.copyOf(publicSkills); + this.resources = List.copyOf(resources); this.camelMcpTools = Collections.unmodifiableSet(new LinkedHashSet<>(camelMcpTools)); this.knowledgeMcpTools = Collections.unmodifiableSet(new LinkedHashSet<>(knowledgeMcpTools)); this.citrusMcpTools = Collections.unmodifiableSet(new LinkedHashSet<>(citrusMcpTools)); @@ -39,13 +42,19 @@ public final class DoctorExpectations { public static DoctorExpectations loadDefault() { try { - return from(WorkflowManifestLoader.loadDefault()); + SkillCatalog catalog = SkillCatalog.bundled(); + return from(catalog.manifest().workflow(), + catalog.paths().stream().filter(p -> !p.endsWith("/SKILL.md")).toList()); } catch (IOException e) { throw new UncheckedIOException("Could not load workflow manifest for doctor expectations", e); } } public static DoctorExpectations from(WorkflowManifest workflow) { + return from(workflow, List.of()); + } + + private static DoctorExpectations from(WorkflowManifest workflow, List<String> resources) { return new DoctorExpectations( workflow.generatedCommandStubs(), workflow.skills().stream() @@ -56,6 +65,7 @@ public final class DoctorExpectations { .map(WorkflowManifest.WorkflowCommand::skill) .distinct() .toList(), + resources, orderedSet(workflow.mcpServer("camel").allowedTools()), orderedSet(workflow.mcpServer("camel-knowledge").allowedTools()), orderedSet(workflow.mcpServer("citrus").allowedTools())); @@ -79,6 +89,10 @@ public final class DoctorExpectations { return requiredSkills; } + public List<String> resources() { + return resources; + } + public List<String> publicSkills() { return publicSkills; } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java index df5c89d4..29278531 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java @@ -188,6 +188,13 @@ public class DoctorService { "Missing SKILL.md for: " + String.join(", ", missingSkills), "Restore the missing skill folders or re-run camel-kit init --here --force.")); } + List<String> missingResources = expectations.resources().stream() + .filter(path -> !Files.isRegularFile(skillsDir.resolve(path))).toList(); + if (!missingResources.isEmpty()) { + findings.add(DoctorFinding.fail("skills", relativize(root, skillsDir), + "Missing skill resources: " + String.join(", ", missingResources), + "Re-run camel-kit init --here --force to restore the bundled resources.")); + } checkAgentSpecificWorkspace(root, agent, findings); } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillCatalog.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillCatalog.java new file mode 100644 index 00000000..7946f8b5 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillCatalog.java @@ -0,0 +1,148 @@ +package org.apache.camel.kit.workflow; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +/** The workflow, provider bindings and installable files selected together by the distribution build. */ +public final class SkillCatalog { + + public static final String DEFAULT = "META-INF/camel-kit/default-catalog.zip"; + public static final String DISTRIBUTION = "META-INF/camel-kit/catalog.zip"; + static final String MANIFEST = "catalog.json"; + static final ObjectMapper JSON = new ObjectMapper().enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + private static SkillCatalog bundled; + + public record Provider(String service, String implementation) { + } + + public record Binding(String pack, int contract, List<String> requires, String path, Provider provider) { + public Binding { + requires = List.copyOf(requires); + } + } + + public record Manifest(int contract, List<String> packs, WorkflowManifest workflow, + Map<String, Binding> contributions) { + public Manifest { + packs = List.copyOf(packs); + contributions = Map.copyOf(contributions); + } + } + + private final Manifest manifest; + private final Map<String, byte[]> files; + + SkillCatalog(Manifest manifest, Map<String, byte[]> files) throws IOException { + if (manifest.contract() != 1) { + throw new IOException("Unsupported skill catalog contract: " + manifest.contract()); + } + WorkflowManifestValidator.validateOrThrow(manifest.workflow()); + Set<String> skills = new HashSet<>(); + for (var skill : manifest.workflow().skills()) { + skills.add(skill.name()); + if (!files.containsKey(skill.name() + "/SKILL.md")) { + throw new IOException("Missing SKILL.md for skill/" + skill.name()); + } + } + for (var entry : manifest.contributions().entrySet()) { + Binding binding = entry.getValue(); + if (binding.contract() != 1 || !manifest.packs().contains(binding.pack()) + || !manifest.contributions().keySet().containsAll(binding.requires()) + || (binding.provider() == null ? !files.containsKey(binding.path()) : binding.path() != null)) { + throw new IOException("Invalid bundled contribution " + binding.pack() + ": " + entry.getKey()); + } + } + // All supported hosts must agree on whether a destination is a file or directory, including on Windows. + Map<String, String> spellings = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (String path : files.keySet()) { + int slash = path.indexOf('/'); + if (!safePath(path) || slash < 0 + || !(skills.contains(path.substring(0, slash)) || path.startsWith("shared/"))) { + throw new IOException("Invalid skill resource destination: " + path); + } + for (String current = path;; current = current.substring(0, current.lastIndexOf('/'))) { + String previous = spellings.putIfAbsent(current, current); + if (previous != null && !previous.equals(current)) { + throw new IOException("Skill resource paths differ only by case: " + previous + " and " + current); + } + if (!current.contains("/")) { + break; + } + } + for (int i = slash; i >= 0; i = path.indexOf('/', i + 1)) { + if (files.containsKey(path.substring(0, i))) { + throw new IOException("Skill resource is both file and directory: " + path.substring(0, i)); + } + } + } + this.manifest = manifest; + this.files = Collections.unmodifiableMap(new TreeMap<>(files)); + } + + public Manifest manifest() { + return manifest; + } + + public Set<String> paths() { + return files.keySet(); + } + + public InputStream open(String path) throws IOException { + byte[] bytes = files.get(path); + if (bytes == null) { + throw new IOException("Unknown skill resource: " + path); + } + return new ByteArrayInputStream(bytes); + } + + static boolean safePath(String path) { + return path != null && path.matches("[a-zA-Z0-9_-][a-zA-Z0-9_.-]*(/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*)*"); + } + + public static synchronized SkillCatalog bundled() throws IOException { + if (bundled == null) { + bundled = load(SkillCatalog.class.getClassLoader()); + } + return bundled; + } + + static SkillCatalog load(ClassLoader loader) throws IOException { + List<URL> urls = Collections.list(loader.getResources(DISTRIBUTION)); + if (urls.isEmpty()) { + urls = Collections.list(loader.getResources(DEFAULT)); + } + if (urls.size() != 1) { + throw new IOException("Expected one assembled Camel Kit skill catalog, found " + urls); + } + try (var stream = new ZipInputStream(urls.get(0).openStream())) { + Manifest manifest = null; + Map<String, byte[]> files = new TreeMap<>(); + for (ZipEntry entry; (entry = stream.getNextEntry()) != null;) { + String name = entry.getName(); + if (name.equals(MANIFEST) && manifest == null) { + manifest = JSON.readValue(stream.readAllBytes(), Manifest.class); + } else if (!name.startsWith("skills/") + || files.putIfAbsent(name.substring(7), stream.readAllBytes()) != null) { + throw new IOException("Unexpected or duplicate skill catalog entry: " + name); + } + } + if (manifest == null) { + throw new IOException("Missing " + MANIFEST + " in " + urls); + } + return new SkillCatalog(manifest, files); + } + } +} diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPack.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPack.java new file mode 100644 index 00000000..2a2ac0e7 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPack.java @@ -0,0 +1,187 @@ +package org.apache.camel.kit.workflow; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +/** Versioned declarations of one build-time module. Keys are stable across explicitly selected replacements. */ +record SkillPack(String id, int schema, List<String> requires, Map<String, Entry> add, Map<String, Entry> replace, + List<String> exclude) { + + static final ObjectMapper YAML = new ObjectMapper( + YAMLFactory.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS); + static final String ID = "[a-z][a-z0-9-]*"; + + record Entry(int contract, String resource, SkillCatalog.Provider provider, List<String> requires) { + Entry { + requires = requires == null ? List.of() : List.copyOf(requires); + } + } + + record Declaration(String pack, String key, Entry entry) { + String kind() { + return key.substring(0, key.indexOf('/')); + } + + String name() { + return key.substring(key.indexOf('/') + 1); + } + + IOException error(String message) { + return new IOException(pack + ": " + key + ": " + message); + } + + String location() { + return pack + ": " + key; + } + } + + SkillPack { + requires = requires == null ? List.of() : List.copyOf(requires); + add = add == null ? Map.of() : Map.copyOf(add); + replace = replace == null ? Map.of() : Map.copyOf(replace); + exclude = exclude == null ? List.of() : List.copyOf(exclude); + } + + static Map<String, SkillPack> load(ClassLoader loader, List<String> selected) throws IOException { + Map<String, SkillPack> packs = new TreeMap<>(); + for (String id : selected) { + if (!id.matches(ID) || packs.containsKey(id)) { + throw new IOException("Invalid or duplicate selected pack ID: " + id); + } + String path = directory(id) + "pack.yaml"; + try (var input = uniqueResource(loader, path).openStream()) { + SkillPack pack = YAML.readValue(input, SkillPack.class); + if (!id.equals(pack.id()) || pack.schema() != 1) { + throw new IOException( + "Expected pack '" + id + "' schema 1, found '" + pack.id() + "' schema " + pack.schema()); + } + packs.put(id, pack); + } catch (IOException | RuntimeException e) { + throw new IOException(path + ": " + e.getMessage(), e); + } + } + Set<String> checked = new HashSet<>(); + for (String id : packs.keySet()) { + checkDependencies(packs, id, checked, new ArrayList<>()); + } + return packs; + } + + private static void checkDependencies( + Map<String, SkillPack> packs, String id, Set<String> checked, List<String> path) + throws IOException { + if (checked.contains(id)) { + return; + } + if (path.contains(id) || !packs.containsKey(id)) { + throw new IOException("Cyclic or missing pack dependency: " + String.join(" -> ", path) + " -> " + id); + } + path.add(id); + for (String required : packs.get(id).requires()) { + checkDependencies(packs, required, checked, path); + } + path.remove(path.size() - 1); + checked.add(id); + } + + static String directory(String id) { + return "META-INF/camel-kit/packs/" + id + "/"; + } + + static URL uniqueResource(ClassLoader loader, String path) throws IOException { + List<URL> urls = Collections.list(loader.getResources(path)); + if (urls.size() != 1) { + throw new IOException("Expected one resource " + path + ", found " + urls); + } + return urls.get(0); + } + + static Map<String, Declaration> definitions(Map<String, SkillPack> packs, Map<String, Declaration> core) + throws IOException { + Map<String, Declaration> definitions = new TreeMap<>(core); + for (SkillPack pack : packs.values()) { + for (var entry : pack.add().entrySet()) { + register(definitions, new Declaration(pack.id(), entry.getKey(), entry.getValue())); + } + } + return definitions; + } + + static Map<String, Declaration> resolve(Map<String, SkillPack> packs, Map<String, Declaration> definitions) + throws IOException { + Map<String, Declaration> effective = new TreeMap<>(definitions); + Map<String, Declaration> edits = new TreeMap<>(); + for (SkillPack pack : packs.values()) { + for (var entry : pack.replace().entrySet()) { + register(edits, new Declaration(pack.id(), entry.getKey(), entry.getValue())); + } + for (String key : pack.exclude()) { + register(edits, new Declaration(pack.id(), key, null)); + } + } + for (Declaration edit : edits.values()) { + Declaration original = definitions.get(edit.key()); + if (original == null) { + throw edit.error("no such contribution to replace or exclude"); + } + if (!packs.get(edit.pack()).requires().contains(original.pack())) { + throw edit.error("requires must name the declaring pack '" + original.pack() + "'"); + } + if (original.entry().provider() != null && edit.entry() != null + && !original.entry().provider().service().equals(edit.entry().provider().service())) { + throw edit.error("replacement must preserve service " + original.entry().provider().service() + + " declared by " + original.location()); + } + if (edit.entry() == null) { + effective.remove(edit.key()); + } else { + effective.put(edit.key(), edit); + } + } + // Removing a skill also removes the guides supplied by its own pack. + for (Declaration d : List.copyOf(effective.values())) { + if (d.kind().equals("resource")) { + String owner = d.name().split("/", 2)[0]; + if (!owner.equals("shared") && !effective.containsKey("skill/" + owner)) { + Declaration skill = definitions.get("skill/" + owner); + if (skill == null || !skill.pack().equals(d.pack())) { + throw d.error("resource requires effective skill/" + owner); + } + effective.remove(d.key()); + } + } + } + for (Declaration d : effective.values()) { + for (String required : d.entry().requires()) { + if (!effective.containsKey(required)) { + throw d.error("requires missing contribution " + required); + } + } + } + return effective; + } + + private static void register(Map<String, Declaration> entries, Declaration next) throws IOException { + Declaration previous = entries.putIfAbsent(next.key(), next); + if (previous != null) { + throw next.error("conflicts with " + previous.location()); + } + } +} diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPackCompiler.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPackCompiler.java new file mode 100644 index 00000000..34f57729 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/SkillPackCompiler.java @@ -0,0 +1,343 @@ +package org.apache.camel.kit.workflow; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.net.JarURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.camel.kit.doc.FrontmatterHandler; +import org.apache.camel.kit.generator.AtomicFileWriter; +import org.apache.camel.kit.workflow.SkillPack.Declaration; +import org.apache.camel.kit.workflow.SkillPack.Entry; +import org.apache.camel.kit.workflow.WorkflowManifest.WorkflowCommand; +import org.apache.camel.kit.workflow.WorkflowManifest.WorkflowSkill; + +import com.fasterxml.jackson.databind.JsonNode; + +/** Maven entry point. Pack selection and resource lookup happen before packaging, never in the user's workspace. */ +public final class SkillPackCompiler { + + private final ClassLoader loader; + private final Map<Declaration, byte[]> resources = new HashMap<>(); + private final Map<String, Declaration> base = new TreeMap<>(); + + private SkillPackCompiler(ClassLoader loader) { + this.loader = loader; + } + + public static void main(String[] args) throws Exception { + if (args.length < 1 || args.length > 2) { + throw new IllegalArgumentException("Usage: SkillPackCompiler <output-catalog.zip> [pack-id,...]"); + } + List<String> packs = args.length == 1 || args[1].isBlank() ? List.of() : Arrays.asList(args[1].split(",", -1)); + Path output = Path.of(args[0]).toAbsolutePath(); + byte[] bytes = compile(SkillPackCompiler.class.getClassLoader(), packs); + Files.createDirectories(output.getParent()); + AtomicFileWriter.write(output, bytes); + } + + static byte[] compile(ClassLoader loader, List<String> selected) throws Exception { + List<String> ids = new ArrayList<>(List.of("core")); + ids.addAll(selected); + Map<String, SkillPack> packs = SkillPack.load(loader, ids); + return new SkillPackCompiler(loader).assemble(packs); + } + + private byte[] assemble(Map<String, SkillPack> packs) throws Exception { + WorkflowManifest workflow = readCore(); + for (SkillPack pack : packs.values()) { + readDeclarations(pack.id(), pack.add()); + readDeclarations(pack.id(), pack.replace()); + } + Map<String, Declaration> definitions = SkillPack.definitions(packs, base); + Map<String, Declaration> entries = SkillPack.resolve(packs, definitions); + Map<String, byte[]> files = new TreeMap<>(); + Map<String, SkillCatalog.Binding> bindings = new TreeMap<>(); + Map<String, List<String>> steps = new TreeMap<>(); + Map<String, String> stageSkills = new HashMap<>(); + workflow.stages().forEach(stage -> stageSkills.put(stage.id(), stage.skill())); + for (Declaration d : entries.values()) { + String path; + switch (d.kind()) { + case "skill", "resource" -> { + path = d.kind().equals("skill") ? d.name() + "/SKILL.md" : d.name(); + files.put(path, resources.get(d)); + } + case "step" -> { + String[] parts = d.name().split("/"); + String skill = stageSkills.get(parts[0]); + if (skill == null) { + throw d.error("unknown workflow stage " + parts[0]); + } + path = skill + "/SKILL.md"; + steps.computeIfAbsent(parts[0] + "/" + parts[1], unused -> new ArrayList<>()) + .add(new String(resources.get(d), StandardCharsets.UTF_8).strip()); + } + case "provider" -> path = null; + default -> throw d.error("unknown contribution kind"); + } + bindings.put(d.key(), new SkillCatalog.Binding( + d.pack(), d.entry().contract(), d.entry().requires(), path, d.entry().provider())); + } + WorkflowManifest effective = composeWorkflow(workflow, entries, definitions, steps); + bindSteps(stageSkills, files, steps, entries); + var manifest = new SkillCatalog.Manifest(1, List.copyOf(packs.keySet()), effective, bindings); + return archive(new SkillCatalog(manifest, files)); + } + + private WorkflowManifest composeWorkflow( + WorkflowManifest workflow, Map<String, Declaration> entries, + Map<String, Declaration> definitions, Map<String, List<String>> steps) + throws IOException { + List<WorkflowSkill> skills = new ArrayList<>(); + List<WorkflowCommand> commands = new ArrayList<>( + workflow.commands().stream() + .filter(c -> entries.containsKey("skill/" + c.skill())).toList()); + for (WorkflowSkill skill : workflow.skills()) { + Declaration d = entries.get("skill/" + skill.name()); + if (d != null) { + if (skillHeader(d).get("user_invocable").booleanValue() != skill.userInvocable()) { + throw d.error("user_invocable differs from the core skill contract"); + } + skills.add(new WorkflowSkill( + skill.name(), skill.userInvocable(), skill.status(), skill.generatedCommand(), + d.entry().requires())); + } + } + List<String> routes = new ArrayList<>(); + for (Declaration d : entries.values()) { + if (!d.kind().equals("skill") || base.containsKey(d.key())) { + continue; + } + JsonNode header = skillHeader(d); + boolean visible = header.get("user_invocable").booleanValue(); + Declaration original = definitions.get(d.key()); + if (d != original && visible != skillHeader(original).get("user_invocable").booleanValue()) { + throw d.error("replacement must preserve visibility declared by " + original.location()); + } + skills.add(new WorkflowSkill( + d.name(), visible, visible ? "standalone" : "internal", visible ? d.name() : null, + d.entry().requires())); + if (visible) { + String description = header.get("description").textValue(); + commands.add(new WorkflowCommand( + d.name(), List.of(), d.name(), true, true, "utility", description, true, false, List.of())); + routes.add("- /" + d.name() + " — " + description); + } + } + if (!routes.isEmpty()) { + steps.computeIfAbsent("route/choose", unused -> new ArrayList<>()).add( + "For a matching request, invoke the corresponding installed skill:\n\n" + + String.join("\n", routes)); + } + var effective = new WorkflowManifest( + workflow.version(), workflow.description(), commands, skills, + workflow.stages(), workflow.artifacts(), workflow.mcpServers(), workflow.websiteReference()); + WorkflowManifestValidator.validateOrThrow(effective); + return effective; + } + + private WorkflowManifest readCore() throws Exception { + URL source = SkillPack.uniqueResource(loader, WorkflowManifestLoader.DEFAULT_RESOURCE); + WorkflowManifest workflow; + try (var in = source.openStream()) { + workflow = WorkflowManifestLoader.load(in); + } + if (!"1.0".equals(workflow.version())) { + throw new IOException("Unsupported core workflow contract " + workflow.version() + " in " + source); + } + if (source.openConnection() instanceof JarURLConnection jar) { + try (var fs = FileSystems.newFileSystem(Path.of(jar.getJarFileURL().toURI()))) { + readCoreFiles(fs.getPath("/skills"), workflow); + } + } else { + readCoreFiles(Path.of(source.toURI()).getParent().resolve("../skills").normalize(), workflow); + } + return workflow; + } + + private void readCoreFiles(Path root, WorkflowManifest workflow) throws IOException { + Map<String, WorkflowSkill> expected = new TreeMap<>(); + workflow.skills().forEach(skill -> expected.put(skill.name(), skill)); + try (var paths = Files.walk(root)) { + for (Path file : paths.filter(Files::isRegularFile).sorted().toList()) { + String path = root.relativize(file).toString().replace('\\', '/'); + String key = path.matches(SkillPack.ID + "/SKILL\\.md") + ? "skill/" + path.substring(0, path.indexOf('/')) : "resource/" + path; + List<String> requires = List.of(); + if (key.startsWith("skill/")) { + WorkflowSkill skill = expected.remove(key.substring("skill/".length())); + if (skill == null) { + throw new IOException("Undeclared core " + key + " in " + path); + } + requires = skill.requires(); + } + var d = new Declaration("core", key, new Entry(1, "skills/" + path, null, requires)); + base.put(key, d); + resources.put(d, Files.readAllBytes(file)); + } + } + if (!expected.isEmpty()) { + throw new IOException("Core workflow skills missing SKILL.md: " + expected.keySet()); + } + } + + private void readDeclarations(String pack, Map<String, Entry> entries) throws IOException { + for (var item : new TreeMap<>(entries).entrySet()) { + var d = new Declaration(pack, item.getKey(), item.getValue()); + Entry e = d.entry(); + if (e.contract() != 1) { + throw d.error("unsupported contribution contract " + e.contract() + " (expected 1)"); + } + String id = SkillPack.ID; + if (d.key().matches("provider/" + id)) { + if (e.provider() == null || e.resource() != null) { + throw d.error("expected a provider with service and implementation"); + } + validateProvider(d); + continue; + } + boolean file = d.key().startsWith("resource/") && SkillCatalog.safePath(d.key()) + && d.key().substring("resource/".length()).contains("/") && !d.key().endsWith("/SKILL.md"); + if (!file && !d.key().matches("skill/" + id) && !d.key().matches("step/" + id + "/" + id + "/" + id)) { + throw d.error("invalid contribution identifier"); + } + if (d.key().equals("skill/shared") || !SkillCatalog.safePath(e.resource()) || e.provider() != null) { + throw d.error("expected a pack-relative resource"); + } + String path = SkillPack.directory(pack) + e.resource(); + try { + URL url = SkillPack.uniqueResource(loader, path); + if ("file".equals(url.getProtocol()) && !Files.isRegularFile(Path.of(url.toURI())) + || url.openConnection() instanceof JarURLConnection jar && jar.getJarEntry().isDirectory()) { + throw new IOException("expected a regular file: " + path); + } + byte[] bytes; + try (var in = url.openStream()) { + bytes = in.readAllBytes(); + } + if (d.key().startsWith("step/") && new String(bytes, StandardCharsets.UTF_8).isBlank()) { + throw new IOException("empty workflow step instructions"); + } + resources.put(d, bytes); + } catch (IOException | java.net.URISyntaxException ex) { + throw d.error(ex.getMessage()); + } + if (d.kind().equals("skill")) { + JsonNode header = skillHeader(d); + String text = new String(resources.get(d), StandardCharsets.UTF_8); + String yaml = FrontmatterHandler.extractFrontmatterYaml(text); + // Host metadata adapters insert their visibility flags next to a top-level block key. + if (!Pattern.compile("(?m)^user_invocable: *(true|false) *(#.*)?$").matcher(yaml).find()) { + String normalized = SkillPack.YAML.writeValueAsString(header) + "---\n" + + FrontmatterHandler.extractBody(text); + resources.put(d, normalized.getBytes(StandardCharsets.UTF_8)); + } + } + } + } + + private JsonNode skillHeader(Declaration d) throws IOException { + String yaml = FrontmatterHandler.extractFrontmatterYaml(new String(resources.get(d), StandardCharsets.UTF_8)); + JsonNode header; + try { + header = yaml == null ? null : SkillPack.YAML.readTree(yaml); + } catch (IOException e) { + throw d.error(e.getMessage()); + } + if (header == null || !d.name().equals(header.path("name").asText()) + || !header.path("user_invocable").isBoolean() + || !header.path("description").isTextual() || header.get("description").textValue().isBlank()) { + throw d.error("SKILL.md requires matching name, description and boolean user_invocable"); + } + if (header.has("user-invocable") || header.has("disable-model-invocation") + || header.path("metadata").has("user-invocable")) { + throw d.error("declare user_invocable only; Kit generates host-specific visibility"); + } + return header; + } + + private void validateProvider(Declaration d) throws IOException { + var provider = d.entry().provider(); + try { + if (provider.service() == null || provider.implementation() == null) { + throw d.error("provider requires service and implementation"); + } + try { + SkillPack.uniqueResource(loader, provider.service().replace('.', '/') + ".class"); + SkillPack.uniqueResource(loader, provider.implementation().replace('.', '/') + ".class"); + } catch (IOException e) { + throw d.error("invalid provider " + provider.implementation() + ": " + e.getMessage()); + } + Class<?> service = Class.forName(provider.service(), false, loader); + Class<?> impl = Class.forName(provider.implementation(), false, loader); + if (!service.isInterface() || !Modifier.isPublic(service.getModifiers()) || !service.isAssignableFrom(impl) + || !Modifier.isPublic(impl.getModifiers()) || Modifier.isAbstract(impl.getModifiers())) { + throw d.error("expected a public concrete implementation of " + provider.service() + ": " + + provider.implementation()); + } + impl.getConstructor(); + } catch (ReflectiveOperationException | LinkageError e) { + throw d.error("invalid provider " + provider + ": " + e); + } + } + + private static void bindSteps( + Map<String, String> stageSkills, Map<String, byte[]> files, Map<String, List<String>> steps, + Map<String, Declaration> entries) + throws IOException { + for (var hook : steps.entrySet()) { + String[] point = hook.getKey().split("/"); + String declarations + = entries.values().stream().filter(d -> d.key().startsWith("step/" + hook.getKey() + "/")) + .map(Declaration::location).toList().toString(); + String path = stageSkills.get(point[0]) + "/SKILL.md"; + String content = new String(files.get(path), StandardCharsets.UTF_8); + String marker = "<!-- camel-kit:step " + point[1] + " -->"; + var match = Pattern.compile("(?m)^" + Pattern.quote(marker) + "\\r?$").matcher(content); + if (match.results().count() != 1) { + throw new IOException( + declarations + ": expected one " + marker + " in " + path + " for " + hook.getKey()); + } + files.put(path, + match.reset() + .replaceFirst( + java.util.regex.Matcher.quoteReplacement(String.join("\n\n", hook.getValue()))) + .getBytes(StandardCharsets.UTF_8)); + } + } + + private static byte[] archive(SkillCatalog catalog) throws IOException { + var buffer = new ByteArrayOutputStream(); + try (var zip = new ZipOutputStream(buffer)) { + writeEntry(zip, SkillCatalog.MANIFEST, SkillCatalog.JSON.writeValueAsBytes(catalog.manifest())); + for (String path : catalog.paths()) { + writeEntry(zip, "skills/" + path, catalog.open(path).readAllBytes()); + } + } + return buffer.toByteArray(); + } + + private static void writeEntry(ZipOutputStream zip, String name, byte[] bytes) throws IOException { + var entry = new ZipEntry(name); + entry.setTimeLocal(LocalDateTime.of(1980, 1, 2, 0, 0)); + zip.putNextEntry(entry); + zip.write(bytes); + zip.closeEntry(); + } +} diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifest.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifest.java index cebad367..72306bbd 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifest.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifest.java @@ -70,7 +70,15 @@ public record WorkflowManifest( String name, boolean userInvocable, String status, - String generatedCommand) { + String generatedCommand, + List<String> requires) { + public WorkflowSkill { + requires = List.copyOf(nullToEmpty(requires)); + } + + public WorkflowSkill(String name, boolean userInvocable, String status, String generatedCommand) { + this(name, userInvocable, status, generatedCommand, List.of()); + } } public record WorkflowStage( diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifestLoader.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifestLoader.java index 17d46761..0f9e42ec 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifestLoader.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowManifestLoader.java @@ -5,7 +5,6 @@ import java.io.InputStream; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; /** * Loads the bundled Camel-Kit workflow manifest. @@ -14,7 +13,7 @@ public final class WorkflowManifestLoader { public static final String DEFAULT_RESOURCE = "workflow/camel-kit-workflow.yaml"; - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory()) + private static final ObjectMapper OBJECT_MAPPER = SkillPack.YAML.copy() .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); private WorkflowManifestLoader() { @@ -22,7 +21,7 @@ public final class WorkflowManifestLoader { } public static WorkflowManifest loadDefault() throws IOException { - return load(DEFAULT_RESOURCE); + return SkillCatalog.bundled().manifest().workflow(); } public static WorkflowManifest load(String resourcePath) throws IOException { diff --git a/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/pack.yaml b/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/pack.yaml new file mode 100644 index 00000000..e116d9ba --- /dev/null +++ b/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/pack.yaml @@ -0,0 +1,6 @@ +id: core +schema: 1 +add: + step/validate/report/timestamp: + contract: 1 + resource: report-timestamp.md diff --git a/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/report-timestamp.md b/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/report-timestamp.md new file mode 100644 index 00000000..4096f8ec --- /dev/null +++ b/kit/camel-kit-core/src/main/resources/META-INF/camel-kit/packs/core/report-timestamp.md @@ -0,0 +1 @@ +Use the current date and time for the timestamped filename (e.g., `validation-report-2026-04-22_14-30.md`). diff --git a/kit/camel-kit-core/src/main/resources/skills/camel-start/SKILL.md b/kit/camel-kit-core/src/main/resources/skills/camel-start/SKILL.md index 1d33fa0e..93ed2aa1 100644 --- a/kit/camel-kit-core/src/main/resources/skills/camel-start/SKILL.md +++ b/kit/camel-kit-core/src/main/resources/skills/camel-start/SKILL.md @@ -20,6 +20,8 @@ record unavailable verification honestly. Then stop; do not fall through to impl ## Decision Tree +<!-- camel-kit:step choose --> + Answer these questions in order. The first "yes" is your destination. | # | Question | If Yes | Slash Command | 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 0d61bf7b..8f13da2e 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 @@ -399,7 +399,7 @@ After completing all validation checks, generate a markdown report saved to: - **Chained mode and standalone pipeline-scoped:** `docs/camel-kit/<PIPELINE_ID>/validation-report.md` - **Standalone project-scoped (no pipeline):** `docs/validation-report-YYYY-MM-DD_HH-mm.md` -Use the current date and time for the timestamped filename (e.g., `validation-report-2026-04-22_14-30.md`). +<!-- camel-kit:step report --> ### Report Format diff --git a/kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml b/kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml index 27c141b2..b68ad994 100644 --- a/kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml +++ b/kit/camel-kit-core/src/main/resources/workflow/camel-kit-workflow.yaml @@ -103,6 +103,10 @@ skills: user_invocable: true status: router generated_command: camel-start + # The core router's decision tree and tier table refer to these skills by name. + requires: [skill/camel-brainstorm, skill/camel-migrate, skill/camel-plan, skill/camel-execute, + skill/camel-validate, skill/camel-debug, skill/camel-ship, skill/camel-knowledge, + skill/camel-design, skill/camel-implement, skill/camel-test, skill/camel-verify] - name: camel-brainstorm user_invocable: false status: pipeline diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/DoctorCommandTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/DoctorCommandTest.java index 1b563392..22d1f984 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/DoctorCommandTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/DoctorCommandTest.java @@ -231,6 +231,12 @@ class DoctorCommandTest { Files.writeString(skillDir.resolve("SKILL.md"), "# " + skill + "\n"); } + for (String path : EXPECTATIONS.resources()) { + Path file = skills.resolve(path); + Files.createDirectories(file.getParent()); + Files.createFile(file); + } + Files.createDirectories(root.resolve(".bob")); Files.writeString(root.resolve(".bob/mcp.json"), mcpJson( diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/SkillResourceInstallerTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/SkillResourceInstallerTest.java index f29deace..78471f6a 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/SkillResourceInstallerTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/SkillResourceInstallerTest.java @@ -26,7 +26,7 @@ class SkillResourceInstallerTest { Body. """); - new SkillResourceInstaller().addCopilotReadableInternalSkillMetadata(skill); + new SkillResourceInstaller().addInternalSkillInvocationMetadata(skill, "copilot"); String content = Files.readString(skill); assertTrue(content.contains("user-invocable: false")); @@ -47,7 +47,7 @@ class SkillResourceInstallerTest { Body. """); - new SkillResourceInstaller().addPiReadableInternalSkillMetadata(skill); + new SkillResourceInstaller().addInternalSkillInvocationMetadata(skill, "pi"); String content = Files.readString(skill); assertTrue(content.contains("user-invocable: false")); diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java new file mode 100644 index 00000000..b670782d --- /dev/null +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java @@ -0,0 +1,293 @@ +package org.apache.camel.kit.workflow; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.camel.kit.doc.FrontmatterHandler; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class SkillPackCompilerTest { + + @TempDir + Path temp; + private static final String REVIEW = "List the routes that the validation run covered"; + private static final String SKILL = """ + --- + name: camel-inspect + description: Inspect an integration. + user_invocable: true + --- + Original instructions. + """; + + @Test + void defaultCatalogPreservesPublicCommandsInternalSkillsAndCoreResources() throws Exception { + var catalog = SkillCatalog.bundled(); + WorkflowManifest workflow = catalog.manifest().workflow(); + assertEquals(WorkflowManifestLoader.load(WorkflowManifestLoader.DEFAULT_RESOURCE), workflow); + assertEquals(Set.of("camel-start", "camel-brainstorm", "camel-plan", "camel-migrate", "camel-execute", + "camel-validate", "camel-debug", "camel-ship", "camel-knowledge"), + workflow.generatedCommandStubs().stream().map(c -> c.name()).collect(Collectors.toSet())); + assertEquals(Set.of("camel-test", "camel-design", "camel-implement", "camel-verify"), workflow.skills().stream() + .filter(s -> "internal".equals(s.status())).map(s -> s.name()).collect(Collectors.toSet())); + assertEquals("camel-validate/SKILL.md", + catalog.manifest().contributions().get("step/validate/report/timestamp").path()); + assertTrue(content(catalog, "camel-validate/SKILL.md").contains("Use the current date and time")); + assertArrayEquals(Files.readAllBytes(Path.of("src/main/resources/skills/shared/iron-laws.md")), + catalog.open("shared/iron-laws.md").readAllBytes()); + } + + @Test + void independentModuleAndDeclarationOrderProduceIdenticalCatalogs() throws Exception { + Path example = Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources").toRealPath(); + String skill = " skill/camel-inspect: {contract: 1, resource: SKILL.md}\n"; + String guide = " resource/camel-inspect/guides/inspect.md: {contract: 1, resource: guide.md}\n"; + String provider + = " provider/list: {contract: 1, provider: {service: java.util.List, implementation: java.util.ArrayList}}\n"; + Path pack = pack("inspect", "add:\n" + skill + guide + provider); + write("inspect", "SKILL.md", SKILL); + write("inspect", "guide.md", "Keep this guide."); + Path overlay = pack("team", + """ + requires: [inspect, core] + replace: + skill/camel-inspect: {contract: 1, resource: SKILL.md} + provider/list: {contract: 1, provider: {service: java.util.List, implementation: java.util.LinkedList}} + exclude: [step/validate/report/timestamp] + """); + write("team", "SKILL.md", SKILL.replace("Original", "Team")); + Path exampleJar = temp.resolve("report-review.jar"); + try (var zip = new ZipOutputStream(Files.newOutputStream(exampleJar)); var files = Files.walk(example)) { + for (Path path : files.filter(Files::isRegularFile).toList()) { + zip.putNextEntry(new ZipEntry(example.relativize(path).toString().replace('\\', '/'))); + Files.copy(path, zip); + zip.closeEntry(); + } + } + byte[] first; + try (var loader = loader(exampleJar, pack, overlay)) { + first = SkillPackCompiler.compile(loader, List.of("team", "report-review", "inspect")); + } + pack("inspect", "add:\n" + provider + guide + skill); + try (var loader = loader(overlay, pack, exampleJar)) { + assertArrayEquals(first, SkillPackCompiler.compile(loader, List.of("inspect", "team", "report-review"))); + } + Path distribution = temp.resolve("distribution"); + Path archive = distribution.resolve(SkillCatalog.DISTRIBUTION); + Files.createDirectories(archive.getParent()); + Files.write(archive, first); + // Consume the assembled distribution without any input pack directories or JARs on the runtime classpath. + try (var loader = loader(distribution)) { + SkillCatalog catalog = SkillCatalog.load(loader); + assertEquals("java.util.LinkedList", + catalog.manifest().contributions().get("provider/list").provider().implementation()); + String validate = content(catalog, "camel-validate/SKILL.md"); + assertTrue(validate.indexOf("## Validation Report\n") < validate.indexOf(REVIEW)); + assertTrue(validate.indexOf(REVIEW) < validate.indexOf("### Report Format")); + assertFalse(validate.contains("Use the current date and time for the timestamped filename")); + } + Path workspace = Files.createDirectory(temp.resolve("workspace")); + assertCli(0, distribution, workspace, "init", "--here", "--ai", "bob2", "--no-fetch"); + Path skills = workspace.resolve(".bob/skills"); + assertTrue(Files.readString(skills.resolve("camel-validate/SKILL.md")).contains(REVIEW)); + assertTrue(Files.readString(skills.resolve("camel-inspect/SKILL.md")).contains("Team instructions.")); + assertTrue(Files.readString(skills.resolve("camel-start/SKILL.md")) + .contains("/camel-inspect — Inspect an integration.")); + assertTrue(Files.readString(workspace.resolve(".bob/commands/camel-inspect.md")) + .contains(".bob/skills/camel-inspect/SKILL.md")); + Path installedGuide = skills.resolve("camel-inspect/guides/inspect.md"); + assertEquals("Keep this guide.", Files.readString(installedGuide)); + assertCli(0, distribution, workspace, "doctor"); + Files.delete(installedGuide); + assertTrue(assertCli(1, distribution, workspace, "doctor").contains("camel-inspect/guides/inspect.md")); + } + + @Test + void installsInternalSkillWithFlowStyleFrontmatterAndExampleMetadataInItsBody() throws Exception { + Path source = pack("library", "add: {skill/camel-reader: {contract: 1, resource: reader.md}}"); + write("library", "reader.md", """ + --- + {name: camel-reader, description: Read the route., user_invocable: false} + --- + + Example settings from an input project: + ```yaml + user-invocable: true + disable-model-invocation: false + ``` + """); + Path archive = temp.resolve(SkillCatalog.DISTRIBUTION); + Files.createDirectories(archive.getParent()); + try (var loader = loader(source)) { + Files.write(archive, SkillPackCompiler.compile(loader, List.of("library"))); + } + Path workspace = Files.createDirectory(temp.resolve("workspace")); + assertCli(0, temp, workspace, "init", "--here", "--ai", "claude", "--no-fetch"); + String installed = Files.readString(workspace.resolve(".claude/skills/camel-reader/SKILL.md")); + String yaml = FrontmatterHandler.extractFrontmatterYaml(installed); + var header = SkillPack.YAML.readTree(yaml); + assertFalse(header.get("user-invocable").booleanValue()); + assertTrue(header.get("disable-model-invocation").booleanValue()); + assertTrue(installed.contains("```yaml\nuser-invocable: true\ndisable-model-invocation: false\n```")); + } + + @Test + void excludingAPackSkillRemovesItsCommandRouteAndOwnedGuides() throws Exception { + Path pack = pack("inspect", """ + add: + skill/camel-inspect: {contract: 1, resource: SKILL.md} + resource/camel-inspect/guides/extra.md: {contract: 1, resource: extra.md} + """); + write("inspect", "SKILL.md", SKILL); + write("inspect", "extra.md", "Extra."); + Path overlay = pack("small", "requires: [inspect]\nexclude: [skill/camel-inspect]\n"); + Path out = temp.resolve(SkillCatalog.DISTRIBUTION); + Files.createDirectories(out.getParent()); + try (var loader = loader(pack, overlay)) { + Files.write(out, SkillPackCompiler.compile(loader, List.of("small", "inspect"))); + } + try (var loader = loader(temp)) { + var catalog = SkillCatalog.load(loader); + assertFalse(catalog.paths().stream().anyMatch(s -> s.startsWith("camel-inspect/"))); + assertFalse( + catalog.manifest().workflow().commands().stream().anyMatch(c -> c.name().equals("camel-inspect"))); + assertFalse(content(catalog, "camel-start/SKILL.md").contains("/camel-inspect")); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "requires: [absent]|absent", + "requires: [bad]|bad -> bad", + "add: {skill/camel-start: {contract: 1, resource: start.md}}|core: skill/camel-start", + "add: {step/validate/report/id: {contract: 2, resource: guide.md}}|unsupported contribution contract 2", + "add: {step/validate/report/id: {contract: 1.5, resource: guide.md}}|1.5", + "add: {step/validate/missing/id: {contract: 1, resource: guide.md}}|validate/missing", + "add: {step/missing/report/id: {contract: 1, resource: guide.md}}|unknown workflow stage missing", + "add: {step/validate/report/id: {contract: 1, resource: missing.md}}|missing.md", + "add: {resource/absent/guide.md: {contract: 1, resource: guide.md}}|requires effective skill/absent", + "add: {provider/check: {contract: 1, provider: {service: java.lang.Runnable, implementation: no.SuchClass}}}|no.SuchClass", + "add: {provider/check: {contract: 1, provider: {service: java.lang.Runnable, implementation: java.util.ArrayList}}}|implementation of java.lang.Runnable", + "exclude: [skill/unknown]|no such contribution", + "exclude: [skill/camel-start]|requires must name", + "requires: [core]\nexclude: [skill/camel-start]|route", + "add: {step/validate/report/id: {contract: 1, resource: guide.md, requires: [provider/missing]}}|requires missing contribution provider/missing", + "unknown: true|unknown", + "exclude: []\nexclude: []|Duplicate" + }) + void malformedDeclarationsIdentifyTheFailure(String scenario) throws Exception { + String[] parts = scenario.split("\\|"); + Path pack = pack("bad", parts[0]); + write("bad", "guide.md", "Additional guidance."); + write("bad", "start.md", SKILL.replace("camel-inspect", "camel-start")); + try (var loader = loader(pack)) { + var failure = assertThrows(IOException.class, () -> SkillPackCompiler.compile(loader, List.of("bad"))); + assertTrue(failure.getMessage().contains(parts[1]), failure::getMessage); + } + } + + @Test + void rejectsCompetingReplacementsAndAmbiguousResourceOrigins() throws Exception { + String replace = """ + requires: [core] + replace: + step/validate/report/timestamp: {contract: 1, resource: guide.md} + """; + Path one = pack("one", replace); + Path two = pack("two", replace); + write("one", "guide.md", "One."); + write("two", "guide.md", "Two."); + try (var loader = loader(two, one)) { + IOException failure + = assertThrows(IOException.class, () -> SkillPackCompiler.compile(loader, List.of("two", "one"))); + assertTrue(failure.getMessage().contains("two: step/validate/report/timestamp: conflicts with one:"), + failure::getMessage); + } + Path other = temp.resolve("other"); + Path duplicate = other.resolve(SkillPack.directory("one")).resolve("guide.md"); + Files.createDirectories(duplicate.getParent()); + Files.writeString(duplicate, "Ambiguous."); + try (var loader = loader(one, other)) { + IOException failure + = assertThrows(IOException.class, () -> SkillPackCompiler.compile(loader, List.of("one"))); + assertTrue(failure.getMessage().contains("one: step/validate/report/timestamp: Expected one resource"), + failure::getMessage); + } + } + + @Test + void rejectsDuplicatePackIdsUnsupportedSchemasAndIncompatibleProviderReplacements() throws Exception { + Path source = pack("upstream", + "add: {provider/check: {contract: 1, provider: {service: java.util.List, implementation: java.util.ArrayList}}}"); + Path overlay = pack("team", """ + requires: [upstream] + replace: + provider/check: {contract: 1, provider: {service: java.util.Set, implementation: java.util.HashSet}} + """); + try (var loader = loader(source, overlay)) { + var duplicate = assertThrows(IOException.class, + () -> SkillPackCompiler.compile(loader, List.of("upstream", "upstream"))); + assertTrue(duplicate.getMessage().contains("duplicate selected pack ID: upstream"), duplicate::getMessage); + var service = assertThrows(IOException.class, + () -> SkillPackCompiler.compile(loader, List.of("upstream", "team"))); + assertTrue(service.getMessage().contains( + "team: provider/check: replacement must preserve service java.util.List declared by upstream:"), + service::getMessage); + write("team", "pack.yaml", "id: team\nschema: 9\n"); + var schema = assertThrows(IOException.class, () -> SkillPackCompiler.compile(loader, List.of("team"))); + assertTrue(schema.getMessage().contains("'team' schema 9"), schema::getMessage); + } + } + + private Path pack(String id, String yaml) throws IOException { + write(id, "pack.yaml", "id: " + id + "\nschema: 1\n" + yaml + "\n"); + return temp.resolve(id); + } + + private void write(String id, String file, String text) throws IOException { + Path path = temp.resolve(id).resolve(SkillPack.directory(id)).resolve(file); + Files.createDirectories(path.getParent()); + Files.writeString(path, text); + } + + private static URLClassLoader loader(Path... modules) throws IOException { + List<URL> urls = new ArrayList<>(); + for (Path module : modules) { + urls.add(module.toUri().toURL()); + } + return new URLClassLoader(urls.toArray(URL[]::new), SkillPackCompilerTest.class.getClassLoader()); + } + + private static String content(SkillCatalog catalog, String file) throws IOException { + return new String(catalog.open(file).readAllBytes(), StandardCharsets.UTF_8); + } + + private static String assertCli(int status, Path distribution, Path cwd, String... args) throws Exception { + String classpath = distribution + File.pathSeparator + System.getProperty("java.class.path"); + List<String> command = new ArrayList<>( + List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", classpath, "org.apache.camel.kit.CamelKitMain")); + command.addAll(List.of(args)); + Process process = new ProcessBuilder(command).directory(cwd.toFile()).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertEquals(status, process.waitFor(), output); + return output; + } +} diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowManifestTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowManifestTest.java index 15123e9e..22f8de08 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowManifestTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowManifestTest.java @@ -144,6 +144,13 @@ class WorkflowManifestTest { assertTrue(executeSkill.contains("full verification report")); } + @Test + void rejectsDuplicateFieldsInTheCorePackInput() { + IOException failure + = assertThrows(IOException.class, () -> loadManifest(MINIMAL_VALID_MANIFEST + "\nversion: 2\n")); + assertTrue(failure.getMessage().contains("Duplicate field 'version'"), failure::getMessage); + } + @Test void loadsMinimalValidManifest() { WorkflowManifest manifest = assertDoesNotThrow(() -> loadManifest(MINIMAL_VALID_MANIFEST));
