From bcf67e69f1c98394c3f2e7be8572827a26dd6d02 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 10 Jul 2026 19:09:01 +0800 Subject: [PATCH] feat: complete Godot static-graph reverse edges and add CLI explore/node Addresses four gaps reported by the Godot-team liaison doc, all verified still-broken on 0.28.3 and confirmed static-analysis / tool-consistency concerns (no WorldFlipper DSL or runtime semantics). - Signal callbacks: the string-form `X.connect("sig", callback.bind(...))` now enters callers. `scan_connect` classifies the SECOND argument as the handler (via the existing connect_handler/split_bind_head/callable_handler), matching the object-form `.connect(cb.bind())` behavior. No new subkind. - Resource reverse-impact: `load/preload("res://X.tscn")` resolves to an imports edge whose node lives on the loader, and .tscn/.tres have no file node, so `affected`/`audit --impact` missed the loader. resource_impact and a new dependent_file_paths_via_import_name now also consult imports edges whose target import node normalizes to the changed resource. Query-side, golden-neutral, no new subkind. - Main-scene UID: parse the .tscn `uid="uid://..."` header into a deterministic uid->path map (sorted, first-write-wins) so `project.godot run/main_scene="uid://..."` resolves to the scene file and enters its reverse impact, via the same untagged References path as the res:// form. - CLI parity: add `codegraph explore` and `codegraph node` subcommands that reuse the MCP ExploreSubgraph engine (no fork), so the shell fallback the tool hint documents actually exists. MCP dispatch and tools/list unchanged. Golden .schema byte-stability preserved (the shipped godot fixture has no string-connect / run/main_scene / uid://, so extraction output is unchanged); equivalence and tools_list goldens untouched. --- crates/codegraph-cli/src/main.rs | 130 ++++++++++- .../codegraph-cli/tests/explore_node_cli.rs | 207 ++++++++++++++++++ crates/codegraph-graph/src/graph/mod.rs | 21 ++ .../tests/godot_resource_audit.rs | 121 ++++++++++ crates/codegraph-mcp/src/engine.rs | 13 ++ .../codegraph-resolve/src/frameworks/godot.rs | 6 +- .../src/frameworks/godot_project.rs | 119 +++++++++- .../src/frameworks/godot_scene.rs | 176 ++++++++++++++- .../src/frameworks/godot_script.rs | 199 ++++++++++++++++- crates/codegraph-store/src/queries.rs | 58 +++++ 10 files changed, 1038 insertions(+), 12 deletions(-) create mode 100644 crates/codegraph-cli/tests/explore_node_cli.rs diff --git a/crates/codegraph-cli/src/main.rs b/crates/codegraph-cli/src/main.rs index 566b825b..af0e0d7d 100644 --- a/crates/codegraph-cli/src/main.rs +++ b/crates/codegraph-cli/src/main.rs @@ -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. @@ -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, + /// Max number of files to include source from (clamped 1..=20). + #[arg(long = "max-files")] + max_files: Option, + #[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, + /// 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 { @@ -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, @@ -2600,6 +2644,89 @@ fn cmd_impact( Ok(()) } +fn cmd_explore( + query: String, + path: Option, + max_files: Option, + 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, + 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 ` 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::>() + .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, path: Option, @@ -2627,6 +2754,7 @@ fn cmd_affected( } let mut dependents = store.dependent_file_paths(¤t)?; dependents.extend(store.dependent_file_paths_unresolved(¤t)?); + dependents.extend(store.dependent_file_paths_via_import_name(¤t)?); dependents.sort(); dependents.dedup(); for dependent in dependents { diff --git a/crates/codegraph-cli/tests/explore_node_cli.rs b/crates/codegraph-cli/tests/explore_node_cli.rs new file mode 100644 index 00000000..ef4b560b --- /dev/null +++ b/crates/codegraph-cli/tests/explore_node_cli.rs @@ -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 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 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 + ); +} diff --git a/crates/codegraph-graph/src/graph/mod.rs b/crates/codegraph-graph/src/graph/mod.rs index cba0d26c..5a1d0ecf 100644 --- a/crates/codegraph-graph/src/graph/mod.rs +++ b/crates/codegraph-graph/src/graph/mod.rs @@ -1114,6 +1114,27 @@ impl<'store> GraphTraverser<'store> { } } + for node in self.store.nodes_by_kind(NodeKind::Import)? { + let Some(stripped) = node.name.strip_prefix("res://") else { + continue; + }; + if strip_res_prefix(&normalize_rel(stripped)) != changed { + continue; + } + let import_edges = self + .store + .edges_by_target_kind(&node.id, Some(EdgeKind::Imports))?; + for edge in import_edges { + affected.push(AffectedRef { + from_file: node.file_path.clone(), + line: edge.line.unwrap_or(node.start_line), + edge_kind: edge.kind.as_str().to_string(), + target: changed.clone(), + edge_subkind: edge_metadata_subkind(&edge), + }); + } + } + affected.sort_by(|a, b| { a.from_file .cmp(&b.from_file) diff --git a/crates/codegraph-graph/tests/godot_resource_audit.rs b/crates/codegraph-graph/tests/godot_resource_audit.rs index 89f761b1..e443f4bb 100644 --- a/crates/codegraph-graph/tests/godot_resource_audit.rs +++ b/crates/codegraph-graph/tests/godot_resource_audit.rs @@ -543,6 +543,49 @@ fn main_scene_ref_is_not_tagged_autoload() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn impact_lists_project_godot_for_uid_main_scene() { + // Given a project.godot whose run/main_scene is a uid:// handle, and a + // main.tscn whose gd_scene header carries that same uid, + let dir = unique_dir("impact-uid-main-scene"); + write( + &dir, + "project.godot", + "config_version=5\n\n[application]\nrun/main_scene=\"uid://dr6r06q24gfti\"\n", + ); + write( + &dir, + "main.tscn", + "[gd_scene format=3 uid=\"uid://dr6r06q24gfti\"]\n\n[node name=\"Root\" type=\"Node\"]\n", + ); + // When impact is computed for the main scene, + let store = run_pipeline( + "impact-uid-main-scene", + &dir, + &["project.godot", "main.tscn"], + ); + let impact = GraphTraverser::new(&store) + .resource_impact("main.tscn") + .expect("impact"); + // Then project.godot is listed as a referrer (uid resolved to the scene). + assert!( + impact + .affected + .iter() + .any(|a| a.from_file == "project.godot"), + "uid main_scene must surface project.godot in impact, got: {impact:?}" + ); + // And it is NOT tagged autoload (shares the untagged reference path). + assert!( + !impact + .affected + .iter() + .any(|a| a.edge_subkind == Some("autoload".to_string())), + "uid main-scene ref must NOT be tagged autoload, got: {impact:?}" + ); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn impact_surfaces_gdscript_preload_via_imports_edge() { // Given a .gd that `preload`s another .gd (a resolved `imports` edge tagged @@ -583,6 +626,84 @@ fn impact_surfaces_gdscript_preload_via_imports_edge() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn impact_surfaces_gdscript_preload_of_scene_via_import_node() { + // Given a .gd that `load`s a .tscn scene: the ref RESOLVES to an `import:` + // node (owned by the loader) rather than an edge into a .tscn `file:` node, + // which does not exist for scenes/resources. + let dir = unique_dir("impact-preload-scene"); + write(&dir, "project.godot", PROJECT_GODOT); + write(&dir, "scenes/Foo.tscn", "[gd_scene format=3]\n"); + write( + &dir, + "loader.gd", + "extends Node\n\nfunc _ready():\n\tvar s = load(\"res://scenes/Foo.tscn\")\n", + ); + // When impact is computed for the loaded scene, + let store = run_pipeline( + "impact-preload-scene", + &dir, + &["project.godot", "scenes/Foo.tscn", "loader.gd"], + ); + let impact = GraphTraverser::new(&store) + .resource_impact("scenes/Foo.tscn") + .expect("impact"); + // Then the loading script surfaces via its res:// import node. + let row = impact + .affected + .iter() + .find(|a| a.from_file == "loader.gd") + .unwrap_or_else(|| panic!("expected loader.gd in impact, got: {impact:?}")); + assert_eq!( + row.edge_kind, "imports", + "scene load must surface as an imports edge, got: {row:?}" + ); + assert_eq!( + row.edge_subkind, + Some("gdscript_load_path".to_string()), + "imports edge must carry the gdscript_load_path subkind, got: {row:?}" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn impact_without_preload_resource_edge_is_unchanged_by_the_import_lane() { + // M1 regression: a project with NO `preload/load(res://X)` import node whose + // name matches the changed resource must be byte-identical to the pre-lane + // output. Here `data.tres` references `target.tres` only via an ExtResource + // path (an unresolved-ref lane match) — there is no `import:` node, so the + // new import-name lane must contribute ZERO extra rows. + let dir = unique_dir("impact-no-preload-lane"); + write(&dir, "project.godot", PROJECT_GODOT); + write(&dir, "target.tres", PLAIN_RESOURCE); + write(&dir, "data.tres", &referencing_resource("target.tres")); + let store = run_pipeline( + "impact-no-preload-lane", + &dir, + &["project.godot", "target.tres", "data.tres"], + ); + let impact = GraphTraverser::new(&store) + .resource_impact("target.tres") + .expect("impact"); + // Then every affected row comes from the pre-existing lanes (the ExtResource + // path ref), and NONE is a spurious import-name (`imports`/gdscript_load_path) + // row — the import lane is inert when no matching import node exists. + assert!( + impact.affected.iter().all(|a| a.from_file == "data.tres"), + "only the ExtResource referrer must appear, got: {impact:?}" + ); + assert!( + !impact.affected.iter().any(|a| a.edge_kind == "imports" + || a.edge_subkind == Some("gdscript_load_path".to_string())), + "no preload import node exists, so the import lane must add no rows, got: {impact:?}" + ); + assert!( + !impact.affected.is_empty(), + "the ExtResource path ref must still surface data.tres, got: {impact:?}" + ); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn impact_surfaces_gdscript_extends_path_via_extends_edge() { // Given a .gd that `extends "res://base.gd"` (a resolved `extends` edge diff --git a/crates/codegraph-mcp/src/engine.rs b/crates/codegraph-mcp/src/engine.rs index a8568c77..7e745a35 100644 --- a/crates/codegraph-mcp/src/engine.rs +++ b/crates/codegraph-mcp/src/engine.rs @@ -83,6 +83,19 @@ impl CodeGraphEngine { HashSet::new() } + /// Indexed file paths (repo-relative). Exposed for the CLI `node` + /// subcommand, which uses it to decide whether a bare argument names a file + /// (file-view mode) or a symbol — the CLI has one positional where the MCP + /// tool has separate `file`/`symbol` params. + pub fn indexed_file_paths(&self) -> anyhow::Result> { + Ok(self + .store + .all_files()? + .into_iter() + .map(|f| f.path) + .collect()) + } + // === Tool dispatch =================================================== /// Dispatch by tool name. Mirrors `ToolHandler.execute` switch diff --git a/crates/codegraph-resolve/src/frameworks/godot.rs b/crates/codegraph-resolve/src/frameworks/godot.rs index 898d9018..28686c6c 100644 --- a/crates/codegraph-resolve/src/frameworks/godot.rs +++ b/crates/codegraph-resolve/src/frameworks/godot.rs @@ -240,7 +240,11 @@ impl FrameworkResolver for GodotResolver { project_root: &str, ) -> Option { if godot_project::is_project_godot(file_path) { - return Some(godot_project::parse_project_godot(file_path, content)); + return Some(godot_project::parse_project_godot( + file_path, + content, + project_root, + )); } if godot_scene::is_tscn(file_path) { return Some(godot_scene::parse_tscn(file_path, content)); diff --git a/crates/codegraph-resolve/src/frameworks/godot_project.rs b/crates/codegraph-resolve/src/frameworks/godot_project.rs index 76531800..b26d1ec5 100644 --- a/crates/codegraph-resolve/src/frameworks/godot_project.rs +++ b/crates/codegraph-resolve/src/frameworks/godot_project.rs @@ -74,10 +74,17 @@ pub(crate) fn is_project_godot(file_path: &str) -> bool { pub(crate) fn parse_project_godot( file_path: &str, content: &str, + project_root: &str, ) -> FrameworkResolverExtractionResult { let mut nodes: Vec = Vec::new(); let mut references: Vec = Vec::new(); + // `run/main_scene` may be a `uid://…` (Godot 4.x default) rather than a + // `res://…` path. Resolving it needs the project-wide `uid → .tscn path` + // map, built lazily on first `uid://` main_scene so a project without one + // pays nothing. + let mut scene_uids: Option> = None; + let mut section: Option
= None; // Track whether we are inside a multi-line `key={ ... }` value so its inner // lines are not mistaken for new keys. @@ -119,7 +126,15 @@ pub(crate) fn parse_project_godot( } Section::Application => { if key == "run/main_scene" { - emit_main_scene(file_path, line_no, value, &mut nodes, &mut references); + emit_main_scene( + file_path, + line_no, + value, + project_root, + &mut scene_uids, + &mut nodes, + &mut references, + ); } } Section::Input => { @@ -231,14 +246,25 @@ fn emit_autoload( } /// Emit a main-scene marker node + a `References` edge to the scene path. +/// +/// `run/main_scene` is either a `res://…` path (mapped directly) or, in Godot +/// 4.x by default, a `uid://…` handle that must be resolved through the +/// project-wide scene `uid → path` map (built lazily into `scene_uids` on first +/// need). Either way the emitted edge is an UNTAGGED `References` edge (subkind +/// `None`) — identical to the existing `res://` path, since the reverse-consume +/// lane (`resource_impact`) already surfaces untagged Godot `References` refs by +/// path. A `uid://…` with no mapped scene yields NO edge (unknown-uid → no +/// panic, no guess). fn emit_main_scene( file_path: &str, line_no: i64, value: &str, + project_root: &str, + scene_uids: &mut Option>, nodes: &mut Vec, references: &mut Vec, ) { - let Some(target) = map_res_path(value) else { + let Some(target) = resolve_main_scene(value, project_root, scene_uids) else { return; }; let node = constant_node(file_path, line_no, "main_scene"); @@ -247,6 +273,25 @@ fn emit_main_scene( references.push(reference(node_id, target, line_no, file_path)); } +/// Resolve a `run/main_scene` value to a repo-relative scene path. A `res://…` +/// value maps via the shared [`map_res_path`]; a `uid://…` value is looked up in +/// the lazily-built scene uid map. Any other form yields `None`. +fn resolve_main_scene( + value: &str, + project_root: &str, + scene_uids: &mut Option>, +) -> Option { + if let Some(target) = map_res_path(value) { + return Some(target); + } + let uid = super::godot_common::strip_quotes(value).trim(); + if !uid.starts_with("uid://") { + return None; + } + let map = scene_uids.get_or_insert_with(|| super::godot_scene::scene_uid_map(project_root)); + map.get(uid).cloned() +} + /// Emit a node per input action name (the key). The value (a dictionary /// literal) is intentionally not parsed at L1. fn emit_input_action(file_path: &str, line_no: i64, name: &str, nodes: &mut Vec) { @@ -435,4 +480,74 @@ X=\"res://x.gd\" fn autoload_script_paths_empty_when_no_autoload() { assert!(autoload_script_paths("; comment\nconfig_version=5\n").is_empty()); } + + #[test] + fn resolve_main_scene_maps_res_path_without_uid_map() { + let mut uids: Option> = None; + let got = resolve_main_scene("\"res://main.tscn\"", "", &mut uids); + assert_eq!(got.as_deref(), Some("main.tscn")); + assert!(uids.is_none(), "res:// path must not build the uid map"); + } + + #[test] + fn resolve_main_scene_non_res_non_uid_is_none() { + let mut uids: Option> = None; + assert!(resolve_main_scene("\"user://x.tscn\"", "", &mut uids).is_none()); + assert!(uids.is_none()); + } + + #[test] + fn emit_main_scene_uid_resolves_via_scene_map() { + let dir = std::env::temp_dir().join(format!( + "cg-mainscene-uid-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_nanos() + )); + std::fs::create_dir_all(dir.join("Scenes/MainMenu")).expect("mkdir"); + std::fs::write( + dir.join("Scenes/MainMenu/main_menu.tscn"), + "[gd_scene load_steps=2 format=3 uid=\"uid://abc123\"]\n\n[node name=\"Root\" type=\"Node\"]\n", + ) + .expect("write tscn"); + let root = dir.to_string_lossy().to_string(); + + let content = "config_version=5\n\n[application]\nrun/main_scene=\"uid://abc123\"\n"; + let result = parse_project_godot("project.godot", content, &root); + + assert_eq!(result.references.len(), 1, "one main_scene ref emitted"); + let r = &result.references[0]; + assert_eq!(r.reference_name, "Scenes/MainMenu/main_menu.tscn"); + assert_eq!(r.reference_kind, EdgeKind::References); + assert_eq!( + r.reference_subkind, None, + "uid main_scene ref must be untagged, like the res:// path" + ); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn emit_main_scene_unknown_uid_yields_no_ref() { + let dir = std::env::temp_dir().join(format!( + "cg-mainscene-uid-miss-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_nanos() + )); + std::fs::create_dir_all(&dir).expect("mkdir"); + let root = dir.to_string_lossy().to_string(); + + let content = "config_version=5\n\n[application]\nrun/main_scene=\"uid://missing\"\n"; + let result = parse_project_godot("project.godot", content, &root); + assert!( + result.references.is_empty(), + "unknown uid must emit no ref, got: {:?}", + result.references + ); + std::fs::remove_dir_all(&dir).ok(); + } } diff --git a/crates/codegraph-resolve/src/frameworks/godot_scene.rs b/crates/codegraph-resolve/src/frameworks/godot_scene.rs index 8b9b6b10..7d29e2f6 100644 --- a/crates/codegraph-resolve/src/frameworks/godot_scene.rs +++ b/crates/codegraph-resolve/src/frameworks/godot_scene.rs @@ -60,7 +60,8 @@ //! quote, or an `ExtResource("id")` whose id has no matching `ext_resource` //! declaration is skipped, never panics. An empty file yields an empty result. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; use codegraph_core::node_id::generate_node_id; use codegraph_core::types::{EdgeKind, Language, Node, NodeKind, ReferenceSubkind}; @@ -171,6 +172,96 @@ pub(crate) fn parse_tscn(file_path: &str, content: &str) -> FrameworkResolverExt FrameworkResolverExtractionResult { nodes, references } } +/// Parse the scene's own UID from its `[gd_scene ... uid="uid://…"]` header +/// line. Godot stamps every saved `.tscn` with a stable `uid="uid://"` +/// attribute on the opening `gd_scene` header; this is the id a +/// `project.godot` `run/main_scene="uid://"` (and `[ext_resource +/// uid="uid://…"]` handles) point at. +/// +/// Returns the FULL `uid://` string (scheme kept, matching how it appears in +/// `run/main_scene`), or `None` when the file has no `gd_scene` header or no +/// `uid` attribute. Scans only the header — resource contents are not +/// interpreted (static-format parse only, in scope per the doc). +pub(crate) fn parse_scene_uid(content: &str) -> Option { + for raw_line in content.lines() { + let line = raw_line.trim(); + if line.is_empty() || is_comment(line) { + continue; + } + let header = parse_section_header(line)?; + if header.name != "gd_scene" { + // The first non-blank header of a `.tscn` is always `[gd_scene …]`; + // if the first header is anything else there is no scene uid. + return None; + } + let uid = attr(&header.attrs, "uid")?.trim(); + if uid.is_empty() { + return None; + } + return Some(uid.to_string()); + } + None +} + +/// Build a deterministic `uid://` → repo-relative `.tscn` path map by +/// reading every `.tscn` under `project_root`. +/// +/// Determinism: the discovered files are sorted lexicographically before +/// parsing, and the map is FIRST-WRITE-WINS on a duplicate uid (mirroring the +/// `[autoload]` dup rule in `godot_project::autoload_script_paths`), so the +/// result is independent of directory-iteration order. A file with no +/// `gd_scene`/`uid` header contributes nothing. An empty or unreadable +/// `project_root` yields an empty map. +pub(crate) fn scene_uid_map(project_root: &str) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + if project_root.is_empty() { + return out; + } + let root = Path::new(project_root); + let mut tscn_files: Vec = Vec::new(); + collect_tscn_files(root, &mut tscn_files); + tscn_files.sort(); + for full in tscn_files { + let Ok(rel) = full.strip_prefix(root) else { + continue; + }; + let rel = rel.to_string_lossy().replace('\\', "/"); + let Ok(content) = std::fs::read_to_string(&full) else { + continue; + }; + if let Some(uid) = parse_scene_uid(&content) { + out.entry(uid).or_insert(rel); + } + } + out +} + +/// Recursively collect `.tscn` files under `dir`, skipping the engine-managed +/// `.godot/` cache and any hidden dir (`.git`, etc.). Errors are ignored +/// (tolerant walk); ordering is imposed by the caller's sort. +fn collect_tscn_files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(file_type) = entry.file_type() else { + continue; + }; + if file_type.is_dir() { + let skip = path + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with('.')); + if !skip { + collect_tscn_files(&path, out); + } + } else if is_tscn(&path.to_string_lossy()) { + out.push(path); + } + } +} + /// The scene node a `key = value` block currently belongs to. struct CurrentNode { id: String, @@ -529,3 +620,86 @@ fn quote(unquoted: &str) -> String { let bare = strip_quotes(unquoted); format!("\"{bare}\"") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_scene_uid_reads_gd_scene_header() { + let content = "[gd_scene load_steps=2 format=3 uid=\"uid://dr6r06q24gfti\"]\n\n[node name=\"Root\" type=\"Node\"]\n"; + assert_eq!( + parse_scene_uid(content).as_deref(), + Some("uid://dr6r06q24gfti") + ); + } + + #[test] + fn parse_scene_uid_none_without_uid_attr() { + let content = "[gd_scene format=3]\n\n[node name=\"Root\" type=\"Node\"]\n"; + assert!(parse_scene_uid(content).is_none()); + } + + #[test] + fn parse_scene_uid_none_when_first_header_is_not_gd_scene() { + let content = "[node name=\"Root\" type=\"Node\"]\n"; + assert!(parse_scene_uid(content).is_none()); + } + + fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "cg-sceneuid-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_nanos() + )); + std::fs::create_dir_all(&dir).expect("mkdir"); + dir + } + + #[test] + fn scene_uid_map_maps_uid_to_relative_path() { + let dir = temp_dir("basic"); + std::fs::create_dir_all(dir.join("Scenes")).unwrap(); + std::fs::write( + dir.join("Scenes/menu.tscn"), + "[gd_scene format=3 uid=\"uid://xyz\"]\n", + ) + .unwrap(); + let map = scene_uid_map(&dir.to_string_lossy()); + assert_eq!( + map.get("uid://xyz").map(String::as_str), + Some("Scenes/menu.tscn") + ); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn scene_uid_map_first_write_wins_on_dup_uid() { + let dir = temp_dir("dup"); + std::fs::write( + dir.join("a.tscn"), + "[gd_scene format=3 uid=\"uid://same\"]\n", + ) + .unwrap(); + std::fs::write( + dir.join("b.tscn"), + "[gd_scene format=3 uid=\"uid://same\"]\n", + ) + .unwrap(); + let map = scene_uid_map(&dir.to_string_lossy()); + assert_eq!( + map.get("uid://same").map(String::as_str), + Some("a.tscn"), + "sorted walk + first-write-wins picks the lexicographically first path" + ); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn scene_uid_map_empty_root_is_empty() { + assert!(scene_uid_map("").is_empty()); + } +} diff --git a/crates/codegraph-resolve/src/frameworks/godot_script.rs b/crates/codegraph-resolve/src/frameworks/godot_script.rs index 5f3f028b..ce0a3fa1 100644 --- a/crates/codegraph-resolve/src/frameworks/godot_script.rs +++ b/crates/codegraph-resolve/src/frameworks/godot_script.rs @@ -407,11 +407,17 @@ fn scan_call_with_string_arg( } } -/// `X.connect(handler)` / `sig.timeout.connect(_on_timeout)` — the handler is the -/// FIRST argument and is normally a bare identifier (a method reference), not a -/// quoted string. A literal identifier first arg → reference to the handler NAME -/// ([`EdgeKind::Calls`]); a call-expression or non-identifier first arg → -/// dynamic-unresolved sentinel. +/// `X.connect(handler)` / `sig.timeout.connect(_on_timeout)` — the Godot 4 +/// signal-as-object form, where the handler is the FIRST argument (a bare method +/// reference, not a quoted string). +/// +/// Also handles the STRING 2-arg form `X.connect("", )` (the +/// classic `Object.connect(signal_name, callable)` API): when the FIRST arg is a +/// string literal (the signal NAME), the handler is the SECOND arg. That second +/// arg is classified by the SAME [`connect_handler`] used for the object form, so +/// both emit the identical [`EdgeKind::Calls`] edge shape (a literal identifier +/// handler → reference to the handler NAME; a call-expression / non-identifier / +/// cross-object callable → dynamic-unresolved sentinel). fn scan_connect(file_path: &str, line_no: i64, line: &str, from: &str, out: &mut Vec) { let mut search_from = 0usize; while let Some(rel) = line[search_from..].find(".connect(") { @@ -419,8 +425,17 @@ fn scan_connect(file_path: &str, line_no: i64, line: &str, from: &str, out: &mut let after = dot + ".connect(".len(); search_from = after; let args = &line[after..]; - let target = first_arg(args); - match connect_handler(target) { + let first = first_arg(args); + // The classic string 2-arg form `connect("", )`: a + // string-literal FIRST arg is the signal NAME, so the handler is the + // SECOND arg. The object form `connect()` has a non-string first + // arg and remains the handler itself. Route the correct arg through the + // shared `connect_handler` so both forms emit the same edge shape. + let handler_arg = match literal_or_dynamic(first) { + ArgKind::Literal(_) => second_arg(args), + ArgKind::Dynamic => first, + }; + match connect_handler(handler_arg) { ArgKind::Literal(name) if !name.is_empty() => { out.push(reference(from, name, EdgeKind::Calls, line_no, file_path)); } @@ -808,6 +823,42 @@ fn first_arg(args: &str) -> &str { args.trim() } +/// Extract the SECOND argument substring from a call's argument list (the text +/// after the opening `(`). Skips the first arg up to the top-level `,`, then +/// returns the next arg via [`first_arg`] on the remainder. Empty when there is +/// no second argument. Paren/quote depth is tracked exactly like [`first_arg`] so +/// a nested call/array/string in the first arg does not split it early. +fn second_arg(args: &str) -> &str { + let bytes = args.as_bytes(); + let mut depth = 0i32; + let mut in_str = false; + let mut i = 0usize; + while i < bytes.len() { + let b = bytes[i]; + if in_str { + if b == b'"' { + in_str = false; + } + i += 1; + continue; + } + match b { + b'"' => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + if depth == 0 { + return ""; + } + depth -= 1; + } + b',' if depth == 0 => return first_arg(&args[i + 1..]), + _ => {} + } + i += 1; + } + "" +} + /// Parse a `func (...)` header → the function name. Returns `None` for any /// line that is not a function header. Handles `static func`, leading /// annotations are on their own line so not considered here. @@ -1027,6 +1078,140 @@ mod tests { assert_eq!(out[0].reference_kind, EdgeKind::Calls); } + // ---- scan_connect: object-form REGRESSION GUARD (m1) ---- + // These pin the pre-existing non-string `.connect()` classifications + // as byte-identical after adding the string 2-arg branch: the string-form + // change must NOT alter the object-form output. + + #[test] + fn scan_connect_object_form_bind_head_unchanged() { + // `sig.connect(cb.bind(x))` — object form, bind-head handler. The first + // arg is NOT a string, so the branch keeps it as the handler; classifies + // to the bind head `cb`. Byte-identical to before the string-form edit. + let mut out = Vec::new(); + scan_connect( + "a.gd", + 5, + "\tsig.connect(_on_died.bind(c))", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, "_on_died"); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + #[test] + fn scan_connect_object_form_callable_self_unchanged() { + // `sig.connect(Callable(self, "m"))` — object form, Callable handler. The + // first arg starts with `Callable(`, not a string literal, so it stays the + // handler and resolves to the method name. Guard against regression. + let mut out = Vec::new(); + scan_connect( + "a.gd", + 6, + "\tsig.connect(Callable(self, \"_on_pressed\"))", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, "_on_pressed"); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + // ---- scan_connect: NEW string 2-arg form `connect("", )` ---- + + #[test] + fn scan_connect_string_form_bind_handler_is_literal() { + // `wp.connect("destroyed", _on_x.bind(wp))` — the string first arg is the + // signal name, so the handler is the SECOND arg; its bind head `_on_x` + // resolves to a literal Calls reference (same edge as the object form). + let mut out = Vec::new(); + scan_connect( + "a.gd", + 7, + "\twp.connect(\"destroyed\", _on_x.bind(wp))", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, "_on_x"); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + #[test] + fn scan_connect_string_form_bare_ident_handler_is_literal() { + // `b.connect("pressed", _on_y)` — bare-ident second-arg handler. + let mut out = Vec::new(); + scan_connect( + "a.gd", + 8, + "\tb.connect(\"pressed\", _on_y)", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, "_on_y"); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + #[test] + fn scan_connect_string_form_call_expr_handler_is_dynamic() { + // `o.connect("sig", some_expr())` — the second-arg handler is a call + // expression → dynamic sentinel (determinism contract preserved). + let mut out = Vec::new(); + scan_connect( + "a.gd", + 9, + "\to.connect(\"sig\", some_expr())", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, dynamic_name("connect")); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + #[test] + fn scan_connect_string_form_cross_object_callable_is_dynamic() { + // `o.connect("sig", Callable(other, "m"))` — a cross-object callable + // second-arg handler stays dynamic (non-self/this receiver). + let mut out = Vec::new(); + scan_connect( + "a.gd", + 10, + "\to.connect(\"sig\", Callable(other, \"m\"))", + "file:a.gd", + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].reference_name, dynamic_name("connect")); + assert_eq!(out[0].reference_kind, EdgeKind::Calls); + } + + // ---- second_arg: extraction primitive ---- + + #[test] + fn second_arg_plain() { + assert_eq!( + second_arg("\"destroyed\", _on_x.bind(wp))"), + "_on_x.bind(wp)" + ); + } + + #[test] + fn second_arg_none_when_single_arg() { + // No top-level comma → no second argument → empty. + assert_eq!(second_arg("_on_timeout)"), ""); + } + + #[test] + fn second_arg_ignores_comma_inside_first_arg() { + // A comma nested in the first arg's parens/string must not split early. + assert_eq!(second_arg("f(a, b), _on_y)"), "_on_y"); + assert_eq!(second_arg("\"a,b\", _on_y)"), "_on_y"); + } + // ---- connect_handler: every classification arm ---- #[test] diff --git a/crates/codegraph-store/src/queries.rs b/crates/codegraph-store/src/queries.rs index 1cea8452..9313a422 100644 --- a/crates/codegraph-store/src/queries.rs +++ b/crates/codegraph-store/src/queries.rs @@ -1042,6 +1042,34 @@ impl Store { Ok(out) } + /// Godot loader-side reverse-dependency lane. A GDScript + /// `preload/load("res://X")` RESOLVES to an `import:` node whose `name` is the + /// `res://` path and whose `file_path` is the LOADER script. When `X` is a + /// scene/resource it owns no `file:` node, so the resolved `imports` edge + /// terminates on that `import:` node and `dependent_file_paths` (which keys on + /// a target `file:` node) never surfaces the loader. This matches `import:` + /// nodes whose `res://`-stripped, `/`-normalized name equals `file_path` and + /// returns their owning loader paths. Only names carrying the `res://` scheme + /// match, so non-Godot import nodes are never returned and other languages stay + /// byte-unchanged. Golden-neutral; returns referrers in scan order (caller + /// sorts/dedups). + pub fn dependent_file_paths_via_import_name( + &self, + file_path: &str, + ) -> rusqlite::Result> { + let target = file_path.replace('\\', "/"); + let mut out = Vec::new(); + for node in self.nodes_by_kind(NodeKind::Import)? { + let Some(stripped) = node.name.strip_prefix("res://") else { + continue; + }; + if stripped.replace('\\', "/") == target { + out.push(node.file_path); + } + } + Ok(out) + } + /// Delete every resolution-produced edge whose SOURCE node lives in /// `file_path`. Every non-`contains` edge is produced by reference resolution /// (it carries `metadata.resolvedBy`); `contains` edges come only from @@ -2439,6 +2467,36 @@ mod tests { ); } + #[test] + fn dependent_file_paths_via_import_name_surfaces_res_loaders_only() { + let mut store = store("import-name-loaders"); + let mut scene_loader = node("import:scene", "res://Scenes/BaseStage.tscn", "loader.gd"); + scene_loader.kind = NodeKind::Import; + let mut other_loader = node("import:other", "res://Scenes/Other.tscn", "other.gd"); + other_loader.kind = NodeKind::Import; + let mut bare_import = node("import:bare", "Scenes/BaseStage.tscn", "bare.gd"); + bare_import.kind = NodeKind::Import; + store + .upsert_nodes(&[scene_loader, other_loader, bare_import]) + .unwrap(); + + let mut referrers = store + .dependent_file_paths_via_import_name("Scenes/BaseStage.tscn") + .unwrap(); + referrers.sort(); + assert_eq!( + referrers, + vec!["loader.gd".to_string()], + "only the res://-scheme import node whose name equals the target surfaces its loader" + ); + assert!( + store + .dependent_file_paths_via_import_name("Scenes/Missing.tscn") + .unwrap() + .is_empty() + ); + } + #[test] fn delete_resolved_edges_and_named_target_sources() { let mut store = store("resolved-edges");