use std::path::{Path, PathBuf};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::domain::index::{LanguageId, SymbolRecord};
use crate::live_index::SharedIndex;
use crate::live_index::store::IndexedFile;
pub(crate) fn safe_repo_path(repo_root: &Path, relative_path: &str) -> Result<PathBuf, String> {
resolve_repo_path(repo_root, relative_path)?
.ok_or_else(|| format!("cannot resolve path '{relative_path}': not found on disk"))
}
pub(crate) use crate::index_lifecycle::guidance::read_gate::{
PATH_SPELLING_DIFFERS, resolve_repo_path,
};
#[cfg(test)]
use crate::edit_safety::structural::{
LineEnding, body_starts_with_doc_comment, collapse_blank_lines,
docless_replacement_splice_start,
};
pub(crate) use crate::edit_safety::structural::{
apply_indentation, apply_splice, build_delete, build_edit_within, build_insert_after,
build_insert_before, detect_indentation, detect_line_ending, extend_past_orphaned_docs,
normalize_line_endings,
};
#[cfg(test)]
pub(crate) use crate::edit_safety::atomic_write::install_write_interleave_hook;
pub(crate) use crate::edit_safety::atomic_write::{
AtomicWriteReport, GuardedWriteOutcome, atomic_write_file, format_tee_snapshot_suffix,
guarded_atomic_write_file,
};
use crate::index_lifecycle::guidance::edit_body::append_response_suffix_to_first_summary;
fn commit_protocol_batch_images(
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
images: &[crate::edit_safety::batch_commit::StagedImage],
operation: &str,
) -> Result<(), String> {
use crate::edit_safety::batch_commit::{BatchAbort, ProtocolBatchIo, commit_staged};
let mut io = ProtocolBatchIo {
repo_root,
project_state_dir,
};
match commit_staged(images, &mut io, None) {
Ok(_) => Ok(()),
Err(BatchAbort::Conflict { index }) => Err(format!(
"Write conflict for {}: on-disk bytes changed after staging. No {operation} was applied.",
images[index].relative.display(),
)),
Err(BatchAbort::PreflightUnavailable { index }) => Err(format!(
"Write failed for {}: source pre-image could not be verified. No {operation} was applied.",
images[index].relative.display(),
)),
Err(BatchAbort::WriteFailed {
index,
reason,
restored,
uncertain,
}) => {
if uncertain.is_empty() {
Err(format!(
"Write failed for {}: {reason}\n\nROLLED BACK — {restored} file(s) restored to original content. No {operation} was applied.",
images[index].relative.display(),
))
} else {
Err(format!(
"Write failed for {}: {reason}\n\nROLLBACK INCOMPLETE — {} file(s) could not be verified. Manually verify affected files.",
images[index].relative.display(),
uncertain.len(),
))
}
}
Err(BatchAbort::Cancelled { .. }) => {
unreachable!("MCP batch operations do not pass a cancellation signal")
}
}
}
pub(crate) fn reindex_after_write(
index: &SharedIndex,
abs_path: &Path,
relative_path: &str,
written: &[u8],
language: LanguageId,
) {
let on_disk = match std::fs::read(abs_path) {
Ok(bytes) => bytes,
Err(e) => {
tracing::warn!(
"reindex_after_write: failed to re-read {}: {e}",
abs_path.display()
);
return;
}
};
debug_assert_eq!(
written,
on_disk.as_slice(),
"reindex_after_write: disk content differs from written buffer for {}",
abs_path.display()
);
let targets = crate::domain::IndexTargets::for_path(relative_path, Some(&language));
let root = index.read().indexed_root.clone();
let admission = match root {
Some(root) => crate::knowledge::classify_stable_content_for_root(
&root,
relative_path,
targets,
&on_disk,
),
None => crate::knowledge::classify_stable_content(relative_path, targets, &on_disk),
};
if let crate::knowledge::StableContentAdmission::MetadataOnly(_) = admission {
drop(on_disk);
index.remove_file(relative_path);
tracing::warn!(
"reindex_after_write: {relative_path} withheld from the index by content policy"
);
return;
}
let mtime_secs = std::fs::metadata(abs_path)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
let result = crate::parsing::process_file(relative_path, &on_disk, language);
let indexed = IndexedFile::from_parse_result(result, on_disk).with_mtime(mtime_secs);
index.update_file(relative_path.to_string(), indexed);
}
pub(crate) struct EditBase {
pub file: std::sync::Arc<IndexedFile>,
pub rebased: bool,
}
pub(crate) fn rebase_edit_base_for_reroute(
file: std::sync::Arc<IndexedFile>,
resolved: &crate::worktree::ResolvedTarget,
) -> Result<EditBase, String> {
if !resolved.rerouted {
return Ok(EditBase {
file,
rebased: false,
});
}
let target_bytes = std::fs::read(&resolved.target_path).map_err(|e| {
format!(
"Error: cannot read rerouted edit target {}: {e}",
resolved.target_path.display()
)
})?;
if target_bytes == file.content {
return Ok(EditBase {
file,
rebased: false,
});
}
let result = crate::parsing::process_file(&file.relative_path, &target_bytes, file.language);
Ok(EditBase {
file: std::sync::Arc::new(IndexedFile::from_parse_result(result, target_bytes)),
rebased: true,
})
}
fn line_ending_insensitive_eq(a: &[u8], b: &[u8]) -> bool {
let mut ai = a.iter().peekable();
let mut bi = b.iter().peekable();
loop {
while ai.peek() == Some(&&b'\r') {
let mut look = ai.clone();
look.next();
if look.peek() == Some(&&b'\n') {
ai.next();
} else {
break;
}
}
while bi.peek() == Some(&&b'\r') {
let mut look = bi.clone();
look.next();
if look.peek() == Some(&&b'\n') {
bi.next();
} else {
break;
}
}
match (ai.next(), bi.next()) {
(None, None) => return true,
(Some(x), Some(y)) if x == y => {}
_ => return false,
}
}
}
pub(crate) fn guard_batch_reroute_divergence(
resolved: &crate::worktree::ResolvedTarget,
indexed_content: &[u8],
relative_path: &str,
) -> Result<Vec<u8>, String> {
if !resolved.rerouted {
return Ok(indexed_content.to_vec());
}
let target_bytes = std::fs::read(&resolved.target_path).map_err(|e| {
format!(
"Error: cannot read rerouted batch target {}: {e}",
resolved.target_path.display()
)
})?;
if target_bytes == indexed_content || line_ending_insensitive_eq(&target_bytes, indexed_content)
{
return Ok(target_bytes);
}
Err(format!(
"Error: rerouted batch edit refused for '{relative_path}': the worktree target {} has \
diverged from the indexed copy (likely an earlier routed edit). Batch tools splice \
index-resolved byte ranges and would overwrite those changes. Use the single-symbol \
edit tools (replace_symbol_body / edit_within_symbol / insert_symbol / delete_symbol) \
with the same working_directory — they rebase onto the worktree target — or commit the \
worktree changes and reindex.",
resolved.target_path.display()
))
}
pub(crate) use crate::index_lifecycle::guidance::edit_body;
pub(crate) use crate::index_lifecycle::guidance::edit_body::resolve_or_error;
#[cfg(test)]
pub(crate) use crate::edit_safety::structural::try_whitespace_flexible_replace;
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct ReplaceSymbolBodyInput {
#[serde(default)]
pub project: Option<String>,
pub path: String,
#[serde(alias = "symbol")]
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
#[serde(alias = "body")]
pub new_body: String,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub if_match: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct InsertSymbolInput {
#[serde(default)]
pub project: Option<String>,
pub path: String,
#[serde(alias = "symbol")]
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
pub content: String,
#[serde(default)]
pub position: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct DeleteSymbolInput {
#[serde(default)]
pub project: Option<String>,
pub path: String,
#[serde(alias = "symbol")]
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct EditWithinSymbolInput {
#[serde(default)]
pub project: Option<String>,
pub path: String,
#[serde(alias = "symbol")]
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
pub old_text: String,
pub new_text: String,
#[serde(default)]
pub replace_all: bool,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub occurrence: Option<u32>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub near_line: Option<u32>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct BatchEditInput {
#[serde(default)]
pub project: Option<String>,
#[serde(deserialize_with = "super::tools::lenient_vec_required")]
#[schemars(with = "Vec<SingleEdit>")]
pub edits: Vec<SingleEdit>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Serialize, JsonSchema)]
pub struct SingleEdit {
pub path: String,
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
pub operation: EditOperation,
#[serde(default)]
pub working_directory: Option<String>,
}
impl SingleEdit {
fn from_shorthand(s: &str) -> Option<Self> {
let (target, op_str) = s.split_once(" => ")?;
let (path, name) = if let Some(pos) = target.find("::") {
(target[..pos].trim(), &target[pos + 2..])
} else {
let pos = target.rfind(':')?;
(target[..pos].trim(), &target[pos + 1..])
};
if path.is_empty() || name.is_empty() {
return None;
}
let op_str = op_str.trim();
let operation = if op_str == "delete" {
EditOperation::Delete
} else if let Some(body) = op_str.strip_prefix("replace ") {
EditOperation::Replace {
new_body: body.to_string(),
}
} else if let Some(body) = op_str.strip_prefix("insert_before ") {
EditOperation::InsertBefore {
content: body.to_string(),
}
} else if let Some(body) = op_str.strip_prefix("insert_after ") {
EditOperation::InsertAfter {
content: body.to_string(),
}
} else {
let body = op_str.strip_prefix("edit_within ")?;
let (old_text, new_text) = body.split_once(" >>> ")?;
EditOperation::EditWithin {
old_text: old_text.to_string(),
new_text: new_text.to_string(),
}
};
Some(SingleEdit {
path: path.to_string(),
name: name.trim().to_string(),
kind: None,
symbol_line: None,
operation,
working_directory: None,
})
}
}
impl<'de> serde::Deserialize<'de> for SingleEdit {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(serde::Deserialize)]
struct EditFields {
path: String,
#[serde(alias = "symbol")]
name: String,
#[serde(default)]
kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
symbol_line: Option<u32>,
operation: EditOperation,
#[serde(default)]
working_directory: Option<String>,
}
enum EditOrStr {
Struct(EditFields),
Str(String),
}
struct EditVisitor;
impl<'de> serde::de::Visitor<'de> for EditVisitor {
type Value = EditOrStr;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a SingleEdit object or a string")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<EditOrStr, E> {
Ok(EditOrStr::Str(s.to_owned()))
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
map: A,
) -> Result<EditOrStr, A::Error> {
EditFields::deserialize(serde::de::value::MapAccessDeserializer::new(map))
.map(EditOrStr::Struct)
}
}
match deserializer.deserialize_any(EditVisitor)? {
EditOrStr::Struct(EditFields {
path,
name,
kind,
symbol_line,
operation,
working_directory,
}) => Ok(SingleEdit {
path,
name,
kind,
symbol_line,
operation,
working_directory,
}),
EditOrStr::Str(s) => {
if let Ok(edit) = serde_json::from_str::<serde_json::Value>(&s)
&& edit.is_object()
{
super::tool_contract::note_keys_of::<EditFields>(&edit);
let path = edit
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let name = edit
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let kind = edit.get("kind").and_then(|v| v.as_str()).map(String::from);
let symbol_line = edit
.get("symbol_line")
.and_then(|v| v.as_u64())
.map(|n| n as u32);
let operation: EditOperation = edit
.get("operation")
.ok_or_else(|| {
D::Error::custom("missing 'operation' in stringified SingleEdit")
})
.and_then(|op| {
serde_json::from_value(op.clone()).map_err(D::Error::custom)
})?;
let working_directory = edit
.get("working_directory")
.and_then(|v| v.as_str())
.map(String::from);
if path.is_empty() || name.is_empty() {
return Err(D::Error::custom(format!(
"SingleEdit stringified object must have non-empty path and name, got '{s}'"
)));
}
return Ok(SingleEdit {
path,
name,
kind,
symbol_line,
operation,
working_directory,
});
}
SingleEdit::from_shorthand(&s).ok_or_else(|| {
D::Error::custom(format!(
"SingleEdit string must be 'path::name => operation body' \
(operations: replace, insert_before, insert_after, delete, \
edit_within old >>> new) or a JSON object with \
path/name/operation fields, got '{s}'"
))
})
}
}
}
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum EditOperation {
#[serde(rename = "replace")]
Replace { new_body: String },
#[serde(rename = "insert_before")]
InsertBefore { content: String },
#[serde(rename = "insert_after")]
InsertAfter { content: String },
#[serde(rename = "delete")]
Delete,
#[serde(rename = "edit_within")]
EditWithin { old_text: String, new_text: String },
}
pub(crate) fn execute_batch_edit(
index: &SharedIndex,
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
edits: &[SingleEdit],
dry_run: bool,
top_level_working_directory: Option<&Path>,
) -> Result<(Vec<String>, Vec<std::path::PathBuf>), String> {
struct ResolvedEdit {
path: String,
sym: SymbolRecord,
operation: usize,
language: LanguageId,
}
crate::worktree::refuse_network_working_directories(
std::iter::once(top_level_working_directory).chain(
edits
.iter()
.map(|e| e.working_directory.as_deref().map(Path::new)),
),
)
.map_err(|error| error.to_string())?;
let n = edits.len();
let targeted_paths: Vec<&str> = edits.iter().map(|e| e.path.as_str()).collect();
let rollback_footer = |paths: &[&str]| -> String {
let path_list = paths
.iter()
.map(|p| format!(" - {p}"))
.collect::<Vec<_>>()
.join("\n");
format!("\n\nROLLED BACK — {n} edit(s) attempted on:\n{path_list}\nNo files were modified.")
};
let mut resolved = Vec::with_capacity(n);
let mut source_files = std::collections::HashMap::new();
{
let guard = index.read();
for (i, edit) in edits.iter().enumerate() {
let file = guard.capture_shared_file(&edit.path).ok_or_else(|| {
format!(
"File not indexed: {}{}",
edit.path,
rollback_footer(&targeted_paths)
)
})?;
let (_, sym) =
resolve_or_error(&file, &edit.name, edit.kind.as_deref(), edit.symbol_line)
.map_err(|e| {
format!("Edit {}: {e}{}", i + 1, rollback_footer(&targeted_paths))
})?;
resolved.push(ResolvedEdit {
path: edit.path.clone(),
sym,
operation: i,
language: file.language,
});
source_files.entry(edit.path.clone()).or_insert(file);
}
}
let mut by_file: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for (i, r) in resolved.iter().enumerate() {
by_file.entry(r.path.clone()).or_default().push(i);
}
let mut insert_before_positions = std::collections::HashMap::new();
for (path, indices) in &by_file {
for i in 0..indices.len() {
for j in (i + 1)..indices.len() {
let a = (
resolved[indices[i]].sym.effective_start(),
resolved[indices[i]].sym.byte_range.1,
);
let b = (
resolved[indices[j]].sym.effective_start(),
resolved[indices[j]].sym.byte_range.1,
);
if a.0 < b.1 && b.0 < a.1 {
return Err(format!(
"Overlapping edits in {path}: `{}` ({}-{}) and `{}` ({}-{}). \
Split into separate calls.{}",
resolved[indices[i]].sym.name,
a.0,
a.1,
resolved[indices[j]].sym.name,
b.0,
b.1,
rollback_footer(&targeted_paths),
));
}
}
}
let file = &source_files[path];
if indices.iter().any(|&index| {
resolved[index].sym.effective_start() as usize > file.content.len()
|| resolved[index].sym.byte_range.1 as usize > file.content.len()
}) {
continue; }
let line_ending = detect_line_ending(&file.content);
let footprints = indices
.iter()
.map(|&index| {
let symbol = &resolved[index].sym;
Ok(match &edits[resolved[index].operation].operation {
EditOperation::InsertBefore { .. } => {
let position = crate::edit_safety::structural::insert_before_position(
&file.content,
symbol,
&file.language,
)?;
insert_before_positions.insert(
index,
(
position,
detect_indentation(&file.content, symbol.byte_range.0),
),
);
crate::edit_safety::structural::SpliceFootprint::Insert(position)
}
EditOperation::InsertAfter { .. } => {
crate::edit_safety::structural::SpliceFootprint::Insert(
crate::edit_safety::structural::insert_after_position(
&file.content,
symbol,
),
)
}
EditOperation::Delete => {
let (start, end) = crate::edit_safety::structural::delete_source_range(
&file.content,
symbol,
line_ending,
);
crate::edit_safety::structural::SpliceFootprint::Bytes(start, end)
}
EditOperation::Replace { new_body } => {
let (start, end) =
crate::edit_safety::structural::replacement_splice_range(
&file.content,
symbol,
new_body,
)
.unwrap_or((symbol.effective_start(), symbol.byte_range.1));
crate::edit_safety::structural::SpliceFootprint::Bytes(start, end)
}
EditOperation::EditWithin { .. } => {
crate::edit_safety::structural::SpliceFootprint::Bytes(
symbol.effective_start(),
symbol.byte_range.1,
)
}
})
})
.collect::<Result<Vec<_>, String>>()?;
for left in 0..footprints.len() {
for right in (left + 1)..footprints.len() {
if crate::edit_safety::structural::splice_footprints_overlap(
footprints[left],
footprints[right],
) {
return Err(format!(
"Overlapping splice footprints in {path}. Split into separate calls.{}",
rollback_footer(&targeted_paths),
));
}
}
}
for (position, &index) in indices.iter().enumerate() {
if !matches!(
&edits[resolved[index].operation].operation,
EditOperation::Delete
) {
continue;
}
let cleanup = crate::edit_safety::structural::delete_cleanup_ranges(
&file.content,
&resolved[index].sym,
line_ending,
);
if footprints.iter().enumerate().any(|(other, footprint)| {
other != position
&& crate::edit_safety::structural::cleanup_invalidates_splice(
&cleanup, *footprint,
)
}) {
return Err(format!(
"Overlapping delete cleanup in {path}. Split into separate calls.{}",
rollback_footer(&targeted_paths),
));
}
}
}
for indices in by_file.values_mut() {
indices.sort_by(|&a, &b| {
resolved[b]
.sym
.effective_start()
.cmp(&resolved[a].sym.effective_start())
});
}
#[cfg(test)]
tests::run_before_batch_edit_stage_hook();
struct StagedFile {
path: String,
abs_path: PathBuf,
original: Vec<u8>,
new_content: Vec<u8>,
language: LanguageId,
summaries: Vec<String>,
working_directory: Option<PathBuf>,
resolved_target: crate::worktree::ResolvedTarget,
}
let mut staged: Vec<StagedFile> = Vec::with_capacity(by_file.len());
let mut file_order: Vec<(&String, &Vec<usize>)> = by_file.iter().collect();
file_order.sort_by(|left, right| left.0.cmp(right.0));
for (path, indices) in file_order {
let file = &source_files[path];
{
let guard = index.read();
let current = guard
.get_file(path)
.ok_or_else(|| format!("File disappeared: {path}"))?;
if current.content != file.content {
return Err(format!(
"Error: file `{path}` changed after symbol resolution; retry with fresh source.{}",
rollback_footer(&targeted_paths),
));
}
}
let mut content = file.content.clone();
for &ri in indices {
let r = &resolved[ri];
if r.sym.byte_range.1 as usize > content.len() {
return Err(format!(
"Symbol `{}` byte range ({},{}) is out of bounds for file `{}` \
(content length {}). The file may have been modified concurrently — \
please retry.",
r.sym.name,
r.sym.byte_range.0,
r.sym.byte_range.1,
path,
content.len(),
));
}
}
let language = resolved[indices[0]].language;
let line_ending = detect_line_ending(&content);
let mut file_summaries: Vec<String> = Vec::new();
for &ri in indices {
let r = &resolved[ri];
let edit = &edits[r.operation];
match &edit.operation {
EditOperation::Replace { new_body } => {
let old_bytes = (r.sym.byte_range.1 - r.sym.byte_range.0) as usize;
let effective = r.sym.effective_start() as usize;
let raw_line_start = content[..effective]
.iter()
.rposition(|&b| b == b'\n')
.map(|p| p + 1)
.unwrap_or(0);
let line_start =
extend_past_orphaned_docs(&content, raw_line_start, &r.sym) as u32;
let indent = detect_indentation(&content, r.sym.byte_range.0);
let normalized = normalize_line_endings(new_body.as_bytes(), line_ending);
let normalized_str = std::str::from_utf8(&normalized).unwrap_or(new_body);
let indented = apply_indentation(normalized_str, &indent, line_ending);
content = apply_splice(&content, (line_start, r.sym.byte_range.1), &indented);
file_summaries.push(super::edit_format::format_replace(
path,
&r.sym.name,
&r.sym.kind.to_string(),
old_bytes,
new_body.len(),
));
}
EditOperation::InsertBefore { content: code } => {
let (position, indent) = insert_before_positions.get(&ri).ok_or_else(|| {
"Cannot determine batch insertion boundary; retry with fresh source"
.to_string()
})?;
content = crate::edit_safety::structural::build_insert_before_at_position(
&content,
&r.sym,
code,
line_ending,
*position,
indent,
);
file_summaries.push(super::edit_format::format_insert(
path,
&r.sym.name,
"before",
code.len(),
));
}
EditOperation::InsertAfter { content: code } => {
content = build_insert_after(&content, &r.sym, code, line_ending);
file_summaries.push(super::edit_format::format_insert(
path,
&r.sym.name,
"after",
code.len(),
));
}
EditOperation::Delete => {
let deleted = (r.sym.byte_range.1 - r.sym.byte_range.0) as usize;
content = build_delete(&content, &r.sym, line_ending);
file_summaries.push(super::edit_format::format_delete(
path,
&r.sym.name,
&r.sym.kind.to_string(),
deleted,
));
}
EditOperation::EditWithin { old_text, new_text } => {
let old_bytes = (r.sym.byte_range.1 - r.sym.byte_range.0) as usize;
let old_content_len = content.len();
let (new, count) =
build_edit_within(&content, &r.sym, old_text, new_text, false)
.map_err(|e| format!("Edit in {path}:{}: {e}", r.sym.name))?;
content = new;
let new_bytes = (old_bytes as isize
+ (content.len() as isize - old_content_len as isize))
as usize;
file_summaries.push(super::edit_format::format_edit_within(
path,
&r.sym.name,
count,
old_bytes,
new_bytes,
));
}
}
}
let indexed_abs_path = match safe_repo_path(repo_root, path) {
Ok(p) => p,
Err(e) => return Err(format!("Path containment error for '{path}': {e}")),
};
let per_file_working_directory: Option<PathBuf> = indices
.iter()
.find_map(|&ri| edits[resolved[ri].operation].working_directory.as_deref())
.map(PathBuf::from)
.or_else(|| top_level_working_directory.map(PathBuf::from));
let hook_ctx = super::edit_hooks::EditContext {
relative_path: path,
indexed_absolute_path: &indexed_abs_path,
repo_root,
project_state_dir,
working_directory: per_file_working_directory.as_deref(),
};
let resolved_target = match super::edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return Err(format!("Path resolution error for '{path}': {e}")),
};
let original = guard_batch_reroute_divergence(&resolved_target, &file.content, path)?;
let abs_path = resolved_target.target_path.clone();
staged.push(StagedFile {
path: path.clone(),
abs_path,
original,
new_content: content,
language,
summaries: file_summaries,
working_directory: per_file_working_directory,
resolved_target,
});
}
if dry_run {
let mut summaries = Vec::new();
for staged_file in &staged {
for summary in &staged_file.summaries {
summaries.push(format!("[DRY RUN] Would {summary}"));
}
}
return Ok((summaries, Vec::new()));
}
let images = staged
.iter()
.map(|file| crate::edit_safety::batch_commit::StagedImage {
relative: PathBuf::from(&file.path),
absolute: file.abs_path.clone(),
original: Some(file.original.clone()),
replacement: file.new_content.clone(),
owner_only: false,
})
.collect::<Vec<_>>();
let mut io = crate::edit_safety::batch_commit::ProtocolBatchIo {
repo_root,
project_state_dir,
};
let mut write_reports: Vec<Option<AtomicWriteReport>> = vec![None; staged.len()];
match crate::edit_safety::batch_commit::commit_staged(&images, &mut io, None) {
Ok(reports) => {
for (index, report) in reports {
write_reports[index] = Some(report);
}
}
Err(crate::edit_safety::batch_commit::BatchAbort::Conflict { index }) => {
return Err(format!(
"Write conflict for {}; on-disk bytes changed after staging. No batch edit was applied.",
staged[index].path,
));
}
Err(crate::edit_safety::batch_commit::BatchAbort::PreflightUnavailable { index }) => {
return Err(format!(
"Write failed preflight for {}; source pre-image could not be verified. No batch edit was applied.",
staged[index].path,
));
}
Err(crate::edit_safety::batch_commit::BatchAbort::WriteFailed {
index,
reason,
restored,
uncertain,
}) => {
if uncertain.is_empty() {
return Err(format!(
"Write failed for {}: {reason}\n\nROLLED BACK — {restored} file(s) restored to original content. No batch edit was applied.",
staged[index].path,
));
}
return Err(format!(
"Write failed for {}: {reason}\n\nROLLBACK INCOMPLETE — {} file(s) could not be verified. Manually verify affected files.",
staged[index].path,
uncertain.len(),
));
}
Err(crate::edit_safety::batch_commit::BatchAbort::Cancelled { .. }) => {
unreachable!("MCP batch edit does not pass a cancellation signal")
}
}
let mut summaries = Vec::new();
for (i, staged_file) in staged.iter().enumerate() {
reindex_after_write(
index,
&staged_file.abs_path,
&staged_file.path,
&staged_file.new_content,
staged_file.language,
);
let hook_ctx = super::edit_hooks::EditContext {
relative_path: &staged_file.path,
indexed_absolute_path: &staged_file.resolved_target.indexed_path,
repo_root,
project_state_dir,
working_directory: staged_file.working_directory.as_deref(),
};
super::edit_hooks::after_commit(&hook_ctx, &staged_file.abs_path);
let mut file_summaries = staged_file.summaries.clone();
if let Some(report) = &write_reports[i]
&& let Some(hint) = report.tee_snapshot.response_hint()
{
append_response_suffix_to_first_summary(&mut file_summaries, &hint);
}
let reroute_suffix = super::edit_format::format_reroute_suffix(
staged_file.working_directory.as_deref(),
&staged_file.resolved_target,
);
append_response_suffix_to_first_summary(&mut file_summaries, &reroute_suffix);
summaries.extend(file_summaries);
}
let written_paths = staged.iter().map(|sf| sf.abs_path.clone()).collect();
Ok((summaries, written_paths))
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct BatchRenameInput {
#[serde(default)]
pub project: Option<String>,
pub path: String,
#[serde(alias = "symbol")]
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
pub new_name: String,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub code_only: Option<bool>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[cfg(test)]
use crate::edit_safety::rename::validate_rename_ranges;
pub(crate) fn execute_batch_rename(
index: &SharedIndex,
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
input: &BatchRenameInput,
) -> Result<(String, Vec<std::path::PathBuf>), String> {
let rename_plan = {
let live = index.read();
let file = live
.get_file(&input.path)
.ok_or_else(|| format!("File not indexed: {}", input.path))?;
let (_, symbol) =
resolve_or_error(file, &input.name, input.kind.as_deref(), input.symbol_line)?;
crate::edit_safety::rename::build_rename_plan(
&live,
file,
&symbol,
&crate::edit_safety::rename::RenamePlanInput {
path: input.path.clone(),
name: input.name.clone(),
code_only: input.code_only.unwrap_or(false),
},
)?
};
if input.dry_run.unwrap_or(false) {
let live = index.read();
let rendered = crate::edit_safety::rename::render_rename_preview(
&live,
&rename_plan,
&input.name,
&input.new_name,
);
return Ok((rendered, Vec::new()));
}
let mut by_file: Vec<(String, Vec<(u32, u32)>)> = rename_plan.by_file.into_iter().collect();
by_file.sort_by(|left, right| left.0.cmp(&right.0));
let uncertain_lines = rename_plan.uncertain_lines;
let language = rename_plan.language;
let new_name_bytes = input.new_name.as_bytes();
struct StagedFile {
path: String,
abs_path: std::path::PathBuf,
original: Vec<u8>,
new_content: Vec<u8>,
language: LanguageId,
refs_count: usize,
working_directory: Option<std::path::PathBuf>,
resolved_target: crate::worktree::ResolvedTarget,
}
let mut staged: Vec<StagedFile> = Vec::with_capacity(by_file.len());
for (path, ranges) in &by_file {
let file = {
let guard = index.read();
guard
.capture_shared_file(path)
.ok_or_else(|| format!("File disappeared: {path}"))?
};
let original = file.content.clone();
let mut new_content = original.clone();
let mut last_start: Option<u32> = None;
for range in ranges {
debug_assert!(
last_start.is_none_or(|prev| range.0 < prev),
"ranges must be strictly descending: {} not < {:?}",
range.0,
last_start
);
new_content = apply_splice(&new_content, *range, new_name_bytes);
last_start = Some(range.0);
}
let lang = if path == &input.path {
language
} else {
file.language
};
let indexed_abs = match safe_repo_path(repo_root, path) {
Ok(p) => p,
Err(e) => return Err(format!("Path containment error for '{path}': {e}")),
};
let working_directory: Option<std::path::PathBuf> = input
.working_directory
.as_deref()
.map(std::path::PathBuf::from);
let hook_ctx = super::edit_hooks::EditContext {
relative_path: path,
indexed_absolute_path: &indexed_abs,
repo_root,
project_state_dir,
working_directory: working_directory.as_deref(),
};
let resolved_target = match super::edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return Err(format!("Path resolution error for '{path}': {e}")),
};
let original = guard_batch_reroute_divergence(&resolved_target, &original, path)?;
staged.push(StagedFile {
path: path.clone(),
abs_path: resolved_target.target_path.clone(),
original,
new_content,
language: lang,
refs_count: ranges.len(),
working_directory,
resolved_target,
});
}
let images = staged
.iter()
.map(|file| crate::edit_safety::batch_commit::StagedImage {
relative: PathBuf::from(&file.path),
absolute: file.abs_path.clone(),
original: Some(file.original.clone()),
replacement: file.new_content.clone(),
owner_only: false,
})
.collect::<Vec<_>>();
if let Err(error) =
commit_protocol_batch_images(repo_root, project_state_dir, &images, "rename")
{
for file in &staged {
if let Ok(on_disk) = std::fs::read(&file.abs_path) {
reindex_after_write(index, &file.abs_path, &file.path, &on_disk, file.language);
}
}
return Err(error);
}
let mut files_updated = 0;
let mut refs_updated = 0;
for sf in &staged {
reindex_after_write(index, &sf.abs_path, &sf.path, &sf.new_content, sf.language);
let hook_ctx = super::edit_hooks::EditContext {
relative_path: &sf.path,
indexed_absolute_path: &sf.resolved_target.indexed_path,
repo_root,
project_state_dir,
working_directory: sf.working_directory.as_deref(),
};
super::edit_hooks::after_commit(&hook_ctx, &sf.abs_path);
files_updated += 1;
refs_updated += sf.refs_count;
}
let mut output = format!(
"Renamed `{}` → `{}` — {refs_updated} site(s) across {files_updated} file(s)",
input.name, input.new_name,
);
if !uncertain_lines.is_empty() {
output.push_str(&format!(
"\n\n── Uncertain matches (NOT applied — review manually) — {} site(s) ──\n",
uncertain_lines.len(),
));
output.push_str(&uncertain_lines.join("\n"));
}
for sf in &staged {
output.push_str(&super::edit_format::format_reroute_suffix(
sf.working_directory.as_deref(),
&sf.resolved_target,
));
}
let written_paths = staged.iter().map(|sf| sf.abs_path.clone()).collect();
Ok((output, written_paths))
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct BatchInsertInput {
#[serde(default)]
pub project: Option<String>,
pub content: String,
pub position: InsertPosition,
#[serde(deserialize_with = "super::tools::lenient_vec_required")]
#[schemars(with = "Vec<InsertTarget>")]
pub targets: Vec<InsertTarget>,
#[serde(default, deserialize_with = "super::tools::lenient_bool")]
pub dry_run: Option<bool>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub working_directory: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InsertPosition {
Before,
After,
}
#[derive(Serialize, JsonSchema)]
pub struct InsertTarget {
pub path: String,
pub name: String,
pub kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
pub symbol_line: Option<u32>,
#[serde(default)]
pub working_directory: Option<String>,
}
impl<'de> serde::Deserialize<'de> for InsertTarget {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(serde::Deserialize)]
struct TargetFields {
path: String,
#[serde(alias = "symbol")]
name: String,
kind: Option<String>,
#[serde(default, deserialize_with = "super::tools::lenient_u32")]
symbol_line: Option<u32>,
#[serde(default)]
working_directory: Option<String>,
}
enum TargetOrStr {
Struct(TargetFields),
Str(String),
}
struct TargetVisitor;
impl<'de> serde::de::Visitor<'de> for TargetVisitor {
type Value = TargetOrStr;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an InsertTarget object or a string")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<TargetOrStr, E> {
Ok(TargetOrStr::Str(s.to_owned()))
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
map: A,
) -> Result<TargetOrStr, A::Error> {
TargetFields::deserialize(serde::de::value::MapAccessDeserializer::new(map))
.map(TargetOrStr::Struct)
}
}
match deserializer.deserialize_any(TargetVisitor)? {
TargetOrStr::Struct(TargetFields {
path,
name,
kind,
symbol_line,
working_directory,
}) => Ok(InsertTarget {
path,
name,
kind,
symbol_line,
working_directory,
}),
TargetOrStr::Str(s) => {
let (path, name) = if let Some(pos) = s.find("::") {
(s[..pos].to_string(), s[pos + 2..].to_string())
} else if let Some(pos) = s.rfind(':') {
(s[..pos].to_string(), s[pos + 1..].to_string())
} else {
return Err(D::Error::custom(format!(
"InsertTarget string must be 'path::name' or a JSON object \
with path/name fields, got '{s}'"
)));
};
if path.is_empty() || name.is_empty() {
return Err(D::Error::custom(format!(
"InsertTarget string must have non-empty path and name, got '{s}'"
)));
}
Ok(InsertTarget {
path,
name,
kind: None,
symbol_line: None,
working_directory: None,
})
}
}
}
}
pub(crate) fn execute_batch_insert(
index: &SharedIndex,
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
input: &BatchInsertInput,
) -> Result<(Vec<String>, Vec<PathBuf>), String> {
struct ResolvedTarget {
path: String,
sym: SymbolRecord,
operation: usize,
language: LanguageId,
}
let position_label = match input.position {
InsertPosition::Before => "before",
InsertPosition::After => "after",
};
crate::worktree::refuse_network_working_directories(
std::iter::once(input.working_directory.as_deref().map(Path::new)).chain(
input
.targets
.iter()
.map(|t| t.working_directory.as_deref().map(Path::new)),
),
)
.map_err(|error| error.to_string())?;
let mut resolved = Vec::with_capacity(input.targets.len());
{
let guard = index.read();
for (i, target) in input.targets.iter().enumerate() {
let file = guard
.get_file(&target.path)
.ok_or_else(|| format!("File not indexed: {}", target.path))?;
let (_, sym) = resolve_or_error(
file,
&target.name,
target.kind.as_deref(),
target.symbol_line,
)
.map_err(|e| format!("Target {} ({}): {e}", i + 1, target.path))?;
resolved.push(ResolvedTarget {
path: target.path.clone(),
sym,
operation: i,
language: file.language,
});
}
}
let mut by_file: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for (i, resolved_target) in resolved.iter().enumerate() {
by_file
.entry(resolved_target.path.clone())
.or_default()
.push(i);
}
fn insertion_anchor(position: InsertPosition, sym: &SymbolRecord) -> u32 {
match position {
InsertPosition::Before => sym.effective_start(),
InsertPosition::After => sym.byte_range.1,
}
}
for indices in by_file.values_mut() {
indices.sort_by(|&a, &b| {
insertion_anchor(input.position, &resolved[b].sym)
.cmp(&insertion_anchor(input.position, &resolved[a].sym))
.then_with(|| resolved[b].operation.cmp(&resolved[a].operation))
});
}
struct StagedFile {
path: String,
abs_path: PathBuf,
original: Vec<u8>,
new_content: Vec<u8>,
language: LanguageId,
summaries: Vec<String>,
working_directory: Option<PathBuf>,
resolved_target: crate::worktree::ResolvedTarget,
}
let mut staged: Vec<StagedFile> = Vec::with_capacity(by_file.len());
let mut staged_paths: Vec<String> = by_file.keys().cloned().collect();
staged_paths.sort();
for path in staged_paths {
let indices = by_file
.get(&path)
.ok_or_else(|| format!("Batch insert staging bug: missing path bucket for {path}"))?;
let file = {
let guard = index.read();
guard
.capture_shared_file(&path)
.ok_or_else(|| format!("File disappeared: {path}"))?
};
let mut content = file.content.clone();
for &ri in indices {
let target = &resolved[ri];
if target.sym.byte_range.1 as usize > content.len() {
return Err(format!(
"Symbol `{}` byte range ({},{}) is out of bounds for file `{}` (content length {}). The file may have been modified concurrently — please retry.",
target.sym.name,
target.sym.byte_range.0,
target.sym.byte_range.1,
path,
content.len(),
));
}
}
let positions = indices
.iter()
.map(|&ri| {
let symbol = &resolved[ri].sym;
match input.position {
InsertPosition::Before => {
let position = crate::edit_safety::structural::insert_before_position(
&file.content,
symbol,
&file.language,
)?;
Ok((
position,
detect_indentation(&file.content, symbol.byte_range.0),
))
}
InsertPosition::After => Ok((symbol.byte_range.1, Vec::new())),
}
})
.collect::<Result<Vec<_>, String>>()?;
let line_ending = detect_line_ending(&content);
let mut file_summaries = Vec::with_capacity(indices.len());
for (&ri, (position, indent)) in indices.iter().zip(&positions) {
let target = &resolved[ri];
content = match input.position {
InsertPosition::Before => {
crate::edit_safety::structural::build_insert_before_at_position(
&content,
&target.sym,
&input.content,
line_ending,
*position,
indent,
)
}
InsertPosition::After => {
build_insert_after(&content, &target.sym, &input.content, line_ending)
}
};
file_summaries.push(super::edit_format::format_insert(
&path,
&target.sym.name,
position_label,
input.content.len(),
));
}
let indexed_abs_path = match safe_repo_path(repo_root, &path) {
Ok(p) => p,
Err(e) => return Err(format!("Target {path}: {e}")),
};
let per_file_working_directory: Option<PathBuf> = indices
.iter()
.find_map(|&ri| {
input.targets[resolved[ri].operation]
.working_directory
.as_deref()
})
.map(PathBuf::from)
.or_else(|| input.working_directory.as_deref().map(PathBuf::from));
let hook_ctx = super::edit_hooks::EditContext {
relative_path: &path,
indexed_absolute_path: &indexed_abs_path,
repo_root,
project_state_dir,
working_directory: per_file_working_directory.as_deref(),
};
let resolved_target = match super::edit_hooks::resolve(&hook_ctx) {
Ok(r) => r,
Err(e) => return Err(format!("Target {path}: path resolution error: {e}")),
};
let original = guard_batch_reroute_divergence(&resolved_target, &file.content, &path)?;
staged.push(StagedFile {
path: path.clone(),
abs_path: resolved_target.target_path.clone(),
original,
new_content: content,
language: resolved[indices[0]].language,
summaries: file_summaries,
working_directory: per_file_working_directory,
resolved_target,
});
}
if input.dry_run.unwrap_or(false) {
let mut summaries = Vec::new();
for staged_file in &staged {
for summary in &staged_file.summaries {
summaries.push(format!("[DRY RUN] Would {summary}"));
}
}
return Ok((summaries, Vec::new()));
}
let images = staged
.iter()
.map(|file| crate::edit_safety::batch_commit::StagedImage {
relative: PathBuf::from(&file.path),
absolute: file.abs_path.clone(),
original: Some(file.original.clone()),
replacement: file.new_content.clone(),
owner_only: false,
})
.collect::<Vec<_>>();
if let Err(error) =
commit_protocol_batch_images(repo_root, project_state_dir, &images, "batch insert")
{
for file in &staged {
if let Ok(on_disk) = std::fs::read(&file.abs_path) {
reindex_after_write(index, &file.abs_path, &file.path, &on_disk, file.language);
}
}
return Err(error);
}
let mut summaries = Vec::new();
for staged_file in &staged {
reindex_after_write(
index,
&staged_file.abs_path,
&staged_file.path,
&staged_file.new_content,
staged_file.language,
);
let hook_ctx = super::edit_hooks::EditContext {
relative_path: &staged_file.path,
indexed_absolute_path: &staged_file.resolved_target.indexed_path,
repo_root,
project_state_dir,
working_directory: staged_file.working_directory.as_deref(),
};
super::edit_hooks::after_commit(&hook_ctx, &staged_file.abs_path);
let mut file_summaries = staged_file.summaries.clone();
let reroute_suffix = super::edit_format::format_reroute_suffix(
staged_file.working_directory.as_deref(),
&staged_file.resolved_target,
);
append_response_suffix_to_first_summary(&mut file_summaries, &reroute_suffix);
summaries.extend(file_summaries);
}
let written_paths = staged.iter().map(|sf| sf.abs_path.clone()).collect();
Ok((summaries, written_paths))
}
pub(crate) use crate::index_lifecycle::guidance::edit_body::extract_signature;
#[cfg(test)]
use crate::index_lifecycle::guidance::file_impact::extract_impl_type_name;
pub(crate) use crate::index_lifecycle::guidance::file_impact::find_parent_impl_type;
pub(crate) fn detect_stale_references(
index: &SharedIndex,
path: &str,
name: &str,
old_signature: &str,
new_signature: &str,
parent_type: Option<&str>,
source_language: Option<&crate::domain::LanguageId>,
) -> Vec<(String, u32, Option<String>)> {
crate::index_lifecycle::guidance::edit_body::stale_references(
&index.read(),
path,
name,
old_signature,
new_signature,
parent_type,
source_language,
)
}
#[cfg(test)]
mod write_authority_wiring {
use super::atomic_write_file;
use crate::live_index::index_lifecycle::activation::project_source_authority;
#[test]
fn atomic_write_file_routes_through_the_source_mutation_permit() {
let root = tempfile::tempdir().expect("oracle root");
let authority = project_source_authority(root.path());
let before = authority.grants_issued();
let target = root.path().join("wired.rs");
atomic_write_file(root.path(), None, &target, b"fn wired() {}")
.expect("the permit-authorized write succeeds");
assert_eq!(
std::fs::read(&target).expect("the write landed"),
b"fn wired() {}"
);
assert_eq!(
authority.grants_issued(),
before + 1,
"the write acquired exactly one mutation grant — zero means the \
legacy lane wrote without authority"
);
assert!(
authority.is_current(),
"the source returned to Current through the permit's terminal path"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::index::SymbolKind;
use crate::live_index::qualified_usages::find_qualified_usages;
#[test]
fn test_apply_splice_replaces_middle() {
let content = b"fn foo() { old_body }";
let result = apply_splice(content, (11, 19), b"new_body");
assert_eq!(result, b"fn foo() { new_body }");
}
#[test]
fn test_apply_splice_replaces_at_start() {
let content = b"old_start rest";
let result = apply_splice(content, (0, 9), b"new");
assert_eq!(result, b"new rest");
}
#[test]
fn test_apply_splice_replaces_at_end() {
let content = b"prefix old_end";
let result = apply_splice(content, (7, 14), b"new_end");
assert_eq!(result, b"prefix new_end");
}
#[test]
fn test_apply_splice_empty_replacement_deletes() {
let content = b"keep_this remove_this keep_that";
let result = apply_splice(content, (10, 21), b"");
assert_eq!(result, b"keep_this keep_that");
}
#[test]
fn test_apply_splice_empty_range_inserts() {
let content = b"ab";
let result = apply_splice(content, (1, 1), b"X");
assert_eq!(result, b"aXb");
}
#[test]
fn test_validate_rename_ranges_exact_dedup() {
let content = b"foo bar foo baz foo";
let mut ranges = vec![(0u32, 3u32), (8, 11), (16, 19), (8, 11)];
validate_rename_ranges(&mut ranges, content, "foo", "test.rs").unwrap();
assert_eq!(ranges.len(), 3);
}
#[test]
fn test_validate_rename_ranges_overlap_rejected() {
let content = b"aaaa";
let mut ranges = vec![(0u32, 2u32), (1, 3)];
let result = validate_rename_ranges(&mut ranges, content, "aa", "test.rs");
assert!(result.is_err());
assert!(result.unwrap_err().contains("overlapping"));
}
#[test]
fn test_validate_rename_ranges_mismatched_filtered() {
let content = b"xxfooxxfooxx";
let mut ranges = vec![(0u32, 12u32), (2, 5)];
validate_rename_ranges(&mut ranges, content, "foo", "test.rs").unwrap();
assert_eq!(ranges.len(), 1);
assert_eq!(ranges[0], (2, 5));
}
#[test]
fn test_validate_rename_ranges_adjacent_allowed() {
let content = b"foofoofoo";
let mut ranges = vec![(0u32, 3u32), (3, 6), (6, 9)];
validate_rename_ranges(&mut ranges, content, "foo", "test.rs").unwrap();
assert_eq!(ranges.len(), 3);
}
#[test]
fn test_validate_rename_ranges_text_mismatch_filtered() {
let content = b"foo bar baz";
let mut ranges = vec![(4u32, 7u32)];
validate_rename_ranges(&mut ranges, content, "foo", "test.rs").unwrap();
assert_eq!(ranges.len(), 0);
}
#[test]
fn test_validate_rename_ranges_dedup_count() {
let content = b"foo + foo + foo";
let mut ranges = vec![(0u32, 3u32), (6, 9), (12, 15), (6, 9)];
validate_rename_ranges(&mut ranges, content, "foo", "test.rs").unwrap();
assert_eq!(ranges.len(), 3);
}
#[test]
fn test_batch_rename_length_change_close_refs() {
let content = b"ab ab ab";
let mut ranges = vec![(0u32, 2u32), (3, 5), (6, 8)];
validate_rename_ranges(&mut ranges, content, "ab", "test.rs").unwrap();
let new_name = b"xyz";
let mut result = content.to_vec();
for range in &ranges {
result = apply_splice(&result, *range, new_name);
}
assert_eq!(result, b"xyz xyz xyz");
}
#[test]
fn test_atomic_write_file_creates_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.rs");
atomic_write_file(dir.path(), None, &path, b"fn main() {}").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"fn main() {}");
}
#[test]
fn test_atomic_write_file_overwrites_existing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.rs");
std::fs::write(&path, b"old content").unwrap();
atomic_write_file(dir.path(), None, &path, b"new content").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new content");
}
#[test]
fn test_atomic_write_file_no_leftover_tmp() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.rs");
atomic_write_file(dir.path(), None, &path, b"content").unwrap();
let tmp = path.with_extension("symforge_tmp");
assert!(!tmp.exists());
}
#[test]
fn test_reindex_after_write_updates_index() {
let dir = tempfile::tempdir().unwrap();
let abs_path = dir.path().join("lib.rs");
let content = b"fn hello() {}\nfn world() {}\n";
std::fs::write(&abs_path, content).unwrap();
let handle = crate::live_index::LiveIndex::empty();
reindex_after_write(&handle, &abs_path, "src/lib.rs", content, LanguageId::Rust);
let guard = handle.read();
let file = guard.get_file("src/lib.rs");
assert!(file.is_some());
let symbols = &file.unwrap().symbols;
assert!(symbols.iter().any(|s| s.name == "hello"));
assert!(symbols.iter().any(|s| s.name == "world"));
}
#[test]
fn test_reindex_after_write_replaces_existing_entry() {
let dir = tempfile::tempdir().unwrap();
let abs_path = dir.path().join("lib.rs");
let handle = crate::live_index::LiveIndex::empty();
let v1 = b"fn alpha() {}\n";
std::fs::write(&abs_path, v1).unwrap();
reindex_after_write(&handle, &abs_path, "src/lib.rs", v1, LanguageId::Rust);
let v2 = b"fn beta() {}\n";
std::fs::write(&abs_path, v2).unwrap();
reindex_after_write(&handle, &abs_path, "src/lib.rs", v2, LanguageId::Rust);
let guard = handle.read();
let file = guard.get_file("src/lib.rs").unwrap();
assert!(!file.symbols.iter().any(|s| s.name == "alpha"));
assert!(file.symbols.iter().any(|s| s.name == "beta"));
}
#[test]
fn test_reindex_reads_from_disk_not_buffer() {
let dir = tempfile::tempdir().unwrap();
let abs_path = dir.path().join("lib.rs");
let on_disk = b"fn disk_fn() {}\n";
std::fs::write(&abs_path, on_disk).unwrap();
let handle = crate::live_index::LiveIndex::empty();
reindex_after_write(&handle, &abs_path, "src/lib.rs", on_disk, LanguageId::Rust);
let guard = handle.read();
let file = guard.get_file("src/lib.rs").unwrap();
assert!(file.symbols.iter().any(|s| s.name == "disk_fn"));
}
#[test]
fn test_search_text_matches_disk_after_edit() {
let dir = tempfile::tempdir().unwrap();
let abs_path = dir.path().join("lib.rs");
let old_content = b"fn old_content_marker() {}\n";
std::fs::write(&abs_path, old_content).unwrap();
let handle = crate::live_index::LiveIndex::empty();
reindex_after_write(
&handle,
&abs_path,
"src/lib.rs",
old_content,
LanguageId::Rust,
);
{
let guard = handle.read();
let file = guard.get_file("src/lib.rs").unwrap();
assert!(file.symbols.iter().any(|s| s.name == "old_content_marker"));
}
let new_content = b"fn new_content_marker() {}\n";
atomic_write_file(dir.path(), None, &abs_path, new_content).unwrap();
reindex_after_write(
&handle,
&abs_path,
"src/lib.rs",
new_content,
LanguageId::Rust,
);
let guard = handle.read();
let file = guard.get_file("src/lib.rs").unwrap();
assert!(
!file.symbols.iter().any(|s| s.name == "old_content_marker"),
"old symbol should no longer be in the index"
);
assert!(
file.symbols.iter().any(|s| s.name == "new_content_marker"),
"new symbol should be in the index after reindex from disk"
);
}
fn make_test_indexed_file(symbols: Vec<SymbolRecord>) -> IndexedFile {
IndexedFile {
relative_path: "test.rs".to_string(),
language: LanguageId::Rust,
classification: crate::domain::index::FileClassification::for_code_path("test.rs"),
content: Vec::new(),
symbols,
parse_status: crate::live_index::store::ParseStatus::Parsed,
parse_diagnostic: None,
byte_len: 0,
content_hash: String::new(),
references: Vec::new(),
alias_map: std::collections::HashMap::new(),
mtime_secs: 0,
}
}
fn make_test_symbol(
name: &str,
kind: SymbolKind,
byte_range: (u32, u32),
line_start: u32,
) -> SymbolRecord {
SymbolRecord {
name: name.to_string(),
kind,
depth: 0,
sort_order: 0,
byte_range,
item_byte_range: Some(byte_range),
line_range: (line_start, line_start + 2),
doc_byte_range: None,
}
}
#[test]
fn test_resolve_or_error_finds_exact() {
let file = make_test_indexed_file(vec![
make_test_symbol("foo", SymbolKind::Function, (0, 20), 1),
make_test_symbol("bar", SymbolKind::Function, (22, 50), 5),
]);
let result = resolve_or_error(&file, "foo", None, None);
assert!(result.is_ok());
let (idx, sym) = result.unwrap();
assert_eq!(idx, 0);
assert_eq!(sym.name, "foo");
}
#[test]
fn test_resolve_or_error_not_found() {
let file = make_test_indexed_file(vec![make_test_symbol(
"foo",
SymbolKind::Function,
(0, 20),
1,
)]);
let result = resolve_or_error(&file, "baz", None, None);
assert!(result.is_err());
assert!(result.unwrap_err().contains("not found"));
}
fn did_you_mean_names(err: &str) -> Vec<&str> {
err.split("did_you_mean: [")
.nth(1)
.and_then(|tail| tail.split(']').next())
.map(|items| {
items
.split(", ")
.filter(|name| !name.is_empty())
.collect::<Vec<_>>()
})
.unwrap_or_default()
}
#[test]
fn test_resolve_or_error_not_found_suggests_close_same_file_symbol() {
let file = make_test_indexed_file(vec![make_test_symbol(
"foo_bar",
SymbolKind::Function,
(0, 20),
1,
)]);
let result = resolve_or_error(&file, "foo", None, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
did_you_mean_names(&err).contains(&"foo_bar"),
"error was: {err}"
);
}
#[test]
fn test_resolve_or_error_not_found_omits_noisy_suggestions() {
let file = make_test_indexed_file(vec![make_test_symbol(
"foo_bar",
SymbolKind::Function,
(0, 20),
1,
)]);
let result = resolve_or_error(&file, "quux", None, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
!err.contains("did_you_mean"),
"unexpected suggestion in: {err}"
);
}
#[test]
fn test_resolve_or_error_not_found_caps_suggestions_at_three() {
let file = make_test_indexed_file(vec![
make_test_symbol("foo_alpha", SymbolKind::Function, (0, 20), 1),
make_test_symbol("foo_beta", SymbolKind::Function, (22, 40), 5),
make_test_symbol("foo_gamma", SymbolKind::Function, (42, 60), 9),
make_test_symbol("foo_delta", SymbolKind::Function, (62, 80), 13),
]);
let result = resolve_or_error(&file, "foo", None, None);
assert!(result.is_err());
let err = result.unwrap_err();
let suggestions = did_you_mean_names(&err);
assert_eq!(suggestions.len(), 3, "error was: {err}");
}
#[test]
fn test_resolve_or_error_not_found_preserves_partial_parse_hint_with_suggestion() {
let mut file = make_test_indexed_file(vec![make_test_symbol(
"foo_bar",
SymbolKind::Function,
(0, 20),
1,
)]);
file.parse_status = crate::live_index::store::ParseStatus::PartialParse {
warning: "syntax error near line 9".to_string(),
};
let result = resolve_or_error(&file, "foo", None, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.contains("did_you_mean: [foo_bar]"), "error was: {err}");
assert!(
err.contains("file partially parsed with errors: syntax error near line 9"),
"error was: {err}"
);
}
#[test]
fn test_resolve_or_error_ambiguous_shows_candidates() {
let file = make_test_indexed_file(vec![
make_test_symbol("foo", SymbolKind::Function, (0, 20), 1),
make_test_symbol("foo", SymbolKind::Function, (22, 50), 5),
]);
let result = resolve_or_error(&file, "foo", None, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.contains("Ambiguous"), "error was: {err}");
assert!(err.contains("symbol_line"), "error was: {err}");
}
#[test]
fn test_resolve_or_error_disambiguates_by_kind() {
let file = make_test_indexed_file(vec![
make_test_symbol("Foo", SymbolKind::Struct, (0, 20), 1),
make_test_symbol("Foo", SymbolKind::Impl, (22, 80), 5),
]);
let result = resolve_or_error(&file, "Foo", Some("struct"), None);
assert!(result.is_ok());
assert_eq!(result.unwrap().1.kind, SymbolKind::Struct);
}
#[test]
fn test_resolve_or_error_disambiguates_by_line() {
let file = make_test_indexed_file(vec![
make_test_symbol("foo", SymbolKind::Function, (0, 20), 1),
make_test_symbol("foo", SymbolKind::Function, (22, 50), 5),
]);
let result = resolve_or_error(&file, "foo", None, Some(6));
assert!(result.is_ok());
assert_eq!(result.unwrap().0, 1);
}
#[test]
fn test_resolve_impl_prefix_trait_for_type() {
let file = make_test_indexed_file(vec![make_test_symbol(
"impl MyTrait for MyStruct",
SymbolKind::Impl,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "MyTrait for MyStruct", None, None);
assert!(result.is_ok(), "should resolve impl without prefix");
}
#[test]
fn test_resolve_impl_prefix_inherent() {
let file = make_test_indexed_file(vec![make_test_symbol(
"impl MyStruct",
SymbolKind::Impl,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "MyStruct", None, None);
assert!(
result.is_ok(),
"should resolve inherent impl without prefix"
);
}
#[test]
fn test_resolve_whitespace_normalised() {
let file = make_test_indexed_file(vec![make_test_symbol(
"impl Display for Vec<T>",
SymbolKind::Impl,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "impl Display for Vec< T >", None, None);
assert!(result.is_ok(), "should resolve with normalised whitespace");
}
#[test]
fn test_resolve_impl_prefix_plus_whitespace() {
let file = make_test_indexed_file(vec![make_test_symbol(
"impl Display for Vec<T>",
SymbolKind::Impl,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "Display for Vec< T >", None, None);
assert!(
result.is_ok(),
"should resolve impl prefix + ws normalisation"
);
}
#[test]
fn test_resolve_cpp_qualified_method() {
let file = make_test_indexed_file(vec![make_test_symbol(
"bar",
SymbolKind::Function,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "Foo::bar", None, None);
assert!(
result.is_ok(),
"should resolve C++ qualified name by stripping"
);
}
#[test]
fn test_resolve_go_receiver_method() {
let file = make_test_indexed_file(vec![make_test_symbol(
"Handle",
SymbolKind::Method,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "Server.Handle", None, None);
assert!(
result.is_ok(),
"should resolve Go receiver method by stripping"
);
}
#[test]
fn test_resolve_css_at_rule_prefix() {
let file = make_test_indexed_file(vec![make_test_symbol(
"@media (max-width: 768px)",
SymbolKind::Other,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "@media", None, None);
assert!(result.is_ok(), "should resolve CSS @-rule by prefix match");
}
#[test]
fn test_resolve_css_selector_prefix() {
let file = make_test_indexed_file(vec![make_test_symbol(
".btn, .btn-primary",
SymbolKind::Other,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, ".btn", None, None);
assert!(
result.is_ok(),
"should resolve CSS selector by prefix match"
);
}
#[test]
fn test_resolve_css_prefix_no_false_positive() {
let file = make_test_indexed_file(vec![make_test_symbol(
".btn-group",
SymbolKind::Other,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, ".btn", None, None);
assert!(
result.is_err(),
"should NOT match .btn-group for .btn query"
);
}
#[test]
fn test_resolve_swift_extension() {
let file = make_test_indexed_file(vec![make_test_symbol(
"MyClass",
SymbolKind::Impl,
(0, 50),
1,
)]);
let result = resolve_or_error(&file, "extension MyClass: Drawable", None, None);
assert!(
result.is_ok(),
"should resolve Swift extension by stripping prefix"
);
}
#[test]
fn test_resolve_exact_match_wins_over_fallback() {
let file = make_test_indexed_file(vec![
make_test_symbol("bar", SymbolKind::Function, (0, 20), 1),
make_test_symbol("impl bar", SymbolKind::Impl, (22, 50), 5),
]);
let result = resolve_or_error(&file, "bar", None, None);
assert!(result.is_ok());
assert_eq!(result.unwrap().0, 0);
}
#[test]
fn test_detect_indentation_spaces() {
let content = b"fn outer() {\n fn inner() {}\n}";
let indent = detect_indentation(content, 14);
assert_eq!(indent, b" ");
}
#[test]
fn test_detect_indentation_tabs() {
let content = b"fn outer() {\n\tfn inner() {}\n}";
let indent = detect_indentation(content, 14);
assert_eq!(indent, b"\t");
}
#[test]
fn test_detect_indentation_no_indent() {
let content = b"fn top_level() {}";
let indent = detect_indentation(content, 0);
assert_eq!(indent, b"");
}
#[test]
fn test_detect_indentation_at_newline_boundary() {
let content = b"line1\nline2";
let indent = detect_indentation(content, 6);
assert_eq!(indent, b"");
}
#[test]
fn test_apply_indentation_adds_prefix() {
let result = apply_indentation("fn new() {\n body;\n}", b" ", LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(text, " fn new() {\n body;\n }");
}
#[test]
fn test_apply_indentation_preserves_empty_lines() {
let result = apply_indentation("a\n\nb", b" ", LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(text, " a\n\n b");
}
#[test]
fn test_apply_indentation_empty_indent_is_identity() {
let result = apply_indentation("fn foo() {}", b"", LineEnding::Lf);
assert_eq!(result, b"fn foo() {}");
}
#[test]
fn test_apply_indentation_dedents_uniform_base_indent() {
let body = " fn foo() {\n bar();\n }";
let result = apply_indentation(body, b" ", LineEnding::Lf);
assert_eq!(
std::str::from_utf8(&result).unwrap(),
" fn foo() {\n bar();\n }"
);
}
#[test]
fn test_apply_indentation_flush_left_body_unchanged_by_dedent() {
let body = "fn foo() {\n bar();\n}";
let result = apply_indentation(body, b" ", LineEnding::Lf);
assert_eq!(
std::str::from_utf8(&result).unwrap(),
" fn foo() {\n bar();\n }"
);
}
#[test]
fn test_build_insert_before_adds_content_with_indent() {
let content = b" fn existing() {}\n";
let sym = make_test_symbol("existing", SymbolKind::Function, (4, 20), 1);
let result = build_insert_before(
content,
&sym,
"fn new_fn() {}",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let text = std::str::from_utf8(&result).unwrap();
assert!(
text.starts_with(" fn new_fn() {}\n\n fn existing"),
"got: {text}"
);
}
#[test]
fn test_build_insert_after_adds_content_with_indent() {
let content = b" fn existing() {}";
let sym = make_test_symbol("existing", SymbolKind::Function, (4, 20), 1);
let result = build_insert_after(content, &sym, "fn new_fn() {}", LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(
text.contains("fn existing() {}\n\n fn new_fn() {}"),
"got: {text}"
);
}
#[test]
fn test_build_insert_after_skips_trailing_semicolon() {
let content = b"struct Foo { int x; };\n";
let sym = make_test_symbol("Foo", SymbolKind::Struct, (0, 21), 1);
let result = build_insert_after(content, &sym, "struct Bar { int y; };", LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(
text.contains("};\n\nstruct Bar"),
"should insert after semicolon, got: {text}"
);
assert!(
!text.contains("}\n\nstruct Bar"),
"should not split '}}; ' got: {text}"
);
}
#[test]
fn test_build_insert_after_no_semicolon_unchanged() {
let content = b"fn foo() {}\nfn bar() {}\n";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, 11), 1);
let result = build_insert_after(content, &sym, "fn baz() {}", LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(text.contains("fn foo() {}\n\nfn baz() {}"), "got: {text}");
}
#[test]
fn test_build_delete_removes_symbol_and_trailing_newline() {
let content = b"fn keep() {}\n\nfn remove() {}\n\nfn also_keep() {}\n";
let sym = make_test_symbol("remove", SymbolKind::Function, (14, 28), 3);
let result = build_delete(content, &sym, LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(!text.contains("remove"), "got: {text}");
assert!(text.contains("keep"), "got: {text}");
assert!(text.contains("also_keep"), "got: {text}");
}
#[test]
fn test_build_delete_removes_leading_attribute_without_orphan() {
let content = b"fn keep() {}\n\n#[test]\nfn remove() {}\n";
let sym = make_test_symbol("remove", SymbolKind::Function, (22, 36), 4);
let result = build_delete(content, &sym, LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(
!text.contains("#[test]"),
"attribute must be removed: {text:?}"
);
assert!(!text.contains("remove"), "item must be removed: {text:?}");
assert!(
text.contains("keep"),
"unrelated item must remain: {text:?}"
);
}
#[test]
fn test_build_delete_removes_multiple_leading_attributes() {
let content = b"fn keep() {}\n\n#[cfg(test)]\n#[tokio::test]\nasync fn remove() {}\n";
let sym = make_test_symbol("remove", SymbolKind::Function, (42, 62), 5);
let result = build_delete(content, &sym, LineEnding::Lf);
let text = std::str::from_utf8(&result).unwrap();
assert!(
!text.contains("#[cfg(test)]"),
"first attribute must be removed: {text:?}"
);
assert!(
!text.contains("#[tokio::test]"),
"second attribute must be removed: {text:?}"
);
assert!(!text.contains("remove"), "item must be removed: {text:?}");
assert!(
text.contains("keep"),
"unrelated item must remain: {text:?}"
);
}
#[test]
fn test_build_delete_collapses_excessive_blank_lines() {
let content = b"fn a() {}\n\n\n\nfn d() {}\n";
let collapsed = super::collapse_blank_lines(content, LineEnding::Lf);
let text = std::str::from_utf8(&collapsed).unwrap();
assert!(
!text.contains("\n\n\n"),
"should collapse 3+ newlines: {text:?}"
);
assert!(text.contains("fn a() {}\n\nfn d()"), "got: {text:?}");
}
#[test]
fn test_build_edit_within_replaces_first_match() {
let content = b"fn foo() { old; old; }";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, 22), 1);
let (result, count) = build_edit_within(content, &sym, "old", "new", false).unwrap();
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(count, 1);
assert_eq!(text, "fn foo() { new; old; }");
}
#[test]
fn test_build_edit_within_replaces_all() {
let content = b"fn foo() { old; old; }";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, 22), 1);
let (result, count) = build_edit_within(content, &sym, "old", "new", true).unwrap();
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(count, 2);
assert_eq!(text, "fn foo() { new; new; }");
}
#[test]
fn test_build_edit_within_not_found() {
let content = b"fn foo() { body; }";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, 18), 1);
let result = build_edit_within(content, &sym, "missing", "new", false);
assert!(result.is_err());
}
#[test]
fn test_build_edit_within_matches_lf_needle_in_crlf_body() {
let content = b"fn foo() {\r\n let x = 1;\r\n bar();\r\n}";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, content.len() as u32), 1);
let (result, count) =
build_edit_within(content, &sym, " let x = 1;\n", " let x = 2;\n", false)
.unwrap();
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(count, 1);
assert_eq!(text, "fn foo() {\r\n let x = 2;\r\n bar();\r\n}");
assert_eq!(
text.matches('\n').count(),
text.matches("\r\n").count(),
"result must not contain lone LF line endings: {text:?}"
);
}
#[test]
fn test_build_edit_within_replace_all_lf_needle_in_crlf_body() {
let content = b"fn foo() {\r\n old();\r\n old();\r\n}";
let sym = make_test_symbol("foo", SymbolKind::Function, (0, content.len() as u32), 1);
let (result, count) =
build_edit_within(content, &sym, " old();\n", " new();\n", true).unwrap();
let text = std::str::from_utf8(&result).unwrap();
assert_eq!(count, 2);
assert_eq!(text, "fn foo() {\r\n new();\r\n new();\r\n}");
}
#[test]
fn test_ws_flexible_basic_indent_mismatch() {
let body = "fn foo() {\n let x = 1;\n let y = 2;\n }";
let old = " let x = 1;\n let y = 2;";
let new = " let x = 10;\n let y = 20;";
let (result, count) = try_whitespace_flexible_replace(body, old, new, false).unwrap();
assert_eq!(count, 1);
assert!(result.contains(" let x = 10;"));
assert!(result.contains(" let y = 20;"));
assert!(!result.contains("let x = 1;"));
}
#[test]
fn test_ws_flexible_replace_all() {
let body = "fn f() {\n a();\n b();\n a();\n}";
let old = " a();";
let new = " z();";
let (result, count) = try_whitespace_flexible_replace(body, old, new, true).unwrap();
assert_eq!(count, 2);
assert_eq!(result.matches("z()").count(), 2);
assert_eq!(result.matches("a()").count(), 0);
}
#[test]
fn test_ws_flexible_no_match_returns_none() {
let body = "fn foo() {\n let x = 1;\n}";
let old = "let y = 99;";
assert!(try_whitespace_flexible_replace(body, old, "z", false).is_none());
}
#[test]
fn test_ws_flexible_preserves_relative_indent() {
let body = "impl Foo {\n fn bar() {\n inner();\n }\n }";
let old = " fn bar() {\n inner();\n }";
let new = " fn bar() {\n outer();\n extra();\n }";
let (result, _) = try_whitespace_flexible_replace(body, old, new, false).unwrap();
assert!(result.contains(" fn bar() {"));
assert!(result.contains(" outer();"));
assert!(result.contains(" extra();"));
assert!(result.contains(" }"));
}
#[test]
fn test_ws_flexible_trailing_newline_preserved() {
let body = "fn f() {\n old();\n next();\n}";
let old = " old();";
let new = " new();";
let (result, count) = try_whitespace_flexible_replace(body, old, new, false).unwrap();
assert_eq!(count, 1);
assert!(result.contains(" next();"));
}
#[test]
fn test_ws_flexible_empty_old_returns_none() {
let body = "fn f() {}";
assert!(try_whitespace_flexible_replace(body, "", "x", false).is_none());
assert!(try_whitespace_flexible_replace(body, " \n ", "x", false).is_none());
}
#[test]
fn test_execute_batch_edit_applies_multiple_edits() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn alpha() { old }\n").unwrap();
std::fs::write(src.join("b.rs"), b"fn beta() { keep }\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn alpha() { old }\n" as &[u8]),
("src/b.rs", b"fn beta() { keep }\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "alpha".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn alpha() { new }".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "src/b.rs".to_string(),
name: "beta".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
];
let (summaries, _written) =
execute_batch_edit(&handle, dir.path(), None, &edits, false, None).unwrap();
assert_eq!(summaries.len(), 2);
let a_content = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(a_content.contains("new"), "a.rs: {a_content}");
let b_content = std::fs::read_to_string(src.join("b.rs")).unwrap();
assert!(!b_content.contains("beta"), "b.rs: {b_content}");
}
std::thread_local! {
static BEFORE_BATCH_EDIT_STAGE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
const { std::cell::RefCell::new(None) };
}
pub(super) fn run_before_batch_edit_stage_hook() {
BEFORE_BATCH_EDIT_STAGE.with(|hook| {
let callback = hook.borrow_mut().take();
if let Some(callback) = callback {
callback();
}
});
}
#[test]
fn batch_edit_refuses_changed_capture_before_staging() {
for dry_run in [false, true] {
let dir = tempfile::tempdir().unwrap();
let original = b"fn prefix() {}\n#[inline]\nfn target() {}\n";
let refreshed = b"fn prefix() { let changed = (); }\n#[inline]\nfn target() {}\n";
let untouched = b"fn other() {}\n";
let index = crate::live_index::LiveIndex::empty();
for (path, content) in [
("a.rs", original.as_slice()),
("b.rs", untouched.as_slice()),
] {
std::fs::write(dir.path().join(path), content).unwrap();
index.update_file(
path.to_string(),
IndexedFile::from_parse_result(
crate::parsing::process_file(path, content, LanguageId::Rust),
content.to_vec(),
),
);
}
let edits = [
SingleEdit {
path: "a.rs".to_string(),
name: "target".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::InsertBefore {
content: "const ADDED: () = ();".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "b.rs".to_string(),
name: "other".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
];
let published = index.clone();
let changed_path = dir.path().join("a.rs");
BEFORE_BATCH_EDIT_STAGE.with(|hook| {
assert!(hook.borrow().is_none());
*hook.borrow_mut() = Some(Box::new(move || {
std::fs::write(changed_path, refreshed).unwrap();
published.update_file(
"a.rs".to_string(),
IndexedFile::from_parse_result(
crate::parsing::process_file("a.rs", refreshed, LanguageId::Rust),
refreshed.to_vec(),
),
);
}));
});
let result = execute_batch_edit(&index, dir.path(), None, &edits, dry_run, None);
assert_eq!(std::fs::read(dir.path().join("a.rs")).unwrap(), refreshed);
assert_eq!(std::fs::read(dir.path().join("b.rs")).unwrap(), untouched);
let error = result.expect_err("a watcher refresh must invalidate planned offsets");
assert!(error.contains("changed after symbol resolution"), "{error}");
assert!(error.contains("No files were modified"), "{error}");
assert_eq!(index.read().get_file("a.rs").unwrap().content, refreshed);
assert_eq!(index.read().get_file("b.rs").unwrap().content, untouched);
}
}
#[test]
fn test_execute_batch_edit_rejects_overlapping() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn foo() {}\nfn bar() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
let content = b"fn foo() {}\nfn bar() {}\n" as &[u8];
let result = crate::parsing::process_file("src/a.rs", content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file("src/a.rs".to_string(), indexed);
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "foo".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
SingleEdit {
path: "src/a.rs".to_string(),
name: "foo".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
];
let result = execute_batch_edit(&handle, dir.path(), None, &edits, false, None);
assert!(result.is_err());
assert!(result.unwrap_err().contains("Overlapping"));
}
#[cfg(windows)]
#[test]
fn test_execute_batch_edit_refuses_any_network_working_directory() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("src")).unwrap();
let original = b"fn foo() {}\nfn bar() {}\n";
std::fs::write(dir.path().join("src/a.rs"), original).unwrap();
let handle = crate::live_index::LiveIndex::empty();
let parsed = crate::parsing::process_file("src/a.rs", original, LanguageId::Rust);
handle.update_file(
"src/a.rs".to_string(),
IndexedFile::from_parse_result(parsed, original.to_vec()),
);
let root = dir.path().to_string_lossy().to_string();
let unc = r"\\nonexistent-host.invalid\share".to_string();
let edit = |name: &str, wd: &str| SingleEdit {
path: "src/a.rs".to_string(),
name: name.to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: Some(wd.to_string()),
};
let cases = [
(vec![edit("foo", &root), edit("bar", &unc)], None),
(vec![edit("foo", &unc), edit("bar", &root)], None),
(
vec![edit("foo", &root), edit("bar", &root)],
Some(Path::new(unc.as_str())),
),
];
for (edits, top_level) in cases {
let error = execute_batch_edit(&handle, dir.path(), None, &edits, false, top_level)
.expect_err("network working_directory must be refused");
assert!(error.starts_with("NetworkPathRefused"), "{error}");
assert_eq!(
std::fs::read(dir.path().join("src/a.rs")).unwrap(),
original
);
}
}
#[test]
fn test_execute_batch_edit_rejects_same_line_delete_insert_splice_overlap() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let original = b"pub fn first() {} pub fn second() {}\n";
std::fs::write(src.join("a.rs"), original).unwrap();
let handle = crate::live_index::LiveIndex::empty();
let parsed = crate::parsing::process_file("src/a.rs", original, LanguageId::Rust);
handle.update_file(
"src/a.rs".to_string(),
IndexedFile::from_parse_result(parsed, original.to_vec()),
);
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "second".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
SingleEdit {
path: "src/a.rs".to_string(),
name: "first".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::InsertAfter {
content: "pub fn helper() {}".to_string(),
},
working_directory: None,
},
];
let error = execute_batch_edit(&handle, dir.path(), None, &edits, false, None)
.expect_err("physical splice ranges overlap");
assert!(error.contains("Overlapping"), "{error}");
assert_eq!(std::fs::read(src.join("a.rs")).unwrap(), original);
}
#[test]
fn test_execute_batch_edit_rejects_delete_cleanup_that_shifts_another_anchor() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let original = format!(
"pub fn first() {{}}\n{}pub fn second() {{}}\npub fn third() {{}}\npub fn fourth() {{ let marker = 1234567890; }}\n",
"\n".repeat(31)
);
std::fs::write(src.join("a.rs"), original.as_bytes()).unwrap();
let handle = crate::live_index::LiveIndex::empty();
let parsed =
crate::parsing::process_file("src/a.rs", original.as_bytes(), LanguageId::Rust);
handle.update_file(
"src/a.rs".to_string(),
IndexedFile::from_parse_result(parsed, original.as_bytes().to_vec()),
);
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "second".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::InsertBefore {
content: "pub fn helper() {}".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "src/a.rs".to_string(),
name: "third".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
];
let error = execute_batch_edit(&handle, dir.path(), None, &edits, false, None)
.expect_err("delete cleanup changes the other captured anchor");
assert!(error.contains("delete cleanup"), "{error}");
assert_eq!(
std::fs::read(src.join("a.rs")).unwrap(),
original.as_bytes()
);
}
#[test]
fn test_execute_batch_edit_rollback_message_on_nonexistent_symbol() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn foo() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
let content = b"fn foo() {}\n" as &[u8];
let result = crate::parsing::process_file("src/a.rs", content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file("src/a.rs".to_string(), indexed);
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "foo".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn foo() { modified }".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "src/a.rs".to_string(),
name: "nonexistent_symbol".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
},
];
let result = execute_batch_edit(&handle, dir.path(), None, &edits, false, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("ROLLED BACK"),
"expected ROLLED BACK in: {err}"
);
assert!(
err.contains("No files were modified"),
"expected 'No files were modified' in: {err}"
);
assert!(err.contains("2"), "expected edit count (2) in: {err}");
let file_content = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
file_content.contains("fn foo() {}"),
"file should be unmodified: {file_content}"
);
}
#[test]
fn test_execute_batch_edit_nonexistent_symbol_includes_same_file_suggestion() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn foo_bar() {}\n").unwrap();
std::fs::write(src.join("b.rs"), b"fn foo() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn foo_bar() {}\n" as &[u8]),
("src/b.rs", b"fn foo() {}\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let edits = vec![SingleEdit {
path: "src/a.rs".to_string(),
name: "foo".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
}];
let result = execute_batch_edit(&handle, dir.path(), None, &edits, false, None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.contains("did_you_mean: [foo_bar]"), "error was: {err}");
assert!(
!err.contains("did_you_mean: [foo]"),
"must not suggest symbol from src/b.rs: {err}"
);
}
#[test]
fn test_execute_batch_edit_dry_run_previews_without_writing() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn alpha() { old }\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
let content = b"fn alpha() { old }\n" as &[u8];
let result = crate::parsing::process_file("src/a.rs", content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file("src/a.rs".to_string(), indexed);
let edits = vec![SingleEdit {
path: "src/a.rs".to_string(),
name: "alpha".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn alpha() { new }".to_string(),
},
working_directory: None,
}];
let (summaries, _written) =
execute_batch_edit(&handle, dir.path(), None, &edits, true, None).unwrap();
assert_eq!(summaries.len(), 1, "expected one preview line");
assert!(
summaries[0].contains("[DRY RUN]"),
"expected [DRY RUN] prefix in: {}",
summaries[0]
);
let file_content = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
file_content.contains("old"),
"dry_run must not write to disk: {file_content}"
);
assert!(
!file_content.contains("new"),
"dry_run must not write to disk: {file_content}"
);
}
#[test]
fn test_execute_batch_edit_dry_run_same_error_as_real() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn foo() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
let content = b"fn foo() {}\n" as &[u8];
let result = crate::parsing::process_file("src/a.rs", content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file("src/a.rs".to_string(), indexed);
let edits = vec![SingleEdit {
path: "src/a.rs".to_string(),
name: "nonexistent_symbol".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Delete,
working_directory: None,
}];
let real_err =
execute_batch_edit(&handle, dir.path(), None, &edits, false, None).unwrap_err();
let dry_err =
execute_batch_edit(&handle, dir.path(), None, &edits, true, None).unwrap_err();
assert_eq!(
real_err, dry_err,
"dry_run must produce identical error to real run"
);
}
#[test]
fn test_execute_batch_insert_adds_to_multiple_files() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn handler_a() {}\n").unwrap();
std::fs::write(src.join("b.rs"), b"fn handler_b() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn handler_a() {}\n" as &[u8]),
("src/b.rs", b"fn handler_b() {}\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let input = BatchInsertInput {
project: None,
content: "fn logging() { log::info!(\"called\"); }".to_string(),
position: InsertPosition::After,
targets: vec![
InsertTarget {
path: "src/a.rs".to_string(),
name: "handler_a".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
InsertTarget {
path: "src/b.rs".to_string(),
name: "handler_b".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
],
dry_run: Some(false),
idempotency_key: None,
working_directory: None,
};
let (summaries, _written) =
execute_batch_insert(&handle, dir.path(), None, &input).unwrap();
assert_eq!(summaries.len(), 2);
let a = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(a.contains("logging"), "a.rs: {a}");
let b = std::fs::read_to_string(src.join("b.rs")).unwrap();
assert!(b.contains("logging"), "b.rs: {b}");
}
#[test]
fn rust_insert_before_batch_preserves_attributes_for_repeated_target() {
let dir = tempfile::tempdir().unwrap();
let original = b"mod nested {\n #[cfg(any())]\n fn target() { unavailable(); }\n}\n";
std::fs::write(dir.path().join("lib.rs"), original).unwrap();
let index = crate::live_index::LiveIndex::empty();
let parsed = crate::parsing::process_file("lib.rs", original, LanguageId::Rust);
index.update_file(
"lib.rs".to_string(),
IndexedFile::from_parse_result(parsed, original.to_vec()),
);
let input = BatchInsertInput {
project: None,
content: "\nconst _: () = {\n let _ = ();\n};".to_string(),
position: InsertPosition::Before,
targets: (0..2)
.map(|_| InsertTarget {
path: "lib.rs".to_string(),
name: "target".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
})
.collect(),
dry_run: Some(false),
idempotency_key: None,
working_directory: None,
};
let (summaries, _) = execute_batch_insert(&index, dir.path(), None, &input).unwrap();
assert_eq!(summaries.len(), 2);
let edited = std::fs::read(dir.path().join("lib.rs")).unwrap();
assert!(edited.starts_with(b"mod nested {\n"));
assert!(edited.ends_with(&original[b"mod nested {\n".len()..]));
let edited = String::from_utf8(edited).unwrap();
assert_eq!(edited.matches(" const _: () = {").count(), 2);
for line in edited
.lines()
.filter(|line| line.trim_start().starts_with("const _:"))
{
assert_eq!(line, " const _: () = {");
}
for line in edited
.lines()
.filter(|line| line.trim_start().starts_with("let _"))
{
assert_eq!(line, " let _ = ();");
}
}
#[test]
fn test_execute_batch_insert_dry_run_previews_without_writing() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.rs"), b"fn handler_a() {}\n").unwrap();
std::fs::write(src.join("b.rs"), b"fn handler_b() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn handler_a() {}\n" as &[u8]),
("src/b.rs", b"fn handler_b() {}\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let input = BatchInsertInput {
project: None,
content: "fn logging() {}".to_string(),
position: InsertPosition::After,
targets: vec![
InsertTarget {
path: "src/a.rs".to_string(),
name: "handler_a".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
InsertTarget {
path: "src/b.rs".to_string(),
name: "handler_b".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
],
dry_run: Some(true),
idempotency_key: None,
working_directory: None,
};
let (summaries, _written) =
execute_batch_insert(&handle, dir.path(), None, &input).unwrap();
assert_eq!(summaries.len(), 2, "expected two preview lines");
for s in &summaries {
assert!(s.contains("[DRY RUN]"), "expected [DRY RUN] prefix in: {s}");
}
let a = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
!a.contains("logging"),
"dry_run must not write to disk: {a}"
);
let b = std::fs::read_to_string(src.join("b.rs")).unwrap();
assert!(
!b.contains("logging"),
"dry_run must not write to disk: {b}"
);
}
#[test]
fn test_execute_batch_insert_rolls_back_on_write_failure() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let sub = src.join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(src.join("a.rs"), b"fn handler_a() {}\n").unwrap();
std::fs::write(sub.join("b.rs"), b"fn handler_b() {}\n").unwrap();
std::fs::write(src.join("c.rs"), b"fn handler_c() {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn handler_a() {}\n" as &[u8]),
("src/sub/b.rs", b"fn handler_b() {}\n"),
("src/c.rs", b"fn handler_c() {}\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let b_path = sub.join("b.rs");
std::fs::remove_file(&b_path).unwrap();
std::fs::create_dir(&b_path).unwrap();
let input = BatchInsertInput {
project: None,
content: "fn logging() {}".to_string(),
position: InsertPosition::After,
targets: vec![
InsertTarget {
path: "src/a.rs".to_string(),
name: "handler_a".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
InsertTarget {
path: "src/sub/b.rs".to_string(),
name: "handler_b".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
InsertTarget {
path: "src/c.rs".to_string(),
name: "handler_c".to_string(),
kind: None,
symbol_line: None,
working_directory: None,
},
],
dry_run: Some(false),
idempotency_key: None,
working_directory: None,
};
let result = execute_batch_insert(&handle, dir.path(), None, &input);
let err = result.unwrap_err();
assert!(
err.contains("ROLLED BACK") || err.contains("Write failed"),
"expected rollback message in: {err}"
);
assert!(
err.contains("No batch insert was applied"),
"expected atomic rollback message in: {err}"
);
for path in ["src/a.rs", "src/c.rs"] {
let disk = std::fs::read_to_string(dir.path().join(path)).unwrap();
assert!(
!disk.contains("logging"),
"{path} should be restored after rollback: {disk}"
);
let guard = handle.read();
let indexed = guard.get_file(path).unwrap();
assert!(
!std::str::from_utf8(&indexed.content)
.unwrap()
.contains("logging"),
"index should match rolled-back disk state for {path}"
);
}
assert!(
b_path.is_dir(),
"failed target should remain a directory to prove the write failed at the filesystem boundary"
);
let missing_target = handle
.read()
.get_file("src/sub/b.rs")
.unwrap()
.content
.clone();
assert!(
!std::str::from_utf8(&missing_target)
.unwrap()
.contains("logging"),
"index entry for failed target should remain unchanged"
);
}
#[test]
fn test_batch_edit_rolls_back_on_write_failure() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let sub = src.join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(src.join("a.rs"), b"fn alpha() { old }\n").unwrap();
std::fs::write(sub.join("b.rs"), b"fn beta() { old }\n").unwrap();
std::fs::write(src.join("c.rs"), b"fn gamma() { old }\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"fn alpha() { old }\n" as &[u8]),
("src/sub/b.rs", b"fn beta() { old }\n"),
("src/c.rs", b"fn gamma() { old }\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let b_path = sub.join("b.rs");
std::fs::remove_file(&b_path).unwrap();
std::fs::create_dir(&b_path).unwrap();
let edits = vec![
SingleEdit {
path: "src/a.rs".to_string(),
name: "alpha".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn alpha() { new }".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "src/sub/b.rs".to_string(),
name: "beta".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn beta() { new }".to_string(),
},
working_directory: None,
},
SingleEdit {
path: "src/c.rs".to_string(),
name: "gamma".to_string(),
kind: None,
symbol_line: None,
operation: EditOperation::Replace {
new_body: "fn gamma() { new }".to_string(),
},
working_directory: None,
},
];
let result = execute_batch_edit(&handle, dir.path(), None, &edits, false, None);
let err = result.unwrap_err();
assert!(
err.contains("ROLLED BACK") || err.contains("Write failed"),
"expected rollback message in: {err}"
);
assert!(
err.contains("No batch edit was applied"),
"expected atomic rollback message in: {err}"
);
let a_content = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
a_content.contains("old"),
"a.rs should be restored after rollback: {a_content}"
);
assert!(
!a_content.contains("new"),
"a.rs must not keep staged edits after rollback: {a_content}"
);
assert!(
b_path.is_dir(),
"failed target should remain a directory to prove the write failed at the filesystem boundary"
);
let c_content = std::fs::read_to_string(src.join("c.rs")).unwrap();
assert!(
c_content.contains("old"),
"c.rs should not be written after a rollback-triggering failure: {c_content}"
);
let guard = handle.read();
let a_indexed = guard.get_file("src/a.rs").unwrap();
let c_indexed = guard.get_file("src/c.rs").unwrap();
assert!(
std::str::from_utf8(&a_indexed.content)
.unwrap()
.contains("old"),
"index should match rolled-back disk state for a.rs"
);
assert!(
std::str::from_utf8(&c_indexed.content)
.unwrap()
.contains("old"),
"index should remain original for c.rs"
);
}
#[test]
fn test_batch_rename_dry_run_shows_per_site_preview() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let content = b"struct OldName;\nfn use_it(x: OldName) {}\n";
std::fs::write(src.join("a.rs"), content).unwrap();
let handle = crate::live_index::LiveIndex::empty();
let result = crate::parsing::process_file("src/a.rs", content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file("src/a.rs".to_string(), indexed);
let input = crate::protocol::edit::BatchRenameInput {
project: None,
path: "src/a.rs".to_string(),
name: "OldName".to_string(),
new_name: "NewName".to_string(),
kind: None,
symbol_line: None,
dry_run: Some(true),
idempotency_key: None,
code_only: None,
working_directory: None,
};
let (out, _written) = execute_batch_rename(&handle, dir.path(), None, &input).unwrap();
assert!(
out.contains("Confident matches (will be applied)"),
"dry run should keep the confident-matches header; got: {out}"
);
assert!(
out.contains("src/a.rs ("),
"dry run should list the file; got: {out}"
);
assert!(
out.contains(" L1: struct OldName;"),
"dry run should show the definition site with its source line; got: {out}"
);
assert!(
out.contains(" L2: fn use_it(x: OldName) {}"),
"dry run should show the use site with its source line; got: {out}"
);
let on_disk = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
!on_disk.contains("NewName"),
"dry run must not write to disk; got: {on_disk}"
);
}
#[test]
fn test_batch_rename_rolls_back_on_failure() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let sub = dir.path().join("src").join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(src.join("a.rs"), b"struct OldName;\n").unwrap();
std::fs::write(sub.join("b.rs"), b"use crate::OldName;\n").unwrap();
std::fs::write(src.join("c.rs"), b"fn use_it(x: OldName) {}\n").unwrap();
let handle = crate::live_index::LiveIndex::empty();
for (path, content) in [
("src/a.rs", b"struct OldName;\n" as &[u8]),
("src/sub/b.rs", b"use crate::OldName;\n"),
("src/c.rs", b"fn use_it(x: OldName) {}\n"),
] {
let result = crate::parsing::process_file(path, content, LanguageId::Rust);
let indexed = IndexedFile::from_parse_result(result, content.to_vec());
handle.update_file(path.to_string(), indexed);
}
let b_path = sub.join("b.rs");
std::fs::remove_file(&b_path).unwrap();
std::fs::create_dir(&b_path).unwrap();
let input = crate::protocol::edit::BatchRenameInput {
project: None,
path: "src/a.rs".to_string(),
name: "OldName".to_string(),
new_name: "NewName".to_string(),
kind: None,
symbol_line: None,
dry_run: Some(false),
idempotency_key: None,
code_only: None,
working_directory: None,
};
let result = execute_batch_rename(&handle, dir.path(), None, &input);
let err = result.unwrap_err();
assert!(
err.contains("ROLLED BACK") || err.contains("Write failed"),
"expected rollback message in: {err}"
);
let a_content = std::fs::read_to_string(src.join("a.rs")).unwrap();
assert!(
a_content.contains("OldName"),
"a.rs should be rolled back to OldName: {a_content}"
);
assert!(
!a_content.contains("NewName"),
"a.rs must not contain NewName after rollback: {a_content}"
);
assert!(
b_path.is_dir(),
"failed target should remain a directory to prove the write failed at the filesystem boundary"
);
}
#[test]
fn test_extract_signature_returns_first_line() {
let content = b"fn foo(x: i32) {\n body();\n}";
let sig = extract_signature(content, (0, 30));
assert_eq!(sig, "fn foo(x: i32) {");
}
#[test]
fn test_extract_signature_single_line() {
let content = b"fn foo() {}";
let sig = extract_signature(content, (0, 11));
assert_eq!(sig, "fn foo() {}");
}
#[test]
fn test_extract_impl_type_name_simple() {
assert_eq!(extract_impl_type_name("impl Foo"), Some("Foo".to_string()));
}
#[test]
fn test_extract_impl_type_name_trait_for() {
assert_eq!(
extract_impl_type_name("impl Display for Foo"),
Some("Foo".to_string())
);
}
#[test]
fn test_extract_impl_type_name_generic() {
assert_eq!(
extract_impl_type_name("impl<T> Foo<T>"),
Some("Foo".to_string())
);
}
#[test]
fn test_extract_impl_type_name_generic_trait_for() {
assert_eq!(
extract_impl_type_name("impl<T: Clone> Trait for Foo<T>"),
Some("Foo".to_string())
);
}
#[test]
fn test_extract_impl_type_name_no_impl_prefix() {
assert_eq!(extract_impl_type_name("Foo"), Some("Foo".to_string()));
}
#[test]
fn test_find_parent_impl_type_for_method() {
let file = make_test_indexed_file(vec![
SymbolRecord {
name: "impl Widget".to_string(),
kind: SymbolKind::Impl,
depth: 0,
sort_order: 0,
byte_range: (0, 100),
line_range: (0, 10),
doc_byte_range: None,
item_byte_range: None,
},
SymbolRecord {
name: "display".to_string(),
kind: SymbolKind::Method,
depth: 1,
sort_order: 1,
byte_range: (20, 80),
line_range: (2, 8),
doc_byte_range: None,
item_byte_range: None,
},
]);
let method = &file.symbols[1];
assert_eq!(
find_parent_impl_type(&file, method),
Some("Widget".to_string())
);
}
#[test]
fn test_find_parent_impl_type_standalone_fn() {
let file = make_test_indexed_file(vec![make_test_symbol(
"standalone",
SymbolKind::Function,
(0, 50),
1,
)]);
let func = &file.symbols[0];
assert_eq!(find_parent_impl_type(&file, func), None);
}
fn make_ref_file(refs: Vec<crate::domain::index::ReferenceRecord>) -> IndexedFile {
IndexedFile {
relative_path: String::new(),
language: LanguageId::Rust,
classification: crate::domain::index::FileClassification::for_code_path("test.rs"),
content: Vec::new(),
symbols: Vec::new(),
parse_status: crate::live_index::store::ParseStatus::Parsed,
parse_diagnostic: None,
byte_len: 0,
content_hash: String::new(),
references: refs,
alias_map: std::collections::HashMap::new(),
mtime_secs: 0,
}
}
#[test]
fn test_detect_stale_refs_method_filters_by_parent_type() {
use crate::domain::index::ReferenceKind;
let handle = crate::live_index::LiveIndex::empty();
handle.update_file(
"src/a.rs".to_string(),
make_ref_file(vec![
crate::domain::index::ReferenceRecord {
name: "display".to_string(),
qualified_name: None,
kind: ReferenceKind::Call,
byte_range: (32, 39),
line_range: (1, 1),
enclosing_symbol_index: None,
},
crate::domain::index::ReferenceRecord {
name: "Widget".to_string(),
qualified_name: None,
kind: ReferenceKind::TypeUsage,
byte_range: (12, 18),
line_range: (0, 0),
enclosing_symbol_index: None,
},
]),
);
handle.update_file(
"src/b.rs".to_string(),
make_ref_file(vec![crate::domain::index::ReferenceRecord {
name: "display".to_string(),
qualified_name: None,
kind: ReferenceKind::Call,
byte_range: (19, 26),
line_range: (0, 0),
enclosing_symbol_index: None,
}]),
);
let refs = detect_stale_references(
&handle,
"src/widget.rs",
"display",
"fn display(&self) {",
"fn display(&self, verbose: bool) {",
Some("Widget"),
None,
);
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].0, "src/a.rs");
}
#[test]
fn test_detect_stale_refs_standalone_fn_warns_all() {
use crate::domain::index::ReferenceKind;
let handle = crate::live_index::LiveIndex::empty();
handle.update_file(
"src/a.rs".to_string(),
make_ref_file(vec![crate::domain::index::ReferenceRecord {
name: "display".to_string(),
qualified_name: None,
kind: ReferenceKind::Call,
byte_range: (12, 19),
line_range: (0, 0),
enclosing_symbol_index: None,
}]),
);
handle.update_file(
"src/b.rs".to_string(),
make_ref_file(vec![crate::domain::index::ReferenceRecord {
name: "display".to_string(),
qualified_name: None,
kind: ReferenceKind::Call,
byte_range: (15, 22),
line_range: (0, 0),
enclosing_symbol_index: None,
}]),
);
let refs = detect_stale_references(
&handle,
"src/lib.rs",
"display",
"fn display() {",
"fn display(verbose: bool) {",
None,
None,
);
assert_eq!(refs.len(), 2);
}
#[test]
fn test_build_delete_includes_doc_comments() {
let content = b"/// Doc line 1\n/// Doc line 2\npub fn foo() {}\n\nfn bar() {}\n";
let sym = SymbolRecord {
name: "foo".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (30, 46),
line_range: (2, 2),
doc_byte_range: Some((0, 30)),
item_byte_range: None,
};
let result = build_delete(content, &sym, LineEnding::Lf);
let result_str = String::from_utf8(result).unwrap();
assert!(
!result_str.contains("/// Doc line 1"),
"doc comments should be deleted"
);
assert!(
!result_str.contains("pub fn foo"),
"function body should be deleted"
);
assert!(
result_str.contains("fn bar()"),
"other function should remain"
);
}
#[test]
fn test_build_delete_removes_blank_line_separated_doc_comments() {
let content = b"/// Batch-inserted marker\n\nfn batch_marker() {}\n\nfn other() {}\n";
let sym = SymbolRecord {
name: "batch_marker".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (27, 48),
line_range: (2, 2),
doc_byte_range: None, item_byte_range: None,
};
let result = build_delete(content, &sym, LineEnding::Lf);
let result_str = String::from_utf8(result).unwrap();
assert!(
!result_str.contains("/// Batch-inserted marker"),
"orphaned doc comment should be cleaned up, got: {result_str}"
);
assert!(
result_str.contains("fn other()"),
"other function should remain, got: {result_str}"
);
}
#[test]
fn test_build_insert_before_goes_above_doc_comments() {
let content = b"/// Doc for foo\npub fn foo() {}\n";
let sym = SymbolRecord {
name: "foo".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (16, 31),
line_range: (1, 1),
doc_byte_range: Some((0, 16)),
item_byte_range: None,
};
let result = build_insert_before(
content,
&sym,
"use std::io;",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let result_str = String::from_utf8(result).unwrap();
let use_pos = result_str
.find("use std::io;")
.expect("inserted content missing");
let doc_pos = result_str
.find("/// Doc for foo")
.expect("doc comment missing");
assert!(
use_pos < doc_pos,
"insert should go above doc comments (use_pos={use_pos}, doc_pos={doc_pos})"
);
}
#[test]
fn test_build_insert_before_double_newline_without_doc_comments() {
let content = b"struct Point { x: f64 }\n";
let sym = SymbolRecord {
name: "Point".to_string(),
kind: SymbolKind::Struct,
depth: 0,
sort_order: 0,
byte_range: (0, 23),
line_range: (0, 0),
doc_byte_range: None,
item_byte_range: None,
};
let result = build_insert_before(
content,
&sym,
"struct Point3D { x: f64 }",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let result_str = String::from_utf8(result).unwrap();
assert!(
result_str.contains("Point3D { x: f64 }\n\nstruct Point"),
"should have \\n\\n separator when no doc comment: {result_str}"
);
}
#[test]
fn test_build_insert_before_no_double_blank_line() {
let content = b"\nfn existing() {}\n";
let sym = SymbolRecord {
name: "existing".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (1, 17),
line_range: (1, 1),
doc_byte_range: None,
item_byte_range: None,
};
let result = build_insert_before(
content,
&sym,
"fn new_fn() {}",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let result_str = String::from_utf8(result).unwrap();
assert!(
!result_str.contains("\n\n\n"),
"should not produce triple newline when blank line already precedes symbol: {result_str:?}"
);
assert!(
result_str.contains("fn new_fn() {}"),
"inserted content missing: {result_str:?}"
);
assert!(
result_str.contains("fn existing() {}"),
"existing content missing: {result_str:?}"
);
}
#[test]
fn test_build_insert_before_first_symbol_in_file() {
let content = b"fn first() {}\n";
let sym = SymbolRecord {
name: "first".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (0, 13),
line_range: (0, 0),
doc_byte_range: None,
item_byte_range: None,
};
let result = build_insert_before(
content,
&sym,
"fn before() {}",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let result_str = String::from_utf8(result).unwrap();
assert!(
!result_str.contains("\n\n\n"),
"should not produce triple newline when symbol is first in file: {result_str:?}"
);
assert!(
result_str.contains("fn before() {}"),
"inserted content missing: {result_str:?}"
);
assert!(
result_str.contains("fn first() {}"),
"original content missing: {result_str:?}"
);
}
#[test]
fn test_build_insert_before_with_doc_byte_range() {
let content = b"/// Doc\nfn target() {}\n\nfn other() {}\n";
let sym = SymbolRecord {
name: "target".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (8, 22),
line_range: (1, 1),
doc_byte_range: Some((0, 8)),
item_byte_range: None,
};
let result = build_insert_before(
content,
&sym,
"fn inserted() {}",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
let result_str = String::from_utf8(result).unwrap();
assert!(
!result_str.contains("\n\n\n"),
"should not produce triple newline with doc_byte_range: {result_str:?}"
);
let ins_pos = result_str
.find("fn inserted()")
.expect("inserted content missing");
let doc_pos = result_str.find("/// Doc").expect("doc comment missing");
assert!(
ins_pos < doc_pos,
"insertion should appear before doc comment: ins={ins_pos} doc={doc_pos}"
);
}
#[test]
fn test_build_edit_within_no_doc_duplication() {
let content = b"/// Doc comment\npub fn foo() {}\n";
let sym = SymbolRecord {
name: "foo".to_string(),
kind: SymbolKind::Function,
depth: 0,
sort_order: 0,
byte_range: (16, 32),
line_range: (1, 1),
doc_byte_range: Some((0, 16)),
item_byte_range: None,
};
let (result, count) = build_edit_within(content, &sym, "foo", "bar", false).unwrap();
let result_str = String::from_utf8(result).unwrap();
assert_eq!(count, 1);
assert_eq!(
result_str.matches("/// Doc comment").count(),
1,
"doc comment should not be duplicated: {result_str}"
);
assert!(result_str.contains("pub fn bar()"), "edit should apply");
}
#[test]
fn test_finds_type_new_qualified_call() {
let source = "let x = MyType::new();";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_finds_deep_nested_qualified() {
let source = "let x = module::MyType::new();";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_finds_use_import_path() {
let source = "use crate::module::MyType;";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_scanner_finds_all_raw_occurrences_of_common_name() {
let source = "let x = SomeOther::new();\nlet y = Target::new();";
let matches = find_qualified_usages("new", source);
assert_eq!(matches.len(), 2);
assert!(matches.iter().all(|m| m.confident));
}
#[test]
fn test_uncertain_match_in_string() {
let source = r#"let s = "MyType::new()";"#;
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(!matches[0].confident);
}
#[test]
fn test_uncertain_match_in_comment() {
let source = "// MyType::new() creates an instance";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(!matches[0].confident);
}
#[test]
fn test_finds_turbofish_qualified_call() {
let source = "let x = MyType::<T>::new();";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_uncertain_match_in_block_comment() {
let source = "/* MyType::new() creates an instance */";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(!matches[0].confident);
}
#[test]
fn test_uncertain_match_in_multiline_string() {
let source = "let s = r\"\n MyType::new()\n \";";
let matches = find_qualified_usages("MyType", source);
assert_eq!(matches.len(), 1);
assert!(!matches[0].confident);
}
#[test]
fn test_find_qualified_usages_non_ascii_no_panic() {
let source = "/// Retry in a moment \u{2014} just wait\nfn foo() { bar::baz(); }\n";
let matches = find_qualified_usages("baz", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_find_qualified_usages_emoji_no_panic() {
let source = "/// \u{1F980} Rust crab\nfn main() { std::io::println(); }\n";
let matches = find_qualified_usages("io", source);
assert!(!matches.is_empty());
}
#[test]
fn test_find_qualified_usages_cjk_no_panic() {
let source = "// \u{4F60}\u{597D}\u{4E16}\u{754C} hello::world\nlet x = foo::bar();\n";
let matches = find_qualified_usages("bar", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
let matches2 = find_qualified_usages("world", source);
assert_eq!(matches2.len(), 1);
assert!(!matches2[0].confident);
}
#[test]
fn test_find_qualified_usages_multibyte_in_string_literal() {
let source = "let s = \"retry \u{2014} now\"; foo::bar();";
let matches = find_qualified_usages("bar", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_find_qualified_usages_multibyte_in_block_comment() {
let source = "/* \u{2014} em dash */ foo::bar();";
let matches = find_qualified_usages("bar", source);
assert_eq!(matches.len(), 1);
assert!(matches[0].confident);
}
#[test]
fn test_find_qualified_usages_macro_body_classified_confident() {
let source = r#"
macro_rules! make_widget {
($val:expr) => {
Widget::new($val)
};
}
fn uses_it() { Widget::default(); }
"#;
let matches = find_qualified_usages("Widget", source);
assert_eq!(
matches.len(),
2,
"should find Widget in macro body and fn body"
);
assert!(
matches.iter().all(|m| m.confident),
"macro body matches must be confident: {:?}",
matches
.iter()
.map(|m| (&m.context, m.confident))
.collect::<Vec<_>>()
);
}
#[test]
fn test_atomic_write_concurrent_no_hybrid() {
use std::io::ErrorKind;
use std::sync::{Arc, Barrier};
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("target.txt");
std::fs::write(&target, b"initial").unwrap();
let payload_a = vec![b'A'; 1024 * 1024];
let payload_b = vec![b'B'; 1024 * 1024];
let barrier = Arc::new(Barrier::new(2));
let target_a = target.clone();
let target_b = target.clone();
let root_a = dir.path().to_path_buf();
let root_b = dir.path().to_path_buf();
let pa = payload_a.clone();
let pb = payload_b.clone();
let ba = Arc::clone(&barrier);
let bb = Arc::clone(&barrier);
let ha = std::thread::spawn(move || {
ba.wait();
atomic_write_file(&root_a, None, &target_a, &pa)
});
let hb = std::thread::spawn(move || {
bb.wait();
atomic_write_file(&root_b, None, &target_b, &pb)
});
let result_a = ha.join().unwrap();
let result_b = hb.join().unwrap();
for result in [&result_a, &result_b] {
if let Err(err) = result {
assert_eq!(
err.kind(),
ErrorKind::PermissionDenied,
"unexpected concurrent atomic_write_file error: {err}"
);
}
}
assert!(
result_a.is_ok() || result_b.is_ok(),
"at least one concurrent writer should succeed: a={result_a:?} b={result_b:?}"
);
let result = std::fs::read(&target).unwrap();
assert!(
result == payload_a || result == payload_b,
"file must be exactly payload A or B, not a hybrid (len={})",
result.len()
);
}
#[test]
fn test_atomic_write_no_orphan_temp_files() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("output.txt");
atomic_write_file(dir.path(), None, &target, b"hello world").unwrap();
let entries: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert_eq!(
entries.len(),
1,
"expected exactly 1 file in dir, found: {:?}",
entries.iter().map(|e| e.file_name()).collect::<Vec<_>>()
);
}
#[test]
fn test_atomic_write_error_path_no_orphan() {
let dir = tempfile::tempdir().unwrap();
let bad_target = dir.path().join("nonexistent_subdir").join("file.txt");
let result = atomic_write_file(dir.path(), None, &bad_target, b"data");
assert!(result.is_err(), "expected error for nonexistent parent dir");
let entries: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert!(
entries.is_empty(),
"expected no orphan temp files, found: {:?}",
entries.iter().map(|e| e.file_name()).collect::<Vec<_>>()
);
}
#[test]
fn test_detect_line_ending_lf() {
assert_eq!(detect_line_ending(b"hello\nworld\n"), LineEnding::Lf);
}
#[test]
fn test_detect_line_ending_crlf() {
assert_eq!(detect_line_ending(b"hello\r\nworld\r\n"), LineEnding::CrLf);
}
#[test]
fn test_detect_line_ending_empty() {
assert_eq!(detect_line_ending(b""), LineEnding::Lf);
}
#[test]
fn test_detect_line_ending_dominant_count() {
assert_eq!(detect_line_ending(b"a\r\nb\r\nc\n"), LineEnding::CrLf);
assert_eq!(detect_line_ending(b"a\r\nb\nc\n"), LineEnding::Lf);
}
#[test]
fn test_normalize_line_endings_to_crlf() {
let result = normalize_line_endings(b"line1\nline2\nline3", LineEnding::CrLf);
assert_eq!(result, b"line1\r\nline2\r\nline3");
}
#[test]
fn test_normalize_line_endings_to_lf() {
let result = normalize_line_endings(b"line1\r\nline2\r\nline3", LineEnding::Lf);
assert_eq!(result, b"line1\nline2\nline3");
}
#[test]
fn test_normalize_lone_cr() {
let result = normalize_line_endings(b"line1\rline2\r", LineEnding::CrLf);
assert_eq!(result, b"line1\r\nline2\r\n");
}
#[test]
fn test_apply_indentation_preserves_crlf() {
let text = "fn foo() {\n bar();\n}\n";
let indent = b" ";
let result = apply_indentation(text, indent, LineEnding::CrLf);
assert!(
result.windows(2).any(|w| w == b"\r\n"),
"should contain CRLF"
);
for (i, &byte) in result.iter().enumerate() {
if byte == b'\n' {
assert!(i > 0 && result[i - 1] == b'\r', "bare LF at byte {i}");
}
}
}
#[test]
fn test_build_insert_before_crlf_preserved() {
let content = b"fn existing() {\r\n body();\r\n}\r\n";
let sym = make_test_symbol("existing", SymbolKind::Function, (0, 31), 1);
let result = build_insert_before(
content,
&sym,
"fn new_fn() {}",
LineEnding::CrLf,
&LanguageId::Rust,
)
.unwrap();
for (i, &byte) in result.iter().enumerate() {
if byte == b'\n' {
assert!(
i > 0 && result[i - 1] == b'\r',
"bare LF at byte {i} in insert_before output"
);
}
}
assert!(
result.windows(2).any(|w| w == b"\r\n"),
"output should contain CRLF"
);
}
#[test]
fn test_build_delete_crlf_no_orphan_cr() {
let content = b"fn keep1() {}\r\n\r\nfn remove() {}\r\n\r\nfn keep2() {}\r\n";
let sym = make_test_symbol("remove", SymbolKind::Function, (17, 31), 3);
let result = build_delete(content, &sym, LineEnding::CrLf);
for (i, &byte) in result.iter().enumerate() {
if byte == b'\r' {
assert!(
i + 1 < result.len() && result[i + 1] == b'\n',
"orphan CR at byte {i}"
);
}
}
let text = std::str::from_utf8(&result).unwrap();
assert!(!text.contains("remove"), "deleted symbol should be absent");
assert!(text.contains("keep1"), "keep1 should remain");
assert!(text.contains("keep2"), "keep2 should remain");
}
#[test]
fn test_collapse_blank_lines_crlf() {
let input = b"line1\r\n\r\n\r\n\r\nline2\r\n";
let result = collapse_blank_lines(input, LineEnding::CrLf);
assert_eq!(result, b"line1\r\n\r\nline2\r\n");
}
#[test]
fn test_lf_file_stays_lf_after_edit() {
let content = b"fn existing() {\n body();\n}\n";
let sym = make_test_symbol("existing", SymbolKind::Function, (0, 29), 1);
let result = build_insert_before(
content,
&sym,
"fn new_fn() {}",
LineEnding::Lf,
&LanguageId::Rust,
)
.unwrap();
assert!(
!result.contains(&b'\r'),
"LF file edit must not introduce CR"
);
}
#[test]
fn test_batch_edit_crlf_multiple_replacements() {
let replacement = "fn alpha() {}\nfn beta() {}\n";
let normalized = normalize_line_endings(replacement.as_bytes(), LineEnding::CrLf);
assert!(
normalized.windows(2).any(|w| w == b"\r\n"),
"normalized replacement should contain CRLF"
);
for (i, &byte) in normalized.iter().enumerate() {
if byte == b'\n' {
assert!(
i > 0 && normalized[i - 1] == b'\r',
"bare LF at byte {i} in normalized replacement"
);
}
}
}
#[test]
fn test_crlf_edit_no_mixed_endings() {
let file_content = b"fn keep() {\r\n x();\r\n}\r\n";
let replacement_lf = b"fn keep() {\r\n y();\r\n}\r\n";
let normalized = normalize_line_endings(replacement_lf, LineEnding::CrLf);
let range = (0u32, file_content.len() as u32);
let result = apply_splice(file_content, range, &normalized);
for (i, &byte) in result.iter().enumerate() {
if byte == b'\n' {
assert!(
i > 0 && result[i - 1] == b'\r',
"bare LF at byte {i} after splice into CRLF file"
);
}
}
}
#[test]
fn test_single_edit_shorthand_replace() {
let json =
serde_json::json!("src/lib.rs::beta => replace fn beta(x: i32) -> i32 { x * 4 }");
let edit: SingleEdit = serde_json::from_value(json).unwrap();
assert_eq!(edit.path, "src/lib.rs");
assert_eq!(edit.name, "beta");
assert!(edit.kind.is_none());
assert!(edit.symbol_line.is_none());
match &edit.operation {
EditOperation::Replace { new_body } => {
assert_eq!(new_body, "fn beta(x: i32) -> i32 { x * 4 }");
}
other => panic!("expected Replace, got {other:?}"),
}
}
#[test]
fn test_single_edit_shorthand_delete() {
let json = serde_json::json!("src/lib.rs::old_fn => delete");
let edit: SingleEdit = serde_json::from_value(json).unwrap();
assert_eq!(edit.path, "src/lib.rs");
assert_eq!(edit.name, "old_fn");
assert!(matches!(edit.operation, EditOperation::Delete));
}
#[test]
fn test_single_edit_shorthand_insert_before() {
let json = serde_json::json!("src/lib.rs::main => insert_before fn setup() {}");
let edit: SingleEdit = serde_json::from_value(json).unwrap();
assert_eq!(edit.name, "main");
match &edit.operation {
EditOperation::InsertBefore { content } => {
assert_eq!(content, "fn setup() {}");
}
other => panic!("expected InsertBefore, got {other:?}"),
}
}
#[test]
fn test_single_edit_shorthand_insert_after() {
let json = serde_json::json!("src/lib.rs::main => insert_after fn teardown() {}");
let edit: SingleEdit = serde_json::from_value(json).unwrap();
match &edit.operation {
EditOperation::InsertAfter { content } => {
assert_eq!(content, "fn teardown() {}");
}
other => panic!("expected InsertAfter, got {other:?}"),
}
}
#[test]
fn test_single_edit_shorthand_edit_within() {
let json = serde_json::json!("src/lib.rs::process => edit_within x + 1 >>> x + 2");
let edit: SingleEdit = serde_json::from_value(json).unwrap();
match &edit.operation {
EditOperation::EditWithin { old_text, new_text } => {
assert_eq!(old_text, "x + 1");
assert_eq!(new_text, "x + 2");
}
other => panic!("expected EditWithin, got {other:?}"),
}
}
#[test]
fn test_single_edit_shorthand_in_batch_array() {
let json = serde_json::json!({
"dry_run": true,
"edits": [
"src/lib.rs::beta => replace fn beta(x: i32) -> i32 { x * 4 }"
]
});
let input: BatchEditInput = serde_json::from_value(json).unwrap();
assert!(input.dry_run == Some(true));
assert_eq!(input.edits.len(), 1);
assert_eq!(input.edits[0].path, "src/lib.rs");
assert_eq!(input.edits[0].name, "beta");
}
#[test]
fn test_single_edit_shorthand_invalid_no_separator() {
let json = serde_json::json!("src/lib.rs beta replace something");
let result = serde_json::from_value::<SingleEdit>(json);
assert!(result.is_err());
let error = result.err().unwrap().to_string();
assert!(
error.contains("JSON object with path/name/operation fields"),
"error: {error}"
);
}
#[test]
fn test_single_edit_struct_still_works() {
let json = serde_json::json!({
"path": "src/lib.rs",
"name": "beta",
"operation": {
"type": "replace",
"new_body": "fn beta() {}"
}
});
let edit: SingleEdit = serde_json::from_value(json).unwrap();
assert_eq!(edit.path, "src/lib.rs");
assert_eq!(edit.name, "beta");
match &edit.operation {
EditOperation::Replace { new_body } => assert_eq!(new_body, "fn beta() {}"),
other => panic!("expected Replace, got {other:?}"),
}
}
#[test]
fn test_single_edit_stringified_json_object() {
let inner = serde_json::json!({
"path": "src/lib.rs",
"name": "gamma",
"operation": { "type": "delete" }
});
let json = serde_json::json!(inner.to_string());
let edit: SingleEdit = serde_json::from_value(json).unwrap();
assert_eq!(edit.path, "src/lib.rs");
assert_eq!(edit.name, "gamma");
assert!(matches!(edit.operation, EditOperation::Delete));
}
#[test]
fn test_insert_target_shorthand_string_still_works() {
let json = serde_json::json!("src/lib.rs::helper");
let target: InsertTarget = serde_json::from_value(json).unwrap();
assert_eq!(target.path, "src/lib.rs");
assert_eq!(target.name, "helper");
assert!(target.kind.is_none());
assert!(target.symbol_line.is_none());
}
#[test]
fn test_insert_target_invalid_message_mentions_structured_payload() {
let json = serde_json::json!("helper");
let result = serde_json::from_value::<InsertTarget>(json);
assert!(result.is_err());
let error = result.err().unwrap().to_string();
assert!(
error.contains("JSON object with path/name fields"),
"error: {error}"
);
}
#[test]
fn test_replace_symbol_body_input_accepts_canonical_new_body() {
let raw = r#"{"path":"src/lib.rs","name":"foo","new_body":"fn foo() {}"}"#;
let input: ReplaceSymbolBodyInput = serde_json::from_str(raw).unwrap();
assert_eq!(input.path, "src/lib.rs");
assert_eq!(input.name, "foo");
assert_eq!(input.new_body, "fn foo() {}");
}
#[test]
fn test_replace_symbol_body_input_accepts_body_alias() {
let raw = r#"{"path":"src/lib.rs","name":"foo","body":"fn foo() {}"}"#;
let input: ReplaceSymbolBodyInput = serde_json::from_str(raw).unwrap();
assert_eq!(input.path, "src/lib.rs");
assert_eq!(input.name, "foo");
assert_eq!(input.new_body, "fn foo() {}");
}
#[test]
fn test_replace_symbol_body_input_rejects_both_new_body_and_body() {
let raw = r#"{"path":"src/lib.rs","name":"foo","new_body":"a","body":"b"}"#;
let result: Result<ReplaceSymbolBodyInput, _> = serde_json::from_str(raw);
assert!(
result.is_err(),
"expected duplicate-field error, got Ok(ReplaceSymbolBodyInput)"
);
let err = result.err().unwrap().to_string();
assert!(
err.contains("duplicate field"),
"expected duplicate-field error, got: {err}"
);
}
#[test]
fn test_edit_within_symbol_input_accepts_symbol_alias() {
let raw =
r#"{"path":"src/lib.rs","symbol":"foo","old_text":"a","new_text":"b","kind":null}"#;
let input: EditWithinSymbolInput = serde_json::from_str(raw).unwrap();
assert_eq!(input.name, "foo");
}
#[test]
fn test_edit_within_symbol_input_rejects_both_name_and_symbol() {
let raw =
r#"{"path":"src/lib.rs","name":"foo","symbol":"bar","old_text":"a","new_text":"b"}"#;
let result: Result<EditWithinSymbolInput, _> = serde_json::from_str(raw);
assert!(result.is_err(), "expected duplicate-field error");
}
#[test]
fn test_replace_symbol_body_input_accepts_working_directory() {
let raw = r#"{
"path":"src/lib.rs",
"name":"foo",
"new_body":"fn foo() {}",
"working_directory":"/tmp/wt"
}"#;
let v: ReplaceSymbolBodyInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
}
#[test]
fn test_replace_symbol_body_input_omitted_working_directory_is_none() {
let raw = r#"{"path":"src/lib.rs","name":"foo","new_body":"fn foo() {}"}"#;
let v: ReplaceSymbolBodyInput = serde_json::from_str(raw).unwrap();
assert!(v.working_directory.is_none());
}
#[test]
fn test_insert_symbol_input_accepts_working_directory() {
let raw = r#"{
"path":"src/lib.rs",
"name":"foo",
"content":"fn bar() {}",
"working_directory":"/tmp/wt"
}"#;
let v: InsertSymbolInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
}
#[test]
fn test_delete_symbol_input_accepts_working_directory() {
let raw = r#"{"path":"src/lib.rs","name":"foo","working_directory":"/tmp/wt"}"#;
let v: DeleteSymbolInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
}
#[test]
fn test_edit_within_symbol_input_accepts_working_directory() {
let raw = r#"{
"path":"src/lib.rs",
"name":"foo",
"old_text":"a",
"new_text":"b",
"working_directory":"/tmp/wt"
}"#;
let v: EditWithinSymbolInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
}
#[test]
fn test_batch_edit_input_accepts_working_directory() {
let raw = r#"{
"edits":[{"path":"src/lib.rs","name":"foo","operation":{"type":"delete"}}],
"working_directory":"/tmp/wt"
}"#;
let v: BatchEditInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
assert!(v.edits[0].working_directory.is_none());
}
#[test]
fn test_batch_insert_input_accepts_working_directory() {
let raw = r#"{
"content":"fn bar() {}",
"position":"after",
"targets":[{"path":"src/lib.rs","name":"foo"}],
"working_directory":"/tmp/wt"
}"#;
let v: BatchInsertInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
assert!(v.targets[0].working_directory.is_none());
}
#[test]
fn test_batch_rename_input_accepts_working_directory() {
let raw = r#"{
"path":"src/lib.rs",
"name":"foo",
"new_name":"bar",
"working_directory":"/tmp/wt"
}"#;
let v: BatchRenameInput = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt"));
}
#[test]
fn test_single_edit_struct_accepts_working_directory() {
let raw = r#"{
"path":"src/lib.rs",
"name":"foo",
"operation":{"type":"delete"},
"working_directory":"/tmp/wt-per-edit"
}"#;
let v: SingleEdit = serde_json::from_str(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt-per-edit"));
}
#[test]
fn test_single_edit_stringified_object_accepts_working_directory() {
let raw = serde_json::Value::String(
r#"{"path":"src/lib.rs","name":"foo","operation":{"type":"delete"},"working_directory":"/tmp/wt-per-edit"}"#
.to_string(),
);
let v: SingleEdit = serde_json::from_value(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt-per-edit"));
}
#[test]
fn test_single_edit_shorthand_leaves_working_directory_none() {
let raw = serde_json::Value::String("src/lib.rs::foo => delete".to_string());
let v: SingleEdit = serde_json::from_value(raw).unwrap();
assert!(v.working_directory.is_none());
}
#[test]
fn test_insert_target_struct_accepts_working_directory() {
let raw = serde_json::json!({
"path": "src/lib.rs",
"name": "foo",
"working_directory": "/tmp/wt-per-target"
});
let v: InsertTarget = serde_json::from_value(raw).unwrap();
assert_eq!(v.working_directory.as_deref(), Some("/tmp/wt-per-target"));
}
#[test]
fn test_insert_target_string_shorthand_leaves_working_directory_none() {
let raw = serde_json::Value::String("src/lib.rs::foo".to_string());
let v: InsertTarget = serde_json::from_value(raw).unwrap();
assert!(v.working_directory.is_none());
}
#[test]
fn docless_replacement_splice_start_preserves_same_line_block_doc() {
let source = b"/** @deprecated */ export function legacy() {}";
let symbol_start = source
.windows(b"function".len())
.position(|window| window == b"function")
.unwrap();
let start = docless_replacement_splice_start(source, 0, symbol_start);
assert_eq!(&source[..start], b"/** @deprecated */ ");
}
#[test]
fn docless_replacement_splice_start_preserves_same_line_doc_attribute() {
let source = br#"#[doc = "legacy"] pub fn legacy() {}"#;
let symbol_start = source
.windows(b"fn".len())
.position(|window| window == b"fn")
.unwrap();
let start = docless_replacement_splice_start(source, 0, symbol_start);
assert_eq!(&source[..start], br#"#[doc = "legacy"] "#);
}
#[test]
fn docless_replacement_splice_start_ignores_non_doc_prefix() {
let source = b"export function legacy() {}";
let symbol_start = source
.windows(b"function".len())
.position(|window| window == b"function")
.unwrap();
let start = docless_replacement_splice_start(source, 0, symbol_start);
assert_eq!(start, 0);
}
#[test]
fn body_starts_with_doc_comment_detects_common_doc_markers() {
assert!(body_starts_with_doc_comment(
"/// rust outer line doc\nfn foo() {}"
));
assert!(body_starts_with_doc_comment(
"//! rust inner line doc\nmod m {}"
));
assert!(body_starts_with_doc_comment(
"/** jsdoc-style block\n * details\n */\nfn foo() {}"
));
assert!(body_starts_with_doc_comment(
"/*! rust inner block doc */\nmod m {}"
));
assert!(body_starts_with_doc_comment(
"#[doc = \"attr doc\"]\nfn foo() {}"
));
assert!(body_starts_with_doc_comment("\n\n/// doc\nfn foo() {}"));
assert!(body_starts_with_doc_comment(
" /// indented doc\n fn foo() {}"
));
}
#[test]
fn body_starts_with_doc_comment_rejects_non_doc_prefixes() {
assert!(!body_starts_with_doc_comment("fn foo() {}"));
assert!(!body_starts_with_doc_comment(
"// regular comment\nfn foo() {}"
));
assert!(!body_starts_with_doc_comment(
"# python comment\ndef foo(): pass"
));
assert!(!body_starts_with_doc_comment("#[inline]\npub fn foo() {}"));
assert!(!body_starts_with_doc_comment("#[derive(Debug)]\nstruct S;"));
assert!(!body_starts_with_doc_comment(""));
assert!(!body_starts_with_doc_comment("\n\n \n"));
}
#[test]
fn symforge_edit_concurrent_same_file_apply_never_clobbers() {
use std::sync::{Arc, Barrier};
enum WriterResult {
Committed,
Rejected,
WriteErr,
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("contended.rs");
let base = b"fn target() { base }\n".to_vec();
let body_a = b"fn target() { writer_a }\n".to_vec();
let body_b = b"fn target() { writer_b }\n".to_vec();
const ROUNDS: usize = 200;
let mut double_commits = 0usize; let mut rejections = 0usize;
for round in 0..ROUNDS {
std::fs::write(&path, &base).expect("reset to base");
let barrier = Arc::new(Barrier::new(2));
let repo_root = dir.path().to_path_buf();
let spawn_writer = |new_content: Vec<u8>| {
let path = path.clone();
let base = base.clone();
let barrier = Arc::clone(&barrier);
let repo_root = repo_root.clone();
std::thread::spawn(move || {
barrier.wait();
match guarded_atomic_write_file(
&repo_root,
None,
&path,
&base,
&new_content,
Some("guard"),
) {
Ok(GuardedWriteOutcome::Written(_)) => WriterResult::Committed,
Ok(GuardedWriteOutcome::Rejected) => WriterResult::Rejected,
Err(_) => WriterResult::WriteErr,
}
})
};
let handle_a = spawn_writer(body_a.clone());
let handle_b = spawn_writer(body_b.clone());
let result_a = handle_a.join().expect("writer A thread panicked");
let result_b = handle_b.join().expect("writer B thread panicked");
let committed_a = matches!(result_a, WriterResult::Committed);
let committed_b = matches!(result_b, WriterResult::Committed);
let rejected_a = matches!(result_a, WriterResult::Rejected);
let rejected_b = matches!(result_b, WriterResult::Rejected);
if committed_a && committed_b {
double_commits += 1;
}
assert!(
!(committed_a && committed_b),
"round {round}: both writers committed — TR-06 clobber (the lock is not \
serializing the re-read → rename critical section)"
);
rejections += usize::from(rejected_a) + usize::from(rejected_b);
let on_disk = std::fs::read(&path).expect("read final on-disk content");
let expected_winner: Option<&Vec<u8>> = if committed_a {
Some(&body_a)
} else if committed_b {
Some(&body_b)
} else {
None
};
match expected_winner {
Some(winner) => {
assert_eq!(
on_disk, *winner,
"round {round}: on-disk content must equal the single committed \
writer's edit verbatim (no torn file)"
);
}
None => {
assert_eq!(
on_disk, base,
"round {round}: with no commit, on-disk must remain the base"
);
}
}
if rejected_a {
assert_ne!(
on_disk, body_a,
"round {round}: writer A was rejected — its body must not be on disk"
);
}
if rejected_b {
assert_ne!(
on_disk, body_b,
"round {round}: writer B was rejected — its body must not be on disk"
);
}
}
assert_eq!(
double_commits, 0,
"no round may double-commit; saw {double_commits} clobbers (the per-path lock \
is the only thing preventing this)"
);
assert!(
rejections > 0,
"expected the per-path lock to force at least one loser rejection across \
{ROUNDS} rounds; saw 0 (the race may not be contending)"
);
}
#[test]
fn guarded_writes_to_distinct_files_both_commit() {
use std::sync::{Arc, Barrier};
let dir = tempfile::tempdir().unwrap();
let path_a = dir.path().join("a.rs");
let path_b = dir.path().join("b.rs");
let base = b"fn t() { base }\n".to_vec();
std::fs::write(&path_a, &base).unwrap();
std::fs::write(&path_b, &base).unwrap();
let barrier = Arc::new(Barrier::new(2));
let repo_root = dir.path().to_path_buf();
let spawn = |path: std::path::PathBuf, body: Vec<u8>| {
let base = base.clone();
let barrier = Arc::clone(&barrier);
let repo_root = repo_root.clone();
std::thread::spawn(move || {
barrier.wait();
guarded_atomic_write_file(&repo_root, None, &path, &base, &body, Some("guard"))
.expect("guarded write must not error")
})
};
let h_a = spawn(path_a.clone(), b"fn t() { a }\n".to_vec());
let h_b = spawn(path_b.clone(), b"fn t() { b }\n".to_vec());
let out_a = h_a.join().unwrap();
let out_b = h_b.join().unwrap();
assert!(
matches!(out_a, GuardedWriteOutcome::Written(_)),
"distinct-file write A must commit"
);
assert!(
matches!(out_b, GuardedWriteOutcome::Written(_)),
"distinct-file write B must commit"
);
}
}