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
130 changes: 129 additions & 1 deletion crates/codegraph-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ impl Cli {
| Command::Impact { path, .. }
| Command::Affected { path, .. }
| Command::Check { path, .. }
| Command::Audit { path, .. } => path.clone(),
| Command::Audit { path, .. }
| Command::Explore { path, .. }
| Command::Node { path, .. } => path.clone(),
Command::Export { path, .. } => path.clone(),
Command::PromptHook { path, .. } => path.clone(),
// install/uninstall/skill are not project-scoped — bootstrap from cwd.
Expand Down Expand Up @@ -311,6 +313,36 @@ enum Command {
#[arg(long = "no-centrality")]
no_centrality: bool,
},
/// Explore an area of the codebase (the shell equivalent of the MCP
/// `codegraph_explore` tool). Runs the SAME deterministic engine and prints
/// the same output — relevant symbols' verbatim source grouped by file plus
/// the call paths between them. NO LLM.
Explore {
/// Symbol names or a natural-language question to explore.
query: String,
#[arg(short, long)]
path: Option<PathBuf>,
/// Max number of files to include source from (clamped 1..=20).
#[arg(long = "max-files")]
max_files: Option<usize>,
#[arg(short = 'j', long = "json")]
json: bool,
},
/// Read one symbol or file (the shell equivalent of the MCP `codegraph_node`
/// tool). Runs the SAME engine: for a symbol it prints its source plus the
/// caller/callee trail; for a file it prints the line-numbered source plus
/// which files depend on it. NO LLM.
Node {
/// A symbol name, or a file path/basename to read.
target: String,
#[arg(short, long)]
path: Option<PathBuf>,
/// Symbol mode: return just the file's symbol map instead of source.
#[arg(long = "symbols-only")]
symbols_only: bool,
#[arg(short = 'j', long = "json")]
json: bool,
},
// Upstream flags/output: upstream bin/codegraph.ts:1864-1870, 1871-1920.
// `--global`/`--local` are convenience aliases for `--location` (task spec).
Install {
Expand Down Expand Up @@ -545,6 +577,18 @@ fn run(cli: Cli) -> Result<()> {
out,
no_centrality,
} => cmd_export(path, out, no_centrality),
Command::Explore {
query,
path,
max_files,
json,
} => cmd_explore(query, path, max_files, json),
Command::Node {
target,
path,
symbols_only,
json,
} => cmd_node(target, path, symbols_only, json),
Command::Install {
target,
location,
Expand Down Expand Up @@ -2600,6 +2644,89 @@ fn cmd_impact(
Ok(())
}

fn cmd_explore(
query: String,
path: Option<PathBuf>,
max_files: Option<usize>,
json_output: bool,
) -> Result<()> {
let project = resolve_required_project(path)?;
let engine = codegraph_mcp::CodeGraphEngine::open(&project)?;
let mut args = json!({ "query": query });
if let Some(max_files) = max_files {
args["maxFiles"] = json!(max_files);
}
let result = engine.execute("codegraph_explore", &args);
print_engine_result("explore", &query, &result, json_output)
}

fn cmd_node(
target: String,
path: Option<PathBuf>,
symbols_only: bool,
json_output: bool,
) -> Result<()> {
let project = resolve_required_project(path)?;
let engine = codegraph_mcp::CodeGraphEngine::open(&project)?;
let args = if node_target_is_file(&engine, &target) {
json!({ "file": target, "symbolsOnly": symbols_only })
} else {
json!({ "symbol": target, "includeCode": true })
};
let result = engine.execute("codegraph_node", &args);
print_engine_result("node", &target, &result, json_output)
}

/// Decide whether a `codegraph node <target>` argument names an indexed FILE (→
/// file-view mode) or a SYMBOL (→ symbol mode). A path separator or a match
/// against an indexed file path means file mode; a bare identifier is a symbol.
fn node_target_is_file(engine: &codegraph_mcp::CodeGraphEngine, target: &str) -> bool {
if target.contains(['/', '\\']) {
return true;
}
engine
.indexed_file_paths()
.map(|paths| {
paths
.iter()
.any(|p| p == target || p.rsplit('/').next() == Some(target))
})
.unwrap_or(false)
}

/// Render an MCP-engine `ToolResult` for a CLI subcommand: the plain rendered
/// text (matching the MCP tool byte-for-byte), or a `{command, query, output,
/// isError}` JSON envelope under `--json`. A tool-level error exits non-zero so
/// scripts can detect a failed lookup.
fn print_engine_result(
command: &str,
query: &str,
result: &codegraph_mcp::protocol::ToolResult,
json_output: bool,
) -> Result<()> {
let text = result
.content
.iter()
.map(|c| c.text.as_str())
.collect::<Vec<_>>()
.join("\n");
let is_error = result.is_error.unwrap_or(false);
if json_output {
print_json_pretty(&json!({
"command": command,
"query": query,
"output": text,
"isError": is_error,
}))?;
} else {
println!("{text}");
}
if is_error {
bail!("codegraph {command} failed: {text}");
}
Ok(())
}

fn cmd_affected(
files: Vec<String>,
path: Option<PathBuf>,
Expand Down Expand Up @@ -2627,6 +2754,7 @@ fn cmd_affected(
}
let mut dependents = store.dependent_file_paths(&current)?;
dependents.extend(store.dependent_file_paths_unresolved(&current)?);
dependents.extend(store.dependent_file_paths_via_import_name(&current)?);
dependents.sort();
dependents.dedup();
for dependent in dependents {
Expand Down
207 changes: 207 additions & 0 deletions crates/codegraph-cli/tests/explore_node_cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
//! CLI integration tests for the `explore` and `node` subcommands, which reuse
//! the MCP `codegraph_explore` / `codegraph_node` engine.
//!
//! Drives the real `codegraph` binary against the committed mini fixture
//! (`crates/codegraph-bench/fixtures/mini`) in a private temp project.

use std::path::{Path, PathBuf};
use std::process::Command;

fn bin() -> PathBuf {
PathBuf::from(env!("CARGO_BIN_EXE_codegraph"))
}

fn workspace_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.expect("codegraph-cli is under crates/")
.to_path_buf()
}

fn mini_fixture() -> PathBuf {
workspace_root().join("crates/codegraph-bench/fixtures/mini")
}

struct TestDir {
path: PathBuf,
}

impl TestDir {
fn new(label: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"codegraph-cli-en-{label}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}

fn path(&self) -> &Path {
&self.path
}
}

impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}

fn copy_tree(src: &Path, dst: &Path) {
std::fs::create_dir_all(dst).unwrap();
for entry in std::fs::read_dir(src).unwrap() {
let entry = entry.unwrap();
let from = entry.path();
let to = dst.join(entry.file_name());
if from.is_dir() {
copy_tree(&from, &to);
} else {
std::fs::copy(&from, &to).unwrap();
}
}
}

struct Run {
stdout: String,
stderr: String,
ok: bool,
}

fn run_in(cwd: &Path, args: &[&str]) -> Run {
let output = Command::new(bin())
.args(args)
.current_dir(cwd)
.env("CODEGRAPH_NO_DAEMON", "1")
.output()
.expect("run codegraph binary");
Run {
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
ok: output.status.success(),
}
}

fn indexed_project(dir: &TestDir) -> PathBuf {
let project = dir.path().join("mini");
copy_tree(&mini_fixture(), &project);
let p = project.to_str().unwrap();
let run = run_in(dir.path(), &["init", p]);
assert!(run.ok, "init failed: {} {}", run.stdout, run.stderr);
project
}

#[test]
fn help_lists_explore_and_node_subcommands() {
let dir = TestDir::new("help");
let run = run_in(dir.path(), &["--help"]);
assert!(run.ok, "--help must succeed: {}", run.stderr);
assert!(
run.stdout.contains("explore"),
"top-level --help must list `explore`: {}",
run.stdout
);
assert!(
run.stdout.contains("node"),
"top-level --help must list `node`: {}",
run.stdout
);

// Neither subcommand may report `unrecognized subcommand`.
let eh = run_in(dir.path(), &["explore", "--help"]);
assert!(eh.ok, "explore --help must succeed: {}", eh.stderr);
assert!(
!eh.stderr.contains("unrecognized subcommand"),
"explore must be a real subcommand: {}",
eh.stderr
);
let nh = run_in(dir.path(), &["node", "--help"]);
assert!(nh.ok, "node --help must succeed: {}", nh.stderr);
assert!(
!nh.stderr.contains("unrecognized subcommand"),
"node must be a real subcommand: {}",
nh.stderr
);
}

#[test]
fn explore_returns_nonempty_structured_output() {
let dir = TestDir::new("explore");
let project = indexed_project(&dir);
let p = project.to_str().unwrap();

let run = run_in(dir.path(), &["explore", "Counter", "-p", p]);
assert!(run.ok, "explore must succeed: {}", run.stderr);
assert!(
run.stdout.contains("## Exploration: Counter"),
"explore output must carry the exploration header: {}",
run.stdout
);
assert!(
run.stdout.contains("Counter"),
"explore output must mention the queried symbol: {}",
run.stdout
);
}

#[test]
fn explore_json_envelope_is_valid() {
let dir = TestDir::new("explore-json");
let project = indexed_project(&dir);
let p = project.to_str().unwrap();

let run = run_in(dir.path(), &["explore", "Counter", "-p", p, "--json"]);
assert!(run.ok, "explore --json must succeed: {}", run.stderr);
let v: serde_json::Value = serde_json::from_str(&run.stdout).expect("explore emits JSON");
assert_eq!(v["command"], serde_json::json!("explore"));
assert_eq!(v["isError"], serde_json::json!(false));
assert!(
v["output"].as_str().unwrap().contains("Exploration"),
"explore JSON output must carry the rendered text: {}",
run.stdout
);
}

#[test]
fn node_symbol_returns_source_and_trail() {
let dir = TestDir::new("node-symbol");
let project = indexed_project(&dir);
let p = project.to_str().unwrap();

let run = run_in(dir.path(), &["node", "Counter", "-p", p]);
assert!(run.ok, "node <symbol> must succeed: {}", run.stderr);
assert!(
run.stdout.contains("Counter"),
"node output must name the symbol: {}",
run.stdout
);
assert!(
run.stdout.contains("Location:"),
"node symbol output must carry the location line: {}",
run.stdout
);
}

#[test]
fn node_file_returns_numbered_source() {
let dir = TestDir::new("node-file");
let project = indexed_project(&dir);
let p = project.to_str().unwrap();

let run = run_in(dir.path(), &["node", "src/math.ts", "-p", p]);
assert!(run.ok, "node <file> must succeed: {}", run.stderr);
assert!(
run.stdout.contains("src/math.ts"),
"node file output must name the file: {}",
run.stdout
);
assert!(
run.stdout.contains("export function add"),
"node file output must include the verbatim source: {}",
run.stdout
);
}
Loading
Loading