use std::path::{Path, PathBuf};
use std::time::Instant;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::{tool, tool_router};
use serde::Serialize;
use crate::edit_safety::trust::{ProjectConfigTrust, TrustEvaluation, TrustStatus};
use crate::live_index::store::IndexState;
use crate::protocol::result_status::{
OutcomeClass, RESULT_STATUS_CONTRACT_VERSION, RESULT_STATUS_META_KEY,
};
use crate::protocol::{edit, edit_format, edit_hooks, format};
use crate::watcher;
use super::SymForgeServer;
use super::tools::{is_error_output, is_index_unavailable_output, safe_repo_path_for_freshen};
fn missing_file_refusal(live: &crate::live_index::LiveIndex, path: &str) -> String {
crate::protocol::read_gate::refuse_by_policy(live, path)
.unwrap_or_else(|| format::not_found_file(path))
}
macro_rules! loading_guard {
($guard:expr) => {
match $guard.index_state() {
IndexState::Ready => {}
IndexState::Empty => return format::empty_guard_message(),
IndexState::Loading => {
return format::loading_guard_message_for(
&$guard.snapshot_verify_state(),
$guard.load_source() == crate::live_index::IndexLoadSource::EmptyBootstrap,
);
}
IndexState::CircuitBreakerTripped { summary } => {
return format!("Index degraded: {summary}");
}
}
};
}
const PROJECT_CONFIG_TRUST_MODE_ENV: &str = "SYMFORGE_PROJECT_CONFIG_TRUST_MODE";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProjectConfigTrustMode {
LogOnly,
Enforce,
}
impl ProjectConfigTrustMode {
fn current() -> Self {
match std::env::var(PROJECT_CONFIG_TRUST_MODE_ENV) {
Ok(value) if value.eq_ignore_ascii_case("enforce") => Self::Enforce,
_ => Self::LogOnly,
}
}
}
#[cfg(test)]
#[cfg(test)]
mod tests {
use super::{EditResultStatus, classify_edit_output, session_stale_recovery};
use crate::protocol::surface_probe::{SurfaceProfile, with_connection_surface};
use std::ffi::OsString;
#[test]
fn echoed_refusal_phrases_never_downgrade_a_reached_apply_path() {
use super::{EditResultStatus as S, classify_edit_output as c};
let rename = "Renamed `old` -> `new` - 2 site(s) across 1 file(s)\n\n -- Uncertain matches (NOT applied - review manually) - 1 site(s) --\n src/lib.rs\n L3: let m = \"symbol not found: {name} in {path}\";\n";
assert_eq!(c(rename, false), S::Success);
let applied = "Edit safety: structural-edit-safe\nPath authority: repository-bound\n Source authority: disk-refreshed\nWrite semantics: atomic write + reindex\n Evidence: symbol anchor `src/lib.rs:1`\nReplaced `f`.\n Symbol not found: this is the NEW BODY text, echoed back\n";
assert_eq!(c(applied, false), S::Success);
let preview = "Edit safety: structural-edit-safe\nPath authority: repository-bound\n Source authority: disk-refreshed\nWrite semantics: dry run (no writes)\n Evidence: symbol anchor `src/lib.rs:1`\n[DRY RUN] Would replace `f`\n Ambiguous: quoted from the preview body\n";
assert_eq!(c(preview, true), S::DryRunSuccess);
let torn = "Edit safety: structural-edit-safe\nWrite semantics: transactional write + rollback + reindex\n ROLLBACK INCOMPLETE: src/lib.rs left modified\n";
assert_eq!(c(torn, false), S::InternalFailure);
}
#[test]
fn edit_output_shapes_that_applied_nothing_never_classify_as_success() {
use super::{EditResultStatus as S, classify_edit_output as c};
assert_eq!(
c("Error: file not found at /repo/src/gone.rs", false),
S::NotFound
);
assert_eq!(
c("`old` not found within symbol `present`", false),
S::NotFound
);
assert_eq!(
c("symbol not found: missing in src/lib.rs", false),
S::NotFound
);
assert_eq!(
c("file not found in index: src/gone.rs", false),
S::NotFound
);
assert_eq!(
c(
"replace_symbol_body: edit safety blocked
Required safety: structural",
false
),
S::InternalFailure
);
}
#[test]
fn batch_insert_target_failures_name_the_failed_operation() {
let statuses = super::failed_batch_operation_statuses(
"Target 2: Symbol not found: beta",
super::EditResultStatus::NotFound,
);
assert_eq!(statuses, vec![(2, super::EditResultStatus::NotFound)]);
}
#[test]
fn daemon_wrapped_edit_errors_classify_as_invalid_request() {
assert_eq!(
classify_edit_output(
"Error in replace_symbol_body: projects must not be empty",
false
),
EditResultStatus::InvalidRequest
);
}
#[test]
fn rejected_index_publications_classify_as_retryable_internal_failures() {
for output in [
"Error: index refresh for 'src/lib.rs' did not publish; retry the edit.",
"Error: index refresh for 'src/lib.rs' did not publish; retry the batch edit.",
] {
assert_eq!(
classify_edit_output(output, false),
EditResultStatus::InternalFailure,
"output was: {output}"
);
}
}
struct SurfaceEnvGuard {
previous: Option<OsString>,
}
#[allow(unsafe_code)] impl SurfaceEnvGuard {
fn set(value: &str) -> Self {
let previous = std::env::var_os("SYMFORGE_SURFACE");
unsafe { std::env::set_var("SYMFORGE_SURFACE", value) };
Self { previous }
}
}
#[allow(unsafe_code)] impl Drop for SurfaceEnvGuard {
fn drop(&mut self) {
match &self.previous {
Some(previous) => unsafe { std::env::set_var("SYMFORGE_SURFACE", previous) },
None => unsafe { std::env::remove_var("SYMFORGE_SURFACE") },
}
}
}
#[tokio::test]
async fn stale_session_recovery_names_compact_over_full_env() {
let _surface = SurfaceEnvGuard::set("full");
let recovery = with_connection_surface(Some(SurfaceProfile::Compact), async {
session_stale_recovery()
})
.await;
assert!(
!recovery.contains("index_folder"),
"compact-connection stale recovery must never name the gated index_folder: {recovery}"
);
assert!(
recovery.contains("SYMFORGE_WORKSPACE_ROOT"),
"compact-connection stale recovery must name a compact-callable path: {recovery}"
);
}
#[tokio::test]
async fn stale_session_recovery_names_index_folder_over_compact_env() {
let _surface = SurfaceEnvGuard::set("compact");
let recovery = with_connection_surface(Some(SurfaceProfile::Full), async {
session_stale_recovery()
})
.await;
assert!(
recovery.contains("index_folder"),
"full-connection stale recovery must name index_folder (callable there): {recovery}"
);
}
}
fn project_config_trust_inputs_exist(repo_root: &Path) -> bool {
let symforge_dir = repo_root.join(".symforge");
symforge_dir.join("config.toml").exists() || symforge_dir.join("config").exists()
}
fn project_config_trust_response_suffix(repo_root: &Path) -> Result<Option<String>, String> {
if !project_config_trust_inputs_exist(repo_root) {
return Ok(None);
}
let Some(trust) = ProjectConfigTrust::default_store() else {
return Ok(Some(
"ProjectConfigTrustWarning: status=Unavailable warning=\"could not determine user-local data directory\"; mode=LOG_ONLY; operation_allowed=true"
.to_string(),
));
};
let evaluation = trust.evaluate(repo_root);
match evaluation.status {
TrustStatus::Trusted | TrustStatus::EnvOverride => Ok(None),
TrustStatus::Untrusted | TrustStatus::ContentChanged { .. } => {
let evidence = project_config_trust_evidence(&evaluation);
match ProjectConfigTrustMode::current() {
ProjectConfigTrustMode::LogOnly => Ok(Some(format!(
"ProjectConfigTrustWarning: {evidence}; mode=LOG_ONLY; operation_allowed=true"
))),
ProjectConfigTrustMode::Enforce => Err(format!(
"ProjectConfigTrustEnforced: {evidence}; mode=ENFORCE; operation_allowed=false; run `symforge trust project-config accept --project {}` with reviewed actual_hash before retrying",
repo_root.display()
)),
}
}
}
}
fn project_config_trust_evidence(evaluation: &TrustEvaluation) -> String {
let mut parts = match &evaluation.status {
TrustStatus::Trusted => vec!["status=Trusted".to_string()],
TrustStatus::Untrusted => vec!["status=Untrusted".to_string()],
TrustStatus::ContentChanged { expected, actual } => vec![
"status=ContentChanged".to_string(),
format!("expected_hash={expected}"),
format!("actual_hash={actual}"),
],
TrustStatus::EnvOverride => vec!["status=EnvOverride".to_string()],
};
if !matches!(evaluation.status, TrustStatus::ContentChanged { .. }) {
parts.push(format!("actual_hash={}", evaluation.actual_hash));
}
if let Some(project_key) = &evaluation.project_key {
parts.push(format!("project_key={project_key}"));
}
if let Some(warning) = evaluation.warnings.first() {
parts.push(format!("warning=\"{}\"", one_line(warning)));
}
parts.join(" ")
}
fn append_project_config_trust_suffix(output: &mut String, suffix: Option<&str>) {
if let Some(suffix) = suffix {
output.push('\n');
output.push_str(suffix);
}
}
fn one_line(value: &str) -> String {
value.split_whitespace().collect::<Vec<_>>().join(" ")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditResultStatus {
Success,
DryRunSuccess,
NotFound,
Ambiguous,
InvalidRequest,
InternalFailure,
}
impl EditResultStatus {
const fn as_str(self) -> &'static str {
match self {
Self::Success => "success",
Self::DryRunSuccess => "dry_run_success",
Self::NotFound => "not_found",
Self::Ambiguous => "ambiguous",
Self::InvalidRequest => "invalid_request",
Self::InternalFailure => "internal_failure",
}
}
const fn outcome_class(self) -> OutcomeClass {
match self {
Self::Success | Self::DryRunSuccess => OutcomeClass::Found,
Self::NotFound => OutcomeClass::NotFound,
Self::Ambiguous => OutcomeClass::Ambiguous,
Self::InvalidRequest => OutcomeClass::InvalidRequest,
Self::InternalFailure => OutcomeClass::InternalFailure,
}
}
const fn is_terminal_failure(self) -> bool {
!matches!(self.outcome_class(), OutcomeClass::Found)
}
}
fn statused_edit_tool_result(
text: String,
status: EditResultStatus,
operation_statuses: Vec<(usize, EditResultStatus)>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let mut status_payload = serde_json::json!({
"contract_version": RESULT_STATUS_CONTRACT_VERSION,
"outcome_class": status.outcome_class().as_str(),
"status": status.as_str(),
});
if !operation_statuses.is_empty() {
status_payload["operations"] = serde_json::Value::Array(
operation_statuses
.into_iter()
.map(|(operation_index, operation_status)| {
serde_json::json!({
"operation_index": operation_index,
"status": operation_status.as_str(),
"outcome_class": operation_status.outcome_class().as_str(),
})
})
.collect(),
);
}
let mut meta = rmcp::model::JsonObject::new();
meta.insert(RESULT_STATUS_META_KEY.to_string(), status_payload);
let content = vec![rmcp::model::ContentBlock::text(text)];
let result = if status.is_terminal_failure() {
rmcp::model::CallToolResult::error(content)
} else {
rmcp::model::CallToolResult::success(content)
};
Ok(result.with_meta(Some(rmcp::model::MetaObject(meta))))
}
fn classify_edit_output(text: &str, dry_run: bool) -> EditResultStatus {
if is_index_unavailable_output(text) {
return EditResultStatus::InternalFailure;
}
let reached_apply_path = text.contains("Write semantics: ") || text.starts_with("Renamed `");
let torn_after_envelope = text.contains("ROLLBACK INCOMPLETE")
|| text.contains("Write failed")
|| text.starts_with("Error writing ")
|| text.contains("File disappeared:");
if reached_apply_path && !torn_after_envelope {
return if dry_run
|| text.contains("[DRY RUN]")
|| text.contains("Write semantics: dry run (no writes)")
{
EditResultStatus::DryRunSuccess
} else {
EditResultStatus::Success
};
}
if text.contains("Ambiguous:") || text.starts_with("Ambiguous:") {
EditResultStatus::Ambiguous
} else if text.starts_with("File not found:")
|| text.starts_with("Symbol not found:")
|| text.contains("Symbol not found:")
|| text.contains("File not indexed:")
|| text.starts_with("Error: file not found at ")
|| text.contains(" not found within symbol ")
|| text.contains("symbol not found:")
|| text.contains("file not found in index:")
{
EditResultStatus::NotFound
} else if text.contains("no repository root configured")
|| text.contains("still loading")
|| text.contains("unavailable")
|| text.starts_with("Error writing ")
|| text.contains("Write failed")
|| text.contains("ROLLBACK INCOMPLETE")
|| text.contains(": edit safety blocked")
|| text.contains("File disappeared:")
|| text.contains("byte range")
|| text.contains("Session stale")
|| (text.starts_with("Error: index refresh for '")
&& text.contains(" did not publish; retry the "))
{
EditResultStatus::InternalFailure
} else if is_error_output(text)
|| text.starts_with("ProjectConfigTrustEnforced:")
|| text.starts_with("Overlapping edits")
|| text.contains("path escapes repo root")
|| text.contains("Path containment error")
|| text.contains("Path resolution error")
{
EditResultStatus::InvalidRequest
} else if dry_run
|| text.contains("[DRY RUN]")
|| text.contains("Write semantics: dry run (no writes)")
{
EditResultStatus::DryRunSuccess
} else {
EditResultStatus::Success
}
}
fn success_operation_statuses(
count: usize,
status: EditResultStatus,
) -> Vec<(usize, EditResultStatus)> {
(1..=count).map(|index| (index, status)).collect()
}
fn failed_batch_operation_statuses(
text: &str,
status: EditResultStatus,
) -> Vec<(usize, EditResultStatus)> {
let Some(rest) = text
.strip_prefix("Edit ")
.or_else(|| text.strip_prefix("Target "))
else {
return Vec::new();
};
let digits = rest
.chars()
.take_while(|ch| ch.is_ascii_digit())
.collect::<String>();
if digits.is_empty() || !matches!(rest.chars().nth(digits.len()), Some(':' | ' ')) {
return Vec::new();
}
match digits.parse::<usize>() {
Ok(index) => vec![(index, status)],
Err(_) => Vec::new(),
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum EditError {
#[error("Error: file not found at {path}")]
PathNotFound { path: std::path::PathBuf },
#[error("Error: session stale at {path} — {recovery}")]
SessionStale {
path: std::path::PathBuf,
recovery: String,
},
}
fn session_stale_recovery() -> String {
match crate::protocol::surface_probe::connection_surface_or_env() {
crate::protocol::surface_probe::SurfaceProfile::Compact => {
"set SYMFORGE_WORKSPACE_ROOT to the project path (or run `symforge init` for \
this harness) and reconnect to refresh repo_root, or set SYMFORGE_SURFACE=full \
for the full tool surface"
.to_string()
}
crate::protocol::surface_probe::SurfaceProfile::Full
| crate::protocol::surface_probe::SurfaceProfile::Meta => {
"call index_folder to refresh repo_root".to_string()
}
}
}
fn edit_capability_label(
capability: crate::parsing::config_extractors::EditCapability,
) -> &'static str {
use crate::parsing::config_extractors::EditCapability;
match capability {
EditCapability::IndexOnly => "index-only",
EditCapability::TextEditSafe => "text-edit-safe",
EditCapability::StructuralEditSafe => "structural-edit-safe",
}
}
pub(crate) fn prepare_exact_path_for_edit(
server: &SymForgeServer,
relative_path: &str,
) -> Result<(PathBuf, edit_format::EditSourceAuthority), String> {
let expected_gen = server.index.data_plane().current_project_generation();
let repo_root = server
.capture_repo_root()
.ok_or_else(|| "Error: no repository root configured.".to_string())?;
let abs_path =
safe_repo_path_for_freshen(&repo_root, relative_path).map_err(|e| format!("Error: {e}"))?;
let lane_authority =
crate::live_index::index_lifecycle::activation::project_source_authority(&repo_root);
let lane_observer = lane_authority.active_observer();
let source_authority = match watcher::freshen_file_if_stale(
relative_path,
&abs_path,
server.index.data_plane(),
expected_gen,
&lane_authority,
lane_observer,
) {
watcher::FreshenResult::Fresh => edit_format::EditSourceAuthority::CurrentIndex,
watcher::FreshenResult::StaleReindexed => edit_format::EditSourceAuthority::DiskRefreshed,
watcher::FreshenResult::StaleRemoved => {
return Err(format!("{}", EditError::PathNotFound { path: abs_path }));
}
watcher::FreshenResult::GenerationMismatch => {
return Err(format!(
"{}",
EditError::SessionStale {
path: abs_path,
recovery: session_stale_recovery(),
}
));
}
watcher::FreshenResult::PublicationRejected => {
return Err(format!(
"Error: index refresh for '{}' did not publish; retry the edit.",
relative_path
));
}
};
Ok((abs_path, source_authority))
}
pub(super) fn prepare_batch_paths_for_edit(
server: &SymForgeServer,
relative_paths: &[String],
) -> Result<(PathBuf, edit_format::EditSourceAuthority), String> {
let expected_gen = server.index.data_plane().current_project_generation();
let repo_root = server
.capture_repo_root()
.ok_or_else(|| "Error: no repository root configured.".to_string())?;
let mut unique_paths = relative_paths.to_vec();
unique_paths.sort();
unique_paths.dedup();
let lane_authority =
crate::live_index::index_lifecycle::activation::project_source_authority(&repo_root);
let lane_observer = lane_authority.active_observer();
let mut refreshed = false;
for relative_path in unique_paths {
let abs_path = safe_repo_path_for_freshen(&repo_root, &relative_path)
.map_err(|e| format!("Error: {e}"))?;
match watcher::freshen_file_if_stale(
&relative_path,
&abs_path,
server.index.data_plane(),
expected_gen,
&lane_authority,
lane_observer,
) {
watcher::FreshenResult::Fresh => {}
watcher::FreshenResult::StaleReindexed => {
refreshed = true;
}
watcher::FreshenResult::StaleRemoved => {
tracing::warn!(
path = %abs_path.display(),
"skipping missing path during batch edit preparation"
);
}
watcher::FreshenResult::GenerationMismatch => {
return Err(format!(
"{}",
EditError::SessionStale {
path: abs_path,
recovery: session_stale_recovery(),
}
));
}
watcher::FreshenResult::PublicationRejected => {
return Err(format!(
"Error: index refresh for '{}' did not publish; retry the batch edit.",
relative_path
));
}
}
}
let source_authority = if refreshed {
edit_format::EditSourceAuthority::DiskRefreshed
} else {
edit_format::EditSourceAuthority::CurrentIndex
};
Ok((repo_root, source_authority))
}
fn prepare_project_wide_rename(
server: &SymForgeServer,
repo_root: &std::path::Path,
) -> edit_format::EditSourceAuthority {
if watcher::reconcile_stale_files(repo_root, server.index.data_plane()) > 0 {
edit_format::EditSourceAuthority::DiskRefreshed
} else {
edit_format::EditSourceAuthority::CurrentIndex
}
}
pub(crate) fn begin_mutation_replay<T: Serialize>(
server: &SymForgeServer,
tool_name: &str,
input: &T,
idempotency_key: Option<&str>,
dry_run: bool,
) -> Result<Option<crate::idempotency::ActiveReplay>, String> {
if dry_run {
return Ok(None);
}
let Some(raw_key) = idempotency_key else {
return Ok(None);
};
let mut request = serde_json::to_value(input)
.map_err(|error| crate::idempotency::format_tool_error(&error.into()))?;
if let serde_json::Value::Object(map) = &mut request {
map.remove("idempotency_key");
}
let project_state = server.capture_project_state_dir().ok_or_else(|| {
"Error: durable project-state replay is unavailable for this binding.".to_string()
})?;
match crate::idempotency::begin_tool_replay_verified(
&project_state,
tool_name,
raw_key,
&request,
) {
Ok(crate::idempotency::ReplayStart::FirstExecution(active)) => Ok(Some(active)),
Ok(crate::idempotency::ReplayStart::Replay(response)) => Err(response),
Err(error) => Err(crate::idempotency::format_tool_error(&error)),
}
}
fn probe_mutation_replay<T: Serialize>(
server: &SymForgeServer,
tool_name: &str,
input: &T,
idempotency_key: Option<&str>,
dry_run: bool,
) -> Result<Option<String>, String> {
if dry_run {
return Ok(None);
}
let Some(raw_key) = idempotency_key else {
return Ok(None);
};
let mut request = serde_json::to_value(input)
.map_err(|error| crate::idempotency::format_tool_error(&error.into()))?;
if let serde_json::Value::Object(map) = &mut request {
map.remove("idempotency_key");
}
let project_state = server.capture_project_state_dir().ok_or_else(|| {
"Error: durable project-state replay is unavailable for this binding.".to_string()
})?;
crate::idempotency::probe_tool_replay_verified(&project_state, tool_name, raw_key, &request)
.map_err(|error| crate::idempotency::format_tool_error(&error))
}
pub(crate) fn probe_symforge_edit_apply_replay(
server: &SymForgeServer,
step_tool: &str,
step_args: &serde_json::Value,
idempotency_key: Option<&str>,
) -> Result<Option<String>, String> {
let dry_run = step_args
.get("dry_run")
.and_then(|value| value.as_bool())
.unwrap_or(false);
macro_rules! probe_as {
($input:ty) => {{
let input: $input = serde_json::from_value(step_args.clone())
.map_err(|error| crate::idempotency::format_tool_error(&error.into()))?;
probe_mutation_replay(server, step_tool, &input, idempotency_key, dry_run)
}};
}
match step_tool {
"replace_symbol_body" => probe_as!(edit::ReplaceSymbolBodyInput),
"insert_symbol" => probe_as!(edit::InsertSymbolInput),
"edit_within_symbol" => probe_as!(edit::EditWithinSymbolInput),
_ => Ok(None),
}
}
fn complete_mutation_replay(
idempotency: &Option<crate::idempotency::ActiveReplay>,
output: &mut String,
written: &[std::path::PathBuf],
) {
let post_image = crate::idempotency::capture_post_image(written).filter(|receipt| {
!receipt.targets.is_empty()
&& receipt
.targets
.iter()
.all(|target| target.content_digest.is_some())
});
complete_mutation_replay_with_receipt(idempotency, output, post_image);
}
pub(crate) fn complete_mutation_replay_with_receipt(
idempotency: &Option<crate::idempotency::ActiveReplay>,
output: &mut String,
post_image: Option<crate::idempotency::PostImageReceipt>,
) {
if let Some(idempotency) = idempotency
&& let Err(error) = idempotency.complete_with_post_image(output.clone(), post_image)
{
output.push_str(&format!(
"\nIdempotency warning: failed to store replay result: {error}"
));
}
}
pub(crate) fn fail_mutation_replay(
idempotency: &Option<crate::idempotency::ActiveReplay>,
output: &str,
) {
if let Some(idempotency) = idempotency {
let _ = idempotency.fail(output.to_string());
}
}
pub(crate) fn fail_and_return_mutation_replay(
idempotency: &Option<crate::idempotency::ActiveReplay>,
output: String,
) -> String {
fail_mutation_replay(idempotency, &output);
output
}
fn symbol_anchor(path: &str, symbol: &crate::domain::SymbolRecord) -> String {
format!("{path}:{}", symbol.line_range.0.saturating_add(1))
}
#[tool_router(router = edit_tool_router, vis = "pub(crate)")]
impl SymForgeServer {
pub(super) fn check_edit_capability(
language: &crate::domain::LanguageId,
required: crate::parsing::config_extractors::EditCapability,
tool_name: &str,
) -> Option<String> {
use crate::parsing::config_extractors::{EditCapability, edit_capability_for_language};
if let Some(cap) = edit_capability_for_language(language) {
let allowed = match required {
EditCapability::IndexOnly => false,
EditCapability::TextEditSafe => {
matches!(
cap,
EditCapability::TextEditSafe | EditCapability::StructuralEditSafe
)
}
EditCapability::StructuralEditSafe => {
matches!(cap, EditCapability::StructuralEditSafe)
}
};
if !allowed {
let suggestion = match required {
EditCapability::StructuralEditSafe => {
"use edit_within_symbol for scoped text replacements, or the built-in Edit tool for raw text edits."
}
EditCapability::TextEditSafe => {
"use the built-in Edit tool for raw text edits in this file type."
}
EditCapability::IndexOnly => {
"inspect the file with read-only tools or use the built-in Edit tool for raw text edits."
}
};
return Some(edit_format::format_capability_warning(
tool_name,
&language.to_string(),
edit_capability_label(required),
edit_capability_label(cap),
suggestion,
));
}
}
None }
fn append_impact_footer(&self, output: &mut String, path: &str) {
let generation = self.index.data_plane().published_generation();
let guard = &generation.live;
if !matches!(guard.index_state(), IndexState::Ready) {
return;
}
let temporal = &generation.code_signals.temporal;
let (deps, cochanges) = format::edit_impact_summary(guard, temporal, path);
output.push('\n');
output.push_str(&format::impact_footer(deps, &cochanges));
}
#[tool(
name = "replace_symbol_body",
description = "Replace a symbol's entire definition; the index resolves the range (no prior read). Not a small inner edit (edit_within_symbol) or a deletion (delete_symbol).",
annotations(
read_only_hint = false,
destructive_hint = true,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn replace_symbol_body_tool(
&self,
params: Parameters<edit::ReplaceSymbolBodyInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let output = self.replace_symbol_body(params).await;
let status = classify_edit_output(&output, dry_run);
self.record_tool_completion_with_success(
"replace_symbol_body",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, Vec::new())
}
pub(crate) async fn replace_symbol_body(
&self,
params: Parameters<edit::ReplaceSymbolBodyInput>,
) -> String {
if let Some(result) = self.proxy_tool_call("replace_symbol_body", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if guard.capture_shared_file(¶ms.0.path).is_none() {
return missing_file_refusal(&guard, ¶ms.0.path);
}
}
let (abs_path, source_authority) = match prepare_exact_path_for_edit(self, ¶ms.0.path) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let repo_root = match self.capture_repo_root() {
Some(root) => root,
None => return "Error: no repository root configured.".to_string(),
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let idempotency = match begin_mutation_replay(
self,
"replace_symbol_body",
¶ms.0,
params.0.idempotency_key.as_deref(),
params.0.dry_run.unwrap_or(false),
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
let working_directory = params
.0
.working_directory
.as_deref()
.map(std::path::Path::new);
let hook_ctx = edit_hooks::EditContext {
relative_path: ¶ms.0.path,
indexed_absolute_path: &abs_path,
repo_root: &repo_root,
project_state_dir: project_state.as_ref(),
working_directory,
};
let resolved_target = match edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return fail_and_return_mutation_replay(&idempotency, format!("Error: {e}")),
};
let resolved_path = resolved_target.target_path.clone();
let file = {
let guard = self.index.data_plane().read();
loading_guard!(guard);
guard.capture_shared_file(¶ms.0.path)
};
let file = match file {
Some(f) => f,
None => {
return fail_and_return_mutation_replay(
&idempotency,
format::not_found_file(¶ms.0.path),
);
}
};
let edit_base = match edit::rebase_edit_base_for_reroute(file, &resolved_target) {
Ok(base) => base,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let source_authority = if edit_base.rebased {
edit_format::EditSourceAuthority::WorktreeTarget
} else {
source_authority
};
let file = edit_base.file;
if let Some(warning) = Self::check_edit_capability(
&file.language,
crate::parsing::config_extractors::EditCapability::StructuralEditSafe,
"replace_symbol_body",
) {
return fail_and_return_mutation_replay(&idempotency, warning);
}
let (_, sym) = match edit::resolve_or_error(
&file,
¶ms.0.name,
params.0.kind.as_deref(),
params.0.symbol_line,
) {
Ok(s) => s,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let evidence_anchor = symbol_anchor(¶ms.0.path, &sym);
if params.0.dry_run == Some(true) {
let old_bytes = (sym.byte_range.1 - sym.byte_range.0) as usize;
let summary = format!(
"[DRY RUN] Would replace `{}` in {} (old: {} bytes -> new: {} bytes)",
params.0.name,
params.0.path,
old_bytes,
params.0.new_body.len()
);
let mut result = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::DryRunNoWrites,
&evidence_anchor,
),
summary
);
append_project_config_trust_suffix(&mut result, project_config_trust_suffix.as_deref());
return result;
}
let old_bytes = (sym.byte_range.1 - sym.byte_range.0) as usize;
let new_body_supplies_docs = edit::body_starts_with_doc_comment(¶ms.0.new_body);
let effective = if new_body_supplies_docs {
sym.effective_start() as usize
} else {
sym.byte_range.0 as usize
};
let raw_line_start = file.content[..effective]
.iter()
.rposition(|&b| b == b'\n')
.map(|p| p + 1)
.unwrap_or(0);
let line_start = if new_body_supplies_docs {
edit::extend_past_orphaned_docs(&file.content, raw_line_start, &sym) as u32
} else {
edit::docless_replacement_splice_start(
&file.content,
raw_line_start,
sym.byte_range.0 as usize,
) as u32
};
let indent = edit::detect_indentation(&file.content, sym.byte_range.0);
let line_ending = edit::detect_line_ending(&file.content);
let normalized = edit::normalize_line_endings(params.0.new_body.as_bytes(), line_ending);
let normalized_str = std::str::from_utf8(&normalized).unwrap_or(¶ms.0.new_body);
let indented = edit::apply_indentation(normalized_str, &indent, line_ending);
let new_content =
edit::apply_splice(&file.content, (line_start, sym.byte_range.1), &indented);
let write_report = match edit::guarded_atomic_write_file(
&repo_root,
project_state.as_ref(),
&resolved_path,
&file.content,
&new_content,
params.0.if_match.as_deref(),
) {
Ok(edit::GuardedWriteOutcome::Written(report)) => report,
Ok(edit::GuardedWriteOutcome::Rejected) => {
let output = format!(
"{} — guarded apply rejected: on-disk body of `{}` in {} \
changed since if_match was captured; the concurrent change was left intact \
and nothing was written. Re-read the symbol and retry.",
edit_format::WRITE_MODE_FAILED_SENTINEL,
params.0.name,
params.0.path
);
fail_mutation_replay(&idempotency, &output);
return output;
}
Err(e) => {
let output = format!("Error writing {}: {e}", params.0.path);
fail_mutation_replay(&idempotency, &output);
return output;
}
};
let old_sig = edit::extract_signature(&file.content, sym.byte_range);
let new_sig = params.0.new_body.lines().next().unwrap_or("").to_string();
let parent_type = edit::find_parent_impl_type(&file, &sym);
if !resolved_target.rerouted {
edit::reindex_after_write(
self.index.data_plane(),
&resolved_path,
¶ms.0.path,
&new_content,
file.language,
);
}
edit_hooks::after_commit(&hook_ctx, &resolved_path);
let warnings = edit::detect_stale_references(
self.index.data_plane(),
¶ms.0.path,
¶ms.0.name,
&old_sig,
&new_sig,
parent_type.as_deref(),
Some(&file.language),
);
let mut result = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::AtomicWriteAndReindex,
&evidence_anchor,
),
edit_format::format_replace(
¶ms.0.path,
¶ms.0.name,
&sym.kind.to_string(),
old_bytes,
indented.len(),
)
);
result.push_str(&edit_format::format_stale_warnings(
¶ms.0.path,
¶ms.0.name,
&warnings,
));
result.push_str(&edit::format_tee_snapshot_suffix(&write_report));
result.push_str(&edit_format::format_reroute_suffix(
working_directory,
&resolved_target,
));
append_project_config_trust_suffix(&mut result, project_config_trust_suffix.as_deref());
self.append_impact_footer(&mut result, ¶ms.0.path);
complete_mutation_replay_with_receipt(
&idempotency,
&mut result,
Some(crate::idempotency::post_image_from_written_bytes(
&resolved_target.target_path,
&new_content,
)),
);
result
}
#[tool(
name = "insert_symbol",
description = "Insert code before or after one named symbol (position=before|after). Pass unindented code; not a replace (replace_symbol_body) or inner edit (edit_within_symbol).",
annotations(
read_only_hint = false,
destructive_hint = false,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn insert_symbol_tool(
&self,
params: Parameters<edit::InsertSymbolInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let output = self.insert_symbol(params).await;
let status = classify_edit_output(&output, dry_run);
self.record_tool_completion_with_success(
"insert_symbol",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, Vec::new())
}
pub(crate) async fn insert_symbol(
&self,
params: Parameters<edit::InsertSymbolInput>,
) -> String {
if let Some(result) = self.proxy_tool_call("insert_symbol", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
let position = params.0.position.as_deref().unwrap_or("after");
if position != "before" && position != "after" {
return format!("Error: position must be 'before' or 'after', got '{position}'");
}
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if guard.capture_shared_file(¶ms.0.path).is_none() {
return missing_file_refusal(&guard, ¶ms.0.path);
}
}
let (abs_path, source_authority) = match prepare_exact_path_for_edit(self, ¶ms.0.path) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let repo_root = match self.capture_repo_root() {
Some(root) => root,
None => return "Error: no repository root configured.".to_string(),
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let idempotency = match begin_mutation_replay(
self,
"insert_symbol",
¶ms.0,
params.0.idempotency_key.as_deref(),
params.0.dry_run.unwrap_or(false),
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
let working_directory = params
.0
.working_directory
.as_deref()
.map(std::path::Path::new);
let hook_ctx = edit_hooks::EditContext {
relative_path: ¶ms.0.path,
indexed_absolute_path: &abs_path,
repo_root: &repo_root,
project_state_dir: project_state.as_ref(),
working_directory,
};
let resolved_target = match edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return fail_and_return_mutation_replay(&idempotency, format!("Error: {e}")),
};
let resolved_path = resolved_target.target_path.clone();
let file = {
let guard = self.index.data_plane().read();
loading_guard!(guard);
guard.capture_shared_file(¶ms.0.path)
};
let file = match file {
Some(f) => f,
None => {
return fail_and_return_mutation_replay(
&idempotency,
format::not_found_file(¶ms.0.path),
);
}
};
let edit_base = match edit::rebase_edit_base_for_reroute(file, &resolved_target) {
Ok(base) => base,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let source_authority = if edit_base.rebased {
edit_format::EditSourceAuthority::WorktreeTarget
} else {
source_authority
};
let file = edit_base.file;
if let Some(warning) = Self::check_edit_capability(
&file.language,
crate::parsing::config_extractors::EditCapability::StructuralEditSafe,
"insert_symbol",
) {
return fail_and_return_mutation_replay(&idempotency, warning);
}
let (_, sym) = match edit::resolve_or_error(
&file,
¶ms.0.name,
params.0.kind.as_deref(),
params.0.symbol_line,
) {
Ok(s) => s,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let evidence_anchor = symbol_anchor(¶ms.0.path, &sym);
if params.0.dry_run == Some(true) {
let summary = format!(
"[DRY RUN] Would insert {} `{}` in {} ({} bytes of content)",
position,
params.0.name,
params.0.path,
params.0.content.len()
);
let mut result = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::DryRunNoWrites,
&evidence_anchor,
),
summary
);
append_project_config_trust_suffix(&mut result, project_config_trust_suffix.as_deref());
return result;
}
let line_ending = edit::detect_line_ending(&file.content);
let new_content = if position == "before" {
edit::build_insert_before(&file.content, &sym, ¶ms.0.content, line_ending)
} else {
edit::build_insert_after(&file.content, &sym, ¶ms.0.content, line_ending)
};
let write_report = match edit::atomic_write_file(
&repo_root,
project_state.as_ref(),
&resolved_path,
&new_content,
) {
Ok(report) => report,
Err(e) => {
let output = format!("Error writing {}: {e}", params.0.path);
fail_mutation_replay(&idempotency, &output);
return output;
}
};
if !resolved_target.rerouted {
edit::reindex_after_write(
self.index.data_plane(),
&resolved_path,
¶ms.0.path,
&new_content,
file.language,
);
}
edit_hooks::after_commit(&hook_ctx, &resolved_path);
let mut out = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::AtomicWriteAndReindex,
&evidence_anchor,
),
edit_format::format_insert(
¶ms.0.path,
¶ms.0.name,
position,
params.0.content.len(),
)
);
out.push_str(&edit_format::format_reroute_suffix(
working_directory,
&resolved_target,
));
out.push_str(&edit::format_tee_snapshot_suffix(&write_report));
append_project_config_trust_suffix(&mut out, project_config_trust_suffix.as_deref());
self.append_impact_footer(&mut out, ¶ms.0.path);
complete_mutation_replay_with_receipt(
&idempotency,
&mut out,
Some(crate::idempotency::post_image_from_written_bytes(
&resolved_target.target_path,
&new_content,
)),
);
out
}
#[tool(
name = "delete_symbol",
description = "Delete a symbol's entire definition and nearby blank lines. Not a body replace (replace_symbol_body) or a scoped find-replace (edit_within_symbol).",
annotations(
read_only_hint = false,
destructive_hint = true,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn delete_symbol_tool(
&self,
params: Parameters<edit::DeleteSymbolInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let output = self.delete_symbol(params).await;
let status = classify_edit_output(&output, dry_run);
self.record_tool_completion_with_success(
"delete_symbol",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, Vec::new())
}
pub(crate) async fn delete_symbol(
&self,
params: Parameters<edit::DeleteSymbolInput>,
) -> String {
if let Some(result) = self.proxy_tool_call("delete_symbol", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if guard.capture_shared_file(¶ms.0.path).is_none() {
return missing_file_refusal(&guard, ¶ms.0.path);
}
}
let (abs_path, source_authority) = match prepare_exact_path_for_edit(self, ¶ms.0.path) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let repo_root = match self.capture_repo_root() {
Some(root) => root,
None => return "Error: no repository root configured.".to_string(),
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let idempotency = match begin_mutation_replay(
self,
"delete_symbol",
¶ms.0,
params.0.idempotency_key.as_deref(),
params.0.dry_run.unwrap_or(false),
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
let working_directory = params
.0
.working_directory
.as_deref()
.map(std::path::Path::new);
let hook_ctx = edit_hooks::EditContext {
relative_path: ¶ms.0.path,
indexed_absolute_path: &abs_path,
repo_root: &repo_root,
project_state_dir: project_state.as_ref(),
working_directory,
};
let resolved_target = match edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return fail_and_return_mutation_replay(&idempotency, format!("Error: {e}")),
};
let resolved_path = resolved_target.target_path.clone();
let file = {
let guard = self.index.data_plane().read();
loading_guard!(guard);
guard.capture_shared_file(¶ms.0.path)
};
let file = match file {
Some(f) => f,
None => {
return fail_and_return_mutation_replay(
&idempotency,
format::not_found_file(¶ms.0.path),
);
}
};
let edit_base = match edit::rebase_edit_base_for_reroute(file, &resolved_target) {
Ok(base) => base,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let source_authority = if edit_base.rebased {
edit_format::EditSourceAuthority::WorktreeTarget
} else {
source_authority
};
let file = edit_base.file;
if let Some(warning) = Self::check_edit_capability(
&file.language,
crate::parsing::config_extractors::EditCapability::StructuralEditSafe,
"delete_symbol",
) {
return fail_and_return_mutation_replay(&idempotency, warning);
}
let (_, sym) = match edit::resolve_or_error(
&file,
¶ms.0.name,
params.0.kind.as_deref(),
params.0.symbol_line,
) {
Ok(s) => s,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let evidence_anchor = symbol_anchor(¶ms.0.path, &sym);
if params.0.dry_run == Some(true) {
let deleted_bytes = (sym.byte_range.1 - sym.byte_range.0) as usize;
let summary = format!(
"[DRY RUN] Would delete `{}` in {} ({} bytes)",
params.0.name, params.0.path, deleted_bytes
);
let mut result = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::DryRunNoWrites,
&evidence_anchor,
),
summary
);
append_project_config_trust_suffix(&mut result, project_config_trust_suffix.as_deref());
return result;
}
let deleted_bytes = (sym.byte_range.1 - sym.byte_range.0) as usize;
let line_ending = edit::detect_line_ending(&file.content);
let new_content = edit::build_delete(&file.content, &sym, line_ending);
let write_report = match edit::atomic_write_file(
&repo_root,
project_state.as_ref(),
&resolved_path,
&new_content,
) {
Ok(report) => report,
Err(e) => {
let output = format!("Error writing {}: {e}", params.0.path);
fail_mutation_replay(&idempotency, &output);
return output;
}
};
if !resolved_target.rerouted {
edit::reindex_after_write(
self.index.data_plane(),
&resolved_path,
¶ms.0.path,
&new_content,
file.language,
);
}
edit_hooks::after_commit(&hook_ctx, &resolved_path);
let mut out = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
source_authority,
edit_format::EditWriteSemantics::AtomicWriteAndReindex,
&evidence_anchor,
),
edit_format::format_delete(
¶ms.0.path,
¶ms.0.name,
&sym.kind.to_string(),
deleted_bytes,
)
);
out.push_str(&edit_format::format_reroute_suffix(
working_directory,
&resolved_target,
));
out.push_str(&edit::format_tee_snapshot_suffix(&write_report));
append_project_config_trust_suffix(&mut out, project_config_trust_suffix.as_deref());
self.append_impact_footer(&mut out, ¶ms.0.path);
complete_mutation_replay_with_receipt(
&idempotency,
&mut out,
Some(crate::idempotency::post_image_from_written_bytes(
&resolved_target.target_path,
&new_content,
)),
);
out
}
#[tool(
name = "edit_within_symbol",
description = "Find-and-replace inside one symbol's byte range only (replace_all=true for every hit). Not a whole-definition rewrite (replace_symbol_body) or a new symbol (insert_symbol).",
annotations(
read_only_hint = false,
destructive_hint = false,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn edit_within_symbol_tool(
&self,
params: Parameters<edit::EditWithinSymbolInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let output = self.edit_within_symbol(params).await;
let status = classify_edit_output(&output, dry_run);
self.record_tool_completion_with_success(
"edit_within_symbol",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, Vec::new())
}
pub(crate) async fn edit_within_symbol(
&self,
params: Parameters<edit::EditWithinSymbolInput>,
) -> String {
if let Some(result) = self.proxy_tool_call("edit_within_symbol", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if guard.capture_shared_file(¶ms.0.path).is_none() {
return missing_file_refusal(&guard, ¶ms.0.path);
}
}
let (abs_path, source_authority) = match prepare_exact_path_for_edit(self, ¶ms.0.path) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let repo_root = match self.capture_repo_root() {
Some(root) => root,
None => return "Error: no repository root configured.".to_string(),
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let idempotency = match begin_mutation_replay(
self,
"edit_within_symbol",
¶ms.0,
params.0.idempotency_key.as_deref(),
params.0.dry_run.unwrap_or(false),
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
let working_directory = params
.0
.working_directory
.as_deref()
.map(std::path::Path::new);
let hook_ctx = edit_hooks::EditContext {
relative_path: ¶ms.0.path,
indexed_absolute_path: &abs_path,
repo_root: &repo_root,
project_state_dir: project_state.as_ref(),
working_directory,
};
let resolved_target = match edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return fail_and_return_mutation_replay(&idempotency, format!("Error: {e}")),
};
let resolved_path = resolved_target.target_path.clone();
let file = {
let guard = self.index.data_plane().read();
loading_guard!(guard);
guard.capture_shared_file(¶ms.0.path)
};
let file = match file {
Some(f) => f,
None => {
return fail_and_return_mutation_replay(
&idempotency,
format::not_found_file(¶ms.0.path),
);
}
};
let edit_base = match edit::rebase_edit_base_for_reroute(file, &resolved_target) {
Ok(base) => base,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let source_authority = if edit_base.rebased {
edit_format::EditSourceAuthority::WorktreeTarget
} else {
source_authority
};
let file = edit_base.file;
if let Some(warning) = Self::check_edit_capability(
&file.language,
crate::parsing::config_extractors::EditCapability::TextEditSafe,
"edit_within_symbol",
) {
return fail_and_return_mutation_replay(&idempotency, warning);
}
let (_, sym) = match edit::resolve_or_error(
&file,
¶ms.0.name,
params.0.kind.as_deref(),
params.0.symbol_line,
) {
Ok(s) => s,
Err(e) => return fail_and_return_mutation_replay(&idempotency, e),
};
let evidence_anchor = symbol_anchor(¶ms.0.path, &sym);
let sym_start = sym.effective_start() as usize;
let sym_end = sym.byte_range.1 as usize;
let body = &file.content[sym_start..sym_end];
let body_str = match std::str::from_utf8(body) {
Ok(s) => s,
Err(_) => {
return fail_and_return_mutation_replay(
&idempotency,
"Error: symbol body is not valid UTF-8.".to_string(),
);
}
};
let line_ending = edit::detect_line_ending(&file.content);
let normalized_old =
edit::normalize_line_endings(params.0.old_text.as_bytes(), line_ending);
let normalized_old_str =
String::from_utf8(normalized_old).unwrap_or_else(|_| params.0.old_text.clone());
let normalized_new =
edit::normalize_line_endings(params.0.new_text.as_bytes(), line_ending);
let normalized_new_str =
String::from_utf8(normalized_new).unwrap_or_else(|_| params.0.new_text.clone());
let targeting_modes = usize::from(params.0.replace_all)
+ usize::from(params.0.occurrence.is_some())
+ usize::from(params.0.near_line.is_some());
if targeting_modes > 1 {
return fail_and_return_mutation_replay(
&idempotency,
"Error: `replace_all`, `occurrence`, and `near_line` are mutually exclusive — pass at most one targeting mode.".to_string(),
);
}
let (new_body, count, untargeted_extra) = if params.0.replace_all {
let count = body_str.matches(&normalized_old_str).count();
if count > 0 {
(
body_str.replace(&normalized_old_str, &normalized_new_str),
count,
0,
)
} else {
match edit::try_whitespace_flexible_replace(
body_str,
&normalized_old_str,
&normalized_new_str,
true,
) {
Some((body, count)) => (body, count, 0),
None => (body_str.to_string(), 0, 0), }
}
} else if params.0.occurrence.is_some() || params.0.near_line.is_some() {
let positions: Vec<usize> = body_str
.match_indices(normalized_old_str.as_str())
.map(|(pos, _)| pos)
.collect();
if positions.is_empty() {
(body_str.to_string(), 0, 0) } else {
let index = if let Some(n) = params.0.occurrence {
let n = n as usize;
if n == 0 || n > positions.len() {
return fail_and_return_mutation_replay(
&idempotency,
format!(
"Error: occurrence {n} is out of range — `old_text` has {} exact occurrence(s) within `{}`.",
positions.len(),
params.0.name
),
);
}
n - 1
} else {
let target = i64::from(params.0.near_line.unwrap_or(1));
let line_of = |pos: usize| {
1 + file.content[..sym_start + pos]
.iter()
.filter(|&&byte| byte == b'\n')
.count() as i64
};
(0..positions.len())
.min_by_key(|&i| (line_of(positions[i]) - target).abs())
.unwrap_or(0)
};
let pos = positions[index];
let mut body = String::with_capacity(body_str.len() + normalized_new_str.len());
body.push_str(&body_str[..pos]);
body.push_str(&normalized_new_str);
body.push_str(&body_str[pos + normalized_old_str.len()..]);
(body, 1, 0)
}
} else {
match body_str.find(&normalized_old_str) {
Some(_) => (
body_str.replacen(&normalized_old_str, &normalized_new_str, 1),
1,
body_str
.matches(&normalized_old_str)
.count()
.saturating_sub(1),
),
None => {
match edit::try_whitespace_flexible_replace(
body_str,
&normalized_old_str,
&normalized_new_str,
false,
) {
Some((body, count)) => (body, count, 0),
None => {
let preview_len = 800.min(body_str.len());
let preview = &body_str[..preview_len];
let truncated = if preview_len < body_str.len() {
format!("\n... ({} more bytes)", body_str.len() - preview_len)
} else {
String::new()
};
let output = format!(
"Error: `{}` not found within symbol `{}`. \
The symbol body is ({} bytes):\n```\n{}{}\n```",
params.0.old_text,
params.0.name,
body_str.len(),
preview,
truncated
);
return fail_and_return_mutation_replay(&idempotency, output);
}
}
}
}
};
if params.0.dry_run == Some(true) {
if count == 0 {
let preview_len = 800.min(body_str.len());
let preview = &body_str[..preview_len];
let truncated = if preview_len < body_str.len() {
format!("\n... ({} more bytes)", body_str.len() - preview_len)
} else {
String::new()
};
let output = format!(
"Error: `{}` not found within symbol `{}`. \
The symbol body is ({} bytes):\n```\n{}{}\n```",
params.0.old_text,
params.0.name,
body_str.len(),
preview,
truncated
);
return fail_and_return_mutation_replay(&idempotency, output);
}
let mut result = format!(
"{}\n[DRY RUN] Would edit within `{}` in {} ({} replacement(s))",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::TextEditSafe,
source_authority,
edit_format::EditWriteSemantics::DryRunNoWrites,
&evidence_anchor,
),
params.0.name,
params.0.path,
count
);
if untargeted_extra > 0 {
result.push_str(&format!(
"\nNote: `old_text` occurs {} times within `{}`; this targets the FIRST. Pass `occurrence: N` or `near_line: L` to pick another.",
untargeted_extra + 1,
params.0.name
));
}
append_project_config_trust_suffix(&mut result, project_config_trust_suffix.as_deref());
return result;
}
if count == 0 {
let preview_len = 800.min(body_str.len());
let preview = &body_str[..preview_len];
let truncated = if preview_len < body_str.len() {
format!("\n... ({} more bytes)", body_str.len() - preview_len)
} else {
String::new()
};
let output = format!(
"Error: `{}` not found within symbol `{}`. \
The symbol body is ({} bytes):\n```\n{}{}\n```",
params.0.old_text,
params.0.name,
body_str.len(),
preview,
truncated
);
return fail_and_return_mutation_replay(&idempotency, output);
}
let old_sym_bytes = sym_end - sym_start;
let effective_range = (sym.effective_start(), sym.byte_range.1);
let new_content = edit::apply_splice(&file.content, effective_range, new_body.as_bytes());
let write_report = match edit::atomic_write_file(
&repo_root,
project_state.as_ref(),
&resolved_path,
&new_content,
) {
Ok(report) => report,
Err(e) => {
let output = format!("Error writing {}: {e}", params.0.path);
fail_mutation_replay(&idempotency, &output);
return output;
}
};
if !resolved_target.rerouted {
edit::reindex_after_write(
self.index.data_plane(),
&resolved_path,
¶ms.0.path,
&new_content,
file.language,
);
}
edit_hooks::after_commit(&hook_ctx, &resolved_path);
let mut out = format!(
"{}\n{}",
edit_format::format_edit_envelope(
edit_format::EditSafetyMode::TextEditSafe,
source_authority,
edit_format::EditWriteSemantics::AtomicWriteAndReindex,
&evidence_anchor,
),
edit_format::format_edit_within(
¶ms.0.path,
¶ms.0.name,
count,
old_sym_bytes,
new_body.len(),
)
);
if untargeted_extra > 0 {
out.push_str(&format!(
"\nNote: `old_text` occurred {} times within `{}`; edited the FIRST. Pass `occurrence: N` or `near_line: L` to target another.",
untargeted_extra + 1,
params.0.name
));
}
out.push_str(&edit_format::format_reroute_suffix(
working_directory,
&resolved_target,
));
out.push_str(&edit::format_tee_snapshot_suffix(&write_report));
append_project_config_trust_suffix(&mut out, project_config_trust_suffix.as_deref());
self.append_impact_footer(&mut out, ¶ms.0.path);
complete_mutation_replay_with_receipt(
&idempotency,
&mut out,
Some(crate::idempotency::post_image_from_written_bytes(
&resolved_target.target_path,
&new_content,
)),
);
out
}
#[tool(
name = "batch_edit",
description = "Apply many symbol-addressed edits atomically across files (all resolve or none write); dry_run=true previews. Not a single-symbol edit (replace_symbol_body / insert_symbol).",
annotations(
read_only_hint = false,
destructive_hint = true,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn batch_edit_tool(
&self,
params: Parameters<edit::BatchEditInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let operation_count = params.0.edits.len();
let output = self.batch_edit(params).await;
let status = classify_edit_output(&output, dry_run);
let operation_statuses = match status {
EditResultStatus::Success | EditResultStatus::DryRunSuccess => {
success_operation_statuses(operation_count, status)
}
_ => failed_batch_operation_statuses(&output, status),
};
self.record_tool_completion_with_success(
"batch_edit",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, operation_statuses)
}
pub(crate) async fn batch_edit(&self, params: Parameters<edit::BatchEditInput>) -> String {
if let Some(result) = self.proxy_tool_call("batch_edit", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
let batch_paths: Vec<String> = params.0.edits.iter().map(|e| e.path.clone()).collect();
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if let Some(notice) = batch_paths
.iter()
.find_map(|path| crate::protocol::read_gate::unverified_notice(&guard, path))
{
return notice;
}
}
let (repo_root, source_authority) = match prepare_batch_paths_for_edit(self, &batch_paths) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let dry_run = params.0.dry_run.unwrap_or(false);
let idempotency = match begin_mutation_replay(
self,
"batch_edit",
¶ms.0,
params.0.idempotency_key.as_deref(),
dry_run,
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
match edit::execute_batch_edit(
self.index.data_plane(),
&repo_root,
project_state.as_ref(),
¶ms.0.edits,
dry_run,
params
.0
.working_directory
.as_deref()
.map(std::path::Path::new),
) {
Ok((summaries, written_paths)) => {
let file_count = params
.0
.edits
.iter()
.map(|e| e.path.as_str())
.collect::<std::collections::HashSet<_>>()
.len();
let write_semantics = if dry_run {
edit_format::EditWriteSemantics::DryRunNoWrites
} else {
edit_format::EditWriteSemantics::TransactionalWriteRollbackAndReindex
};
let evidence = format!(
"{} edit target(s) across {} file(s)",
params.0.edits.len(),
file_count
);
let mut result = format!(
"{}\n{}",
edit_format::format_batch_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
edit_format::MatchType::Exact,
source_authority,
write_semantics,
&evidence,
),
edit_format::format_batch_summary(&summaries, file_count),
);
append_project_config_trust_suffix(
&mut result,
project_config_trust_suffix.as_deref(),
);
if let Some(primary) = params.0.edits.first() {
self.append_impact_footer(&mut result, &primary.path);
}
complete_mutation_replay(&idempotency, &mut result, &written_paths);
result
}
Err(e) => {
fail_mutation_replay(&idempotency, &e);
e
}
}
}
#[tool(
name = "batch_rename",
description = "Rename a symbol and update confident references project-wide; dry_run=true previews. Uncertain matches stay for review; not a body rewrite (replace_symbol_body).",
annotations(
read_only_hint = false,
destructive_hint = true,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn batch_rename_tool(
&self,
params: Parameters<edit::BatchRenameInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let output = self.batch_rename(params).await;
let status = classify_edit_output(&output, dry_run);
self.record_tool_completion_with_success(
"batch_rename",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, Vec::new())
}
pub(crate) async fn batch_rename(&self, params: Parameters<edit::BatchRenameInput>) -> String {
if let Some(result) = self.proxy_tool_call("batch_rename", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
let repo_root = match self.capture_repo_root() {
Some(root) => root,
None => return "Error: no repository root configured.".to_string(),
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if let Some(refusal) = format::project_wide_mutation_refused_unverified(
"batch_rename",
guard.withheld_since_restore(),
) {
return refusal;
}
}
let source_authority = prepare_project_wide_rename(self, &repo_root);
let dry_run = params.0.dry_run.unwrap_or(false);
let idempotency = match begin_mutation_replay(
self,
"batch_rename",
¶ms.0,
params.0.idempotency_key.as_deref(),
dry_run,
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
match edit::execute_batch_rename(
self.index.data_plane(),
&repo_root,
project_state.as_ref(),
¶ms.0,
) {
Ok((summary, written_paths)) => {
let write_semantics = if dry_run {
edit_format::EditWriteSemantics::DryRunNoWrites
} else {
edit_format::EditWriteSemantics::TransactionalWriteRollbackAndReindex
};
let evidence = format!(
"definition `{}` + project-wide constrained references",
params.0.path
);
let mut result = format!(
"{}\n{}",
edit_format::format_batch_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
edit_format::MatchType::Constrained,
source_authority,
write_semantics,
&evidence,
),
summary,
);
append_project_config_trust_suffix(
&mut result,
project_config_trust_suffix.as_deref(),
);
self.append_impact_footer(&mut result, ¶ms.0.path);
complete_mutation_replay(&idempotency, &mut result, &written_paths);
result
}
Err(e) => {
fail_mutation_replay(&idempotency, &e);
e
}
}
}
#[tool(
name = "batch_insert",
description = "Insert the same snippet before or after many symbols (logging, boilerplate); dry_run=true previews. Not a single-location insert (insert_symbol).",
annotations(
read_only_hint = false,
destructive_hint = false,
idempotent_hint = false,
open_world_hint = false
)
)]
pub(crate) async fn batch_insert_tool(
&self,
params: Parameters<edit::BatchInsertInput>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let started = Instant::now();
let dry_run = params.0.dry_run.unwrap_or(false);
let operation_count = params.0.targets.len();
let output = self.batch_insert(params).await;
let status = classify_edit_output(&output, dry_run);
let operation_statuses = match status {
EditResultStatus::Success | EditResultStatus::DryRunSuccess => {
success_operation_statuses(operation_count, status)
}
_ => failed_batch_operation_statuses(&output, status),
};
self.record_tool_completion_with_success(
"batch_insert",
&output,
started.elapsed(),
status.outcome_class(),
!status.is_terminal_failure(),
);
statused_edit_tool_result(output, status, operation_statuses)
}
pub(crate) async fn batch_insert(&self, params: Parameters<edit::BatchInsertInput>) -> String {
if let Some(result) = self.proxy_tool_call("batch_insert", ¶ms.0).await {
return result;
}
if let Some(refusal) = self.foreign_project_refusal(params.0.project.as_deref()) {
return refusal;
}
self.note_worktree_misuse_if_active(params.0.working_directory.as_deref());
let batch_paths: Vec<String> = params.0.targets.iter().map(|t| t.path.clone()).collect();
{
let guard = self.index.data_plane().read();
loading_guard!(guard);
if let Some(notice) = batch_paths
.iter()
.find_map(|path| crate::protocol::read_gate::unverified_notice(&guard, path))
{
return notice;
}
}
let (repo_root, source_authority) = match prepare_batch_paths_for_edit(self, &batch_paths) {
Ok(prepared) => prepared,
Err(e) => return e,
};
let project_state = self.capture_project_state_dir();
let project_config_trust_suffix = match project_config_trust_response_suffix(&repo_root) {
Ok(suffix) => suffix,
Err(message) => return message,
};
let dry_run = params.0.dry_run.unwrap_or(false);
let idempotency = match begin_mutation_replay(
self,
"batch_insert",
¶ms.0,
params.0.idempotency_key.as_deref(),
dry_run,
) {
Ok(idempotency) => idempotency,
Err(output) => return output,
};
match edit::execute_batch_insert(
self.index.data_plane(),
&repo_root,
project_state.as_ref(),
¶ms.0,
) {
Ok((summaries, written_paths)) => {
let file_count = params
.0
.targets
.iter()
.map(|t| t.path.as_str())
.collect::<std::collections::HashSet<_>>()
.len();
let write_semantics = if dry_run {
edit_format::EditWriteSemantics::DryRunNoWrites
} else {
edit_format::EditWriteSemantics::TransactionalWriteRollbackAndReindex
};
let evidence = format!(
"{} target(s) across {} file(s)",
params.0.targets.len(),
file_count
);
let mut result = format!(
"{}\n{}",
edit_format::format_batch_envelope(
edit_format::EditSafetyMode::StructuralEditSafe,
edit_format::MatchType::Exact,
source_authority,
write_semantics,
&evidence,
),
edit_format::format_batch_summary(&summaries, file_count),
);
append_project_config_trust_suffix(
&mut result,
project_config_trust_suffix.as_deref(),
);
if let Some(primary) = params.0.targets.first() {
self.append_impact_footer(&mut result, &primary.path);
}
complete_mutation_replay(&idempotency, &mut result, &written_paths);
result
}
Err(e) => {
fail_mutation_replay(&idempotency, &e);
e
}
}
}
}