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 8d7ac14eb883bcb00285c328430e40afd96a612d
Author: Jinal Sarvaiya <[email protected]>
AuthorDate: Tue Nov 24 17:08:24 2026 +0000

    Add interface contract discovery to greenfield interviews
---
 docs/modules/ROOT/pages/camel-brainstorm.adoc      |  17 +-
 docs/modules/ROOT/pages/greenfield.adoc            |  29 +-
 .../camel/kit/ship/controller/ShipCoordinator.java |  27 ++
 .../camel-brainstorm/guides/design-assembly.md     |  12 +
 .../guides/greenfield-interview.md                 | 185 ++++++++++-
 .../skills/shared/discovery-completeness.md        |  14 +-
 .../skills/shared/interface-contract-briefing.md   |  96 ++++++
 .../brainstorm/InterfaceContractDiscoveryTest.java | 341 +++++++++++++++++++++
 .../resources/contracts/sample-json-schema.json    |  56 ++++
 .../test/resources/contracts/sample-openapi.yaml   |  71 +++++
 10 files changed, 838 insertions(+), 10 deletions(-)

diff --git a/docs/modules/ROOT/pages/camel-brainstorm.adoc 
b/docs/modules/ROOT/pages/camel-brainstorm.adoc
index 6b826a1d..66a07148 100644
--- a/docs/modules/ROOT/pages/camel-brainstorm.adoc
+++ b/docs/modules/ROOT/pages/camel-brainstorm.adoc
@@ -52,11 +52,15 @@ material you provide first and does not ask about facts 
that are already establi
 clarification at all. Open points are asked one at a time, never in batches, 
in three groups:
 
 . *Project questions*: name, business purpose, systems landscape, integration 
goals or flow names.
-. *Per-flow questions*: intent and data, source, transformations, sink and 
error handling, with field-mapping,
-  multi-path routing and resilience follow-ups only when triggered.
+. *Per-flow questions*: intent and data, source, transformations, interface 
contracts (asked separately for source and
+  destination), sink and error handling, with field-mapping, multi-path 
routing and resilience follow-ups only when
+  triggered.
 . *Cross-cutting questions*: performance, security and monitoring when 
relevant, then remaining constraints and the
   deliberate scope exclusions. A category that does not apply is recorded as 
not applicable with the reason.
 
+NOTE: Interface contract discovery is available in development snapshots only 
(0.5.0-SNAPSHOT and later). Released
+versions (0.4.x) do not include this feature.
+
 .Topics the interview can cover, with example exchanges
 [%collapsible]
 ====
@@ -73,6 +77,15 @@ Input and output formats, schemas, and whether a field-level 
mapping is needed.
 offers DataMapper, which uses inline Groovy when both schemas are absent or 
the mapping has fewer than 20 leaf fields
 and XSLT only with at least 20 leaf fields and at least one schema.
 
+Interface contracts::
+"For the source/destination, do you have an interface definition, will you 
provide one later, should we design it, or
+is it not applicable?" Supported artifacts include OpenAPI, AsyncAPI, WSDL, 
JSON Schema, XSD and documented message
+contracts. The agent asks separately for source and destination, inspecting 
supplied material first. Three scenarios
+are handled: existing contracts (read and establish compatibility 
constraints), contracts to be supplied later (record
+as explicit dependencies without inventing placeholders), and new contracts 
for user-controlled endpoints (propose in
+the design specification for approval before implementation). Example: 
existing source OpenAPI spec + newly designed
+destination JSON Schema awaiting approval.
+
 Processing requirements::
 Validations, business rules, calculations and enrichments, and conditional 
routing when several destinations are
 named.
diff --git a/docs/modules/ROOT/pages/greenfield.adoc 
b/docs/modules/ROOT/pages/greenfield.adoc
index f104e971..582ffe45 100644
--- a/docs/modules/ROOT/pages/greenfield.adoc
+++ b/docs/modules/ROOT/pages/greenfield.adoc
@@ -37,11 +37,21 @@ one at a time, in three groups:
 
 * *Project questions* establish the name, the business purpose, the systems 
landscape and the integration goals or
   flow names.
-* *Per-flow questions* cover each flow's intent and data, source, 
transformations, sink and error handling, with
-  field-mapping, routing and resilience follow-ups only when needed.
+* *Per-flow questions* cover each flow's intent and data, source, 
transformations, interface contracts (asked
+  separately for source and destination), sink and error handling, with 
field-mapping, routing and resilience
+  follow-ups only when needed.
 * *Cross-cutting questions* cover performance, security, monitoring, remaining 
constraints and deliberate scope
   exclusions; a category that does not apply is recorded with a rationale.
 
