Merge pull request #23 from giancarloerra:feat/multi-collection-search

feat: cross-project search and branch-aware indexing
This commit is contained in:
Giancarlo Erra
2026-04-12 19:15:08 +01:00
committed by GitHub
11 changed files with 1057 additions and 13 deletions
+9 -1
View File
@@ -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 |
+65 -2
View File
@@ -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
@@ -177,6 +178,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 +563,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 +639,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 +808,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. |
+150
View File
@@ -1,8 +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.
@@ -11,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();
@@ -22,6 +61,28 @@ export function projectIdFromPath(folderPath: string): string {
}
return explicit;
}
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(path.resolve(folderPath));
if (branch) {
const sanitized = sanitizeBranchName(branch);
if (sanitized) {
id = `${id}__${sanitized}`;
}
}
}
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);
}
@@ -46,3 +107,92 @@ 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<string>();
// 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 currentCoreId = coreProjectId(resolvedRoot);
const collections: Array<{ name: string; label: string }> = [
{ name: collectionName(currentId), label: path.basename(resolvedRoot) },
];
const linked = loadLinkedProjects(resolvedRoot);
for (const linkedPath of linked) {
// 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 the same path hash)
if (linkedId === currentCoreId) continue;
collections.push({
name: collectionName(linkedId),
label: path.basename(linkedPath),
});
}
return collections;
}
+4
View File
@@ -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) }],
+1 -1
View File
@@ -170,7 +170,7 @@ function migrateAbsolutePathKeys(hashes: Map<string, string>, resolvedProjectPat
// Try to strip the stored project path prefix, or detect the common prefix
const prefix = resolvedProjectPath
? resolvedProjectPath + "/"
? `${resolvedProjectPath}/`
: detectCommonPrefix(hashes);
if (!prefix) {
+103 -1
View File
@@ -309,8 +309,21 @@ export async function searchChunks(
fileFilter?: string,
languageFilter?: string,
): Promise<SearchResult[]> {
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<SearchResult[]> {
const qdrant = getClient();
const filter: { must: Array<{ key: string; match: { value: string } }> } = { must: [] };
if (fileFilter) {
@@ -354,6 +367,95 @@ export async function searchChunks(
}));
}
/** Merge results from multiple collection queries using client-side Reciprocal Rank Fusion.
* 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[] }>,
limit: number,
): SearchResult[] {
const RRF_K = 60;
const scored = new Map<string, SearchResult & { rrfScore: number }>();
for (const { label, results } of collectionResults) {
for (let rank = 0; rank < results.length; rank++) {
const r = results[rank];
const key = `${label}::${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<SearchResult[]> {
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 }));
}
// 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[] }> = [];
const allResults = await Promise.all(
collections.map(async ({ name, label }) => {
try {
const results = await searchChunksWithVector(name, query, queryVector, 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(
+13 -4
View File
@@ -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,8 +12,9 @@ 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";
import type { SearchResult } from "../types.js";
/** Format an IndexingProgress into display lines (elapsed, progress, batches, graph). */
function formatProgressLines(progress: IndexingProgress): {
@@ -71,8 +72,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: SearchResult[];
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 +118,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("");
}
+2
View File
@@ -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 {
+309 -3
View File
@@ -1,17 +1,27 @@
// 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 { execFileSync } from "node:child_process";
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", () => {
// 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", () => {
@@ -135,4 +145,300 @@ 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;
const savedLinkedEnv = process.env.SOCRATICODE_LINKED_PROJECTS;
const savedProjectIdEnv = process.env.SOCRATICODE_PROJECT_ID;
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 });
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", () => {
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);
});
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 ────────────────────────────────────────────────
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");
});
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. */
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 {
initTempRepo(tmpDir, "test-branch");
const branch = detectGitBranch(tmpDir);
expect(branch).toBe("test-branch");
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
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", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-"));
try {
initTempRepo(tmpDir, "my-feature");
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", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-braware-"));
try {
initTempRepo(tmpDir, "feat/some-branch");
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", () => {
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}$/);
});
});
});
+271
View File
@@ -0,0 +1,271 @@
// 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, vi } from "vitest";
import { mergeMultiCollectionResults } from "../../src/services/qdrant.js";
import type { SearchResult } from "../../src/types.js";
// ── Helpers ─────────────────────────────────────────────────────────────
function makeResult(relativePath: string, score: number, overrides?: Partial<SearchResult>): 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("keeps same relativePath from different projects as separate entries", () => {
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,
);
// 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(2);
expect(sharedResults.map((r) => r.project)).toEqual(
expect.arrayContaining(["project-a", "project-b"]),
);
});
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(
[
{
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,
);
// 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", () => {
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"]),
);
});
});
// ── 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([]);
});
});
+130 -1
View File
@@ -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 ────────────────────────────────────────────────────────────────
@@ -64,19 +65,29 @@ vi.mock("../../src/services/docker.js", () => ({
// ── qdrant.js mock ───────────────────────────────────────────────────────
const mockSearchChunks = vi.fn(async (_collection: string, _query: string, _limit: number) => []);
import type { SearchResult } from "../../src/types.js";
const mockSearchChunks = vi.fn(async (_collection: string, _query: string, _limit: number): Promise<SearchResult[]> => []);
const mockSearchMultipleCollections = vi.fn(async (): Promise<SearchResult[]> => []);
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 +189,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(path.resolve(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
});
});