Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ Pass `--split-identifiers=false` to keep the old behaviour.
| `--embedding-model <model>` | `bge-small` | `bge-small` (384d, fast), `jina-code-v2` (768d, 6× slower), `granite-97m` (384d, 32K ctx, ~3× slower), or `static` (model2vec, 256d — ~100× faster indexing, no ONNX; needs a local model dir, see below) |
| `--full-body-embedding` | `true` | Embed full function body (~50 lines) for better semantic search and duplicate detection. Takes a value: `--full-body-embedding=false` turns it off |
| `--split-identifiers` | `true` | Also embed the word-split form of identifiers whose words are run together, so `getUserById` embeds as "get user by id" too. Names already separated by `_` or `-` are left alone, since they tokenise into the same words; a leading or trailing delimiter separates nothing, so `_handleClick` is split like `handleClick`. Takes a value: `--split-identifiers=false` embeds raw names, as releases up to 0.20.1 did |
| `--max-files <n>` | 5000 | Maximum files to index |
| `--max-files <n>` | 5000 | Maximum files to index (in LSP mode, a positive `codegraph.maxFiles` setting wins) |
| `--max-threads <n>` | half the CPUs | Most threads the engine computes on: the embedding model's pool, the pool tokenizing for it, and the async runtime. Also read from `CODEGRAPH_MAX_THREADS`. Lower it to keep the machine responsive while a large workspace embeds |
| `--profile <name>` | `all` | Filter the exposed MCP tool surface to a named subset (see below) |
| `--graph-only` | off | Skip embedding generation — build the graph and serve structural tools only. No ONNX model load, 10-50× faster indexing. Semantic search and memory tools unavailable. For CI / one-shot graph queries. |
| `--graph-only` | off | Skip embedding generation — build the graph and serve structural tools only. No ONNX model load, 10-50× faster indexing. Semantic search and memory tools unavailable. For CI / one-shot graph queries. Not applied in LSP mode. |
| `--run-tool <name>` | — | One-shot mode: index, run a single tool, print its result, exit. No MCP handshake. Pair with `--tool-args '<json>'`. |

`--split-identifiers` and `--full-body-embedding` both change the text every symbol is embedded from, and vectors built from different text cannot be ranked against each other.
Expand Down
142 changes: 133 additions & 9 deletions crates/codegraph-server/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,34 @@ pub struct CodeGraphConfig {
/// stays current. When false, embeddings refresh only on save / reindex.
#[serde(default = "default_embed_on_open")]
pub embed_on_open: bool,
/// Files indexed per workspace scan, from `codegraph.maxFiles`. Zero means
/// the client has no opinion and the engine's `--max-files` applies.
#[serde(default)]
pub max_files: usize,
}

/// Indexing limits fixed when the engine starts, from its command line.
///
/// Kept apart from [`CodeGraphConfig`] because that is replaced wholesale
/// whenever the client pushes settings, and a value the client never sends must
/// survive that. LSP mode used to ignore `--max-files` and `--exclude`
/// entirely, so an engine started with a raised limit - the usual way to run
/// it in a container - still stopped at 5,000 files.
#[derive(Debug, Clone)]
pub struct LaunchOptions {
/// `--max-files`.
pub max_files: usize,
/// `--exclude`: directory names skipped on top of the defaults.
pub exclude_dirs: Vec<String>,
}

impl Default for LaunchOptions {
fn default() -> Self {
Self {
max_files: crate::indexer::IndexConfig::DEFAULT_MAX_FILES,
exclude_dirs: Vec::new(),
}
}
}

