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 5292ce3ebc6730a038b45a20913b34384728c80a Author: Luigi De Masi <[email protected]> AuthorDate: Mon Nov 23 19:35:31 2026 +0100 Fix #196: Verify assistant workflow hook results Resolve an executable step against a handler that declares support for its contribution ID. Bind skill and Java results to the selected catalog, target, source files, evidence revisions and confirmed decisions. Provide a stateless CLI on both hosts, an executable example pack and tests for pending, failed, stale and verified results. Co-authored-by: OpenAI Codex <[email protected]> --- CHANGELOG.md | 3 + docs/architecture.md | 5 + docs/commands.md | 8 + .../camel-kit/packs/report-review/coverage.md | 9 + .../camel-kit/packs/report-review/coverage.py | 25 +++ .../camel-kit/packs/report-review/pack.yaml | 14 ++ docs/modules/ROOT/pages/architecture.adoc | 10 +- docs/modules/ROOT/pages/commands.adoc | 14 +- docs/modules/ROOT/pages/contributing.adoc | 52 ++++- docs/modules/ROOT/pages/skills.adoc | 34 ++++ .../org/apache/camel/kit/jbang/CamelKitPlugin.java | 2 + .../apache/camel/kit/jbang/CamelKitPluginTest.java | 12 ++ .../java/org/apache/camel/kit/CamelKitMain.java | 2 + .../org/apache/camel/kit/command/HookCommand.java | 45 +++++ .../apache/camel/kit/workflow/SkillCatalog.java | 46 ++++- .../org/apache/camel/kit/workflow/SkillPack.java | 13 +- .../camel/kit/workflow/SkillPackCompiler.java | 23 ++- .../apache/camel/kit/workflow/WorkflowHook.java | 61 ++++++ .../camel/kit/workflow/WorkflowHookProvider.java | 72 +++++++ .../camel/kit/workflow/WorkflowHookRunner.java | 215 +++++++++++++++++++++ .../camel/kit/workflow/SkillPackCompilerTest.java | 167 +++++++++++++++- .../camel/kit/workflow/WorkflowHookRunnerTest.java | 163 ++++++++++++++++ 22 files changed, 977 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40c9ac77..c878bd80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Run a distribution's required workflow hooks with `camel-kit hook` or `camel kit hook`. Bundled skills and Java + providers share a versioned result contract, including developer questions and checks bound to file revisions (#196). + - **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. After successful generation, reinitialization removes matching retired files, recognizes Git diff --git a/docs/architecture.md b/docs/architecture.md index dd20b967..6ef8c69c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -228,6 +228,11 @@ This graph-aware context complements file analysis with a bounded topology view ## 3. The Orchestration Model +A pack can bind a named step to a skill or a Java provider. Both receive the same versioned request and +return observations for required checks. The CLI binds acceptance to the current source and artifact bytes. +The caller handles pending decisions and ordinary stage sequencing. See the +[workflow hook contract](modules/ROOT/pages/contributing.adoc#implement-hook). + ### Pipeline The end-to-end pipeline follows a strict phase progression: diff --git a/docs/commands.md b/docs/commands.md index 89a3dd90..97385a16 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -16,6 +16,7 @@ retains its single CLI invocation with the supplied options. - [camel-kit doctor](#camel-kit-doctor) - [camel-kit graph](#camel-kit-graph) - [camel-kit doc](#camel-kit-doc) + - [camel-kit hook](#camel-kit-hook) - [camel-kit nextId](#camel-kit-nextid) - [Slash Commands](#slash-commands) - [/camel-start](#camel-start) @@ -417,6 +418,13 @@ camel-kit graph migration-context processOrders camel-kit graph migration-context processOrders --depth 5 ``` +### camel-kit hook + +Run `camel-kit hook --id <step-contribution> --input <caller.json>` from the project root. +For a skill handler, pass the emitted request to the selected skill and submit its response with +`--result <skill-result.json>`. Java handlers return their response directly. To relay a developer answer, supply the prior pending output with `--resume <pending.json>`. A verified pass exits zero. +See the [workflow hook guide](modules/ROOT/pages/skills.adoc#workflow-hooks). + ### camel-kit nextId Generate the next sequential pipeline ID and create the pipeline directory. diff --git a/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.md b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.md new file mode 100644 index 00000000..dbac2e0e --- /dev/null +++ b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.md @@ -0,0 +1,9 @@ +--- +name: camel-review-coverage +description: Check a validation suite's route inventory against a workflow hook request. +user_invocable: false +--- + +When invoked for the coverage hook, save the supplied request object as JSON in a temporary file. +From the project root, run `python3 <this skill directory>/guides/coverage.py <request file>`. +Return its JSON result to the caller for submission to Kit. The caller handles developer questions. diff --git a/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.py b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.py new file mode 100644 index 00000000..6d5ea804 --- /dev/null +++ b/docs/modules/ROOT/examples/skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.py @@ -0,0 +1,25 @@ +"""Example skill helper. Run from the project root with the hook request as its argument.""" +import json +import sys +from pathlib import Path + + +def review(request): + decisions = request["decisions"] + if not decisions: + return {"request": request, "status": "needs-input", + "question": "Which validation suite should cover these routes?"} + + suite = decisions[-1]["answer"] + inventory = Path(request["artifacts"]["inventory"]["path"]) + rows = inventory.read_text(encoding="utf-8").splitlines() + covered = {row.removeprefix(suite + "\t") for row in rows if row.startswith(suite + "\t")} + missing = sorted(request["sources"].keys() - covered) + evidence = (f"Suite {suite}: missing {', '.join(missing)}" if missing + else f"Suite {suite} covers all {len(request['sources'])} scoped routes in {inventory}.") + return {"request": request, "status": "failed" if missing else "passed", + "checks": {"route-coverage": {"passed": not missing, "evidence": evidence}}} + + +if __name__ == "__main__": + print(json.dumps(review(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))))) 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 index 1ca7b6bf..367d08d5 100644 --- 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 @@ -5,3 +5,17 @@ add: step/validate/report/review: contract: 1 resource: review.md + skill/camel-review-coverage: + contract: 1 + resource: coverage.md + handles: [step/validate/report/coverage] + requires: [resource/camel-review-coverage/guides/coverage.py] + resource/camel-review-coverage/guides/coverage.py: + contract: 1 + resource: coverage.py + step/validate/report/coverage: + contract: 1 + hook: + handler: skill/camel-review-coverage + targets: [quarkus, spring-boot] + checks: {route-coverage: inventory} diff --git a/docs/modules/ROOT/pages/architecture.adoc b/docs/modules/ROOT/pages/architecture.adoc index 58548ee8..ca9ab455 100644 --- a/docs/modules/ROOT/pages/architecture.adoc +++ b/docs/modules/ROOT/pages/architecture.adoc @@ -81,9 +81,13 @@ composed instructions at the declared step. Public pack skills appear in the ins tree and in host instructions that list direct commands. 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]. +An executable step names one bundled skill or Java provider, the supported targets and its required checks. +The assistant supplies the source scope, selected target and evidence paths. Kit resolves the handler and binds +the request to the SHA-256 of each file. Both kinds of handler use the same request and result. +The provider chooses its helper calls and their order. Kit checks the returned binding and required evidence +against the caller's current files. The assistant uses that outcome to sequence ordinary stages. +A direct call returns to its caller. Ship's controller owns its durable state and stage transitions. +See xref:skills.adoc#workflow-hooks[handling a pending or failed hook]. The committed ownership ledger records the installed content after host-specific changes. A catalog switch retires matching files after generating the replacement assets. An owned file can become a directory of guides or a diff --git a/docs/modules/ROOT/pages/commands.adoc b/docs/modules/ROOT/pages/commands.adoc index c3957263..3b8dd4e4 100644 --- a/docs/modules/ROOT/pages/commands.adoc +++ b/docs/modules/ROOT/pages/commands.adoc @@ -9,7 +9,7 @@ CLI, "Use the `/camel-start` skill" in GitHub Copilot CLI, `/skill:camel-start` [[cli]] == CLI commands -Development builds use Aesh for one-shot execution. Use `-h`/`--help` on the root, `init`, `doctor` or `ship`, +Development builds use Aesh for one-shot execution. Use `-h`/`--help` on the root, `init`, `doctor`, `hook` or `ship`, and the `help` subcommand for `doc`, `graph` and `plan`. Use `-V`/`--version` at the CLI root for the Kit version. See xref:getting-started.adoc#cli-host[development host compatibility]. `init -p one=1 two=2` accepts several property values; Ship's `-p` consumes one value per occurrence. @@ -171,6 +171,18 @@ camel-kit doc stale --reason "design spec was amended" --cascade \ camel-kit doc unstale docs/camel-kit/001-order-processing/implementation-plan.md ---- +[[hook]] +=== hook + +Run a required assistant workflow contribution from the project root. + +---- +camel-kit hook --id <step-contribution> --input <caller.json> [--resume <pending.json>] [--result <skill-result.json>] +---- + +The CLI prints a JSON request for an installed skill or invokes the bundled Java provider. Only a verified +`passed` result exits zero. See xref:skills.adoc#workflow-hooks[responding to a question or failed check]. + [[graph]] === graph diff --git a/docs/modules/ROOT/pages/contributing.adoc b/docs/modules/ROOT/pages/contributing.adoc index c0fd3889..c8ef4d61 100644 --- a/docs/modules/ROOT/pages/contributing.adoc +++ b/docs/modules/ROOT/pages/contributing.adoc @@ -99,7 +99,7 @@ steps and providers start with a lowercase ASCII letter and continue with lowerc 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. +The example distribution adds report guidance and a required route-coverage check to validation. .pack.yaml [source,yaml] @@ -156,7 +156,7 @@ Other resources and files containing a NUL byte or invalid UTF-8 must match the | `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. +key order. Set `hook` to require an executable check at that point. 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 @@ -182,6 +182,54 @@ replace: requires: [resource/camel-validate/guides/report-format.md] ---- +[[implement-hook]] +=== Implement a workflow hook + +A step declares either a guidance resource or a `hook`. Its `handler` selects one effective `skill/<id>` or +`provider/<id>`. The handler advertises that step ID in its own `handles` list. The compiler checks the match and records the dependency. List supported target IDs in `targets` and map each +mandatory check ID to an evidence artifact role in `checks`. Use the same lowercase ID syntax as pack IDs. +A replacement can switch the implementation while preserving the targets and checks. + +The caller supplies workspace-relative file paths with `/` separators. Each source and evidence path must refer +to a regular file within the project through directories without symbolic links. Artifact keys must match the +declared roles exactly. The CLI prepares a version 1 request containing the step and handler identities, their +owning packs, the assembled catalog SHA-256, the skill entry or Java class, target, source paths and SHA-256 digests, artifact paths and SHA-256 +digests, check-to-role map and ordered list of confirmed questions and answers. + +A skill returns a JSON object with the following fields. A Java implementation of +`org.apache.camel.kit.workflow.WorkflowHookProvider` receives the project root and the same typed `Request` +and returns a `Result`. Both handlers can call their own helpers. + +[cols="1,4"] +|=== +| Field | Value +| `request` | Echo the entire request object supplied by Kit. +| `status` | `needs-input`, `failed` or `passed`. +| `question` | A nonblank question for `needs-input`. Omit or use `null` for a terminal result. +| `checks` | Omit or use an empty object while awaiting a decision. For a terminal result, provide exactly the +declared IDs, each with a boolean `passed` and nonblank `evidence` describing the observation for its assigned +artifact. A failure identifies at least one failed check. +|=== + +For example, the bundled example skill reads the inventory as tab-separated suite and source-path pairs. +It asks which suite to use, then checks that every source appears in that suite. Its Python helper returns +`{"passed":false,"evidence":"Suite integration: missing routes/orders.yaml"}` under `checks.route-coverage` +when the inventory omits the route. See xref:skills.adoc#workflow-hooks[invocation and diagnostics]. + +To use a compiled handler, package a public implementation with a public zero-argument constructor on the +distribution classpath, declare it as below, and set the step's `hook.handler` to `provider/coverage`. + +[source,yaml] +---- +add: + provider/coverage: + contract: 1 + handles: [step/validate/report/coverage] + provider: + service: org.apache.camel.kit.workflow.WorkflowHookProvider + implementation: example.CoverageProvider +---- + === Build and try the example From the repository root, build Kit and then package the example against the installed Kit version. diff --git a/docs/modules/ROOT/pages/skills.adoc b/docs/modules/ROOT/pages/skills.adoc index 2eef4795..032cb584 100644 --- a/docs/modules/ROOT/pages/skills.adoc +++ b/docs/modules/ROOT/pages/skills.adoc @@ -35,6 +35,40 @@ the composition primitives the stages assemble. `camel-ship` is the outlier of i delegate that invokes the registered `camel-kit ship` command once and does not follow the guide-based structure described below. +[[workflow-hooks]] +== Running a required workflow hook + +When an installed stage names a hook, use the CLI invocation in that step with the distribution that installed it. +From the project root, write the caller's input file with the complete list of in-scope source files, the selected +target and the existing evidence file for each named artifact role. Keep the input under the caller's control. + +[source,json] +---- +{"sources":["routes/orders.yaml"],"target":"quarkus","artifacts":{"inventory":"coverage.tsv"}} +---- + +[source,shell] +---- +camel-kit hook --id step/validate/report/coverage --input input.json +---- + +* On `invoke-skill`, pass the emitted `request` object to the named installed skill. The `implementation` path + is relative to the host's skills directory. Submit the returned JSON using the same command with + `--result result.json`. Kit dispatches a Java handler directly. +* On `needs-input`, save the CLI's pending output in a separate file. Ask the developer its `question`, put the confirmed + answer in the input's `answer` string and invoke the same hook with `--resume pending.json`. Keep that option + when submitting the skill result. Kit checks the pending request against the current binding and includes + the question and answer in the provider's `decisions` list. Save each new pending output separately if more + questions follow. If the binding changes, start a fresh request and confirm the decision for the new inputs. +* On `failed`, inspect the named checks and their observations. Correct the source or evidence and rerun. + For a missing check, return an observation for the required ID. For a stale request, obtain a fresh request and + repeat the check against the current files. For an unsupported target or handler, check the distribution's pack declaration. +* Only exit code zero with `passed` satisfies this contribution. Return the outcome to the calling skill or + developer. The assistant decides when the ordinary stage's other requirements are also complete. + +The verifier checks the provider's observations for completeness and binds them to the selected files. +The provider performs the domain check. See xref:contributing.adoc#implement-hook[implementing a handler]. + [[shared-guides]] == Shared guides diff --git a/kit/camel-jbang-plugin-kit/src/main/java/org/apache/camel/kit/jbang/CamelKitPlugin.java b/kit/camel-jbang-plugin-kit/src/main/java/org/apache/camel/kit/jbang/CamelKitPlugin.java index abb524ff..a4601db4 100644 --- a/kit/camel-jbang-plugin-kit/src/main/java/org/apache/camel/kit/jbang/CamelKitPlugin.java +++ b/kit/camel-jbang-plugin-kit/src/main/java/org/apache/camel/kit/jbang/CamelKitPlugin.java @@ -6,6 +6,7 @@ import org.apache.camel.dsl.jbang.core.common.CommandTree; import org.apache.camel.dsl.jbang.core.common.Plugin; import org.apache.camel.kit.CamelKitMain; import org.apache.camel.kit.command.DoctorCommand; +import org.apache.camel.kit.command.HookCommand; import org.apache.camel.kit.command.InitCommand; import org.apache.camel.kit.command.doc.DocCommand; import org.apache.camel.kit.command.graph.GraphCommand; @@ -27,6 +28,7 @@ public class CamelKitPlugin implements Plugin { .addSubcommand("init", new CommandTree(new InitCommand(camelKitMain))) .addSubcommand("doctor", new CommandTree(new DoctorCommand(camelKitMain))) .addSubcommand("doc", new CommandTree(new DocCommand())) + .addSubcommand("hook", new CommandTree(new HookCommand())) .addSubcommand("graph", new CommandTree(new GraphCommand())) .addSubcommand("plan", new CommandTree(new PlanCommand())) .addSubcommand("nextId", new CommandTree(new NextIdCommand())) diff --git a/kit/camel-jbang-plugin-kit/src/test/java/org/apache/camel/kit/jbang/CamelKitPluginTest.java b/kit/camel-jbang-plugin-kit/src/test/java/org/apache/camel/kit/jbang/CamelKitPluginTest.java index 9ac8fb9d..2d91f51c 100644 --- a/kit/camel-jbang-plugin-kit/src/test/java/org/apache/camel/kit/jbang/CamelKitPluginTest.java +++ b/kit/camel-jbang-plugin-kit/src/test/java/org/apache/camel/kit/jbang/CamelKitPluginTest.java @@ -62,6 +62,18 @@ class CamelKitPluginTest { assertInstanceOf(NextIdCommand.class, kit.getSubcommands().get("nextId").getCommand()); } + @Test + void hookIsDiscoverableThroughTheCamelHost() throws Exception { + var main = new CamelJBangMain(); + var root = new CommandTree(main); + new CamelKitPlugin().customize(root, main); + var output = new StringWriter(); + root.setOutput(output::write); + assertEquals(0, root.execute("kit", "hook", "--help").getResultValue()); + assertTrue(output.toString().contains("--result"), output::toString); + assertTrue(output.toString().contains("camel kit hook"), output::toString); + } + @Test void acceptsHostEscapedLiteralShipContextAndCamelArgumentFiles() throws Exception { Path context = Files.writeString(tempDir.resolve("ship-context"), "EXPANDED VALUE"); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/CamelKitMain.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/CamelKitMain.java index 6c852a0a..51a855e0 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/CamelKitMain.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/CamelKitMain.java @@ -6,6 +6,7 @@ import java.nio.file.Path; import org.apache.camel.kit.command.DoctorCommand; import org.apache.camel.kit.command.HelpAwareCommand; +import org.apache.camel.kit.command.HookCommand; import org.apache.camel.kit.command.InformationOptionParser; import org.apache.camel.kit.command.InitCommand; import org.apache.camel.kit.command.doc.DocCommand; @@ -175,6 +176,7 @@ public class CamelKitMain extends HelpAwareCommand { .addSubcommand("init", new InitCommand(main)) .addSubcommand("doctor", new DoctorCommand(main)) .addSubcommand("doc", new DocCommand()) + .addSubcommand("hook", new HookCommand()) .addSubcommand("graph", new GraphCommand()) .addSubcommand("plan", new PlanCommand()) .addSubcommand("nextId", new NextIdCommand()) diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/HookCommand.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/HookCommand.java new file mode 100644 index 00000000..d85ff1c1 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/HookCommand.java @@ -0,0 +1,45 @@ +package org.apache.camel.kit.command; + +import java.nio.file.Path; +import java.util.Objects; + +import org.apache.camel.kit.workflow.SkillCatalog; +import org.apache.camel.kit.workflow.WorkflowHookRunner; + +import org.aesh.command.CommandDefinition; +import org.aesh.command.option.Option; + +@CommandDefinition(name = "hook", generateHelp = true, + description = "Invoke a bundled workflow hook or verify its skill result") +public class HookCommand extends HelpAwareCommand { + @Option(parser = KitOptionParser.class, required = true, description = "Declared step contribution ID") + String id; + + @Option(parser = KitOptionParser.class, required = true, converter = PathConverter.class, + description = "Caller-owned JSON with sources, target, artifacts and optional confirmed answer") + Path input; + + @Option(parser = KitOptionParser.class, converter = PathConverter.class, + description = "JSON result from the requested skill") + Path result; + + @Option(parser = KitOptionParser.class, converter = PathConverter.class, + description = "Prior needs-input JSON for the confirmed answer") + Path resume; + + @Override + public Integer call() { + if (helpRequested) { + out.print(invocation.getHelpInfo()); + return 0; + } + try { + var outcome = new WorkflowHookRunner(SkillCatalog.bundled(), Path.of(".")).run(id, input, result, resume); + out.println(WorkflowHookRunner.toJson(outcome)); + return outcome.status().equals("passed") ? 0 : 1; + } catch (Exception | LinkageError e) { + err.println(id + ": " + Objects.toString(e.getMessage(), e.toString())); + return 1; + } + } +} 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 index 63a6b0b9..80b199f6 100644 --- 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 @@ -13,6 +13,7 @@ import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -28,8 +29,15 @@ public final class SkillCatalog { public record Provider(String service, String implementation) { } - public record Binding(String pack, int contract, List<String> requires, String path, Provider provider) { + public record Binding(String pack, int contract, List<String> requires, String path, Provider provider, + @JsonInclude(JsonInclude.Include.NON_NULL) WorkflowHook hook, + @JsonInclude(JsonInclude.Include.NON_EMPTY) List<String> handles) { + public Binding(String pack, int contract, List<String> requires, String path, Provider provider) { + this(pack, contract, requires, path, provider, null, List.of()); + } + public Binding { + handles = handles == null ? List.of() : List.copyOf(handles); requires = List.copyOf(requires); } } @@ -42,10 +50,11 @@ public final class SkillCatalog { } } + private final String archiveSha256; private final Manifest manifest; private final Map<String, byte[]> files; - SkillCatalog(Manifest manifest, Map<String, byte[]> files) throws IOException { + SkillCatalog(Manifest manifest, Map<String, byte[]> files, String archiveSha256) throws IOException { if (manifest.contract() != 1) { throw new IOException("Unsupported skill catalog contract: " + manifest.contract()); } @@ -61,9 +70,29 @@ public final class SkillCatalog { 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)) { + || (binding.provider() == null + ? binding.path() == null || !files.containsKey(binding.path()) : binding.path() != null)) { throw new IOException("Invalid bundled contribution " + binding.pack() + ": " + entry.getKey()); } + if (!binding.handles().isEmpty() && (!(entry.getKey().startsWith("skill/") + || entry.getKey().startsWith("provider/") && binding.provider() != null + && WorkflowHookProvider.class.getName().equals(binding.provider().service())) + || binding.handles().stream().anyMatch(key -> !key.matches(WorkflowHook.STEP)) + || Set.copyOf(binding.handles()).size() != binding.handles().size())) { + throw new IOException(binding.pack() + ": invalid handles declaration on " + entry.getKey()); + } + WorkflowHook hook = binding.hook(); + if (hook != null) { + hook.validate(entry.getKey()); + String stage = entry.getKey().split("/")[1]; + boolean atStage = manifest.workflow().stages().stream().anyMatch(s -> s.id().equals(stage) + && (s.skill() + "/SKILL.md").equals(binding.path())); + if (!atStage || !binding.requires().contains(hook.handler()) + || !hook.supports(entry.getKey(), manifest.contributions().get(hook.handler()), skills)) { + throw new IOException( + binding.pack() + ": " + entry.getKey() + ": unsupported hook handler " + hook.handler()); + } + } } // 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); @@ -88,10 +117,15 @@ public final class SkillCatalog { } } } + this.archiveSha256 = archiveSha256; this.manifest = manifest; this.files = Collections.unmodifiableMap(new TreeMap<>(files)); } + String archiveSha256() { + return archiveSha256; + } + public Manifest manifest() { return manifest; } @@ -127,7 +161,8 @@ public final class SkillCatalog { 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())) { + try (var archive = WorkflowHookProvider.Revision.hashing(urls.getFirst().openStream()); + var stream = new ZipInputStream(archive)) { Manifest manifest = null; Map<String, byte[]> files = new TreeMap<>(); for (ZipEntry entry; (entry = stream.getNextEntry()) != null;) { @@ -142,7 +177,8 @@ public final class SkillCatalog { if (manifest == null) { throw new IOException("Missing " + MANIFEST + " in " + urls); } - return new SkillCatalog(manifest, files); + return new SkillCatalog( + manifest, files, WorkflowHookProvider.Revision.finishDigest(archive)); } } } 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 index d02ff6b1..75430048 100644 --- 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 @@ -30,8 +30,10 @@ record SkillPack(String id, int schema, List<String> requires, Map<String, Entry .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) { + record Entry(int contract, String resource, SkillCatalog.Provider provider, List<String> requires, + WorkflowHook hook, List<String> handles) { Entry { + handles = handles == null ? List.of() : List.copyOf(handles); requires = requires == null ? List.of() : List.copyOf(requires); } } @@ -156,6 +158,15 @@ record SkillPack(String id, int schema, List<String> requires, Map<String, Entry throw edit.error("replacement must preserve service " + original.entry().provider().service() + " declared by " + original.location()); } + WorkflowHook originalHook = original.entry().hook(); + if (originalHook != null && edit.entry() != null) { + WorkflowHook replacement = edit.entry().hook(); + if (replacement == null || !replacement.checks().equals(originalHook.checks()) + || !Set.copyOf(replacement.targets()).equals(Set.copyOf(originalHook.targets()))) { + throw edit.error( + "replacement must preserve hook targets and checks declared by " + original.location()); + } + } if (edit.entry() == null) { if (edit.kind().equals("skill")) { for (var stage : workflow.stages()) { 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 index 18f22f5c..65883efd 100644 --- 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 @@ -109,7 +109,9 @@ public final class SkillPackCompiler { } path = skill + "/SKILL.md"; steps.computeIfAbsent(parts[0] + "/" + parts[1], unused -> new ArrayList<>()) - .add(new String(resources.get(d), StandardCharsets.UTF_8).strip()); + .add(d.entry().hook() == null + ? new String(resources.get(d), StandardCharsets.UTF_8).strip() + : d.entry().hook().instructions(d.key())); } case "provider" -> path = null; default -> throw d.error("unknown contribution kind"); @@ -119,17 +121,21 @@ public final class SkillPackCompiler { SkillPack.requireContribution(d, key, entries, packs); } bindings.put(d.key(), - new SkillCatalog.Binding(d.pack(), d.entry().contract(), requires, path, d.entry().provider())); + new SkillCatalog.Binding( + d.pack(), d.entry().contract(), requires, path, d.entry().provider(), d.entry().hook(), + d.entry().handles())); } 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)); + return archive(new SkillCatalog(manifest, files, null)); } private List<String> requirements(Declaration declaration, String path, Map<String, Declaration> definitions) { var requires = new TreeSet<>(declaration.entry().requires()); - if (path != null && path.endsWith(".md")) { + if (declaration.entry().hook() != null) { + requires.add(declaration.entry().hook().handler()); + } else if (path != null && path.endsWith(".md")) { String owner = path.substring(0, path.indexOf('/')); Matcher links = GUIDE_REFERENCE.matcher(new String(resources.get(declaration), StandardCharsets.UTF_8)); while (links.find()) { @@ -235,7 +241,7 @@ public final class SkillPackCompiler { } requires = skill.requires(); } - var d = new Declaration("core", key, new Entry(1, "skills/" + path, null, requires)); + var d = new Declaration("core", key, new Entry(1, "skills/" + path, null, requires, null, List.of())); base.put(key, d); resources.put(d, Files.readAllBytes(file)); } @@ -252,6 +258,13 @@ public final class SkillPackCompiler { if (e.contract() != 1) { throw d.error("unsupported contribution contract " + e.contract() + " (expected 1)"); } + if (e.hook() != null) { + e.hook().validate(d.key()); + if (e.resource() != null || e.provider() != null) { + throw d.error("hook takes the place of step instruction resources"); + } + continue; + } String id = SkillPack.ID; if (d.key().matches("provider/" + id)) { if (e.provider() == null || e.resource() != null) { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHook.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHook.java new file mode 100644 index 00000000..69561759 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHook.java @@ -0,0 +1,61 @@ +package org.apache.camel.kit.workflow; + +import java.io.IOException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** Contract 1 for a required check at a named assistant-led workflow step. */ +public record WorkflowHook(String handler, List<String> targets, Map<String, String> checks) { + static final String STEP = "step/" + SkillPack.ID + "/" + SkillPack.ID + "/" + SkillPack.ID; + + public WorkflowHook { + targets = targets == null ? List.of() : List.copyOf(targets); + checks = checks == null ? Map.of() : Map.copyOf(checks); + } + + void validate(String key) throws IOException { + if (!key.matches(STEP) + || handler == null || !handler.matches("(skill|provider)/" + SkillPack.ID)) { + throw new IOException(key + ": hook requires one skill/<id> or provider/<id> handler at a named step"); + } + if (targets.isEmpty() || targets.stream().anyMatch(t -> !t.matches(SkillPack.ID)) + || Set.copyOf(targets).size() != targets.size()) { + throw new IOException(key + ": declare distinct supported target IDs"); + } + if (checks.isEmpty() || checks.entrySet().stream().anyMatch(c -> !c.getKey().matches(SkillPack.ID) + || !c.getValue().matches(SkillPack.ID))) { + throw new IOException(key + ": declare required check IDs and their evidence artifact roles"); + } + } + + boolean supports(String key, SkillCatalog.Binding binding, Set<String> skills) { + if (binding == null || !binding.handles().contains(key)) { + return false; + } + if (handler.startsWith("skill/")) { + String skill = handler.substring("skill/".length()); + return skills.contains(skill) && (skill + "/SKILL.md").equals(binding.path()) && binding.provider() == null; + } + return binding.provider() != null && WorkflowHookProvider.class.getName().equals(binding.provider().service()); + } + + String instructions(String key) { + return String.format(Locale.ROOT, + """ + Before completing this stage, run the required hook `%s` from the project root. + Write caller-owned input JSON with `sources` (all in-scope source file paths), `target` + (the selected target, one of %s), and `artifacts` (workspace-relative files by role). + The required checks and their evidence roles are %s. Use the Kit distribution that installed this step. + Run `{COMMAND_PREFIX} hook --id %s --input <input.json>`. On `invoke-skill`, invoke the named installed skill + with the emitted request. Submit its result with the same command plus `--result <result.json>`. + On `needs-input`, save that output, ask the developer its question, put their confirmed answer in + `input.answer`, and repeat the call with `--resume <pending-result.json>` for dispatch and submission. + Only a zero exit with status `passed` satisfies this hook. Return the outcome to the caller. + The assistant decides the next ordinary step. + """, + key, targets, new TreeMap<>(checks), key).stripTrailing(); + } +} diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookProvider.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookProvider.java new file mode 100644 index 00000000..58b141f8 --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookProvider.java @@ -0,0 +1,72 @@ +package org.apache.camel.kit.workflow; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Path; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; + +/** A bundled Java implementation of the same contract used for assistant-run skill submissions. */ +@FunctionalInterface +public interface WorkflowHookProvider { + Result invoke(Path project, Request request) throws Exception; + + /** SHA-256 covers the exact bytes at the project-relative path. */ + record Revision(String path, String sha256) { + static DigestInputStream hashing(InputStream input) { + try { + return new DigestInputStream(input, MessageDigest.getInstance("SHA-256")); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + static String finishDigest(DigestInputStream input) throws IOException { + input.transferTo(OutputStream.nullOutputStream()); + return HexFormat.of().formatHex(input.getMessageDigest().digest()); + } + } + + record Decision(String question, String answer) { + public Decision { + if (question == null || question.isBlank() || answer == null || answer.isBlank()) { + throw new IllegalArgumentException("A decision requires a question and its confirmed answer"); + } + } + } + + record Request(int contract, String catalogSha256, String contribution, String pack, String handler, + String handlerPack, + String implementation, String target, Map<String, String> sources, Map<String, Revision> artifacts, + Map<String, String> checks, List<Decision> decisions) { + public Request { + sources = Map.copyOf(sources); + artifacts = Map.copyOf(artifacts); + checks = Map.copyOf(checks); + decisions = List.copyOf(decisions); + } + + Request withDecisions(List<Decision> confirmed) { + return new Request( + contract, catalogSha256, contribution, pack, handler, handlerPack, implementation, target, sources, + artifacts, + checks, confirmed); + } + } + + /** The provider's observation for the artifact role assigned to this check in the request. */ + record Check(Boolean passed, String evidence) { + } + + /** Echo the request. Use passed, failed or needs-input. Only needs-input carries a question. */ + record Result(Request request, String status, Map<String, Check> checks, String question) { + public Result { + checks = checks == null ? Map.of() : Map.copyOf(checks); + } + } +} diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookRunner.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookRunner.java new file mode 100644 index 00000000..03fbdb9c --- /dev/null +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/WorkflowHookRunner.java @@ -0,0 +1,215 @@ +package org.apache.camel.kit.workflow; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.apache.camel.kit.workflow.WorkflowHookProvider.Check; +import org.apache.camel.kit.workflow.WorkflowHookProvider.Decision; +import org.apache.camel.kit.workflow.WorkflowHookProvider.Request; +import org.apache.camel.kit.workflow.WorkflowHookProvider.Result; +import org.apache.camel.kit.workflow.WorkflowHookProvider.Revision; + +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.cfg.CoercionAction; +import com.fasterxml.jackson.databind.cfg.CoercionInputShape; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.type.LogicalType; + +/** Stateless dispatch. Only the distribution selects executable code. The caller owns the inputs and sequencing. */ +public final class WorkflowHookRunner { + private static final JsonMapper JSON = JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) + .withCoercionConfig(LogicalType.Textual, config -> { + for (var shape : List.of(CoercionInputShape.Integer, CoercionInputShape.Float, + CoercionInputShape.Boolean)) { + config.setCoercion(shape, CoercionAction.Fail); + } + }).build(); + + private record Input(List<String> sources, String target, Map<String, String> artifacts, String answer) { + } + + public static String toJson(Result result) throws IOException { + return JSON.writeValueAsString(result); + } + + private final SkillCatalog catalog; + private final Path project; + + public WorkflowHookRunner(SkillCatalog catalog, Path project) throws IOException { + this.catalog = catalog; + this.project = project.toRealPath(); + } + + public Result run(String id, Path inputFile, Path submission, Path resume) throws Exception { + var entries = catalog.manifest().contributions(); + var step = entries.get(id); + if (step == null || step.hook() == null) { + throw new IOException("No executable hook declared for this contribution"); + } + var handler = entries.get(step.hook().handler()); + var provider = handler.provider(); + if (provider != null && submission != null) { + throw new IOException("requires Java dispatch to " + step.hook().handler()); + } + Result result; + if (submission != null) { + result = read(submission, Result.class); + } else { + Request request = request(id, step, handler, inputFile, resume); + if (provider == null) { + return new Result(request, "invoke-skill", Map.of(), null); + } + var type = Class.forName(provider.implementation(), false, WorkflowHookProvider.class.getClassLoader()) + .asSubclass(WorkflowHookProvider.class); + result = type.getConstructor().newInstance().invoke(project, request); + verifyRequest(request, result); + } + // Verify the caller's current inputs after reading the submission or executing bundled code. + Request expected = request(id, step, handler, inputFile, resume); + verifyRequest(expected, result); + if ("needs-input".equals(result.status())) { + requirePending(result); + } else { + if (!"passed".equals(result.status()) && !"failed".equals(result.status()) || result.question() != null) { + throw new IOException("expected passed, failed or needs-input result"); + } + if (!expected.checks().keySet().containsAll(result.checks().keySet())) { + throw new IOException("undeclared checks in " + result.checks().keySet()); + } + boolean failed = false; + for (String name : new TreeMap<>(expected.checks()).keySet()) { + Check check = result.checks().get(name); + if (check == null || check.passed() == null || blank(check.evidence())) { + throw new IOException("missing check or evidence for " + name); + } + failed |= !check.passed(); + if (!check.passed() && "passed".equals(result.status())) { + throw new IOException("check " + name + " failed: " + check.evidence()); + } + } + if (!failed && "failed".equals(result.status())) { + throw new IOException("provider reported failure with all checks passed"); + } + } + return result; + } + + private static void verifyRequest(Request expected, Result result) throws IOException { + if (result == null || result.request() == null) { + throw new IOException("Missing result request"); + } + if (!expected.equals(result.request())) { + ObjectNode current = JSON.valueToTree(expected); + ObjectNode submitted = JSON.valueToTree(result.request()); + var differences = current.properties().stream() + .filter(field -> !field.getValue().equals(submitted.get(field.getKey()))) + .map(Map.Entry::getKey).sorted().toList(); + throw new IOException("Stale or mismatched result request fields: " + differences); + } + } + + private Request request(String id, SkillCatalog.Binding step, SkillCatalog.Binding handler, Path file, Path resume) + throws IOException { + Input input = read(file, Input.class); + WorkflowHook hook = step.hook(); + if (input.target() == null || !hook.targets().contains(input.target())) { + throw new IOException( + "unsupported target " + input.target() + ", expected one of " + hook.targets()); + } + if (input.sources() == null || input.sources().isEmpty()) { + throw new IOException("sources must name the files in scope"); + } + if (input.answer() != null && input.answer().isBlank()) { + throw new IOException("confirmed answer must be nonblank"); + } + var roles = Set.copyOf(hook.checks().values()); + if (input.artifacts() == null || !roles.equals(input.artifacts().keySet())) { + throw new IOException( + "expected artifact roles " + roles + ", received " + + (input.artifacts() == null ? "none" : input.artifacts().keySet())); + } + Map<String, String> sources = new TreeMap<>(); + for (String source : input.sources()) { + Revision revision = revision("source", source); + if (sources.put(source, revision.sha256()) != null) { + throw new IOException("Duplicate source path: " + source); + } + } + Map<String, Revision> artifacts = new TreeMap<>(); + for (var artifact : input.artifacts().entrySet()) { + artifacts.put(artifact.getKey(), revision(artifact.getKey(), artifact.getValue())); + } + String implementation = handler.provider() == null ? handler.path() : handler.provider().implementation(); + Request current = new Request( + step.contract(), catalog.archiveSha256(), id, step.pack(), hook.handler(), handler.pack(), + implementation, + input.target(), sources, artifacts, hook.checks(), List.of()); + if (resume == null && input.answer() == null) { + return current; + } + if (resume == null || blank(input.answer())) { + throw new IOException("A confirmed answer and --resume <pending-result.json> must be supplied together"); + } + Result pending = read(resume, Result.class); + requirePending(pending); + var previous = pending.request().decisions(); + verifyRequest(current.withDecisions(previous), pending); + var decisions = new ArrayList<>(previous); + decisions.add(new Decision(pending.question(), input.answer())); + return current.withDecisions(decisions); + } + + private static void requirePending(Result result) throws IOException { + if (!"needs-input".equals(result.status()) || result.request() == null + || blank(result.question()) || !result.checks().isEmpty()) { + throw new IOException( + "Expected a needs-input result with the original request, a question and no completed checks"); + } + } + + private Revision revision(String role, String name) throws IOException { + if (blank(name) || name.contains("\\") || name.contains(":") || name.startsWith("/") + || Arrays.stream(name.split("/", -1)) + .anyMatch(s -> s.isEmpty() || s.equals(".") || s.equals(".."))) { + throw new IOException(role + ": expected a project-relative file path, got " + name); + } + Path path = project.resolve(name); + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || !path.equals(path.toRealPath())) { + throw new IOException(role + ": expected a regular project file without symlinks: " + name); + } + try (var stream = Revision.hashing(Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS))) { + return new Revision(name, Revision.finishDigest(stream)); + } + } + + private static <T> T read(Path file, Class<T> type) throws IOException { + try (var stream = Files.newInputStream(file)) { + T value = JSON.readValue(stream, type); + if (value == null) { + throw new IOException("expected a JSON object"); + } + return value; + } catch (IOException e) { + throw new IOException(file + ": " + e.getMessage(), e); + } + } + + private static boolean blank(String text) { + return text == null || text.isBlank(); + } +} 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 index b6c929c5..da503540 100644 --- 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 @@ -12,6 +12,7 @@ import java.security.MessageDigest; import java.util.ArrayList; import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -23,6 +24,7 @@ import org.apache.camel.kit.CamelKitMain; import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.doc.FrontmatterHandler; +import com.fasterxml.jackson.databind.JsonNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; @@ -282,7 +284,9 @@ class SkillPackCompilerTest { core.stages(), artifacts, core.mcpServers(), core.websiteReference()); WorkflowManifestValidator.validateOrThrow(workflow); var overlay = new SkillPack("team", 1, List.of("core"), Map.of(), Map.of(), List.of(key)); - var original = new SkillPack.Declaration("core", key, new SkillPack.Entry(1, "entry.md", null, List.of())); + var original + = new SkillPack.Declaration( + "core", key, new SkillPack.Entry(1, "entry.md", null, List.of(), null, List.of())); var failure = assertThrows(IOException.class, () -> SkillPack.resolve(Map.of("team", overlay), Map.of(key, original), workflow)); assertEquals("team: " + key + ": required by core workflow artifact report", failure.getMessage()); @@ -973,6 +977,167 @@ class SkillPackCompilerTest { } } + private static final String COVERAGE = "step/validate/report/coverage"; + private static final String HOOK_INPUT = """ + {"sources":["orders.yaml"],"target":"quarkus","artifacts":{"inventory":"coverage.tsv"}} + """; + + @Test + @Tag("cli-compat") + void installedSkillSubmitsItsDecisionFailureAndVerifiedCoverage() throws Exception { + Path example = Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources").toRealPath(); + Path dist = distribution(example, "report-review"); + assertCli(0, dist, temp, "init", "--here", "--ai", "bob2", "--no-fetch", "--silent"); + Path skills = temp.resolve(".bob/skills"); + assertTrue(Files.readString(skills.resolve("camel-validate/SKILL.md")).contains("hook --id " + COVERAGE)); + Files.writeString(temp.resolve("orders.yaml"), "route: orders"); + Path inventory = Files.writeString(temp.resolve("coverage.tsv"), "unit\torders.yaml\n"); + Path input = Files.writeString(temp.resolve("input.json"), HOOK_INPUT); + var pending = submitCoverage(dist, skills, 1, false); + assertEquals("needs-input", pending.path("status").asText()); + Files.writeString(temp.resolve("pending.json"), pending.toString()); + String confirmed = HOOK_INPUT.replace("\"sources\"", "\"answer\":\"integration\",\"sources\""); + Files.writeString(input, confirmed); + var failure = submitCoverage(dist, skills, 1, true); + assertEquals("failed", failure.path("status").asText()); + assertTrue(failure.at("/checks/route-coverage/evidence").asText().contains("missing orders.yaml")); + Files.writeString(inventory, "integration\torders.yaml\n"); + String staleDecision = assertCli(1, dist, temp, "hook", "--id", COVERAGE, "--input", "input.json", "--resume", + "pending.json"); + assertTrue(staleDecision.contains("artifacts"), staleDecision); + Files.writeString(input, HOOK_INPUT); + Files.writeString(temp.resolve("pending.json"), submitCoverage(dist, skills, 1, false).toString()); + Files.writeString(input, confirmed); + assertEquals("passed", submitCoverage(dist, skills, 0, true).path("status").asText()); + Files.writeString(inventory, ""); + String stale = assertCli(1, dist, temp, "hook", "--id", COVERAGE, + "--input", "input.json", "--result", "result.json", "--resume", "pending.json"); + assertTrue(stale.contains("artifacts"), stale); + } + + private JsonNode submitCoverage(Path dist, Path skills, int expectedExit, boolean resume) throws Exception { + var args = new ArrayList<>(List.of("hook", "--id", COVERAGE, "--input", "input.json")); + if (resume) { + args.addAll(List.of("--resume", "pending.json")); + } + String dispatch = assertCli(1, dist, temp, args.toArray(String[]::new)); + var message = SkillCatalog.JSON.readTree(dispatch); + assertEquals("invoke-skill", message.path("status").asText()); + var request = message.required("request"); + Path entry = skills.resolve(request.required("implementation").textValue()); + assertTrue(Files.readString(entry).contains("guides/coverage.py")); + Files.writeString(temp.resolve("request.json"), request.toString()); + String python = File.separatorChar == '\\' ? "python" : "python3"; + var process = new ProcessBuilder(python, entry.resolveSibling("guides/coverage.py").toString(), "request.json") + .directory(temp.toFile()).redirectOutput(temp.resolve("result.json").toFile()) + .redirectError(ProcessBuilder.Redirect.INHERIT).start(); + assertEquals(0, process.waitFor()); + args.addAll(List.of("--result", "result.json")); + return SkillCatalog.JSON.readTree(assertCli(expectedExit, dist, temp, args.toArray(String[]::new))); + } + + @ParameterizedTest + @ValueSource(strings = {"resource/shared/guide.md", "skill/camel-migrate", "skill/missing", "provider/list"}) + void buildRejectsUnsupportedHookHandlers(String handler) throws Exception { + Path pack = pack("bad", String.format(Locale.ROOT, """ + add: + provider/list: + contract: 1 + provider: {service: java.util.List, implementation: java.util.ArrayList} + step/validate/report/check: + contract: 1 + hook: {handler: %s, targets: [quarkus], checks: {coverage: report}} + """, handler)); + try (var loader = loader(pack)) { + var error = assertThrows(IOException.class, () -> SkillPackCompiler.compile(loader, List.of("bad"))); + assertTrue(error.getMessage().contains("step/validate/report/check"), error::getMessage); + assertTrue(error.getMessage().contains(handler) || error.getMessage().contains("handler"), + error::getMessage); + } + } + + @Test + void replacementCannotDropARequiredCheck() throws Exception { + Path example = Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources").toRealPath(); + Path pack = pack("overlay", """ + requires: [report-review] + replace: + step/validate/report/coverage: + contract: 1 + hook: {handler: skill/camel-validate, targets: [quarkus, spring-boot], checks: {other: inventory}} + """); + try (var loader = loader(pack, example)) { + var error = assertThrows(IOException.class, + () -> SkillPackCompiler.compile(loader, List.of("report-review", "overlay"))); + assertTrue(error.getMessage().contains("preserve hook targets and checks"), error::getMessage); + } + } + + public static class InventoryProvider implements WorkflowHookProvider { + @Override + public Result invoke(Path project, Request request) throws IOException { + if (request.decisions().isEmpty()) { + return new Result(request, "needs-input", Map.of(), "Which suite?"); + } + String answer = request.decisions().getLast().answer(); + var inventory = project.resolve(request.artifacts().get("inventory").path()); + if (answer.equals("rewrite")) { + Files.writeString(inventory, "changed during dispatch"); + } + boolean passed = Files.readAllLines(inventory).contains(answer); + return new Result( + request, passed ? "passed" : "failed", + Map.of("route-coverage", new Check(passed, "Looked for suite " + answer)), null); + } + } + + @Test + void executableReplacementDispatchesJavaAndRechecksItsFiles() throws Exception { + Path example = Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources").toRealPath(); + Path overlay = pack("compiled", String.format(Locale.ROOT, """ + requires: [report-review] + add: + provider/inventory: + contract: 1 + handles: [step/validate/report/coverage] + provider: {service: %s, implementation: %s} + replace: + step/validate/report/coverage: + contract: 1 + hook: + handler: provider/inventory + targets: [spring-boot, quarkus] + checks: {route-coverage: inventory} + """, WorkflowHookProvider.class.getName(), InventoryProvider.class.getName())); + var archive = temp.resolve(SkillCatalog.DISTRIBUTION); + Files.createDirectories(archive.getParent()); + try (var loader = loader(example, overlay)) { + Files.write(archive, SkillPackCompiler.compile(loader, List.of("compiled", "report-review"))); + } + Files.writeString(temp.resolve("orders.yaml"), "orders"); + Files.writeString(temp.resolve("coverage.tsv"), "integration\n"); + Path input = Files.writeString(temp.resolve("input.json"), HOOK_INPUT); + String[] invoke = {"hook", "--id", COVERAGE, "--input", "input.json"}; + String pending = assertCli(1, temp, temp, invoke); + assertEquals("needs-input", SkillCatalog.JSON.readTree(pending).path("status").asText()); + Files.writeString(temp.resolve("pending.json"), pending); + for (String answer : List.of("unit", "integration", "rewrite")) { + Files.writeString(input, HOOK_INPUT.replace("\"sources\"", "\"answer\":\"" + answer + "\",\"sources\"")); + String output = assertCli(answer.equals("integration") ? 0 : 1, temp, temp, "hook", "--id", COVERAGE, + "--input", "input.json", "--resume", "pending.json"); + if (answer.equals("rewrite")) { + assertTrue(output.contains("artifacts"), output); + } else { + var result = SkillCatalog.JSON.readTree(output); + assertEquals(answer.equals("integration") ? "passed" : "failed", result.path("status").asText()); + assertEquals("provider/inventory", result.at("/request/handler").asText()); + } + } + assertTrue( + assertCli(1, temp, temp, "hook", "--id", COVERAGE, "--input", "input.json", "--result", "forged.json") + .contains("requires Java dispatch")); + } + private Path pack(String id, String yaml) throws IOException { write(id, "pack.yaml", "id: " + id + "\nschema: 1\n" + yaml + "\n"); return temp.resolve(id); diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowHookRunnerTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowHookRunnerTest.java new file mode 100644 index 00000000..201126af --- /dev/null +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/WorkflowHookRunnerTest.java @@ -0,0 +1,163 @@ +package org.apache.camel.kit.workflow; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import org.apache.camel.kit.workflow.WorkflowHookProvider.Check; +import org.apache.camel.kit.workflow.WorkflowHookProvider.Result; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +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 WorkflowHookRunnerTest { + private static final String ID = "step/validate/report/coverage"; + private static final String INPUT = """ + {"sources":["orders.yaml"],"target":"quarkus","artifacts":{"inventory":"coverage.tsv"}} + """; + private static SkillCatalog catalog; + + @TempDir + Path project; + private Path input; + private Path submission; + private WorkflowHookRunner runner; + private String result; + + @BeforeAll + static void compileExample(@TempDir Path dist) throws Exception { + Path example = Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources"); + try (var loader = new URLClassLoader( + new URL[]{example.toUri().toURL(), dist.toUri().toURL()}, + WorkflowHookRunnerTest.class.getClassLoader())) { + Path archive = dist.resolve(SkillCatalog.DISTRIBUTION); + Files.createDirectories(archive.getParent()); + Files.write(archive, SkillPackCompiler.compile(loader, List.of("report-review"))); + catalog = SkillCatalog.load(loader); + } + } + + @BeforeEach + void prepare() throws Exception { + input = Files.writeString(project.resolve("input.json"), INPUT); + Files.writeString(project.resolve("orders.yaml"), "orders"); + Files.writeString(project.resolve("coverage.tsv"), "unit\torders.yaml"); + submission = project.resolve("result.json"); + runner = new WorkflowHookRunner(catalog, project); + var request = runner.run(ID, input, null, null).request(); + result = WorkflowHookRunner.toJson(new Result( + request, "passed", + Map.of("route-coverage", new Check(true, "Orders route covered by unit suite")), null)); + Files.writeString(submission, result); + assertEquals("passed", runner.run(ID, input, submission, null).status()); + } + + @ParameterizedTest + @ValueSource(strings = { + "sources", "artifacts", "target", "decisions", "catalogSha256", "contribution", "handler", "contract"}) + void rejectsStaleOrReboundEvidenceAndIdentifiesTheDifference(String field) throws Exception { + switch (field) { + case "sources" -> Files.writeString(project.resolve("orders.yaml"), "revised"); + case "artifacts" -> Files.writeString(project.resolve("coverage.tsv"), "revised"); + case "target" -> Files.writeString(input, INPUT.replace("quarkus", "spring-boot")); + default -> { + var edited = SkillCatalog.JSON.readTree(result); + var binding = (ObjectNode) edited.required("request"); + if (field.equals("contract")) { + binding.put(field, 2); + } else if (field.equals("decisions")) { + binding.putArray(field).addObject().put("question", "Which suite?").put("answer", "unit"); + } else { + binding.put(field, "some-other-binding"); + } + Files.writeString(submission, edited.toString()); + } + } + assertRejected(field); + } + + @Test + void requiresTheExactChecksAndARealObservation() throws Exception { + var json = (ObjectNode) SkillCatalog.JSON.readTree(result); + var checks = json.putObject("checks"); + Files.writeString(submission, json.toString()); + assertRejected("route-coverage"); + var check = checks.putObject("route-coverage"); + check.put("passed", true).put("evidence", " "); + Files.writeString(submission, json.toString()); + assertRejected("route-coverage"); + check.put("evidence", "route absent").put("passed", false); + Files.writeString(submission, json.toString()); + assertRejected("route-coverage failed"); + checks.set("other", check.deepCopy()); + Files.writeString(submission, json.toString()); + assertRejected("undeclared"); + } + + @Test + void rejectsMalformedWireDataAndIncompleteDecisions() throws Exception { + for (String malformed : List.of(result + " {}", "null", + result.replace("\"passed\":true", "\"passed\":\"true\""), + result.replace("\"passed\":true", "\"passed\":false,\"passed\":true"), + result.replace("\"status\":\"passed\"", "\"status\":8"), + result.replace("\"status\":\"passed\"", "\"status\":\"needs-input\""), + result.replace("\"status\":\"passed\"", "\"status\":\"unknown\""))) { + Files.writeString(submission, malformed); + assertThrows(IOException.class, () -> runner.run(ID, input, submission, null), malformed); + } + } + + @Test + void rejectsUnsupportedTargetsMissingArtifactsAndUndeclaredHooks() throws Exception { + Files.writeString(input, INPUT.replace("quarkus", "unsupported")); + assertRejected("unsupported target"); + Files.writeString(input, INPUT.replace("inventory", "extra")); + assertRejected("inventory"); + Files.writeString(input, INPUT.replace("orders.yaml", "../orders.yaml")); + assertRejected("project-relative"); + Files.writeString(input, INPUT.replace("coverage.tsv", "missing.tsv")); + assertRejected("missing.tsv"); + for (String id : List.of("skill/camel-migrate", "step/validate/report/timestamp", "provider/missing")) { + var failure = assertThrows(IOException.class, () -> runner.run(id, input, submission, null)); + assertTrue(failure.getMessage().contains("No executable hook"), failure::getMessage); + } + } + + @Test + void onlyMatchingPendingRequestsCanCarryConfirmedAnswersAcrossMultipleQuestions() throws Exception { + var initial = runner.run(ID, input, null, null).request(); + Path pending = project.resolve("pending.json"); + Files.writeString(input, INPUT.replace("\"sources\"", "\"answer\":\"integration\",\"sources\"")); + assertRejected("--resume"); + Files.writeString(pending, result); + assertThrows(IOException.class, () -> runner.run(ID, input, null, pending)); + Files.writeString(pending, + WorkflowHookRunner.toJson(new Result(initial, "needs-input", Map.of(), "Which suite?"))); + var first = runner.run(ID, input, null, pending).request(); + Files.writeString(pending, + WorkflowHookRunner.toJson(new Result(first, "needs-input", Map.of(), "Which release?"))); + Files.writeString(input, INPUT.replace("\"sources\"", "\"answer\":\"summer\",\"sources\"")); + var resumed = runner.run(ID, input, null, pending).request(); + assertEquals(List.of(new WorkflowHookProvider.Decision("Which suite?", "integration"), + new WorkflowHookProvider.Decision("Which release?", "summer")), resumed.decisions()); + Files.writeString(input, Files.readString(input).replace("quarkus", "spring-boot")); + var stale = assertThrows(IOException.class, () -> runner.run(ID, input, null, pending)); + assertTrue(stale.getMessage().contains("target"), stale::getMessage); + } + + private void assertRejected(String reason) { + var failure = assertThrows(IOException.class, () -> runner.run(ID, input, submission, null)); + assertTrue(failure.getMessage().contains(reason), failure::getMessage); + } +}
