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


##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -133,12 +174,34 @@ 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));
+        // Currently only apache-camel collection is supported with built-in 
ApacheCamelDomain
+        // Custom collections require implementing and registering custom 
DocumentDomain classes
+        if ("apache-camel".equals(collectionId)) {
+            domains.add(new ApacheCamelDomain(cacheDir, resourcesDir));
+            LOG.info("Building apache-camel collection with 
ApacheCamelDomain");
+        } else {
+            throw new IllegalArgumentException(

Review Comment:
   **P1 · Make a registered custom collection buildable**
   
   The `rebuild-index` Maven profile with the README’s `my-integration` 
properties exits here. Foo and Bar also fail through `IndexerMain`. The 
supplied source list is read only after this branch. Rejecting an unknown ID 
fixes the previous mislabeling, but there’s no way to select either fixture 
through the shipped builder. Wire the selected ID to registered sources or 
domain providers, and build both fixtures through that entry point. I inverted 
this selector locally: even with `apache-camel` rejected at startup, the 
indexer suite still reported 117 tests, zero failures, two skips.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -534,6 +609,62 @@ 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 and manifest, 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)
+     * @param manifest The manifest that declared this index version
+     */
+    private void verifyStagedIndex(Path indexDir, Manifest manifest) 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;
+            String indexCollectionVersion = null;
+            if (td.scoreDocs.length > 0) {
+                Document metaDoc = searcher.doc(td.scoreDocs[0].doc);
+                indexCollectionId = metaDoc.get(KnowledgeFields.COLLECTION_ID);
+                indexCollectionVersion = 
metaDoc.get(KnowledgeFields.COLLECTION_VERSION);
+            }
+
+            // Backward compatibility: indexes without collection metadata are 
treated as apache-camel
+            if (indexCollectionId == null) {
+                indexCollectionId = "apache-camel";
+            }
+
+            // Verify the staged index matches the requested collection
+            String requestedCollection = config.collectionId();
+            if (!indexCollectionId.equals(requestedCollection)) {
+                throw new IOException(String.format(
+                        "Collection mismatch in staged index: requested '%s' 
but index contains '%s'. " +
+                        "The downloaded release is mislabeled or intended for 
a different collection.",
+                        requestedCollection, indexCollectionId));
+            }
+
+            // Verify the embedded corpus version matches the manifest's 
declared version
+            // (The manifest version is the release timestamp; collection 
version is the corpus identity)
+            if (indexCollectionVersion != null && manifest.version() != null

Review Comment:
   **P1 · Compare the two corpus versions before moving `current`**
   
   I activated a valid release containing corpus `1.0`, then offered a later 
release declaring `collectionVersion=2.0` with the same `1.0` archive. The new 
release became `current` and MCP continued reporting `1.0`. `Manifest` discards 
`collectionVersion`, and this comparison uses the publication timestamp and 
only logs a warning. Preserve the declared corpus version, compare it with the 
embedded value before activation, and keep the last good release on mismatch. 
Cover a valid corpus version that differs from its release timestamp, plus 
legacy community manifests.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
.github/workflows/index-release.yml:
##########
@@ -46,14 +46,26 @@ 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: runs full quality gate with corpus-specific 
assertions (Camel 4.22, Timer IDs, etc)
+      # For custom collections: runs only if apache-camel (quality tests are 
corpus-specific)
       - name: Retrieval quality gate
+        if: steps.collection.outputs.collection_id == 'apache-camel'

Review Comment:
   **P1 · Keep a retrieval gate for custom releases**
   
   For Foo, this condition skips the only step that opens the reviewed index 
and checks working vectors. The packaging predicate passed for my fixture even 
though the packaged server reported embedding model `none` and BM25-only 
retrieval. Keep the Camel-specific judgments conditional, run the shared vector 
check for every release, and check a query against an expected document from 
the selected custom corpus.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -133,12 +174,34 @@ 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));
+        // Currently only apache-camel collection is supported with built-in 
ApacheCamelDomain
+        // Custom collections require implementing and registering custom 
DocumentDomain classes
+        if ("apache-camel".equals(collectionId)) {
+            domains.add(new ApacheCamelDomain(cacheDir, resourcesDir));
+            LOG.info("Building apache-camel collection with 
ApacheCamelDomain");
+        } else {
+            throw new IllegalArgumentException(
+                    "Unknown collection ID: '" + collectionId + "'. " +
+                    "Currently only 'apache-camel' is supported. " +
+                    "To build custom collections, implement a DocumentDomain 
for your collection " +
+                    "and register it in IndexerMain.buildDomains(). " +
+                    "See ApacheCamelDomain as a reference implementation.");
+        }
 
         return domains;
     }
