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


##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomain.java:
##########
@@ -0,0 +1,204 @@
+package org.apache.camel.kit.knowledge.indexer.domain;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.camel.kit.knowledge.indexer.GitRepoFetcher;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker.Section;
+import org.apache.camel.kit.knowledge.indexer.parser.AsciidocConverter;
+import org.apache.camel.kit.knowledge.schema.DomainMetadata;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Generic documentation domain that reads from collection.sources property. 
Supports arbitrary Git repositories with
+ * AsciiDoc or Markdown content.
+ *
+ * <p>
+ * Source format: JSON array of repository objects with repo, branch 
(optional), tag (optional). Example:
+ * {@code 
[{"repo":"my-org/docs","branch":"main"},{"repo":"other/repo","tag":"v1.0"}]}
+ */
+public class GenericDocumentDomain implements DocumentDomain {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(GenericDocumentDomain.class);
+
+    private final String collectionId;
+    private final String collectionSources;
+    private final GitRepoFetcher repoFetcher;
+    private final AsciidocConverter adocConverter;
+    private final SectionChunker sectionChunker;
+    private final Path reposDir;
+
+    /**
+     * @param cacheDir          base cache directory
+     * @param resourcesDir      base resources directory for git clones
+     * @param collectionId      collection identifier
+     * @param collectionSources JSON array of source repositories to index
+     */
+    public GenericDocumentDomain(Path cacheDir, Path resourcesDir,
+                                 String collectionId, String 
collectionSources) throws IOException {
+        this.collectionId = collectionId;
+        this.collectionSources = collectionSources;
+        this.reposDir = resourcesDir.resolve(collectionId + "/repos");
+        Files.createDirectories(reposDir);
+
+        this.repoFetcher = new GitRepoFetcher(reposDir);
+        this.adocConverter = new AsciidocConverter();
+        this.sectionChunker = new SectionChunker();
+    }
+
+    @Override
+    public DomainMetadata metadata() {
+        return new DomainMetadata(
+                collectionId,
+                collectionId + "_docs",
+                "Custom documentation collection: " + collectionId,
+                false,  // Not Apache Camel
+                false); // No default domain
+    }
+
+    @Override
+    public List<DocumentChunk> buildChunks() throws IOException, 
InterruptedException {
+        List<DocumentChunk> chunks = new ArrayList<>();
+
+        // Parse collection.sources JSON array
+        JSONArray sourcesArray = new JSONArray(collectionSources);
+        LOG.info("Building {} collection from {} source(s)", collectionId, 
sourcesArray.length());
+
+        for (int i = 0; i < sourcesArray.length(); i++) {
+            JSONObject source = sourcesArray.getJSONObject(i);
+            String repo = source.getString("repo");
+            String branch = source.optString("branch", null);
+            String tag = source.optString("tag", null);
+
+            // Determine ref and whether it's a tag
+            String ref = tag != null ? tag : (branch != null ? branch : 
"main");
+            boolean isTag = tag != null;
+
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + ref;

Review Comment:
   **Keep distinct source repositories in distinct checkouts.** 
`sample-team/manual` and `sample/team-manual` on `main` both map to the same 
directory here. On the second fetch, `GitRepoFetcher` updates the existing 
checkout from its own `origin`. I built a collection from two repositories with 
those names and different guides. Searching the resulting index returned the 
first guide twice and zero hits for the second. Building the second repository 
alone returned its guide. Use a cache key that preserves repository and ref 
identity, and cover this pair with a two-source build.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomain.java:
##########
@@ -0,0 +1,204 @@
+package org.apache.camel.kit.knowledge.indexer.domain;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.camel.kit.knowledge.indexer.GitRepoFetcher;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker.Section;
+import org.apache.camel.kit.knowledge.indexer.parser.AsciidocConverter;
+import org.apache.camel.kit.knowledge.schema.DomainMetadata;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Generic documentation domain that reads from collection.sources property. 
Supports arbitrary Git repositories with
+ * AsciiDoc or Markdown content.
+ *
+ * <p>
+ * Source format: JSON array of repository objects with repo, branch 
(optional), tag (optional). Example:
+ * {@code 
[{"repo":"my-org/docs","branch":"main"},{"repo":"other/repo","tag":"v1.0"}]}
+ */
+public class GenericDocumentDomain implements DocumentDomain {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(GenericDocumentDomain.class);
+
+    private final String collectionId;
+    private final String collectionSources;
+    private final GitRepoFetcher repoFetcher;
+    private final AsciidocConverter adocConverter;
+    private final SectionChunker sectionChunker;
+    private final Path reposDir;
+
+    /**
+     * @param cacheDir          base cache directory
+     * @param resourcesDir      base resources directory for git clones
+     * @param collectionId      collection identifier
+     * @param collectionSources JSON array of source repositories to index
+     */
+    public GenericDocumentDomain(Path cacheDir, Path resourcesDir,
+                                 String collectionId, String 
collectionSources) throws IOException {
+        this.collectionId = collectionId;
+        this.collectionSources = collectionSources;
+        this.reposDir = resourcesDir.resolve(collectionId + "/repos");
+        Files.createDirectories(reposDir);
+
+        this.repoFetcher = new GitRepoFetcher(reposDir);
+        this.adocConverter = new AsciidocConverter();
+        this.sectionChunker = new SectionChunker();
+    }
+
+    @Override
+    public DomainMetadata metadata() {
+        return new DomainMetadata(
+                collectionId,
+                collectionId + "_docs",
+                "Custom documentation collection: " + collectionId,
+                false,  // Not Apache Camel
+                false); // No default domain
+    }
+
+    @Override
+    public List<DocumentChunk> buildChunks() throws IOException, 
InterruptedException {
+        List<DocumentChunk> chunks = new ArrayList<>();
+
+        // Parse collection.sources JSON array
+        JSONArray sourcesArray = new JSONArray(collectionSources);
+        LOG.info("Building {} collection from {} source(s)", collectionId, 
sourcesArray.length());
+
+        for (int i = 0; i < sourcesArray.length(); i++) {
+            JSONObject source = sourcesArray.getJSONObject(i);
+            String repo = source.getString("repo");
+            String branch = source.optString("branch", null);
+            String tag = source.optString("tag", null);
+
+            // Determine ref and whether it's a tag
+            String ref = tag != null ? tag : (branch != null ? branch : 
"main");
+            boolean isTag = tag != null;
+
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + ref;
+
+            LOG.info("  Fetching {}: {} @ {}", repo, ref, (isTag ? "tag" : 
"branch"));
+
+            try {
+                Path repoPath = repoFetcher.fetchRepo(
+                        "https://github.com/"; + repo + ".git", ref, localName, 
isTag);
+
+                // Index all .adoc and .md files recursively
+                List<Path> adocFiles = repoFetcher.listFiles(repoPath, 
"*.adoc");
+                List<Path> mdFiles = repoFetcher.listFiles(repoPath, "*.md");

Review Comment:
   **Include guides below the repository root.** `listFiles` uses a single 
directory stream. A repository containing only `docs/guide.adoc` built 
successfully with `docCount: 0`, and MCP returned zero hits both immediately 
and after an offline restart. A second repository indexed its root guides and 
silently omitted `docs/overview.md`. Walk the documentation tree for both 
formats and run a nested-only fixture through the production build and search. 
The current 117 indexer tests had identical outcomes even when I inverted the 
file filter and reduced a two-document build to zero.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/IndexerMain.java:
##########
@@ -62,14 +63,47 @@ 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);
+
+        // Get and validate collection sources from system property
+        String collectionSources = System.getProperty("collection.sources");
+        if (collectionSources != null && !collectionSources.isBlank()) {
+            // Validate user-provided sources is valid JSON array using 
org.json
+            try {
+                org.json.JSONArray sourcesArray = new 
org.json.JSONArray(collectionSources);
+                // Re-serialize to ensure clean JSON
+                collectionSources = sourcesArray.toString();
+                LOG.info("Using user-provided collection sources: {}", 
collectionSources);
+            } catch (org.json.JSONException e) {
+                throw new IllegalArgumentException(
+                        "Invalid collection.sources: must be a valid JSON 
array. Example: "
+                                                   + 
"[{\"repo\":\"apache/camel\",\"branch\":\"main\"}]",
+                        e);
+            }
+        }
+
+        // Build domains based on collection ID and sources
+        List<DocumentDomain> domains = buildDomains(cacheDir, resourcesDir, 
collectionId, collectionSources);
+
+        // Derive collection sources from actual domains built if not provided
+        if (collectionSources == null || collectionSources.isBlank()) {

Review Comment:
   **Stamp the sources the Apache domain actually consumes.** For 
`apache-camel`, `buildDomains` warns that it ignored my `fixtures/foo` 
override. This condition still keeps that override and passes it to both the 
Lucene metadata and the release manifest. MCP reported `fixtures/foo` as the 
source of a collection whose hit was an Apache Camel release note. The custom 
branch already enforces a nonempty source list. For the community branch, 
derive the built-in provenance unconditionally.
   
   ```suggestion
           if ("apache-camel".equals(collectionId)) {
   ```
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
docs/modules/ROOT/pages/knowledge.adoc:
##########
@@ -114,6 +114,109 @@ root. Maintainers review generated data before manually 
dispatching `Index Relea
 `main`; the workflow validates retrieval with working vectors before 
publication. Index
 publication is independent of Kit and Knowledge server releases.
 
+[[collections]]
+== Custom documentation collections
+
+Knowledge supports versioned, isolated documentation collections for custom 
content.
+Each collection has its own index, cache directory and GitHub release tag 
namespace.
+
+=== Building a custom collection
+
+**Note**: Currently, only the `apache-camel` collection is supported. Custom 
collections

Review Comment:
   **Show the custom build that now works.** I ran the Maven command below with 
a two-document repository. It produced a `my-vendor` index under 
`knowledge/index/src/main/resources/knowledge-index` without any Java 
registration. Replace the expected-failure example with the working build and a 
`knowledge.index.path` example for querying that output. Update the same 
guidance in `knowledge/README.md` and in the release workflow’s rejection 
message. The automated release workflow currently accepts only `apache-camel`.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomain.java:
##########
@@ -0,0 +1,204 @@
+package org.apache.camel.kit.knowledge.indexer.domain;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.camel.kit.knowledge.indexer.GitRepoFetcher;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker;
+import org.apache.camel.kit.knowledge.indexer.chunker.SectionChunker.Section;
+import org.apache.camel.kit.knowledge.indexer.parser.AsciidocConverter;
+import org.apache.camel.kit.knowledge.schema.DomainMetadata;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Generic documentation domain that reads from collection.sources property. 
Supports arbitrary Git repositories with
+ * AsciiDoc or Markdown content.
+ *
+ * <p>
+ * Source format: JSON array of repository objects with repo, branch 
(optional), tag (optional). Example:
+ * {@code 
[{"repo":"my-org/docs","branch":"main"},{"repo":"other/repo","tag":"v1.0"}]}
+ */
+public class GenericDocumentDomain implements DocumentDomain {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(GenericDocumentDomain.class);
+
+    private final String collectionId;
+    private final String collectionSources;
+    private final GitRepoFetcher repoFetcher;
+    private final AsciidocConverter adocConverter;
+    private final SectionChunker sectionChunker;
+    private final Path reposDir;
+
+    /**
+     * @param cacheDir          base cache directory
+     * @param resourcesDir      base resources directory for git clones
+     * @param collectionId      collection identifier
+     * @param collectionSources JSON array of source repositories to index
+     */
+    public GenericDocumentDomain(Path cacheDir, Path resourcesDir,
+                                 String collectionId, String 
collectionSources) throws IOException {
+        this.collectionId = collectionId;
+        this.collectionSources = collectionSources;
+        this.reposDir = resourcesDir.resolve(collectionId + "/repos");
+        Files.createDirectories(reposDir);
+
+        this.repoFetcher = new GitRepoFetcher(reposDir);
+        this.adocConverter = new AsciidocConverter();
+        this.sectionChunker = new SectionChunker();
+    }
+
+    @Override
+    public DomainMetadata metadata() {
+        return new DomainMetadata(
+                collectionId,
+                collectionId + "_docs",
+                "Custom documentation collection: " + collectionId,
+                false,  // Not Apache Camel
+                false); // No default domain
+    }
+
+    @Override
+    public List<DocumentChunk> buildChunks() throws IOException, 
InterruptedException {
+        List<DocumentChunk> chunks = new ArrayList<>();
+
+        // Parse collection.sources JSON array
+        JSONArray sourcesArray = new JSONArray(collectionSources);
+        LOG.info("Building {} collection from {} source(s)", collectionId, 
sourcesArray.length());
+
+        for (int i = 0; i < sourcesArray.length(); i++) {
+            JSONObject source = sourcesArray.getJSONObject(i);
+            String repo = source.getString("repo");
+            String branch = source.optString("branch", null);
+            String tag = source.optString("tag", null);
+
+            // Determine ref and whether it's a tag
+            String ref = tag != null ? tag : (branch != null ? branch : 
"main");
+            boolean isTag = tag != null;
+
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + ref;
+
+            LOG.info("  Fetching {}: {} @ {}", repo, ref, (isTag ? "tag" : 
"branch"));
+
+            try {
+                Path repoPath = repoFetcher.fetchRepo(
+                        "https://github.com/"; + repo + ".git", ref, localName, 
isTag);
+
+                // Index all .adoc and .md files recursively
+                List<Path> adocFiles = repoFetcher.listFiles(repoPath, 
"*.adoc");
+                List<Path> mdFiles = repoFetcher.listFiles(repoPath, "*.md");
+
+                LOG.info("  Found {} .adoc and {} .md files in {}",
+                        adocFiles.size(), mdFiles.size(), repo);
+
+                // Process AsciiDoc files
+                for (Path file : adocFiles) {
+                    chunks.addAll(convertAndChunk(file, repo, ref, "adoc"));
+                }
+
+                // Process Markdown files
+                for (Path file : mdFiles) {
+                    chunks.addAll(convertAndChunk(file, repo, ref, 
"markdown"));
+                }
+
+            } catch (IOException e) {
+                LOG.error("  Failed to fetch {}: {}", repo, e.getMessage());
+                throw new IOException("Failed to fetch source repository: " + 
repo, e);
+            }
+        }
+
+        LOG.info("Built {} total chunks for collection {}", chunks.size(), 
collectionId);
+        return chunks;
+    }
+
+    /**
+     * Convert a file to markdown and chunk by sections.
+     */
+    private List<DocumentChunk> convertAndChunk(Path file, String repo, String 
ref, String fileType)
+            throws IOException {
+        List<DocumentChunk> chunks = new ArrayList<>();
+
+        String fileName = file.getFileName().toString();
+        String baseName = fileName.replaceAll("\\.(adoc|md)$", "");
+
+        // Skip Antora includes/nav files
+        if (fileName.startsWith("_") || fileName.startsWith("nav")) {
+            return chunks;
+        }
+
+        try {
+            String markdown;
+            if ("adoc".equals(fileType)) {
+                // Convert AsciiDoc to Markdown
+                Path partialsDir = file.getParent().resolve("../partials");
+                Path examplesDir = file.getParent().resolve("../examples");
+                markdown = adocConverter.toMarkdown(file, partialsDir, 
examplesDir);
+            } else {
+                // Read Markdown as-is
+                markdown = Files.readString(file);
+            }
+
+            // Chunk by sections
+            List<Section> sections = sectionChunker.chunk(markdown);
+
+            for (Section section : sections) {
+                String slug = slugify(section.title());
+                String id = chunkId(baseName, slug, repo, ref);

Review Comment:
   **Give each search hit an unambiguous source ID.** A root `guide.md` and a 
root `guide.adoc`, each with a `Setup` section, produced two different results 
with the identical ID `foo-guides-fixtures-foo-main-guide-setup`. Both also 
reported the collection name as their source. A consumer cannot cite which file 
supplied the answer. Include the repository-relative path with its extension 
and a stable section discriminator, and assert that both hits can be 
distinguished.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -230,6 +305,20 @@ private ResolvedIndex resolveCached(Path cacheDir) throws 
IOException {
         }
 
         if (manifest.version().equals(cachedVersion) && haveCached) {
+            // Verify the cached version against the fresh manifest before 
reactivating
+            // This catches cases where a pinned version was cached but the 
manifest changed
+            // (e.g., corpus version mismatch, collection ID mismatch)
+            LOG.info("Verifying cached version {} against fresh manifest", 
cachedVersion);
+            try {
+                verifyStagedIndex(cachedDir, manifest);
+            } catch (IOException e) {
+                throw new IOException(

Review Comment:
   **Propagate a confirmed mismatch for a strict pin.** The new check detects 
that a freshly fetched manifest declares corpus 2.0 while the pinned cache 
contains 1.0. Its exception reaches the outer handler at lines 215–221, which 
immediately returns that same directory. Index info reported 1.0 and search 
returned hits for both the current pin and a retained pin. A fresh manifest 
declaring a different collection also served warm hits through the 
manifest-error handler at lines 292–298. On an empty cache the latter returned 
a generic acquisition error that omitted the conflicting ID. Distinguish an 
unavailable manifest from a verified incompatibility in both handlers. Keep 
offline reuse of a previously verified pin and return the mismatch to the 
caller when a fresh declaration contradicts it.
   
   _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