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


##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -207,13 +295,32 @@ private ResolvedIndex resolveCached(Path cacheDir) throws 
IOException {
             manifest = fetchManifest(manifestUri, cacheDir, haveCached ? 
cachedVersion : null);
             if (location.version() != null
                     && !location.version().equals(manifest == null ? 
cachedVersion : manifest.version())) {
-                throw new IOException("Index manifest version does not match 
its release tag");
+                String declaredVersion = manifest != null ? manifest.version() 
: cachedVersion;
+                throw new IndexIncompatibilityException(
+                        String.format(

Review Comment:
   **The full build fails in `forbiddenapis:check`.** This call and seven other 
calls introduced by the PR use the default-locale `String.format` overload. The 
same check flags `IndexDownloader` lines 632, 748, 761 and 768, and 
`LuceneSearchService` lines 90, 240 and 766. Passing `Locale.ROOT` at all eight 
sites made the Knowledge MCP verification build pass locally. For this 
occurrence, `Locale` is already imported.
   
   ```suggestion
                           String.format(Locale.ROOT,
   ```
   
   _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,238 @@
+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"
+            // Include ref kind to prevent branch/tag collision (same name, 
different commits)
+            String repoHash = Integer.toHexString(repo.hashCode());
+            String refKind = isTag ? "tag" : "branch";
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + repoHash + "-" + refKind + "-" + ref;
+
+            LOG.info("  Fetching {}: {} @ {}", repo, ref, (isTag ? "tag" : 
"branch"));
+
+            try {
+                // If repo is already a full URL (http://, https://, file://), 
use it directly
+                // Otherwise assume it's a GitHub owner/repo path
+                String repoUrl = repo.matches("^[a-z]+://.*")

Review Comment:
   **Keep the checkout fixture portable.** The new full-URL form sends the raw 
repository string into the cache directory name at line 91. For a 
`file:///C:/manual` source, `buildChunks()` on a Windows-style Jimfs filesystem 
threw `InvalidPathException` at the colon in `manual-file:…`, before JGit 
opened the repository. The revised regression test supplies this same kind of 
URL.
   
   The smallest fix is to keep the documented `owner/repo` input and point the 
test’s Git configuration at its local fixture. If full URLs are intended as a 
feature, derive a filesystem-safe checkout name, test it with Windows path 
rules, and update the K2 source description in `docs/security-model.md` and 
`.yaml` to cover the supported origins.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -230,22 +337,69 @@ 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 (IndexIncompatibilityException e) {
+                // Verified incompatibility - do NOT fallback, propagate
+                throw e;
+            } catch (IOException e) {
+                // Verification failed - treat as incompatibility
+                throw new IndexIncompatibilityException(
+                        "Cached index version " + cachedVersion + " failed 
verification against fresh manifest: " +
+                                                        e.getMessage()
+                                                        + ". The cached 
snapshot does not match the current manifest declaration. "
+                                                        +
+                                                        "Delete " + cachedDir 
+ " to force re-download.");
+            }
             saveValidator(cacheDir, manifestUri, manifest);
             LOG.info("Knowledge index up to date (version {})", cachedVersion);
             return new ResolvedIndex(cachedDir, false);
         }
 
         Path versionDir = versionDirectory(cacheDir, manifest.version());
-        if (!Files.isDirectory(versionDir)) {
-            downloadAndUnpack(manifestUri, manifest, cacheDir, versionDir);
-        }
+        try {
+            if (!Files.isDirectory(versionDir)) {
+                downloadAndUnpack(manifestUri, manifest, cacheDir, versionDir);
+            } else {
+                // Verify cached snapshot before reactivating it - must match 
declared version
+                LOG.info("Version {} already cached, verifying before 
reactivating", manifest.version());
+                try {
+                    verifyStagedIndex(versionDir, manifest);
+                } catch (IOException e) {
+                    throw new IndexIncompatibilityException(
+                            "Cached index version " + manifest.version() + " 
failed verification: " + e.getMessage() +
+                                                            ". The cached 
snapshot does not match the declared manifest. "
+                                                            +
+                                                            "Delete " + 
versionDir + " to force re-download.");
+                }
+            }
 
-        writeAtomically(marker, manifest.version());
-        saveValidator(cacheDir, manifestUri, manifest);
-        // Pruning follows activation and the best-effort validator-save 
attempt.
-        prune(cacheDir, manifest.version(), cachedVersion);
-        LOG.info("Knowledge index version {} ready at {}", manifest.version(), 
versionDir);
-        return new ResolvedIndex(versionDir, false);
+            writeAtomically(marker, manifest.version());
+            saveValidator(cacheDir, manifestUri, manifest);
+            // Pruning follows activation and the best-effort validator-save 
attempt.
+            prune(cacheDir, manifest.version(), cachedVersion);
+            LOG.info("Knowledge index version {} ready at {}", 
manifest.version(), versionDir);
+            return new ResolvedIndex(versionDir, false);
+        } catch (IndexIncompatibilityException e) {
+            // Staged or downloaded index is incompatible (collection 
mismatch, format, model, etc.)
+            // For pinned versions, this is an error (strict requirement)
+            // For unpinned, treat as a failed update and keep serving the 
previous verified index
+            if (config.version().isPresent()) {
+                throw e; // Pinned: strict requirement, fail
+            }
+            // Unpinned: reject bad update, keep serving previous verified 
snapshot
+            if (haveCached) {

Review Comment:
   **Add regression tests for the two downloader fixes.** I temporarily 
restored `IndexDownloader` from `e1908976` and reran the MCP suite. All 135 
outcomes stayed identical, including the four skips. The packaged server 
distinguishes the two revisions in both cases.
   
   Please cover (1) a cached, pinned release A whose fresh manifest declares B, 
asserting that resolution reports both versions, and (2) an unpinned community 
release A followed by a checksummed release B archive from another collection, 
asserting that search still returns A’s content and `current` still points to 
A. These cases distinguish a confirmed pin mismatch from a failed update with a 
usable cache.
   
   _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,238 @@
+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"
+            // Include ref kind to prevent branch/tag collision (same name, 
different commits)
+            String repoHash = Integer.toHexString(repo.hashCode());
+            String refKind = isTag ? "tag" : "branch";
+            String localName = collectionId + "-" + repo.replace("/", "-") + 
"-" + repoHash + "-" + refKind + "-" + ref;
+
+            LOG.info("  Fetching {}: {} @ {}", repo, ref, (isTag ? "tag" : 
"branch"));
+
+            try {
+                // If repo is already a full URL (http://, https://, file://), 
use it directly
+                // Otherwise assume it's a GitHub owner/repo path
+                String repoUrl = repo.matches("^[a-z]+://.*")
+                        ? repo
+                        : "https://github.com/"; + repo + ".git";
+                Path repoPath = repoFetcher.fetchRepo(repoUrl, ref, localName, 
isTag);
+
+                // Index all .adoc and .md files recursively (walk entire tree)
+                List<Path> adocFiles = 
repoFetcher.listFilesRecursive(repoPath, "*.adoc");
+                List<Path> mdFiles = repoFetcher.listFilesRecursive(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, refKind, 
"adoc", repoPath));
+                }
+
+                // Process Markdown files
+                for (Path file : mdFiles) {
+                    chunks.addAll(convertAndChunk(file, repo, ref, refKind, 
"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 refKind, 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 (int sectionIndex = 0; sectionIndex < sections.size(); 
sectionIndex++) {
+                Section section = sections.get(sectionIndex);
+                String slug = slugify(section.title());
+                // Include section position to ensure uniqueness when slugs 
collide (e.g., "C++" and "C#" both -> "c")
+                String id = chunkId(relativePath, slug, sectionIndex, repo, 
ref, refKind);
+
+                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;
+    }
+
+    /**
+     * Generate a unique chunk ID including repository-relative path and 
extension. Encodes all path components to
+     * preserve identity: sample-team/manual vs sample/team-manual, 
docs/setup.md vs docs-setup.md, branch vs tag with
+     * same name, case-sensitive paths like docs/API.md vs docs/api.md.
+     */
+    private String chunkId(
+            String relativePath, String slug, int sectionIndex, String repo, 
String ref, String refKind) {
+        // Encode all separators to preserve distinct identities
+        // Do NOT lowercase - Git paths and refs are case-sensitive
+        // Encode underscores first to prevent collision (e.g., 
"docs/setup.md" vs "docs_2f_setup.md")
+        String encodedRepo = repo
+                .replace("_", "_5f_")  // Underscore (must be first)
+                .replace("/", "_2f_"); // Repository path separator
+        String encodedRef = ref
+                .replace("_", "_5f_")  // Underscore (must be first)
+                .replace("/", "_2f_"); // Ref might contain /
+        String encodedPath = relativePath
+                .replace("_", "_5f_")  // Underscore (must be first)
+                .replace("/", "_2f_")  // File path separator
+                .replace(".", "_2e_"); // File extension separator
+
+        return String.format(Locale.ROOT, "%s-%s-%s-%s-%s-%s-%d",

Review Comment:
   **Make the citation identify a single source.** I indexed `qa-guide.md` on 
branch `release` and `guide.md` on branch `release-qa` in the same repository. 
Both guides start with `Configuration`. One search for `delivery` returned both 
guides with different text and the same `id`, ending in 
`-branch-release-qa-guide_2e_md-configuration-0`. Both hits also had the same 
`source` and section title. A consumer citing the ID cannot tell which guide 
supplied the answer.
   
   Please encode the boundaries between fields as well as the characters within 
each field. A length-prefixed tuple would work. Add the two refs to one 
collection fixture and assert that the search results have distinct IDs.
   
   _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