fn default_max_file_size_kb() -> u64 {
Expand All @@ -59,6 +87,7 @@ impl Default for CodeGraphConfig {
index_paths: Vec::new(),
max_file_size_kb: 1024,
embed_on_open: true,
max_files: 0,
}
}
}
Expand Down Expand Up @@ -147,6 +176,9 @@ pub struct CodeGraphBackend {
/// Indexing configuration from VS Code settings.
pub config: Arc<RwLock<CodeGraphConfig>>,

/// Indexing limits from the engine's command line.
launch: LaunchOptions,

/// Extension point for pro LSP commands (community uses NoopProCommandProvider).
pub pro_commands: Arc<dyn crate::lsp_pro_hooks::ProCommandProvider>,

Expand Down Expand Up @@ -193,6 +225,7 @@ impl CodeGraphBackend {
file_watcher: Arc::new(Mutex::new(None)),
branch_watcher: Arc::new(Mutex::new(None)),
config: Arc::new(RwLock::new(CodeGraphConfig::default())),
launch: LaunchOptions::default(),
pro_commands: Arc::new(crate::lsp_pro_hooks::NoopProCommandProvider),
command_prefix: "codegraph".to_string(),
index_state,
Expand All @@ -201,6 +234,13 @@ impl CodeGraphBackend {
}
}

/// Apply the engine's command-line indexing limits.
#[must_use]
pub fn with_launch_options(mut self, launch: LaunchOptions) -> Self {
self.launch = launch;
self
}

/// Create a backend with a custom pro command provider for LSP.
/// The command prefix is taken from the provider (e.g., "stellarion").
pub fn with_pro_commands(
Expand Down Expand Up @@ -246,6 +286,7 @@ impl CodeGraphBackend {
file_watcher: Arc::new(Mutex::new(None)),
branch_watcher: Arc::new(Mutex::new(None)),
config: Arc::new(RwLock::new(CodeGraphConfig::default())),
launch: LaunchOptions::default(),
pro_commands: Arc::new(crate::lsp_pro_hooks::NoopProCommandProvider),
command_prefix: "codegraph".to_string(),
index_state,
Expand Down Expand Up @@ -465,7 +506,12 @@ impl CodeGraphBackend {

/// Build an [`IndexConfig`](crate::indexer::IndexConfig) from the current
/// LSP configuration.
fn index_config_from_lsp(config: &CodeGraphConfig) -> crate::indexer::IndexConfig {
///
/// The client's `maxFiles` wins when it sets one; otherwise `--max-files`.
fn index_config_from_lsp(
config: &CodeGraphConfig,
launch: &LaunchOptions,
) -> crate::indexer::IndexConfig {
// Merge user-provided exclude patterns with the hardcoded defaults
// rather than replacing them. The defaults cover binary archives,
// secret files, package artifacts, and vendored parser sources.
Expand All @@ -477,10 +523,21 @@ impl CodeGraphBackend {
patterns.push(p.clone());
}
}
let mut exclude_dirs = crate::indexer::IndexConfig::default_exclude_dirs();
for d in &launch.exclude_dirs {
if !exclude_dirs.contains(d) {
exclude_dirs.push(d.clone());
}
}
crate::indexer::IndexConfig {
exclude_dirs: crate::indexer::IndexConfig::default_exclude_dirs(),
exclude_dirs,
exclude_patterns: patterns,
max_file_size_bytes: config.max_file_size_kb * 1024,
max_files: if config.max_files > 0 {
config.max_files
} else {
launch.max_files
},
..crate::indexer::IndexConfig::default()
}
}
Expand Down Expand Up @@ -575,7 +632,7 @@ impl CodeGraphBackend {
) -> std::pin::Pin<Box<dyn std::future::Future<Output = usize> + Send + 'a>> {
Box::pin(async move {
let config = self.config.read().await.clone();
let idx_config = Self::index_config_from_lsp(&config);
let idx_config = Self::index_config_from_lsp(&config, &self.launch);
let counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (total, _parsed, _skipped, _by_lang, _errors) = self
.indexer
Expand Down Expand Up @@ -962,9 +1019,14 @@ impl LanguageServer for CodeGraphBackend {
.get("embedOnOpen")
.and_then(|v| v.as_bool())
.unwrap_or_else(default_embed_on_open),
max_files: opts
.get("maxFiles")
.and_then(|v| v.as_u64())
.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)),
};
tracing::info!("CodeGraph config: index_on_startup={}, exclude_patterns={:?}, index_paths={:?}, max_file_size_kb={}, embed_on_open={}",
config.index_on_startup, config.exclude_patterns, config.index_paths, config.max_file_size_kb, config.embed_on_open);
tracing::info!("CodeGraph config: index_on_startup={}, exclude_patterns={:?}, index_paths={:?}, max_file_size_kb={}, embed_on_open={}, max_files={}",
config.index_on_startup, config.exclude_patterns, config.index_paths, config.max_file_size_kb, config.embed_on_open,
Self::index_config_from_lsp(&config, &self.launch).max_files);
*self.config.write().await = config;
}

Expand Down Expand Up @@ -1245,7 +1307,7 @@ impl LanguageServer for CodeGraphBackend {
.collect()
};

let idx_config = Self::index_config_from_lsp(&config);
let idx_config = Self::index_config_from_lsp(&config, &self.launch);
let result = self
.indexer
.index_workspace(&self.graph, &paths_to_index, &idx_config)
Expand Down Expand Up @@ -1531,7 +1593,7 @@ impl LanguageServer for CodeGraphBackend {
let config = self.config.read().await.clone();

// Skip files matching exclude patterns (binary archives, vendored sources, secrets…).
let exclude_set = Self::index_config_from_lsp(&config).build_exclude_set();
let exclude_set = Self::index_config_from_lsp(&config, &self.launch).build_exclude_set();
if exclude_set.is_match(path.to_string_lossy().as_ref()) {
tracing::info!("Skipping did_open for {:?}: matched exclude pattern", path);
return;
Expand Down Expand Up @@ -2024,7 +2086,7 @@ impl LanguageServer for CodeGraphBackend {
.collect()
};

let idx_config = Self::index_config_from_lsp(&config);
let idx_config = Self::index_config_from_lsp(&config, &self.launch);
let started_at = std::time::Instant::now();
let result = self
.indexer
Expand Down Expand Up @@ -2492,7 +2554,7 @@ impl LanguageServer for CodeGraphBackend {
}

let lsp_config = self.config.read().await.clone();
let config = Self::index_config_from_lsp(&lsp_config);
let config = Self::index_config_from_lsp(&lsp_config, &self.launch);
let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (total, _parsed, _skipped, _by_lang, _errors) = self
.indexer
Expand Down Expand Up @@ -4164,6 +4226,68 @@ mod tests {
use std::path::Path;
use tempfile::TempDir;

mod launch_options {
use super::*;

fn launch(max_files: usize) -> LaunchOptions {
LaunchOptions {
max_files,
exclude_dirs: vec!["generated".into()],
}
}

#[test]
fn the_engine_flag_sets_the_limit_when_the_client_has_none() {
let config = CodeGraphConfig::default();
let idx = CodeGraphBackend::index_config_from_lsp(&config, &launch(30_000));
assert_eq!(idx.max_files, 30_000);
}

#[test]
fn a_client_limit_wins_over_the_engine_flag() {
let config = CodeGraphConfig {
max_files: 12_000,
..CodeGraphConfig::default()
};
let idx = CodeGraphBackend::index_config_from_lsp(&config, &launch(30_000));
assert_eq!(idx.max_files, 12_000);
}

#[test]
fn engine_excludes_add_to_the_defaults() {
let idx =
CodeGraphBackend::index_config_from_lsp(&CodeGraphConfig::default(), &launch(1));
assert!(idx.exclude_dirs.iter().any(|d| d == "generated"));
assert!(idx.exclude_dirs.iter().any(|d| d == "node_modules"));
}

#[test]
fn a_settings_push_keeps_the_engine_flag() {
// The client replaces the whole config on every settings change,
// and older clients never send maxFiles at all.
let pushed: CodeGraphConfig =
serde_json::from_value(serde_json::json!({"indexOnStartup": true})).unwrap();
let idx = CodeGraphBackend::index_config_from_lsp(&pushed, &launch(30_000));
assert_eq!(idx.max_files, 30_000);
}

#[tokio::test]
async fn initialize_reads_max_files_from_the_client() {
let (service, _socket) = tower_lsp::LspService::new(|client| {
CodeGraphBackend::new(client).with_launch_options(launch(30_000))
});
let backend = service.inner();
let params = InitializeParams {
initialization_options: Some(serde_json::json!({"maxFiles": 9_000})),
..Default::default()
};
backend.initialize(params).await.unwrap();
let config = backend.config.read().await.clone();
let idx = CodeGraphBackend::index_config_from_lsp(&config, &backend.launch);
assert_eq!(idx.max_files, 9_000);
}
}

mod workspace_paths {
use super::*;

Expand Down
3 changes: 3 additions & 0 deletions crates/codegraph-server/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ pub struct DaemonConfig {
/// Whether to split run-together identifiers into words when embedding.
/// Carried for the same reason as [`Self::full_body_embedding`].
pub split_identifiers: bool,
/// Files indexed per scan (`--max-files`).
pub max_files: usize,
}

/// Run the watcher daemon for a workspace until a termination signal arrives.
Expand Down Expand Up @@ -219,6 +221,7 @@ pub async fn run(config: DaemonConfig) -> Result<(), String> {
"fullBodyEmbedding": config.full_body_embedding,
"splitIdentifiers": config.split_identifiers,
"embedOnOpen": true,
"maxFiles": config.max_files,
});
let uri = Url::from_file_path(&workspace)
.map_err(|_| format!("invalid workspace path: {workspace:?}"))?;
Expand Down
8 changes: 6 additions & 2 deletions crates/codegraph-server/src/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,15 @@ impl Default for IndexConfig {
exclude_patterns: Self::default_exclude_patterns(),
max_file_size_bytes: 1024 * 1024, // 1 MiB
max_depth: 20,
max_files: 5_000,
max_files: Self::DEFAULT_MAX_FILES,
}
}
}

impl IndexConfig {
/// Files indexed per scan when neither the client nor `--max-files` says otherwise.
pub const DEFAULT_MAX_FILES: usize = 5_000;

/// The hardcoded list of directories that are always excluded.
///
/// Three categories:
Expand Down Expand Up @@ -639,7 +642,8 @@ impl Indexer {
for entry in entries.flatten() {
if counter.load(Ordering::Relaxed) >= config.max_files {
tracing::warn!(
"Reached max indexed file limit of {}; stopping",
"Reached max indexed file limit of {}; stopping. Raise it with \
--max-files or the codegraph.maxFiles setting",
config.max_files
);
break;
Expand Down
2 changes: 1 addition & 1 deletion crates/codegraph-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub mod runtime_deps;
pub mod telemetry;
pub mod watcher;

pub use backend::CodeGraphBackend;
pub use backend::{CodeGraphBackend, LaunchOptions};
pub use error::LspError;
pub use git_mining::{GitMiner, MiningConfig, MiningResult};
pub use memory::MemoryManager;
Expand Down
20 changes: 17 additions & 3 deletions crates/codegraph-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ struct Args {
#[arg(long, short)]
exclude: Vec<String>,

/// Maximum number of files to index (default: 5000)
#[arg(long, default_value = "5000")]
/// Maximum number of files to index (default: 5000). In LSP mode a
/// positive `maxFiles` from the client takes precedence.
#[arg(long, default_value_t = codegraph_server::indexer::IndexConfig::DEFAULT_MAX_FILES)]
max_files: usize,

/// Embedding model: bge-small (384d, 512 ctx, fast — default),
Expand Down Expand Up @@ -110,6 +111,7 @@ struct Args {
/// tools only. The ONNX model is never loaded (faster startup, lower
/// memory, ~10-50× faster indexing). Semantic search and similarity
/// tools are unavailable. Ideal for CI / one-shot graph queries.
/// Not applied in LSP mode, where the client's settings decide embedding.
#[arg(long)]
graph_only: bool,

Expand Down Expand Up @@ -504,6 +506,7 @@ async fn run(args: Args, budget: ThreadBudget) {
embedding_model: Some(args.embedding_model.clone()),
full_body_embedding: args.full_body_embedding,
split_identifiers: args.split_identifiers,
max_files: args.max_files,
};
if let Err(e) = codegraph_server::daemon::run(config).await {
eprintln!("daemon error: {e}");
Expand Down Expand Up @@ -634,11 +637,22 @@ async fn run(args: Args, budget: ThreadBudget) {
use tower_lsp::{LspService, Server};

tracing::info!("Starting CodeGraph LSP server");
if args.graph_only {
tracing::warn!(
"--graph-only is not applied in LSP mode; the client's settings decide embedding"
);
}

let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();

let (service, socket) = LspService::new(CodeGraphBackend::new);
let launch = codegraph_server::LaunchOptions {
max_files: args.max_files,
exclude_dirs: args.exclude.clone(),
};
let (service, socket) = LspService::new(move |client| {
CodeGraphBackend::new(client).with_launch_options(launch.clone())
});

codegraph_server::crash_phase::mark("serving");
// Race the serve loop against the exit signal: tower-lsp will not
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ class CodeGraphConnectionProvider(private val project: Project) : OSProcessStrea
"excludePatterns" to settings.excludePatterns.toList(),
"indexPaths" to settings.indexPaths.toList(),
"maxFileSizeKB" to settings.maxFileSizeKB,
"maxFiles" to settings.maxFiles,
"embeddingModel" to settings.embeddingModel,
"staticModelPath" to settings.staticModelPath.ifBlank { null },
"fullBodyEmbedding" to settings.fullBodyEmbedding,
Expand Down
Loading
Loading