use std::collections::{BTreeMap, HashMap};
use std::ops::Range;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use crate::domain::SymbolRecord;
use crate::edit_safety::batch_commit::{
BatchAbort, BatchIo, EmbeddedBatchIo, StagedImage, commit_staged_locked, with_staged_locks,
};
use crate::edit_safety::preview::render_safe_batch;
use crate::edit_safety::rename::{RenamePlanInput, build_rename_plan};
use crate::edit_safety::structural::{
SpliceFootprint, WithinSelectionError, apply_splice, build_delete, build_insert_after,
cleanup_invalidates_splice, delete_cleanup_ranges, delete_source_range, detect_line_ending,
insert_after_position, insert_before_position, prepare_replace, replacement_splice_range,
select_edit_within_body, splice_footprints_overlap,
};
use crate::edit_safety::structural_rewrite::{
RewritePlan, paths_in_scope, plan_structural_rewrite, refusal,
};
use crate::embed::parity::edit::{
BatchEditAction, BatchEditApplied, BatchEditPreview, BatchEditRequest, BatchFilePreview,
BatchInsertRequest, BatchRenamePlan, BatchRenamePreview, BatchRenameRequest,
EditApplyAuthority, EditBody, EditError, EditErrorKind, EditTarget, InsertPosition,
InsertRequest, RoutedBatchApplied, RoutedBatchPart, StructuralRewriteRequest,
};
use crate::embed::parity::replay::{
OutcomeKind, ReplayKey, ReplayOutcome, ReplayState, ReplayStore, RequestFingerprint,
ReserveOutcome,
};
use crate::hash::digest_hex;
use crate::knowledge::{StableContentAdmission, classify_stable_content_for_root};
use super::embed_edit_body::{
self as answer, BatchBody, BatchFileParts, BatchParts, EditBodyParts,
};
use super::embed_mutation::{admitted, validate_guard};
use super::embed_query::EmbeddedQuerySnapshot;
use super::embedded::EmbeddedSourceHandle;
use super::guidance::edit_body::{self as shared, EditWriteSemantics, MatchType};
#[derive(Clone, Copy)]
enum BatchTool {
Edit,
Insert(InsertPosition),
}
impl BatchTool {
fn name(self) -> &'static str {
match self {
Self::Edit => "batch_edit",
Self::Insert(_) => "batch_insert",
}
}
}
fn position_label(position: InsertPosition) -> &'static str {
match position {
InsertPosition::Before => "before",
InsertPosition::After => "after",
}
}
struct PendingAnswer {
match_type: MatchType,
evidence: String,
body: BatchBody,
primary: String,
}
fn batch_file_parts(
snapshot: &EmbeddedQuerySnapshot,
request: &BatchEditRequest,
tool: BatchTool,
dry_run: bool,
) -> Result<Vec<BatchFileParts>, EditErrorKind> {
let mut by_file = BTreeMap::<String, Vec<(u32, usize, String)>>::new();
for (operation, action) in request.actions.iter().enumerate() {
let guard = action.guard();
let (file, symbol, _) = validate_guard(snapshot, guard)?;
let path = guard.path.as_str();
let old_bytes = (symbol.byte_range.1 - symbol.byte_range.0) as usize;
let summary = match action {
BatchEditAction::Replace(request) => shared::format_replace(
path,
&symbol.name,
&symbol.kind.to_string(),
old_bytes,
request.new_body.len(),
),
BatchEditAction::Insert(request) => shared::format_insert(
path,
&symbol.name,
position_label(request.position),
request.content.len(),
),
BatchEditAction::Delete(_) => {
shared::format_delete(path, &symbol.name, &symbol.kind.to_string(), old_bytes)
}
BatchEditAction::EditWithin(request) => {
let selection = select_edit_within_body(
&file.content,
symbol,
&request.old_text,
&request.new_text,
request.replace_all,
request.occurrence,
request.near_line,
)
.map_err(|_| EditErrorKind::TextNotFound)?;
let spliced = (symbol.byte_range.1 - symbol.effective_start()) as usize;
let new_bytes = (old_bytes + selection.new_body.len()).saturating_sub(spliced);
shared::format_edit_within(
path,
&symbol.name,
selection.count,
old_bytes,
new_bytes,
)
}
};
let summary = if dry_run {
format!("[DRY RUN] Would {summary}")
} else {
summary
};
let key = match tool {
BatchTool::Insert(InsertPosition::After) => symbol.byte_range.1,
_ => symbol.effective_start(),
};
by_file
.entry(guard.path.clone())
.or_default()
.push((key, operation, summary));
}
Ok(by_file
.into_iter()
.map(|(path, mut rows)| {
match tool {
BatchTool::Edit => rows.sort_by_key(|row| std::cmp::Reverse(row.0)),
BatchTool::Insert(_) => {
rows.sort_by(|left, right| right.0.cmp(&left.0).then(right.1.cmp(&left.1)))
}
}
BatchFileParts {
path,
summaries: rows.into_iter().map(|(_, _, summary)| summary).collect(),
tee: None,
reroute: String::new(),
}
})
.collect())
}
fn pending_batch(
snapshot: &EmbeddedQuerySnapshot,
request: &BatchEditRequest,
tool: BatchTool,
dry_run: bool,
) -> Result<PendingAnswer, EditErrorKind> {
let files = batch_file_parts(snapshot, request, tool, dry_run)?;
let file_count = files.len();
let count = request.actions.len();
Ok(PendingAnswer {
match_type: MatchType::Exact,
evidence: match tool {
BatchTool::Edit => format!("{count} edit target(s) across {file_count} file(s)"),
BatchTool::Insert(_) => format!("{count} target(s) across {file_count} file(s)"),
},
body: BatchBody::Summaries { files, file_count },
primary: request
.actions
.first()
.map(|action| action.guard().path.clone())
.unwrap_or_default(),
})
}
fn rename_evidence(path: &str) -> String {
format!("definition `{path}` + project-wide constrained references")
}
fn preview_answer(snapshot: &EmbeddedQuerySnapshot, pending: PendingAnswer) -> EditBody {
let impact = answer::impact_footer(snapshot, &snapshot.generation.live, &pending.primary);
EditBody::new(EditBodyParts::Batch(BatchParts {
match_type: pending.match_type,
semantics: EditWriteSemantics::DryRunNoWrites,
evidence: pending.evidence,
body: pending.body,
trust: answer::trust_suffix(snapshot),
impact: Some(impact),
}))
}
fn applied_answer(
snapshot: &EmbeddedQuerySnapshot,
mut pending: PendingAnswer,
staged: &[StagedImage],
tees: &[(usize, Option<crate::edit_safety::tee::TeeSnapshot>)],
reroute: &dyn Fn(&str) -> String,
) -> EditBody {
if let BatchBody::Summaries { files, .. } = &mut pending.body {
for file in files.iter_mut() {
file.reroute = reroute(&file.path);
}
for (index, tee) in tees {
let hint = tee.as_ref().and_then(|tee| tee.response_hint());
let path = staged[*index].relative.to_string_lossy();
if let Some(file) = files.iter_mut().find(|file| file.path == path) {
file.tee = hint;
}
}
}
let written: Vec<(String, &[u8])> = staged
.iter()
.map(|image| {
(
image.relative.to_string_lossy().into_owned(),
image.replacement.as_slice(),
)
})
.collect();
let written: Vec<(&str, &[u8])> = written
.iter()
.map(|(path, bytes)| (path.as_str(), *bytes))
.collect();
let after = answer::post_edit_index(snapshot, &written);
let impact = answer::impact_footer(snapshot, &after, &pending.primary);
EditBody::new(EditBodyParts::Batch(BatchParts {
match_type: pending.match_type,
semantics: EditWriteSemantics::TransactionalWriteRollbackAndReindex,
evidence: pending.evidence,
body: pending.body,
trust: answer::trust_suffix(snapshot),
impact: Some(impact),
}))
}
fn replayed_answer(tool: &'static str, files: &[(String, String)]) -> EditBody {
let paths = files
.iter()
.map(|(path, _)| path.as_str())
.collect::<Vec<_>>()
.join(", ");
let manifest = serde_json::to_vec(files).unwrap_or_default();
EditBody::new(EditBodyParts::Replayed {
tool,
path: paths,
post_image_hash: digest_hex(&manifest),
})
}
struct ResolvedAction<'a> {
symbol: SymbolRecord,
action: &'a BatchEditAction,
absolute: PathBuf,
}
fn stage_batch(
snapshot: &EmbeddedQuerySnapshot,
request: &BatchEditRequest,
) -> Result<Vec<StagedImage>, EditErrorKind> {
if request.actions.is_empty() || request.actions.len() > 100 {
return Err(EditErrorKind::InvalidReplacement);
}
let mut by_file = BTreeMap::<String, Vec<ResolvedAction<'_>>>::new();
for action in &request.actions {
let (file, symbol, absolute) = validate_guard(snapshot, action.guard())?;
if let Some(capability) =
crate::parsing::config_extractors::edit_capability_for_language(&file.language)
{
let allowed = match action {
BatchEditAction::EditWithin(_) => !matches!(
capability,
crate::parsing::config_extractors::EditCapability::IndexOnly
),
_ => matches!(
capability,
crate::parsing::config_extractors::EditCapability::StructuralEditSafe
),
};
if !allowed {
return Err(EditErrorKind::InvalidReplacement);
}
}
by_file
.entry(action.guard().path.clone())
.or_default()
.push(ResolvedAction {
symbol: symbol.clone(),
action,
absolute,
});
}
let mut staged = Vec::with_capacity(by_file.len());
for (path, mut actions) in by_file {
for left in 0..actions.len() {
for right in (left + 1)..actions.len() {
let a = &actions[left].symbol;
let b = &actions[right].symbol;
if a.effective_start() < b.byte_range.1 && b.effective_start() < a.byte_range.1 {
return Err(EditErrorKind::WriteConflict);
}
}
}
actions.sort_by(|left, right| {
right
.symbol
.effective_start()
.cmp(&left.symbol.effective_start())
});
let file = snapshot
.generation
.live
.get_file(&path)
.ok_or(EditErrorKind::FileNotAdmitted)?;
let line_ending = detect_line_ending(&file.content);
let footprints = actions
.iter()
.map(|resolved| {
Ok(match resolved.action {
BatchEditAction::Insert(request) => {
SpliceFootprint::Insert(match request.position {
crate::embed::parity::edit::InsertPosition::Before => {
insert_before_position(
&file.content,
&resolved.symbol,
&file.language,
)
.map_err(|_| EditErrorKind::InvalidReplacement)?
}
crate::embed::parity::edit::InsertPosition::After => {
insert_after_position(&file.content, &resolved.symbol)
}
})
}
BatchEditAction::Delete(_) => {
let (start, end) =
delete_source_range(&file.content, &resolved.symbol, line_ending);
SpliceFootprint::Bytes(start, end)
}
BatchEditAction::Replace(request) => {
let (start, end) = replacement_splice_range(
&file.content,
&resolved.symbol,
&request.new_body,
)
.map_err(|_| EditErrorKind::StaleContent)?;
SpliceFootprint::Bytes(start, end)
}
BatchEditAction::EditWithin(_) => SpliceFootprint::Bytes(
resolved.symbol.effective_start(),
resolved.symbol.byte_range.1,
),
})
})
.collect::<Result<Vec<_>, EditErrorKind>>()?;
for left in 0..footprints.len() {
for right in (left + 1)..footprints.len() {
if splice_footprints_overlap(footprints[left], footprints[right]) {
return Err(EditErrorKind::WriteConflict);
}
}
}
for (index, resolved) in actions.iter().enumerate() {
if !matches!(resolved.action, BatchEditAction::Delete(_)) {
continue;
}
let cleanup = delete_cleanup_ranges(&file.content, &resolved.symbol, line_ending);
if footprints.iter().enumerate().any(|(other, footprint)| {
other != index && cleanup_invalidates_splice(&cleanup, *footprint)
}) {
return Err(EditErrorKind::WriteConflict);
}
}
let mut content = file.content.clone();
for (action_index, resolved) in actions.iter().enumerate() {
content = match resolved.action {
BatchEditAction::Replace(request) => {
prepare_replace(&content, &resolved.symbol, &request.new_body)
.map_err(|_| EditErrorKind::StaleContent)?
.new_content
}
BatchEditAction::Insert(request) => {
let line_ending = detect_line_ending(&content);
match request.position {
crate::embed::parity::edit::InsertPosition::Before => {
let SpliceFootprint::Insert(position) = footprints[action_index] else {
return Err(EditErrorKind::StaleContent);
};
crate::edit_safety::structural::build_insert_before_at_position(
&content,
&resolved.symbol,
&request.content,
line_ending,
position,
&crate::edit_safety::structural::detect_indentation(
&file.content,
resolved.symbol.byte_range.0,
),
)
}
crate::embed::parity::edit::InsertPosition::After => build_insert_after(
&content,
&resolved.symbol,
&request.content,
line_ending,
),
}
}
BatchEditAction::Delete(_) => {
build_delete(&content, &resolved.symbol, detect_line_ending(&content))
}
BatchEditAction::EditWithin(request) => {
let selection = select_edit_within_body(
&content,
&resolved.symbol,
&request.old_text,
&request.new_text,
request.replace_all,
request.occurrence,
request.near_line,
)
.map_err(|error| match error {
WithinSelectionError::InvalidSpan | WithinSelectionError::InvalidUtf8 => {
EditErrorKind::StaleContent
}
WithinSelectionError::ConflictingTargeting => {
EditErrorKind::ConflictingTargeting
}
WithinSelectionError::OccurrenceOutOfRange { requested, total } => {
EditErrorKind::OccurrenceOutOfRange { requested, total }
}
WithinSelectionError::NotFound => EditErrorKind::TextNotFound,
})?;
apply_splice(
&content,
(
resolved.symbol.effective_start(),
resolved.symbol.byte_range.1,
),
selection.new_body.as_bytes(),
)
}
};
}
let targets =
crate::domain::IndexTargets::for_path(&file.relative_path, Some(&file.language));
if !matches!(
classify_stable_content_for_root(
&snapshot.root,
&file.relative_path,
targets,
&content,
),
StableContentAdmission::Admitted
) {
return Err(EditErrorKind::UnsafeContent);
}
staged.push(StagedImage {
relative: PathBuf::from(path),
absolute: actions[0].absolute.clone(),
original: Some(file.content.clone()),
replacement: content,
owner_only: false,
});
}
Ok(staged)
}
fn rename_plan(
snapshot: &EmbeddedQuerySnapshot,
guard: &crate::embed::parity::edit::EditGuard,
code_only: bool,
) -> Result<crate::edit_safety::rename::RenamePlan, EditErrorKind> {
let (file, symbol, _) = validate_guard(snapshot, guard)?;
build_rename_plan(
&snapshot.generation.live,
file,
symbol,
&RenamePlanInput {
path: guard.path.clone(),
name: guard.name.clone(),
code_only,
},
)
.map_err(|_| EditErrorKind::StaleContent)
}
fn stage_rename(
snapshot: &EmbeddedQuerySnapshot,
request: &BatchRenameRequest,
) -> Result<(Vec<StagedImage>, crate::edit_safety::rename::RenamePlan), EditErrorKind> {
if request.new_name.is_empty()
|| request.new_name.len() > crate::domain::index::METADATA_ONLY_CODE_BYTES as usize
{
return Err(EditErrorKind::InvalidReplacement);
}
let plan = rename_plan(snapshot, &request.plan.guard, request.plan.code_only)?;
let by_file = plan
.by_file
.iter()
.map(|(path, ranges)| (path.clone(), ranges.clone()))
.collect::<BTreeMap<_, _>>();
let paths = by_file.keys().cloned().collect::<Vec<_>>();
let sites = by_file.values().map(Vec::len).sum::<usize>();
if paths != request.plan.affected_paths
|| sites != request.plan.confident_sites
|| plan.uncertain_lines.len() != request.plan.uncertain_sites
{
return Err(EditErrorKind::WriteConflict);
}
let mut staged = Vec::with_capacity(paths.len());
for (path, ranges) in by_file {
let file = snapshot
.generation
.live
.get_file(&path)
.ok_or(EditErrorKind::FileNotAdmitted)?;
if !admitted(snapshot, file) {
return Err(EditErrorKind::UnsafeContent);
}
let absolute = crate::discovery::resolve_repo_path(&snapshot.root, &path)
.map_err(|_| EditErrorKind::InvalidPath)?
.ok_or(EditErrorKind::FileNotAdmitted)?;
let mut replacement = file.content.clone();
for range in ranges {
replacement = apply_splice(&replacement, range, request.new_name.as_bytes());
}
let targets =
crate::domain::IndexTargets::for_path(&file.relative_path, Some(&file.language));
if !matches!(
classify_stable_content_for_root(
&snapshot.root,
&file.relative_path,
targets,
&replacement,
),
StableContentAdmission::Admitted
) {
return Err(EditErrorKind::UnsafeContent);
}
staged.push(StagedImage {
relative: PathBuf::from(path),
absolute,
original: Some(file.content.clone()),
replacement,
owner_only: false,
});
}
Ok((staged, plan))
}
fn manifest(
staged: &[StagedImage],
authority: &super::activation::ProjectSourceAuthority,
) -> Result<Vec<u8>, EditErrorKind> {
serde_json::to_vec(&manifest_entries(staged, authority)?)
.map_err(|_| EditErrorKind::ReplayUnavailable)
}
fn manifest_entries(
staged: &[StagedImage],
authority: &super::activation::ProjectSourceAuthority,
) -> Result<Vec<(String, String)>, EditErrorKind> {
let mut entries = Vec::with_capacity(staged.len());
for image in staged {
let digest = crate::idempotency::post_image_digest_beneath(authority, &image.relative)
.ok_or(EditErrorKind::WriteUncertain)?
.ok_or(EditErrorKind::WriteUncertain)?;
entries.push((image.relative.to_string_lossy().to_string(), digest));
}
Ok(entries)
}
type PathManifest = (Vec<u8>, Vec<(String, String)>);
fn scope_manifest_for_paths(
paths: &[String],
authority: &super::activation::ProjectSourceAuthority,
) -> Result<PathManifest, EditErrorKind> {
let mut entries = Vec::with_capacity(paths.len());
for path in paths {
let digest =
crate::idempotency::post_image_digest_beneath(authority, std::path::Path::new(path))
.ok_or(EditErrorKind::ReplayConflict)?
.unwrap_or_else(|| "absent".to_string());
entries.push((path.clone(), digest));
}
let manifest = serde_json::to_vec(&entries).map_err(|_| EditErrorKind::ReplayUnavailable)?;
Ok((manifest, entries))
}
fn current_manifest_for_paths(
root: &std::path::Path,
paths: &[String],
authority: &super::activation::ProjectSourceAuthority,
) -> Result<PathManifest, EditErrorKind> {
if paths.is_empty() {
return Err(EditErrorKind::ReplayConflict);
}
let mut files = BTreeMap::new();
for path in paths {
let absolute = crate::discovery::resolve_repo_path(root, path)
.map_err(|_| EditErrorKind::ReplayConflict)?
.ok_or(EditErrorKind::ReplayConflict)?;
if files.insert(path.clone(), absolute).is_some() {
return Err(EditErrorKind::ReplayConflict);
}
}
let images = files
.into_iter()
.map(|(path, absolute)| StagedImage {
relative: PathBuf::from(path),
absolute,
original: None,
replacement: Vec::new(),
owner_only: false,
})
.collect::<Vec<_>>();
with_staged_locks(&images, |_| {
let mut entries = Vec::with_capacity(images.len());
for image in &images {
let digest = crate::idempotency::post_image_digest_beneath(authority, &image.relative)
.ok_or(EditErrorKind::ReplayConflict)?
.ok_or(EditErrorKind::ReplayConflict)?;
entries.push((image.relative.to_string_lossy().to_string(), digest));
}
let manifest =
serde_json::to_vec(&entries).map_err(|_| EditErrorKind::ReplayUnavailable)?;
Ok((manifest, entries))
})
.map_err(|_| EditErrorKind::ReplayConflict)?
}
fn edit_paths(
root: &std::path::Path,
request: &BatchEditRequest,
) -> Result<Vec<String>, EditErrorKind> {
if request.actions.is_empty() || request.actions.len() > 100 {
return Err(EditErrorKind::InvalidReplacement);
}
let mut paths = std::collections::BTreeSet::new();
for action in &request.actions {
let guard = action.guard();
if guard.root != root {
return Err(EditErrorKind::InvalidPath);
}
paths.insert(guard.path.clone());
}
Ok(paths.into_iter().collect())
}
fn request_fingerprint(
request: &BatchEditRequest,
authority: &EditApplyAuthority,
) -> Result<RequestFingerprint, EditErrorKind> {
RequestFingerprint::for_json(
"embed_batch_edit_v1",
&serde_json::json!({"scope": authority.scope, "actions": action_rows(request)?}),
)
.map_err(|_| EditErrorKind::ReplayUnavailable)
}
fn action_rows(request: &BatchEditRequest) -> Result<Vec<serde_json::Value>, EditErrorKind> {
let mut actions = Vec::with_capacity(request.actions.len());
for action in &request.actions {
let guard = action.guard();
let (operation, payload) = match action {
BatchEditAction::Replace(request) => {
("replace", digest_hex(request.new_body.as_bytes()))
}
BatchEditAction::Insert(request) => (
match request.position {
crate::embed::parity::edit::InsertPosition::Before => "insert_before",
crate::embed::parity::edit::InsertPosition::After => "insert_after",
},
digest_hex(request.content.as_bytes()),
),
BatchEditAction::Delete(_) => ("delete", String::new()),
BatchEditAction::EditWithin(request) => {
let args = serde_json::json!({
"old_hash": digest_hex(request.old_text.as_bytes()),
"new_hash": digest_hex(request.new_text.as_bytes()),
"replace_all": request.replace_all,
"occurrence": request.occurrence,
"near_line": request.near_line,
});
(
"edit_within",
digest_hex(
&serde_json::to_vec(&args).map_err(|_| EditErrorKind::ReplayUnavailable)?,
),
)
}
};
actions.push(serde_json::json!({
"path": guard.path,
"name": guard.name,
"kind": guard.kind,
"symbol_line": guard.symbol_line,
"source_version": guard.source_version,
"publication_identity": guard.publication_identity,
"serving_publication_identity": guard.serving_publication_identity,
"publication_generation": guard.publication_generation,
"content_generation": guard.content_generation,
"content_hash": guard.content_hash,
"symbol_hash": guard.symbol_hash,
"operation": operation,
"payload_hash": payload,
}));
}
Ok(actions)
}
fn rename_fingerprint(
request: &BatchRenameRequest,
authority: &EditApplyAuthority,
) -> Result<RequestFingerprint, EditErrorKind> {
let guard = &request.plan.guard;
RequestFingerprint::for_json(
"embed_batch_rename_v1",
&serde_json::json!({
"scope": authority.scope,
"path": guard.path,
"name": guard.name,
"kind": guard.kind,
"symbol_line": guard.symbol_line,
"source_version": guard.source_version,
"publication_identity": guard.publication_identity,
"serving_publication_identity": guard.serving_publication_identity,
"publication_generation": guard.publication_generation,
"content_generation": guard.content_generation,
"content_hash": guard.content_hash,
"symbol_hash": guard.symbol_hash,
"new_name_hash": digest_hex(request.new_name.as_bytes()),
"code_only": request.plan.code_only,
"affected_paths": request.plan.affected_paths,
"confident_sites": request.plan.confident_sites,
"uncertain_sites": request.plan.uncertain_sites,
}),
)
.map_err(|_| EditErrorKind::ReplayUnavailable)
}
impl EmbeddedSourceHandle {
pub fn plan_batch_rename(
&self,
target: &EditTarget,
code_only: bool,
) -> Result<BatchRenamePlan, EditError> {
let edit_plan = self.edit_plan(target)?;
let snapshot = self.capture_query_snapshot(b"plan-batch-rename")?;
let plan = rename_plan(&snapshot, &edit_plan.guard, code_only).map_err(EditError::Edit)?;
let by_file = plan.by_file.into_iter().collect::<BTreeMap<_, _>>();
Ok(BatchRenamePlan {
guard: edit_plan.guard,
code_only,
affected_paths: by_file.keys().cloned().collect(),
confident_sites: by_file.values().map(Vec::len).sum(),
uncertain_sites: plan.uncertain_lines.len(),
})
}
pub fn preview_batch_rename(
&self,
request: &BatchRenameRequest,
) -> Result<BatchRenamePreview, EditError> {
let snapshot = self.capture_query_snapshot(b"preview-batch-rename")?;
answer::enforce_trust(&snapshot)?;
let (staged, plan) = stage_rename(&snapshot, request).map_err(EditError::Edit)?;
let mut rendered = crate::edit_safety::rename::render_rename_preview(
&snapshot.generation.live,
&plan,
&request.plan.guard.name,
&request.new_name,
);
let body = preview_answer(
&snapshot,
PendingAnswer {
match_type: MatchType::Constrained,
evidence: rename_evidence(&request.plan.guard.path),
body: BatchBody::Rename {
text: rendered.clone(),
paths: Vec::new(),
},
primary: request.plan.guard.path.clone(),
},
);
const MAX_PREVIEW_BYTES: usize = 1_048_576;
let truncated = rendered.len() > MAX_PREVIEW_BYTES;
if truncated {
let mut boundary = MAX_PREVIEW_BYTES;
while !rendered.is_char_boundary(boundary) {
boundary -= 1;
}
rendered.truncate(boundary);
rendered.push_str("\n… preview truncated; hashes cover the complete staged rename");
}
if crate::knowledge::guard_query(&rendered).is_err() {
return Err(EditError::Edit(EditErrorKind::UnsafeContent));
}
let diff = render_safe_batch(staged.iter().map(|image| {
(
image.relative.to_str().expect("indexed UTF-8 path"),
image.original.as_deref().expect("indexed source"),
image.replacement.as_slice(),
)
}))
.map_err(|_| EditError::Edit(EditErrorKind::UnsafeContent))?;
let changes = BatchEditPreview {
files: staged
.iter()
.map(|image| BatchFilePreview {
path: image.relative.to_string_lossy().to_string(),
old_file_hash: digest_hex(image.original.as_deref().expect("indexed source")),
proposed_file_hash: digest_hex(&image.replacement),
})
.collect(),
action_count: request.plan.confident_sites,
publication_identity: snapshot.publication_identity,
source_version: snapshot.source_version,
rendered: diff.rendered,
truncated: diff.truncated,
redacted: diff.redacted,
body,
};
Ok(BatchRenamePreview {
changes,
rendered,
truncated,
})
}
pub fn apply_batch_rename(
&self,
request: &BatchRenameRequest,
authority: &EditApplyAuthority,
operation_key: &str,
) -> Result<BatchEditApplied, EditError> {
let snapshot = self.capture_query_snapshot(b"apply-batch-rename")?;
answer::enforce_trust(&snapshot)?;
if request.plan.guard.root != snapshot.root || request.plan.affected_paths.is_empty() {
return Err(EditError::Edit(EditErrorKind::InvalidPath));
}
let fingerprint = rename_fingerprint(request, authority).map_err(EditError::Edit)?;
self.apply_staged_batch(
snapshot,
authority,
operation_key,
fingerprint,
request.plan.affected_paths.clone(),
StagedAnswer {
tool: "batch_rename",
tee: false,
scope_manifest: false,
stage: Box::new(|snapshot| {
let (staged, plan) = stage_rename(snapshot, request)?;
let sites = plan.by_file.values().map(Vec::len).sum::<usize>();
let mut text = format!(
"Renamed `{}` → `{}` — {sites} site(s) across {} file(s)",
request.plan.guard.name,
request.new_name,
staged.len(),
);
if !plan.uncertain_lines.is_empty() {
text.push_str(&format!(
"\n\n── Uncertain matches (NOT applied — review manually) — {} site(s) ──\n",
plan.uncertain_lines.len(),
));
text.push_str(&plan.uncertain_lines.join("\n"));
}
let paths = staged
.iter()
.map(|image| image.relative.to_string_lossy().into_owned())
.collect();
Ok((
staged,
PendingAnswer {
match_type: MatchType::Constrained,
evidence: rename_evidence(&request.plan.guard.path),
body: BatchBody::Rename { text, paths },
primary: request.plan.guard.path.clone(),
},
))
}),
},
)
}
pub fn preview_batch_insert(
&self,
request: &BatchInsertRequest,
) -> Result<BatchEditPreview, EditError> {
self.preview_batch(
&batch_insert_as_edits(request).map_err(EditError::Edit)?,
BatchTool::Insert(request.position),
)
}
pub fn apply_batch_insert(
&self,
request: &BatchInsertRequest,
authority: &EditApplyAuthority,
operation_key: &str,
) -> Result<BatchEditApplied, EditError> {
self.apply_batch(
&batch_insert_as_edits(request).map_err(EditError::Edit)?,
authority,
operation_key,
BatchTool::Insert(request.position),
)
}
pub fn preview_batch_edit(
&self,
request: &BatchEditRequest,
) -> Result<BatchEditPreview, EditError> {
self.preview_batch(request, BatchTool::Edit)
}
fn preview_batch(
&self,
request: &BatchEditRequest,
tool: BatchTool,
) -> Result<BatchEditPreview, EditError> {
let snapshot = self.capture_query_snapshot(b"preview-batch-edit")?;
answer::enforce_trust(&snapshot)?;
let staged = stage_batch(&snapshot, request).map_err(EditError::Edit)?;
let body = preview_answer(
&snapshot,
pending_batch(&snapshot, request, tool, true).map_err(EditError::Edit)?,
);
let diff = render_safe_batch(staged.iter().map(|image| {
(
image.relative.to_str().expect("indexed UTF-8 path"),
image.original.as_deref().expect("indexed source"),
image.replacement.as_slice(),
)
}))
.map_err(|_| EditError::Edit(EditErrorKind::UnsafeContent))?;
Ok(BatchEditPreview {
files: staged
.iter()
.map(|image| BatchFilePreview {
path: image.relative.to_string_lossy().to_string(),
old_file_hash: digest_hex(image.original.as_deref().expect("indexed source")),
proposed_file_hash: digest_hex(&image.replacement),
})
.collect(),
action_count: request.actions.len(),
publication_identity: snapshot.publication_identity,
source_version: snapshot.source_version,
rendered: diff.rendered,
truncated: diff.truncated,
redacted: diff.redacted,
body,
})
}
pub fn apply_batch_edit(
&self,
request: &BatchEditRequest,
authority: &EditApplyAuthority,
operation_key: &str,
) -> Result<BatchEditApplied, EditError> {
self.apply_batch(request, authority, operation_key, BatchTool::Edit)
}
fn apply_batch(
&self,
request: &BatchEditRequest,
authority: &EditApplyAuthority,
operation_key: &str,
tool: BatchTool,
) -> Result<BatchEditApplied, EditError> {
let snapshot = self.capture_query_snapshot(b"apply-batch-edit")?;
answer::enforce_trust(&snapshot)?;
let replay_paths = edit_paths(&snapshot.root, request).map_err(EditError::Edit)?;
let fingerprint = request_fingerprint(request, authority).map_err(EditError::Edit)?;
self.apply_staged_batch(
snapshot,
authority,
operation_key,
fingerprint,
replay_paths,
StagedAnswer {
tool: tool.name(),
tee: matches!(tool, BatchTool::Edit),
scope_manifest: false,
stage: Box::new(move |snapshot| {
Ok((
stage_batch(snapshot, request)?,
pending_batch(snapshot, request, tool, false)?,
))
}),
},
)
}
fn apply_staged_batch(
&self,
snapshot: EmbeddedQuerySnapshot,
authority: &EditApplyAuthority,
operation_key: &str,
fingerprint: RequestFingerprint,
replay_paths: Vec<String>,
answer: StagedAnswer<'_>,
) -> Result<BatchEditApplied, EditError> {
let StagedAnswer {
tool,
tee,
scope_manifest,
stage,
} = answer;
if authority.root != snapshot.root || authority.cancel.load(Ordering::Acquire) {
return Err(EditError::Edit(EditErrorKind::WriteAuthorityRefused));
}
let state_dir = snapshot
.state_dir
.as_deref()
.ok_or(EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let key = ReplayKey::new(operation_key)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let anchor = snapshot
.authority
.physical_root_stable_key()
.ok_or(EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let replay = ReplayStore::open_bound(&snapshot.root, state_dir, &authority.scope, anchor)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let lease = match replay
.reserve_with_lease(&key, &fingerprint, std::time::Duration::from_secs(3600))
.map_err(|_| EditError::Edit(EditErrorKind::ReplayConflict))?
{
ReserveOutcome::Acquired(lease) => lease,
ReserveOutcome::Existing(record) => {
if record.state != ReplayState::Completed
|| record
.outcome
.as_ref()
.is_none_or(|outcome| outcome.kind != OutcomeKind::Applied)
{
return Err(EditError::Edit(EditErrorKind::ReplayConflict));
}
let (current, files) = if scope_manifest {
scope_manifest_for_paths(&replay_paths, &snapshot.authority)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayConflict))?
} else {
current_manifest_for_paths(&snapshot.root, &replay_paths, &snapshot.authority)
.map_err(EditError::Edit)?
};
if !record.matches_post_image(¤t) {
return Err(EditError::Edit(EditErrorKind::ReplayConflict));
}
let body = replayed_answer(tool, &files);
return Ok(BatchEditApplied {
files,
replayed: true,
refresh_ticket_identity: None,
body,
});
}
};
let (staged, pending) = match stage(&snapshot) {
Ok(staged) => staged,
Err(error) => {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(error));
}
};
if authority.cancel.load(Ordering::Acquire) {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(EditErrorKind::Cancelled));
}
if replay.mark_started(&lease).is_err() {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(EditErrorKind::ReplayUnavailable));
}
with_staged_locks(&staged, |order| {
let source_authority = &snapshot.authority;
let write =
match source_authority.acquire_write_expected(snapshot.authority_publication) {
Ok(write) => write,
Err(_) => {
let _ = replay.mark_uncertain(&lease);
return Err(EditError::Edit(EditErrorKind::WriteUncertain));
}
};
let mut io = EmbeddedBatchIo::new(write);
if tee && let Some(project_state) = snapshot.project_state.as_ref() {
io = io.with_tee(crate::edit_safety::tee::Tee::for_repo(
&snapshot.root,
project_state,
));
}
let committed = commit_staged_locked(&staged, order, &mut io, Some(&authority.cancel));
match committed {
Ok(tees) => {
if io.finish().is_err() {
let _ = replay.mark_uncertain(&lease);
return Err(EditError::Edit(EditErrorKind::WriteUncertain));
}
let refresh = self.request_refresh();
if authority.cancel.load(Ordering::Acquire) || refresh.is_err() {
let _ = replay.mark_uncertain(&lease);
return Err(EditError::Edit(EditErrorKind::WriteUncertain));
}
let post = if scope_manifest {
scope_manifest_for_paths(&replay_paths, &snapshot.authority)
.map(|(bytes, _)| bytes)
} else {
manifest(&staged, &snapshot.authority)
}
.map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
let outcome = ReplayOutcome::from_response_and_post_image(
OutcomeKind::Applied,
b"batch_applied",
&post,
)
.map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
replay.complete(&lease, &outcome).map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
snapshot.record_commitment(
&staged
.iter()
.map(|image| image.relative.clone())
.collect::<Vec<_>>(),
);
let body =
applied_answer(&snapshot, pending, &staged, &tees, &|_| String::new());
Ok(BatchEditApplied {
files: staged
.iter()
.map(|image| {
(
image.relative.to_string_lossy().to_string(),
digest_hex(&image.replacement),
)
})
.collect(),
replayed: false,
refresh_ticket_identity: Some(
refresh
.expect("checked refresh")
.ticket_identity()
.to_owned(),
),
body,
})
}
Err(abort) => {
let no_source_write = abort.no_source_write();
let uncertain = abort.rollback_uncertain();
if uncertain || io.finish().is_err() {
let _ = replay.mark_uncertain(&lease);
return Err(EditError::Edit(EditErrorKind::WriteUncertain));
}
let _ = self.request_refresh();
let current = manifest(&staged, &snapshot.authority).map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
let outcome = ReplayOutcome::from_response_and_post_image(
OutcomeKind::Rejected,
b"batch_rejected",
¤t,
)
.map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
replay.fail(&lease, &outcome).map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?;
Err(EditError::Edit(if no_source_write {
EditErrorKind::WriteConflict
} else {
match abort {
BatchAbort::Cancelled { .. } => EditErrorKind::Cancelled,
_ => EditErrorKind::WriteConflict,
}
}))
}
}
})
.map_err(|_| {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
})?
}
}
struct StagedAnswer<'a> {
tool: &'static str,
tee: bool,
scope_manifest: bool,
#[allow(clippy::type_complexity)]
stage: Box<
dyn FnOnce(
&EmbeddedQuerySnapshot,
) -> Result<(Vec<StagedImage>, PendingAnswer), EditErrorKind>
+ 'a,
>,
}
struct RoutedBatchIo {
ios: Vec<EmbeddedBatchIo>,
owner: HashMap<PathBuf, usize>,
}
impl RoutedBatchIo {
fn io(&mut self, image: &StagedImage) -> Result<&mut EmbeddedBatchIo, String> {
let index = *self
.owner
.get(&image.absolute)
.ok_or_else(|| "batch_image_unrouted".to_string())?;
Ok(&mut self.ios[index])
}
fn finish(self) -> Result<(), String> {
let mut result = Ok(());
for io in self.ios {
if let Err(error) = io.finish() {
result = Err(error);
}
}
result
}
}
impl BatchIo for RoutedBatchIo {
type Report = Option<crate::edit_safety::tee::TeeSnapshot>;
fn matches(&mut self, image: &StagedImage, expected: Option<&[u8]>) -> Result<bool, String> {
self.io(image)?.matches(image, expected)
}
fn write(&mut self, image: &StagedImage, bytes: &[u8]) -> Result<Self::Report, String> {
self.io(image)?.write(image, bytes)
}
}
type RoutedManifest = Vec<(String, Vec<(String, String)>)>;
fn routed_manifest(entries: &[(String, Vec<(String, String)>)]) -> Result<Vec<u8>, EditErrorKind> {
serde_json::to_vec(entries).map_err(|_| EditErrorKind::ReplayUnavailable)
}
impl EmbeddedSourceHandle {
pub fn apply_routed_batch_edit(
&self,
authority: &EditApplyAuthority,
parts: &[RoutedBatchPart<'_>],
operation_key: &str,
) -> Result<RoutedBatchApplied, EditError> {
self.apply_routed_batch(authority, parts, operation_key, BatchTool::Edit)
}
fn apply_routed_batch(
&self,
authority: &EditApplyAuthority,
parts: &[RoutedBatchPart<'_>],
operation_key: &str,
tool: BatchTool,
) -> Result<RoutedBatchApplied, EditError> {
let bound = self.capture_query_snapshot(b"apply-routed-batch-edit")?;
answer::enforce_trust(&bound)?;
if authority.root != bound.root || authority.cancel.load(Ordering::Acquire) {
return Err(EditError::Edit(EditErrorKind::WriteAuthorityRefused));
}
let action_count: usize = parts.iter().map(|part| part.request.actions.len()).sum();
if parts.is_empty() || action_count == 0 || action_count > 100 {
return Err(EditError::Edit(EditErrorKind::InvalidReplacement));
}
let mut snapshots: Vec<EmbeddedQuerySnapshot> = Vec::with_capacity(parts.len());
let mut replay_paths = Vec::with_capacity(parts.len());
let mut rows = Vec::with_capacity(parts.len());
for part in parts {
let snapshot = part
.handle
.capture_query_snapshot(b"apply-routed-batch-part")?;
if part.authority.root != snapshot.root || part.authority.cancel.load(Ordering::Acquire)
{
return Err(EditError::Edit(EditErrorKind::WriteAuthorityRefused));
}
if snapshot.root != bound.root
&& !super::embed_route::same_repository(&bound, &snapshot)
{
return Err(EditError::Edit(EditErrorKind::WorkingDirectoryNotAWorktree));
}
if snapshots.iter().any(|other| other.root == snapshot.root) {
return Err(EditError::Edit(EditErrorKind::InvalidPath));
}
replay_paths.push(edit_paths(&snapshot.root, &part.request).map_err(EditError::Edit)?);
rows.push(serde_json::json!({
"root": snapshot.root.to_string_lossy(),
"scope": part.authority.scope,
"actions": action_rows(&part.request).map_err(EditError::Edit)?,
}));
snapshots.push(snapshot);
}
let fingerprint = RequestFingerprint::for_json(
"embed_routed_batch_edit_v1",
&serde_json::json!({"scope": authority.scope, "parts": rows}),
)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let state_dir = bound
.state_dir
.as_deref()
.ok_or(EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let key = ReplayKey::new(operation_key)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let anchor = bound
.authority
.physical_root_stable_key()
.ok_or(EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let replay = ReplayStore::open_bound(&bound.root, state_dir, &authority.scope, anchor)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
let root_key =
|snapshot: &EmbeddedQuerySnapshot| snapshot.root.to_string_lossy().into_owned();
let lease = match replay
.reserve_with_lease(&key, &fingerprint, std::time::Duration::from_secs(3600))
.map_err(|_| EditError::Edit(EditErrorKind::ReplayConflict))?
{
ReserveOutcome::Acquired(lease) => lease,
ReserveOutcome::Existing(record) => {
if record.state != ReplayState::Completed
|| record
.outcome
.as_ref()
.is_none_or(|outcome| outcome.kind != OutcomeKind::Applied)
{
return Err(EditError::Edit(EditErrorKind::ReplayConflict));
}
let mut entries = Vec::with_capacity(snapshots.len());
for (snapshot, paths) in snapshots.iter().zip(&replay_paths) {
let (_, files) =
current_manifest_for_paths(&snapshot.root, paths, &snapshot.authority)
.map_err(EditError::Edit)?;
entries.push((root_key(snapshot), files));
}
if !record.matches_post_image(&routed_manifest(&entries).map_err(EditError::Edit)?)
{
return Err(EditError::Edit(EditErrorKind::ReplayConflict));
}
let body = replayed_answer(
tool.name(),
&entries
.iter()
.flat_map(|(_, files)| files.iter().cloned())
.collect::<Vec<_>>(),
);
return Ok(RoutedBatchApplied {
parts: entries
.into_iter()
.map(|(_, files)| BatchEditApplied {
files,
replayed: true,
refresh_ticket_identity: None,
body: body.clone(),
})
.collect(),
replayed: true,
body,
});
}
};
let mut staged = Vec::new();
let mut ranges: Vec<Range<usize>> = Vec::with_capacity(parts.len());
let mut owner = HashMap::new();
for (index, (part, snapshot)) in parts.iter().zip(&snapshots).enumerate() {
let images = match stage_batch(snapshot, &part.request) {
Ok(images) => images,
Err(error) => {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(error));
}
};
let start = staged.len();
for image in images {
owner.insert(image.absolute.clone(), index);
staged.push(image);
}
ranges.push(start..staged.len());
}
let mut files = Vec::new();
let mut reroutes = HashMap::new();
for (part, snapshot) in parts.iter().zip(&snapshots) {
let part_files = match batch_file_parts(snapshot, &part.request, tool, false) {
Ok(part_files) => part_files,
Err(error) => {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(error));
}
};
for file in part_files {
if let Some(working_directory) = part.working_directory.as_deref() {
reroutes.insert(
file.path.clone(),
answer::shared_reroute(
working_directory,
snapshot.root != bound.root,
&dunce::simplified(&snapshot.root).join(&file.path),
&dunce::simplified(&bound.root).join(&file.path),
),
);
}
files.push(file);
}
}
files.sort_by(|left, right| left.path.cmp(&right.path));
let file_count = files.len();
let pending = PendingAnswer {
match_type: MatchType::Exact,
evidence: match tool {
BatchTool::Edit => {
format!("{action_count} edit target(s) across {file_count} file(s)")
}
BatchTool::Insert(_) => {
format!("{action_count} target(s) across {file_count} file(s)")
}
},
body: BatchBody::Summaries { files, file_count },
primary: parts
.iter()
.find_map(|part| part.request.actions.first())
.map(|action| action.guard().path.clone())
.unwrap_or_default(),
};
if authority.cancel.load(Ordering::Acquire) {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(EditErrorKind::Cancelled));
}
if replay.mark_started(&lease).is_err() {
let _ = replay.release_not_started(&lease);
return Err(EditError::Edit(EditErrorKind::ReplayUnavailable));
}
let uncertain = || {
let _ = replay.mark_uncertain(&lease);
EditError::Edit(EditErrorKind::WriteUncertain)
};
let current_entries = || -> Result<RoutedManifest, EditError> {
snapshots
.iter()
.zip(&ranges)
.map(|(snapshot, range)| {
manifest_entries(&staged[range.clone()], &snapshot.authority)
.map(|files| (root_key(snapshot), files))
.map_err(|_| uncertain())
})
.collect()
};
with_staged_locks(&staged, |order| {
let mut by_root: Vec<usize> = (0..snapshots.len()).collect();
by_root.sort_by(|left, right| snapshots[*left].root.cmp(&snapshots[*right].root));
let mut writes: Vec<Option<EmbeddedBatchIo>> =
(0..snapshots.len()).map(|_| None).collect();
for index in by_root {
let snapshot = &snapshots[index];
match snapshot
.authority
.acquire_write_expected(snapshot.authority_publication)
{
Ok(write) => {
let mut io = EmbeddedBatchIo::new(write);
if matches!(tool, BatchTool::Edit)
&& let Some(project_state) = bound.project_state.as_ref()
{
io = io.with_tee(crate::edit_safety::tee::Tee::for_repo(
&bound.root,
project_state,
));
}
writes[index] = Some(io);
}
Err(_) => {
for io in writes.into_iter().flatten() {
let _ = io.finish();
}
return Err(uncertain());
}
}
}
let mut io = RoutedBatchIo {
ios: writes.into_iter().flatten().collect(),
owner,
};
match commit_staged_locked(&staged, order, &mut io, Some(&authority.cancel)) {
Ok(tees) => {
if io.finish().is_err() {
return Err(uncertain());
}
let body = applied_answer(&bound, pending, &staged, &tees, &|path| {
reroutes.get(path).cloned().unwrap_or_default()
});
let mut tickets = Vec::with_capacity(parts.len());
for part in parts {
match part.handle.request_refresh() {
Ok(ticket) => tickets.push(ticket.ticket_identity().to_owned()),
Err(_) => return Err(uncertain()),
}
}
if authority.cancel.load(Ordering::Acquire) {
return Err(uncertain());
}
let post = current_entries()?;
let outcome = ReplayOutcome::from_response_and_post_image(
OutcomeKind::Applied,
b"routed_batch_applied",
&routed_manifest(&post).map_err(|_| uncertain())?,
)
.map_err(|_| uncertain())?;
replay.complete(&lease, &outcome).map_err(|_| uncertain())?;
for (snapshot, range) in snapshots.iter().zip(&ranges) {
snapshot.record_commitment(
&staged[range.clone()]
.iter()
.map(|image| image.relative.clone())
.collect::<Vec<_>>(),
);
}
Ok(RoutedBatchApplied {
parts: ranges
.iter()
.zip(tickets)
.map(|(range, ticket)| BatchEditApplied {
files: staged[range.clone()]
.iter()
.map(|image| {
(
image.relative.to_string_lossy().to_string(),
digest_hex(&image.replacement),
)
})
.collect(),
replayed: false,
refresh_ticket_identity: Some(ticket),
body: body.clone(),
})
.collect(),
replayed: false,
body,
})
}
Err(abort) => {
let no_source_write = abort.no_source_write();
if abort.rollback_uncertain() || io.finish().is_err() {
return Err(uncertain());
}
for part in parts {
let _ = part.handle.request_refresh();
}
let current = current_entries()?;
let outcome = ReplayOutcome::from_response_and_post_image(
OutcomeKind::Rejected,
b"routed_batch_rejected",
&routed_manifest(¤t).map_err(|_| uncertain())?,
)
.map_err(|_| uncertain())?;
replay.fail(&lease, &outcome).map_err(|_| uncertain())?;
Err(EditError::Edit(if no_source_write {
EditErrorKind::WriteConflict
} else {
match abort {
BatchAbort::Cancelled { .. } => EditErrorKind::Cancelled,
_ => EditErrorKind::WriteConflict,
}
}))
}
}
})
.map_err(|_| uncertain())?
}
pub fn apply_routed_batch_insert(
&self,
authority: &EditApplyAuthority,
parts: &[RoutedBatchPart<'_, BatchInsertRequest>],
operation_key: &str,
) -> Result<RoutedBatchApplied, EditError> {
let position = parts
.first()
.map_or(InsertPosition::After, |part| part.request.position);
let parts = parts
.iter()
.map(|part| {
Ok(RoutedBatchPart {
handle: part.handle,
authority: part.authority,
request: batch_insert_as_edits(&part.request)?,
working_directory: part.working_directory.clone(),
})
})
.collect::<Result<Vec<_>, EditErrorKind>>()
.map_err(EditError::Edit)?;
self.apply_routed_batch(
authority,
&parts,
operation_key,
BatchTool::Insert(position),
)
}
}
fn batch_insert_as_edits(request: &BatchInsertRequest) -> Result<BatchEditRequest, EditErrorKind> {
if request.targets.is_empty()
|| request.targets.len() > 100
|| request.content.len() > crate::domain::index::METADATA_ONLY_CODE_BYTES as usize
{
return Err(EditErrorKind::InvalidReplacement);
}
Ok(BatchEditRequest {
actions: request
.targets
.iter()
.map(|guard| {
BatchEditAction::Insert(InsertRequest {
guard: guard.clone(),
position: request.position,
content: request.content.clone(),
})
})
.collect(),
})
}
fn plan_rewrite(
snapshot: &EmbeddedQuerySnapshot,
request: &StructuralRewriteRequest,
) -> Result<RewritePlan, EditErrorKind> {
let language = super::guidance::filters::parse_language_filter(request.language.as_deref())
.map_err(|error| EditErrorKind::StructuralRewriteRefused {
message: refusal(error),
})?;
let refused = |message| EditErrorKind::StructuralRewriteRefused { message };
let live = &snapshot.generation.live;
super::guidance::read_context::structural_rewrite_refused_unverified(live, request, language)
.map_err(refused)?;
plan_structural_rewrite(live, request, language).map_err(refused)
}
fn rewrite_scope(
snapshot: &EmbeddedQuerySnapshot,
request: &StructuralRewriteRequest,
) -> Result<Vec<String>, EditErrorKind> {
let refused = |message| EditErrorKind::StructuralRewriteRefused { message };
let language = super::guidance::filters::parse_language_filter(request.language.as_deref())
.map_err(|error| refused(refusal(error)))?;
let live = &snapshot.generation.live;
super::guidance::read_context::structural_rewrite_refused_unverified(live, request, language)
.map_err(refused)?;
paths_in_scope(live, request, language).map_err(refused)
}
fn stage_rewrite(
snapshot: &EmbeddedQuerySnapshot,
plan: &RewritePlan,
) -> Result<Vec<StagedImage>, EditErrorKind> {
let mut staged = Vec::with_capacity(plan.files.len());
for planned in &plan.files {
let file = snapshot
.generation
.live
.get_file(&planned.path)
.ok_or(EditErrorKind::FileNotAdmitted)?;
if file.content != planned.original {
return Err(EditErrorKind::StaleContent);
}
if !admitted(snapshot, file) {
return Err(EditErrorKind::UnsafeContent);
}
let absolute = crate::discovery::resolve_repo_path(&snapshot.root, &planned.path)
.map_err(|_| EditErrorKind::InvalidPath)?
.ok_or(EditErrorKind::FileNotAdmitted)?;
let targets =
crate::domain::IndexTargets::for_path(&file.relative_path, Some(&file.language));
if !matches!(
classify_stable_content_for_root(
&snapshot.root,
&file.relative_path,
targets,
&planned.replacement,
),
StableContentAdmission::Admitted
) {
return Err(EditErrorKind::UnsafeContent);
}
staged.push(StagedImage {
relative: PathBuf::from(&planned.path),
absolute,
original: Some(file.content.clone()),
replacement: planned.replacement.clone(),
owner_only: false,
});
}
Ok(staged)
}
fn pending_rewrite(plan: &RewritePlan, dry_run: bool) -> PendingAnswer {
let files = plan
.files
.iter()
.zip(plan.summaries(dry_run))
.map(|(file, summary)| BatchFileParts {
path: file.path.clone(),
summaries: vec![summary],
tee: None,
reroute: String::new(),
})
.collect::<Vec<_>>();
PendingAnswer {
match_type: MatchType::Exact,
evidence: plan.evidence(),
body: BatchBody::Summaries {
file_count: files.len(),
files,
},
primary: plan
.files
.first()
.map(|file| file.path.clone())
.unwrap_or_default(),
}
}
impl EmbeddedSourceHandle {
pub fn preview_structural_rewrite(
&self,
request: &StructuralRewriteRequest,
) -> Result<BatchEditPreview, EditError> {
let snapshot = self.capture_query_snapshot(b"preview-structural-rewrite")?;
answer::enforce_trust(&snapshot)?;
let plan = plan_rewrite(&snapshot, request).map_err(EditError::Edit)?;
let staged = stage_rewrite(&snapshot, &plan).map_err(EditError::Edit)?;
let body = preview_answer(&snapshot, pending_rewrite(&plan, true));
let diff = render_safe_batch(staged.iter().map(|image| {
(
image.relative.to_str().expect("indexed UTF-8 path"),
image.original.as_deref().expect("indexed source"),
image.replacement.as_slice(),
)
}))
.map_err(|_| EditError::Edit(EditErrorKind::UnsafeContent))?;
Ok(BatchEditPreview {
files: staged
.iter()
.map(|image| BatchFilePreview {
path: image.relative.to_string_lossy().to_string(),
old_file_hash: digest_hex(image.original.as_deref().expect("indexed source")),
proposed_file_hash: digest_hex(&image.replacement),
})
.collect(),
action_count: plan.sites(),
publication_identity: snapshot.publication_identity,
source_version: snapshot.source_version,
rendered: diff.rendered,
truncated: diff.truncated,
redacted: diff.redacted,
body,
})
}
pub fn apply_structural_rewrite(
&self,
request: &StructuralRewriteRequest,
authority: &EditApplyAuthority,
operation_key: &str,
) -> Result<BatchEditApplied, EditError> {
let snapshot = self.capture_query_snapshot(b"apply-structural-rewrite")?;
answer::enforce_trust(&snapshot)?;
let replay_paths = rewrite_scope(&snapshot, request).map_err(EditError::Edit)?;
let fingerprint = RequestFingerprint::for_json(
"embed_structural_rewrite_v1",
&serde_json::json!({"scope": authority.scope, "rewrite": request}),
)
.map_err(|_| EditError::Edit(EditErrorKind::ReplayUnavailable))?;
self.apply_staged_batch(
snapshot,
authority,
operation_key,
fingerprint,
replay_paths,
StagedAnswer {
tool: "batch_edit",
tee: true,
scope_manifest: true,
stage: Box::new(move |snapshot| {
let plan = plan_rewrite(snapshot, request)?;
Ok((
stage_rewrite(snapshot, &plan)?,
pending_rewrite(&plan, false),
))
}),
},
)
}
}