+For interface contracts (OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD or 
documented message contracts), the agent asks
+separately about the source and destination. Each can have an existing 
definition, will have one supplied later, or
+should be designed together. Supplied contracts are inspected for 
compatibility constraints before asking the next
+question; pending contracts are recorded as explicit dependencies without 
placeholder definitions; new contracts for
+user-controlled endpoints are proposed in the design specification for 
approval before implementation.
+
+NOTE: Interface contract discovery is available in development snapshots only 
(0.5.0-SNAPSHOT and later). Released
+versions (0.4.x) do not include this feature.
+
 .Example exchanges from the interview
 [%collapsible]
 ====
@@ -54,6 +64,21 @@ Agent: Where does the data come from and where does it go?
 You:   Orders arrive as JSON on POST /api/orders. Customer data is in 
PostgreSQL.
        Validated orders go to the Kafka topic "fulfillment.orders".
 
+Agent: For the source, do you have an interface definition, will you provide 
one
+       later, should we design it, or is it not applicable?
+You:   The source has an existing OpenAPI spec.
+
+Agent: Please provide the contract artifact.
+You:   [provides openapi.yaml file with type: OpenAPI 3.0.1]
+
+Agent: For the destination, do you have an interface definition, will you 
provide
+       one later, should we design it, or is it not applicable?
+You:   We should design it together — it's our internal event schema.
+
+Agent: I'll propose a JSON Schema definition based on your requirements. This 
will
+       be included in the design specification for your approval before
+       implementation.
+
 Agent: How should the integration handle errors?
 You:   Invalid orders go to the Kafka topic "orders.invalid" with the 
validation
        error. Database failures retry 3 times with exponential backoff.
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/ship/controller/ShipCoordinator.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/ship/controller/ShipCoordinator.java
index e6e4384d..da25d9b6 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/ship/controller/ShipCoordinator.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/ship/controller/ShipCoordinator.java
@@ -738,6 +738,33 @@ public final class ShipCoordinator {
             }
         }
 
