aKode 0.8.0: grafo del codice locale (tree-sitter + git) e strumento code_graph, memorie ancorate ai simboli con stato stale, client MCP akode-mcp-client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-15 11:14:42 +01:00
parent b87057603d
commit 83959bccd0
74 changed files with 5019 additions and 229 deletions

View File

@@ -0,0 +1,480 @@
//! The read-only `code_graph` tool: where symbols are defined, who calls them, what they call,
//! which files are related, and module outlines, from a local index built with tree-sitter and
//! git (see `akode-code-graph`). No model is involved and nothing leaves the machine.
//!
//! The index of the working directory's repository is updated in the background when a thread
//! starts and incrementally before every answer. One index per repository is shared by all the
//! threads of the process.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;
use akode_code_graph::CodeIndex;
use akode_code_graph::git;
use akode_core::config::CodeGraphConfig;
use akode_core::config::Config;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ContentItemKind;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::FunctionCallError;
use akode_extension_api::PromptFragment;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolContributor;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolOutput;
use akode_extension_api::ToolPayload;
use akode_extension_api::ToolSpec;
use akode_protocol::models::FunctionCallOutputContentItem;
use akode_protocol::models::FunctionCallOutputPayload;
use akode_protocol::models::ResponseInputItem;
use akode_tools::JsonSchema;
use akode_tools::ToolExposure;
use serde::Deserialize;
pub const TOOL_NAME: &str = "code_graph";
/// Content kind of the repository map in the initial context.
pub const MAP_KIND: &str = "code_graph.map";
/// The map waits at most this long for the first index of a session.
const MAP_TIMEOUT: Duration = Duration::from_secs(3);
/// Token budget of the repository map.
const MAP_TOKENS: usize = 350;
/// An update younger than this is reused (parallel calls of one step).
const FRESH_FOR: Duration = Duration::from_secs(2);
const TOOL_DESCRIPTION: &str = "Read-only code graph of this repository, built locally from git with tree-sitter (no model). Prefer it to grep/rg when looking for where something is defined, who calls a function or what a module contains: one call returns exact path:line answers.\n\
Actions: search (symbols whose name matches `symbol`; filter with `kind` or `path`), definition (file:line range and first lines of `symbol`), callers (who calls or uses `symbol`), callees (what `symbol` calls, resolved to file:line), related (files linked to `path` or `symbol` by references), module_map (outline of the file or folder `path`), overview (folders and languages).\n\
search matches symbol names only (not comments or text): for a concept with no name yet, use rg. `symbol` accepts name, Type::name, Type.name or path#name. References are matched by name: callers of a common method name can include homonyms (the answer says how many definitions share the name). Answers are compact path:line lists; open the file for the full code.";
/// One index per repository root, shared by every thread of the process.
struct SharedIndex {
index: Mutex<Option<CodeIndex>>,
last_update: Mutex<Option<Instant>>,
}
fn registry() -> &'static Mutex<HashMap<PathBuf, Arc<SharedIndex>>> {
static REGISTRY: OnceLock<Mutex<HashMap<PathBuf, Arc<SharedIndex>>>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
fn shared_for(root: &Path) -> Arc<SharedIndex> {
let mut map = registry().lock().unwrap_or_else(std::sync::PoisonError::into_inner);
map.entry(root.to_path_buf())
.or_insert_with(|| {
Arc::new(SharedIndex {
index: Mutex::new(None),
last_update: Mutex::new(None),
})
})
.clone()
}
/// Repository of one thread.
#[derive(Clone)]
struct Repo {
home: PathBuf,
root: PathBuf,
/// Working directory relative to the root (`""` at the root).
cwd_prefix: String,
shared: Arc<SharedIndex>,
}
impl Repo {
fn locate(home: &Path, cwd: &Path) -> Option<Self> {
let root = git::toplevel(cwd)?;
let root = root.canonicalize().unwrap_or(root);
let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
let cwd_prefix = cwd
.strip_prefix(&root)
.map(|prefix| prefix.to_string_lossy().replace('\\', "/"))
.unwrap_or_default();
Some(Self {
home: home.to_path_buf(),
shared: shared_for(&root),
root,
cwd_prefix,
})
}
/// Opens the index if needed, updates it unless it was just updated, and runs `f`.
fn with_index<T>(&self, f: impl FnOnce(&CodeIndex) -> Result<T, String>) -> Result<T, String> {
let mut guard = self
.shared
.index
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if guard.is_none() {
let path = CodeIndex::default_path(&self.home, &self.root);
*guard = Some(CodeIndex::open(&path, &self.root)?);
}
let Some(index) = guard.as_mut() else {
return Err("code graph index not available".to_string());
};
let mut last = self
.shared
.last_update
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if last.is_none_or(|at| at.elapsed() > FRESH_FOR) {
let report = index.update()?;
tracing::debug!(
mode = report.mode,
parsed = report.parsed,
removed = report.removed,
ms = report.millis as u64,
"code graph updated"
);
*last = Some(Instant::now());
}
drop(last);
f(index)
}
}
#[derive(Clone)]
struct ThreadState {
config: CodeGraphConfig,
repo: Option<Repo>,
map: Arc<tokio::sync::OnceCell<Option<String>>>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Args {
action: String,
#[serde(default)]
symbol: Option<String>,
#[serde(default)]
path: Option<String>,
#[serde(default)]
kind: Option<String>,
#[serde(default)]
limit: Option<usize>,
}
fn answer(index: &CodeIndex, args: &Args, cwd_prefix: &str, budget: usize) -> Result<String, String> {
let symbol = || {
args.symbol
.as_deref()
.map(str::trim)
.filter(|symbol| !symbol.is_empty())
.ok_or_else(|| format!("action {} needs `symbol`", args.action))
};
match args.action.as_str() {
"search" => {
let path = args
.path
.as_deref()
.map(|path| index.normalize_path(path, cwd_prefix));
index.search(
symbol()?,
args.kind.as_deref(),
path.as_deref(),
args.limit.unwrap_or(25).clamp(1, 100),
budget,
)
}
"definition" => index.definition(symbol()?, 15, budget),
"callers" => index.callers(symbol()?, budget),
"callees" => index.callees(symbol()?, budget),
"related" => {
let target = args
.path
.as_deref()
.or(args.symbol.as_deref())
.ok_or("action related needs `path` or `symbol`")?;
index.related(target, cwd_prefix, budget)
}
"module_map" => index.module_map(args.path.as_deref().unwrap_or(cwd_prefix), cwd_prefix, budget),
"overview" => index.repo_summary(budget),
other => Err(format!(
"unknown action {other:?}: use search, definition, callers, callees, related, module_map or overview"
)),
}
}
struct CodeGraphTool {
repo: Repo,
budget: usize,
}
struct TextOutput {
payload: FunctionCallOutputPayload,
}
impl TextOutput {
fn new(result: Result<String, String>) -> Self {
let payload = match result {
Ok(text) => FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputText { text },
]),
Err(error) => FunctionCallOutputPayload {
success: Some(false),
..FunctionCallOutputPayload::from_text(error)
},
};
Self { payload }
}
}
impl ToolOutput for TextOutput {
fn log_output(&self) -> String {
"[code_graph output]".to_string()
}
fn success_for_logging(&self) -> bool {
self.payload.success.unwrap_or(true)
}
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: self.payload.clone(),
}
}
}
fn spec() -> ToolSpec {
let string = |description: &str| JsonSchema::string(Some(description.to_string()));
let properties = BTreeMap::from([
(
"action".to_string(),
string("One of: search, definition, callers, callees, related, module_map, overview."),
),
(
"symbol".to_string(),
string("Symbol name, Type::name, Type.name or path#name (search, definition, callers, callees, related)."),
),
(
"path".to_string(),
string("File or folder, relative to the working directory (module_map, related; filter for search)."),
),
(
"kind".to_string(),
string("Filter for search: function, method, struct, enum, trait, interface, class, type, module, const, macro, section, key."),
),
(
"limit".to_string(),
JsonSchema::integer(Some("Maximum results for search (default 25).".to_string())),
),
]);
ToolSpec::Function(ResponsesApiTool {
name: TOOL_NAME.to_string(),
description: TOOL_DESCRIPTION.to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(properties, Some(vec!["action".to_string()]), Some(false.into())),
output_schema: None,
})
}
impl<'call> ToolExecutor<ToolCall<'call>> for CodeGraphTool {
fn tool_name(&self) -> ToolName {
ToolName::plain(TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
spec()
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: Args = serde_json::from_str(call.function_arguments()?).map_err(|error| {
FunctionCallError::RespondToModel(format!("invalid code_graph arguments: {error}"))
})?;
let repo = self.repo.clone();
let budget = self.budget;
let result = tokio::task::spawn_blocking(move || {
repo.with_index(|index| answer(index, &args, &repo.cwd_prefix, budget))
})
.await
.unwrap_or_else(|error| Err(format!("code_graph failed: {error}")));
Ok(Box::new(TextOutput::new(result)) as Box<dyn ToolOutput>)
})
}
}
#[derive(Clone, Copy, Default)]
struct CodeGraphExtension;
fn thread_state(config: &Config) -> ThreadState {
let repo = if config.code_graph.enabled {
Repo::locate(config.codex_home.as_path(), config.cwd.as_path())
} else {
None
};
ThreadState {
config: config.code_graph,
repo,
map: Arc::new(tokio::sync::OnceCell::new()),
}
}
impl ThreadLifecycleContributor<Config> for CodeGraphExtension {
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, Config>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let state = thread_state(input.config);
if let Some(repo) = state.repo.clone() {
// Warm the index in the background: the first answer is then incremental.
tokio::task::spawn_blocking(move || {
if let Err(error) = repo.with_index(|_| Ok(())) {
tracing::warn!(%error, "code graph index not updated");
}
});
}
input.thread_store.insert(state);
})
}
}
impl ConfigContributor<Config> for CodeGraphExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
if let Some(state) = thread_store.get::<ThreadState>() {
let mut next = thread_state(new_config);
// The map already in the prompt stays: the prefix must not change mid-thread.
next.map = state.map.clone();
thread_store.insert(next);
}
}
}
impl ToolContributor for CodeGraphExtension {
fn tools(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let Some(state) = thread_store.get::<ThreadState>() else {
return Vec::new();
};
match (&state.repo, state.config.enabled) {
(Some(repo), true) => vec![Arc::new(CodeGraphTool {
repo: repo.clone(),
budget: state.config.max_output_tokens as usize,
})],
_ => Vec::new(),
}
}
}
async fn repo_map(repo: Repo) -> Option<String> {
let task = tokio::task::spawn_blocking(move || repo.with_index(|index| index.repo_summary(MAP_TOKENS)));
match tokio::time::timeout(MAP_TIMEOUT, task).await {
Ok(Ok(Ok(map))) => Some(format!(
"<code_map>\n{map}\nTo find where something is defined, who calls a function or what it calls, use the code_graph tool (definition, callers, callees, module_map): it answers with exact path:line.\n</code_map>"
)),
Ok(Ok(Err(error))) => {
tracing::warn!(%error, "code map not available");
None
}
Ok(Err(_)) => None,
Err(_) => {
tracing::info!("code map not ready in time; the session starts without it");
None
}
}
}
impl ContextContributor for CodeGraphExtension {
fn contribute_thread_context<'a>(
&'a self,
_session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> Pin<Box<dyn Future<Output = Vec<PromptFragment>> + Send + 'a>> {
Box::pin(async move {
let Some(state) = thread_store.get::<ThreadState>() else {
return Vec::new();
};
let (Some(repo), true, true) = (&state.repo, state.config.enabled, state.config.repo_map) else {
return Vec::new();
};
let map = state.map.get_or_init(|| repo_map(repo.clone())).await;
match map {
Some(map) => vec![PromptFragment::developer_policy(
map.clone(),
ContentItemKind(MAP_KIND.to_string()),
)],
None => Vec::new(),
}
})
}
}
/// Installs the `code_graph` tool, the background index and the optional repository map.
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>) {
let extension = Arc::new(CodeGraphExtension);
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.tool_contributor(extension.clone());
registry.prompt_contributor(extension);
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn answers_by_action() {
let repo = tempfile::tempdir().expect("repo");
let home = tempfile::tempdir().expect("home");
let root = repo.path().canonicalize().expect("root");
let run = |args: &[&str]| {
let status = std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(args)
.output()
.expect("git");
assert!(status.status.success());
};
run(&["init", "-q"]);
std::fs::create_dir_all(root.join("src")).expect("mkdir");
std::fs::write(root.join("src/lib.rs"), "pub fn alpha() { beta(); }\nfn beta() {}\n").expect("write");
let repo = Repo::locate(home.path(), &root.join("src")).expect("repo");
assert_eq!(repo.cwd_prefix, "src");
let ask = |json: &str| {
let args: Args = serde_json::from_str(json).expect("args");
repo.with_index(|index| answer(index, &args, &repo.cwd_prefix, 800))
};
assert!(ask(r#"{"action":"callers","symbol":"beta"}"#).expect("callers").contains("src/lib.rs:1 in function alpha"));
assert!(ask(r#"{"action":"module_map","path":"lib.rs"}"#).expect("map").contains("1 function alpha"));
assert_eq!(
ask(r#"{"action":"callers"}"#).expect_err("missing symbol"),
"action callers needs `symbol`"
);
assert!(ask(r#"{"action":"nope"}"#).is_err());
}
}