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 286dcffa17f32715b05b4a10feb1b48247e49c4a
Author: Luigi De Masi <[email protected]>
AuthorDate: Tue Nov 24 09:08:52 2026 +0100

    Fix #196: Reject incomplete hook results with field-specific errors
    
    Make hook results deterministic and identify missing files and malformed
    fields. Validate handler declarations while allowing an explicitly
    excluded hook to leave its handler installed.
    
    Share the invocation protocol at each contribution point and document
    provider trust, runtime verification and the complete example pack.
    
    Co-authored-by: OpenAI Codex <[email protected]>
---
 docs/modules/ROOT/pages/contributing.adoc          | 17 ++++-
 docs/modules/ROOT/pages/skills.adoc                |  6 +-
 docs/security-model.md                             | 16 +++-
 docs/security-model.yaml                           | 11 ++-
 .../java/org/apache/camel/kit/workflow/Sha256.java | 28 +++++++
 .../apache/camel/kit/workflow/SkillCatalog.java    | 11 ++-
 .../camel/kit/workflow/SkillPackCompiler.java      | 17 ++++-
 .../apache/camel/kit/workflow/WorkflowHook.java    | 32 ++++----
 .../camel/kit/workflow/WorkflowHookProvider.java   | 41 +++++------
 .../camel/kit/workflow/WorkflowHookRunner.java     | 23 +++++-
 .../camel/kit/workflow/SkillPackCompilerTest.java  | 86 +++++++++++++++++++++-
 .../camel/kit/workflow/WorkflowHookRunnerTest.java | 80 ++++++++++++++++++++
 12 files changed, 313 insertions(+), 55 deletions(-)

diff --git a/docs/modules/ROOT/pages/contributing.adoc 
b/docs/modules/ROOT/pages/contributing.adoc
index c8ef4d61..9e9e5e5c 100644
--- a/docs/modules/ROOT/pages/contributing.adoc
+++ b/docs/modules/ROOT/pages/contributing.adoc
@@ -113,6 +113,18 @@ 
include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-r
 
include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/review.md[]
 ----
 
+.coverage.md
+[source,markdown]
+----
+include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.md[]
+----
+
+.coverage.py
+[source,python]
+----
+include::example$skill-pack/src/main/resources/META-INF/camel-kit/packs/report-review/coverage.py[]
+----
+
 === Composition rules
 
 * `schema: 1` versions the pack descriptor. Each added or replaced entry 