+
+    /**
+     * Build default collection sources JSON from registered domains.
+     * Returns a JSON array describing the sources that were actually indexed.
+     */
+    private static String buildDefaultCollectionSources(List<DocumentDomain> 
domains) {
+        // Derive sources from the domains that were actually built
+        // Currently only ApacheCamelDomain is registered
+        return 
"[{\"repo\":\"apache/camel\"},{\"repo\":\"apache/camel-quarkus\"},{\"repo\":\"apache/camel-spring-boot\"}]";

Review Comment:
   **P2 · Report the sources actually indexed**
   
   `buildDefaultCollectionSources` ignores `domains` and omits 
`apache/camel-website`, which supplies release notes and advisories. A caller 
can also stamp an unrelated repository through `collection.sources` without 
changing what the domain reads. Derive the source records and resolved 
revisions from the selected inputs, and check that the manifest and MCP report 
that same provenance.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/KnowledgeMcpServer.java:
##########
@@ -219,19 +230,65 @@ public String camel_docs_index_info() {
             String versions = info.versions().stream()
                     .map(v -> "\"" + escape(v) + "\"")
                     .collect(Collectors.joining(","));
-            return "{\"total_docs\":" + info.totalDocs()
-                   + ",\"embedding_model\":\""
-                   + escape(info.embeddingModel() != null ? 
info.embeddingModel() : "unknown") + "\""
-                   + ",\"search_mode\":\"" + escape(info.searchMode()) + "\""
-                   + ",\"versions\":[" + versions + "]"
-                   + ",\"doc_types\":{" + docTypes + "}}";
+
+            StringBuilder result = new StringBuilder();
+            result.append("{\"collection_id\":\"")
+                    .append(escape(
+                            searchService.getCollectionId() != null ? 
searchService.getCollectionId() : "unknown"))
+                    .append("\",\"collection_version\":\"")
+                    .append(escape(searchService.getCollectionVersion() != null
+                            ? searchService.getCollectionVersion() : 
"unversioned"))
+                    .append('"');
+
+            // Parse and validate collection_sources as JSON array
+            if (searchService.getCollectionSources() != null) {
+                try {
+                    JsonNode sourcesNode = 
mapper.readTree(searchService.getCollectionSources());
+                    if (sourcesNode.isArray()) {
+                        // Re-serialize with proper JSON encoding
+                        
result.append(",\"collection_sources\":").append(mapper.writeValueAsString(sourcesNode));
+                    } else {
+                        LOG.warn("Collection sources is not a valid JSON 
array, omitting from response");
+                    }
+                } catch (Exception e) {
+                    LOG.warn("Failed to parse collection sources as JSON: {}", 
e.toString());
+                    // Omit malformed sources from response instead of 
breaking the entire JSON
+                }
+            }
+
+            result.append(",\"total_docs\":").append(info.totalDocs())
+                    .append(",\"embedding_model\":\"")
+                    .append(escape(info.embeddingModel() != null ? 
info.embeddingModel() : "unknown"))
+                    
.append("\",\"search_mode\":\"").append(escape(info.searchMode()))
+                    .append("\",\"versions\":[").append(versions)
+                    .append("],\"doc_types\":{").append(docTypes)
+                    .append("}}");
+
+            return result.toString();
         } catch (Exception e) {
             return errorJson(e);
         }
     }
 
     // ── Helpers ─────────────────────────────────────────────────────────
 
+    /**
+     * Get the default domain to search. For backward compatibility with 
apache-camel collection,
+     * returns "apache_camel". For custom collections, returns the first 
domain or null to search all.
+     */
+    private String getDefaultDomain() {
+        try {
+            String collectionId = searchService.getCollectionId();
+            if ("apache-camel".equals(collectionId)) {
+                return DOMAIN; // "apache_camel" for backward compatibility
+            }
+            // For custom collections, search all domains (null = all domains)
+            return null;
+        } catch (Exception e) {
+            return DOMAIN; // Fallback to apache_camel

Review Comment:
   **P2 · Propagate the first acquisition failure from search**
   
   The index-info error now takes one manifest request. With the same pinned 
collection and a local manifest endpoint returning HTTP 503, a single 
`camel_docs_search` call still made two requests. `getDefaultDomain()` catches 
the failed service initialization and returns `DOMAIN`, so the subsequent 
search initializes the same service again. Let the original exception reach the 
tool’s existing error handler. The same helper is used for component lookup.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java:
##########
@@ -57,21 +57,41 @@ public class LuceneSearchService {
     @Inject
     IndexDownloader indexDownloader;
 
+    @Inject
+    IndexResolverConfig config;
+
     private IndexReader reader;
     private IndexSearcher searcher;
     private EmbeddingProvider embeddingProvider;
     private OnnxReranker reranker;
     private IndexDownloader.ResolvedIndex resolvedIndex;
     private final StandardAnalyzer analyzer = new StandardAnalyzer();
+    private String collectionId;
+    private String collectionVersion;
+    private String collectionSources;
 
     @PostConstruct
     void init() {
         try {
             resolvedIndex = resolveIndex();
             reader = 
DirectoryReader.open(FSDirectory.open(resolvedIndex.dir()));
             searcher = new IndexSearcher(reader);
+
+            // Verify collection metadata
+            verifyCollectionMetadata();
         } catch (Exception e) {
-            throw new RuntimeException("Failed to open knowledge index", e);
+            // Preserve acquisition failure details for MCP error responses
+            String requestedCollection = config.collectionId();
+            String requestedVersion = config.version().orElse("latest");
+            String fallbackHint = config.allowFallback()
+                    ? " (fallback enabled but unavailable)"
+                    : " (strict mode - set knowledge.index.allow-fallback=true 
to use mismatched collection)";
+
+            String detailedMessage = String.format(
+                    "Failed to open knowledge index for collection '%s' 
version '%s'%s. %s",

Review Comment:
   **P2 · Keep the resolver’s diagnostic on a strict, unpinned miss**
   
   With a required custom collection, no version pin, an unavailable manifest 
and an empty cache, the packaged runner returned `no segments* file found` in a 
temporary Lucene directory. `resolveIndex()` discards the acquisition error and 
tries classpath extraction. Preserve the missing collection, cache location and 
remedy for this case. The legacy community fallback can still run when 
appropriate.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/README.md:
##########
@@ -119,28 +119,208 @@ 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 isolated directories:
+```
+~/.camel-kit/knowledge-index/
+  2024.11.29-120000/              # apache-camel version directories
+  current                          # points to active apache-camel version
+  
+~/.camel-kit/knowledge-index-collections/
+  my-vendor/
+    2024.11.29-130000/
+    current
+  another-vendor/
+    2024.11.30-140000/
+    current
+```
+
+**Cache isolation**: Custom collections use a sibling directory 
(`knowledge-index-collections/`) 
+completely outside the apache-camel pruning scope to prevent cache deletion 
during community updates.
+
+### 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 (uses apache-camel 
as fallback)
+```
+
+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:
+   - Reads collection ID from the committed `index.json`
+   - Generates release version as `YYYY.MM.DD-HHMMSS` at publication time (UTC)
+   - Creates collection-specific tag:
+     - `apache-camel` → `knowledge-index-v1-{YYYY.MM.DD-HHMMSS}`
+     - Custom → `knowledge-index-v1-{collection-id}-{YYYY.MM.DD-HHMMSS}`
+
+4. **The workflow publishes** the index with a tag like 
`knowledge-index-v1-my-integration-2026.11.30-150000`

Review Comment:
   **P2 · Put the collection workflow in the published Knowledge guide**
   
   The README now explains how publication assigns the tag suffix. The Antora 
page named in #199 still has no custom-collection instructions. Once the 
registration path works, add a runnable build/selection example to 
`docs/modules/ROOT/pages/knowledge.adoc` and show how to inspect provenance and 
diagnose a missing or incompatible snapshot. [Issue 
#199](https://github.com/apache/camel-kit/issues/199)
   
   _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