From ad8db7f0db53bc0425e26282313706a8099fb792 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Wed, 8 Apr 2026 14:12:41 +0100 Subject: [PATCH 01/12] feat: multi-collection search with client-side RRF fusion and deduplication Add searchMultipleCollections() and mergeMultiCollectionResults() to qdrant.ts. Queries multiple Qdrant collections in parallel, merges results using Reciprocal Rank Fusion (k=60), and deduplicates by relativePath (first collection wins). Add optional 'project' field to SearchResult type for source attribution. This is the shared foundation for linked projects (#20) and branch-aware indexing (#19). Refs: #19, #20 --- src/services/qdrant.ts | 84 ++++++++ src/types.ts | 2 + tests/unit/multi-collection-search.test.ts | 224 +++++++++++++++++++++ 3 files changed, 310 insertions(+) create mode 100644 tests/unit/multi-collection-search.test.ts diff --git a/src/services/qdrant.ts b/src/services/qdrant.ts index 9057bd4..d9b4e92 100644 --- a/src/services/qdrant.ts +++ b/src/services/qdrant.ts @@ -354,6 +354,90 @@ export async function searchChunks( })); } +/** Merge results from multiple collection queries using client-side Reciprocal Rank Fusion. + * Deduplicates by relativePath — first (higher-priority) collection wins on conflict. + * Exported for unit testing. */ +export function mergeMultiCollectionResults( + collectionResults: Array<{ label: string; results: SearchResult[] }>, + limit: number, +): SearchResult[] { + const RRF_K = 60; + const scored = new Map(); + + for (const { label, results } of collectionResults) { + for (let rank = 0; rank < results.length; rank++) { + const r = results[rank]; + const key = r.relativePath; + const rrfContribution = 1 / (RRF_K + rank + 1); + + const existing = scored.get(key); + if (existing) { + existing.rrfScore += rrfContribution; + // Keep the version from the higher-priority (earlier) collection + } else { + scored.set(key, { ...r, project: label, rrfScore: rrfContribution }); + } + } + } + + return Array.from(scored.values()) + .sort((a, b) => b.rrfScore - a.rrfScore) + .slice(0, limit) + .map(({ rrfScore, ...result }) => ({ + ...result, + score: rrfScore, + })); +} + +/** Search across multiple collections in parallel with client-side RRF fusion and deduplication. + * Each collection's results are queried independently, then merged using Reciprocal Rank Fusion. + * When the same relativePath appears in multiple collections, the result from the + * earlier (higher-priority) collection wins. + * + * @param collections - Array of { name, label } where label identifies the source project + * in results. Order defines priority for deduplication (first wins). + * @param query - Natural language search query. + * @param limit - Maximum total results to return after merge. + * @param fileFilter - Optional relativePath filter applied to every collection. + * @param languageFilter - Optional language filter applied to every collection. + */ +export async function searchMultipleCollections( + collections: Array<{ name: string; label: string }>, + query: string, + limit: number = 10, + fileFilter?: string, + languageFilter?: string, +): Promise { + if (collections.length === 0) return []; + if (collections.length === 1) { + const results = await searchChunks(collections[0].name, query, limit, fileFilter, languageFilter); + return results.map((r) => ({ ...r, project: collections[0].label })); + } + + // Query all collections in parallel, requesting extra candidates for RRF re-ranking + const perCollectionLimit = Math.max(limit * 2, 20); + const collectionResults: Array<{ label: string; results: SearchResult[] }> = []; + + const allResults = await Promise.all( + collections.map(async ({ name, label }) => { + try { + const results = await searchChunks(name, query, perCollectionLimit, fileFilter, languageFilter); + return { label, results }; + } catch (err) { + logger.warn("searchMultipleCollections: collection query failed, skipping", { + collection: name, + error: err instanceof Error ? err.message : String(err), + }); + return { label, results: [] as SearchResult[] }; + } + }), + ); + + collectionResults.push(...allResults); + + return mergeMultiCollectionResults(collectionResults, limit); +} + /** Hybrid search with arbitrary payload filters. * Used by context artifacts to filter by artifactName. */ export async function searchChunksWithFilter( diff --git a/src/types.ts b/src/types.ts index ba56186..56354b2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -39,6 +39,8 @@ export interface SearchResult { endLine: number; language: string; score: number; + /** Source project label (set when searching across multiple collections) */ + project?: string; } export interface HealthStatus { diff --git a/tests/unit/multi-collection-search.test.ts b/tests/unit/multi-collection-search.test.ts new file mode 100644 index 0000000..7b57b77 --- /dev/null +++ b/tests/unit/multi-collection-search.test.ts @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Giancarlo Erra - Altaire Limited + +/** + * Unit tests for mergeMultiCollectionResults — client-side RRF fusion + * and deduplication across multiple collection result sets. + * Tests the pure function directly (no mocks needed). + */ + +import { describe, expect, it } from "vitest"; +import type { SearchResult } from "../../src/types.js"; +import { mergeMultiCollectionResults } from "../../src/services/qdrant.js"; + +// ── Helpers ───────────────────────────────────────────────────────────── + +function makeResult(relativePath: string, score: number, overrides?: Partial): SearchResult { + return { + filePath: `/project/${relativePath}`, + relativePath, + content: `content of ${relativePath}`, + startLine: 1, + endLine: 10, + language: "typescript", + score, + ...overrides, + }; +} + +// ── Tests ──────────────────────────────────────────────────────────────── + +describe("mergeMultiCollectionResults", () => { + it("returns empty array for empty input", () => { + const results = mergeMultiCollectionResults([], 10); + expect(results).toEqual([]); + }); + + it("returns results from a single collection with project label", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "my-project", + results: [ + makeResult("src/index.ts", 0.85), + makeResult("src/utils.ts", 0.72), + ], + }, + ], + 10, + ); + + expect(results).toHaveLength(2); + expect(results[0].project).toBe("my-project"); + expect(results[1].project).toBe("my-project"); + expect(results[0].relativePath).toBe("src/index.ts"); + expect(results[1].relativePath).toBe("src/utils.ts"); + }); + + it("merges results from two collections — all unique files present", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "project-a", + results: [ + makeResult("src/file1.ts", 0.90), + makeResult("src/file2.ts", 0.80), + ], + }, + { + label: "project-b", + results: [ + makeResult("src/file3.ts", 0.95), + makeResult("src/file4.ts", 0.70), + ], + }, + ], + 10, + ); + + expect(results).toHaveLength(4); + const paths = results.map((r) => r.relativePath); + expect(paths).toContain("src/file1.ts"); + expect(paths).toContain("src/file2.ts"); + expect(paths).toContain("src/file3.ts"); + expect(paths).toContain("src/file4.ts"); + + // Correct project labels + expect(results.find((r) => r.relativePath === "src/file1.ts")?.project).toBe("project-a"); + expect(results.find((r) => r.relativePath === "src/file3.ts")?.project).toBe("project-b"); + }); + + it("deduplicates by relativePath — first (higher-priority) collection wins", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "project-a", + results: [makeResult("src/shared.ts", 0.90, { content: "content from A" })], + }, + { + label: "project-b", + results: [makeResult("src/shared.ts", 0.85, { content: "content from B" })], + }, + ], + 10, + ); + + const sharedResults = results.filter((r) => r.relativePath === "src/shared.ts"); + expect(sharedResults).toHaveLength(1); + expect(sharedResults[0].content).toBe("content from A"); + expect(sharedResults[0].project).toBe("project-a"); + }); + + it("RRF scores accumulate for files appearing in multiple collections", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "project-a", + results: [ + makeResult("src/popular.ts", 0.90), + makeResult("src/only-a.ts", 0.80), + ], + }, + { + label: "project-b", + results: [ + makeResult("src/popular.ts", 0.85), + makeResult("src/only-b.ts", 0.75), + ], + }, + ], + 10, + ); + + // popular.ts should rank first due to accumulated RRF score from both collections + expect(results[0].relativePath).toBe("src/popular.ts"); + // Its score should be higher than single-collection results + expect(results[0].score).toBeGreaterThan(results[1].score); + // The accumulated score = 1/(60+1) + 1/(60+1) = 2 * 1/61 ≈ 0.0328 + const expectedAccumulated = 2 * (1 / 61); + expect(results[0].score).toBeCloseTo(expectedAccumulated, 6); + }); + + it("respects the limit parameter", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "a", + results: [ + makeResult("src/a1.ts", 0.9), + makeResult("src/a2.ts", 0.8), + makeResult("src/a3.ts", 0.7), + ], + }, + { + label: "b", + results: [ + makeResult("src/b1.ts", 0.95), + makeResult("src/b2.ts", 0.85), + makeResult("src/b3.ts", 0.75), + ], + }, + ], + 3, + ); + + expect(results).toHaveLength(3); + }); + + it("results are sorted by fused RRF score descending", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "a", + results: [ + makeResult("src/first.ts", 0.90), + makeResult("src/second.ts", 0.80), + ], + }, + { + label: "b", + results: [ + makeResult("src/third.ts", 0.95), + ], + }, + ], + 10, + ); + + for (let i = 1; i < results.length; i++) { + expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score); + } + }); + + it("handles three collections", () => { + const results = mergeMultiCollectionResults( + [ + { label: "a", results: [makeResult("src/a.ts", 0.9)] }, + { label: "b", results: [makeResult("src/b.ts", 0.8)] }, + { label: "c", results: [makeResult("src/c.ts", 0.7)] }, + ], + 10, + ); + + expect(results).toHaveLength(3); + expect(results.map((r) => r.project)).toEqual( + expect.arrayContaining(["a", "b", "c"]), + ); + }); + + it("handles empty results from some collections", () => { + const results = mergeMultiCollectionResults( + [ + { label: "a", results: [makeResult("src/a.ts", 0.9)] }, + { label: "b", results: [] }, + { label: "c", results: [makeResult("src/c.ts", 0.7)] }, + ], + 10, + ); + + expect(results).toHaveLength(2); + expect(results.map((r) => r.project)).toEqual( + expect.arrayContaining(["a", "c"]), + ); + }); +}); From 61e868cf9ef484cc83777d302094b10dd48ec5e3 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Wed, 8 Apr 2026 14:17:16 +0100 Subject: [PATCH 02/12] feat: linked projects support via .socraticode.json and SOCRATICODE_LINKED_PROJECTS - loadLinkedProjects() reads .socraticode.json config and env var - resolveLinkedCollections() maps linked projects to collection names - codebase_search gains includeLinked parameter for cross-project queries - Results tagged with [project-label] when searching across projects - 10 unit tests for config loading and collection resolution Relates to #20 --- src/config.ts | 87 +++++++++++++++++++++++ src/index.ts | 4 ++ src/tools/query-tools.ts | 16 +++-- tests/unit/config.test.ts | 146 +++++++++++++++++++++++++++++++++++++- 4 files changed, 247 insertions(+), 6 deletions(-) diff --git a/src/config.ts b/src/config.ts index 7252438..46ce910 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited import { createHash } from "node:crypto"; +import fs from "node:fs"; import path from "node:path"; /** @@ -46,3 +47,89 @@ export function graphCollectionName(projectId: string): string { export function contextCollectionName(projectId: string): string { return `context_${projectId}`; } + +// ── Linked projects ────────────────────────────────────────────────────── + +/** Configuration file name for linked projects */ +const SOCRATICODE_CONFIG_FILE = ".socraticode.json"; + +/** Shape of .socraticode.json */ +interface SocratiCodeConfig { + linkedProjects?: string[]; +} + +/** + * Load linked project paths from `.socraticode.json` and/or the + * `SOCRATICODE_LINKED_PROJECTS` env var (comma-separated absolute or relative paths). + * + * Returns resolved absolute paths. Invalid/missing paths are silently skipped. + */ +export function loadLinkedProjects(projectPath: string): string[] { + const resolvedRoot = path.resolve(projectPath); + const paths = new Set(); + + // 1. Read .socraticode.json + const configPath = path.join(resolvedRoot, SOCRATICODE_CONFIG_FILE); + try { + if (fs.existsSync(configPath)) { + const raw = fs.readFileSync(configPath, "utf-8"); + const config = JSON.parse(raw) as SocratiCodeConfig; + if (Array.isArray(config.linkedProjects)) { + for (const p of config.linkedProjects) { + if (typeof p === "string" && p.trim()) { + const resolved = path.resolve(resolvedRoot, p.trim()); + if (resolved !== resolvedRoot && fs.existsSync(resolved)) { + paths.add(resolved); + } + } + } + } + } + } catch { + // Malformed JSON or read error — skip silently + } + + // 2. Read env var (comma-separated) + const envLinked = process.env.SOCRATICODE_LINKED_PROJECTS?.trim(); + if (envLinked) { + for (const p of envLinked.split(",")) { + const trimmed = p.trim(); + if (trimmed) { + const resolved = path.resolve(resolvedRoot, trimmed); + if (resolved !== resolvedRoot && fs.existsSync(resolved)) { + paths.add(resolved); + } + } + } + } + + return Array.from(paths); +} + +/** + * Resolve linked projects into Qdrant collection descriptors for multi-collection search. + * Returns an array of { name, label } suitable for `searchMultipleCollections()`. + * The current project is always first (highest priority for dedup). + */ +export function resolveLinkedCollections( + projectPath: string, +): Array<{ name: string; label: string }> { + const resolvedRoot = path.resolve(projectPath); + const currentId = projectIdFromPath(resolvedRoot); + const collections: Array<{ name: string; label: string }> = [ + { name: collectionName(currentId), label: path.basename(resolvedRoot) }, + ]; + + const linked = loadLinkedProjects(resolvedRoot); + for (const linkedPath of linked) { + const linkedId = projectIdFromPath(linkedPath); + // Skip if same project ID (e.g. worktrees sharing SOCRATICODE_PROJECT_ID) + if (linkedId === currentId) continue; + collections.push({ + name: collectionName(linkedId), + label: path.basename(linkedPath), + }); + } + + return collections; +} diff --git a/src/index.ts b/src/index.ts index d6b96ef..2ac4e72 100644 --- a/src/index.ts +++ b/src/index.ts @@ -143,6 +143,10 @@ server.tool( .max(1) .describe("Minimum RRF score threshold (0-1). Results below this are filtered out. Default: 0.10 (override globally via SEARCH_MIN_SCORE env var). Set to 0 to disable filtering.") .optional(), + includeLinked: z + .boolean() + .describe("When true, also search across linked projects defined in .socraticode.json or SOCRATICODE_LINKED_PROJECTS env var. Results include a project label showing which project each result came from. Default: false.") + .optional(), }, async (args) => ({ content: [{ type: "text", text: await handleQueryTool("codebase_search", args) }], diff --git a/src/tools/query-tools.ts b/src/tools/query-tools.ts index 0a4d5bc..2aec320 100644 --- a/src/tools/query-tools.ts +++ b/src/tools/query-tools.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited import path from "node:path"; -import { collectionName, projectIdFromPath } from "../config.js"; +import { collectionName, projectIdFromPath, resolveLinkedCollections } from "../config.js"; import { SEARCH_DEFAULT_LIMIT, SEARCH_MIN_SCORE } from "../constants.js"; import { getGraphStatus } from "../services/code-graph.js"; import { getArtifactStatusSummary } from "../services/context-artifacts.js"; @@ -12,7 +12,7 @@ import type { IndexingProgress } from "../services/indexer.js"; import { getIndexingProgress, getLastCompleted, isIndexingInProgress } from "../services/indexer.js"; import { getLockHolderPid, } from "../services/lock.js"; import { ensureOllamaReady } from "../services/ollama.js"; -import { getCollectionInfo, getProjectMetadata, searchChunks } from "../services/qdrant.js"; +import { getCollectionInfo, getProjectMetadata, searchChunks, searchMultipleCollections } from "../services/qdrant.js"; import { ensureWatcherStarted, isWatchedByAnyProcess, isWatching } from "../services/watcher.js"; /** Format an IndexingProgress into display lines (elapsed, progress, batches, graph). */ @@ -71,8 +71,15 @@ export async function handleQueryTool( const limit = (args.limit as number) || SEARCH_DEFAULT_LIMIT; const fileFilter = args.fileFilter as string | undefined; const languageFilter = args.languageFilter as string | undefined; + const includeLinked = args.includeLinked as boolean | undefined; - const allResults = await searchChunks(collection, query, limit, fileFilter, languageFilter); + let allResults; + if (includeLinked) { + const collections = resolveLinkedCollections(resolvedPath); + allResults = await searchMultipleCollections(collections, query, limit, fileFilter, languageFilter); + } else { + allResults = await searchChunks(collection, query, limit, fileFilter, languageFilter); + } // Apply minimum score threshold const minScore = (args.minScore as number) ?? SEARCH_MIN_SCORE; @@ -110,7 +117,8 @@ export async function handleQueryTool( } for (const r of results) { - lines.push(`--- ${r.relativePath} (lines ${r.startLine}-${r.endLine}) [${r.language}] score: ${r.score.toFixed(4)} ---`); + const projectTag = r.project ? ` [${r.project}]` : ""; + lines.push(`--- ${r.relativePath} (lines ${r.startLine}-${r.endLine}) [${r.language}]${projectTag} score: ${r.score.toFixed(4)} ---`); lines.push(r.content); lines.push(""); } diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index c75fbfe..4465169 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -1,7 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited -import { afterEach, describe, expect, it } from "vitest"; -import { collectionName, contextCollectionName, graphCollectionName, projectIdFromPath } from "../../src/config.js"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { collectionName, contextCollectionName, graphCollectionName, loadLinkedProjects, projectIdFromPath, resolveLinkedCollections } from "../../src/config.js"; describe("config", () => { // Clean up env override between tests @@ -135,4 +138,143 @@ describe("config", () => { expect(contextColl).toMatch(/^context_[0-9a-f]{12}$/); }); }); + + // ── Linked projects ───────────────────────────────────────────────── + + describe("loadLinkedProjects", () => { + let tmpDir: string; + let projectDir: string; + let linkedDirA: string; + let linkedDirB: string; + const originalLinkedEnv = process.env.SOCRATICODE_LINKED_PROJECTS; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-test-")); + projectDir = path.join(tmpDir, "my-project"); + linkedDirA = path.join(tmpDir, "linked-a"); + linkedDirB = path.join(tmpDir, "linked-b"); + fs.mkdirSync(projectDir, { recursive: true }); + fs.mkdirSync(linkedDirA, { recursive: true }); + fs.mkdirSync(linkedDirB, { recursive: true }); + delete process.env.SOCRATICODE_LINKED_PROJECTS; + }); + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + if (originalLinkedEnv === undefined) { + delete process.env.SOCRATICODE_LINKED_PROJECTS; + } else { + process.env.SOCRATICODE_LINKED_PROJECTS = originalLinkedEnv; + } + }); + + it("returns empty array when no .socraticode.json exists", () => { + expect(loadLinkedProjects(projectDir)).toEqual([]); + }); + + it("reads linked projects from .socraticode.json", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: ["../linked-a", "../linked-b"] }), + ); + const result = loadLinkedProjects(projectDir); + expect(result).toHaveLength(2); + expect(result).toContain(linkedDirA); + expect(result).toContain(linkedDirB); + }); + + it("skips non-existent linked paths", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: ["../linked-a", "../does-not-exist"] }), + ); + const result = loadLinkedProjects(projectDir); + expect(result).toHaveLength(1); + expect(result).toContain(linkedDirA); + }); + + it("skips self-references", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: [".", "../my-project"] }), + ); + expect(loadLinkedProjects(projectDir)).toEqual([]); + }); + + it("reads from SOCRATICODE_LINKED_PROJECTS env var", () => { + process.env.SOCRATICODE_LINKED_PROJECTS = `${linkedDirA},${linkedDirB}`; + const result = loadLinkedProjects(projectDir); + expect(result).toHaveLength(2); + expect(result).toContain(linkedDirA); + expect(result).toContain(linkedDirB); + }); + + it("merges config file and env var without duplicates", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: ["../linked-a"] }), + ); + process.env.SOCRATICODE_LINKED_PROJECTS = `${linkedDirA},${linkedDirB}`; + const result = loadLinkedProjects(projectDir); + // linked-a appears in both sources but should be deduplicated + expect(result).toHaveLength(2); + expect(result).toContain(linkedDirA); + expect(result).toContain(linkedDirB); + }); + + it("handles malformed .socraticode.json gracefully", () => { + fs.writeFileSync(path.join(projectDir, ".socraticode.json"), "not valid json{{{"); + expect(loadLinkedProjects(projectDir)).toEqual([]); + }); + + it("handles .socraticode.json with missing linkedProjects field", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ someOtherField: true }), + ); + expect(loadLinkedProjects(projectDir)).toEqual([]); + }); + }); + + describe("resolveLinkedCollections", () => { + let tmpDir: string; + let projectDir: string; + let linkedDir: string; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-test-")); + projectDir = path.join(tmpDir, "main-project"); + linkedDir = path.join(tmpDir, "linked-lib"); + fs.mkdirSync(projectDir, { recursive: true }); + fs.mkdirSync(linkedDir, { recursive: true }); + delete process.env.SOCRATICODE_LINKED_PROJECTS; + delete process.env.SOCRATICODE_PROJECT_ID; + }); + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + delete process.env.SOCRATICODE_LINKED_PROJECTS; + }); + + it("returns only current project when no links configured", () => { + const collections = resolveLinkedCollections(projectDir); + expect(collections).toHaveLength(1); + expect(collections[0].label).toBe("main-project"); + expect(collections[0].name).toMatch(/^codebase_/); + }); + + it("returns current + linked collections with correct labels", () => { + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: ["../linked-lib"] }), + ); + const collections = resolveLinkedCollections(projectDir); + expect(collections).toHaveLength(2); + // Current project is first (highest priority) + expect(collections[0].label).toBe("main-project"); + expect(collections[1].label).toBe("linked-lib"); + // Different collection names + expect(collections[0].name).not.toBe(collections[1].name); + }); + }); }); From 3a4139d71426e7097a0b897db47dce99c5fac5b4 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Wed, 8 Apr 2026 14:19:57 +0100 Subject: [PATCH 03/12] feat: branch-aware collection naming via SOCRATICODE_BRANCH_AWARE - detectGitBranch() detects current git branch via git rev-parse - sanitizeBranchName() converts branch names to Qdrant-safe suffixes - When SOCRATICODE_BRANCH_AWARE=true, projectIdFromPath appends __branch to create separate indexes per branch - Explicit SOCRATICODE_PROJECT_ID takes precedence (no branch suffix) - 14 unit tests for sanitization, detection, and integration Relates to #19 --- src/config.ts | 50 +++++++++++++++++- tests/unit/config.test.ts | 105 +++++++++++++++++++++++++++++++++++++- 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/src/config.ts b/src/config.ts index 46ce910..f816378 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,9 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited +import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; +// ── Branch detection ───────────────────────────────────────────────────── + +/** + * Detect the current git branch for a project path. + * Returns `null` if the path is not inside a git repository or detection fails. + */ +export function detectGitBranch(projectPath: string): string | null { + try { + const branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: path.resolve(projectPath), + encoding: "utf-8", + timeout: 5000, + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + // "HEAD" is returned for detached HEAD state — treat as no branch + return branch && branch !== "HEAD" ? branch : null; + } catch { + return null; + } +} + +/** + * Sanitize a git branch name for use in Qdrant collection names. + * Replaces characters outside `[a-zA-Z0-9_-]` with underscores, + * collapses consecutive underscores, and strips leading/trailing underscores. + */ +export function sanitizeBranchName(branch: string): string { + return branch + .replace(/[^a-zA-Z0-9_-]/g, "_") + .replace(/_+/g, "_") + .replace(/^_|_$/g, ""); +} + /** * Generate a stable project ID from an absolute folder path. * Uses a short SHA-256 prefix so collection names stay Qdrant-friendly. @@ -12,6 +46,10 @@ import path from "node:path"; * of hashing the path. This lets multiple directory trees (e.g. git * worktrees) share a single Qdrant index. The value must contain only * characters valid in a Qdrant collection name (`[a-zA-Z0-9_-]`). + * + * When `SOCRATICODE_BRANCH_AWARE` is `"true"` (and no explicit project ID + * is set), the current git branch name is appended to the hash, producing + * a separate set of collections per branch. */ export function projectIdFromPath(folderPath: string): string { const explicit = process.env.SOCRATICODE_PROJECT_ID?.trim(); @@ -24,7 +62,17 @@ export function projectIdFromPath(folderPath: string): string { return explicit; } const normalized = path.resolve(folderPath); - return createHash("sha256").update(normalized).digest("hex").slice(0, 12); + let id = createHash("sha256").update(normalized).digest("hex").slice(0, 12); + + // Branch-aware mode: append sanitized branch name to isolate per-branch indexes + if (process.env.SOCRATICODE_BRANCH_AWARE === "true") { + const branch = detectGitBranch(normalized); + if (branch) { + id = `${id}__${sanitizeBranchName(branch)}`; + } + } + + return id; } /** diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index 4465169..bbecb3a 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -4,17 +4,23 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { collectionName, contextCollectionName, graphCollectionName, loadLinkedProjects, projectIdFromPath, resolveLinkedCollections } from "../../src/config.js"; +import { collectionName, contextCollectionName, detectGitBranch, graphCollectionName, loadLinkedProjects, projectIdFromPath, resolveLinkedCollections, sanitizeBranchName } from "../../src/config.js"; describe("config", () => { - // Clean up env override between tests + // Clean up env overrides between tests const originalEnv = process.env.SOCRATICODE_PROJECT_ID; + const originalBranchAware = process.env.SOCRATICODE_BRANCH_AWARE; afterEach(() => { if (originalEnv === undefined) { delete process.env.SOCRATICODE_PROJECT_ID; } else { process.env.SOCRATICODE_PROJECT_ID = originalEnv; } + if (originalBranchAware === undefined) { + delete process.env.SOCRATICODE_BRANCH_AWARE; + } else { + process.env.SOCRATICODE_BRANCH_AWARE = originalBranchAware; + } }); describe("projectIdFromPath", () => { @@ -277,4 +283,99 @@ describe("config", () => { expect(collections[0].name).not.toBe(collections[1].name); }); }); + + // ── Branch awareness ──────────────────────────────────────────────── + + describe("sanitizeBranchName", () => { + it("passes through simple branch names", () => { + expect(sanitizeBranchName("main")).toBe("main"); + expect(sanitizeBranchName("develop")).toBe("develop"); + }); + + it("replaces slashes with underscores", () => { + expect(sanitizeBranchName("feat/my-feature")).toBe("feat_my-feature"); + }); + + it("handles deeply nested branch names", () => { + expect(sanitizeBranchName("feature/JIRA-123/some-work")).toBe( + "feature_JIRA-123_some-work", + ); + }); + + it("collapses consecutive underscores", () => { + expect(sanitizeBranchName("feat//double")).toBe("feat_double"); + }); + + it("strips leading and trailing underscores", () => { + expect(sanitizeBranchName("/leading")).toBe("leading"); + expect(sanitizeBranchName("trailing/")).toBe("trailing"); + }); + + it("preserves hyphens", () => { + expect(sanitizeBranchName("my-branch-name")).toBe("my-branch-name"); + }); + + it("replaces special characters", () => { + expect(sanitizeBranchName("feat@v2.0")).toBe("feat_v2_0"); + }); + }); + + describe("detectGitBranch", () => { + it("detects a branch in the current repo", () => { + // This test runs inside the socraticode git repo + const branch = detectGitBranch(process.cwd()); + expect(branch).toBeTruthy(); + expect(typeof branch).toBe("string"); + }); + + it("returns null for non-git directories", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-nogit-")); + try { + expect(detectGitBranch(tmpDir)).toBeNull(); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + }); + + describe("projectIdFromPath with SOCRATICODE_BRANCH_AWARE", () => { + it("does not include branch suffix by default", () => { + const id = projectIdFromPath("/some/project/path"); + expect(id).toMatch(/^[0-9a-f]{12}$/); + expect(id).not.toContain("__"); + }); + + it("appends branch suffix when SOCRATICODE_BRANCH_AWARE=true", () => { + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + // Run from current repo directory so git detection works + const id = projectIdFromPath(process.cwd()); + expect(id).toContain("__"); + // Hash part + __ + branch + const parts = id.split("__"); + expect(parts[0]).toMatch(/^[0-9a-f]{12}$/); + expect(parts[1]).toBeTruthy(); + }); + + it("produces valid Qdrant collection names with branch suffix", () => { + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + const id = projectIdFromPath(process.cwd()); + const coll = collectionName(id); + // Must be valid Qdrant name: [a-zA-Z0-9_-]+ + expect(coll).toMatch(/^[a-zA-Z0-9_-]+$/); + }); + + it("does not append branch when SOCRATICODE_PROJECT_ID is set", () => { + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + process.env.SOCRATICODE_PROJECT_ID = "explicit-id"; + const id = projectIdFromPath(process.cwd()); + expect(id).toBe("explicit-id"); + expect(id).not.toContain("__"); + }); + + it("does not append branch when SOCRATICODE_BRANCH_AWARE is not true", () => { + process.env.SOCRATICODE_BRANCH_AWARE = "false"; + const id = projectIdFromPath(process.cwd()); + expect(id).toMatch(/^[0-9a-f]{12}$/); + }); + }); }); From 76e3ff5f59720402bbbe07819ed69e6c93976f43 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Wed, 8 Apr 2026 14:22:01 +0100 Subject: [PATCH 04/12] docs: add cross-project search and branch-aware indexing documentation - README: new Features entries, full sections with config examples - README: new env vars SOCRATICODE_BRANCH_AWARE, SOCRATICODE_LINKED_PROJECTS - README: updated codebase_search tool description for includeLinked - DEVELOPER.md: updated config.ts description, branch-aware and linked projects sections --- DEVELOPER.md | 10 +++++++- README.md | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/DEVELOPER.md b/DEVELOPER.md index 39376cc..2f71a6d 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -178,7 +178,7 @@ This will automatically: ``` src/ ├── index.ts # MCP server entry point — registers all 21 tools -├── config.ts # Project ID generation (SHA-256), collection naming +├── config.ts # Project ID generation (SHA-256), collection naming, linked projects, branch detection ├── constants.ts # All constants: ports, container names, models, chunk sizes, extensions ├── types.ts # TypeScript interfaces and types │ @@ -270,6 +270,14 @@ Defined in `src/config.ts`: This means the same folder path always maps to the same collection, even across restarts. +#### Branch-aware mode + +When `SOCRATICODE_BRANCH_AWARE=true`, the current git branch is detected via `git rev-parse --abbrev-ref HEAD` and appended to the project ID (e.g. `abc123def456__feat_my-feature`). Branch names are sanitized: non-alphanumeric characters (except `-`) become `_`, consecutive underscores collapse, leading/trailing underscores are stripped. Detached HEAD states fall back to the branchless ID. Ignored when `SOCRATICODE_PROJECT_ID` is set explicitly. + +#### Linked projects + +`loadLinkedProjects()` reads `.socraticode.json` and `SOCRATICODE_LINKED_PROJECTS` env var. `resolveLinkedCollections()` maps linked paths to `{ name, label }` descriptors for `searchMultipleCollections()`. The current project is always first (highest dedup priority). + ### Supported File Extensions (54) | Category | Extensions | diff --git a/README.md b/README.md index f201c14..631da76 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,8 @@ I built SocratiCode because I regularly work on existing, large, and complex cod - **Live file watching** — Optionally watch for file changes and keep the index updated in real time (debounced 2s). Watcher also invalidates the code graph cache. - **Parallel processing** — Files are scanned and chunked in parallel batches (50 at a time) for fast I/O, while embedding generation and upserts are batched separately for optimal throughput. - **Multi-project** — Index multiple projects simultaneously. Each gets its own isolated collection with full project path tracking. +- **Cross-project search** — Search across multiple related projects in a single query. Link projects via `.socraticode.json` or the `SOCRATICODE_LINKED_PROJECTS` env var, then set `includeLinked: true` on `codebase_search`. Results are tagged with project labels and deduplicated via client-side RRF fusion. +- **Branch-aware indexing** — Maintain separate indexes per git branch by setting `SOCRATICODE_BRANCH_AWARE=true`. Each branch gets its own Qdrant collections, so switching branches instantly switches to the correct index. Ideal for CI/CD pipelines and PR review workflows. - **Respects ignore rules** — Honors all `.gitignore` files (root + nested), plus an optional `.socraticodeignore` for additional exclusions. Includes sensible built-in defaults. `.gitignore` processing can be disabled via `RESPECT_GITIGNORE=false`. Dot-directories (e.g. `.agent`) can be included via `INCLUDE_DOT_FILES=true`. - **Custom file extensions** — Projects with non-standard extensions (e.g. `.tpl`, `.blade`) can be included via `EXTRA_EXTENSIONS` env var or `extraExtensions` tool parameter. Works for both indexing and code graph. - **Configurable infrastructure** — All ports, hosts, and API keys are configurable via environment variables. Qdrant API key support for enterprise deployments. @@ -560,6 +562,64 @@ With this config, agents running in `/repo/main`, `/repo/worktree-feat-a`, and ` - Your AI agent reads actual file contents from its own worktree; the shared index is only used for discovery and navigation - When changes merge back to main, the file watcher re-indexes the changed files and the index converges +### Cross-Project Search (linked projects) + +If you work across multiple related repositories or packages, you can search them all in a single query. + +#### Configuration + +Create a `.socraticode.json` file in your project root: + +```json +{ + "linkedProjects": [ + "../shared-lib", + "/absolute/path/to/other-project" + ] +} +``` + +Or set the `SOCRATICODE_LINKED_PROJECTS` environment variable (comma-separated paths): + +```bash +SOCRATICODE_LINKED_PROJECTS="../shared-lib,/absolute/path/to/other-project" +``` + +Both sources are merged and deduplicated. Relative paths are resolved from the project root. Non-existent paths are silently skipped. + +#### Usage + +Pass `includeLinked: true` to `codebase_search`: + +> Search for "authentication middleware" with includeLinked: true + +Results are tagged with `[project-name]` labels showing which project each result came from. The current project always has highest priority for deduplication — if the same file exists in multiple linked projects, the current project's version wins. + +> **Note:** Each linked project must be independently indexed (`codebase_index`) before it can be searched. + +### Branch-Aware Indexing + +By default, all branches of a project share the same index. When you switch branches, changed files are re-indexed by the watcher, and the index reflects the current branch state. + +For workflows where you need **separate, persistent indexes per branch** — such as CI/CD pipelines or comparing code across branches — enable branch-aware mode: + +```bash +SOCRATICODE_BRANCH_AWARE=true +``` + +With this enabled, collection names include the branch name (e.g. `codebase_abc123__main`, `codebase_abc123__feat_my-feature`). Each branch maintains its own independent index, code graph, and context artifacts. + +**When to use:** +- CI/CD pipelines that index each branch/PR separately +- Comparing search results across branches +- Keeping a pristine `main` index unaffected by feature branch changes + +**When NOT to use:** +- Local development with frequent branch switching (default shared index is more efficient) +- Projects tracked via `SOCRATICODE_PROJECT_ID` (explicit IDs bypass branch detection) + +> **How it works:** `projectIdFromPath()` detects the current git branch via `git rev-parse --abbrev-ref HEAD` and appends a sanitized branch suffix (e.g. `feat/my-feature` → `feat_my-feature`) to the hash-based project ID. Detached HEAD states fall back to the branchless ID. + ### Available tools Once connected, 21 tools are available to your AI assistant: @@ -578,7 +638,7 @@ Once connected, 21 tools are available to your AI assistant: | Tool | Description | |------|-------------| -| `codebase_search` | Hybrid semantic + keyword search (dense + BM25, RRF-fused) with optional file path and language filters | +| `codebase_search` | Hybrid semantic + keyword search (dense + BM25, RRF-fused) with optional file path, language filters, and cross-project search (`includeLinked`) | | `codebase_status` | Check index status and chunk count | #### Code Graph @@ -747,6 +807,8 @@ Artifacts are chunked and embedded into Qdrant using the same hybrid dense + BM2 | `SEARCH_DEFAULT_LIMIT` | `10` | Default number of results returned by `codebase_search` (1-50). Each result is a ranked code chunk with file path, line range, and content. Higher values give broader coverage but produce more output. Can still be overridden per-query via the `limit` tool parameter. | | `SEARCH_MIN_SCORE` | `0.10` | Minimum RRF (Reciprocal Rank Fusion) score threshold (0-1). Results below this score are filtered out. Helps remove low-relevance noise from search results. Set to `0` to disable filtering (returns all results up to `limit`). Can be overridden per-query via the `minScore` tool parameter. Works together with `limit`: results are first filtered by score, then capped at `limit`. | | `SOCRATICODE_PROJECT_ID` | *(none)* | Override the auto-generated project ID. When set, all paths resolve to the same Qdrant collections, allowing multiple directories (e.g. git worktrees of the same repo) to share a single index. Must match `[a-zA-Z0-9_-]+`. | +| `SOCRATICODE_BRANCH_AWARE` | `false` | When `true`, append the current git branch name to the project ID, creating separate Qdrant collections per branch. Ignored when `SOCRATICODE_PROJECT_ID` is set. | +| `SOCRATICODE_LINKED_PROJECTS` | *(none)* | Comma-separated list of additional project paths to include in cross-project search. Merged with paths from `.socraticode.json`. Non-existent paths are silently skipped. | | `SOCRATICODE_LOG_LEVEL` | `info` | Log verbosity: `debug`, `info`, `warn`, `error` | | `SOCRATICODE_LOG_FILE` | *(none)* | Absolute path to a log file. When set, all log entries are appended to this file (a session separator is written on each server start). Useful for debugging when the MCP host doesn't surface log notifications. | From 096f59da130b155b435b291be85b212c78ae25fa Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Thu, 9 Apr 2026 16:58:40 +0100 Subject: [PATCH 05/12] fix: update path handling and type imports in indexer and query tools --- src/services/indexer.ts | 2 +- src/tools/query-tools.ts | 3 ++- tests/unit/config.test.ts | 2 +- tests/unit/multi-collection-search.test.ts | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/services/indexer.ts b/src/services/indexer.ts index f27da0b..09ebe72 100644 --- a/src/services/indexer.ts +++ b/src/services/indexer.ts @@ -170,7 +170,7 @@ function migrateAbsolutePathKeys(hashes: Map, resolvedProjectPat // Try to strip the stored project path prefix, or detect the common prefix const prefix = resolvedProjectPath - ? resolvedProjectPath + "/" + ? `${resolvedProjectPath}/` : detectCommonPrefix(hashes); if (!prefix) { diff --git a/src/tools/query-tools.ts b/src/tools/query-tools.ts index 2aec320..52f9f0f 100644 --- a/src/tools/query-tools.ts +++ b/src/tools/query-tools.ts @@ -14,6 +14,7 @@ import { getLockHolderPid, } from "../services/lock.js"; import { ensureOllamaReady } from "../services/ollama.js"; import { getCollectionInfo, getProjectMetadata, searchChunks, searchMultipleCollections } from "../services/qdrant.js"; import { ensureWatcherStarted, isWatchedByAnyProcess, isWatching } from "../services/watcher.js"; +import type { SearchResult } from "../types.js"; /** Format an IndexingProgress into display lines (elapsed, progress, batches, graph). */ function formatProgressLines(progress: IndexingProgress): { @@ -73,7 +74,7 @@ export async function handleQueryTool( const languageFilter = args.languageFilter as string | undefined; const includeLinked = args.includeLinked as boolean | undefined; - let allResults; + let allResults: SearchResult[]; if (includeLinked) { const collections = resolveLinkedCollections(resolvedPath); allResults = await searchMultipleCollections(collections, query, limit, fileFilter, languageFilter); diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index bbecb3a..c26089e 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -1,9 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited -import { afterEach, beforeEach, describe, expect, it } from "vitest"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { collectionName, contextCollectionName, detectGitBranch, graphCollectionName, loadLinkedProjects, projectIdFromPath, resolveLinkedCollections, sanitizeBranchName } from "../../src/config.js"; describe("config", () => { diff --git a/tests/unit/multi-collection-search.test.ts b/tests/unit/multi-collection-search.test.ts index 7b57b77..b94faad 100644 --- a/tests/unit/multi-collection-search.test.ts +++ b/tests/unit/multi-collection-search.test.ts @@ -8,8 +8,8 @@ */ import { describe, expect, it } from "vitest"; -import type { SearchResult } from "../../src/types.js"; import { mergeMultiCollectionResults } from "../../src/services/qdrant.js"; +import type { SearchResult } from "../../src/types.js"; // ── Helpers ───────────────────────────────────────────────────────────── From fc3c2988fa44c4441f2bddd209c4a55d1e4d8a1b Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 16:18:20 +0100 Subject: [PATCH 06/12] fix: linked projects use base hash without branch suffix resolveLinkedCollections() was calling projectIdFromPath() for linked projects, which with SOCRATICODE_BRANCH_AWARE=true appended the linked project's git branch to its ID. Linked projects indexed without branch-aware mode don't have __branch collections, so lookups failed. Extract coreProjectId() helper (hash-only, no branch suffix) and use it for linked projects. Also fix dedup to compare collection names instead of raw IDs to handle the branch suffix mismatch. Adds unit test verifying linked collection names are branch-agnostic. --- src/config.ts | 23 +++++++++++++++++------ tests/unit/config.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/config.ts b/src/config.ts index f816378..38bb083 100644 --- a/src/config.ts +++ b/src/config.ts @@ -61,12 +61,11 @@ export function projectIdFromPath(folderPath: string): string { } return explicit; } - const normalized = path.resolve(folderPath); - let id = createHash("sha256").update(normalized).digest("hex").slice(0, 12); + let id = coreProjectId(folderPath); // Branch-aware mode: append sanitized branch name to isolate per-branch indexes if (process.env.SOCRATICODE_BRANCH_AWARE === "true") { - const branch = detectGitBranch(normalized); + const branch = detectGitBranch(path.resolve(folderPath)); if (branch) { id = `${id}__${sanitizeBranchName(branch)}`; } @@ -75,6 +74,16 @@ export function projectIdFromPath(folderPath: string): string { return id; } +/** + * Core project ID: SHA-256 hash of the resolved path, without branch suffix. + * Used internally by resolveLinkedCollections so linked projects always + * resolve to their base collection regardless of SOCRATICODE_BRANCH_AWARE. + */ +function coreProjectId(folderPath: string): string { + const normalized = path.resolve(folderPath); + return createHash("sha256").update(normalized).digest("hex").slice(0, 12); +} + /** * Derive a Qdrant collection name for a project's code chunks. */ @@ -170,9 +179,11 @@ export function resolveLinkedCollections( const linked = loadLinkedProjects(resolvedRoot); for (const linkedPath of linked) { - const linkedId = projectIdFromPath(linkedPath); - // Skip if same project ID (e.g. worktrees sharing SOCRATICODE_PROJECT_ID) - if (linkedId === currentId) continue; + // Use base hash (no branch suffix) — linked projects are resolved by their + // standard collection name regardless of SOCRATICODE_BRANCH_AWARE. + const linkedId = coreProjectId(linkedPath); + // Skip if same base project (e.g. worktrees sharing SOCRATICODE_PROJECT_ID) + if (collectionName(linkedId) === collections[0].name) continue; collections.push({ name: collectionName(linkedId), label: path.basename(linkedPath), diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index c26089e..4063f82 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -282,6 +282,29 @@ describe("config", () => { // Different collection names expect(collections[0].name).not.toBe(collections[1].name); }); + + it("linked collections use base hash without branch suffix when SOCRATICODE_BRANCH_AWARE is true", () => { + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + fs.writeFileSync( + path.join(projectDir, ".socraticode.json"), + JSON.stringify({ linkedProjects: ["../linked-lib"] }), + ); + + // Get linked collection name with branch-aware on + const withBranch = resolveLinkedCollections(projectDir); + expect(withBranch).toHaveLength(2); + const linkedNameWithBranch = withBranch[1].name; + + // Get linked collection name with branch-aware off + delete process.env.SOCRATICODE_BRANCH_AWARE; + const withoutBranch = resolveLinkedCollections(projectDir); + const linkedNameWithoutBranch = withoutBranch[1].name; + + // Linked project collection name must be identical regardless of SOCRATICODE_BRANCH_AWARE + expect(linkedNameWithBranch).toBe(linkedNameWithoutBranch); + // And must NOT contain a branch suffix (double-underscore) + expect(linkedNameWithBranch).not.toContain("__"); + }); }); // ── Branch awareness ──────────────────────────────────────────────── From bf93e4a992ae39d2030a1452c60b8613e72b4d2e Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 16:43:06 +0100 Subject: [PATCH 07/12] test: add includeLinked and searchMultipleCollections tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - query-tools.test.ts: 6 new tests for includeLinked parameter: - omitted/false → calls searchChunks (not searchMultipleCollections) - true → calls searchMultipleCollections via resolveLinkedCollections - passes collections and args correctly - project label appears in output - no project tag when field absent - multi-collection-search.test.ts: 1 new test for searchMultipleCollections empty-input short-circuit (internal searchChunks calls cannot be mocked from the same module — integration covered by query-tools tests) --- tests/unit/multi-collection-search.test.ts | 23 +++- tests/unit/query-tools.test.ts | 126 +++++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) diff --git a/tests/unit/multi-collection-search.test.ts b/tests/unit/multi-collection-search.test.ts index b94faad..c86cbc2 100644 --- a/tests/unit/multi-collection-search.test.ts +++ b/tests/unit/multi-collection-search.test.ts @@ -7,7 +7,7 @@ * Tests the pure function directly (no mocks needed). */ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { mergeMultiCollectionResults } from "../../src/services/qdrant.js"; import type { SearchResult } from "../../src/types.js"; @@ -222,3 +222,24 @@ describe("mergeMultiCollectionResults", () => { ); }); }); + +// ── searchMultipleCollections tests ───────────────────────────────────── +// searchMultipleCollections calls searchChunks internally (same module), +// so vi.mock cannot intercept those calls. The pure merge logic is +// thoroughly tested above (9 tests). The orchestration layer (includeLinked +// → resolveLinkedCollections → searchMultipleCollections) is tested via +// query-tools.test.ts which mocks at the module boundary. +// Here we only test the empty-input short-circuit which needs no Qdrant. + +vi.mock("../../src/services/logger.js", () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +const { searchMultipleCollections } = await import("../../src/services/qdrant.js"); + +describe("searchMultipleCollections", () => { + it("returns empty array when collections array is empty", async () => { + const results = await searchMultipleCollections([], "test", 10); + expect(results).toEqual([]); + }); +}); diff --git a/tests/unit/query-tools.test.ts b/tests/unit/query-tools.test.ts index 76d2b97..98625b5 100644 --- a/tests/unit/query-tools.test.ts +++ b/tests/unit/query-tools.test.ts @@ -65,18 +65,26 @@ vi.mock("../../src/services/docker.js", () => ({ // ── qdrant.js mock ─────────────────────────────────────────────────────── const mockSearchChunks = vi.fn(async (_collection: string, _query: string, _limit: number) => []); +const mockSearchMultipleCollections = vi.fn(async () => []); vi.mock("../../src/services/qdrant.js", () => ({ searchChunks: (...args: unknown[]) => mockSearchChunks(...(args as [string, string, number])), + searchMultipleCollections: (...args: unknown[]) => mockSearchMultipleCollections(...(args as [])), getCollectionInfo: vi.fn(async () => ({ points_count: 0 })), getProjectMetadata: vi.fn(async () => null), })); // ── config.js mock ─────────────────────────────────────────────────────── +const mockResolveLinkedCollections = vi.fn(() => [ + { name: "codebase_abc123", label: "my-project" }, + { name: "codebase_def456", label: "shared-lib" }, +]); + vi.mock("../../src/config.js", () => ({ collectionName: vi.fn(() => "test-collection"), projectIdFromPath: vi.fn(() => "test-project-id"), + resolveLinkedCollections: (...args: unknown[]) => mockResolveLinkedCollections(...(args as [])), })); // ── indexer.js mock ────────────────────────────────────────────────────── @@ -178,3 +186,121 @@ describe("codebase_search — embedding provider readiness guard", () => { expect(mockGetEmbeddingProvider).toHaveBeenCalledOnce(); }); }); + +// ── includeLinked tests ────────────────────────────────────────────────── + +describe("codebase_search — includeLinked parameter", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Default: ollama provider + mockGetEmbeddingConfig.mockReturnValue({ + embeddingProvider: "ollama", + embeddingModel: "test-model", + }); + }); + + it("calls searchChunks (not searchMultipleCollections) when includeLinked is omitted", async () => { + await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "test query", + }); + + expect(mockSearchChunks).toHaveBeenCalledOnce(); + expect(mockSearchMultipleCollections).not.toHaveBeenCalled(); + expect(mockResolveLinkedCollections).not.toHaveBeenCalled(); + }); + + it("calls searchChunks (not searchMultipleCollections) when includeLinked is false", async () => { + await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "test query", + includeLinked: false, + }); + + expect(mockSearchChunks).toHaveBeenCalledOnce(); + expect(mockSearchMultipleCollections).not.toHaveBeenCalled(); + expect(mockResolveLinkedCollections).not.toHaveBeenCalled(); + }); + + it("calls searchMultipleCollections when includeLinked is true", async () => { + await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "test query", + includeLinked: true, + }); + + expect(mockSearchMultipleCollections).toHaveBeenCalledOnce(); + expect(mockResolveLinkedCollections).toHaveBeenCalledOnce(); + expect(mockSearchChunks).not.toHaveBeenCalled(); + }); + + it("passes collections from resolveLinkedCollections to searchMultipleCollections", async () => { + await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "find me", + includeLinked: true, + limit: 5, + }); + + expect(mockResolveLinkedCollections).toHaveBeenCalledWith( + expect.stringContaining(TEST_PATH), + ); + expect(mockSearchMultipleCollections).toHaveBeenCalledWith( + [ + { name: "codebase_abc123", label: "my-project" }, + { name: "codebase_def456", label: "shared-lib" }, + ], + "find me", + 5, + undefined, // fileFilter + undefined, // languageFilter + ); + }); + + it("includes project label in output when results have project field", async () => { + mockSearchMultipleCollections.mockResolvedValueOnce([ + { + filePath: "/proj/src/index.ts", + relativePath: "src/index.ts", + content: "console.log('hello')", + startLine: 1, + endLine: 5, + language: "typescript", + score: 0.5, + project: "shared-lib", + }, + ]); + + const output = await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "hello", + includeLinked: true, + }); + + expect(output).toContain("[shared-lib]"); + expect(output).toContain("src/index.ts"); + }); + + it("does not include project tag when project field is absent", async () => { + mockSearchChunks.mockResolvedValueOnce([ + { + filePath: "/proj/src/index.ts", + relativePath: "src/index.ts", + content: "console.log('hello')", + startLine: 1, + endLine: 5, + language: "typescript", + score: 0.5, + }, + ]); + + const output = await handleQueryTool("codebase_search", { + projectPath: TEST_PATH, + query: "hello", + }); + + // Should have the file but no project tag brackets + expect(output).toContain("src/index.ts"); + expect(output).not.toMatch(/\[.*-.*\]/); // no [project-name] tag + }); +}); From 24faa1075b77f88e63c785afb42c5bcd9538767d Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 16:46:03 +0100 Subject: [PATCH 08/12] docs: add cross-project and branch-aware highlights to intro and Why SocratiCode --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 631da76..6f0658e 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ > If SocratiCode has been useful to you, please ⭐ **star this repo** — it helps others discover it — and share it with your dev team and fellow developers! -**One thing, done well: deep codebase intelligence — zero setup, no bloat, fully automatic.** SocratiCode gives AI assistants deep semantic understanding of your codebase — hybrid search, polyglot code dependency graphs, and searchable context artifacts (database schemas, API specs, infra configs, architecture docs). Zero configuration — add it to **any MCP host**, or install the **Claude Code plugin** for built-in workflow skills. It manages everything automatically. +**One thing, done well: deep codebase intelligence — zero setup, no bloat, fully automatic.** SocratiCode gives AI assistants deep semantic understanding of your codebase — hybrid search, cross-project search, polyglot code dependency graphs, and searchable context artifacts (database schemas, API specs, infra configs, architecture docs). Zero configuration — add it to **any MCP host**, or install the **Claude Code plugin** for built-in workflow skills. It manages everything automatically. **Production-ready**, battle-tested on **enterprise-level** large repositories (up to and over **~40 million lines of code**). **Batched**, automatic **resumable** indexing checkpoints progress — pauses, crashes, restarts, and interruptions don't lose work. The file watcher keeps the **index automatically updated** at every file change and across sessions. **Multi-agent ready** — multiple AI agents can work on the same codebase simultaneously, sharing a single index with automatic coordination and zero configuration. @@ -161,6 +161,7 @@ I built SocratiCode because I regularly work on existing, large, and complex cod - **Flexible Embedding Providers** — Switch between Local Ollama (private), Docker Ollama (zero-config), OpenAI (fastest), or Google Gemini (free tier) with a single environment variable. No provider-specific configuration files. - **Enterprise-Ready Simplicity** — No agent coordination tuning, no memory limit environment variables, no coordinator/conductor capacity knobs, no backpressure configuration. SocratiCode scales by relying on production-grade infrastructure (Qdrant, proven embedding APIs) rather than complex in-process orchestration. - **Multi-Agent Ready** — Multiple AI agents share a single index with zero configuration. Cross-process locking coordinates indexing and watching automatically — one agent indexes, all agents search, one watcher keeps everyone current. Crashed agents don't block others; stale locks are reclaimed automatically. +- **Cross-Project & Branch-Aware** — Search across multiple related repositories in a single query via linked projects. Maintain separate indexes per git branch for CI/CD pipelines and PR review workflows. Results from linked projects are tagged with source labels and deduplicated automatically. - **Measurably better than grep** — On VS Code's 2.45M‑line codebase, SocratiCode answers architectural questions with **61% less data**, **84% fewer steps**, and **37× faster** response than a grep‑based AI agent. [Full benchmark →](#real-world-benchmark-vs-code-245m-lines-of-code-with-claude-opus-46) ## Features From ffa8e95bdf00f2a245bbd181dec0ea5fbbec6804 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 17:11:39 +0100 Subject: [PATCH 09/12] fix: use self-contained temp git repos in branch-aware tests CI checks out in detached HEAD state, causing detectGitBranch(process.cwd()) to return null. Replace process.cwd() with temporary git repos that have a known branch and initial commit, making tests deterministic everywhere. --- tests/unit/config.test.ts | 54 ++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index 4063f82..c2c3981 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited +import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -344,11 +345,16 @@ describe("config", () => { }); describe("detectGitBranch", () => { - it("detects a branch in the current repo", () => { - // This test runs inside the socraticode git repo - const branch = detectGitBranch(process.cwd()); - expect(branch).toBeTruthy(); - expect(typeof branch).toBe("string"); + it("detects a branch in a git repo", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-git-")); + try { + execFileSync("git", ["init", "-b", "test-branch", tmpDir]); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + const branch = detectGitBranch(tmpDir); + expect(branch).toBe("test-branch"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); it("returns null for non-git directories", () => { @@ -369,22 +375,34 @@ describe("config", () => { }); it("appends branch suffix when SOCRATICODE_BRANCH_AWARE=true", () => { - process.env.SOCRATICODE_BRANCH_AWARE = "true"; - // Run from current repo directory so git detection works - const id = projectIdFromPath(process.cwd()); - expect(id).toContain("__"); - // Hash part + __ + branch - const parts = id.split("__"); - expect(parts[0]).toMatch(/^[0-9a-f]{12}$/); - expect(parts[1]).toBeTruthy(); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); + try { + execFileSync("git", ["init", "-b", "my-feature", tmpDir]); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + const id = projectIdFromPath(tmpDir); + expect(id).toContain("__"); + const parts = id.split("__"); + expect(parts[0]).toMatch(/^[0-9a-f]{12}$/); + expect(parts[1]).toBe("my-feature"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); it("produces valid Qdrant collection names with branch suffix", () => { - process.env.SOCRATICODE_BRANCH_AWARE = "true"; - const id = projectIdFromPath(process.cwd()); - const coll = collectionName(id); - // Must be valid Qdrant name: [a-zA-Z0-9_-]+ - expect(coll).toMatch(/^[a-zA-Z0-9_-]+$/); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); + try { + execFileSync("git", ["init", "-b", "feat/some-branch", tmpDir]); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + process.env.SOCRATICODE_BRANCH_AWARE = "true"; + const id = projectIdFromPath(tmpDir); + const coll = collectionName(id); + // Must be valid Qdrant name: [a-zA-Z0-9_-]+ + expect(coll).toMatch(/^[a-zA-Z0-9_-]+$/); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); it("does not append branch when SOCRATICODE_PROJECT_ID is set", () => { From ad2e3b9ea16f24a39c7f0122c2388eaa4ca442a9 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 17:15:29 +0100 Subject: [PATCH 10/12] fix: provide git identity for temp repo commits in CI CI runners have no git user.name/email configured, causing 'git commit --allow-empty' to fail with 'Author identity unknown'. Pass GIT_AUTHOR_NAME/EMAIL and GIT_COMMITTER_NAME/EMAIL env vars. --- tests/unit/config.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index c2c3981..53308d0 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -344,12 +344,14 @@ describe("config", () => { }); }); + const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "test", GIT_AUTHOR_EMAIL: "test@test.com", GIT_COMMITTER_NAME: "test", GIT_COMMITTER_EMAIL: "test@test.com" }; + describe("detectGitBranch", () => { it("detects a branch in a git repo", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-git-")); try { execFileSync("git", ["init", "-b", "test-branch", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); const branch = detectGitBranch(tmpDir); expect(branch).toBe("test-branch"); } finally { @@ -378,7 +380,7 @@ describe("config", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); try { execFileSync("git", ["init", "-b", "my-feature", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); process.env.SOCRATICODE_BRANCH_AWARE = "true"; const id = projectIdFromPath(tmpDir); expect(id).toContain("__"); @@ -394,7 +396,7 @@ describe("config", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); try { execFileSync("git", ["init", "-b", "feat/some-branch", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); process.env.SOCRATICODE_BRANCH_AWARE = "true"; const id = projectIdFromPath(tmpDir); const coll = collectionName(id); From f09f417c6ec5446482b3fd7dc069b31435e7b81d Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 17:25:46 +0100 Subject: [PATCH 11/12] fix: address CodeRabbit review feedback on tests - Refactor git temp repos into initTempRepo() helper using git config instead of env vars (resolves Critical finding) - Restore SOCRATICODE_LINKED_PROJECTS and SOCRATICODE_PROJECT_ID to original values in resolveLinkedCollections afterEach - Fix TypeScript 'never' type errors in query-tools mocks by adding explicit SearchResult[] return types --- tests/unit/config.test.ts | 30 ++++++++++++++++++++++-------- tests/unit/query-tools.test.ts | 6 ++++-- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index 53308d0..902da6b 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -247,6 +247,8 @@ describe("config", () => { let tmpDir: string; let projectDir: string; let linkedDir: string; + const savedLinkedEnv = process.env.SOCRATICODE_LINKED_PROJECTS; + const savedProjectIdEnv = process.env.SOCRATICODE_PROJECT_ID; beforeEach(() => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-test-")); @@ -260,7 +262,16 @@ describe("config", () => { afterEach(() => { fs.rmSync(tmpDir, { recursive: true, force: true }); - delete process.env.SOCRATICODE_LINKED_PROJECTS; + if (savedLinkedEnv === undefined) { + delete process.env.SOCRATICODE_LINKED_PROJECTS; + } else { + process.env.SOCRATICODE_LINKED_PROJECTS = savedLinkedEnv; + } + if (savedProjectIdEnv === undefined) { + delete process.env.SOCRATICODE_PROJECT_ID; + } else { + process.env.SOCRATICODE_PROJECT_ID = savedProjectIdEnv; + } }); it("returns only current project when no links configured", () => { @@ -344,14 +355,19 @@ describe("config", () => { }); }); - const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "test", GIT_AUTHOR_EMAIL: "test@test.com", GIT_COMMITTER_NAME: "test", GIT_COMMITTER_EMAIL: "test@test.com" }; + /** Create a temporary git repo with a named branch and initial commit. */ + function initTempRepo(tmpDir: string, branch: string): void { + execFileSync("git", ["init", "-b", branch, tmpDir]); + execFileSync("git", ["config", "user.name", "test"], { cwd: tmpDir }); + execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: tmpDir }); + execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir }); + } describe("detectGitBranch", () => { it("detects a branch in a git repo", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-git-")); try { - execFileSync("git", ["init", "-b", "test-branch", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); + initTempRepo(tmpDir, "test-branch"); const branch = detectGitBranch(tmpDir); expect(branch).toBe("test-branch"); } finally { @@ -379,8 +395,7 @@ describe("config", () => { it("appends branch suffix when SOCRATICODE_BRANCH_AWARE=true", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); try { - execFileSync("git", ["init", "-b", "my-feature", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); + initTempRepo(tmpDir, "my-feature"); process.env.SOCRATICODE_BRANCH_AWARE = "true"; const id = projectIdFromPath(tmpDir); expect(id).toContain("__"); @@ -395,8 +410,7 @@ describe("config", () => { it("produces valid Qdrant collection names with branch suffix", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-")); try { - execFileSync("git", ["init", "-b", "feat/some-branch", tmpDir]); - execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: tmpDir, env: gitEnv }); + initTempRepo(tmpDir, "feat/some-branch"); process.env.SOCRATICODE_BRANCH_AWARE = "true"; const id = projectIdFromPath(tmpDir); const coll = collectionName(id); diff --git a/tests/unit/query-tools.test.ts b/tests/unit/query-tools.test.ts index 98625b5..9d033b7 100644 --- a/tests/unit/query-tools.test.ts +++ b/tests/unit/query-tools.test.ts @@ -64,8 +64,10 @@ vi.mock("../../src/services/docker.js", () => ({ // ── qdrant.js mock ─────────────────────────────────────────────────────── -const mockSearchChunks = vi.fn(async (_collection: string, _query: string, _limit: number) => []); -const mockSearchMultipleCollections = vi.fn(async () => []); +import type { SearchResult } from "../../src/types.js"; + +const mockSearchChunks = vi.fn(async (_collection: string, _query: string, _limit: number): Promise => []); +const mockSearchMultipleCollections = vi.fn(async (): Promise => []); vi.mock("../../src/services/qdrant.js", () => ({ searchChunks: (...args: unknown[]) => mockSearchChunks(...(args as [string, string, number])), From f745d59ddd5baa722c49f2183bc2b922b630711d Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Sat, 11 Apr 2026 17:34:21 +0100 Subject: [PATCH 12/12] fix: address remaining CodeRabbit production code issues - Scope dedupe key to label::relativePath in mergeMultiCollectionResults so same file in different projects is not collapsed - Compute embedding once in searchMultipleCollections via internal searchChunksWithVector helper (avoids N redundant API calls) - Compare base project hashes (not branch-suffixed names) when skipping duplicate linked projects in resolveLinkedCollections - Use path.resolve() for platform-neutral assertion in query-tools tests - Update multi-collection-search tests for new cross-project dedup semantics --- src/config.ts | 10 +++-- src/services/qdrant.ts | 26 +++++++++-- tests/unit/config.test.ts | 6 +++ tests/unit/multi-collection-search.test.ts | 50 ++++++++++++++++------ tests/unit/query-tools.test.ts | 3 +- 5 files changed, 75 insertions(+), 20 deletions(-) diff --git a/src/config.ts b/src/config.ts index 38bb083..096eb22 100644 --- a/src/config.ts +++ b/src/config.ts @@ -67,7 +67,10 @@ export function projectIdFromPath(folderPath: string): string { if (process.env.SOCRATICODE_BRANCH_AWARE === "true") { const branch = detectGitBranch(path.resolve(folderPath)); if (branch) { - id = `${id}__${sanitizeBranchName(branch)}`; + const sanitized = sanitizeBranchName(branch); + if (sanitized) { + id = `${id}__${sanitized}`; + } } } @@ -173,6 +176,7 @@ export function resolveLinkedCollections( ): Array<{ name: string; label: string }> { const resolvedRoot = path.resolve(projectPath); const currentId = projectIdFromPath(resolvedRoot); + const currentCoreId = coreProjectId(resolvedRoot); const collections: Array<{ name: string; label: string }> = [ { name: collectionName(currentId), label: path.basename(resolvedRoot) }, ]; @@ -182,8 +186,8 @@ export function resolveLinkedCollections( // Use base hash (no branch suffix) — linked projects are resolved by their // standard collection name regardless of SOCRATICODE_BRANCH_AWARE. const linkedId = coreProjectId(linkedPath); - // Skip if same base project (e.g. worktrees sharing SOCRATICODE_PROJECT_ID) - if (collectionName(linkedId) === collections[0].name) continue; + // Skip if same base project (e.g. worktrees sharing the same path hash) + if (linkedId === currentCoreId) continue; collections.push({ name: collectionName(linkedId), label: path.basename(linkedPath), diff --git a/src/services/qdrant.ts b/src/services/qdrant.ts index d9b4e92..585149d 100644 --- a/src/services/qdrant.ts +++ b/src/services/qdrant.ts @@ -309,8 +309,21 @@ export async function searchChunks( fileFilter?: string, languageFilter?: string, ): Promise { - const qdrant = getClient(); const queryVector = await generateQueryEmbedding(query); + return searchChunksWithVector(collectionName, query, queryVector, limit, fileFilter, languageFilter); +} + +/** Internal: hybrid search using a pre-computed dense embedding vector. + * Avoids recomputing the same embedding when querying multiple collections. */ +async function searchChunksWithVector( + collectionName: string, + query: string, + queryVector: number[], + limit: number, + fileFilter?: string, + languageFilter?: string, +): Promise { + const qdrant = getClient(); const filter: { must: Array<{ key: string; match: { value: string } }> } = { must: [] }; if (fileFilter) { @@ -355,7 +368,9 @@ export async function searchChunks( } /** Merge results from multiple collection queries using client-side Reciprocal Rank Fusion. - * Deduplicates by relativePath — first (higher-priority) collection wins on conflict. + * Deduplicates by `label::relativePath` so that files with the same relative path + * in different projects are kept as separate hits. Within a single project, + * the first (higher-priority) occurrence wins on conflict. * Exported for unit testing. */ export function mergeMultiCollectionResults( collectionResults: Array<{ label: string; results: SearchResult[] }>, @@ -367,7 +382,7 @@ export function mergeMultiCollectionResults( for (const { label, results } of collectionResults) { for (let rank = 0; rank < results.length; rank++) { const r = results[rank]; - const key = r.relativePath; + const key = `${label}::${r.relativePath}`; const rrfContribution = 1 / (RRF_K + rank + 1); const existing = scored.get(key); @@ -414,6 +429,9 @@ export async function searchMultipleCollections( return results.map((r) => ({ ...r, project: collections[0].label })); } + // Compute the dense embedding once for all collections + const queryVector = await generateQueryEmbedding(query); + // Query all collections in parallel, requesting extra candidates for RRF re-ranking const perCollectionLimit = Math.max(limit * 2, 20); const collectionResults: Array<{ label: string; results: SearchResult[] }> = []; @@ -421,7 +439,7 @@ export async function searchMultipleCollections( const allResults = await Promise.all( collections.map(async ({ name, label }) => { try { - const results = await searchChunks(name, query, perCollectionLimit, fileFilter, languageFilter); + const results = await searchChunksWithVector(name, query, queryVector, perCollectionLimit, fileFilter, languageFilter); return { label, results }; } catch (err) { logger.warn("searchMultipleCollections: collection query failed, skipping", { diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index 902da6b..4407de1 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -353,6 +353,12 @@ describe("config", () => { it("replaces special characters", () => { expect(sanitizeBranchName("feat@v2.0")).toBe("feat_v2_0"); }); + + it("returns empty string when all characters are invalid", () => { + expect(sanitizeBranchName("///")).toBe(""); + expect(sanitizeBranchName("@@@")).toBe(""); + expect(sanitizeBranchName("...")).toBe(""); + }); }); /** Create a temporary git repo with a named branch and initial commit. */ diff --git a/tests/unit/multi-collection-search.test.ts b/tests/unit/multi-collection-search.test.ts index c86cbc2..24e19ea 100644 --- a/tests/unit/multi-collection-search.test.ts +++ b/tests/unit/multi-collection-search.test.ts @@ -88,7 +88,7 @@ describe("mergeMultiCollectionResults", () => { expect(results.find((r) => r.relativePath === "src/file3.ts")?.project).toBe("project-b"); }); - it("deduplicates by relativePath — first (higher-priority) collection wins", () => { + it("keeps same relativePath from different projects as separate entries", () => { const results = mergeMultiCollectionResults( [ { @@ -103,13 +103,35 @@ describe("mergeMultiCollectionResults", () => { 10, ); + // Dedupe key is label::relativePath, so same file in different projects stays separate const sharedResults = results.filter((r) => r.relativePath === "src/shared.ts"); - expect(sharedResults).toHaveLength(1); - expect(sharedResults[0].content).toBe("content from A"); - expect(sharedResults[0].project).toBe("project-a"); + expect(sharedResults).toHaveLength(2); + expect(sharedResults.map((r) => r.project)).toEqual( + expect.arrayContaining(["project-a", "project-b"]), + ); }); - it("RRF scores accumulate for files appearing in multiple collections", () => { + it("deduplicates same relativePath within the same project", () => { + const results = mergeMultiCollectionResults( + [ + { + label: "project-a", + results: [ + makeResult("src/shared.ts", 0.90, { content: "first chunk" }), + makeResult("src/shared.ts", 0.80, { content: "second chunk" }), + ], + }, + ], + 10, + ); + + // Same label + same relativePath → deduplicated, first (higher-ranked) wins + const sharedResults = results.filter((r) => r.relativePath === "src/shared.ts"); + expect(sharedResults).toHaveLength(1); + expect(sharedResults[0].content).toBe("first chunk"); + }); + + it("same relativePath from different projects has independent RRF scores", () => { const results = mergeMultiCollectionResults( [ { @@ -130,13 +152,17 @@ describe("mergeMultiCollectionResults", () => { 10, ); - // popular.ts should rank first due to accumulated RRF score from both collections - expect(results[0].relativePath).toBe("src/popular.ts"); - // Its score should be higher than single-collection results - expect(results[0].score).toBeGreaterThan(results[1].score); - // The accumulated score = 1/(60+1) + 1/(60+1) = 2 * 1/61 ≈ 0.0328 - const expectedAccumulated = 2 * (1 / 61); - expect(results[0].score).toBeCloseTo(expectedAccumulated, 6); + // With label-scoped keys, src/popular.ts from A and B are separate entries + const popularResults = results.filter((r) => r.relativePath === "src/popular.ts"); + expect(popularResults).toHaveLength(2); + + // Each has a single-collection RRF score: 1/(60+rank) + // project-a's popular.ts is rank 1 → 1/61 + // project-b's popular.ts is rank 1 → 1/61 + const expectedSingle = 1 / 61; + for (const r of popularResults) { + expect(r.score).toBeCloseTo(expectedSingle, 6); + } }); it("respects the limit parameter", () => { diff --git a/tests/unit/query-tools.test.ts b/tests/unit/query-tools.test.ts index 9d033b7..51dc80d 100644 --- a/tests/unit/query-tools.test.ts +++ b/tests/unit/query-tools.test.ts @@ -7,6 +7,7 @@ * provider, and uses getEmbeddingProvider() for OpenAI/Google. */ +import path from "node:path"; import { beforeEach, describe, expect, it, vi } from "vitest"; // ── Mocks ──────────────────────────────────────────────────────────────── @@ -245,7 +246,7 @@ describe("codebase_search — includeLinked parameter", () => { }); expect(mockResolveLinkedCollections).toHaveBeenCalledWith( - expect.stringContaining(TEST_PATH), + expect.stringContaining(path.resolve(TEST_PATH)), ); expect(mockSearchMultipleCollections).toHaveBeenCalledWith( [