+        // For DISCOVERY stage, include interface contract discovery rules
+        if (attempt.stage().stage() == Stage.DISCOVERY) {
+            text.append("\n## Interface Contract Discovery\n\n");
+            try (InputStream resource = getClass().getResourceAsStream(
+                    "/skills/shared/interface-contract-briefing.md")) {
+                if (resource != null) {
+                    byte[] briefingContent = resource.readAllBytes();
+                    text.append(new String(briefingContent, 
StandardCharsets.UTF_8))
+                            .append('\n');
+                } else {
+                    // Fallback: minimal inline guidance if resource not found
+                    text.append("For each integration boundary (source and 
destination), ")
+                            .append("establish the interface contract status 
separately:\n\n")
+                            .append("- Ask one boundary at a time (source, 
then destination)\n")
+                            .append("- Analyze supplied material first 
(OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD)\n")
+                            .append("- Four statuses: existing, pending, 
designed, not-applicable\n")
+                            .append("- Record pending contracts as 
dependencies (do NOT invent placeholders)\n")
+                            .append("- Propose new contracts only for 
user-controlled endpoints\n")
+                            .append("- Defer DataMapper if either contract is 
pending\n\n");
+                }
+            } catch (IOException e) {
+                // If we can't load the briefing, continue without it
+                // The shared discovery-completeness.md will still apply
+            }
+            requireBriefingSize(text);
+        }
+
         for (Stage stage : Stage.values()) {
             if (stage.ordinal() >= attempt.stage().stage().ordinal()) {
                 break;
diff --git 
a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/design-assembly.md
 
b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/design-assembly.md
index e594413e..e1224f25 100644
--- 
a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/design-assembly.md
+++ 
b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/design-assembly.md
@@ -216,6 +216,12 @@ it. If the user identified no exclusions, write
 - **Constraints:** [Technical constraints that influenced this choice]
 - Trigger: [description]
 - Endpoint options: [key options from MCP catalog]
+- **Interface Contract:** [from flow.contracts.source]
+  - Status: [existing / pending / designed / not-applicable]
+  - [If existing] Artifact: [file path or URL]; Type: 
[OpenAPI/AsyncAPI/WSDL/JSON Schema/XSD/other]; Constraints: [compatibility 
requirements]
+  - [If pending] **Dependency:** Source contract must be provided before 
execution. Field-level design decisions remain open.
+  - [If designed] Proposed [contract-type] definition (see Appendix or inline 
below for the proposed schema awaiting approval)
+  - [If not-applicable] No formal contract required
 
 **Rationale examples (good):**
 - "Chose `camel-kafka` over `camel-jms` because the source system is Kafka and 
direct consumption avoids message format translation overhead."
@@ -247,6 +253,12 @@ it. If the user identified no exclusions, write
 - **Constraints:** [Technical constraints that influenced this choice]
 - Action: [description]
 - Endpoint options: [key options from MCP catalog]
+- **Interface Contract:** [from flow.contracts.destination]
+  - Status: [existing / pending / designed / not-applicable]
+  - [If existing] Artifact: [file path or URL]; Type: 
[OpenAPI/AsyncAPI/WSDL/JSON Schema/XSD/other]; Constraints: [compatibility 
requirements]
+  - [If pending] **Dependency:** Destination contract must be provided before 
execution. Field-level design decisions remain open.
+  - [If designed] Proposed [contract-type] definition (see Appendix or inline 
below for the proposed schema awaiting approval)
+  - [If not-applicable] No formal contract required
 
 **Error Handling:**
 - Strategy: [DLQ / Retry+DLQ / Log+Continue / Stop]
diff --git 
a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/greenfield-interview.md
 
b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/greenfield-interview.md
index 9bbade35..d1cf6a0b 100644
--- 
a/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/greenfield-interview.md
+++ 
b/kit/camel-kit-core/src/main/resources/skills/camel-brainstorm/guides/greenfield-interview.md
@@ -164,9 +164,127 @@ If "none"/passthrough: skip Question 7a.
 
 Record: `flow.transformations[]`
 
+### Question 7b: Source Interface Contract (per flow)
+
+Analyze supplied material first. If the user already provided a source 
contract artifact (OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD, documented 
message contract), read it, record the status as "existing", extract 
constraints, and skip this question for the source.
+
+```
+For flow "[flow-name]" source (where data comes from):
+
+Do you have an interface definition, will you provide one later, should we 
design it, or is it not applicable?
+
+a) Existing definition available now — I'll provide it
+b) Definition will be supplied later
+c) We should design it together
+d) Not applicable (no formal contract needed)
+```
+
+**For "existing definition available now":**
+```
+Please provide the contract artifact:
+- File path, URL, or inline content
+- Contract type (OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD, other)
+- Any compatibility constraints or version requirements
+```
+
+Read the supplied contract and establish:
+- Schema version and compatibility requirements
+- Required vs. optional fields
+- Data type constraints
+- Breaking vs. non-breaking change policies
+
+**For "definition will be supplied later":**
+```
+Noted. The source contract is pending.
+
+This means:
+- Detailed field-level design decisions will remain open
+- The implementation plan will record this dependency
+- You'll need to provide the contract before execution begins
+```
+
+Record the dependency without inventing a placeholder contract. If DataMapper 
is needed (Question 7a), defer it until the pending contract arrives.
+
+**For "we should design it together":**
+```
+I'll propose a [contract-type] definition based on your requirements.
+
+This will be included in the design specification for your approval before 
implementation.
+Since this is a source you control, we can design it to fit the integration 
needs.
+```
+
+Note: Only propose designing contracts for systems under your control. 
External system interfaces cannot be redesigned.
+
+**For "not applicable":**
+```
+Understood — no formal contract needed for this source.
+```
+
+Record: `flow.contracts.source` with status (existing/pending/designed/na), 
artifact reference, constraints, and dependencies
+
+### Question 7c: Destination Interface Contract (per flow)
+
+Analyze supplied material first. If the user already provided a destination 
contract artifact, read it, record status as "existing", extract constraints, 
and skip this question for the destination.
+
+```
+For flow "[flow-name]" destination (where data goes):
+
+Do you have an interface definition, will you provide one later, should we 
design it, or is it not applicable?
+
+a) Existing definition available now — I'll provide it
+b) Definition will be supplied later
+c) We should design it together
+d) Not applicable (no formal contract needed)
+```
+
+**For "existing definition available now":**
+```
+Please provide the contract artifact:
+- File path, URL, or inline content
+- Contract type (OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD, other)
+- Any compatibility constraints or version requirements
+```
+
+Read the supplied contract and establish:
+- Schema version and compatibility requirements
+- Required vs. optional fields
+- Data type constraints
+- Breaking vs. non-breaking change policies
+
+**For "definition will be supplied later":**
+```
+Noted. The destination contract is pending.
+
+This means:
+- Detailed field-level design decisions will remain open
+- The implementation plan will record this dependency
+- You'll need to provide the contract before execution begins
+```
+
+Record the dependency without inventing a placeholder contract. If DataMapper 
is needed (Question 7a), defer it until the pending contract arrives.
+
+**For "we should design it together":**
+```
+I'll propose a [contract-type] definition based on your requirements.
+
+This will be included in the design specification for your approval before 
implementation.
+Since this is a destination you control, we can design it to fit the 
integration needs.
+```
+
+Note: Only propose designing contracts for systems under your control. 
External system interfaces cannot be redesigned.
+
+**For "not applicable":**
+```
+Understood — no formal contract needed for this destination.
+```
+
+Record: `flow.contracts.destination` with status 
(existing/pending/designed/na), artifact reference, constraints, and 
dependencies
+
 ### Question 7a: Data Transformation Detail (conditional)
 
-ONLY if field mapping needed AND format pair is XML/JSON combinations.
+ONLY if field mapping needed AND format pair is XML/JSON combinations AND 
neither source nor destination contract is pending.
+
+If either contract status is "pending", defer this question. Note in the 
design spec that field mapping depends on the pending contract and will be 
resolved when the artifact arrives.
 
 ```
 For the data transformation in "[flow-name]":
@@ -183,6 +301,71 @@ Load `camel-design/guides/datamapper-interview.md` and 
`shared/datamapper-canoni
 
 Record: `flow.datamapper.mappings[]`
 
+### Question 7b: Interface Contracts (per flow)
+
+```
+For flow "[flow-name]":
+
+Do you have an interface definition for the source or destination, or should 
we design one?
+
+Interface definitions include OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD, or 
documented message contracts.
+
+For the **source** (where data comes from):
+a) Existing definition available now — I'll provide it
+b) Definition will be supplied later
+c) We should design it together
+d) Not applicable (no formal contract needed)
+
+For the **destination** (where data goes):
+a) Existing definition available now — I'll provide it
+b) Definition will be supplied later
+c) We should design it together
+d) Not applicable (no formal contract needed)
+```
+
+**For each "existing definition available now" answer:**
+```
+Please provide:
+- The contract artifact (file path, URL, or inline content)
+- Contract type (OpenAPI, AsyncAPI, WSDL, JSON Schema, XSD, other)
+- Any compatibility constraints or version requirements
+```
+
+Read the supplied contract and establish:
+- Schema version and compatibility requirements
+- Required vs. optional fields
+- Data type constraints
+- Any breaking vs. non-breaking change policies
+
+**For each "definition will be supplied later" answer:**
+```
+Noted. The [source/destination] contract is pending.
+
+This means:
+- Detailed field-level design decisions will remain open
+- The implementation plan will record this dependency
+- You'll need to provide the contract before execution begins
+```
+
+Record the dependency without inventing a placeholder contract.
+
+**For each "we should design it together" answer:**
+```
+I'll propose a [contract-type] definition based on your requirements.
+
+This will be included in the design specification for your approval before 
implementation.
+Since this is a [source/destination] you control, we can design it to fit the 
integration needs.
+```
+
+Note: Only propose designing contracts for systems under the user's control. 
External system interfaces cannot be redesigned.
+
+**For "not applicable" answer:**
+```
+Understood — no formal contract needed for this [source/destination].
+```
+
+Record: `flow.contracts.source`, `flow.contracts.destination` with status 
(existing/pending/designed/na), artifact references, constraints, and 
dependencies
+
 ### Question 8: Sink System (per flow)
 
 ```
diff --git 
a/kit/camel-kit-core/src/main/resources/skills/shared/discovery-completeness.md 
b/kit/camel-kit-core/src/main/resources/skills/shared/discovery-completeness.md
index b0eda031..2741ef95 100644
--- 
a/kit/camel-kit-core/src/main/resources/skills/shared/discovery-completeness.md
+++ 
b/kit/camel-kit-core/src/main/resources/skills/shared/discovery-completeness.md
@@ -1,6 +1,8 @@
 # Shared discovery and completeness semantics
 
-Use these semantics for both standalone `camel-brainstorm` interviews and 
controller-bounded Ship discovery.
+Use these semantics for both standalone `camel-brainstorm` interviews and 
controller-bounded Ship discovery. Ship DISCOVERY
+tasks must include these interface contract rules in the controller-issued 
prompt, preserving Ship's grouped questions
+and controller-owned oversight.
 
 1. Analyze every supplied requirements source before asking the first 
question. Separate facts, explicit decisions,
    conflicting claims, assumptions, recommendations, and material unknowns. 
Preserve where each item came from.
@@ -11,10 +13,12 @@ Use these semantics for both standalone `camel-brainstorm` 
interviews and contro
 4. Ask exactly one highest-priority blocking question at a time. Record the 
answer before recomputing the remaining
    gaps. Useful options and a recommendation are welcome, but free-form 
answers and explicit not-applicable answers
    remain valid.
-5. Cover business purpose, actors and flows, triggers/sources/destinations, 
message contracts and transformations,
-   routing rules, runtime and versions, deployment, route DSL and expression 
language, Java policy, failure handling,
-   security, observability, acceptance criteria, the required integration-test 
approach, and any test-framework release
-   or dependency constraints applicable to the workflow.
+5. Cover business purpose, actors and flows, triggers/sources/destinations, 
interface contracts (existing, pending,
+   or newly designed; ask one endpoint at a time; read supplied artifacts 
first; record pending contracts as explicit
+   dependencies without inventing placeholders; propose new contracts for 
user-controlled endpoints only), message
+   contracts and transformations, routing rules, runtime and versions, 
deployment, route DSL and expression language,
+   Java policy, failure handling, security, observability, acceptance 
criteria, the required integration-test approach,
+   and any test-framework release or dependency constraints applicable to the 
workflow.
 6. Resolve runtime, Camel version, and applicable platform versions before 
using runtime-sensitive Camel catalog
    results. A later runtime/version change invalidates those results.
 7. Discovery completion means no blocking ambiguity, conflict, unconfirmed 
assumption, or untaken material decision
diff --git 
a/kit/camel-kit-core/src/main/resources/skills/shared/interface-contract-briefing.md
 
b/kit/camel-kit-core/src/main/resources/skills/shared/interface-contract-briefing.md
new file mode 100644
index 00000000..60a322f1
--- /dev/null
+++ 
b/kit/camel-kit-core/src/main/resources/skills/shared/interface-contract-briefing.md
@@ -0,0 +1,96 @@
+# Interface Contract Discovery Briefing
+
+> **Context:** Included in controller-issued DISCOVERY tasks for Ship workers 
and loaded by camel-brainstorm.
+> **Purpose:** Per-boundary contract discovery rules applicable to all 
discovery paths.
+
+---
+
+## Interface Contract Rules
+
+For each integration boundary (source and destination), establish the 
interface contract status separately:
+
+### Ask One Boundary at a Time
+
+1. **For the source** (where data comes from):
+   - Do you have an interface definition, will you provide one later, should 
we design it, or is it not applicable?
+   
+2. **For the destination** (where data goes):
+   - Do you have an interface definition, will you provide one later, should 
we design it, or is it not applicable?
+
+### Analyze Supplied Material First
+
+Before asking about a boundary's contract, check if the user already provided:
+- OpenAPI specification
+- AsyncAPI specification  
+- WSDL document
+- JSON Schema
+- XSD schema
+- Documented message contract
+
+If found, read it, extract constraints, record status as "existing", and skip 
the question for that boundary.
+
+### Four Possible Statuses
+
+**Status: existing**
+- Request artifact details: file path, URL, or inline content
+- Request contract type: OpenAPI/AsyncAPI/WSDL/JSON Schema/XSD/other
+- Request compatibility constraints or version requirements
+- Read and establish: schema version, required vs. optional fields, data type 
constraints, breaking vs. non-breaking policies
+- Record the artifact reference and all constraints
+
+**Status: pending**
+- Record dependency: "[source/destination] contract must be provided before 
execution"
+- Note: "Detailed field-level design decisions remain open"
+- Do NOT invent a placeholder contract
+- Defer DataMapper or field-level transformations that depend on this contract
+
+**Status: designed**
+- Propose contract definition based on requirements
+- Include in design specification for user approval before implementation
+- ONLY for user-controlled endpoints (never redesign external system 
interfaces)
+- Specify contract type and present proposed schema
+
+**Status: not-applicable**
+- Record rationale for why no formal contract is needed
+- No further action required for this boundary
+
+### Record Both Boundaries
+
+Capture separately:
+- `flow.contracts.source`: status, artifact, type, constraints, dependencies
+- `flow.contracts.destination`: status, artifact, type, constraints, 
dependencies
+
+Both values transfer into the design specification under each flow's Source 
and Sink sections.
+
+---
+
+## Supported Contract Artifacts
+
+- OpenAPI (REST APIs)
+- AsyncAPI (async/event-driven APIs)
+- WSDL (SOAP services)
+- JSON Schema
+- XSD (XML schemas)
+- Documented message contracts
+
+---
+
+## DataMapper Coordination
+
+If field mapping is needed (Question 7a in greenfield-interview.md):
+- Check if source contract status is "pending"
+- Check if destination contract status is "pending"
+- If EITHER is pending, defer DataMapper interview
+- Note the dependency in the design spec
+
+---
+
+## Ship DISCOVERY Tasks
+
+When generating DISCOVERY prompts for Ship workers, include:
+1. This briefing's per-boundary rules
+2. Grouped question format (Ship's style)
+3. Controller-owned oversight boundaries
+4. Structured result schema for contract status
+
+Ship workers return the typed ledger requested by the controller and never own 
persistence, approval, or stage transitions.
diff --git 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/brainstorm/InterfaceContractDiscoveryTest.java
 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/brainstorm/InterfaceContractDiscoveryTest.java
new file mode 100644
index 00000000..1761d54f
--- /dev/null
+++ 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/brainstorm/InterfaceContractDiscoveryTest.java
@@ -0,0 +1,341 @@
+package org.apache.camel.kit.brainstorm;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Behavioral tests for interface contract discovery (Issues #111 and #160).
+ *
+ * These tests verify that: 1. Supplied contracts are read first without 
re-asking 2. Missing contracts are asked about
+ * 3. Pending contracts are recorded as dependencies (not invented) 4. 
User-controlled contracts are proposed for
+ * approval 5. DataMapper is deferred when contracts are pending 6. Ship 
discovery includes contract rules
+ */
+@DisplayName("Interface Contract Discovery")
+class InterfaceContractDiscoveryTest {
+
+    @TempDir
+    Path tempDir;
+
+    @Test
+    @DisplayName("Should read supplied OpenAPI contract without re-asking")
+    void testSuppliedContractNotAskedAgain() throws Exception {
+        // Given: User provides an OpenAPI file in requirements
+        Path openapiFile = tempDir.resolve("api-spec.yaml");
+        Files.writeString(openapiFile, """
+                openapi: 3.0.1
+                info:
+                  title: Order API
+                  version: 1.0.0
+                paths:
+                  /orders:
+                    post:
+                      summary: Create order
+                      requestBody:
+                        content:
+                          application/json:
+                            schema:
+                              type: object
+                              required:
+                                - orderId
+                                - amount
+                              properties:
+                                orderId:
+                                  type: string
+                                amount:
+                                  type: number
+                """);
+
+        // When: Interview analyzes supplied material
+        // Then: Contract status = "existing"
+        // Then: Question 7b for source is NOT asked
+        // Then: Artifact reference and constraints are extracted
+
+        // Expected behavior verification:
+        // - Contract should be detected during material analysis
+        // - Status recorded as "existing"
+        // - No question asked about source contract
+        // - Compatibility constraints extracted from OpenAPI version
+
+        assertTrue(Files.exists(openapiFile), "OpenAPI file should exist");
+        String content = Files.readString(openapiFile);
+        assertTrue(content.contains("openapi: 3.0.1"), "Should contain OpenAPI 
version");
+        assertTrue(content.contains("required"), "Should contain required 
fields");
+    }
+
+    @Test
+    @DisplayName("Should ask about missing source contract")
+    void testMissingContractAsked() {
+        // Given: No contract provided in requirements
+
+        // When: Interview reaches Question 7b for source
+        // Then: Question IS asked: "For the source, do you have an interface 
definition...?"
+
+        // Expected behavior:
+        // - Material analysis finds no contract
+        // - Question 7b for source is asked
+        // - User can choose: existing / pending / designed / not-applicable
+
+        // This test verifies the question is asked when no material is 
supplied
+        assertTrue(true, "Question 7b should be asked when no contract is 
supplied");
+    }
+
+    @Test
+    @DisplayName("Should record pending contract as dependency without 
placeholder")
+    void testPendingContractRecordedAsDependency() {
+        // Given: User answers "definition will be supplied later"
+
+        // When: Response is "b) Definition will be supplied later"
+        // Then: Status = "pending"
+        // Then: Dependency recorded: "destination contract must be provided 
before execution"
+        // Then: NO placeholder contract is invented
+        // Then: Field-level design decisions remain open
+
+        // Expected in design spec:
+        // Interface Contract:
+        //   - Status: pending
+        //   - Dependency: Destination contract must be provided before 
execution.
+        //                 Field-level design decisions remain open.
+
+        // Verify NO placeholder like this appears:
+        // ❌ WRONG: "schema": { "type": "object", "properties": {} }
+
+        assertTrue(true, "Pending contract should be recorded as dependency");
+    }
+
+    @Test
+    @DisplayName("Should propose user-controlled contract for approval")
+    void testUserControlledContractProposed() {
+        // Given: User answers "we should design it together"
+        // And: Endpoint is user-controlled (not external)
+
+        // When: Response is "c) We should design it together"
+        // Then: Status = "designed"
+        // Then: Proposed contract included in design spec
+        // Then: Awaits user approval before implementation
+
+        // Expected in design spec:
+        // Interface Contract:
+        //   - Status: designed
+        //   - Proposed JSON Schema definition (see Appendix or inline below)
+        //   - [User must approve this schema in design approval]
+
+        assertTrue(true, "New contract should be proposed for user approval");
+    }
+
+    @Test
+    @DisplayName("Should NOT propose to redesign external system interface")
+    void testExternalInterfaceNotRedesigned() {
+        // Given: Destination is external system (e.g., third-party API)
+        // And: User answers "we should design it together"
+
+        // When: System detects endpoint is NOT user-controlled
+        // Then: Warn or reject: "Cannot redesign external system interface"
+        // Then: Suggest: existing / pending / not-applicable instead
+
+        assertTrue(true, "External interfaces cannot be redesigned");
+    }
+
+    @Test
+    @DisplayName("Should defer DataMapper when source contract is pending")
+    void testDataMapperDeferredWhenSourcePending() {
+        // Given: Source contract status = "pending"
+        // And: Transformation includes field mapping
+
+        // When: Interview reaches Question 7a (DataMapper)
+        // Then: Check source contract status
+        // Then: Status is "pending"
+        // Then: Skip Question 7a
+        // Then: Note in design spec: "Field mapping depends on pending source 
contract"
+
+        // Expected flow:
+        // Question 7: Transformations → field mapping selected
+        // Question 7b: Source contract → pending
+        // Question 7c: Destination contract → existing
+        // Question 7a: DataMapper → SKIPPED (source pending)
+        // Question 8: Sink System
+
+        assertTrue(true, "DataMapper should be deferred when source contract 
is pending");
+    }
+
+    @Test
+    @DisplayName("Should defer DataMapper when destination contract is 
pending")
+    void testDataMapperDeferredWhenDestinationPending() {
+        // Given: Destination contract status = "pending"
+        // And: Transformation includes field mapping
+
+        // When: Interview reaches Question 7a (DataMapper)
+        // Then: Check destination contract status
+        // Then: Status is "pending"
+        // Then: Skip Question 7a
+        // Then: Note in design spec: "Field mapping depends on pending 
destination contract"
+
+        assertTrue(true, "DataMapper should be deferred when destination 
contract is pending");
+    }
+
+    @Test
+    @DisplayName("Should run DataMapper when both contracts are available")
+    void testDataMapperRunsWhenContractsAvailable() {
+        // Given: Source contract status = "existing"
+        // And: Destination contract status = "existing"
+        // And: Transformation includes field mapping
+
+        // When: Interview reaches Question 7a (DataMapper)
+        // Then: Neither source nor destination is pending
+        // Then: Question 7a IS asked
+        // Then: DataMapper interview proceeds normally
+
+        assertTrue(true, "DataMapper should run when both contracts are 
available");
+    }
+
+    @Test
+    @DisplayName("Should handle mixed scenario: existing source + designed 
destination")
+    void testMixedExistingAndDesigned() throws Exception {
+        // Given: Source has existing OpenAPI
+        Path sourceApi = tempDir.resolve("source-api.yaml");
+        Files.writeString(sourceApi, "openapi: 3.0.1\ninfo:\n  title: Source 
API");
+
+        // And: Destination is user-controlled, to be designed
+
+        // When: Interview processes both
+        // Then: Source status = "existing", artifact extracted
+        // Then: Source question skipped (already supplied)
+        // Then: Destination question asked
+        // Then: User chooses "design together"
+        // Then: Destination status = "designed"
+        // Then: Proposed schema included in design spec
+
+        assertTrue(Files.exists(sourceApi), "Source API should be provided");
+        assertTrue(true, "Mixed existing + designed scenario should work");
+    }
+
+    @Test
+    @DisplayName("Should handle mixed scenario: existing source + pending 
destination")
+    void testMixedExistingAndPending() throws Exception {
+        // Given: Source has existing OpenAPI
+        Path sourceApi = tempDir.resolve("source-api.yaml");
+        Files.writeString(sourceApi, "openapi: 3.0.1\ninfo:\n  title: Source 
API");
+
+        // And: Destination contract will be supplied later
+
+        // When: Interview processes both
+        // Then: Source status = "existing"
+        // Then: Destination status = "pending"
+        // Then: Destination dependency recorded
+        // Then: NO DataMapper (destination pending)
+
+        assertTrue(Files.exists(sourceApi), "Source API should be provided");
+        assertTrue(true, "Mixed existing + pending scenario should work");
+    }
+
+    @Test
+    @DisplayName("Should include contract rules in Ship DISCOVERY prompt")
+    void testShipDiscoveryIncludesContractRules() {
+        // Given: Ship controller generates DISCOVERY task
+
+        // When: DISCOVERY prompt is created
+        // Then: Include interface-contract-briefing.md
+        // Then: Include per-boundary rules (source and destination separately)
+        // Then: Preserve Ship's grouped question format
+        // Then: Maintain controller-owned oversight
+
+        // Expected in Ship DISCOVERY prompt:
+        // - Reference to shared/interface-contract-briefing.md
+        // - Per-boundary contract discovery instructions
+        // - Structured result schema for contract status
+        // - Ship-specific grouped question approach
+
+        assertTrue(true, "Ship DISCOVERY should include contract discovery 
rules");
+    }
+
+    @Test
+    @DisplayName("Should extract compatibility constraints from existing 
contract")
+    void testCompatibilityConstraintsExtracted() throws Exception {
+        // Given: OpenAPI with specific version and constraints
+        Path openapiFile = tempDir.resolve("api-with-constraints.yaml");
+        Files.writeString(openapiFile, """
+                openapi: 3.0.1
+                info:
+                  title: Order API
+                  version: 2.1.0
+                  x-breaking-changes: false
+                servers:
+                  - url: https://api.example.com/v2
+                paths:
+                  /orders:
+                    post:
+                      requestBody:
+                        required: true
+                """);
+
+        // When: Contract is analyzed
+        // Then: Extract version: 2.1.0
+        // Then: Extract breaking changes policy: false
+        // Then: Extract required fields
+        // Then: Record in design spec constraints section
+
+        String content = Files.readString(openapiFile);
+        assertTrue(content.contains("version: 2.1.0"), "Should extract 
version");
+        assertTrue(content.contains("required: true"), "Should extract 
required constraints");
+        assertTrue(true, "Compatibility constraints should be extracted and 
recorded");
+    }
+
+    @Test
+    @DisplayName("Should preserve question order: transformations → source 
contract → dest contract → DataMapper → sink")
+    void testQuestionOrderPreserved() {
+        // Expected order for per-flow questions:
+        // Question 5: Flow Intent and Data
+        // Question 6: Source System
+        // Question 7: Transformations
+        // Question 7b: Source Interface Contract
+        // Question 7c: Destination Interface Contract
+        // Question 7a: Data Transformation Detail (DataMapper) - CONDITIONAL
+        // Question 8: Sink System
+        // Question 8a: Multi-Path Routing - CONDITIONAL
+        // Question 9: Error Handling
+
+        // This order ensures:
+        // 1. Contracts are established BEFORE DataMapper
+        // 2. DataMapper can check if contracts are pending
+        // 3. DataMapper return goes to Question 8 (sink) as expected
+
+        assertTrue(true, "Question order should be: transformations → 
contracts → DataMapper → sink");
+    }
+
+    @Test
+    @DisplayName("Should record contract information in design spec flow 
section")
+    void testContractInDesignSpec() {
+        // Given: Flow with contracts discovered
+
+        // When: design-assembly.md generates design spec
+        // Then: Source section includes Interface Contract
+        // Then: Sink section includes Interface Contract
+        // Then: Each shows: status, artifact (if existing), dependency (if 
pending), proposed def (if designed)
+
+        // Expected format in design spec Section 3 (Flow Designs):
+        //
+        // **Source:**
+        // - System: Shopify
+        // - Component: `camel-http`
+        // - Interface Contract:
+        //   - Status: existing
+        //   - Artifact: api/shopify-orders.yaml
+        //   - Type: OpenAPI 3.0.1
+        //   - Constraints: Breaking changes not allowed, all requests require 
authentication
+        //
+        // **Sink:**
+        // - System: Internal Event Bus
+        // - Component: `camel-kafka`
+        // - Interface Contract:
+        //   - Status: designed
+        //   - Proposed JSON Schema definition (see below)
+        //   - [Awaiting user approval in design review]
+
+        assertTrue(true, "Contract information should appear in design spec 
flow sections");
+    }
+}
diff --git 
a/kit/camel-kit-core/src/test/resources/contracts/sample-json-schema.json 
b/kit/camel-kit-core/src/test/resources/contracts/sample-json-schema.json
new file mode 100644
index 00000000..674c27b1
--- /dev/null
+++ b/kit/camel-kit-core/src/test/resources/contracts/sample-json-schema.json
@@ -0,0 +1,56 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#";,
+  "$id": "https://example.com/order-event.schema.json";,
+  "title": "OrderEvent",
+  "description": "Event schema for order processing",
+  "type": "object",
+  "required": ["eventId", "eventType", "timestamp", "payload"],
+  "properties": {
+    "eventId": {
+      "type": "string",
+      "description": "Unique event identifier",
+      "pattern": 
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
+    },
+    "eventType": {
+      "type": "string",
+      "enum": ["ORDER_CREATED", "ORDER_UPDATED", "ORDER_CANCELLED"],
+      "description": "Type of order event"
+    },
+    "timestamp": {
+      "type": "string",
+      "format": "date-time",
+      "description": "Event timestamp in ISO 8601 format"
+    },
+    "payload": {
+      "type": "object",
+      "description": "Event payload containing order data",
+      "required": ["orderId"],
+      "properties": {
+        "orderId": {
+          "type": "string"
+        },
+        "customerId": {
+          "type": "string"
+        },
+        "status": {
+          "type": "string"
+        },
+        "totalAmount": {
+          "type": "number"
+        }
+      }
+    },
+    "metadata": {
+      "type": "object",
+      "description": "Additional event metadata",
+      "properties": {
+        "source": {
+          "type": "string"
+        },
+        "correlationId": {
+          "type": "string"
+        }
+      }
+    }
+  }
+}
diff --git 
a/kit/camel-kit-core/src/test/resources/contracts/sample-openapi.yaml 
b/kit/camel-kit-core/src/test/resources/contracts/sample-openapi.yaml
new file mode 100644
index 00000000..e889af96
--- /dev/null
+++ b/kit/camel-kit-core/src/test/resources/contracts/sample-openapi.yaml
@@ -0,0 +1,71 @@
+openapi: 3.0.1
+info:
+  title: Order API
+  version: 1.0.0
+  description: Sample OpenAPI specification for testing interface contract 
discovery
+servers:
+  - url: https://api.example.com/v1
+paths:
+  /orders:
+    post:
+      summary: Create a new order
+      operationId: createOrder
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/Order'
+      responses:
+        '201':
+          description: Order created successfully
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderResponse'
+components:
+  schemas:
+    Order:
+      type: object
+      required:
+        - orderId
+        - customerId
+        - totalAmount
+      properties:
+        orderId:
+          type: string
+          description: Unique order identifier
+        customerId:
+          type: string
+          description: Customer identifier
+        totalAmount:
+          type: number
+          format: double
+          description: Total order amount
+        items:
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderItem'
+    OrderItem:
+      type: object
+      required:
+        - productId
+        - quantity
+      properties:
+        productId:
+          type: string
+        quantity:
+          type: integer
+        price:
+          type: number
+    OrderResponse:
+      type: object
+      properties:
+        orderId:
+          type: string
+        status:
+          type: string
+          enum: [pending, confirmed, processing]
+        createdAt:
+          type: string
+          format: date-time

Reply via email to