mirror of
https://github.com/giancarloerra/socraticode.git
synced 2026-07-03 14:05:21 +02:00
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"description": "Codebase intelligence — semantic search workflows, dependency graph analysis, and context artifact exploration for SocratiCode",
|
||||
"author": {
|
||||
"name": "Giancarlo Erra",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"description": "Codebase intelligence: semantic search workflows, dependency graph analysis, and context artifact exploration for SocratiCode",
|
||||
"author": {
|
||||
"name": "Giancarlo Erra",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"description": "Codebase intelligence: semantic search workflows, dependency graph analysis, and context artifact exploration for SocratiCode",
|
||||
"author": {
|
||||
"name": "Giancarlo Erra",
|
||||
|
||||
@@ -4,6 +4,42 @@ All notable changes to SocratiCode are documented here.
|
||||
This project uses [Conventional Commits](https://www.conventionalcommits.org/) and [Semantic Versioning](https://semver.org/).
|
||||
|
||||
|
||||
## [1.8.8](https://github.com/giancarloerra/socraticode/compare/v1.8.7...v1.8.8) (2026-05-06)
|
||||
|
||||
### Features
|
||||
|
||||
* **config:** support projectId in .socraticode.json for team-shared indexes ([#53](https://github.com/giancarloerra/socraticode/issues/53)) ([2c4d55c](https://github.com/giancarloerra/socraticode/commit/2c4d55ca50ae4eb60bb365dbcbff7923db4966e3))
|
||||
|
||||
## [1.8.7](https://github.com/giancarloerra/socraticode/compare/v1.8.6...v1.8.7) (2026-05-06)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **context:** checkpoint artifact metadata after each successful index ([#52](https://github.com/giancarloerra/socraticode/issues/52)) ([2007a18](https://github.com/giancarloerra/socraticode/commit/2007a18865d31cad3be6f5e2e88f834156c5df37))
|
||||
|
||||
## [1.8.6](https://github.com/giancarloerra/socraticode/compare/v1.8.5...v1.8.6) (2026-05-05)
|
||||
|
||||
### Features
|
||||
|
||||
* **qdrant:** add QDRANT_COLLECTION_PREFIX env var for shared instances ([70db002](https://github.com/giancarloerra/socraticode/commit/70db002796a76596badfed86c25d5af6c0331e69))
|
||||
|
||||
## [1.8.5](https://github.com/giancarloerra/socraticode/compare/v1.8.4...v1.8.5) (2026-05-05)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **graph:** allow Go resolution for projects with golang.org/* module paths ([8c26ed8](https://github.com/giancarloerra/socraticode/commit/8c26ed8b49f8aae030d519aca3a0ab84ad07d90d))
|
||||
* **graph:** resolve Go imports via go.mod module path ([c156da1](https://github.com/giancarloerra/socraticode/commit/c156da1688e4e2b8b9c1dfb042094b018131d8f7))
|
||||
* **graph:** resolve Python sibling-flat imports in service-style monorepos ([8921690](https://github.com/giancarloerra/socraticode/commit/8921690d7286ba858337d2df478ef01772d6d055))
|
||||
|
||||
### Documentation
|
||||
|
||||
* add note about MCP governance and JanuScope ([bf36c0c](https://github.com/giancarloerra/socraticode/commit/bf36c0c1b7d3ceb73161afe20628cc994dca404c))
|
||||
|
||||
## [1.8.4](https://github.com/giancarloerra/socraticode/compare/v1.8.3...v1.8.4) (2026-05-04)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **graph:** pre-validate ast-grep grammar libraryPath to survive missing prebuilds ([#44](https://github.com/giancarloerra/socraticode/issues/44)) ([e6ce327](https://github.com/giancarloerra/socraticode/commit/e6ce32710acccd6cb4a241c39a3561803e0e7dbd))
|
||||
|
||||
## [1.8.3](https://github.com/giancarloerra/socraticode/compare/v1.8.2...v1.8.3) (2026-05-04)
|
||||
|
||||
### Features
|
||||
|
||||
+11
-4
@@ -269,17 +269,24 @@ Defined in `src/services/docker.ts`: after starting the container, the server po
|
||||
|
||||
### Project ID & Collection Naming
|
||||
|
||||
Defined in `src/config.ts`:
|
||||
- **Project ID**: First 12 characters of SHA-256 hash of the absolute project path.
|
||||
Defined in `src/config.ts`. `projectIdFromPath()` resolves the project ID with the following precedence (highest first):
|
||||
|
||||
1. **`SOCRATICODE_PROJECT_ID` env var** — per-machine override; bypasses both file lookup and path hashing.
|
||||
2. **`projectId` field in `.socraticode.json`** — committed, team-wide stable identifier; survives different filesystem layouts and OS users.
|
||||
3. **First 12 characters of SHA-256 of the absolute project path** — default fallback.
|
||||
|
||||
In both override paths the value must match `[a-zA-Z0-9_-]+`; whitespace is trimmed; empty/whitespace-only values fall through to the next level. Invalid characters in an explicit override fail loud (throw) — silent fallback would hide misconfigurations that map a project to the wrong (or new) collection.
|
||||
|
||||
Collection names derived from the project ID:
|
||||
- **Code collection**: `codebase_{projectId}`
|
||||
- **Graph collection**: `codegraph_{projectId}`
|
||||
- **Context artifacts collection**: `context_{projectId}`
|
||||
|
||||
This means the same folder path always maps to the same collection, even across restarts.
|
||||
With the default (path-hash) ID, the same folder path always maps to the same collection across restarts. With either override, the mapping is stable across machines and checkouts.
|
||||
|
||||
#### 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.
|
||||
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 or when `projectId` is set in `.socraticode.json` — explicit identifiers are treated as stable and not augmented per branch.
|
||||
|
||||
#### Linked projects
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
Kindly sponsored by <a href="https://altaire.com">Altaire Limited</a>
|
||||
</p>
|
||||
|
||||
> 🛡️ **Need MCP governance together with codebase context?** See our sibling project [**JanuScope**](https://github.com/giancarloerra/januscope) — the local-first MCP policy proxy: tool blocking, SQL-mutation gate, PII redaction, audit, rate-limit.
|
||||
|
||||
> 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!
|
||||
>
|
||||
> 💬 Questions or just want to chat? Join us on [Discord](https://discord.gg/5DrMXfNG).
|
||||
@@ -766,6 +768,20 @@ 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
|
||||
|
||||
### Team-Shared Index (committed `projectId`)
|
||||
|
||||
The env-var approach above works per-machine. For a stable identifier that every teammate (and CI runner) picks up automatically, commit a `projectId` in `.socraticode.json` at the project root:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectId": "my-project"
|
||||
}
|
||||
```
|
||||
|
||||
Now any checkout of the repo — regardless of where it lives on disk or which user account owns it — addresses the same `codebase_my-project`, `codegraph_my-project`, and `context_my-project` Qdrant collections. This is the recommended setup for teams sharing a Qdrant instance: the index is built once and benefits everyone, even across different OS users and laptops with completely different filesystem layouts.
|
||||
|
||||
The value must match `[a-zA-Z0-9_-]+`; whitespace is trimmed, and a missing or empty value falls back to the path-hash default. The `SOCRATICODE_PROJECT_ID` env var, when set, takes precedence over this file — handy for ad-hoc per-machine overrides without touching the repo.
|
||||
|
||||
### Cross-Project Search (linked projects)
|
||||
|
||||
If you work across multiple related repositories or packages, you can search them all in a single query.
|
||||
@@ -1141,6 +1157,7 @@ The rest of this section documents the variables themselves. Pass them using whi
|
||||
| `QDRANT_GRPC_PORT` | `16334` | Qdrant gRPC port (managed mode only) |
|
||||
| `QDRANT_HOST` | `localhost` | Qdrant hostname (alternative to `QDRANT_URL` for non-HTTPS external instances) |
|
||||
| `QDRANT_API_KEY` | *(none)* | Qdrant API key (required for Qdrant Cloud and other authenticated deployments). When set, the URL must be `https://...` so the key is not transmitted over plain HTTP. Loopback URLs (`localhost`, `127.0.0.1`, `[::1]`) are accepted on `http://` for local development. |
|
||||
| `QDRANT_COLLECTION_PREFIX` | *(empty)* | Optional prefix prepended to every Qdrant collection name SocratiCode creates. Useful when sharing one Qdrant instance with other applications (Open-WebUI, custom RAG, etc.) or running multiple SocratiCode instances against one Qdrant for separation between projects, environments, or per-user indexes. Default empty string keeps collection names unchanged from previous releases (fully backwards compatible). Must match `[a-zA-Z0-9_-]+` if set; an invalid prefix throws at startup. Changing the prefix between runs orphans the previous collections; use `codebase_remove` first if you need to migrate. |
|
||||
|
||||
### Indexing Behaviour
|
||||
|
||||
@@ -1152,8 +1169,8 @@ The rest of this section documents the variables themselves. Pass them using whi
|
||||
| `MAX_FILE_SIZE_MB` | `5` | Maximum file size in MB. Files larger than this are skipped during indexing. Increase for repos with large generated or data files you want indexed. |
|
||||
| `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_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_-]+`. Takes precedence over the `projectId` field in `.socraticode.json`. |
|
||||
| `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 or when `projectId` is set in `.socraticode.json`. |
|
||||
| `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. |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "socraticode",
|
||||
"displayName": "SocratiCode",
|
||||
"description": "Codebase context engine for AI assistants. Hybrid search, dependency and call graphs, symbol-level impact analysis (blast radius), interactive graph explorer, and searchable architecture artefacts. Works with Copilot agent mode, Cline, Continue, Roo Code, and any MCP-compatible host.",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"publisher": "giancarloerra",
|
||||
"license": "AGPL-3.0-only",
|
||||
"icon": "images/icon.png",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@ast-grep/lang-bash": "^0.0.7",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "socraticode",
|
||||
"mcpName": "io.github.giancarloerra/socraticode",
|
||||
"version": "1.8.3",
|
||||
"version": "1.8.8",
|
||||
"description": "SocratiCode — MCP server for local codebase indexing, semantic search, and code dependency graphs. All private, all local via Docker.",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
+141
-47
@@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { QDRANT_COLLECTION_PREFIX } from "./constants.js";
|
||||
|
||||
// ── Branch detection ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -38,29 +39,65 @@ export function sanitizeBranchName(branch: string): string {
|
||||
.replace(/^_|_$/g, "");
|
||||
}
|
||||
|
||||
/** Pattern of characters valid in a Qdrant collection name suffix. */
|
||||
const PROJECT_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
/** Validate an explicitly-supplied projectId. Throws on bad characters. */
|
||||
function assertValidProjectId(value: string, source: string): void {
|
||||
if (!PROJECT_ID_PATTERN.test(value)) {
|
||||
throw new Error(`${source} must match [a-zA-Z0-9_-]+ but got: "${value}"`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and validate `projectId` from `.socraticode.json`, if present.
|
||||
*
|
||||
* Returns the trimmed id when the file declares a usable string, `null`
|
||||
* otherwise (file missing, malformed JSON, field absent, wrong type, or
|
||||
* empty after trim). Throws when the field is a string with characters
|
||||
* outside the Qdrant-friendly set — explicit user intent fails loud.
|
||||
*/
|
||||
function readProjectIdFromConfigFile(folderPath: string): string | null {
|
||||
const config = loadSocratiCodeConfig(folderPath);
|
||||
if (!config || typeof config.projectId !== "string") return null;
|
||||
const trimmed = config.projectId.trim();
|
||||
if (!trimmed) return null;
|
||||
assertValidProjectId(trimmed, ".socraticode.json: projectId");
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a stable project ID from an absolute folder path.
|
||||
* Uses a short SHA-256 prefix so collection names stay Qdrant-friendly.
|
||||
*
|
||||
* When `SOCRATICODE_PROJECT_ID` is set, that value is used directly instead
|
||||
* 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_-]`).
|
||||
* Resolution order (highest precedence first):
|
||||
* 1. `SOCRATICODE_PROJECT_ID` env var — per-machine override.
|
||||
* 2. `projectId` in `.socraticode.json` — committed, shared across the
|
||||
* team so every checkout addresses the same Qdrant collection
|
||||
* regardless of where the working tree lives on disk.
|
||||
* 3. SHA-256 prefix of the resolved absolute path — default fallback.
|
||||
*
|
||||
* In both override paths the value must match `[a-zA-Z0-9_-]+`; invalid
|
||||
* characters throw. Whitespace is trimmed; empty/whitespace-only values
|
||||
* fall through to the next level.
|
||||
*
|
||||
* 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.
|
||||
* is set via env var or config file), 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();
|
||||
if (explicit) {
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(explicit)) {
|
||||
throw new Error(
|
||||
`SOCRATICODE_PROJECT_ID must match [a-zA-Z0-9_-]+ but got: "${explicit}"`,
|
||||
);
|
||||
}
|
||||
return explicit;
|
||||
const envExplicit = process.env.SOCRATICODE_PROJECT_ID?.trim();
|
||||
if (envExplicit) {
|
||||
assertValidProjectId(envExplicit, "SOCRATICODE_PROJECT_ID");
|
||||
return envExplicit;
|
||||
}
|
||||
|
||||
const fileExplicit = readProjectIdFromConfigFile(folderPath);
|
||||
if (fileExplicit) {
|
||||
return fileExplicit;
|
||||
}
|
||||
|
||||
let id = coreProjectId(folderPath);
|
||||
|
||||
// Branch-aware mode: append sanitized branch name to isolate per-branch indexes
|
||||
@@ -79,62 +116,115 @@ export function projectIdFromPath(folderPath: string): string {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Used as the default fallback when no explicit project ID is configured.
|
||||
*/
|
||||
function coreProjectId(folderPath: string): string {
|
||||
const normalized = path.resolve(folderPath);
|
||||
return createHash("sha256").update(normalized).digest("hex").slice(0, 12);
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch-suffix-free, env-var-free project ID for a given path.
|
||||
*
|
||||
* Resolution: `projectId` from `.socraticode.json` if present, else the
|
||||
* SHA-256 path hash. Used for linked projects (where `SOCRATICODE_PROJECT_ID`
|
||||
* is process-scoped and ambiguous when applied to a different project) and
|
||||
* for dedup keys in `resolveLinkedCollections` (where we need a stable
|
||||
* identity that doesn't drift across branches).
|
||||
*/
|
||||
function effectiveBaseProjectId(folderPath: string): string {
|
||||
const fileId = readProjectIdFromConfigFile(folderPath);
|
||||
return fileId ?? coreProjectId(folderPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a Qdrant collection name for a project's code chunks.
|
||||
*
|
||||
* The optional `QDRANT_COLLECTION_PREFIX` env var is prepended verbatim to
|
||||
* isolate this SocratiCode instance's collections when sharing a Qdrant
|
||||
* server with other applications or other SocratiCode instances. Empty
|
||||
* prefix (the default) preserves the legacy `codebase_<id>` form exactly.
|
||||
*/
|
||||
export function collectionName(projectId: string): string {
|
||||
return `codebase_${projectId}`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}codebase_${projectId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a Qdrant collection name for a project's code graph.
|
||||
* See {@link collectionName} for the prefix semantics.
|
||||
*/
|
||||
export function graphCollectionName(projectId: string): string {
|
||||
return `codegraph_${projectId}`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}codegraph_${projectId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a Qdrant collection name for a project's context artifacts.
|
||||
* See {@link collectionName} for the prefix semantics.
|
||||
*/
|
||||
export function contextCollectionName(projectId: string): string {
|
||||
return `context_${projectId}`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}context_${projectId}`;
|
||||
}
|
||||
|
||||
// ── Symbol graph collections ─────────────────────────────────────────────
|
||||
|
||||
/** Top-level metadata point for a project's symbol graph. */
|
||||
export function symgraphMetaCollectionName(projectId: string): string {
|
||||
return `${projectId}_symgraph_meta`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_meta`;
|
||||
}
|
||||
|
||||
/** Per-file payloads for a project's symbol graph. */
|
||||
export function symgraphFileCollectionName(projectId: string): string {
|
||||
return `${projectId}_symgraph_file`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_file`;
|
||||
}
|
||||
|
||||
/** Sharded indices (name index + reverse-call file index). */
|
||||
export function symgraphIndexCollectionName(projectId: string): string {
|
||||
return `${projectId}_symgraph_index`;
|
||||
return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_index`;
|
||||
}
|
||||
|
||||
// ── Linked projects ──────────────────────────────────────────────────────
|
||||
|
||||
/** Configuration file name for linked projects */
|
||||
/** Configuration file name shared by all `.socraticode.json` consumers. */
|
||||
const SOCRATICODE_CONFIG_FILE = ".socraticode.json";
|
||||
|
||||
/** Shape of .socraticode.json */
|
||||
/**
|
||||
* Shape of `.socraticode.json`.
|
||||
*
|
||||
* Fields are typed as their intended shape; runtime validators in the
|
||||
* consumers tolerate malformed values (wrong type, null, etc.) so the
|
||||
* MCP server stays resilient against hand-edited config files.
|
||||
*/
|
||||
interface SocratiCodeConfig {
|
||||
/**
|
||||
* Stable project identifier shared across machines/checkouts.
|
||||
* When set, overrides the path-hash default so every team member
|
||||
* addresses the same Qdrant collection regardless of where the
|
||||
* working tree lives on disk. The env var
|
||||
* `SOCRATICODE_PROJECT_ID` takes precedence over this field.
|
||||
*/
|
||||
projectId?: string;
|
||||
/** Paths (absolute or relative to this file) of related projects to search alongside this one. */
|
||||
linkedProjects?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and parse `.socraticode.json` from a project directory.
|
||||
*
|
||||
* Returns the parsed object or `null` when the file is missing,
|
||||
* unreadable, or contains malformed JSON. Per-field validation is the
|
||||
* caller's responsibility — this loader only handles I/O and parsing.
|
||||
*/
|
||||
function loadSocratiCodeConfig(projectPath: string): SocratiCodeConfig | null {
|
||||
const configPath = path.join(path.resolve(projectPath), SOCRATICODE_CONFIG_FILE);
|
||||
try {
|
||||
if (!fs.existsSync(configPath)) return null;
|
||||
const raw = fs.readFileSync(configPath, "utf-8");
|
||||
return JSON.parse(raw) as SocratiCodeConfig;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load linked project paths from `.socraticode.json` and/or the
|
||||
* `SOCRATICODE_LINKED_PROJECTS` env var (comma-separated absolute or relative paths).
|
||||
@@ -146,24 +236,16 @@ export function loadLinkedProjects(projectPath: string): string[] {
|
||||
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);
|
||||
}
|
||||
}
|
||||
const config = loadSocratiCodeConfig(resolvedRoot);
|
||||
if (config && 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)
|
||||
@@ -187,24 +269,36 @@ export function loadLinkedProjects(projectPath: string): string[] {
|
||||
* 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).
|
||||
*
|
||||
* Linked-project IDs are resolved via `effectiveBaseProjectId`, which honors
|
||||
* each linked project's own `.socraticode.json` `projectId` field. This
|
||||
* preserves symmetry — a project addresses the same Qdrant collection whether
|
||||
* it is the current root or a linked dependency from another project.
|
||||
*
|
||||
* Dedup compares against the *current project's full ID* (env override → file
|
||||
* → path-hash, with optional branch suffix). This guarantees the dedup key
|
||||
* matches the actual collection name being added: a linked project is skipped
|
||||
* only when it would resolve to the same collection that the current project
|
||||
* already occupies. Seeding from `effectiveBaseProjectId(resolvedRoot)` would
|
||||
* misalign the seed when `SOCRATICODE_PROJECT_ID` is set, causing linked
|
||||
* projects whose file `projectId` happens to match the current project's file
|
||||
* `projectId` to be silently dropped even though their data lives in a
|
||||
* different collection than the env-overridden current one.
|
||||
*/
|
||||
export function resolveLinkedCollections(
|
||||
projectPath: string,
|
||||
): Array<{ name: string; label: string }> {
|
||||
const resolvedRoot = path.resolve(projectPath);
|
||||
const currentId = projectIdFromPath(resolvedRoot);
|
||||
const currentCoreId = coreProjectId(resolvedRoot);
|
||||
const seen = new Set<string>([currentId]);
|
||||
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;
|
||||
for (const linkedPath of loadLinkedProjects(resolvedRoot)) {
|
||||
const linkedId = effectiveBaseProjectId(linkedPath);
|
||||
if (seen.has(linkedId)) continue;
|
||||
seen.add(linkedId);
|
||||
collections.push({
|
||||
name: collectionName(linkedId),
|
||||
label: path.basename(linkedPath),
|
||||
|
||||
@@ -30,6 +30,32 @@ export const QDRANT_MODE: "managed" | "external" =
|
||||
export const QDRANT_CONTAINER_NAME = "socraticode-qdrant";
|
||||
export const QDRANT_IMAGE = "qdrant/qdrant:v1.17.0";
|
||||
|
||||
/**
|
||||
* Optional prefix prepended to every Qdrant collection name SocratiCode
|
||||
* creates, queries or deletes. Useful when sharing one Qdrant instance with
|
||||
* other applications (Open-WebUI, custom RAG tools, etc.) or when running
|
||||
* multiple SocratiCode instances against one Qdrant for separation between
|
||||
* projects, environments, or per-user indexes.
|
||||
*
|
||||
* Default is the empty string, which keeps every collection name unchanged
|
||||
* from previous releases — fully backwards compatible.
|
||||
*
|
||||
* Validated at module load: Qdrant accepts only `[a-zA-Z0-9_-]` in
|
||||
* collection names, so the prefix must too. An invalid prefix throws
|
||||
* before any Qdrant call is made, with a message naming the offending
|
||||
* value so the misconfiguration is obvious.
|
||||
*/
|
||||
export const QDRANT_COLLECTION_PREFIX = (() => {
|
||||
const raw = process.env.QDRANT_COLLECTION_PREFIX || "";
|
||||
if (raw && !/^[a-zA-Z0-9_-]+$/.test(raw)) {
|
||||
throw new Error(
|
||||
`Invalid QDRANT_COLLECTION_PREFIX: "${raw}". Qdrant collection names ` +
|
||||
"accept only alphanumeric characters, underscore, and hyphen.",
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Resolve the Qdrant REST port from a URL.
|
||||
* Returns the explicit port if present (e.g. `:8443`),
|
||||
|
||||
+68
-11
@@ -13,7 +13,7 @@ import type {
|
||||
} from "../types.js";
|
||||
import { loadPathAliases } from "./graph-aliases.js";
|
||||
import { extractImports } from "./graph-imports.js";
|
||||
import { buildCsNamespaceMap, buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
|
||||
import { buildCsNamespaceMap, buildGoModuleInfo, buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
|
||||
import { computeUnresolvedPct, resolveCallSites } from "./graph-symbol-resolution.js";
|
||||
import { extractSymbolsAndCalls, rawCallsToUnresolvedEdges } from "./graph-symbols.js";
|
||||
import { createIgnoreFilter, shouldIgnore } from "./ignore.js";
|
||||
@@ -445,13 +445,38 @@ export async function getGraphStatus(projectPath: string): Promise<{
|
||||
// ── Register dynamic language grammars ───────────────────────────────────
|
||||
|
||||
let dynamicLangsRegistered = false;
|
||||
const loadedDynamicLanguages = new Set<string>();
|
||||
const failedDynamicLanguages = new Map<string, string>();
|
||||
|
||||
/** Module export shape exposed by `@ast-grep/lang-*` packages. */
|
||||
interface AstGrepLangModule {
|
||||
libraryPath: string;
|
||||
extensions: string[];
|
||||
languageSymbol?: string;
|
||||
}
|
||||
|
||||
/** Snapshot of dynamic-language registration state, for diagnostics. */
|
||||
export interface DynamicLanguageStatus {
|
||||
loaded: string[];
|
||||
failed: Array<{ name: string; error: string }>;
|
||||
}
|
||||
|
||||
/** Returns which dynamic ast-grep grammars registered successfully and which failed. */
|
||||
export function getDynamicLanguageStatus(): DynamicLanguageStatus {
|
||||
return {
|
||||
loaded: [...loadedDynamicLanguages].sort(),
|
||||
failed: [...failedDynamicLanguages.entries()]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, error]) => ({ name, error })),
|
||||
};
|
||||
}
|
||||
|
||||
export function ensureDynamicLanguages(): void {
|
||||
if (dynamicLangsRegistered) return;
|
||||
dynamicLangsRegistered = true;
|
||||
|
||||
try {
|
||||
const langModules: Record<string, { libraryPath: string; extensions: string[]; languageSymbol?: string }> = {};
|
||||
const survivors: Record<string, AstGrepLangModule> = {};
|
||||
|
||||
const langPackages: Array<[string, string]> = [
|
||||
["python", "@ast-grep/lang-python"],
|
||||
@@ -471,21 +496,45 @@ export function ensureDynamicLanguages(): void {
|
||||
|
||||
for (const [name, pkg] of langPackages) {
|
||||
try {
|
||||
langModules[name] = esmRequire(pkg);
|
||||
} catch {
|
||||
// Language grammar not installed — skip silently
|
||||
logger.debug(`ast-grep language not available: ${name}`);
|
||||
const mod = esmRequire(pkg) as AstGrepLangModule;
|
||||
// Pre-validate the lazy `libraryPath` getter. `registerDynamicLanguage`
|
||||
// accesses this property for every entry it receives, and a single
|
||||
// throwing getter aborts the entire batch atomically (issue #43).
|
||||
// Touching the getter here, inside the per-grammar try/catch, isolates
|
||||
// a missing-prebuild failure to that one grammar so the rest can still
|
||||
// be registered. The getter caches its result inside the package, so
|
||||
// this is not duplicated work.
|
||||
void mod.libraryPath;
|
||||
survivors[name] = mod;
|
||||
loadedDynamicLanguages.add(name);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
failedDynamicLanguages.set(name, message);
|
||||
logger.warn("ast-grep grammar failed to load", { name, error: message });
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(langModules).length > 0) {
|
||||
registerDynamicLanguage(langModules);
|
||||
if (Object.keys(survivors).length > 0) {
|
||||
registerDynamicLanguage(survivors);
|
||||
logger.info("Registered dynamic ast-grep languages", {
|
||||
languages: Object.keys(langModules),
|
||||
languages: [...loadedDynamicLanguages].sort(),
|
||||
});
|
||||
} else {
|
||||
logger.warn(
|
||||
"No dynamic ast-grep grammars loaded; PHP, Python, JVM and other dynamic languages will fall through to <module>-only extraction",
|
||||
);
|
||||
}
|
||||
if (failedDynamicLanguages.size > 0) {
|
||||
logger.warn(
|
||||
"Some dynamic ast-grep grammars failed to load; affected languages will produce only <module>-level symbols",
|
||||
{ failed: [...failedDynamicLanguages.keys()].sort() },
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Failed to register dynamic ast-grep languages", { error: String(err) });
|
||||
// Should be unreachable now that each grammar is validated independently,
|
||||
// but keep the outer guard so an unexpected throw cannot take the indexer
|
||||
// process down.
|
||||
logger.warn("Unexpected error in ensureDynamicLanguages", { error: String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,6 +668,14 @@ export async function buildCodeGraph(
|
||||
const hasCs = files.some((f) => path.extname(f).toLowerCase() === ".cs");
|
||||
const csNamespaceMap = hasCs ? buildCsNamespaceMap(fileSet, resolvedPath) : undefined;
|
||||
|
||||
// Build Go module-resolution info from go.mod (issue #45). Without this,
|
||||
// every Go import resolved to null and Go projects produced an empty
|
||||
// file graph. The info is null when go.mod is missing or unparseable;
|
||||
// the resolver treats null as "no Go resolution available" and behaves
|
||||
// exactly as it did before this PR for those cases.
|
||||
const hasGo = files.some((f) => f.endsWith(".go"));
|
||||
const goModuleInfo = hasGo ? buildGoModuleInfo(fileSet, resolvedPath) : undefined;
|
||||
|
||||
for (const relPath of files) {
|
||||
const ext = path.extname(relPath).toLowerCase();
|
||||
const lang = getAstGrepLang(ext);
|
||||
@@ -689,7 +746,7 @@ export async function buildCodeGraph(
|
||||
// Try to resolve to a project file
|
||||
// CSS imports from <style> blocks use CSS resolution even when the source file is Svelte/Vue
|
||||
const resolutionLanguage = imp.isCssImport ? "css" : language;
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap, csNamespaceMap);
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap, csNamespaceMap, goModuleInfo);
|
||||
if (resolved) {
|
||||
node.dependencies.push(resolved);
|
||||
|
||||
|
||||
@@ -374,11 +374,24 @@ export async function indexAllArtifacts(projectPath: string): Promise<{
|
||||
|
||||
const indexed: ArtifactIndexState[] = [];
|
||||
const errors: Array<{ name: string; error: string }> = [];
|
||||
const configNames = new Set(config.artifacts.map((a) => a.name));
|
||||
const stateMap = new Map<string, ArtifactIndexState>();
|
||||
|
||||
const existingStates = await loadContextMetadata(collection);
|
||||
if (existingStates) {
|
||||
for (const state of existingStates) {
|
||||
if (configNames.has(state.name)) {
|
||||
stateMap.set(state.name, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const artifact of config.artifacts) {
|
||||
try {
|
||||
const state = await indexArtifact(resolvedProject, artifact, collection);
|
||||
indexed.push(state);
|
||||
stateMap.set(artifact.name, state);
|
||||
await saveContextMetadata(collection, resolvedProject, [...stateMap.values()]);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to index artifact", { name: artifact.name, error: msg });
|
||||
@@ -386,9 +399,10 @@ export async function indexAllArtifacts(projectPath: string): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
// Save metadata
|
||||
if (indexed.length > 0) {
|
||||
await saveContextMetadata(collection, resolvedProject, indexed);
|
||||
// Save final metadata, even if all artifacts failed, so removed artifacts no
|
||||
// longer linger in status after a config change.
|
||||
if (stateMap.size > 0 || existingStates?.length) {
|
||||
await saveContextMetadata(collection, resolvedProject, [...stateMap.values()]);
|
||||
}
|
||||
|
||||
return { indexed, errors };
|
||||
@@ -425,7 +439,13 @@ export async function ensureArtifactsIndexed(projectPath: string): Promise<{
|
||||
const reindexed: string[] = [];
|
||||
const upToDate: string[] = [];
|
||||
const errors: Array<{ name: string; error: string }> = [];
|
||||
const allStates: ArtifactIndexState[] = [];
|
||||
const configNames = new Set(config.artifacts.map((a) => a.name));
|
||||
|
||||
for (const name of [...stateMap.keys()]) {
|
||||
if (!configNames.has(name)) {
|
||||
stateMap.delete(name);
|
||||
}
|
||||
}
|
||||
|
||||
for (const artifact of config.artifacts) {
|
||||
try {
|
||||
@@ -440,29 +460,26 @@ export async function ensureArtifactsIndexed(projectPath: string): Promise<{
|
||||
if (existing && existing.contentHash === currentHash) {
|
||||
// Up to date
|
||||
upToDate.push(artifact.name);
|
||||
allStates.push(existing);
|
||||
} else {
|
||||
// Stale or new — re-index
|
||||
const state = await indexArtifact(resolvedProject, artifact, collection);
|
||||
reindexed.push(artifact.name);
|
||||
allStates.push(state);
|
||||
stateMap.set(artifact.name, state);
|
||||
await saveContextMetadata(collection, resolvedProject, [...stateMap.values()]);
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to check/index artifact", { name: artifact.name, error: msg });
|
||||
errors.push({ name: artifact.name, error: msg });
|
||||
// Preserve existing state if available
|
||||
const existing = stateMap.get(artifact.name);
|
||||
if (existing) allStates.push(existing);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove artifacts that are no longer in config
|
||||
const configNames = new Set(config.artifacts.map((a) => a.name));
|
||||
for (const [name] of stateMap) {
|
||||
for (const name of existingStates?.map((s) => s.name) ?? []) {
|
||||
if (!configNames.has(name)) {
|
||||
try {
|
||||
await deleteArtifactChunks(collection, name);
|
||||
stateMap.delete(name);
|
||||
logger.info("Removed artifact no longer in config", { name });
|
||||
} catch {
|
||||
// ignore
|
||||
@@ -470,9 +487,9 @@ export async function ensureArtifactsIndexed(projectPath: string): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
// Save updated metadata
|
||||
if (allStates.length > 0) {
|
||||
await saveContextMetadata(collection, resolvedProject, allStates);
|
||||
// Save updated metadata, even when only removals happened.
|
||||
if (stateMap.size > 0 || existingStates?.length) {
|
||||
await saveContextMetadata(collection, resolvedProject, [...stateMap.values()]);
|
||||
}
|
||||
|
||||
return { reindexed, upToDate, errors };
|
||||
|
||||
@@ -11,6 +11,22 @@ export interface ImportInfo {
|
||||
isCssImport?: boolean; // True when extracted from a CSS/style context
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-language dedupe set for import-extraction failures. Without this, a
|
||||
* missing PHP grammar would emit one warn per file (potentially hundreds).
|
||||
* We log the first failure per language at warn level (with the underlying
|
||||
* error attached) and silently skip subsequent failures.
|
||||
*/
|
||||
const importExtractionWarned = new Set<string>();
|
||||
|
||||
/**
|
||||
* Reset the per-language dedupe set. Intended for tests that want to assert
|
||||
* deterministically on extraction warnings.
|
||||
*/
|
||||
export function resetImportExtractionWarnings(): void {
|
||||
importExtractionWarned.clear();
|
||||
}
|
||||
|
||||
/** Extract CSS/SCSS/Stylus @import statements from raw style source text. */
|
||||
function extractCssImports(source: string): ImportInfo[] {
|
||||
const imports: ImportInfo[] = [];
|
||||
@@ -349,7 +365,17 @@ export function extractImports(source: string, lang: Lang | string, _ext: string
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Failed to parse file for imports", { lang: String(lang), error: String(err) });
|
||||
const langKey = String(lang);
|
||||
if (!importExtractionWarned.has(langKey)) {
|
||||
importExtractionWarned.add(langKey);
|
||||
logger.warn(
|
||||
"Failed to parse file for imports; subsequent failures will be suppressed for this language",
|
||||
{
|
||||
lang: langKey,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return imports;
|
||||
|
||||
@@ -118,6 +118,88 @@ export function buildCsNamespaceMap(
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Information needed to resolve Go imports to local files.
|
||||
*
|
||||
* Built once per graph build by parsing the project's `go.mod` and walking
|
||||
* the file set. `modulePath` is the value of the `module` directive in
|
||||
* `go.mod` (e.g. `github.com/user/repo`); imports starting with this
|
||||
* prefix are local to the project. `packageMap` maps a Go package's
|
||||
* directory (relative to the project root, with "." for the root package)
|
||||
* to the lex-smallest non-test `.go` file in that directory, used as a
|
||||
* representative target for file-level edges in the graph.
|
||||
*
|
||||
* Returns null when `go.mod` is missing or malformed (no parseable
|
||||
* `module` directive). Callers must treat null as "no Go resolution
|
||||
* available" and return null for all Go imports.
|
||||
*/
|
||||
export interface GoModuleInfo {
|
||||
modulePath: string;
|
||||
packageMap: Map<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Go module-resolution info for a project.
|
||||
*
|
||||
* Reads `<projectPath>/go.mod` once, parses the module path with a regex,
|
||||
* and constructs a directory-to-representative-file map across all `.go`
|
||||
* files in the file set. `_test.go` files are excluded — Go does not
|
||||
* allow them to be imported from non-test code in other packages. Files
|
||||
* are sorted lexicographically before the map is built so the
|
||||
* representative chosen for each multi-file package is deterministic
|
||||
* across machines and runs.
|
||||
*
|
||||
* Cost: one `readFileSync` plus an O(n) walk over `.go` files at
|
||||
* graph-build time. Lookups during resolution are O(1).
|
||||
*
|
||||
* Limitations (deferred to follow-up issues if reported):
|
||||
* - Parenthesized `module ( ... )` form (rare; not used by any
|
||||
* mainstream Go project).
|
||||
* - `vendor/` directory shadowing of external imports.
|
||||
* - `replace` directives in `go.mod`.
|
||||
* - `go.work` multi-module workspaces.
|
||||
*/
|
||||
export function buildGoModuleInfo(
|
||||
fileSet: Set<string>,
|
||||
projectPath: string,
|
||||
): GoModuleInfo | null {
|
||||
let goModSource: string;
|
||||
try {
|
||||
goModSource = readFileSync(path.join(projectPath, "go.mod"), "utf-8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Match `module <path>` at the start of a line, allowing leading
|
||||
// horizontal whitespace and capturing the path token greedily up to
|
||||
// the next whitespace. Module paths are non-whitespace tokens (e.g.
|
||||
// `github.com/user/repo`, `go.uber.org/zap`).
|
||||
const match = goModSource.match(/^[ \t]*module[ \t]+(\S+)/m);
|
||||
if (!match) return null;
|
||||
const modulePath = match[1];
|
||||
|
||||
const goFiles = [...fileSet]
|
||||
.filter((f) => f.endsWith(".go") && !f.endsWith("_test.go"))
|
||||
.sort();
|
||||
|
||||
const packageMap = new Map<string, string>();
|
||||
for (const f of goFiles) {
|
||||
// Normalize the directory key to forward slashes. Go import paths
|
||||
// always use forward slashes regardless of host OS, so the key must
|
||||
// be in the same form for the lookup in resolveImport to succeed on
|
||||
// Windows (where path.dirname produces backslash separators for
|
||||
// nested directories like `pkg\subpkg`). The map value keeps the
|
||||
// file's native-separator form so it matches fileSet entries used
|
||||
// elsewhere as graph node keys.
|
||||
const dir = path.dirname(f).replace(/\\/g, "/"); // "." for files at the project root
|
||||
if (!packageMap.has(dir)) {
|
||||
packageMap.set(dir, f);
|
||||
}
|
||||
}
|
||||
|
||||
return { modulePath, packageMap };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a module specifier to a relative file path within the project.
|
||||
* Returns null if the module is external (e.g., npm package, stdlib).
|
||||
@@ -131,9 +213,16 @@ export function resolveImport(
|
||||
aliases?: PathAliases,
|
||||
jvmSuffixMap?: Map<string, string>,
|
||||
csNamespaceMap?: Map<string, string[]>,
|
||||
goModuleInfo?: GoModuleInfo | null,
|
||||
): string | null {
|
||||
// Skip obvious external/stdlib modules
|
||||
if (isExternalModule(moduleSpecifier, language)) return null;
|
||||
// Skip obvious external/stdlib modules. Go is excluded from this
|
||||
// pre-check because its external classifier in `isExternalModule`
|
||||
// treats any `golang.org/...` import as external, which would block
|
||||
// valid local imports for projects whose own module path starts with
|
||||
// `golang.org/` (e.g. someone working on `golang.org/x/sync` itself).
|
||||
// The Go case below performs its own module-path-aware classification
|
||||
// and returns null for everything outside the local module.
|
||||
if (language !== "go" && isExternalModule(moduleSpecifier, language)) return null;
|
||||
|
||||
const sourceDir = path.dirname(sourceFile);
|
||||
|
||||
@@ -189,13 +278,48 @@ export function resolveImport(
|
||||
);
|
||||
if (inSrc) return inSrc;
|
||||
}
|
||||
|
||||
// Sibling-flat fallback (issue #46). Common in service-style monorepos
|
||||
// where each top-level directory is a runnable Python application root
|
||||
// and `import config` from `service-a/main.py` means
|
||||
// `service-a/config.py` because the file is run via `python main.py`
|
||||
// from inside its own directory. Tried last to preserve existing
|
||||
// project-root precedence: any layout that already resolved before
|
||||
// this PR continues to resolve to the same file. resolveRelativePath
|
||||
// also handles the `<sourceDir>/<module>/__init__.py` package case
|
||||
// via its built-in Python init fallback.
|
||||
const sibling = resolveRelativePath(modulePath, sourceDir, projectPath, fileSet, [".py"]);
|
||||
if (sibling) return sibling;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
case "go": {
|
||||
// Go imports are package paths; only track if it looks like a local module
|
||||
// (contains the module name or starts with ./)
|
||||
return null; // Go resolution requires go.mod analysis
|
||||
// Local Go imports are rooted at the module path declared in go.mod
|
||||
// (built by buildGoModuleInfo at graph-build time). When the import
|
||||
// starts with that prefix, strip it to get the package's directory
|
||||
// relative to the project root, then look up the representative
|
||||
// file for that directory. Anything else (stdlib like "fmt",
|
||||
// third-party packages like "github.com/x/y", or sibling-module
|
||||
// paths that share a prefix textually but not structurally)
|
||||
// resolves to null.
|
||||
if (!goModuleInfo) return null;
|
||||
if (!moduleSpecifier.startsWith(goModuleInfo.modulePath)) return null;
|
||||
const rest = moduleSpecifier.slice(goModuleInfo.modulePath.length);
|
||||
// rest === "" → the root package (the directory containing go.mod).
|
||||
// rest starts with "/" → a subpackage; strip the leading slash.
|
||||
// Anything else (e.g. an import that happens to share the prefix
|
||||
// but isn't actually a subpackage, like
|
||||
// `github.com/user/repo-other`) is external.
|
||||
let dir: string;
|
||||
if (rest === "") {
|
||||
dir = ".";
|
||||
} else if (rest.startsWith("/")) {
|
||||
dir = rest.slice(1);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return goModuleInfo.packageMap.get(dir) ?? null;
|
||||
}
|
||||
|
||||
case "java":
|
||||
|
||||
@@ -52,6 +52,22 @@ interface ScopeFrame {
|
||||
symbolId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-language dedupe set for symbol-extraction failures. Without this, a
|
||||
* missing PHP grammar would emit one warn per file (potentially hundreds).
|
||||
* We log the first failure per language at warn level (with the underlying
|
||||
* error attached) and silently skip subsequent failures.
|
||||
*/
|
||||
const symbolExtractionWarned = new Set<string>();
|
||||
|
||||
/**
|
||||
* Reset the per-language dedupe set. Intended for tests that want to assert
|
||||
* deterministically on extraction warnings.
|
||||
*/
|
||||
export function resetSymbolExtractionWarnings(): void {
|
||||
symbolExtractionWarned.clear();
|
||||
}
|
||||
|
||||
/** Find the deepest scope frame covering a line. */
|
||||
function findCallerId(scopes: ScopeFrame[], line: number, fallback: string): string {
|
||||
let best: ScopeFrame | null = null;
|
||||
@@ -129,11 +145,17 @@ export function extractSymbolsAndCalls(
|
||||
// Dart, Lua, Svelte, Vue and others fall through to the regex fallback.
|
||||
return extractFromRegex(source, relativePath, language, moduleSymbol);
|
||||
} catch (err) {
|
||||
logger.debug("extractSymbolsAndCalls failed", {
|
||||
file: relativePath,
|
||||
lang: langKey,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
if (!symbolExtractionWarned.has(langKey)) {
|
||||
symbolExtractionWarned.add(langKey);
|
||||
logger.warn(
|
||||
"Symbol extraction failed for language; subsequent failures will be suppressed for this language",
|
||||
{
|
||||
lang: langKey,
|
||||
file: relativePath,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
);
|
||||
}
|
||||
return { symbols: [moduleSymbol], rawCalls: [] };
|
||||
}
|
||||
}
|
||||
|
||||
+22
-5
@@ -2,7 +2,7 @@
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
import { createHash } from "node:crypto";
|
||||
import { QdrantClient } from "@qdrant/js-client-rest";
|
||||
import { QDRANT_API_KEY, QDRANT_HOST, QDRANT_PORT, QDRANT_URL, resolveQdrantPort } from "../constants.js";
|
||||
import { QDRANT_API_KEY, QDRANT_COLLECTION_PREFIX, QDRANT_HOST, QDRANT_PORT, QDRANT_URL, resolveQdrantPort } from "../constants.js";
|
||||
import type { ArtifactIndexState, CodeGraph, FileChunk, SearchResult } from "../types.js";
|
||||
import { getEmbeddingConfig } from "./embedding-config.js";
|
||||
import { generateEmbeddings, generateQueryEmbedding, prepareDocumentText } from "./embeddings.js";
|
||||
@@ -134,13 +134,23 @@ export async function deleteCollection(name: string): Promise<void> {
|
||||
}
|
||||
|
||||
/** List all codebase, codegraph, and context artifact entries.
|
||||
* Codebase and context entries are actual collections; codegraph entries come from metadata. */
|
||||
* Codebase and context entries are actual collections; codegraph entries come from metadata.
|
||||
*
|
||||
* The collection-name filters honour `QDRANT_COLLECTION_PREFIX` so when
|
||||
* sharing a Qdrant server with other applications or other SocratiCode
|
||||
* instances, only this instance's collections are listed. */
|
||||
export async function listCodebaseCollections(): Promise<string[]> {
|
||||
const qdrant = getClient();
|
||||
const collections = await qdrant.getCollections();
|
||||
const p = QDRANT_COLLECTION_PREFIX;
|
||||
const result = collections.collections
|
||||
.map((c) => c.name)
|
||||
.filter((n) => n.startsWith("codebase_") || n.startsWith("codegraph_") || n.startsWith("context_"));
|
||||
.filter(
|
||||
(n) =>
|
||||
n.startsWith(`${p}codebase_`) ||
|
||||
n.startsWith(`${p}codegraph_`) ||
|
||||
n.startsWith(`${p}context_`),
|
||||
);
|
||||
|
||||
// Also check metadata for graph and context entries (stored as metadata points, not real collections)
|
||||
try {
|
||||
@@ -152,7 +162,7 @@ export async function listCodebaseCollections(): Promise<string[]> {
|
||||
for (const point of metaPoints.points) {
|
||||
const collName = point.payload?.collectionName as string | undefined;
|
||||
if (
|
||||
(collName?.startsWith("codegraph_") || collName?.startsWith("context_")) &&
|
||||
(collName?.startsWith(`${p}codegraph_`) || collName?.startsWith(`${p}context_`)) &&
|
||||
!result.includes(collName)
|
||||
) {
|
||||
result.push(collName);
|
||||
@@ -533,7 +543,14 @@ export async function getCollectionInfo(name: string): Promise<{
|
||||
|
||||
// ── Project metadata collection ──────────────────────────────────────────
|
||||
|
||||
const METADATA_COLLECTION = "socraticode_metadata";
|
||||
/**
|
||||
* Global per-instance metadata collection. Stores cross-project state such
|
||||
* as graph metadata pointers and context-artifact metadata. Honours
|
||||
* `QDRANT_COLLECTION_PREFIX` so two SocratiCode instances sharing one
|
||||
* Qdrant server keep their metadata isolated as well as their per-project
|
||||
* code/graph/context collections.
|
||||
*/
|
||||
const METADATA_COLLECTION = `${QDRANT_COLLECTION_PREFIX}socraticode_metadata`;
|
||||
|
||||
/** Cached flag: once the metadata collection is confirmed to exist, skip re-checking */
|
||||
let metadataCollectionReady = false;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import path from "node:path";
|
||||
import { projectIdFromPath } from "../config.js";
|
||||
import { mergeExtraExtensions } from "../constants.js";
|
||||
import { awaitGraphBuild, findCircularDependencies, generateMermaidDiagram, getFileDependencies, getGraphBuildProgress, getGraphStats, getGraphStatus, getLastGraphBuildCompleted, getOrBuildGraph, isGraphBuildInProgress, rebuildGraph, removeGraph } from "../services/code-graph.js";
|
||||
import { awaitGraphBuild, ensureDynamicLanguages, findCircularDependencies, generateMermaidDiagram, getDynamicLanguageStatus, getFileDependencies, getGraphBuildProgress, getGraphStats, getGraphStatus, getLastGraphBuildCompleted, getOrBuildGraph, isGraphBuildInProgress, rebuildGraph, removeGraph } from "../services/code-graph.js";
|
||||
import { detectEntryPoints } from "../services/graph-entrypoints.js";
|
||||
import {
|
||||
type FlowNode,
|
||||
@@ -234,6 +234,30 @@ export async function handleGraphTool(
|
||||
case "codebase_graph_status": {
|
||||
const resolved = path.resolve(projectPath);
|
||||
|
||||
// Trigger grammar registration so the diagnostic block below reflects
|
||||
// the real loader state. Idempotent and cheap after the first call.
|
||||
ensureDynamicLanguages();
|
||||
const grammarStatus = getDynamicLanguageStatus();
|
||||
const renderGrammarBlock = (): string[] => {
|
||||
if (grammarStatus.loaded.length === 0 && grammarStatus.failed.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const block: string[] = ["", "AST grammars:"];
|
||||
if (grammarStatus.loaded.length > 0) {
|
||||
block.push(` Loaded (${grammarStatus.loaded.length}): ${grammarStatus.loaded.join(", ")}`);
|
||||
}
|
||||
if (grammarStatus.failed.length > 0) {
|
||||
block.push(` Failed (${grammarStatus.failed.length}):`);
|
||||
for (const f of grammarStatus.failed) {
|
||||
block.push(` - ${f.name}: ${f.error}`);
|
||||
}
|
||||
block.push(
|
||||
" Symbols and imports for failed languages will be empty until the underlying load error is resolved.",
|
||||
);
|
||||
}
|
||||
return block;
|
||||
};
|
||||
|
||||
// Show in-flight build progress if building
|
||||
if (isGraphBuildInProgress(resolved)) {
|
||||
const progress = getGraphBuildProgress(resolved);
|
||||
@@ -243,17 +267,19 @@ export async function handleGraphTool(
|
||||
? Math.round((progress.filesProcessed / progress.filesTotal) * 100)
|
||||
: 0;
|
||||
|
||||
return [
|
||||
const buildingLines = [
|
||||
`Code Graph Status for: ${resolved}`,
|
||||
"",
|
||||
`Status: BUILDING`,
|
||||
`Phase: ${progress.phase}`,
|
||||
`Progress: ${progress.filesProcessed}/${progress.filesTotal} files (${pct}%)`,
|
||||
`Elapsed: ${elapsed}s`,
|
||||
...renderGrammarBlock(),
|
||||
"",
|
||||
"The graph is being built in the background.",
|
||||
"Call codebase_graph_status again to check progress.",
|
||||
].join("\n");
|
||||
];
|
||||
return buildingLines.join("\n");
|
||||
}
|
||||
|
||||
// Show last completed build info if available
|
||||
@@ -266,6 +292,7 @@ export async function handleGraphTool(
|
||||
lines.push(`Last build failed: ${lastBuild.error}`);
|
||||
}
|
||||
lines.push("Run codebase_graph_build or codebase_index to create one.");
|
||||
lines.push(...renderGrammarBlock());
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
@@ -294,6 +321,8 @@ export async function handleGraphTool(
|
||||
lines.push(` Unresolved: ${sm.unresolvedEdgePct.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
lines.push(...renderGrammarBlock());
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
|
||||
import { QDRANT_HOST, QDRANT_MODE, QDRANT_PORT, QDRANT_URL, SOCRATICODE_VERSION } from "../constants.js";
|
||||
import { QDRANT_COLLECTION_PREFIX, QDRANT_HOST, QDRANT_MODE, QDRANT_PORT, QDRANT_URL, SOCRATICODE_VERSION } from "../constants.js";
|
||||
import { getArtifactStatusSummary } from "../services/context-artifacts.js";
|
||||
import { isDockerAvailable, isQdrantImagePresent, isQdrantRunning } from "../services/docker.js";
|
||||
import { getEmbeddingConfig } from "../services/embedding-config.js";
|
||||
@@ -136,14 +136,20 @@ export async function handleManageTool(
|
||||
return "No projects have been indexed yet. Use codebase_index to index a project.";
|
||||
}
|
||||
|
||||
const codebaseCollections = collections.filter((c) => c.startsWith("codebase_"));
|
||||
const graphCollections = collections.filter((c) => c.startsWith("codegraph_"));
|
||||
// All four references below honour QDRANT_COLLECTION_PREFIX so this
|
||||
// tool keeps working on shared Qdrant deployments where SocratiCode's
|
||||
// collection names carry an instance-specific prefix.
|
||||
const p = QDRANT_COLLECTION_PREFIX;
|
||||
const codebasePrefix = `${p}codebase_`;
|
||||
const graphPrefix = `${p}codegraph_`;
|
||||
const codebaseCollections = collections.filter((c) => c.startsWith(codebasePrefix));
|
||||
const graphCollections = collections.filter((c) => c.startsWith(graphPrefix));
|
||||
|
||||
const lines = ["Indexed projects:\n"];
|
||||
|
||||
for (const c of codebaseCollections) {
|
||||
const projectId = c.replace("codebase_", "");
|
||||
const hasGraph = graphCollections.includes(`codegraph_${projectId}`);
|
||||
const projectId = c.slice(codebasePrefix.length);
|
||||
const hasGraph = graphCollections.includes(`${graphPrefix}${projectId}`);
|
||||
const metadata = await getProjectMetadata(c);
|
||||
const pathInfo = metadata?.projectPath || "(path unknown — indexed before path tracking)";
|
||||
lines.push(` - ${pathInfo}`);
|
||||
@@ -159,7 +165,7 @@ export async function handleManageTool(
|
||||
}
|
||||
}
|
||||
if (hasGraph) {
|
||||
const graphMeta = await getGraphMetadata(`codegraph_${projectId}`);
|
||||
const graphMeta = await getGraphMetadata(`${graphPrefix}${projectId}`);
|
||||
if (graphMeta) {
|
||||
lines.push(` Code graph: ${graphMeta.nodeCount} files, ${graphMeta.edgeCount} edges (built: ${graphMeta.lastBuiltAt})`);
|
||||
} else {
|
||||
|
||||
@@ -317,6 +317,88 @@ describe("config", () => {
|
||||
// And must NOT contain a branch suffix (double-underscore)
|
||||
expect(linkedNameWithBranch).not.toContain("__");
|
||||
});
|
||||
|
||||
it("honors a linked project's committed projectId", () => {
|
||||
// Symmetry guarantee: the same project must resolve to the same
|
||||
// Qdrant collection whether it's the current root or a linked
|
||||
// dependency from another project. Without this, cross-project
|
||||
// search would silently miss the linked project's data when that
|
||||
// project pins its id via .socraticode.json.
|
||||
fs.writeFileSync(
|
||||
path.join(linkedDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "linked-stable" }),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, ".socraticode.json"),
|
||||
JSON.stringify({ linkedProjects: ["../linked-lib"] }),
|
||||
);
|
||||
|
||||
const collections = resolveLinkedCollections(projectDir);
|
||||
expect(collections).toHaveLength(2);
|
||||
expect(collections[1].name).toBe("codebase_linked-stable");
|
||||
});
|
||||
|
||||
it("dedups linked projects that share a committed projectId with the current project", () => {
|
||||
// Two physically distinct paths can declare the same shared
|
||||
// projectId — they point to the same Qdrant collection, so the
|
||||
// current project must not be queried twice (once as "self" and
|
||||
// once as "linked").
|
||||
fs.writeFileSync(
|
||||
path.join(linkedDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "shared-team-id" }),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "shared-team-id", linkedProjects: ["../linked-lib"] }),
|
||||
);
|
||||
|
||||
const collections = resolveLinkedCollections(projectDir);
|
||||
expect(collections).toHaveLength(1);
|
||||
expect(collections[0].name).toBe("codebase_shared-team-id");
|
||||
});
|
||||
|
||||
it("does not wrongly dedup a linked project when env override diverges from file projectId", () => {
|
||||
// Regression for a subtle dedup misalignment: the dedup seed used
|
||||
// the file-only `effectiveBaseProjectId`, while the current
|
||||
// project's collection name comes from the env-aware
|
||||
// `projectIdFromPath`. When `SOCRATICODE_PROJECT_ID` is set on the
|
||||
// current project AND both projects pin the same `projectId` in
|
||||
// their `.socraticode.json`, the two computations disagreed and
|
||||
// the linked project was wrongly skipped — losing its data even
|
||||
// though it lives in a collection genuinely distinct from the
|
||||
// env-overridden current one.
|
||||
process.env.SOCRATICODE_PROJECT_ID = "env-override";
|
||||
fs.writeFileSync(
|
||||
path.join(linkedDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "shared-id" }),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "shared-id", linkedProjects: ["../linked-lib"] }),
|
||||
);
|
||||
|
||||
const collections = resolveLinkedCollections(projectDir);
|
||||
expect(collections).toHaveLength(2);
|
||||
expect(collections[0].name).toBe("codebase_env-override");
|
||||
expect(collections[1].name).toBe("codebase_shared-id");
|
||||
});
|
||||
|
||||
it("does not leak SOCRATICODE_PROJECT_ID env var into linked-project collection names", () => {
|
||||
// The env var is process-scoped and applies only to the current
|
||||
// project. Without this guard, linked projects would all collapse
|
||||
// onto the env-var collection name — wrong and silently lossy.
|
||||
process.env.SOCRATICODE_PROJECT_ID = "current-only";
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, ".socraticode.json"),
|
||||
JSON.stringify({ linkedProjects: ["../linked-lib"] }),
|
||||
);
|
||||
|
||||
const collections = resolveLinkedCollections(projectDir);
|
||||
expect(collections).toHaveLength(2);
|
||||
expect(collections[0].name).toBe("codebase_current-only");
|
||||
expect(collections[1].name).toMatch(/^codebase_[0-9a-f]{12}$/);
|
||||
expect(collections[1].name).not.toBe("codebase_current-only");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Branch awareness ────────────────────────────────────────────────
|
||||
@@ -441,4 +523,127 @@ describe("config", () => {
|
||||
expect(id).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
});
|
||||
|
||||
// ── projectId override via .socraticode.json ────────────────────────
|
||||
//
|
||||
// Allow teams to commit a stable `projectId` in `.socraticode.json` so
|
||||
// every machine that checks out the project addresses the same Qdrant
|
||||
// collection regardless of where the working tree lives on disk.
|
||||
|
||||
describe("projectIdFromPath with .socraticode.json projectId", () => {
|
||||
let tmpDir: string;
|
||||
let projectDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-projid-"));
|
||||
projectDir = path.join(tmpDir, "my-project");
|
||||
fs.mkdirSync(projectDir, { recursive: true });
|
||||
delete process.env.SOCRATICODE_PROJECT_ID;
|
||||
delete process.env.SOCRATICODE_BRANCH_AWARE;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function writeConfig(config: unknown): void {
|
||||
fs.writeFileSync(path.join(projectDir, ".socraticode.json"), JSON.stringify(config));
|
||||
}
|
||||
|
||||
it("uses projectId from .socraticode.json when env var is not set", () => {
|
||||
writeConfig({ projectId: "team-shared-ios" });
|
||||
expect(projectIdFromPath(projectDir)).toBe("team-shared-ios");
|
||||
});
|
||||
|
||||
it("ignores path differences when file projectId is set", () => {
|
||||
// Two different projects on disk both pin to the same id — they should share collections.
|
||||
const otherDir = path.join(tmpDir, "another-project");
|
||||
fs.mkdirSync(otherDir, { recursive: true });
|
||||
writeConfig({ projectId: "shared-id" });
|
||||
fs.writeFileSync(
|
||||
path.join(otherDir, ".socraticode.json"),
|
||||
JSON.stringify({ projectId: "shared-id" }),
|
||||
);
|
||||
expect(projectIdFromPath(projectDir)).toBe(projectIdFromPath(otherDir));
|
||||
});
|
||||
|
||||
it("trims whitespace from file projectId", () => {
|
||||
writeConfig({ projectId: " trimmed-id " });
|
||||
expect(projectIdFromPath(projectDir)).toBe("trimmed-id");
|
||||
});
|
||||
|
||||
it("throws on invalid characters in file projectId", () => {
|
||||
writeConfig({ projectId: "invalid/name" });
|
||||
expect(() => projectIdFromPath(projectDir)).toThrow(
|
||||
/\.socraticode\.json.*projectId.*\[a-zA-Z0-9_-\]/,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to path hash when file projectId is empty string", () => {
|
||||
writeConfig({ projectId: "" });
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("falls back to path hash when file projectId is whitespace only", () => {
|
||||
writeConfig({ projectId: " " });
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("falls back to path hash when file projectId has wrong type", () => {
|
||||
writeConfig({ projectId: 12345 });
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("falls back to path hash when file projectId field is null", () => {
|
||||
writeConfig({ projectId: null });
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("SOCRATICODE_PROJECT_ID env var takes precedence over file projectId", () => {
|
||||
writeConfig({ projectId: "from-file" });
|
||||
process.env.SOCRATICODE_PROJECT_ID = "from-env";
|
||||
expect(projectIdFromPath(projectDir)).toBe("from-env");
|
||||
});
|
||||
|
||||
it("uses file projectId when .socraticode.json is absent → falls back to hash", () => {
|
||||
// No .socraticode.json written — current default behavior unchanged
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("falls back to hash when .socraticode.json is malformed JSON", () => {
|
||||
fs.writeFileSync(path.join(projectDir, ".socraticode.json"), "not valid json{{{");
|
||||
expect(projectIdFromPath(projectDir)).toMatch(/^[0-9a-f]{12}$/);
|
||||
});
|
||||
|
||||
it("does not append branch suffix when file projectId is set", () => {
|
||||
writeConfig({ projectId: "stable-id" });
|
||||
process.env.SOCRATICODE_BRANCH_AWARE = "true";
|
||||
// Initialize tmpDir as a git repo with a non-default branch to prove
|
||||
// that branch-aware mode is suppressed by an explicit projectId.
|
||||
// Disable gpg/ssh signing locally so the test is robust against the
|
||||
// user's global git config (commit.gpgsign=true is common).
|
||||
execFileSync("git", ["init", "-b", "feature-branch", projectDir]);
|
||||
execFileSync("git", ["config", "user.name", "test"], { cwd: projectDir });
|
||||
execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: projectDir });
|
||||
execFileSync("git", ["config", "commit.gpgsign", "false"], { cwd: projectDir });
|
||||
execFileSync("git", ["config", "tag.gpgsign", "false"], { cwd: projectDir });
|
||||
execFileSync("git", ["commit", "--allow-empty", "-m", "init"], { cwd: projectDir });
|
||||
|
||||
const id = projectIdFromPath(projectDir);
|
||||
expect(id).toBe("stable-id");
|
||||
expect(id).not.toContain("__");
|
||||
});
|
||||
|
||||
it("coexists with linkedProjects field in the same file", () => {
|
||||
// Regression guard: adding projectId must not break linkedProjects parsing.
|
||||
const linked = path.join(tmpDir, "linked");
|
||||
fs.mkdirSync(linked, { recursive: true });
|
||||
writeConfig({ projectId: "shared-id", linkedProjects: ["../linked"] });
|
||||
expect(projectIdFromPath(projectDir)).toBe("shared-id");
|
||||
// loadLinkedProjects is still happy — round-trip via resolveLinkedCollections
|
||||
const collections = resolveLinkedCollections(projectDir);
|
||||
expect(collections).toHaveLength(2);
|
||||
expect(collections[0].name).toBe("codebase_shared-id");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
|
||||
import fsp from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ArtifactIndexState } from "../../src/types.js";
|
||||
|
||||
let tempDir: string;
|
||||
let existingMetadata: ArtifactIndexState[] | null = null;
|
||||
const saveCalls: ArtifactIndexState[][] = [];
|
||||
|
||||
vi.mock("../../src/services/embeddings.js", () => ({
|
||||
generateEmbeddings: vi.fn(async (texts: string[]) =>
|
||||
texts.map(() => [0.1, 0.2, 0.3]),
|
||||
),
|
||||
prepareDocumentText: vi.fn((content: string, filePath: string) =>
|
||||
`search_document: ${filePath}\n${content}`,
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../../src/services/qdrant.js", () => ({
|
||||
deleteArtifactChunks: vi.fn(async () => undefined),
|
||||
deleteCollection: vi.fn(async () => undefined),
|
||||
deleteContextMetadata: vi.fn(async () => undefined),
|
||||
ensureCollection: vi.fn(async () => undefined),
|
||||
ensurePayloadIndex: vi.fn(async () => undefined),
|
||||
getCollectionInfo: vi.fn(async () => ({ pointsCount: 1 })),
|
||||
loadContextMetadata: vi.fn(async () => existingMetadata),
|
||||
saveContextMetadata: vi.fn(async (
|
||||
_collection: string,
|
||||
_projectPath: string,
|
||||
artifacts: ArtifactIndexState[],
|
||||
) => {
|
||||
saveCalls.push([...artifacts]);
|
||||
existingMetadata = [...artifacts];
|
||||
}),
|
||||
searchChunks: vi.fn(async () => []),
|
||||
searchChunksWithFilter: vi.fn(async () => []),
|
||||
upsertPreEmbeddedChunks: vi.fn(async () => ({ pointsSkipped: 0 })),
|
||||
}));
|
||||
|
||||
const { ensureArtifactsIndexed, indexAllArtifacts } = await import(
|
||||
"../../src/services/context-artifacts.js"
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
existingMetadata = null;
|
||||
saveCalls.length = 0;
|
||||
tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "socraticode-checkpoint-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fsp.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function createProject(files: Record<string, string>): Promise<string> {
|
||||
const projectDir = path.join(tempDir, `proj-${Math.random().toString(36).slice(2)}`);
|
||||
for (const [filePath, content] of Object.entries(files)) {
|
||||
const fullPath = path.join(projectDir, filePath);
|
||||
await fsp.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await fsp.writeFile(fullPath, content);
|
||||
}
|
||||
return projectDir;
|
||||
}
|
||||
|
||||
describe("context artifact metadata checkpoints", () => {
|
||||
it("saves metadata after each artifact during full indexing", async () => {
|
||||
const projectDir = await createProject({
|
||||
".socraticodecontextartifacts.json": JSON.stringify({
|
||||
artifacts: [
|
||||
{ name: "a", path: "./a.md", description: "Artifact A" },
|
||||
{ name: "b", path: "./b.md", description: "Artifact B" },
|
||||
],
|
||||
}),
|
||||
"a.md": "# A",
|
||||
"b.md": "# B",
|
||||
});
|
||||
|
||||
const { indexed, errors } = await indexAllArtifacts(projectDir);
|
||||
|
||||
expect(errors).toHaveLength(0);
|
||||
expect(indexed.map((a) => a.name)).toEqual(["a", "b"]);
|
||||
expect(saveCalls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(saveCalls[0].map((a) => a.name)).toEqual(["a"]);
|
||||
expect(saveCalls[1].map((a) => a.name)).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("keeps a successful artifact checkpoint when a later artifact fails", async () => {
|
||||
const projectDir = await createProject({
|
||||
".socraticodecontextartifacts.json": JSON.stringify({
|
||||
artifacts: [
|
||||
{ name: "ok", path: "./ok.md", description: "OK artifact" },
|
||||
{ name: "missing", path: "./missing.md", description: "Missing artifact" },
|
||||
],
|
||||
}),
|
||||
"ok.md": "# OK",
|
||||
});
|
||||
|
||||
const { indexed, errors } = await indexAllArtifacts(projectDir);
|
||||
|
||||
expect(indexed.map((a) => a.name)).toEqual(["ok"]);
|
||||
expect(errors.map((e) => e.name)).toEqual(["missing"]);
|
||||
expect(saveCalls[0].map((a) => a.name)).toEqual(["ok"]);
|
||||
});
|
||||
|
||||
it("preserves existing states while checkpointing stale artifacts", async () => {
|
||||
const projectDir = await createProject({
|
||||
".socraticodecontextartifacts.json": JSON.stringify({
|
||||
artifacts: [
|
||||
{ name: "changed", path: "./changed.md", description: "Changed artifact" },
|
||||
{ name: "same", path: "./same.md", description: "Same artifact" },
|
||||
],
|
||||
}),
|
||||
"changed.md": "# Changed",
|
||||
"same.md": "# Same",
|
||||
});
|
||||
|
||||
const { readArtifactContent } = await import("../../src/services/context-artifacts.js");
|
||||
const same = await readArtifactContent("./same.md", projectDir);
|
||||
existingMetadata = [
|
||||
{
|
||||
name: "changed",
|
||||
description: "Changed artifact",
|
||||
resolvedPath: path.join(projectDir, "changed.md"),
|
||||
contentHash: "stale-hash",
|
||||
lastIndexedAt: "2026-01-01T00:00:00.000Z",
|
||||
chunksIndexed: 1,
|
||||
},
|
||||
{
|
||||
name: "same",
|
||||
description: "Same artifact",
|
||||
resolvedPath: path.join(projectDir, "same.md"),
|
||||
contentHash: same.contentHash,
|
||||
lastIndexedAt: "2026-01-01T00:00:00.000Z",
|
||||
chunksIndexed: 1,
|
||||
},
|
||||
];
|
||||
|
||||
const result = await ensureArtifactsIndexed(projectDir);
|
||||
|
||||
expect(result.reindexed).toEqual(["changed"]);
|
||||
expect(result.upToDate).toEqual(["same"]);
|
||||
expect(saveCalls[0].map((a) => a.name).sort()).toEqual(["changed", "same"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
//
|
||||
// Tests for the dynamic ast-grep grammar loader.
|
||||
//
|
||||
// Background: in 1.8.3 the loader called `registerDynamicLanguage` once with
|
||||
// every loaded grammar in a single batch. Per `@ast-grep/napi`, that call is
|
||||
// atomic: a single throwing `libraryPath` getter aborts the whole batch and
|
||||
// no grammar gets registered. On environments where one prebuilt binary is
|
||||
// missing for the host architecture, this manifested as all dynamic
|
||||
// languages being silently broken (issue #43).
|
||||
//
|
||||
// 1.8.4 fixes this by pre-validating each grammar's `libraryPath` getter in
|
||||
// the inner per-grammar try/catch so a missing prebuild is contained to that
|
||||
// one grammar. The `getDynamicLanguageStatus` API exposes which grammars
|
||||
// registered successfully and which failed (with the underlying reason),
|
||||
// surfaced in `codebase_graph_status`.
|
||||
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
ensureDynamicLanguages,
|
||||
getDynamicLanguageStatus,
|
||||
} from "../../src/services/code-graph.js";
|
||||
|
||||
beforeAll(() => {
|
||||
ensureDynamicLanguages();
|
||||
});
|
||||
|
||||
describe("dynamic-language-loader", () => {
|
||||
describe("ensureDynamicLanguages", () => {
|
||||
it("is synchronous (returns void, not a Promise)", () => {
|
||||
const result = ensureDynamicLanguages();
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is idempotent — calling repeatedly does not change registration state", () => {
|
||||
const before = getDynamicLanguageStatus();
|
||||
ensureDynamicLanguages();
|
||||
ensureDynamicLanguages();
|
||||
const after = getDynamicLanguageStatus();
|
||||
|
||||
expect(after.loaded).toEqual(before.loaded);
|
||||
expect(after.failed.map((f) => f.name)).toEqual(before.failed.map((f) => f.name));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDynamicLanguageStatus", () => {
|
||||
it("returns loaded and failed arrays", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
expect(status).toHaveProperty("loaded");
|
||||
expect(status).toHaveProperty("failed");
|
||||
expect(Array.isArray(status.loaded)).toBe(true);
|
||||
expect(Array.isArray(status.failed)).toBe(true);
|
||||
});
|
||||
|
||||
it("loaded entries are unique strings", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
const seen = new Set<string>();
|
||||
for (const name of status.loaded) {
|
||||
expect(typeof name).toBe("string");
|
||||
expect(seen.has(name)).toBe(false);
|
||||
seen.add(name);
|
||||
}
|
||||
});
|
||||
|
||||
it("failed entries each include name and error", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
for (const f of status.failed) {
|
||||
expect(typeof f.name).toBe("string");
|
||||
expect(typeof f.error).toBe("string");
|
||||
expect(f.error.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("loaded list is sorted alphabetically", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
const sorted = [...status.loaded].sort();
|
||||
expect(status.loaded).toEqual(sorted);
|
||||
});
|
||||
|
||||
it("failed list is sorted alphabetically by name", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
const names = status.failed.map((f) => f.name);
|
||||
const sorted = [...names].sort();
|
||||
expect(names).toEqual(sorted);
|
||||
});
|
||||
|
||||
it("loaded and failed sets are disjoint", () => {
|
||||
const status = getDynamicLanguageStatus();
|
||||
const failedNames = new Set(status.failed.map((f) => f.name));
|
||||
for (const loaded of status.loaded) {
|
||||
expect(failedNames.has(loaded)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("at least one expected dynamic grammar registers in this environment", () => {
|
||||
// On every supported dev environment for this repo (macOS, common
|
||||
// Linux distros), the pre-validation step should let at least a few
|
||||
// of these load successfully. If this fails, either the environment
|
||||
// is unusual (and we want to know) or there is a real regression in
|
||||
// the loader.
|
||||
const status = getDynamicLanguageStatus();
|
||||
const loaded = new Set(status.loaded);
|
||||
const expected = ["python", "go", "java", "php", "ruby"];
|
||||
const found = expected.filter((n) => loaded.has(n));
|
||||
expect(found.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildCsNamespaceMap,
|
||||
buildGoModuleInfo,
|
||||
buildJvmSuffixMap,
|
||||
resolveImport,
|
||||
} from "../../src/services/graph-resolution.js";
|
||||
@@ -268,6 +269,103 @@ describe("graph-resolution", () => {
|
||||
|
||||
expect(result).toBe("src/mypackage/utils.py");
|
||||
});
|
||||
|
||||
it("resolves sibling-flat imports in service-style monorepos (#46)", () => {
|
||||
// service-a/main.py runs as `python main.py` from inside service-a/,
|
||||
// so `import config` resolves to service-a/config.py at runtime.
|
||||
project = createTempProject({
|
||||
"service-a/main.py": "",
|
||||
"service-a/config.py": "",
|
||||
"service-b/main.py": "",
|
||||
"service-b/config.py": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"config",
|
||||
path.join(project.root, "service-a/main.py"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"python",
|
||||
);
|
||||
|
||||
expect(result).toBe("service-a/config.py");
|
||||
});
|
||||
|
||||
it("resolves sibling-flat imports for dotted module paths", () => {
|
||||
// `import shared.utils` from service-a/main.py with shared/utils.py
|
||||
// sitting next to main.py.
|
||||
project = createTempProject({
|
||||
"service-a/main.py": "",
|
||||
"service-a/shared/utils.py": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"shared.utils",
|
||||
path.join(project.root, "service-a/main.py"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"python",
|
||||
);
|
||||
|
||||
expect(result).toBe("service-a/shared/utils.py");
|
||||
});
|
||||
|
||||
it("resolves sibling packages via __init__.py", () => {
|
||||
// `import config` resolves to service-a/config/__init__.py when no
|
||||
// bare service-a/config.py exists.
|
||||
project = createTempProject({
|
||||
"service-a/main.py": "",
|
||||
"service-a/config/__init__.py": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"config",
|
||||
path.join(project.root, "service-a/main.py"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"python",
|
||||
);
|
||||
|
||||
expect(result).toBe("service-a/config/__init__.py");
|
||||
});
|
||||
|
||||
it("preserves project-root precedence when the same name exists at root and as a sibling", () => {
|
||||
// Backward-compat guarantee: `import config` from service-a/main.py
|
||||
// still resolves to the project-root config.py if one exists, so
|
||||
// existing layouts do not change after this PR. The sibling fallback
|
||||
// only fires when the project-root lookup fails.
|
||||
project = createTempProject({
|
||||
"config.py": "",
|
||||
"service-a/main.py": "",
|
||||
"service-a/config.py": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"config",
|
||||
path.join(project.root, "service-a/main.py"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"python",
|
||||
);
|
||||
|
||||
expect(result).toBe("config.py");
|
||||
});
|
||||
|
||||
it("returns null when neither project-root, src/, lib/, nor sibling have the module", () => {
|
||||
project = createTempProject({
|
||||
"service-a/main.py": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"config",
|
||||
path.join(project.root, "service-a/main.py"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"python",
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rust resolution", () => {
|
||||
@@ -674,7 +772,10 @@ describe("graph-resolution", () => {
|
||||
// ── Go resolution ──────────────────────────────────────────────────────
|
||||
|
||||
describe("Go resolution", () => {
|
||||
it("returns null (Go requires go.mod analysis)", () => {
|
||||
it("returns null when no goModuleInfo is supplied (no go.mod path active)", () => {
|
||||
// Back-compat: when the resolver is called without Go module info
|
||||
// (e.g. for projects with no go.mod), every Go import resolves to
|
||||
// null. This is the path before issue #45's fix.
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
@@ -690,6 +791,326 @@ describe("graph-resolution", () => {
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves a subpackage import to the representative .go file (#45)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
"internal/util.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
expect(goInfo).not.toBeNull();
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/internal",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
// helper.go is the lexically smallest non-test .go file in
|
||||
// internal/, so it's picked as the package's representative.
|
||||
expect(result).toBe("internal/helper.go");
|
||||
});
|
||||
|
||||
it("resolves the root-package import to a project-root .go file", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"doc.go": "",
|
||||
"internal/helper.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp",
|
||||
path.join(project.root, "internal/helper.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("doc.go");
|
||||
});
|
||||
|
||||
it("returns null for external imports (not under module path)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"github.com/spf13/cobra",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod is missing", () => {
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
// No go.mod → buildGoModuleInfo returns null → resolver returns null
|
||||
// for any Go import.
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod has no module directive", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "go 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("excludes _test.go files from representative selection", () => {
|
||||
// service/foo.go and service/foo_test.go both exist in the same
|
||||
// directory. The map's representative should be foo.go (the
|
||||
// non-test file), not foo_test.go.
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"service/foo.go": "",
|
||||
"service/foo_test.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/service",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("service/foo.go");
|
||||
});
|
||||
|
||||
it("uses lexically smallest non-test file as the representative (determinism)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"pkg/zeta.go": "",
|
||||
"pkg/alpha.go": "",
|
||||
"pkg/middle.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/pkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("pkg/alpha.go");
|
||||
});
|
||||
|
||||
it("resolves local imports when the module path starts with golang.org/", () => {
|
||||
// Real-world case: someone working ON one of the Go-team packages
|
||||
// like golang.org/x/sync. Their go.mod declares
|
||||
// `module golang.org/x/sync` and internal subpackages must resolve
|
||||
// locally, even though isExternalModule treats `golang.org/...`
|
||||
// imports as external for non-local-module projects.
|
||||
project = createTempProject({
|
||||
"go.mod": "module golang.org/x/custom\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/foo.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"golang.org/x/custom/internal",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("internal/foo.go");
|
||||
});
|
||||
|
||||
it("returns null for a similar-prefix import that is not a subpackage", () => {
|
||||
// `example.com/myapp-other/pkg` shares the prefix `example.com/myapp`
|
||||
// textually but is a separate module. Must not resolve to anything
|
||||
// inside the local project.
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"pkg/foo.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp-other/pkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGoModuleInfo", () => {
|
||||
it("parses a simple go.mod and returns module path + package map", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
"internal/util.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).not.toBeNull();
|
||||
expect(goInfo?.modulePath).toBe("example.com/myapp");
|
||||
// Root package
|
||||
expect(goInfo?.packageMap.get(".")).toBe("main.go");
|
||||
// Subpackage — first lex-sorted file wins
|
||||
expect(goInfo?.packageMap.get("internal")).toBe("internal/helper.go");
|
||||
});
|
||||
|
||||
it("parses go.mod with leading whitespace and trailing content", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": " module github.com/user/repo\n\ngo 1.21\n\nrequire (\n\tgithub.com/x/y v1.0.0\n)\n",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.modulePath).toBe("github.com/user/repo");
|
||||
});
|
||||
|
||||
it("returns null when go.mod is missing", () => {
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod has no module directive", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "// no module line\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("excludes _test.go files from the package map representatives", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"service/foo_test.go": "",
|
||||
"service/foo.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.packageMap.get("service")).toBe("service/foo.go");
|
||||
});
|
||||
|
||||
it("does not include directories that contain only _test.go files", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"internal/only_test.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
// Map has "." (for main.go) but no "internal" entry, because the
|
||||
// only file there is a test file.
|
||||
expect(goInfo?.packageMap.has(".")).toBe(true);
|
||||
expect(goInfo?.packageMap.has("internal")).toBe(false);
|
||||
});
|
||||
|
||||
it("uses forward-slash keys for nested packages (cross-platform lookup)", () => {
|
||||
// Go imports always use forward slashes; the map keys must match
|
||||
// that form so resolution works on Windows, where path.dirname
|
||||
// would otherwise produce backslash-separated keys for nested
|
||||
// packages. The map value preserves the fileSet's native form
|
||||
// (test fixtures use forward slashes since createTempProject keys
|
||||
// its fileSet by the input relPath).
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"pkg/subpkg/file.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.packageMap.has("pkg/subpkg")).toBe(true);
|
||||
expect(goInfo?.packageMap.get("pkg/subpkg")).toBe("pkg/subpkg/file.go");
|
||||
});
|
||||
|
||||
it("resolves nested-package imports", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"pkg/subpkg/file.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/pkg/subpkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("pkg/subpkg/file.go");
|
||||
});
|
||||
});
|
||||
|
||||
// ── C# resolution ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
//
|
||||
// Tests for QDRANT_COLLECTION_PREFIX (issue #49).
|
||||
//
|
||||
// QDRANT_COLLECTION_PREFIX is read once at module load in
|
||||
// `src/constants.ts` and used by `src/config.ts` collection-name
|
||||
// generators (and by `src/services/qdrant.ts` for the metadata
|
||||
// collection). To exercise multiple prefix values in one test run we
|
||||
// reset the module cache between cases and dynamically re-import the
|
||||
// modules under test, which forces the env-var-reading IIFE in
|
||||
// constants.ts to execute again.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const ENV_KEY = "QDRANT_COLLECTION_PREFIX";
|
||||
|
||||
describe("QDRANT_COLLECTION_PREFIX", () => {
|
||||
const original = process.env[ENV_KEY];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (original === undefined) {
|
||||
delete process.env[ENV_KEY];
|
||||
} else {
|
||||
process.env[ENV_KEY] = original;
|
||||
}
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe("default (empty prefix) — backwards compatibility", () => {
|
||||
it("collectionName returns the legacy `codebase_<id>` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { collectionName } = await import("../../src/config.js");
|
||||
expect(collectionName("abc123def456")).toBe("codebase_abc123def456");
|
||||
});
|
||||
|
||||
it("graphCollectionName returns the legacy `codegraph_<id>` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { graphCollectionName } = await import("../../src/config.js");
|
||||
expect(graphCollectionName("abc123def456")).toBe("codegraph_abc123def456");
|
||||
});
|
||||
|
||||
it("contextCollectionName returns the legacy `context_<id>` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { contextCollectionName } = await import("../../src/config.js");
|
||||
expect(contextCollectionName("abc123def456")).toBe("context_abc123def456");
|
||||
});
|
||||
|
||||
it("symgraphMetaCollectionName returns the legacy `<id>_symgraph_meta` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { symgraphMetaCollectionName } = await import("../../src/config.js");
|
||||
expect(symgraphMetaCollectionName("abc123def456")).toBe("abc123def456_symgraph_meta");
|
||||
});
|
||||
|
||||
it("symgraphFileCollectionName returns the legacy `<id>_symgraph_file` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { symgraphFileCollectionName } = await import("../../src/config.js");
|
||||
expect(symgraphFileCollectionName("abc123def456")).toBe("abc123def456_symgraph_file");
|
||||
});
|
||||
|
||||
it("symgraphIndexCollectionName returns the legacy `<id>_symgraph_index` form", async () => {
|
||||
delete process.env[ENV_KEY];
|
||||
const { symgraphIndexCollectionName } = await import("../../src/config.js");
|
||||
expect(symgraphIndexCollectionName("abc123def456")).toBe("abc123def456_symgraph_index");
|
||||
});
|
||||
|
||||
it("treats empty-string env var the same as unset", async () => {
|
||||
process.env[ENV_KEY] = "";
|
||||
const { collectionName } = await import("../../src/config.js");
|
||||
expect(collectionName("abc")).toBe("codebase_abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("non-empty prefix", () => {
|
||||
it("prepends the prefix to collectionName", async () => {
|
||||
process.env[ENV_KEY] = "myapp_";
|
||||
const { collectionName } = await import("../../src/config.js");
|
||||
expect(collectionName("abc123")).toBe("myapp_codebase_abc123");
|
||||
});
|
||||
|
||||
it("prepends the prefix to graphCollectionName", async () => {
|
||||
process.env[ENV_KEY] = "myapp_";
|
||||
const { graphCollectionName } = await import("../../src/config.js");
|
||||
expect(graphCollectionName("abc123")).toBe("myapp_codegraph_abc123");
|
||||
});
|
||||
|
||||
it("prepends the prefix to contextCollectionName", async () => {
|
||||
process.env[ENV_KEY] = "myapp_";
|
||||
const { contextCollectionName } = await import("../../src/config.js");
|
||||
expect(contextCollectionName("abc123")).toBe("myapp_context_abc123");
|
||||
});
|
||||
|
||||
it("prepends the prefix to symgraph collection names (suffix-style still gets prefix)", async () => {
|
||||
process.env[ENV_KEY] = "myapp_";
|
||||
const {
|
||||
symgraphMetaCollectionName,
|
||||
symgraphFileCollectionName,
|
||||
symgraphIndexCollectionName,
|
||||
} = await import("../../src/config.js");
|
||||
expect(symgraphMetaCollectionName("abc")).toBe("myapp_abc_symgraph_meta");
|
||||
expect(symgraphFileCollectionName("abc")).toBe("myapp_abc_symgraph_file");
|
||||
expect(symgraphIndexCollectionName("abc")).toBe("myapp_abc_symgraph_index");
|
||||
});
|
||||
|
||||
it("accepts prefixes without trailing separator (user choice)", async () => {
|
||||
process.env[ENV_KEY] = "myapp";
|
||||
const { collectionName } = await import("../../src/config.js");
|
||||
// The user may or may not include a separator; we prepend verbatim.
|
||||
expect(collectionName("abc")).toBe("myappcodebase_abc");
|
||||
});
|
||||
|
||||
it("accepts prefixes with hyphen separator", async () => {
|
||||
process.env[ENV_KEY] = "team-alpha-";
|
||||
const { collectionName } = await import("../../src/config.js");
|
||||
expect(collectionName("abc")).toBe("team-alpha-codebase_abc");
|
||||
});
|
||||
|
||||
it("two different prefixes produce disjoint collection-name sets for the same projectId", async () => {
|
||||
process.env[ENV_KEY] = "instance_a_";
|
||||
const { collectionName: collA } = await import("../../src/config.js");
|
||||
const nameA = collA("project1");
|
||||
|
||||
vi.resetModules();
|
||||
process.env[ENV_KEY] = "instance_b_";
|
||||
const { collectionName: collB } = await import("../../src/config.js");
|
||||
const nameB = collB("project1");
|
||||
|
||||
expect(nameA).toBe("instance_a_codebase_project1");
|
||||
expect(nameB).toBe("instance_b_codebase_project1");
|
||||
expect(nameA).not.toBe(nameB);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validation", () => {
|
||||
it("rejects a prefix containing whitespace", async () => {
|
||||
process.env[ENV_KEY] = "my app";
|
||||
await expect(import("../../src/constants.js")).rejects.toThrow(
|
||||
/Invalid QDRANT_COLLECTION_PREFIX/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a prefix containing a slash", async () => {
|
||||
process.env[ENV_KEY] = "team/alpha";
|
||||
await expect(import("../../src/constants.js")).rejects.toThrow(
|
||||
/Invalid QDRANT_COLLECTION_PREFIX/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a prefix containing a colon", async () => {
|
||||
process.env[ENV_KEY] = "team:alpha";
|
||||
await expect(import("../../src/constants.js")).rejects.toThrow(
|
||||
/Invalid QDRANT_COLLECTION_PREFIX/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a prefix containing emoji or other unicode", async () => {
|
||||
process.env[ENV_KEY] = "rocket🚀";
|
||||
await expect(import("../../src/constants.js")).rejects.toThrow(
|
||||
/Invalid QDRANT_COLLECTION_PREFIX/,
|
||||
);
|
||||
});
|
||||
|
||||
it("includes the offending value in the error message for discoverability", async () => {
|
||||
process.env[ENV_KEY] = "bad value";
|
||||
await expect(import("../../src/constants.js")).rejects.toThrow(/"bad value"/);
|
||||
});
|
||||
|
||||
it("accepts a prefix containing only ASCII letters, digits, underscore, hyphen", async () => {
|
||||
process.env[ENV_KEY] = "a_B-9-z_";
|
||||
const constants = await import("../../src/constants.js");
|
||||
expect(constants.QDRANT_COLLECTION_PREFIX).toBe("a_B-9-z_");
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user