From 61e868cf9ef484cc83777d302094b10dd48ec5e3 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Wed, 8 Apr 2026 14:17:16 +0100 Subject: [PATCH] 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); + }); + }); });