luigidemasi commented on code in PR #214:
URL: https://github.com/apache/camel-kit/pull/214#discussion_r4739681228


##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -62,14 +62,49 @@ public static void main(String[] args) throws Exception {
 
         Files.createDirectories(outputDir);
 
-        List<DocumentDomain> domains = buildDomains(cacheDir, resourcesDir);
+        // Get collection metadata from system properties first
+        String collectionId = System.getProperty("collection.id", 
"apache-camel");
+        String collectionVersion = System.getProperty("collection.version",
+                Instant.now().toString().substring(0, 19).replace(':', '-'));
+
+        LOG.info("Collection ID: {}", collectionId);
+        LOG.info("Collection Version: {}", collectionVersion);
+
+        // Build domains based on collection ID
+        List<DocumentDomain> domains = buildDomains(cacheDir, resourcesDir, 
collectionId);
+
+        // Derive collection sources from actual domains built, or validate 
user-provided sources
+        String collectionSources = System.getProperty("collection.sources");
+        if (collectionSources != null && !collectionSources.isBlank()) {
+            // Validate user-provided sources is valid JSON array
+            try {
+                com.fasterxml.jackson.databind.ObjectMapper mapper = new 
com.fasterxml.jackson.databind.ObjectMapper();

Review Comment:
   **P1 · Restore the indexer build**
   
   A clean Java 21 compilation stops here with `package 
com.fasterxml.jackson.databind does not exist`. `knowledge/indexer` already 
depends on `org.json`, and its parsers use `JSONArray` and `JSONObject`. Reuse 
that library to validate the array and serialize the manifest, then run the 
indexer and MCP tests together.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -129,8 +172,20 @@ public ResolvedIndex resolve() throws IOException {
         }
 
         // 2. Manifest + local cache
-        Path cacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();
+        Path baseCacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();
+        String collectionId = 
validateAndNormalizeCollectionId(config.collectionId());
+
+        // Backward compatibility: apache-camel collection uses root cache 
directory
+        // Custom collections use subdirectories isolated from community 
pruning: {cacheDir}/collections/{collection-id}/
+        Path cacheDir = "apache-camel".equals(collectionId)
+                ? baseCacheDir
+                : baseCacheDir.resolve("collections").resolve(collectionId);

Review Comment:
   **P1 · Keep custom snapshots outside the community prune scope**
   
   Both Foo and Bar reopened offline from this layout. I then activated a valid 
community release in the same cache. `prune(baseCacheDir, …)` recursively 
removed `collections`, and Foo’s next pinned offline search failed. Older 
community clients also prune that root. Put the custom namespace outside the 
directory those clients prune, and cover both custom collections across a 
community update and restart.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -133,12 +178,31 @@ private static Path resolvePath(String sysProp, String 
argValue, String defaultV
         return Path.of(defaultValue).toAbsolutePath();
     }
 
-    private static List<DocumentDomain> buildDomains(Path cacheDir, Path 
resourcesDir) throws IOException {
+    private static List<DocumentDomain> buildDomains(Path cacheDir, Path 
resourcesDir, String collectionId)
+            throws IOException {
         List<DocumentDomain> domains = new ArrayList<>();
 
-        // Add all registered domains here
-        domains.add(new ApacheCamelDomain(cacheDir, resourcesDir));
+        // For now, only apache-camel collection is supported with 
ApacheCamelDomain
+        // Custom collections require custom DocumentDomain implementations
+        if ("apache-camel".equals(collectionId)) {
+            domains.add(new ApacheCamelDomain(cacheDir, resourcesDir));
+        } else {
+            LOG.warn("Custom collection '{}' requested, but only 
ApacheCamelDomain is registered. "
+                    + "Building with ApacheCamelDomain. To index custom 
sources, implement and register "
+                    + "a DocumentDomain for your collection.", collectionId);
+            domains.add(new ApacheCamelDomain(cacheDir, resourcesDir));

Review Comment:
   **P1 · Build the sources registered for the selected collection**
   
   Both branches construct `ApacheCamelDomain`. With the missing Jackson 
classes supplied only for a local probe, the production selector returned 
`apache_camel` for both `foo-integration` and `bar-platform`, despite different 
source lists. The builder can stamp vendor provenance on Apache content. Select 
the registered domains for the requested ID, reject unknown IDs, and derive the 
source list from the inputs actually indexed. The current default list also 
omits `apache/camel-website`, which supplies advisories and release notes. 
Exercise the two disjoint corpora through the build entry point.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -534,6 +604,48 @@ void moveAtomically(Path source, Path target) throws 
IOException {
         Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, 
StandardCopyOption.REPLACE_EXISTING);
     }
 
+    /**
+     * Verify that a staged index contains the expected collection metadata 
before activating it.
+     * Opens the index, reads collection metadata, checks it matches 
configuration, then closes.
+     * This prevents mislabeled releases from displacing working snapshots.
+     *
+     * @param indexDir The directory containing the extracted Lucene index 
files (unzip strips the archive prefix)
+     */
+    private void verifyStagedIndex(Path indexDir) throws IOException {
+        // unzip extracts files directly to indexDir, not to a subdirectory
+        try (FSDirectory directory = FSDirectory.open(indexDir);
+             DirectoryReader reader = DirectoryReader.open(directory)) {
+
+            IndexSearcher searcher = new IndexSearcher(reader);
+
+            // Read collection metadata from the staged index
+            TopDocs td = searcher.search(
+                    new TermQuery(new Term(KnowledgeFields.ID, 
KnowledgeFields.INDEX_META_ID)), 1);
+
+            String indexCollectionId = null;
+            if (td.scoreDocs.length > 0) {
+                Document metaDoc = searcher.doc(td.scoreDocs[0].doc);
+                indexCollectionId = metaDoc.get(KnowledgeFields.COLLECTION_ID);

Review Comment:
   **P1 · Verify the published snapshot identity before activation**
   
   Staging now opens the correct directory. It only reads the collection ID, 
though. A valid archive whose manifest declared `collectionVersion=2.0.0` was 
activated and served documents even though `camel_docs_index_info` reported the 
embedded `2026.11.29-120000`. Carry the declared collection version from the 
manifest into this check and reject disagreement before switching `current`. 
Compare the corpus version with its embedded counterpart, preserving the 
independent release timestamp and legacy community manifests.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java:
##########
@@ -187,6 +207,65 @@ private String readIndexEmbeddingModel() {
         return null;
     }
 
+    /**
+     * Verify collection metadata matches configuration. Reads collection ID, 
version, and sources from the index and
+     * checks against the configured collection. For backward compatibility, 
missing collection metadata is treated as
+     * "apache-camel" collection.
+     */
+    private void verifyCollectionMetadata() throws IOException {
+        TopDocs td = searcher.search(
+                new TermQuery(new Term(KnowledgeFields.ID, 
KnowledgeFields.INDEX_META_ID)), 1);
+
+        // Read collection metadata from index (or default to apache-camel for 
legacy)
+        if (td.scoreDocs.length > 0) {
+            Document metaDoc = searcher.doc(td.scoreDocs[0].doc);
+            collectionId = metaDoc.get(KnowledgeFields.COLLECTION_ID);
+            collectionVersion = 
metaDoc.get(KnowledgeFields.COLLECTION_VERSION);
+            collectionSources = 
metaDoc.get(KnowledgeFields.COLLECTION_SOURCES);
+
+            // Backward compatibility: indexes without collection metadata are 
treated as "apache-camel"
+            if (collectionId == null) {
+                collectionId = "apache-camel";
+                LOG.info("Index has no collection metadata, treating as 
'apache-camel' (legacy index)");
+            }
+        } else {
+            // Legacy index without any metadata document
+            collectionId = "apache-camel";
+            LOG.warn("Index has no metadata document - treating as legacy 
'apache-camel' collection");
+        }
+
+        // Apply collection selection policy to both legacy and stamped indexes
+        String requestedCollection = config.collectionId();
+        if (!collectionId.equals(requestedCollection)) {
+            String message = String.format(
+                    "Collection mismatch: requested '%s' but index contains 
'%s' (version: %s).\n" +
+                                           "Index location: %s\n" +
+                                           "Available collections may be 
cached at: %s/%s/",
+                    requestedCollection, collectionId,
+                    collectionVersion != null ? collectionVersion : "unknown",
+                    resolvedIndex.dir(),
+                    config.cacheDir(), requestedCollection);
+
+            if (config.allowFallback()) {

Review Comment:
   **P1 · Limit opt-in fallback to the documented community collection**
   
   The new lookup successfully uses the cached `apache-camel` collection when a 
custom release is missing. This check still accepts any loaded ID when fallback 
is enabled. Requesting Bar with a local Foo index returned `foo-chunk-1` and 
`foo-chunk-2` over MCP. `IndexResolverConfig.allowFallback()` specifies 
`apache-camel` as the fallback. Enforce that identity for direct paths and 
warm-cache opens as well as staged downloads, and test a third collection as 
the negative case.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/KnowledgeMcpServer.java:
##########
@@ -74,18 +81,19 @@ public String camel_docs_component_info(
         }
     }
 
-    @Tool(description = "Search Apache Camel documentation by keyword. " +
+    @Tool(description = "Search documentation by keyword. " +
                         "Covers component references, EIP patterns, user 
manual, migration guides, " +
-                        "getting started guides, and release notes.")
+                        "getting started guides, and release notes from the 
loaded collection.")
     public String camel_docs_search(
             @ToolArg(description = "Search query, e.g., 'configure SSL for 
HTTP component'") String query,
-            @ToolArg(description = "Camel version filter (major.minor, e.g., 
'4.14'). Optional.",
+            @ToolArg(description = "Version filter (major.minor, e.g., 
'4.14'). Optional.",
                      required = false) String version,
             @ToolArg(description = "Maximum results to return (default 5, max 
25)",
                      required = false) Integer max_results) {
         try {
+            // Search across all domains in the loaded collection (null = all 
domains)
             List<LuceneSearchService.SearchResult> results
-                    = searchService.search(DOMAIN, query, 
normalizeMinor(version), null, clamp(max_results, 5));
+                    = searchService.search(null, query, 
normalizeMinor(version), null, clamp(max_results, 5));

Review Comment:
   **P2 · Preserve the community search domain**
   
   Generic search now works for each custom fixture. Passing `null` for every 
collection also broadens the default community search. 
`KnowledgeInputBoundaryTest.querySyntaxCannotSelectFieldsOrTurnIntoMatchAll` 
now returns the `foreign-domain` document for an ordinary matching query. Apply 
the same collection-aware domain selection used by `camel_docs_component_info`, 
and exercise a mixed-domain community fixture alongside a custom one.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
.github/workflows/index-release.yml:
##########
@@ -46,14 +46,24 @@ jobs:
       - name: Build reviewed index
         run: ./mvnw install -pl knowledge/index -am -B -Dformat.skip=true
 
+      # Read collection ID before quality gate to configure tests appropriately
+      - name: Read collection metadata
+        id: collection
+        run: |
+          COLLECTION_ID=$(jq -r '.collectionId // "apache-camel"' 
knowledge/index/src/main/resources/index.json)
+          echo "collection_id=$COLLECTION_ID" >> "$GITHUB_OUTPUT"
+          echo "Collection ID: $COLLECTION_ID"
+
       # Quality gate — the mcp tests evaluate the reviewed in-repo index
       # (knowledge.index.path in test config points at 
knowledge/index/src/main/resources/knowledge-index).
       # eval.requireVectors makes a disabled vector leg (model mismatch / 
failed
       # embedding self-check) a hard failure instead of graceful degradation.
+      # For apache-camel, use existing quality thresholds; custom collections 
skip corpus-specific checks.
       - name: Retrieval quality gate
         run: >
           ./mvnw test -pl knowledge/mcp -am -B -Dformat.skip=true
           -Deval.requireVectors=true
+          -Dknowledge.index.collection-id=${{ 
steps.collection.outputs.collection_id }}

Review Comment:
   **P1 · Run a quality gate for the selected corpus**
   
   I ran `RetrievalQualityTest.productionSearchQuality` against Foo with this 
collection property and `eval.requireVectors=true`. It failed at the 
unconditional Camel 4.22 coverage assertion. The test also requires Camel Timer 
IDs, the `apache_camel` domain and community relevance judgments. Select a 
corpus-appropriate evaluation dataset and keep the shared vector and retrieval 
checks. A custom release should pass with its own expected documents and fail 
when they are missing.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/README.md:
##########
@@ -119,28 +119,190 @@ the Apache advisory is still indexed without the 
optional enrichment; failures a
 later rebuild retries them. Rerun the rebuild command after updating the 
indexer to enrich previously
 skipped CVEs; completed index files are not changed automatically.
 
+## Collections
+
+Knowledge supports **named, versioned collections** for custom documentation 
sources. Each collection is isolated with its own index, cache, and release 
artifacts.
+
+### Collection Metadata
+
+Every collection stores:
+- **Collection ID**: unique identifier (e.g., `apache-camel`, `custom-vendor`)
+- **Collection version**: version string or content digest
+- **Collection sources**: JSON array of source repositories and versions
+
+The default `apache-camel` collection includes Apache Camel core, Quarkus, and 
Spring Boot documentation.
+
+### Building a Custom Collection
+
+```bash
+# Create your DocumentDomain implementations in indexer module
+# Then build with collection metadata:
+
+# Collection ID: unique identifier (letters, digits, hyphens only)
+# Collection version: version string or timestamp
+# Collection sources: JSON array describing indexed repositories
+./mvnw install -pl knowledge/index -Prebuild-index -am -B \
+  -Dcollection.id=my-vendor \
+  -Dcollection.version=1.0.0 \
+  
-Dcollection.sources='[{"repo":"my-org/docs","branch":"main","tag":"v1.0.0"}]'
+```
+
+**Collection sources format**: JSON array where each object can contain:
+- `repo`: repository identifier (e.g., `"apache/camel"`)
+- `branch`: branch name (optional)
+- `tag`: git tag or version (optional)
+- Any other metadata relevant to your documentation sources
+
+Example sources:
+```json
+[
+  {"repo":"apache/camel","branch":"main"},
+  {"repo":"apache/camel-quarkus","tag":"3.17.0"},
+  {"repo":"apache/camel-spring-boot","branch":"main"}
+]
+```
+
+The `camel_docs_index_info` MCP tool returns the parsed sources array showing 
what was indexed.
+
+Package the generated `knowledge-index/` as a GitHub Release asset tagged 
`knowledge-index-v1-my-vendor-YYYY.MM.DD-HHMMSS`.
+
+### Selecting a Collection
+
+Configure which collection the MCP server loads:
+
+```properties
+# Collection ID to load (default: apache-camel)
+knowledge.index.collection-id=my-vendor
+
+# Optional: pin exact version (default: latest available)
+knowledge.index.version=2024.11.29-123456
+
+# Whether to use mismatched collection if requested one unavailable (default: 
false)
+knowledge.index.allow-fallback=false
+```
+
+Collections are cached in collection-specific directories:
+```
+~/.camel-kit/knowledge-index/
+  2024.11.29-120000/              # apache-camel (root directory for backward 
compatibility)
+  current                          # points to active apache-camel version
+  collections/
+    my-vendor/
+      2024.11.29-130000/
+      current
+```
+
+### Inspecting Collection Provenance
+
+Call `camel_docs_index_info()` to see the loaded collection:
+
+```json
+{
+  "collection_id": "apache-camel",
+  "collection_version": "2024.11.29-120000",
+  "collection_sources": [
+    {"repo": "apache/camel"},
+    {"repo": "apache/camel-quarkus"},
+    {"repo": "apache/camel-spring-boot"}
+  ],
+  "total_docs": 20367,
+  "embedding_model": "granite-embedding-small-english-r2-q8",
+  "search_mode": "hybrid+rerank",
+  "versions": ["4.18", "4.19", "4.20", "4.21", "4.22"],
+  "doc_types": {
+    "component": 450,
+    "eip": 65,
+    "manual": 850
+  }
+}
+```
+
+### Troubleshooting Collection Mismatches
+
+When a required collection is not found:
+
+```
+Collection mismatch: requested 'my-vendor' but index contains 'apache-camel' 
(version: 2024.11.29-120000).
+Index location: ~/.camel-kit/knowledge-index/2024.11.29-120000/
+Available collections may be cached at: 
~/.camel-kit/knowledge-index/collections/my-vendor/
+
+To use the loaded collection, set knowledge.index.collection-id=apache-camel
+Or enable fallback with knowledge.index.allow-fallback=true (not recommended 
for production)
+```
+
+Resolution steps:
+1. Verify the collection ID matches your configuration
+2. Check GitHub releases for `knowledge-index-v1-my-vendor-*` tags
+3. For local development, use `knowledge.index.path=/path/to/index`
+4. Inspect cache directory for available collections
+
 ## Index Distribution
 
 The index is **data, not code** — it is published as a GitHub Release asset, 
not a Maven artifact.
 Reindexing is performed on a branch; the generated index is committed with a 
signed commit and reviewed through a PR.
 After that PR is merged, the `Index Release` workflow (manually dispatched 
from `main` with the reviewed commit SHA, independently of server releases)
 builds the reviewed index without regenerating it, runs the retrieval-quality 
gate (`RetrievalQualityTest`, with working
 vectors required), verifies that the build did not modify the index, and 
publishes the reviewed `knowledge-index.zip` +
-`index.json` to a release tagged `knowledge-index-v1-YYYY.MM.DD-HHMMSS`.
+`index.json` to a release tagged `knowledge-index-v1-YYYY.MM.DD-HHMMSS` 
(apache-camel collection) or 
+`knowledge-index-v1-{collection-id}-YYYY.MM.DD-HHMMSS` (custom collections).
+
+### Publishing Custom Collections
+
+Custom documentation collections follow the same workflow as `apache-camel` 
but use collection-specific release tags:
+
+1. **Build the custom index** with collection metadata properties:
+   ```bash
+   ./mvnw clean install -pl knowledge/index -am -Prebuild-index -B \
+     -Dcollection.id=my-integration \
+     -Dcollection.version=2026.11.30-150000 \
+     -Dcollection.sources='[{"repo":"myorg/my-integration","branch":"main"}]'
+   ```
+
+2. **Commit the index** to a branch with a signed commit and open a PR for 
review
+
+3. **After PR merge**, manually dispatch the `Index Release` workflow from 
`main` with the reviewed commit SHA
+   
+   **Note**: The `Index Release` workflow automatically detects the collection 
ID from the index manifest
+   (`index.json`) and creates the appropriate release tag format:
+   - `apache-camel` → `knowledge-index-v1-{version}` (legacy format)
+   - Custom collections → `knowledge-index-v1-{collection-id}-{version}`
+
+4. **The workflow publishes** the index to a release tagged 
`knowledge-index-v1-my-integration-2026.11.30-150000`

Review Comment:
   **P2 · Document the published workflow and its actual tag**
   
   The corrected repository-root build command and cache diagram help. This 
example still promises the build-time suffix, while the workflow generates the 
release suffix with `date -u` at publication. Show how to obtain the actual tag 
for a version pin. Issue #199 also requires the published Knowledge guide at 
`docs/modules/ROOT/pages/knowledge.adoc` to cover building, selecting, 
inspecting provenance and troubleshooting a collection. That page is unchanged.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/KnowledgeMcpServer.java:
##########
@@ -264,7 +320,24 @@ private String normalizeRuntime(String runtime) {
     }
 
     private String errorJson(Exception e) {
-        return "{\"error\":\"" + escape(e.getMessage()) + "\"}";
+        StringBuilder error = new StringBuilder("{\"error\":\"" + 
escape(e.getMessage()) + "\"");
+
+        // Include collection context in errors to help diagnose issues
+        try {
+            String collectionId = searchService.getCollectionId();

Review Comment:
   **P2 · Preserve the acquisition error without reopening the index**
   
   The pinned-miss response now identifies the collection, version and cache. A 
single `camel_docs_index_info` call still made two manifest requests to a local 
server returning 503 because this error handler calls the failed CDI service 
again. For an unpinned strict miss the caller got `no segments* file found` in 
a temporary classpath directory, and the direct mismatch hint still points to 
`cache/<id>` instead of `cache/collections/<id>`. Preserve the resolver error 
for a required collection, pass its context directly into the response, and use 
the resolver’s cache path for the hint.
   
   _AI-generated by Codex on behalf of @luigidemasi._



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to