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


##########
knowledge/indexer/src/main/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomain.java:
##########
@@ -0,0 +1,232 @@
+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;
+
+            // Use hash of repo URL to ensure distinct checkouts for different 
repositories
+            // This prevents collision between repos like "sample-team/manual" 
and "sample/team-manual"
+            String repoHash = Integer.toHexString(repo.hashCode());
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + repoHash + "-" + ref;

Review Comment:
   **Keep branch and tag checkouts separate.** I started with an empty checkout 
cache and a Git repository whose `release` tag and `release` branch pointed to 
different commits. Building the tag, then the branch, then the tag again 
returned the branch’s guide on the third build. MCP still reported the tag as 
its source. Both refs map to this directory, and the branch update leaves the 
tag marker in place. Include the ref kind in the checkout key and add a tag → 
branch → tag regression that checks the final document content.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -463,10 +578,30 @@ private Manifest fetchManifest(URI uri, Path cacheDir, 
String cachedVersion)
                 || 
!OnnxEmbeddingProvider.MODEL_ID.equals(root.path("embeddingModel").asText())) {
             throw new IOException("Index format or embedding model is 
incompatible with this server");
         }
+
+        // Read collection metadata from manifest (backward compat: 
apache-camel if omitted)
+        String manifestCollectionId = root.path("collectionId").asText(null);
+        if (manifestCollectionId == null) {
+            manifestCollectionId = "apache-camel";
+        }
+
+        // Verify manifest's declared collection matches the requested 
collection
+        String requestedCollection = config.collectionId();
+        if (!manifestCollectionId.equals(requestedCollection)) {
+            throw new IOException(

Review Comment:
   **Propagate a fresh manifest’s collection mismatch to a pinned caller.** 
With `mixed-guides` pinned and cached, I supplied a fresh manifest for the same 
release that declared `other-guides`. Index info and search both succeeded 
using the cache. With an empty cache the request failed, but the error omitted 
the conflicting ID. The generic catch in `resolveCached` handles this exception 
as an unavailable manifest. Raise the dedicated incompatibility exception here 
and propagate it through that catch before consulting the cache. Keep the 
offline-pin test as a positive control alongside cold and warm mismatched-ID 
tests.
   
   _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,232 @@
+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;
+
+            // Use hash of repo URL to ensure distinct checkouts for different 
repositories
+            // This prevents collision between repos like "sample-team/manual" 
and "sample/team-manual"
+            String repoHash = Integer.toHexString(repo.hashCode());
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + repoHash + "-" + 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 (walk entire tree)
+                List<Path> adocFiles = listFilesRecursively(repoPath, 
"*.adoc");
+                List<Path> mdFiles = listFilesRecursively(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", 
repoPath));
+                }
+
+                // Process Markdown files
+                for (Path file : mdFiles) {
+                    chunks.addAll(convertAndChunk(file, repo, ref, "markdown", 
repoPath));
+                }
+
+            } 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, Path repoRoot)
+            throws IOException {
+        List<DocumentChunk> chunks = new ArrayList<>();
+
+        String fileName = file.getFileName().toString();
+
+        // Skip Antora includes/nav files
+        if (fileName.startsWith("_") || fileName.startsWith("nav")) {
+            return chunks;
+        }
+
+        // Get repository-relative path including extension for unique IDs
+        String relativePath = repoRoot.relativize(file).toString();
+
+        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(relativePath, slug, repo, ref);
+
+                chunks.add(new DocumentChunk(
+                        id,
+                        collectionId,  // source
+                        "document",    // docType
+                        null,          // version (custom collections are 
unversioned)
+                        null,          // versionNumeric
+                        null,          // component
+                        section.title(),
+                        section.content(),
+                        null,          // runtimes
+                        null,          // jiraIds
+                        null,          // erratumId
+                        null,          // advisoryType
+                        null,          // severity
+                        null,          // cveIds
+                        null           // fixedVersions
+                ));
+            }
+
+            LOG.info("    Chunked {}: {} sections", fileName, sections.size());
+
+        } catch (Exception e) {
+            LOG.warn("    Failed to convert {}: {} (skipping)", fileName, 
e.getMessage());
+        }
+
+        return chunks;
+    }
+
+    /**
+     * List files recursively matching a glob pattern.
+     * Walks the entire directory tree to find nested documentation.
+     */
+    private List<Path> listFilesRecursively(Path root, String glob) throws 
IOException {
+        List<Path> results = new ArrayList<>();
+        if (!Files.isDirectory(root)) {
+            return results;
+        }
+
+        try (var stream = Files.walk(root)) {
+            stream.filter(Files::isRegularFile)
+                    .filter(p -> {
+                        String fileName = p.getFileName().toString();
+                        String pattern = glob.replace("*", ".*");
+                        return fileName.matches(pattern);
+                    })
+                    .forEach(results::add);
+        }
+        return results;
+    }
+
+    /**
+     * Generate a unique chunk ID including repository-relative path and 
extension.
+     * This prevents collisions between guide.md and guide.adoc with same 
section names.
+     */
+    private String chunkId(String relativePath, String slug, String repo, 
String ref) {
+        return String.format(Locale.ROOT, "%s-%s-%s-%s-%s",
+                collectionId,
+                repo.replace("/", "-"),
+                ref.replaceAll("[^a-z0-9-]", "-"),
+                relativePath.replace("/", "-").replace(".", "-"),

Review Comment:
   **Preserve source identity in citation IDs.** The checkout keys now 
distinguish `sample-team/manual` from `sample/team-manual`, and I retrieved the 
correct guide from each. When both had `docs/intro.md` with a `Habitat` 
heading, both hits still had the identical citation ID and collection-level 
`source`. Within one repository, `docs/setup.md` and `docs-setup.md` also 
collapsed to the same ID. Encode the repository, ref and relative path without 
flattening their separators, then include a stable discriminator for the 
section. Assert unique IDs alongside the document contents.
   
   _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,232 @@
+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;
+
+            // Use hash of repo URL to ensure distinct checkouts for different 
repositories
+            // This prevents collision between repos like "sample-team/manual" 
and "sample/team-manual"
+            String repoHash = Integer.toHexString(repo.hashCode());
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + repoHash + "-" + 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 (walk entire tree)
+                List<Path> adocFiles = listFilesRecursively(repoPath, 
"*.adoc");
+                List<Path> mdFiles = listFilesRecursively(repoPath, "*.md");

Review Comment:
   **Limit recursive ingestion to the advertised file types.** In a repository 
with two Markdown guides and `ops/build.cmd`, the generic reader indexed all 
three. MCP returned the command file as documentation. The new matcher turns 
`*.md` into `.*.md`, where the second dot matches any character. The existing 
recursive helper already handles the literal dot. These calls can replace the 
duplicate traversal, and a fixture with a nested guide and a sibling `.cmd` 
file would catch regressions.
   
   ```suggestion
                   List<Path> adocFiles = 
repoFetcher.listFilesRecursive(repoPath, "*.adoc");
                   List<Path> mdFiles = 
repoFetcher.listFilesRecursive(repoPath, "*.md");
   ```
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
docs/modules/ROOT/pages/knowledge.adoc:
##########
@@ -114,6 +114,112 @@ 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
+
+Custom collections are now supported through the generic source reader.
+Provide a collection ID, version, and JSON array of repository sources:
+
+[source,bash]
+----
+./mvnw clean install -pl knowledge/index -am -Prebuild-index -B \
+  -Dcollection.id=my-vendor \
+  -Dcollection.version=1.0.0 \
+  -Dcollection.sources='[{"repo":"my-org/docs","branch":"main"}]'
+----
+
+The build produces an index under `knowledge/index/target/knowledge-index/`.
+To query it, point the MCP server at the generated output directory:
+
+[source,bash]
+----
+java -Dknowledge.index.path=knowledge/index/target/knowledge-index \

Review Comment:
   **Point the query command at the generated index.** I ran the documented 
clean Maven rebuild for `my-vendor`. It succeeded, but the path below did not 
exist, and MCP reported “knowledge.index.path is not a directory”. The same 
runner loaded `my-vendor` version `1.0.0` and returned its guides from the path 
configured in `knowledge/index/pom.xml`. Apply this correction to the paragraph 
above, the Knowledge README, and the release workflow message as well. The 
later Antora note and the README’s publishing section still say local builds 
need a custom `DocumentDomain`.
   
   ```suggestion
   java 
-Dknowledge.index.path=knowledge/index/src/main/resources/knowledge-index \
   ```
   
   _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