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


##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -214,6 +302,20 @@ private ResolvedIndex resolveCached(Path cacheDir) throws 
IOException {
                 LOG.info("Knowledge index up to date (version {})", 
cachedVersion);
                 return new ResolvedIndex(cachedDir, false);
             }
+        } catch (IndexIncompatibilityException e) {
+            // For pinned versions, incompatibility is an error (no fallback)
+            // For unpinned, treat as a failed update and keep working cache
+            if (config.version().isPresent()) {

Review Comment:
   **P1 · Report a manifest that declares a different release from the pin.** I 
cached `2026.11.30-130000`, pinned that release with fallback disabled, then 
served a fresh manifest for the same collection declaring `2026.11.30-150000`. 
The packaged server returned two cached hits. With an empty cache it returned a 
generic acquisition error that omitted the declared release.
   
   The release-version comparison just above this catch throws an ordinary 
`IOException`, so it bypasses the new incompatibility handler. Classify that 
mismatch alongside the format checks and include the requested and declared 
versions in the error. A truly unreachable manifest should still allow an exact 
cached pin.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -534,6 +689,80 @@ 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 and manifest, then 
closes. This prevents mislabeled releases
+     * from displacing working snapshots.
+     *
+     * @param indexDir The directory containing the extracted Lucene index 
files (unzip strips the archive prefix)
+     * @param manifest The manifest that declared this index version
+     */
+    private void verifyStagedIndex(Path indexDir, Manifest manifest) throws 
IOException {
+        // unzip extracts files directly to indexDir, not to a subdirectory
+        try (FSDirectory directory = FSDirectory.open(indexDir);
+             DirectoryReader reader = DirectoryReader.open(directory)) {
+
+            IndexSearcher searcher = new IndexSearcher(reader);
+
+            // Read collection metadata from the staged index
+            TopDocs td = searcher.search(
+                    new TermQuery(new Term(KnowledgeFields.ID, 
KnowledgeFields.INDEX_META_ID)), 1);
+
+            String indexCollectionId = null;
+            String indexCollectionVersion = null;
+            if (td.scoreDocs.length > 0) {
+                Document metaDoc = searcher.doc(td.scoreDocs[0].doc);
+                indexCollectionId = metaDoc.get(KnowledgeFields.COLLECTION_ID);
+                indexCollectionVersion = 
metaDoc.get(KnowledgeFields.COLLECTION_VERSION);
+            }
+
+            // Backward compatibility: indexes without collection metadata are 
treated as apache-camel
+            if (indexCollectionId == null) {
+                indexCollectionId = "apache-camel";
+            }
+
+            // Verify the staged index matches the requested collection
+            String requestedCollection = config.collectionId();
+            if (!indexCollectionId.equals(requestedCollection)) {
+                throw new IndexIncompatibilityException(

Review Comment:
   **P1 · Keep serving the last verified community index after rejecting a bad 
update.** I started the unpinned server with a working community release, then 
supplied a newer manifest naming `apache-camel` whose correctly checksummed 
archive contained `bar-guides`. This revision rejected the candidate, left the 
old `current` marker intact, and returned an error on search. The previous 
runner returned the original community guide with the same inputs. Taking the 
manifest offline also restored that guide on this revision.
   
   The staged mismatch now escapes the outer resolver as an incompatibility, so 
the server tries an unavailable classpath index. For an unpinned update, leave 
the bad archive inactive and serve the previous verified snapshot of the 
requested collection. Preserve the error for clients pinned to the rejected 
release. [Documented cache 
behavior](https://github.com/apache/camel-kit/blob/e19089761ca3c688995dc36d5e2c7f3ec03eedfc/docs/modules/ROOT/pages/knowledge.adoc#L106)
   
   _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,224 @@
+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 {
+                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 = 
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 (Section section : sections) {
+                String slug = slugify(section.title());
+                String id = chunkId(relativePath, slug, 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, String repo, 
String ref, String refKind) {
+        // Encode all separators to preserve distinct identities
+        // Do NOT lowercase - Git paths and refs are case-sensitive
+        String encodedRepo = repo.replace("/", "_2f_");  // Repository path 
separator
+        String encodedRef = ref.replace("/", "_2f_");    // Ref might contain /
+        String encodedPath = relativePath
+                .replace("/", "_2f_")  // File path separator
+                .replace(".", "_2e_"); // File extension separator
+
+        return String.format(Locale.ROOT, "%s-%s-%s-%s-%s-%s",
+                collectionId,
+                encodedRepo,
+                refKind,
+                encodedRef,
+                encodedPath,
+                slug);

Review Comment:
   **P2 · Preserve section and path identity in the citation.** In one Markdown 
guide I indexed sections titled `C++` and `C#`. Searching for a phrase unique 
to each returned the correct text and title, but both results had the same ID 
ending in `-c`. With the same heading in `docs/setup.md` and 
`docs_2f_setup.md`, the packaged server also returned identical IDs for the two 
files.
   
   Use an unambiguous representation of the exact source components and a 
section identifier that distinguishes headings which share a slug. Please 
assert the IDs on emitted chunks for these examples. The earlier ref-kind and 
case-sensitive path examples now pass.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/test/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomainTest.java:
##########
@@ -0,0 +1,175 @@
+package org.apache.camel.kit.knowledge.indexer.domain;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.camel.kit.knowledge.indexer.GitRepoFetcher;
+
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Regression tests for GenericDocumentDomain to prevent: - Tag/branch 
checkout collisions - Duplicate citation IDs -
+ * Incorrect file type filtering
+ */
+@Timeout(30)
+class GenericDocumentDomainTest {
+
+    private static final PersonIdent IDENTITY = new PersonIdent("Test 
fixture", "[email protected]");
+
+    @TempDir
+    Path tempDir;
+
+    private GitRepoFetcher fetcher;
+
+    @BeforeEach
+    void setup() throws Exception {
+        fetcher = new GitRepoFetcher(tempDir.resolve("cache"));
+    }
+
+    /**
+     * Regression test for file type filtering. *.md must match guide.md but 
NOT build.cmd
+     */
+    @Test
+    void fileFilteringExcludesCommandFiles() throws Exception {
+        // Create test directory with mixed file types
+        Path testRepo = tempDir.resolve("test-repo");
+        Files.createDirectories(testRepo.resolve("docs/nested"));
+        Files.createDirectories(testRepo.resolve("ops"));
+        Files.createDirectories(testRepo.resolve("scripts"));
+
+        Files.writeString(testRepo.resolve("docs/guide.md"), "# Guide");
+        Files.writeString(testRepo.resolve("docs/nested/tutorial.md"), "# 
Tutorial");
+        Files.writeString(testRepo.resolve("ops/build.cmd"), "@echo off");
+        Files.writeString(testRepo.resolve("scripts/deploy.cmd"), "deploy");
+        Files.writeString(testRepo.resolve("README.md"), "# README");
+
+        // Test listFilesRecursive - should match .md but not .cmd
+        List<Path> mdFiles = fetcher.listFilesRecursive(testRepo, "*.md");
+        assertEquals(3, mdFiles.size(), "Should find exactly 3 .md files");
+        assertTrue(mdFiles.stream().allMatch(p -> 
p.toString().endsWith(".md")),
+                "All results should end with .md");
+        assertTrue(mdFiles.stream().noneMatch(p -> 
p.toString().endsWith(".cmd")),
+                "No .cmd files should be matched");
+    }
+
+    /**
+     * Regression test for tag → branch → tag collision. Tests that production 
directory naming with ref kind prevents
+     * collisions when tag and branch have the same name.
+     */
+    @Test
+    void tagAndBranchCheckoutsAreSeparate() throws Exception {
+        // Create upstream repository
+        Git upstream = 
Git.init().setDirectory(tempDir.resolve("upstream").toFile())
+                .setInitialBranch("main").call();
+        try {
+            Path workTree = upstream.getRepository().getWorkTree().toPath();
+
+            // Create release branch with one content
+            Files.writeString(workTree.resolve("guide.md"), "Branch content");
+            upstream.add().addFilepattern(".").call();
+            
upstream.commit().setMessage("branch").setAuthor(IDENTITY).setCommitter(IDENTITY)
+                    .setSign(false).setNoVerify(true).call();
+            upstream.branchCreate().setName("release").call();
+
+            // Switch back to main and create tag with different content
+            Files.writeString(workTree.resolve("guide.md"), "Tag content");
+            upstream.add().addFilepattern(".").call();
+            
upstream.commit().setMessage("tag").setAuthor(IDENTITY).setCommitter(IDENTITY)
+                    .setSign(false).setNoVerify(true).call();
+            
upstream.tag().setName("release").setAnnotated(true).setMessage("release")
+                    .setTagger(IDENTITY).setSigned(false).call();
+
+            String repoUrl = tempDir.resolve("upstream").toUri().toString();
+            String repoHash = Integer.toHexString(repoUrl.hashCode());
+
+            // Use actual production directory names that include ref kind
+            // Format matches GenericDocumentDomain: 
collectionId-repo-repoHash-refKind-ref
+            String tagDir = "test-collection-test-repo-" + repoHash + 
"-tag-release";
+            String branchDir = "test-collection-test-repo-" + repoHash + 
"-branch-release";

Review Comment:
   **P2 · Exercise checkout selection through the collection reader.** The 
fixture still supplies its own separate tag and branch directory names. I 
temporarily made the production reader use one directory for both. In a real 
tag → branch → tag build, the third build then served the branch guide. All 120 
indexer test outcomes stayed identical.
   
   Use the local Git fixture with `GenericDocumentDomain.buildChunks()`, call 
it three times against one cache, and assert the emitted content each time. 
That test can also check citation IDs without reflecting into a private method.
   
   _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