luigidemasi commented on code in PR #214:
URL: https://github.com/apache/camel-kit/pull/214#discussion_r4737846122
##########
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:
**P1 · Generic search now fails for the default collection as well**
`LuceneSearchService.search` always constructs a `Term` from `domain`.
Passing `null` makes `camel_docs_search("kafka")` return a null-text error on
the shipped community index. The Foo and Bar fixtures produce the same error.
Custom `component_info` also passes `null` to `lookupComponent`. Implement
all-domain lookup in the query builder, preserving version, runtime and
document-type filters. Include the unfiltered case where no optional filters
are set. [Query
construction](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java#L475)
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -64,12 +64,23 @@ public static void main(String[] args) throws Exception {
List<DocumentDomain> domains = buildDomains(cacheDir, resourcesDir);
+ // Get collection metadata from system properties
+ String collectionId = System.getProperty("collection.id",
"apache-camel");
+ String collectionVersion = System.getProperty("collection.version",
+ Instant.now().toString().substring(0, 19).replace(':', '-'));
+ String collectionSources = System.getProperty("collection.sources",
Review Comment:
**P1 · Select the sources that the build actually indexes**
The Maven properties now stamp the output, but `buildDomains` still
constructs only `ApacheCamelDomain` before the properties are read. Calling the
production domain selection with two different custom IDs and an explicit
vendor source list selected `apache_camel` in both cases. The resulting
manifest can claim vendor provenance for community content. Register/select the
actual inputs first and derive provenance from them. Validate the source array
at build time and use a JSON serializer for the manifest. The current writer
even accepts `{}` as `collectionSources`. [Domain
registration](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java#L157)
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -534,6 +590,54 @@ 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.
+ */
+ private void verifyStagedIndex(Path indexDir) throws IOException {
+ DirectoryReader reader = null;
+ try {
+ reader =
DirectoryReader.open(FSDirectory.open(indexDir.resolve("knowledge-index")));
Review Comment:
**P1 · Validate the directory produced by extraction**
`unzip` strips the archive’s `knowledge-index/` prefix. The Lucene files are
directly in `indexDir`. With a valid release-format archive, this line opened
an empty child and threw `IndexNotFoundException`. Both custom fixtures opened
from disk and failed on cold download. Open `indexDir` itself and close both
the directory and reader with try-with-resources. Use a real Lucene index in
successful-download fixtures. Check the expected corpus version or digest as
well as the ID before activation, including when reusing a version directory.
[Extraction](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java#L867)
_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: {cacheDir}/{collection-id}/
+ Path cacheDir = "apache-camel".equals(collectionId)
+ ? baseCacheDir
+ : baseCacheDir.resolve(collectionId);
Review Comment:
**P1 · Community cache pruning includes custom collections**
Reusing the root fixes the previous offline-upgrade failure. It also makes
every custom collection directory an immediate child of the directory that
community updates prune. `prune` recursively removes every such directory
except the current and previous community versions and staging names. A
successful community update can therefore erase a custom collection’s warm
cache. Give custom collections a separate directory outside the legacy pruning
scope, or otherwise ensure both old and new community clients preserve them.
Test a community update between two offline opens of the same custom
collection.
[Pruning](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java#L920)
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/LuceneSearchService.java:
##########
@@ -187,6 +196,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 · Resolve the configured fallback explicitly**
The shared comparison fixes strict selection for metadata-free indexes. With
fallback enabled, this branch still accepts any mismatched collection it
happens to open, while the resolver never tries the documented community cache
on a custom miss. A control opened the community cache offline and found Kafka.
Requesting a missing collection with fallback enabled against the same cache
returned an error. Resolve the allowed fallback explicitly and use one identity
policy for staged, cached and direct-path opens.
_AI-generated by Codex on behalf of @luigidemasi._
##########
.github/workflows/index-release.yml:
##########
@@ -65,7 +65,17 @@ jobs:
run: |
jq -e '.formatVersion == 1 and .embeddingDimensions == 384 and
.embeddingModel == "granite-embedding-small-english-r2-q8"'
knowledge/index/src/main/resources/index.json
VERSION=$(date -u +%Y.%m.%d-%H%M%S)
- TAG="knowledge-index-v1-$VERSION"
+
+ # Read collection ID from index manifest to support custom
collections
+ # For apache-camel (default), use legacy tag format without
collection ID in tag
+ COLLECTION_ID=$(jq -r '.collectionId // "apache-camel"'
knowledge/index/src/main/resources/index.json)
Review Comment:
**P1 · Run the quality gate against the collection being published**
Tag selection is collection-aware, but the earlier retrieval gate still
requests `apache-camel`. Running its quality test on the Foo fixture failed
with `requested 'apache-camel' but index contains 'foo-integration'` before
evaluation. The evaluation also hardcodes the `apache_camel` domain and
community relevance judgments. Read the collection identity before the gate and
run positive and negative retrieval checks appropriate to that corpus. Keep the
existing quality thresholds for community releases. [Quality
gate](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/.github/workflows/index-release.yml#L53)
· [Evaluation
domain](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/knowledge/mcp/src/test/java/org/apache/camel/kit/knowledge/mcp/RetrievalQualityTest.java#L45)
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/README.md:
##########
@@ -119,26 +119,184 @@ 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/
+ 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"},
+ {"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/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).
+
+### 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
+ cd knowledge/indexer
+ ./mvnw clean install \
Review Comment:
**P2 · Fix the publishing command and update the published guide**
`knowledge/indexer` has no `./mvnw`, and installing the indexer module alone
does not rebuild the index. Use the root wrapper with `-pl knowledge/index -am
-Prebuild-index`. The release suffix is generated at publication time, and the
community cache diagram still shows an `apache-camel/` subdirectory. Please
align the examples and add the build, selection, provenance and troubleshooting
instructions to the published Knowledge guide required by #199. [Published
guide](https://github.com/apache/camel-kit/blob/d99007dc26390df2a165901949b39476ef8ff97d/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/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 · Return the cause of acquisition failures without retrying
initialization**
Both an unavailable pin and a mismatched local index still returned only
`Failed to open knowledge index` over stdio. The getters here access the same
CDI service whose initialization just failed. The outer exception masks the
useful cause. Carry the requested ID, snapshot and recovery hint in the
acquisition error and serialize it directly. Please also assert the sources
array through MCP. Inverting the new array check removed valid provenance in
the runner while the two collection tests and the existing index-info test all
passed.
_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]