From 58f66f46da73684816235845ee4a6ac7e807c8a8 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 27 Nov 2026 15:20:54 +0800 Subject: [PATCH] fix(mcp): ask the user before initializing a project that has no index An agent that met a project without an index was told to build one itself. The no-project tool text said "run `codegraph init` there" or "run `codegraph init` in the project", and the server instructions only said to offer `codegraph init .` without saying that the user decides (sunerpy/codegraph-rust#269). The no-default text and the explicit-projectPath error now say: if the project has no CodeGraph index yet, tell the user so, offer to run `codegraph init .` in the project directory, and do not run it without the user's consent. The rest of each message (projectPath, --path, the truncated-scan note) is unchanged, and the text that lists indexed sub-projects still does not mention init. The Limitations bullet of the server instructions gives the same rule, so the instructions string of reference/golden/mcp/initialize.json changes in that one bullet and is recorded in the new v0.56.1 regeneration log of docs/equivalence.md. docs/mcp.md describes the rule. The skill told agents to follow the recovery command a CLI command prints, which for a project without an index is `codegraph init`; it now says that case is the user's decision. Verified: the new tests in roots.rs and instructions.rs, the extended server.rs, rmcp_handler.rs, rmcp_roots.rs and codegraph-rs http_serve tests, golden_mcp and rmcp_parity all failed on the old text and pass now. cargo test -p codegraph-mcp --locked passes (548 tests). The codegraph-rs http_serve, rmcp_serve_direct, zed_bare_serve, batch_m_failed_open_recovery and skill_install tests and the embedded skill unit tests pass. Clippy with -D warnings passes on codegraph-mcp and codegraph-rs. scripts/regen-goldens.sh --check with the release codegraph and bench binaries of this tree reports all 32 corpora identical. A stdio session of the release binary in an unindexed directory returns the new text for both cases. --- crates/codegraph-cli/tests/http_serve.rs | 5 ++ crates/codegraph-mcp/src/instructions.rs | 38 +++++++++++++- crates/codegraph-mcp/src/rmcp_handler.rs | 5 ++ crates/codegraph-mcp/src/roots.rs | 65 +++++++++++++++++++++++- crates/codegraph-mcp/src/server.rs | 10 ++++ crates/codegraph-mcp/tests/rmcp_roots.rs | 10 ++++ docs/equivalence.md | 8 +++ docs/mcp.md | 7 +++ reference/golden/mcp/initialize.json | 2 +- skills/codegraph/SKILL.md | 5 ++ 10 files changed, 151 insertions(+), 4 deletions(-) diff --git a/crates/codegraph-cli/tests/http_serve.rs b/crates/codegraph-cli/tests/http_serve.rs index aba6fcc9..ff4e00dc 100644 --- a/crates/codegraph-cli/tests/http_serve.rs +++ b/crates/codegraph-cli/tests/http_serve.rs @@ -390,6 +390,11 @@ fn serve_http_global_without_projectpath_returns_actionable_error() { resp.contains("No indexed project resolved"), "global mode without projectPath must return the actionable resolve error: {resp}" ); + assert!( + resp.contains("offer to run `codegraph init .`") + && resp.contains("do not run it without the user's consent"), + "the error offers init and asks for the user's consent (#269): {resp}" + ); } /// Spawn `serve --http --path ` with `CODEGRAPH_DEBUG` set to `debug` diff --git a/crates/codegraph-mcp/src/instructions.rs b/crates/codegraph-mcp/src/instructions.rs index be872264..902c17fe 100644 --- a/crates/codegraph-mcp/src/instructions.rs +++ b/crates/codegraph-mcp/src/instructions.rs @@ -11,6 +11,12 @@ //! can never drift from what the binary actually parses. Upstream hardcodes a //! "30+" prose count; a copied number would silently go stale the next time a //! grammar lands. +//! +//! The Limitations bullet for a project without an index is this repository's +//! own wording as well (sunerpy/codegraph-rust#269): the agent tells the user, +//! offers `codegraph init .`, and runs it only with the user's consent. Upstream +//! (`461a5d87`) instead tells the agent to stop calling codegraph tools for that +//! project and never to run `codegraph init` itself. use codegraph_core::types::Language; use std::sync::OnceLock; @@ -107,7 +113,7 @@ typically one to a few calls; a grep/read exploration is dozens. ## Limitations -- If a tool reports the project isn't initialized, `.codegraph/` doesn't exist yet — offer to run `codegraph init .` to build the index. +- If a tool reports the project isn't initialized (no `.codegraph/` directory), tell the user the project has no CodeGraph index yet, offer to run `codegraph init .` to build it, and do not run it without the user's consent. - Index lags file writes by ~1 second. A burst of many changes (a branch switch, a mass rename) or a sign that the OS dropped file events makes the watcher re-scan the whole project on its own, and responses can start with "⚠️ CodeGraph auto-sync is RECOVERING" until that catch-up commits. Renames never need a rebuild: `codegraph sync` reconciles the whole project when no watcher is running. - Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates. - Explore matches names and indexed code words lexically, not by meaning; an empty result reports word matches and may suggest indexed candidate names to retry with `codegraph_explore`. @@ -196,4 +202,34 @@ mod tests { "single trailing newline" ); } + + /// sunerpy/codegraph-rust#269: when a tool reports a project without an + /// index, the agent tells the user and offers `codegraph init .`, and does + /// not run it without the user's consent. + #[test] + fn instructions_offer_init_only_with_the_users_consent() { + let text = server_instructions(); + let bullet = text + .lines() + .find(|line| line.contains("isn't initialized")) + .expect("the Limitations section covers a project without an index"); + assert!( + bullet.contains("tell the user the project has no CodeGraph index yet"), + "{bullet}" + ); + assert!( + bullet.contains("offer to run `codegraph init .`"), + "{bullet}" + ); + assert!( + bullet.contains("do not run it without the user's consent"), + "{bullet}" + ); + assert!( + !text + .replace("offer to run `codegraph init .`", "") + .contains("codegraph init"), + "every mention of `codegraph init` must be an offer" + ); + } } diff --git a/crates/codegraph-mcp/src/rmcp_handler.rs b/crates/codegraph-mcp/src/rmcp_handler.rs index eb4e768d..f6fec17e 100644 --- a/crates/codegraph-mcp/src/rmcp_handler.rs +++ b/crates/codegraph-mcp/src/rmcp_handler.rs @@ -1543,6 +1543,11 @@ mod handler_tests { text.contains("No indexed project found for projectPath"), "bad-projectPath message, got: {text}" ); + assert!( + text.contains("offer to run `codegraph init .`") + && text.contains("do not run it without the user's consent"), + "the error offers init and asks for the user's consent (#269), got: {text}" + ); let _ = client.cancel().await; let _ = task.await; }); diff --git a/crates/codegraph-mcp/src/roots.rs b/crates/codegraph-mcp/src/roots.rs index 5dda1790..4f6dd86e 100644 --- a/crates/codegraph-mcp/src/roots.rs +++ b/crates/codegraph-mcp/src/roots.rs @@ -483,6 +483,11 @@ pub(crate) fn format_subproject_candidates(base: Option<&Path>, roots: &[PathBuf display.join(", ") } +/// What a tool response says about a project that may have no index yet: +/// creating one is the user's decision, so the agent offers `codegraph init .` +/// and never runs it on its own (sunerpy/codegraph-rust#269). +const ASK_BEFORE_INIT: &str = "If the project has no CodeGraph index yet, tell the user so, offer to run `codegraph init .` in the project directory, and do not run it without the user's consent."; + pub(crate) fn not_indexed_message( raw_project: Option<&str>, search_from: Option<&Path>, @@ -491,11 +496,13 @@ pub(crate) fn not_indexed_message( ) -> String { if let Some(raw) = raw_project { return format!( - "No indexed project found for projectPath {raw:?}. Pass an absolute path to an indexed project, or run `codegraph init` there." + "No indexed project found for projectPath {raw:?}. Pass an absolute path to an indexed project. {ASK_BEFORE_INIT}" ); } let mut message = if candidates.is_empty() { - "No indexed project resolved. Pass a `projectPath` argument, run `codegraph init` in the project, or start the server with `--path `.".to_string() + format!( + "No indexed project resolved. Pass a `projectPath` argument, or start the server with `--path `. {ASK_BEFORE_INIT}" + ) } else { let listed = format_subproject_candidates(search_from, candidates); format!( @@ -1645,6 +1652,60 @@ mod tests { ); } + /// sunerpy/codegraph-rust#269: creating an index is the user's decision. + /// A message that mentions `codegraph init` only offers it, and tells the + /// agent to say the project has no index and to wait for the user's + /// consent; the rest of each message stays as it was. + #[test] + fn not_indexed_messages_offer_init_only_with_the_users_consent() { + let explicit = not_indexed_message(Some("/no/such/project"), None, &[], false); + let unresolved = not_indexed_message(None, None, &[], false); + let truncated = not_indexed_message(None, None, &[], true); + for message in [&explicit, &unresolved, &truncated] { + assert!( + message.contains("has no CodeGraph index yet, tell the user"), + "{message}" + ); + assert!( + message.contains("offer to run `codegraph init .`"), + "{message}" + ); + assert!( + message.contains("do not run it without the user's consent"), + "{message}" + ); + assert!( + !message + .replace("offer to run `codegraph init .`", "") + .contains("codegraph init"), + "every mention of `codegraph init` must be an offer: {message}" + ); + } + assert!( + explicit.starts_with("No indexed project found for projectPath \"/no/such/project\"."), + "{explicit}" + ); + assert!( + explicit.contains("Pass an absolute path to an indexed project"), + "{explicit}" + ); + assert!( + unresolved.starts_with("No indexed project resolved."), + "{unresolved}" + ); + assert!( + unresolved.contains("`projectPath`") && unresolved.contains("`--path `"), + "{unresolved}" + ); + assert!(truncated.contains("stopped after"), "{truncated}"); + + // With indexed sub-projects to choose from, the message names them and + // does not bring up `codegraph init` at all. + let base = Path::new("/workspace"); + let listed = not_indexed_message(None, Some(base), &[base.join("service-a")], false); + assert!(!listed.contains("codegraph init"), "{listed}"); + } + #[test] fn subproject_scan_caps_candidates_at_sixty_four() { let workspace = unindexed_dir("subscan-cap"); diff --git a/crates/codegraph-mcp/src/server.rs b/crates/codegraph-mcp/src/server.rs index 92b8bab0..593761cd 100644 --- a/crates/codegraph-mcp/src/server.rs +++ b/crates/codegraph-mcp/src/server.rs @@ -1329,6 +1329,11 @@ mod tests { text.contains("No indexed project resolved"), "unresolved (raw=None) message, got: {text}" ); + assert!( + text.contains("offer to run `codegraph init .`") + && text.contains("do not run it without the user's consent"), + "the guidance offers init and asks for the user's consent (#269), got: {text}" + ); } #[test] @@ -1352,6 +1357,11 @@ mod tests { text.contains("No indexed project found for projectPath"), "raw-project message, got: {text}" ); + assert!( + text.contains("offer to run `codegraph init .`") + && text.contains("do not run it without the user's consent"), + "the error offers init and asks for the user's consent (#269), got: {text}" + ); } #[test] diff --git a/crates/codegraph-mcp/tests/rmcp_roots.rs b/crates/codegraph-mcp/tests/rmcp_roots.rs index 0b9cc7e0..ef4c044b 100644 --- a/crates/codegraph-mcp/tests/rmcp_roots.rs +++ b/crates/codegraph-mcp/tests/rmcp_roots.rs @@ -242,6 +242,11 @@ fn rmcp_does_not_adopt_unindexed_client_root() { text.contains("No indexed project"), "unindexed client root must NOT be adopted; expected no-project guidance, got: {text}" ); + assert!( + text.contains("offer to run `codegraph init .`") + && text.contains("do not run it without the user's consent"), + "the guidance offers init and asks for the user's consent (#269), got: {text}" + ); let _ = client.cancel().await; let _ = server_task.await; @@ -299,6 +304,11 @@ fn rmcp_http_no_roots_never_adopts() { text.contains("No indexed project"), "http no_roots mode must NOT adopt the client's indexed root: {text}" ); + assert!( + text.contains("offer to run `codegraph init .`") + && text.contains("do not run it without the user's consent"), + "the HTTP guidance offers init and asks for the user's consent (#269), got: {text}" + ); let _ = client.cancel().await; let _ = server_task.await; diff --git a/docs/equivalence.md b/docs/equivalence.md index 7f9c84c3..4ef5094f 100644 --- a/docs/equivalence.md +++ b/docs/equivalence.md @@ -292,6 +292,14 @@ The golden changes of the v0.56.0 follow-up program, in commit order. | `feat(resolve): Erlang behaviours, macros, escripts and application resource files` | erlang | `edges.json`, `colby.db` | a macro use links its `-define` (upstream #1168): `m.erl`'s `g/0` gains `references` to the constant `m::X` for `?X` (16:20, `exact-match` 0.9); the corpus has no `-behaviour`, variable-module call, escript or application resource file, so the `implements` rule, the `erlang-behaviour` pass and the resource-tuple references move nothing (`bench --graph-diff` of the committed and regenerated goldens: 1 added row, 0 removed; every other corpus is identical under `--check`) | `scripts/regen-goldens.sh --write erlang` | | `feat(explore): gather the subgraph the way upstream walks it` | mcp | `codegraph_explore.json` | explore's search takes upstream's high-value kinds only (`findRelevantContext`'s default node kinds), so on the mini fixture the import `./math` and the property `value` no longer seed or join the gathered subgraph: the text's `Found 7 symbols across 2 files.` becomes `Found 5 symbols across 2 files.` and the `src/math.ts` header loses `value(property)`; no extraction golden moves | re-captured from the Rust output (OD-4) | +#### v0.56.1 regeneration log + +The golden changes of the v0.56.1 maintenance patch, in commit order. + +| Commit | Corpus | Artifacts | Intent | Command | +| ------------------------------------------------------------------------ | ------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `fix(mcp): ask the user before initializing a project that has no index` | mcp | `initialize.json` | when a tool reports the project isn't initialized, the server instructions now have the agent tell the user the project has no CodeGraph index yet, offer to run `codegraph init .`, and not run it without the user's consent; before, they only said to offer it (sunerpy/codegraph-rust#269); the fixture's `instructions` string changes in that one bullet, the rest of the fixture is unchanged, and no graph artifact moves | edited with `crates/codegraph-mcp/src/instructions.rs`; `cargo test -p codegraph-mcp --locked --test golden_mcp --test rmcp_parity` requires the instructions byte-identical | + The canonicalizer strips inherently unstable timestamp columns (`nodes.updated_at`, `files.modified_at`, `files.indexed_at`), parses JSON text columns before re-serializing them with deterministic key order, asserts all diff --git a/docs/mcp.md b/docs/mcp.md index f37ca87f..0335b09a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -744,6 +744,13 @@ probe runs again on relevant requests, while the downward scan is throttled to once per five seconds so a project initialized after server startup can be adopted without walking the workspace on every call. +The no-default text and the explicit-path error never tell the agent to run +`codegraph init` on its own. Where one mentions it, it says that if the project +has no CodeGraph index yet, the agent should tell the user so, offer to run +`codegraph init .` in the project directory, and not run it without the user's +consent. The server instructions in the `initialize` response give the same +rule. + For an explicit path that **does** resolve to an existing index, the first call is also the live-service boundary: it waits for catch-up and retains that project's shared daemon/watcher as described above. Query routing therefore does diff --git a/reference/golden/mcp/initialize.json b/reference/golden/mcp/initialize.json index f74dfc4a..5a63404d 100644 --- a/reference/golden/mcp/initialize.json +++ b/reference/golden/mcp/initialize.json @@ -24,7 +24,7 @@ "name": "codegraph", "version": "0.12.0" }, - "instructions": "# Codegraph — code intelligence over an indexed knowledge graph\n\nCodegraph is a SQLite knowledge graph of every symbol, edge, and file in\nthe workspace — pre-computed structure you would otherwise re-derive by\nreading files (cached intelligence: thousands of parse/trace decisions you\ndon't pay to re-reason each run). Reads are sub-millisecond; the index lags\nwrites by ~1s through the file watcher. Reach for it BEFORE *and* while\nwriting or editing code — not just for questions: one call returns the\nverbatim source PLUS who calls it and what it affects, so you edit with the\nblast radius in view. More accurate context, in far fewer tokens and\nround-trips than reading files yourself.\n\n## Use codegraph instead of reading files — for questions AND edits\n\nWhether you're answering \"how does X work\" or implementing a change (fixing\na bug, adding a feature), reach for codegraph before you Read. For\nunderstanding, answer DIRECTLY — usually with ONE `codegraph_explore` call.\n`codegraph_explore` takes either a natural-language question or a bag of\nsymbol/file names and returns the verbatim source of the relevant symbols\ngrouped by file, so it is Read-equivalent and most often the ONLY\ncodegraph call you need. Codegraph IS the pre-built search index — so\ndelegating the lookup to a separate file-reading sub-task/agent, or\nrunning your own grep + read loop, repeats work codegraph already did and\ncosts more for the same answer. Reach for raw Read/Grep only to confirm a\nspecific detail codegraph didn't cover. A direct codegraph answer is\ntypically one to a few calls; a grep/read exploration is dozens.\n\n## Tool selection by intent\n\n- **Almost any question — \"how does X work\", architecture, a bug, \"what/where is X\", or surveying an area** → `codegraph_explore` (PRIMARY — call FIRST; ONE capped call returns the verbatim source of the relevant symbols grouped by file; most often the ONLY call you need)\n- **\"How does X reach/become Y? / the flow / the path from X to Y\"** → `codegraph_explore`, naming the symbols that span the flow (e.g. `mutateElement renderScene`) — it surfaces the call path among them, including dynamic-dispatch hops (callbacks, React re-render, JSX children) grep can't follow\n- **\"What is the symbol named X?\" (just its location)** → `codegraph_search`\n- **\"What calls this?\" / \"What does this call?\" / \"What would changing this break?\"** → `codegraph_callers` / `codegraph_callees` / `codegraph_impact`\n- **Reading a source FILE (any time you'd use the `Read` tool)** → `codegraph_node` with a `file` path and no `symbol`. It returns the file's **current source with line numbers — the same `\\t` shape `Read` gives you, safe to `Edit` from** — narrowable with `offset`/`limit` exactly like `Read`, PLUS a one-line note of which files depend on it. Same bytes as `Read`, faster (served from the index), with the blast radius attached. Use it **instead of `Read`** for indexed source files; fall back to `Read` only for what codegraph doesn't index (configs, docs). Pass `symbolsOnly: true` for just the file's structure.\n- **About to read or edit a symbol you can name (or whose exact node ID you have)** → `codegraph_node` with that `symbol` (SECONDARY — the after-explore depth tool): the verbatim source (`includeCode: true`) PLUS its caller/callee trail, so before changing it you see what calls it and what your edit would break. For an OVERLOADED name it returns EVERY matching definition's body in one call, so you never Read a file to find the right overload\n- **\"What's in directory X?\"** → `codegraph_files`\n- **\"Is the index ready / what's its size?\"** → `codegraph_status`\n\n## Common chains\n\n- **Flow / \"how does X reach Y\"**: ONE `codegraph_explore` with the symbol names spanning the flow — it surfaces the call path among them (riding dynamic-dispatch hops) AND returns their source. No need to reconstruct the path with `codegraph_search` + `codegraph_callers`.\n- **Onboarding / understanding any area**: ONE `codegraph_explore` is usually the whole answer. Only follow up — `codegraph_node` for a specific symbol — if something is still unclear.\n- **Refactor planning**: `codegraph_search` → `codegraph_callers` → `codegraph_impact`. The blast-radius answer comes from impact, not from walking callers manually.\n- **Debugging a regression**: `codegraph_callers` of the suspected symbol; widen with `codegraph_impact` if an unexpected call appears.\n\n## Anti-patterns\n\n- **Trust codegraph's results — don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.\n- **Don't grep first** when looking up a symbol by name — `codegraph_search` is faster and returns kind + location + signature.\n- **Don't chain `codegraph_search` + `codegraph_node`** to understand an area — ONE `codegraph_explore` returns the relevant symbols' source together in a single round-trip.\n- **Don't loop `codegraph_node` over many symbols** — one `codegraph_explore` call returns them all grouped by file, while each separate call re-reads the whole context and costs far more. Use `codegraph_node` for a single symbol.\n- **Don't reach for the `Read` tool on an indexed source file** — `codegraph_node` with a `file` reads it for you (same `\\t` source, `offset`/`limit` like Read, faster, with its blast radius), and with a `symbol` it returns the source plus the caller/callee trail. Reach for raw `Read` only for what codegraph doesn't index (configs, docs) or when the staleness banner flags a file as pending re-index.\n- **After editing, check the staleness banner.** When a tool response starts with \"⚠️ Some files referenced below were edited since the last index sync…\", the listed files are pending re-index — Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust codegraph. `codegraph_status` also lists pending files under \"Pending sync\".\n\n## Limitations\n\n- If a tool reports the project isn't initialized, `.codegraph/` doesn't exist yet — offer to run `codegraph init .` to build the index.\n- Index lags file writes by ~1 second. A burst of many changes (a branch switch, a mass rename) or a sign that the OS dropped file events makes the watcher re-scan the whole project on its own, and responses can start with \"⚠️ CodeGraph auto-sync is RECOVERING\" until that catch-up commits. Renames never need a rebuild: `codegraph sync` reconciles the whole project when no watcher is running.\n- Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.\n- Explore matches names and indexed code words lexically, not by meaning; an empty result reports word matches and may suggest indexed candidate names to retry with `codegraph_explore`.\n- No live correctness validation — that's still the TypeScript compiler / test suite / linter's job. Codegraph supplements those with structural context they don't have.\n\n## Supported languages\n\nCodegraph extracts these 38 languages (typescript, javascript, tsx, jsx, arkts, python, go, rust, java, c, cpp, csharp, razor, php, ruby, swift, kotlin, dart, svelte, vue, astro, liquid, pascal, scala, lua, luau, objc, r, solidity, nix, terraform, erlang, cfml, yaml, twig, xml, properties, gdscript). A file outside this set is not indexed, so no codegraph tool can see it — reach for Read there.\n" + "instructions": "# Codegraph — code intelligence over an indexed knowledge graph\n\nCodegraph is a SQLite knowledge graph of every symbol, edge, and file in\nthe workspace — pre-computed structure you would otherwise re-derive by\nreading files (cached intelligence: thousands of parse/trace decisions you\ndon't pay to re-reason each run). Reads are sub-millisecond; the index lags\nwrites by ~1s through the file watcher. Reach for it BEFORE *and* while\nwriting or editing code — not just for questions: one call returns the\nverbatim source PLUS who calls it and what it affects, so you edit with the\nblast radius in view. More accurate context, in far fewer tokens and\nround-trips than reading files yourself.\n\n## Use codegraph instead of reading files — for questions AND edits\n\nWhether you're answering \"how does X work\" or implementing a change (fixing\na bug, adding a feature), reach for codegraph before you Read. For\nunderstanding, answer DIRECTLY — usually with ONE `codegraph_explore` call.\n`codegraph_explore` takes either a natural-language question or a bag of\nsymbol/file names and returns the verbatim source of the relevant symbols\ngrouped by file, so it is Read-equivalent and most often the ONLY\ncodegraph call you need. Codegraph IS the pre-built search index — so\ndelegating the lookup to a separate file-reading sub-task/agent, or\nrunning your own grep + read loop, repeats work codegraph already did and\ncosts more for the same answer. Reach for raw Read/Grep only to confirm a\nspecific detail codegraph didn't cover. A direct codegraph answer is\ntypically one to a few calls; a grep/read exploration is dozens.\n\n## Tool selection by intent\n\n- **Almost any question — \"how does X work\", architecture, a bug, \"what/where is X\", or surveying an area** → `codegraph_explore` (PRIMARY — call FIRST; ONE capped call returns the verbatim source of the relevant symbols grouped by file; most often the ONLY call you need)\n- **\"How does X reach/become Y? / the flow / the path from X to Y\"** → `codegraph_explore`, naming the symbols that span the flow (e.g. `mutateElement renderScene`) — it surfaces the call path among them, including dynamic-dispatch hops (callbacks, React re-render, JSX children) grep can't follow\n- **\"What is the symbol named X?\" (just its location)** → `codegraph_search`\n- **\"What calls this?\" / \"What does this call?\" / \"What would changing this break?\"** → `codegraph_callers` / `codegraph_callees` / `codegraph_impact`\n- **Reading a source FILE (any time you'd use the `Read` tool)** → `codegraph_node` with a `file` path and no `symbol`. It returns the file's **current source with line numbers — the same `\\t` shape `Read` gives you, safe to `Edit` from** — narrowable with `offset`/`limit` exactly like `Read`, PLUS a one-line note of which files depend on it. Same bytes as `Read`, faster (served from the index), with the blast radius attached. Use it **instead of `Read`** for indexed source files; fall back to `Read` only for what codegraph doesn't index (configs, docs). Pass `symbolsOnly: true` for just the file's structure.\n- **About to read or edit a symbol you can name (or whose exact node ID you have)** → `codegraph_node` with that `symbol` (SECONDARY — the after-explore depth tool): the verbatim source (`includeCode: true`) PLUS its caller/callee trail, so before changing it you see what calls it and what your edit would break. For an OVERLOADED name it returns EVERY matching definition's body in one call, so you never Read a file to find the right overload\n- **\"What's in directory X?\"** → `codegraph_files`\n- **\"Is the index ready / what's its size?\"** → `codegraph_status`\n\n## Common chains\n\n- **Flow / \"how does X reach Y\"**: ONE `codegraph_explore` with the symbol names spanning the flow — it surfaces the call path among them (riding dynamic-dispatch hops) AND returns their source. No need to reconstruct the path with `codegraph_search` + `codegraph_callers`.\n- **Onboarding / understanding any area**: ONE `codegraph_explore` is usually the whole answer. Only follow up — `codegraph_node` for a specific symbol — if something is still unclear.\n- **Refactor planning**: `codegraph_search` → `codegraph_callers` → `codegraph_impact`. The blast-radius answer comes from impact, not from walking callers manually.\n- **Debugging a regression**: `codegraph_callers` of the suspected symbol; widen with `codegraph_impact` if an unexpected call appears.\n\n## Anti-patterns\n\n- **Trust codegraph's results — don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.\n- **Don't grep first** when looking up a symbol by name — `codegraph_search` is faster and returns kind + location + signature.\n- **Don't chain `codegraph_search` + `codegraph_node`** to understand an area — ONE `codegraph_explore` returns the relevant symbols' source together in a single round-trip.\n- **Don't loop `codegraph_node` over many symbols** — one `codegraph_explore` call returns them all grouped by file, while each separate call re-reads the whole context and costs far more. Use `codegraph_node` for a single symbol.\n- **Don't reach for the `Read` tool on an indexed source file** — `codegraph_node` with a `file` reads it for you (same `\\t` source, `offset`/`limit` like Read, faster, with its blast radius), and with a `symbol` it returns the source plus the caller/callee trail. Reach for raw `Read` only for what codegraph doesn't index (configs, docs) or when the staleness banner flags a file as pending re-index.\n- **After editing, check the staleness banner.** When a tool response starts with \"⚠️ Some files referenced below were edited since the last index sync…\", the listed files are pending re-index — Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust codegraph. `codegraph_status` also lists pending files under \"Pending sync\".\n\n## Limitations\n\n- If a tool reports the project isn't initialized (no `.codegraph/` directory), tell the user the project has no CodeGraph index yet, offer to run `codegraph init .` to build it, and do not run it without the user's consent.\n- Index lags file writes by ~1 second. A burst of many changes (a branch switch, a mass rename) or a sign that the OS dropped file events makes the watcher re-scan the whole project on its own, and responses can start with \"⚠️ CodeGraph auto-sync is RECOVERING\" until that catch-up commits. Renames never need a rebuild: `codegraph sync` reconciles the whole project when no watcher is running.\n- Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.\n- Explore matches names and indexed code words lexically, not by meaning; an empty result reports word matches and may suggest indexed candidate names to retry with `codegraph_explore`.\n- No live correctness validation — that's still the TypeScript compiler / test suite / linter's job. Codegraph supplements those with structural context they don't have.\n\n## Supported languages\n\nCodegraph extracts these 38 languages (typescript, javascript, tsx, jsx, arkts, python, go, rust, java, c, cpp, csharp, razor, php, ruby, swift, kotlin, dart, svelte, vue, astro, liquid, pascal, scala, lua, luau, objc, r, solidity, nix, terraform, erlang, cfml, yaml, twig, xml, properties, gdscript). A file outside this set is not indexed, so no codegraph tool can see it — reach for Read there.\n" } } } diff --git a/skills/codegraph/SKILL.md b/skills/codegraph/SKILL.md index f340b730..8929144a 100644 --- a/skills/codegraph/SKILL.md +++ b/skills/codegraph/SKILL.md @@ -65,6 +65,11 @@ also escalate through `sync`; do not jump to a forced rebuild merely because the CLI version changed. Follow the exact recovery command printed by `status` or the failed command. +A project with no CodeGraph index yet is not a recovery case. Creating its index +is the user's decision: tell the user the project has no index yet, offer to run +`codegraph init .` in the project directory, and do not run it without the +user's consent. + Missing index-state slots and an all-`OwnerMismatch` index after a project move or copy are supported `init` recovery cases. When `status`, `sync`, or another failed command explicitly prints `codegraph init ...`, run that exact command to