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


##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexResolverConfig.java:
##########
@@ -30,4 +30,18 @@ public interface IndexResolverConfig {
     /** Local cache directory holding downloaded index versions. */
     @WithDefault("${user.home}/.camel-kit/knowledge-index")
     String cacheDir();
+
+    /**
+     * Collection ID to load. When absent, defaults to "apache-camel" for 
backward compatibility. Collection-specific
+     * releases are tagged as: knowledge-index-v1-{collectionId}-{version}
+     */
+    @WithDefault("apache-camel")
+    String collectionId();
+
+    /**
+     * Whether to allow fallback to default "apache-camel" collection when the 
requested collection is not found.
+     * Default is false - missing required collection will fail with a clear 
error.
+     */
+    @WithDefault("false")
+    boolean allowFallback();

Review Comment:
   **P1 · Restore MCP test compilation**
   
   Five anonymous implementations across four test files lack the two new 
accessors. The Java 21 build stops at MCP test compilation. In a separate local 
run I supplied the two defaults in the fixtures. Of 91 acquisition tests, 23 
failed assertions and 18 errored, many around the existing marker, validator 
and lock paths. Please restore the fixtures and keep those cache guarantees 
covered.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexBuilder.java:
##########
@@ -46,6 +46,50 @@ public IndexBuilder(EmbeddingProvider embeddingProvider, 
EmbeddingCache embeddin
         this.embeddingCache = embeddingCache;
     }
 
+    /**
+     * Build the Lucene index at the given path from the provided domains with 
collection metadata.
+     *
+     * @param  indexPath         directory where the Lucene index will be 
written
+     * @param  domains           list of domains to index
+     * @param  collectionId      unique identifier for this collection
+     * @param  collectionVersion version or digest of this collection
+     * @param  collectionSources JSON array of source repositories/versions
+     * @return                   total number of documents indexed
+     */
+    public int buildWithCollectionMeta(

Review Comment:
   **P1 · Wire collection selection into the Maven rebuild**
   
   Only the new tests call this method. The documented `-Dcollection.*` options 
never reach the production builder. `IndexerMain` registers only 
`ApacheCamelDomain` and invokes the legacy `build` method. Please select the 
registered sources from the build inputs, record the provenance of those 
sources, and use one writer lifecycle for both community and custom builds. 
[Production entry 
point](https://github.com/apache/camel-kit/blob/564b0be9170601acbcd69be657b6da1d5de6e5f6/knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java#L65)
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -128,8 +141,9 @@ public ResolvedIndex resolve() throws IOException {
             return new ResolvedIndex(path, false);
         }
 
-        // 2. Manifest + local cache
-        Path cacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();
+        // 2. Manifest + local cache (collection-specific subdirectory)
+        Path baseCacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();
+        Path cacheDir = baseCacheDir.resolve(config.collectionId());

Review Comment:
   **P1 · Keep cache maintenance inside the selected collection**
   
   The configured ID becomes the directory used for updates and recursive 
pruning. Please validate it as one safe directory name and reject a linked 
collection directory before creating directories or performing maintenance. An 
operator configuration mistake here could remove unrelated files.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/test/java/org/apache/camel/kit/knowledge/indexer/CollectionIsolationTest.java:
##########
@@ -0,0 +1,219 @@
+package org.apache.camel.kit.knowledge.indexer;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.apache.camel.kit.knowledge.indexer.domain.DocumentChunk;
+import org.apache.camel.kit.knowledge.indexer.domain.DocumentDomain;
+import org.apache.camel.kit.knowledge.schema.DomainMetadata;
+import org.apache.camel.kit.knowledge.schema.KnowledgeFields;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.FSDirectory;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests that custom documentation collections are properly isolated and 
identifiable. Verifies collection metadata,
+ * source provenance, and that searches never return content from the wrong 
collection.
+ */
+class CollectionIsolationTest {
+
+    @TempDir
+    Path collectionA;
+
+    @TempDir
+    Path collectionB;
+
+    /**
+     * Test domain for FooIntegration collection with identifiable phrase.
+     */
+    static class FooIntegrationDomain implements DocumentDomain {
+        @Override
+        public DomainMetadata metadata() {
+            return DomainMetadata.general("foo_integration", "foo_docs", 
"FooIntegration documentation");
+        }
+
+        @Override
+        public List<DocumentChunk> buildChunks() {
+            return List.of(
+                    new DocumentChunk(
+                            "foo-chunk-1", "foo-repo", "connector-doc",
+                            null, null, null,
+                            "FooIntegration Connectors",
+                            "FooIntegration uses connectors to link systems. 
The FTP connector moves files."),
+                    new DocumentChunk(
+                            "foo-chunk-2", "foo-repo", "config-doc",
+                            null, null, null,
+                            "FooIntegration Configuration",
+                            "Configure FooIntegration using YAML files. Set 
timeout: 30s for connectors."));
+        }
+    }
+
+    /**
+     * Test domain for BarPlatform collection with different identifiable 
phrase.
+     */
+    static class BarPlatformDomain implements DocumentDomain {
+        @Override
+        public DomainMetadata metadata() {
+            return DomainMetadata.general("bar_platform", "bar_docs", 
"BarPlatform documentation");
+        }
+
+        @Override
+        public List<DocumentChunk> buildChunks() {
+            return List.of(
+                    new DocumentChunk(
+                            "bar-chunk-1", "bar-repo", "adapter-doc",
+                            null, null, null,
+                            "BarPlatform Adapters",
+                            "BarPlatform uses adapters to integrate services. 
The HTTP adapter calls REST APIs."),
+                    new DocumentChunk(
+                            "bar-chunk-2", "bar-repo", "setup-doc",
+                            null, null, null,
+                            "BarPlatform Setup",
+                            "Install BarPlatform using Docker. Run 
docker-compose up to start adapters."));
+        }
+    }
+
+    @Test
+    void collectionsAreIsolatedAndIdentifiable() throws IOException, 
InterruptedException {
+        // Build collection A: FooIntegration
+        IndexBuilder builderA = new IndexBuilder();
+        int countA = builderA.buildWithCollectionMeta(
+                collectionA,
+                List.of(new FooIntegrationDomain()),
+                "foo-integration",
+                "1.0.0",
+                "[{\"repo\":\"foo-repo\",\"version\":\"1.0\"}]");
+        assertEquals(2, countA, "FooIntegration should have 2 chunks");
+
+        // Build collection B: BarPlatform
+        IndexBuilder builderB = new IndexBuilder();
+        int countB = builderB.buildWithCollectionMeta(
+                collectionB,
+                List.of(new BarPlatformDomain()),
+                "bar-platform",
+                "2.5.0",
+                "[{\"repo\":\"bar-repo\",\"version\":\"2.5\"}]");
+        assertEquals(2, countB, "BarPlatform should have 2 chunks");
+
+        // Verify collection A metadata and content
+        try (IndexReader readerA = 
DirectoryReader.open(FSDirectory.open(collectionA))) {
+            IndexSearcher searcherA = new IndexSearcher(readerA);
+
+            // Check index metadata for collection A
+            TopDocs metaHitsA = searcherA.search(
+                    new TermQuery(new Term(KnowledgeFields.ID, 
KnowledgeFields.INDEX_META_ID)), 1);
+            assertEquals(1, metaHitsA.totalHits.value, "Collection A should 
have index metadata");
+            Document metaDocA = searcherA.doc(metaHitsA.scoreDocs[0].doc);
+            assertEquals("foo-integration", 
metaDocA.get(KnowledgeFields.COLLECTION_ID));
+            assertEquals("1.0.0", 
metaDocA.get(KnowledgeFields.COLLECTION_VERSION));
+            
assertTrue(metaDocA.get(KnowledgeFields.COLLECTION_SOURCES).contains("foo-repo"));
+
+            // Search for FooIntegration-specific phrase
+            TopDocs fooHits = searcherA.search(
+                    new TermQuery(new Term(KnowledgeFields.SOURCE, 
"foo-repo")), 10);
+            assertEquals(2, fooHits.totalHits.value);
+

Review Comment:
   **P1 · Exercise search through the MCP tool**
   
   Both fixture collections were identified correctly, but `camel_docs_search` 
returned zero hits for their own phrases, on cold starts and offline restarts. 
Changing only the Foo domain to `apache_camel` returned both identical 
documents for the same query. The public tool hardcodes that domain. Please 
search the loaded collection’s domains and assert the returned content and 
provenance through MCP. [Search 
call](https://github.com/apache/camel-kit/blob/564b0be9170601acbcd69be657b6da1d5de6e5f6/knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/KnowledgeMcpServer.java#L88)
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/KnowledgeMcpServer.java:
##########
@@ -219,12 +221,29 @@ 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('"');
+
+            if (searchService.getCollectionSources() != null) {
+                
result.append(",\"collection_sources\":").append(searchService.getCollectionSources());

Review Comment:
   **P2 · Return actionable errors and structured provenance**
   
   A missing pinned snapshot and a strict local collection mismatch both 
returned only `Failed to open knowledge index` over MCP. Please preserve the 
requested collection, expected snapshot and a safe resolution hint in the tool 
response. Parse and validate the sources as an array and serialize it with the 
existing JSON library. Appending stored text verbatim lets malformed provenance 
invalidate the entire response. The README should show the array the tool 
returns.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/README.md:
##########
@@ -119,26 +119,109 @@ 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:
+./mvnw install -pl knowledge/index -Prebuild-index -am -B \
+  -Dcollection.id=my-vendor \
+  -Dcollection.version=1.0.0 \
+  -Dcollection.sources='[{"repo":"my-org/docs","tag":"v1.0.0"}]'
+```
+
+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
+knowledge.index.collection-id=my-vendor  # Default: apache-camel
+knowledge.index.version=2024.11.29-123456  # Optional: pin exact version
+knowledge.index.allow-fallback=false     # Default: false (strict matching)
+```
+
+Collections are cached in collection-specific directories:
+```
+~/.camel-kit/knowledge-index/
+  apache-camel/
+    2024.11.29-120000/
+  my-vendor/
+    2024.11.29-130000/
+```
+
+### 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\",\"tag\":\"camel-4.22.1\"}]",
+  "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"]
+}
+```
+
+### 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/apache-camel/2024.11.29-120000/
+Available collections may be cached at: ~/.camel-kit/knowledge-index/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).

Review Comment:
   **P2 · Document the supported publishing and selection path**
   
   The release workflow always emits the community tag. Please document the 
working custom publishing path, or extend the workflow if it should handle that 
case. Issue #199 also requires the published Knowledge guide to cover build, 
selection, provenance and troubleshooting. Update the Knowledge changelog, and 
put the comments in the properties example on separate lines so they do not 
become part of the values. [Release 
workflow](https://github.com/apache/camel-kit/blob/564b0be9170601acbcd69be657b6da1d5de6e5f6/.github/workflows/index-release.yml#L68)
 · [Published 
guide](https://github.com/apache/camel-kit/blob/564b0be9170601acbcd69be657b6da1d5de6e5f6/docs/modules/ROOT/pages/knowledge.adoc#L90)
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java:
##########
@@ -187,6 +196,63 @@ 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);
+        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)");
+            }
+
+            // Verify the loaded collection matches configuration
+            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()) {
+                    LOG.warn("{}\nFallback is enabled, using loaded collection 
anyway.", message);
+                } else {
+                    throw new IOException(
+                            message + "\n" +
+                                          "To use the loaded collection, set 
knowledge.index.collection-id="
+                                          + collectionId + "\n" +
+                                          "Or enable fallback with 
knowledge.index.allow-fallback=true (not recommended for production)");
+                }
+            }
+
+            LOG.info("Loaded knowledge collection '{}' version {} from {}",
+                    collectionId,
+                    collectionVersion != null ? collectionVersion : 
"unversioned",
+                    resolvedIndex.dir());
+            if (collectionSources != null) {
+                LOG.info("Collection sources: {}", collectionSources);
+            }
+        } else {
+            // Legacy index without any metadata
+            collectionId = "apache-camel";

Review Comment:
   **P1 · Apply the same selection policy to legacy and stamped indexes**
   
   This branch assigns the community ID and skips the requested-ID check. The 
stamped branch permits any mismatched collection when fallback is enabled. In 
the other direction, a request for a missing custom collection with fallback 
enabled failed even though a control query verified a working community cache. 
Please normalize legacy metadata first, compare every source against the 
requested ID, and resolve only the configured fallback.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -128,8 +141,9 @@ public ResolvedIndex resolve() throws IOException {
             return new ResolvedIndex(path, false);
         }
 
-        // 2. Manifest + local cache
-        Path cacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();
+        // 2. Manifest + local cache (collection-specific subdirectory)
+        Path baseCacheDir = 
Path.of(config.cacheDir()).toAbsolutePath().normalize();

Review Comment:
   **P1 · Preserve the community cache on upgrade**
   
   The previous layout placed `current` and the version directories directly 
under the cache root. An offline restart with a valid pinned community cache 
failed after this change. Opening the same index directly returned community 
hits. Please preserve or safely migrate the old layout, including its marker, 
validator and lock. If old and new clients share the root, account for the old 
client’s pruning.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java:
##########
@@ -57,19 +57,28 @@ 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();

Review Comment:
   **P1 · Validate the candidate before activating it**
   
   By this point the downloader has already installed the version directory, 
advanced `current`, and pruned the cache. A mislabelled release can displace 
the working snapshot and be reused on retry even after the archive is 
corrected. Define how the expected snapshot identifies the stored corpus 
version or digest, verify it and the collection ID while staged, and keep the 
last good marker on rejection. Also close any reader opened during failed 
validation. [Activation 
order](https://github.com/apache/camel-kit/blob/564b0be9170601acbcd69be657b6da1d5de6e5f6/knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java#L252)
   
   _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