1use std::collections::{HashMap, HashSet};
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use adk_core::{Result, Tool, ToolContext, ToolEffect};
9use async_trait::async_trait;
10use serde_json::{Value, json};
11
12use crate::error::DevToolError;
13use crate::patch::{PatchOp, apply_hunks, parse_patch};
14use crate::read_ledger::sha256_hex;
15use crate::tools::read::require_str;
16use crate::workspace::{Precondition, Workspace};
17
18pub struct ApplyPatchTool {
45 workspace: Workspace,
46}
47
48impl ApplyPatchTool {
49 pub fn new(workspace: Workspace) -> Self {
51 Self { workspace }
52 }
53}
54
55struct Planned {
57 op: &'static str,
58 path: PathBuf,
60 target: PathBuf,
61 from: Option<(PathBuf, PathBuf)>,
63 before: Option<Vec<u8>>,
64 after: Option<Vec<u8>>,
65}
66
67struct Undo {
70 target: PathBuf,
71 original: Option<Vec<u8>>,
72 now: Option<Vec<u8>>,
73}
74
75impl ApplyPatchTool {
76 async fn check_existing(
80 &self,
81 ctx: &dyn ToolContext,
82 expects: &HashMap<String, Precondition>,
83 resolved: &std::path::Path,
84 current: &[u8],
85 ) -> std::result::Result<(), DevToolError> {
86 let key = self.workspace.record_path(resolved);
87 let expected = match expects.get(&key) {
88 Some(expected) => expected.clone(),
89 None => match self.workspace.read_digest(ctx, resolved).await? {
90 Some(digest) => Precondition::Sha256(digest),
91 None => Precondition::Sha256(sha256_hex(current)),
92 },
93 };
94 expected.check(Some(current)).map_err(|error| DevToolError::Stale {
95 path: self.workspace.record_path(resolved),
96 detail: error.get_ref().map(ToString::to_string).unwrap_or_else(|| error.to_string()),
97 })
98 }
99
100 async fn plan(
102 &self,
103 ctx: &dyn ToolContext,
104 patch: &crate::patch::Patch,
105 expects: &HashMap<String, Precondition>,
106 ) -> Result<Vec<Planned>> {
107 let mut seen = HashSet::new();
108 for path in patch.paths() {
109 let (resolved, _) = self.workspace.resolve_target(path)?;
110 if !seen.insert(self.workspace.record_path(&resolved)) {
111 return Err(DevToolError::Other(format!(
112 "'{path}' appears twice in the patch; put every change to a file in one \
113 'Update File' section"
114 ))
115 .into());
116 }
117 }
118 let absent = |resolved: &std::path::Path| -> std::result::Result<(), DevToolError> {
119 let key = self.workspace.record_path(resolved);
120 match expects.get(&key) {
121 Some(Precondition::Sha256(_)) => Err(DevToolError::Stale {
122 path: self.workspace.record_path(resolved),
123 detail: "the call expected a file there, and there is none".to_string(),
124 }),
125 _ => Ok(()),
126 }
127 };
128 let mut planned = Vec::new();
129 for op in &patch.ops {
130 match op {
131 PatchOp::Add { path, contents } => {
132 let (resolved, target) = self.workspace.resolve_target(path)?;
133 if self.exists(&target).await? {
134 return Err(DevToolError::Other(format!(
135 "'{path}' already exists; change it with '*** Update File: {path}'"
136 ))
137 .into());
138 }
139 absent(&resolved)?;
140 planned.push(Planned {
141 op: "add",
142 path: resolved,
143 target,
144 from: None,
145 before: None,
146 after: Some(contents.clone().into_bytes()),
147 });
148 }
149 PatchOp::Delete { path } => {
150 let (resolved, target) = self.workspace.resolve_target(path)?;
151 let current = self.workspace.read_contained_bytes(&target).await?;
152 self.check_existing(ctx, expects, &resolved, ¤t).await?;
153 planned.push(Planned {
154 op: "delete",
155 path: resolved,
156 target,
157 from: None,
158 before: Some(current),
159 after: None,
160 });
161 }
162 PatchOp::Update { path, move_to, hunks } => {
163 let (resolved, target) = self.workspace.resolve_target(path)?;
164 if self.workspace.is_excluded(&resolved) || self.workspace.is_excluded(&target)
166 {
167 return Err(
168 DevToolError::Excluded(self.workspace.record_path(&resolved)).into()
169 );
170 }
171 let current = self.workspace.read_contained(&target).await?;
172 self.check_existing(ctx, expects, &resolved, current.as_bytes()).await?;
173 let display = self.workspace.record_path(&resolved);
174 let updated = if hunks.is_empty() {
175 current.clone()
176 } else {
177 apply_hunks(&display, ¤t, hunks)
178 .map_err(|error| DevToolError::Other(error.0))?
179 };
180 let (op, path, target, from) = match move_to {
181 Some(to) => {
182 let (to_resolved, to_target) = self.workspace.resolve_target(to)?;
183 if self.exists(&to_target).await? {
184 return Err(DevToolError::Other(format!(
185 "'{to}' already exists; a move does not replace a file"
186 ))
187 .into());
188 }
189 absent(&to_resolved)?;
190 ("move", to_resolved, to_target, Some((resolved, target)))
191 }
192 None => ("update", resolved, target, None),
193 };
194 planned.push(Planned {
195 op,
196 path,
197 target,
198 from,
199 before: Some(current.into_bytes()),
200 after: Some(updated.into_bytes()),
201 });
202 }
203 }
204 }
205 Ok(planned)
206 }
207
208 async fn exists(&self, target: &std::path::Path) -> std::result::Result<bool, DevToolError> {
209 match tokio::fs::symlink_metadata(target).await {
210 Ok(_) => Ok(true),
211 Err(error)
213 if matches!(
214 error.kind(),
215 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
216 ) =>
217 {
218 Ok(false)
219 }
220 Err(error) => Err(error.into()),
221 }
222 }
223
224 async fn write(
226 &self,
227 file: &Planned,
228 undo: &mut Vec<Undo>,
229 ) -> std::result::Result<(), DevToolError> {
230 let ws = &self.workspace;
231 match (&file.from, &file.before, &file.after) {
232 (None, None, Some(after)) => {
233 ws.replace_contained(&file.target, after, Precondition::Absent).await?;
234 undo.push(Undo {
235 target: file.target.clone(),
236 original: None,
237 now: Some(after.clone()),
238 });
239 }
240 (None, Some(before), None) => {
241 ws.remove_contained(&file.target, Precondition::Sha256(sha256_hex(before))).await?;
242 undo.push(Undo {
243 target: file.target.clone(),
244 original: Some(before.clone()),
245 now: None,
246 });
247 }
248 (None, Some(before), Some(after)) => {
249 ws.replace_contained(&file.target, after, Precondition::Sha256(sha256_hex(before)))
250 .await?;
251 undo.push(Undo {
252 target: file.target.clone(),
253 original: Some(before.clone()),
254 now: Some(after.clone()),
255 });
256 }
257 (Some((_, source)), Some(before), Some(after)) => {
258 ws.replace_contained(&file.target, after, Precondition::Absent).await?;
259 undo.push(Undo {
260 target: file.target.clone(),
261 original: None,
262 now: Some(after.clone()),
263 });
264 ws.remove_contained(source, Precondition::Sha256(sha256_hex(before))).await?;
265 undo.push(Undo {
266 target: source.clone(),
267 original: Some(before.clone()),
268 now: None,
269 });
270 }
271 _ => {
272 return Err(DevToolError::Other("the patch planned an impossible step".into()));
273 }
274 }
275 Ok(())
276 }
277
278 async fn restore(&self, undo: Vec<Undo>) -> Vec<String> {
280 let mut failed = Vec::new();
281 for step in undo.into_iter().rev() {
282 let Undo { target, original, now } = step;
283 let now = match &now {
284 Some(bytes) => Precondition::Sha256(sha256_hex(bytes)),
285 None => Precondition::Absent,
286 };
287 let restored = match &original {
288 Some(bytes) => self.workspace.replace_contained(&target, bytes, now).await,
289 None => self.workspace.remove_contained(&target, now).await,
290 };
291 if let Err(error) = restored {
292 let path = self.workspace.record_path(&target);
293 tracing::warn!(file.path = %path, error = %error, "apply_patch could not restore a file");
294 failed.push(path);
295 }
296 }
297 failed
298 }
299}
300
301#[async_trait]
302impl Tool for ApplyPatchTool {
303 fn name(&self) -> &str {
304 "apply_patch"
305 }
306
307 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
309 adk_core::egress::ToolEgress::None
310 }
311
312 fn description(&self) -> &str {
313 "Apply a patch that adds, deletes, updates or moves several files at once, all or \
314 nothing. The patch starts with '*** Begin Patch' and ends with '*** End Patch'; each \
315 file is a section: '*** Add File: <path>' followed by lines starting with '+'; \
316 '*** Delete File: <path>'; or '*** Update File: <path>', optionally '*** Move to: \
317 <path>', then hunks. A hunk starts with '@@' (optionally followed by a line of the \
318 file, such as a function signature, that precedes the change) and lists context lines \
319 starting with ' ', removed lines starting with '-' and added lines starting with '+'. \
320 Use no line numbers; give about three lines of context so each hunk matches exactly \
321 one place."
322 }
323
324 fn effect(&self) -> ToolEffect {
325 ToolEffect::NonIdempotent
326 }
327
328 fn parameters_schema(&self) -> Option<Value> {
329 Some(json!({
330 "type": "object",
331 "properties": {
332 "patch": { "type": "string", "description": "The patch text, from '*** Begin Patch' to '*** End Patch'." },
333 "expect_sha256": {
334 "type": "object",
335 "description": "Optional: per path, the sha256 the file must have, or \"absent\" for a file that must not exist yet.",
336 "additionalProperties": { "type": "string" }
337 }
338 },
339 "required": ["patch"]
340 }))
341 }
342
343 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
344 if !self.workspace.is_writable() {
345 return Err(DevToolError::ReadOnly("apply_patch").into());
346 }
347 let text = require_str(&args, "patch")?;
348 let patch = parse_patch(&text).map_err(|error| DevToolError::Other(error.0))?;
349 let mut expects = HashMap::new();
350 if let Some(map) = args.get("expect_sha256").filter(|value| !value.is_null()) {
351 let Some(map) = map.as_object() else {
352 return Err(DevToolError::Other(
353 "expect_sha256 maps each path to a sha256 or \"absent\"".into(),
354 )
355 .into());
356 };
357 for (path, expect) in map {
358 let Some(expect) = expect.as_str() else {
359 return Err(DevToolError::Other(format!(
360 "expect_sha256['{path}'] must be a string"
361 ))
362 .into());
363 };
364 let (resolved, _) = self.workspace.resolve_target(path)?;
365 expects.insert(
366 self.workspace.record_path(&resolved),
367 Precondition::from_expect(expect)?,
368 );
369 }
370 }
371
372 let planned = self.plan(ctx.as_ref(), &patch, &expects).await?;
373 let mut undo = Vec::new();
374 for file in &planned {
375 if let Err(error) = self.write(file, &mut undo).await {
376 let failed = self.restore(undo).await;
377 if failed.is_empty() {
378 return Err(error.into());
379 }
380 return Err(DevToolError::Other(format!(
381 "{error}; the patch was not applied, and these files could not be restored \
382 to their content before it: {}",
383 failed.join(", ")
384 ))
385 .into());
386 }
387 }
388
389 let mut files = Vec::new();
390 for file in &planned {
391 let before = file.before.as_deref().map(sha256_hex);
392 let after = file.after.as_deref().map(sha256_hex);
393 match &after {
394 Some(digest) => {
395 self.workspace.record_digest(ctx.as_ref(), &file.path, digest).await
396 }
397 None => self.workspace.forget_read(ctx.as_ref(), &file.path).await,
398 }
399 let mut entry = json!({
401 "path": self.workspace.record_path(&file.path),
402 "op": file.op,
403 "beforeSha256": before,
404 "afterSha256": after,
405 });
406 if let Some((from, _)) = &file.from {
407 self.workspace.forget_read(ctx.as_ref(), from).await;
408 entry["from"] = json!(self.workspace.record_path(from));
409 }
410 files.push(entry);
411 }
412 let summary = files
413 .iter()
414 .map(|file| {
415 format!(
416 "{} {}",
417 file["op"].as_str().unwrap_or(""),
418 file["path"].as_str().unwrap_or("")
419 )
420 })
421 .collect::<Vec<_>>()
422 .join(", ");
423 Ok(json!({
424 "files": files,
425 "message": format!("Applied the patch: {summary}"),
426 }))
427 }
428}