luigidemasi commented on code in PR #214:
URL: https://github.com/apache/camel-kit/pull/214#discussion_r4754395170
##########
knowledge/indexer/src/test/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomainTest.java:
##########
@@ -0,0 +1,167 @@
+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.eclipse.jgit.revwalk.RevCommit;
+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
code using ref kind in directory names
+ * prevents tag and branch with same ref value from colliding.
+ */
+ @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();
+ RevCommit tagCommit =
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 · Make the checkout test exercise the production directory selection.**
This fixture constructs separate tag and branch directory names itself. I
temporarily made the production reader use one directory for both kinds. The
real tag → branch → tag build then returned branch content on the last read,
while all 120 indexer test outcomes stayed identical.
Run the fixture through `GenericDocumentDomain.buildChunks()` with the same
cache and assert the emitted content after each selection. The citation test
below similarly needs to assert emitted IDs instead of copying the production
encoding into its own loop.
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/mcp/src/main/java/org/apache/camel/kit/knowledge/mcp/IndexDownloader.java:
##########
@@ -214,6 +302,9 @@ private ResolvedIndex resolveCached(Path cacheDir) throws
IOException {
LOG.info("Knowledge index up to date (version {})",
cachedVersion);
return new ResolvedIndex(cachedDir, false);
}
+ } catch (IndexIncompatibilityException e) {
Review Comment:
**P1 · Report incompatible manifests for a pinned release.** The new catch
fixes a wrong `collectionId`. With fallback disabled and a matching release
already cached, I changed only `formatVersion` to 2 in a fresh manifest. The
packaged server returned two cached hits. Changing only the embedding model,
dimensions, or declared release version produced the same result. On a cold
cache those cases returned a generic acquisition error.
The compatibility and release-version checks still throw ordinary
`IOException`, which takes the cache-reuse path. For a strict pin, propagate
the specific incompatibility to the caller. Please cover a warm and cold pin,
preserve offline use of a matching pin, and keep the existing unpinned
community update behavior.
_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,219 @@
+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, "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;
+ }
+
+ /**
+ * 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.
+ */
+ private String chunkId(String relativePath, String slug, String repo,
String ref) {
+ // Encode all separators to preserve distinct identities
+ 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",
+ collectionId,
+ encodedRepo.toLowerCase(Locale.ROOT),
+ encodedRef.toLowerCase(Locale.ROOT),
+ encodedPath.toLowerCase(Locale.ROOT),
Review Comment:
**P1 · Preserve Git file and ref identity in citations.** In one collection
I registered both the tag and branch named `release`, pointing at different
commits. The packaged server returned different guide text with identical `id`
and `source`. In a second collection, `docs/API.md` and `docs/api.md` with the
same heading produced another identical pair. Git distinguishes those paths,
but this line lowercases them, and `chunkId` receives no ref kind.
Please encode the ref kind and exact ref and path as distinct components.
Assert the IDs on chunks produced by the real reader. The repository-name pair
from the previous review now passes.
_AI-generated by Codex on behalf of @luigidemasi._
##########
knowledge/mcp/src/test/java/org/apache/camel/kit/knowledge/mcp/LuceneTestFixtures.java:
##########
@@ -0,0 +1,57 @@
+package org.apache.camel.kit.knowledge.mcp;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+
+/**
+ * Shared test utilities for creating and reading minimal valid Lucene indexes
for test fixtures.
+ */
+public final class LuceneTestFixtures {
+
+ private LuceneTestFixtures() {
+ }
+
+ /**
+ * Creates a minimal valid Lucene index with a marker field for test
verification.
+ *
+ * @param indexDir directory to create the index in
+ * @param marker marker value to store in the index
+ */
+ public static void createMinimalIndex(Path indexDir, String marker) throws
Exception {
Review Comment:
**P1 · Use the real index fixture in discovery and timeout tests as well.**
All 68 `IndexDownloaderTest` cases now pass. `IndexDiscoveryTest.release()` and
`IndexDownloaderTimeoutTest` still write plain text as `segments_1`. Four
discovery cases and eight timeout cases fail or error before they can verify
the intended behavior. For example,
`pinUsesExactTagAndOfflineFallbackUsesOnlyThatVersion` gets
`IndexFormatTooOldException`.
Share the valid archive builder and marker reader across these suites. A
fresh temporary directory per archive also lets the builder drop version
sanitization and propagate setup errors directly.
_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]