declares `contract: 1` for its
@@ -189,8 +201,11 @@ A step declares either a guidance resource or a `hook`. 
Its `handler` selects on
 `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.
+An explicit `exclude` of the step removes both the hook and its invocation 
from that distribution.
+The handler remains available for other hooks. Each ID in `handles` must name 
a hook declared by the
+selected packs, including hooks explicitly excluded during composition.
 
-The caller supplies workspace-relative file paths with `/` separators. Each 
source and evidence path must refer
+The caller supplies project-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
diff --git a/docs/modules/ROOT/pages/skills.adoc 
b/docs/modules/ROOT/pages/skills.adoc
index 032cb584..3ca0cf4c 100644
--- a/docs/modules/ROOT/pages/skills.adoc
+++ b/docs/modules/ROOT/pages/skills.adoc
@@ -63,7 +63,11 @@ camel-kit hook --id step/validate/report/coverage --input 
input.json
 * 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
+* An invalid submission writes a diagnostic to standard error identifying the 
missing or mismatched requirement.
+  Echo every request field, including `decisions: []` on the first invocation. 
A missing source or artifact
+  is reported relative to the project root where the command was run.
+* `invoke-skill`, `needs-input` and `failed` return exit code 1 with their 
JSON status on standard output.
+  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.
diff --git a/docs/security-model.md b/docs/security-model.md
index a9035ec6..ad00bf99 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -97,7 +97,7 @@ metadata; Kit configures it for each harness, and it also 
serves MCP clients tha
 
   | Family | Representative entry points | Touches outside the process? | In 
this model? |
   | --- | --- | --- | --- |
-  | **A. Workspace CLI** — `init`, `doctor`, `doc`, `nextId`, `plan analyze`, 
`graph *` (`camel-kit-core` commands, services, generators, catalog 
downloaders; `camel-kit-main` JBang launcher; `camel-jbang-plugin-kit`) | Aesh 
commands | Writes the target workspace; reads `~/.camel-kit/config.properties`; 
`init` downloads catalogs over HTTPS unless `--no-fetch`; prerequisite probes 
spawn `java`, `jbang`, `camel` (including `camel test --help`) and `mvn` when 
no wrapper exists; see §4.5 | **In** |
+  | **A. Workspace CLI** — `init`, `doctor`, `doc`, `nextId`, `plan analyze`, 
`hook`, `graph *` (`camel-kit-core` commands, services, generators, catalog 
downloaders; `camel-kit-main` JBang launcher; `camel-jbang-plugin-kit`) | Aesh 
commands | Writes the target workspace; reads `~/.camel-kit/config.properties`; 
`init` downloads catalogs over HTTPS unless `--no-fetch`; prerequisite probes 
spawn `java`, `jbang`, `camel` (including `camel test --help`) and `mvn` when 
no wrapper exists; see  [...]
   | **B. Graph analysis** (`camel-kit-graph`: Pom, Java, Groovy, XML route, 
Mule XML, DataWeave, BizTalk, YAML route, Config parsers plus the cross-linker 
and property-binding post-processors) | `camel-kit graph …`; `init --here` 
auto-analysis | Reads the analysed tree; writes 
`.camel-kit/project-graph.json`; no network, no child process *(documented — 
`ParserSourceReadingContractTest`; [V1 
evidence](security-verification.md#v1-source-reading))* | **In** — the analysed 
tree is untrusted input |
   | **C. Skills, templates, traits, agent registry, workflow manifest and 
assembled skill catalog** 
(`kit/camel-kit-core/src/main/resources/{skills,templates,agents,workflow,META-INF/camel-kit/packs}`
 and the packaged `META-INF/camel-kit/*catalog.zip`) | installed by `init` into 
the workspace | Nothing by itself; the harness executes the instructions with 
its own permissions; generated MCP configs make the harness launch MCP servers 
through `jbang` at pinned coordinates | **In** as shipp [...]
   | **D. Ship controller** (Technology Preview; `camel-kit-core` `ship/**`, 
`command/ship`) | `camel-kit ship`, `/camel-ship` delegates | Spawns 
`pi`/`node` (Pi backend), `/usr/bin/setsid`, `/bin/kill`, its own `java`; 
writes `.camel-kit/ship/state` or `$CAMEL_KIT_SHIP_STATE_HOME`; publishes into 
the live project; HTTPS to Maven Central through family E | **In** |
@@ -192,7 +192,7 @@ trusted")*.
 4. **Shipped skills + loaded context → harness/model → generated artifacts.** 
Skills are the only instruction
    source besides the user *(documented — `context-authority.md`, "Instruction 
Authority")*. Everything the model
    produces is untrusted input to any deterministic consumer: `doc check` 
frontmatter, `plan analyze` task metadata,
-   Ship worker results.
+   workflow hook submissions and pending results, and Ship worker results.
 5. **Ship: controller ↔ worker ↔ evidence ↔ publication.** The controller "is 
the only component that writes Ship run
    state and commits stage transitions" *(documented — `docs/commands.md`)*. 
Workers run in a controller-owned
    staging workspace; "the request working directory is the child process cwd, 
not a filesystem sandbox. The
@@ -399,6 +399,17 @@ on the build classpath. The compiler checks provider types 
without initializing
 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).
 
+At runtime, `camel-kit hook` resolves the step and handler from that same 
bundled catalog. The assistant
+invokes a bundled skill in its host. For a Java handler, Kit constructs the 
distribution-selected provider
+and calls it in the CLI JVM with the operator's permissions. Trusting that 
distribution includes trusting
+its provider code and the helpers it chooses to run.
+
+The caller owns the source scope, target, evidence paths and confirmed 
answers. Kit reads the submitted
+and pending JSON as data. It checks the echoed binding and decisions against 
the caller's request,
+hashes the named project files, and requires an observation for each declared 
check before accepting a pass.
+The provider is responsible for the substance of the observations. On 
re-entry, earlier decisions come from
+the last verified pending result, which the caller must keep intact. The 
assistant controls stage completion.
+
 The knobs that move the security envelope:
 
 | Knob | Default | Effect on the model | Maintainer stance |
@@ -443,6 +454,7 @@ Per-entry-point trust table. "Caller" is the developer 
unless stated otherwise.
 | `camel-kit graph …` output, `.camel-kit/project-graph.json` | graph JSON 
consumed by skills | derived from the tree | Treat as data in prompts 
*(documented — umbrella "Reading route sources")* |
 | `camel-kit doc check/stale/unstale <file>` | YAML frontmatter of pipeline 
artifacts | model-authored → **yes** | Legacy frontmatter flags parsed as data 
by `FrontmatterHandler` (Jackson YAML); no separate byte quota is claimed for 
these legacy commands |
 | `camel-kit doc snapshot/record`, `doc check --project` | source tree, JSON 
snapshot/receipt and documentation review | tree/model-authored → **yes** | 
`DocumentationEvidence` resolves the selected project root (including an 
alias), confines reads and receipt writes to it, and rejects descendant 
symlinks, traversal and Git internals; hashes regular files only. Source 
limits: 10,000 entries, 64 MiB/file, 512 MiB total; snapshot/report/document 
inputs to `record`: 1 MiB each; receipts: 2  [...]
+| `camel-kit hook` | caller input JSON, skill result, saved pending result, 
source and artifact files | model or analysed tree → **yes** | Check binding, 
revisions, required checks and decision history (§4.5a). Only the bundled 
catalog selects executable code. |
 | `camel-kit plan analyze` | `implementation-plan.md` task metadata | 
model-authored → **yes** | Parsed as data by `PlanAnalyzer`; no project 
execution |
 | `camel-kit nextId <slug>` | slug → `docs/camel-kit/NNN-slug/` | no — 
operator | — |
 | `camel-kit ship --text`, `--document PATH` | context for the model | 
supplied by the developer; **content is loaded context** for the model | Do not 
pass secrets; third-party documents can carry instruction-like text (§4.3, 
§4.10) |
diff --git a/docs/security-model.yaml b/docs/security-model.yaml
index 38b11f42..dee61426 100644
--- a/docs/security-model.yaml
+++ b/docs/security-model.yaml
@@ -57,7 +57,7 @@ component_families:
   - id: A
     name: Kit workspace CLI (Aesh)
     paths: ["kit/camel-kit-core (command, service, generator, catalog, 
config)", kit/camel-kit-main, kit/camel-jbang-plugin-kit]
-    entry_points: [init, doctor, doc, nextId, plan analyze, graph]
+    entry_points: [init, doctor, doc, nextId, plan analyze, hook, graph]
     in_model: true
     reachability: Reachable from a non-operator input (analysed tree via init 
--here, downloaded catalog content, model-authored pipeline artifact, another 
local account).
   - id: B
@@ -71,6 +71,7 @@ component_families:
     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.
+    hook_dispatch: The assistant invokes the bundled skill in its host. Kit 
constructs a distribution-selected Java provider in the CLI JVM with the 
operator's permissions. The provider controls helper calls and is responsible 
for its observations.
     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)
@@ -145,6 +146,14 @@ entry_points:
     input: source inventory, JSON snapshot/receipt, document and review report
     attacker_controllable: true
     caller_must_enforce: Project-contained regular files under the resolved 
root (root aliases allowed); reject descendant symlinks, traversal, Git 
internals, duplicate/trailing JSON and scalar coercion; simultaneous source 
limits 10000 entries, 64 MiB/file, 512 MiB total; snapshot/report/document 
inputs to record 1 MiB each; receipts 2 MiB to fit the embedded snapshot and 
review fields. No source execution or network. Review scope and conclusions 
remain the reviewer's responsibility.
+  - entry: camel-kit hook
+    input: Caller-owned scope, target, evidence paths and confirmed answer, 
skill result and saved pending JSON, source and artifact contents.
+    attacker_controllable: true
+    server_enforces:
+      - Resolve the handler from the bundled catalog.
+      - Match the echoed binding, decisions and current file digests.
+      - Require a passing observation for each declared check before accepting 
a pass.
+    caller_must_enforce: Trust the distribution and its provider code, select 
the complete source scope, keep the last verified pending result intact, 
confirm developer answers and decide stage completion.
   - entry: camel-kit plan analyze
     input: implementation-plan.md task metadata (model-authored)
     attacker_controllable: true
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/Sha256.java 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/Sha256.java
new file mode 100644
index 00000000..5753b006
--- /dev/null
+++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/workflow/Sha256.java
@@ -0,0 +1,28 @@
+package org.apache.camel.kit.workflow;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.DigestInputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+
+/** SHA-256 over the complete file or catalog stream, including any unread 
trailing bytes. */
+final class Sha256 {
+    private Sha256() {
+    }
+
+    static DigestInputStream stream(InputStream input) {
+        try {
+            return new DigestInputStream(input, 
MessageDigest.getInstance("SHA-256"));
+        } catch (NoSuchAlgorithmException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    static String finish(DigestInputStream input) throws IOException {
+        input.transferTo(OutputStream.nullOutputStream());
+        return HexFormat.of().formatHex(input.getMessageDigest().digest());
+    }
+}
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 80b199f6..52655d9b 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
@@ -87,7 +87,12 @@ public final class SkillCatalog {
                 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())
+                if (!atStage) {
+                    throw new IOException(
+                            binding.pack() + ": " + entry.getKey() + ": 
expected the skill entry for stage "
+                                          + stage + ", got " + binding.path());
+                }
+                if (!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());
@@ -161,7 +166,7 @@ public final class SkillCatalog {
         if (urls.size() != 1) {
             throw new IOException("Expected one assembled Camel Kit skill 
catalog, found " + urls);
         }
-        try (var archive = 
WorkflowHookProvider.Revision.hashing(urls.getFirst().openStream());
+        try (var archive = Sha256.stream(urls.getFirst().openStream());
              var stream = new ZipInputStream(archive)) {
             Manifest manifest = null;
             Map<String, byte[]> files = new TreeMap<>();
@@ -178,7 +183,7 @@ public final class SkillCatalog {
                 throw new IOException("Missing " + MANIFEST + " in " + urls);
             }
             return new SkillCatalog(
-                    manifest, files, 
WorkflowHookProvider.Revision.finishDigest(archive));
+                    manifest, files, Sha256.finish(archive));
         }
     }
 }
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 65883efd..b97bd7e1 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
@@ -92,6 +92,7 @@ public final class SkillPackCompiler {
         Map<String, byte[]> files = new TreeMap<>();
         Map<String, SkillCatalog.Binding> bindings = new TreeMap<>();
         Map<String, List<String>> steps = new TreeMap<>();
+        var hookPoints = new TreeSet<String>();
         Map<String, String> stageSkills = new HashMap<>();
         workflow.stages().forEach(stage -> stageSkills.put(stage.id(), 
stage.skill()));
         for (Declaration d : entries.values()) {
@@ -108,7 +109,11 @@ public final class SkillPackCompiler {
                         throw d.error("unknown workflow stage " + parts[0]);
                     }
                     path = skill + "/SKILL.md";
-                    steps.computeIfAbsent(parts[0] + "/" + parts[1], unused -> 
new ArrayList<>())
+                    String point = parts[0] + "/" + parts[1];
+                    if (d.entry().hook() != null) {
+                        hookPoints.add(point);
+                    }
+                    steps.computeIfAbsent(point, unused -> new ArrayList<>())
                             .add(d.entry().hook() == null
                                     ? new String(resources.get(d), 
StandardCharsets.UTF_8).strip()
                                     : d.entry().hook().instructions(d.key()));
@@ -116,6 +121,13 @@ public final class SkillPackCompiler {
                 case "provider" -> path = null;
                 default -> throw d.error("unknown contribution kind");
             }
+            for (String handle : d.entry().handles()) {
+                // An explicit exclusion removes the invocation but leaves its 
handler available.
+                Declaration handled = entries.getOrDefault(handle, 
definitions.get(handle));
+                if (handled == null || handled.entry().hook() == null) {
+                    throw d.error("handles references an undeclared hook: " + 
handle);
+                }
+            }
             List<String> requires = requirements(d, path, definitions);
             for (String key : requires) {
                 SkillPack.requireContribution(d, key, entries, packs);
@@ -126,6 +138,7 @@ public final class SkillPackCompiler {
                             d.entry().handles()));
         }
         WorkflowManifest effective = composeWorkflow(workflow, entries, 
definitions, steps);
+        hookPoints.forEach(point -> 
steps.get(point).add(WorkflowHook.PROTOCOL));
         bindSteps(stageSkills, files, steps, entries);
         var manifest = new SkillCatalog.Manifest(1, 
List.copyOf(packs.keySet()), effective, bindings);
         return archive(new SkillCatalog(manifest, files, null));
@@ -275,7 +288,7 @@ public final class SkillPackCompiler {
             }
             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)) {
+            if (!file && !d.key().matches("skill/" + id) && 
!d.key().matches(WorkflowHook.STEP)) {
                 throw d.error("invalid contribution identifier");
             }
             if (d.key().equals("skill/shared")) {
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
index 69561759..868634ea 100644
--- 
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
@@ -19,7 +19,8 @@ public record WorkflowHook(String handler, List<String> 
targets, Map<String, Str
     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");
+            throw new IOException(
+                    key + ": expected a named step and a skill/<id> or 
provider/<id> handler, got " + handler);
         }
         if (targets.isEmpty() || targets.stream().anyMatch(t -> 
!t.matches(SkillPack.ID))
                 || Set.copyOf(targets).size() != targets.size()) {
@@ -42,20 +43,23 @@ public record WorkflowHook(String handler, List<String> 
targets, Map<String, Str
         return binding.provider() != null && 
WorkflowHookProvider.class.getName().equals(binding.provider().service());
     }
 
+    static final String PROTOCOL = """
+            Run each required hook from the project root using the Kit 
distribution that installed this step.
+            Write caller-owned input JSON with the selected `target`, all 
in-scope `sources` and the evidence
+            `artifacts` by role. Use project-relative paths for sources and 
artifacts.
+            On `invoke-skill`, open `request.implementation` relative to the 
host's installed skills directory
+            (the parent of this skill's directory). Invoke that skill with the 
emitted request and submit its
+            result with the same command plus `--result <result.json>`.
+            On `needs-input`, save the 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 a hook. Return the 
outcome to the caller.
+            The assistant decides the next ordinary step.
+            """.stripTrailing();
+
     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();
+                "Required hook: `{COMMAND_PREFIX} hook --id %s --input 
<input.json>`. Supported targets: %s. "
+                                          + "Required checks and evidence 
roles: %s.",
+                key, targets, new TreeMap<>(checks));
     }
 }
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
index 58b141f8..a6524ac8 100644
--- 
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
@@ -1,15 +1,9 @@
 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;
+import java.util.Objects;
 
 /** A bundled Java implementation of the same contract used for assistant-run 
skill submissions. */
 @FunctionalInterface
@@ -18,18 +12,6 @@ public interface WorkflowHookProvider {
 
     /** 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) {
@@ -45,9 +27,13 @@ public interface WorkflowHookProvider {
             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);
+            sources = copyFields("request.sources", sources);
+            artifacts = copyFields("request.artifacts", artifacts);
+            checks = copyFields("request.checks", checks);
+            Objects.requireNonNull(decisions, "request.decisions is required");
+            for (int i = 0; i < decisions.size(); i++) {
+                Objects.requireNonNull(decisions.get(i), "request.decisions[" 
+ i + "] is null");
+            }
             decisions = List.copyOf(decisions);
         }
 
@@ -66,7 +52,16 @@ public interface WorkflowHookProvider {
     /** 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);
+            checks = checks == null ? Map.of() : copyFields("checks", checks);
         }
     }
+
+    private static <T> Map<String, T> copyFields(String field, Map<String, T> 
values) {
+        Objects.requireNonNull(values, field + " is required");
+        values.forEach((key, value) -> {
+            Objects.requireNonNull(key, field + " contains a null key");
+            Objects.requireNonNull(value, () -> field + "." + key + " is 
null");
+        });
+        return Map.copyOf(values);
+    }
 }
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
index 03fbdb9c..d01ac1c0 100644
--- 
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
@@ -3,9 +3,11 @@ package org.apache.camel.kit.workflow;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
 import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -20,8 +22,10 @@ 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.SerializationFeature;
 import com.fasterxml.jackson.databind.cfg.CoercionAction;
 import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
+import com.fasterxml.jackson.databind.exc.ValueInstantiationException;
 import com.fasterxml.jackson.databind.json.JsonMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.fasterxml.jackson.databind.type.LogicalType;
@@ -30,6 +34,7 @@ import com.fasterxml.jackson.databind.type.LogicalType;
 public final class WorkflowHookRunner {
     private static final JsonMapper JSON = JsonMapper.builder()
             .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+            .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
             .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
             .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
             .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT)
@@ -143,14 +148,14 @@ public final class WorkflowHookRunner {
                     "expected artifact roles " + roles + ", received "
                                   + (input.artifacts() == null ? "none" : 
input.artifacts().keySet()));
         }
-        Map<String, String> sources = new TreeMap<>();
+        Map<String, String> sources = new HashMap<>();
         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<>();
+        Map<String, Revision> artifacts = new HashMap<>();
         for (var artifact : input.artifacts().entrySet()) {
             artifacts.put(artifact.getKey(), revision(artifact.getKey(), 
artifact.getValue()));
         }
@@ -189,11 +194,16 @@ public final class WorkflowHookRunner {
             throw new IOException(role + ": expected a project-relative file 
path, got " + name);
         }
         Path path = project.resolve(name);
+        if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) {
+            throw new IOException(
+                    role + ": file not found: " + name + " (project root: " + 
project
+                                  + "; run the hook from the project root)");
+        }
         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));
+        try (var stream = Sha256.stream(Files.newInputStream(path, 
LinkOption.NOFOLLOW_LINKS))) {
+            return new Revision(name, Sha256.finish(stream));
         }
     }
 
@@ -204,6 +214,11 @@ public final class WorkflowHookRunner {
                 throw new IOException("expected a JSON object");
             }
             return value;
+        } catch (ValueInstantiationException e) {
+            Throwable cause = e.getCause();
+            throw new IOException(file + ": " + (cause == null ? 
e.getOriginalMessage() : cause.getMessage()), e);
+        } catch (NoSuchFileException e) {
+            throw new IOException("File not found: " + file, e);
         } catch (IOException e) {
             throw new IOException(file + ": " + e.getMessage(), e);
         }
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 da503540..9c1500e0 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
@@ -31,6 +31,7 @@ import org.junit.jupiter.api.Tag;
 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.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
 import static org.junit.jupiter.api.Assertions.*;
@@ -1037,8 +1038,13 @@ class SkillPackCompilerTest {
     }
 
     @ParameterizedTest
-    @ValueSource(strings = {"resource/shared/guide.md", "skill/camel-migrate", 
"skill/missing", "provider/list"})
-    void buildRejectsUnsupportedHookHandlers(String handler) throws Exception {
+    @CsvSource({
+            "resource/shared/guide.md, expected a named step and a skill/<id> 
or provider/<id> handler",
+            "skill/camel-migrate, unsupported hook handler",
+            "skill/missing, requires missing contribution",
+            "provider/list, unsupported hook handler"
+    })
+    void buildRejectsUnsupportedHookHandlers(String handler, String reason) 
throws Exception {
         Path pack = pack("bad", String.format(Locale.ROOT, """
                 add:
                   provider/list:
@@ -1051,8 +1057,80 @@ class SkillPackCompilerTest {
         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);
+            assertTrue(error.getMessage().contains(reason), error::getMessage);
+            assertTrue(error.getMessage().contains(handler), 
error::getMessage);
+        }
+    }
+
+    @Test
+    void exclusionRemovesTheHookAndItsInstructionsButKeepsTheHandler() throws 
Exception {
+        Path example = 
Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources");
+        Path overlay = pack("overlay", "requires: [report-review]\nexclude: [" 
+ COVERAGE + "]");
+        Path archive = temp.resolve(SkillCatalog.DISTRIBUTION);
+        Files.createDirectories(archive.getParent());
+        try (var loader = loader(example, overlay)) {
+            Files.write(archive, SkillPackCompiler.compile(loader, 
List.of("report-review", "overlay")));
+        }
+        try (var loader = loader(temp)) {
+            var catalog = SkillCatalog.load(loader);
+            var entries = catalog.manifest().contributions();
+            assertFalse(entries.containsKey(COVERAGE));
+            assertEquals(List.of(COVERAGE), 
entries.get("skill/camel-review-coverage").handles());
+            String instructions = content(catalog, "camel-validate/SKILL.md");
+            assertFalse(instructions.contains(COVERAGE));
+            assertFalse(instructions.contains(WorkflowHook.PROTOCOL));
+            assertTrue(instructions.contains(REVIEW));
+        }
+    }
+
+    @Test
+    void twoHooksAtOnePointShareTheInvocationProtocol() throws Exception {
+        String second = "step/validate/report/second";
+        Path addon = pack("more", """
+                requires: [report-review]
+                add:
+                  skill/camel-inspect:
+                    contract: 1
+                    resource: inspect.md
+                    handles: [step/validate/report/second]
+                  step/validate/report/second:
+                    contract: 1
+                    hook: {handler: skill/camel-inspect, targets: [quarkus], 
checks: {smoke: report}}
+                """);
+        write("more", "inspect.md", SKILL);
+        Path example = 
Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources");
+        Path archive = temp.resolve(SkillCatalog.DISTRIBUTION);
+        Files.createDirectories(archive.getParent());
+        try (var loader = loader(example, addon)) {
+            Files.write(archive, SkillPackCompiler.compile(loader, 
List.of("report-review", "more")));
+        }
+        try (var loader = loader(temp)) {
+            String stage = content(SkillCatalog.load(loader), 
"camel-validate/SKILL.md");
+            assertTrue(stage.contains("hook --id " + COVERAGE));
+            assertTrue(stage.contains("hook --id " + second));
+            String pathHelp = "open `request.implementation` relative to the 
host's installed skills directory";
+            assertTrue(stage.contains(pathHelp));
+            assertEquals(stage.indexOf(pathHelp), stage.lastIndexOf(pathHelp));
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource(delimiter = '|', value = {
+            "skill/camel-inspect | step/validate/report/missing | undeclared 
hook",
+            "skill/camel-inspect | step/validate/report/coverage, 
step/validate/report/coverage | invalid handles",
+            "skill/camel-inspect | invalid | undeclared hook",
+            "resource/shared/extra.md | step/validate/report/coverage | 
invalid handles"
+    })
+    void rejectsInvalidHandlerDeclarations(String owner, String handles, 
String reason) throws Exception {
+        Path example = 
Path.of("../../docs/modules/ROOT/examples/skill-pack/src/main/resources");
+        Path extra = pack("extra", "add: {" + owner + ": {contract: 1, 
resource: extra.md, handles: ["
+                                   + handles + "]}}");
+        write("extra", "extra.md", SKILL);
+        try (var loader = loader(example, extra)) {
+            var error = assertThrows(IOException.class,
+                    () -> SkillPackCompiler.compile(loader, List.of("extra", 
"report-review")));
+            assertTrue(error.getMessage().contains(owner), error::getMessage);
+            assertTrue(error.getMessage().contains(reason), error::getMessage);
         }
     }
 
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
index 201126af..826e3b48 100644
--- 
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
@@ -5,6 +5,7 @@ import java.net.URL;
 import java.net.URLClassLoader;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -17,6 +18,7 @@ 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.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
 import static org.junit.jupiter.api.Assertions.*;
@@ -87,6 +89,84 @@ class WorkflowHookRunnerTest {
         assertRejected(field);
     }
 
+    @ParameterizedTest
+    @ValueSource(strings = {"sources", "artifacts", "checks", "decisions"})
+    void namesMissingAndNullEchoedCollections(String field) throws Exception {
+        var json = (ObjectNode) SkillCatalog.JSON.readTree(result);
+        var request = (ObjectNode) json.required("request");
+        request.remove(field);
+        Files.writeString(submission, json.toString());
+        assertRejected("request." + field + " is required");
+        request.putNull(field);
+        Files.writeString(submission, json.toString());
+        assertRejected("request." + field + " is required");
+    }
+
+    @Test
+    void namesNullCheckEntry() throws Exception {
+        var json = (ObjectNode) SkillCatalog.JSON.readTree(result);
+        json.withObject("/checks").putNull("route-coverage");
+        Files.writeString(submission, json.toString());
+        assertRejected("checks.route-coverage is null");
+    }
+
+    @Test
+    void namesNullDecisionEntry() throws Exception {
+        var json = (ObjectNode) SkillCatalog.JSON.readTree(result);
+        json.withArray("/request/decisions").addNull();
+        Files.writeString(submission, json.toString());
+        assertRejected("request.decisions[0] is null");
+    }
+
+    @Test
+    void serializesSourceKeysInPathOrder() throws Exception {
+        var paths = List.of("orders.yaml", "customers.yaml", "returns.yaml", 
"accounts.yaml");
+        for (String path : paths) {
+            Files.writeString(project.resolve(path), path);
+        }
+        var json = (ObjectNode) SkillCatalog.JSON.readTree(INPUT);
+        json.set("sources", SkillCatalog.JSON.valueToTree(paths));
+        Files.writeString(input, json.toString());
+        String dispatch = WorkflowHookRunner.toJson(runner.run(ID, input, 
null, null));
+        var sources = 
SkillCatalog.JSON.readTree(dispatch).at("/request/sources");
+        assertEquals(paths.stream().sorted().toList(), 
sources.properties().stream().map(Map.Entry::getKey).toList());
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+            "skill/camel-review-coverage, handles, wrong-format, invalid 
handles",
+            "step/validate/report/coverage, path, camel-start/SKILL.md, 
expected the skill entry for stage validate"
+    })
+    void catalogLoadIdentifiesInvalidBindingFields(String key, String field, 
String value, String diagnostic)
+            throws Exception {
+        var manifest = (ObjectNode) 
SkillCatalog.JSON.valueToTree(catalog.manifest());
+        var binding = (ObjectNode) 
manifest.required("contributions").required(key);
+        if (field.equals("handles")) {
+            binding.withArray(field).add(value);
+        } else {
+            binding.put(field, value);
+        }
+        var files = new HashMap<String, byte[]>();
+        for (String path : catalog.paths()) {
+            try (var stream = catalog.open(path)) {
+                files.put(path, stream.readAllBytes());
+            }
+        }
+        var altered = SkillCatalog.JSON.treeToValue(manifest, 
SkillCatalog.Manifest.class);
+        var error = assertThrows(IOException.class, () -> new 
SkillCatalog(altered, files, null));
+        assertTrue(error.getMessage().contains(key), error::getMessage);
+        assertTrue(error.getMessage().contains(diagnostic), error::getMessage);
+    }
+
+    @Test
+    void identifiesMissingFilesAndTheProjectRoot() throws Exception {
+        Files.delete(input);
+        assertEquals("File not found: " + input,
+                assertThrows(IOException.class, () -> runner.run(ID, input, 
null, null)).getMessage());
+        Files.writeString(input, INPUT.replace("orders.yaml", "missing.yaml"));
+        assertRejected("source: file not found: missing.yaml (project root: " 
+ project.toRealPath());
+    }
+
     @Test
     void requiresTheExactChecksAndARealObservation() throws Exception {
         var json = (ObjectNode) SkillCatalog.JSON.readTree(result);

Reply via email to