1use std::collections::{BTreeMap, HashSet};
12use std::fmt::Write as _;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, Ordering};
15
16use adk_devtools::Workspace;
17use adk_devtools::patch::{PatchOp, apply_hunks, parse_patch};
18use adk_devtools::sha256_hex;
19use serde_json::{Map, Value, json};
20
21use crate::mode::HarnessMode;
22
23pub const CHANGE_SET_MAX_BYTES: usize = 16 * 1024;
31
32const CONTEXT_LINES: usize = 3;
34const DIFF_CELLS_MAX: usize = 4_000_000;
36
37#[derive(Clone, Debug, PartialEq)]
39#[non_exhaustive]
40pub struct ChangeSetCall {
41 pub function_call_id: String,
43 pub tool: String,
45 pub args: Value,
47 pub files: Vec<String>,
49 pub failure: Option<String>,
51 expect: Option<Value>,
54}
55
56impl ChangeSetCall {
57 pub fn approved_args(&self) -> Option<Value> {
76 if self.failure.is_some() {
77 return None;
78 }
79 let mut args = self.args.clone();
80 if let (Some(object), Some(expect)) = (args.as_object_mut(), &self.expect) {
81 object.insert("expect_sha256".to_string(), expect.clone());
82 }
83 Some(args)
84 }
85}
86
87#[derive(Clone, Debug, PartialEq)]
89#[non_exhaustive]
90pub struct ChangeSetFile {
91 pub path: String,
93 pub before_sha256: Option<String>,
95 pub after_sha256: Option<String>,
97 pub diff: String,
99 pub call_ids: Vec<String>,
101}
102
103#[derive(Clone, Debug, PartialEq)]
105#[non_exhaustive]
106pub struct ChangeSet {
107 pub digest: String,
109 pub files: Vec<ChangeSetFile>,
111 pub calls: Vec<ChangeSetCall>,
113}
114
115struct Entry {
117 display: String,
118 base: Option<Vec<u8>>,
119 current: Option<Vec<u8>>,
120}
121
122fn digest_or_absent(bytes: Option<&[u8]>) -> String {
123 bytes.map_or_else(|| "absent".to_string(), sha256_hex)
124}
125
126#[derive(Default)]
128struct Overlay {
129 entries: BTreeMap<String, Entry>,
130 order: Vec<String>,
131}
132
133impl Overlay {
134 async fn load(&mut self, workspace: &Workspace, path: &str) -> Result<String, String> {
136 let key = workspace.record_key(path).map_err(|error| error.to_string())?;
137 if !self.entries.contains_key(&key) {
138 let content =
139 workspace.read_for_review(path).await.map_err(|error| error.to_string())?;
140 self.entries.insert(
141 key.clone(),
142 Entry { display: key.clone(), base: content.clone(), current: content },
143 );
144 }
145 Ok(key)
146 }
147
148 fn current(&self, key: &str) -> Option<&Vec<u8>> {
149 self.entries.get(key).and_then(|entry| entry.current.as_ref())
150 }
151
152 fn set(&mut self, key: &str, content: Option<Vec<u8>>) {
153 if let Some(entry) = self.entries.get_mut(key) {
154 entry.current = content;
155 }
156 if !self.order.iter().any(|seen| seen == key) {
157 self.order.push(key.to_string());
158 }
159 }
160}
161
162fn text_of<'a>(bytes: Option<&'a Vec<u8>>, path: &str) -> Result<&'a str, String> {
164 let bytes = bytes.ok_or_else(|| format!("'{path}' does not exist"))?;
165 std::str::from_utf8(bytes).map_err(|_| format!("'{path}' is not UTF-8 text"))
166}
167
168fn check_model_expect(
170 expect: Option<&Value>,
171 current: Option<&[u8]>,
172 path: &str,
173) -> Result<(), String> {
174 let Some(expect) = expect.and_then(Value::as_str) else {
175 return Ok(());
176 };
177 let found = digest_or_absent(current);
178 let wanted = expect.trim().trim_start_matches("sha256:").to_ascii_lowercase();
179 if wanted == found {
180 Ok(())
181 } else {
182 Err(format!("'{path}' does not have the sha256 the call expects; read it again"))
183 }
184}
185
186impl ChangeSet {
187 pub async fn compose(workspace: &Workspace, calls: Vec<(String, String, Value)>) -> ChangeSet {
216 let mut overlay = Overlay::default();
217 let mut composed = Vec::with_capacity(calls.len());
218 for (function_call_id, tool, args) in calls {
219 let mut call = ChangeSetCall {
220 function_call_id,
221 tool: tool.clone(),
222 args: args.clone(),
223 files: Vec::new(),
224 failure: None,
225 expect: None,
226 };
227 let outcome = match tool.as_str() {
228 "write_file" | "edit_file" => {
229 compose_file_call(workspace, &mut overlay, &tool, &args).await
230 }
231 crate::edits::APPLY_PATCH => compose_patch(workspace, &mut overlay, &args).await,
232 other => Err(format!("{other} is not an edit a change set can show")),
233 };
234 match outcome {
235 Ok((files, expect)) => {
236 call.files = files;
237 call.expect = Some(expect);
238 }
239 Err(failure) => call.failure = Some(failure),
240 }
241 composed.push(call);
242 }
243 let mut files = Vec::new();
244 for key in &overlay.order {
245 let Some(entry) = overlay.entries.get(key) else { continue };
246 let call_ids = composed
247 .iter()
248 .filter(|call| call.failure.is_none() && call.files.contains(&entry.display))
249 .map(|call| call.function_call_id.clone())
250 .collect();
251 files.push(ChangeSetFile {
252 path: entry.display.clone(),
253 before_sha256: entry.base.as_deref().map(sha256_hex),
254 after_sha256: entry.current.as_deref().map(sha256_hex),
255 diff: file_diff(entry.base.as_deref(), entry.current.as_deref()),
256 call_ids,
257 });
258 }
259 let mut triples: Vec<String> = files
260 .iter()
261 .map(|file| {
262 format!(
263 "{}\u{1f}{}\u{1f}{}\n",
264 file.path,
265 file.before_sha256.as_deref().unwrap_or("absent"),
266 file.after_sha256.as_deref().unwrap_or("absent")
267 )
268 })
269 .collect();
270 triples.sort();
271 let digest = format!("sha256:{}", sha256_hex(triples.concat().as_bytes()));
272 ChangeSet { digest, files, calls: composed }
273 }
274
275 pub fn render(&self) -> String {
277 let mut out = String::new();
278 for file in &self.files {
279 let before = file.before_sha256.as_deref().map_or("new file".to_string(), short);
280 let after = file.after_sha256.as_deref().map_or("deleted".to_string(), short);
281 let _ = writeln!(out, "{} {before} → {after}", display_safe(&file.path));
282 for line in file.diff.lines() {
283 let _ = writeln!(out, " {}", display_safe(line));
284 }
285 }
286 for call in &self.calls {
287 if let Some(failure) = &call.failure {
288 let _ = writeln!(
289 out,
290 "{} {} fails and will not run: {}",
291 display_safe(&call.tool),
292 display_safe(&call.function_call_id),
293 display_safe(failure)
294 );
295 }
296 }
297 out
298 }
299
300 pub(crate) fn calls_within<'a>(
302 &'a self,
303 approved: &'a HashSet<String>,
304 ) -> impl Iterator<Item = &'a ChangeSetCall> {
305 self.calls.iter().filter(move |call| {
306 call.failure.is_none() && call.files.iter().all(|file| approved.contains(file))
307 })
308 }
309}
310
311fn short(digest: &str) -> String {
313 format!("sha256:{}…", &digest[..12.min(digest.len())])
314}
315
316fn display_safe(text: &str) -> String {
318 text.split('\t').map(crate::approvals::escape_control).collect::<Vec<_>>().join("\t")
319}
320
321async fn compose_file_call(
323 workspace: &Workspace,
324 overlay: &mut Overlay,
325 tool: &str,
326 args: &Value,
327) -> Result<(Vec<String>, Value), String> {
328 let path = args.get("path").and_then(Value::as_str).ok_or("the call names no path")?;
329 let key = overlay.load(workspace, path).await?;
330 let before = overlay.current(&key).cloned();
331 check_model_expect(args.get("expect_sha256"), before.as_deref(), &key)?;
332 let after = if tool == "write_file" {
333 args.get("content")
334 .and_then(Value::as_str)
335 .ok_or("write_file needs content")?
336 .as_bytes()
337 .to_vec()
338 } else {
339 let text = text_of(before.as_ref(), &key)?;
340 adk_devtools::tools::edit::preview(text, args, &key)
341 .map_err(|error| error.message.to_string())?
342 .into_bytes()
343 };
344 overlay.set(&key, Some(after));
345 Ok((vec![key], Value::String(digest_or_absent(before.as_deref()))))
346}
347
348async fn compose_patch(
351 workspace: &Workspace,
352 overlay: &mut Overlay,
353 args: &Value,
354) -> Result<(Vec<String>, Value), String> {
355 let text = args.get("patch").and_then(Value::as_str).ok_or("the call carries no patch")?;
356 let patch = parse_patch(text).map_err(|error| error.0)?;
357 let mut keys = Vec::new();
358 for path in patch.paths() {
359 let key = overlay.load(workspace, path).await?;
360 if keys.contains(&key) {
361 return Err(format!("'{path}' appears twice in the patch"));
362 }
363 keys.push(key);
364 }
365 let model_expects = args.get("expect_sha256").and_then(Value::as_object);
366 let mut expects = Map::new();
367 let mut changes: Vec<(String, Option<Vec<u8>>)> = Vec::new();
368 let mut keys = keys.into_iter();
369 for op in &patch.ops {
370 let key = keys.next().unwrap_or_default();
371 let current = overlay.current(&key).cloned();
372 let model_expect = model_expects.and_then(|map| {
373 map.iter()
374 .find(|(path, _)| workspace.record_key(path).is_ok_and(|named| named == key))
375 .map(|(_, value)| value)
376 });
377 check_model_expect(model_expect, current.as_deref(), &key)?;
378 expects.insert(key.clone(), Value::String(digest_or_absent(current.as_deref())));
379 match op {
380 PatchOp::Add { contents, .. } => {
381 if current.is_some() {
382 return Err(format!("'{key}' already exists; a patch adds only new files"));
383 }
384 changes.push((key, Some(contents.clone().into_bytes())));
385 }
386 PatchOp::Delete { .. } => {
387 if current.is_none() {
388 return Err(format!("'{key}' does not exist"));
389 }
390 changes.push((key, None));
391 }
392 PatchOp::Update { move_to, hunks, .. } => {
393 let text = text_of(current.as_ref(), &key)?;
394 let updated = if hunks.is_empty() {
395 text.to_string()
396 } else {
397 apply_hunks(&key, text, hunks).map_err(|error| error.0)?
398 };
399 match move_to {
400 Some(_) => {
401 let to = keys.next().unwrap_or_default();
402 let existing = overlay.current(&to).cloned();
403 if existing.is_some() {
404 return Err(format!(
405 "'{to}' already exists; a move does not replace a file"
406 ));
407 }
408 expects.insert(to.clone(), Value::String("absent".into()));
409 changes.push((key, None));
410 changes.push((to, Some(updated.into_bytes())));
411 }
412 None => changes.push((key, Some(updated.into_bytes()))),
413 }
414 }
415 _ => return Err("the patch holds an operation this harness cannot show".to_string()),
416 }
417 }
418 let files = changes.iter().map(|(key, _)| key.clone()).collect();
419 for (key, content) in changes {
420 overlay.set(&key, content);
421 }
422 Ok((files, Value::Object(expects)))
423}
424
425fn file_diff(before: Option<&[u8]>, after: Option<&[u8]>) -> String {
427 match (before.map(std::str::from_utf8).transpose(), after.map(std::str::from_utf8).transpose())
428 {
429 (Ok(before), Ok(after)) => unified_diff(before.unwrap_or(""), after.unwrap_or("")),
430 _ => format!(
431 "binary content: {} → {} bytes\n",
432 before.map_or(0, <[u8]>::len),
433 after.map_or(0, <[u8]>::len)
434 ),
435 }
436}
437
438#[derive(Clone, Copy, PartialEq)]
439enum Op {
440 Equal,
441 Delete,
442 Insert,
443}
444
445pub(crate) fn unified_diff(old: &str, new: &str) -> String {
448 let old: Vec<&str> = old.lines().collect();
449 let new: Vec<&str> = new.lines().collect();
450 let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
452 let suffix = old[prefix..]
453 .iter()
454 .rev()
455 .zip(new[prefix..].iter().rev())
456 .take_while(|(a, b)| a == b)
457 .count();
458 let (a, b) = (&old[prefix..old.len() - suffix], &new[prefix..new.len() - suffix]);
459 let mut ops = vec![Op::Equal; prefix];
460 if a.len().saturating_mul(b.len()) <= DIFF_CELLS_MAX {
461 let width = b.len() + 1;
463 let mut table = vec![0u32; (a.len() + 1) * width];
464 for i in (0..a.len()).rev() {
465 for j in (0..b.len()).rev() {
466 table[i * width + j] = if a[i] == b[j] {
467 table[(i + 1) * width + j + 1] + 1
468 } else {
469 table[(i + 1) * width + j].max(table[i * width + j + 1])
470 };
471 }
472 }
473 let (mut i, mut j) = (0, 0);
474 while i < a.len() || j < b.len() {
475 if i < a.len() && j < b.len() && a[i] == b[j] {
476 ops.push(Op::Equal);
477 i += 1;
478 j += 1;
479 } else if j < b.len()
480 && (i == a.len() || table[i * width + j + 1] > table[(i + 1) * width + j])
481 {
482 ops.push(Op::Insert);
483 j += 1;
484 } else {
485 ops.push(Op::Delete);
486 i += 1;
487 }
488 }
489 } else {
490 ops.extend(std::iter::repeat_n(Op::Delete, a.len()));
491 ops.extend(std::iter::repeat_n(Op::Insert, b.len()));
492 }
493 ops.extend(std::iter::repeat_n(Op::Equal, suffix));
494
495 let mut positions = Vec::with_capacity(ops.len());
497 let (mut o, mut n) = (0usize, 0usize);
498 for op in &ops {
499 positions.push((o, n));
500 match op {
501 Op::Equal => {
502 o += 1;
503 n += 1;
504 }
505 Op::Delete => o += 1,
506 Op::Insert => n += 1,
507 }
508 }
509 let changed: Vec<usize> = (0..ops.len()).filter(|&index| ops[index] != Op::Equal).collect();
510 let mut out = String::new();
511 let mut index = 0;
512 while index < changed.len() {
513 let start = changed[index].saturating_sub(CONTEXT_LINES);
514 let mut end = changed[index];
515 while index < changed.len() && changed[index] <= end + 2 * CONTEXT_LINES {
516 end = changed[index];
517 index += 1;
518 }
519 let end = (end + CONTEXT_LINES + 1).min(ops.len());
520 let (old_start, new_start) = positions[start];
521 let old_count = ops[start..end].iter().filter(|op| **op != Op::Insert).count();
522 let new_count = ops[start..end].iter().filter(|op| **op != Op::Delete).count();
523 let _ = writeln!(
524 out,
525 "@@ -{},{old_count} +{},{new_count} @@",
526 if old_count == 0 { old_start } else { old_start + 1 },
527 if new_count == 0 { new_start } else { new_start + 1 },
528 );
529 for at in start..end {
530 let (o, n) = positions[at];
531 match ops[at] {
532 Op::Equal => {
533 let _ = writeln!(out, " {}", old[o]);
534 }
535 Op::Delete => {
536 let _ = writeln!(out, "-{}", old[o]);
537 }
538 Op::Insert => {
539 let _ = writeln!(out, "+{}", new[n]);
540 }
541 }
542 }
543 }
544 out
545}
546
547#[derive(Clone, Debug)]
549#[non_exhaustive]
550pub struct ChangeSetPrompt {
551 pub change_set: ChangeSet,
553 pub mode: HarnessMode,
555 pub agent: String,
557 pub under_rules: usize,
559 pub asked_separately: usize,
562 pub rendered: RenderedChangeSet,
564}
565
566impl ChangeSetPrompt {
567 pub(crate) fn new(
568 change_set: ChangeSet,
569 mode: HarnessMode,
570 agent: String,
571 under_rules: usize,
572 asked_separately: usize,
573 ) -> Self {
574 let full = change_set.render();
575 let (body, truncated) = if full.len() > CHANGE_SET_MAX_BYTES {
576 let end = full.floor_char_boundary(CHANGE_SET_MAX_BYTES);
577 (format!("{}… [cut: {end} of {} bytes shown]\n", &full[..end], full.len()), true)
578 } else {
579 (full.clone(), false)
580 };
581 Self {
582 change_set,
583 mode,
584 agent,
585 under_rules,
586 asked_separately,
587 rendered: RenderedChangeSet {
588 body,
589 truncated,
590 full,
591 expanded: Arc::new(AtomicBool::new(false)),
592 },
593 }
594 }
595
596 pub fn title(&self) -> String {
598 let edits = self.change_set.calls.len();
599 let files = self.change_set.files.len();
600 format!(
601 "change set: {edits} edit{} to {files} file{} · {}",
602 if edits == 1 { "" } else { "s" },
603 if files == 1 { "" } else { "s" },
604 short(self.change_set.digest.trim_start_matches("sha256:"))
605 )
606 }
607
608 pub fn edit_document(&self) -> String {
611 let mut out = format!(
612 "# {}\n# Edit the calls' arguments below; lines starting with # are ignored.\n",
613 self.title()
614 );
615 for line in self.rendered.full.lines() {
616 let _ = writeln!(out, "# {line}");
617 }
618 let calls: Vec<Value> = self
619 .change_set
620 .calls
621 .iter()
622 .map(|call| json!({ "call": call.function_call_id, "tool": call.tool, "args": call.args }))
623 .collect();
624 out.push_str(&serde_json::to_string_pretty(&calls).unwrap_or_default());
625 out.push('\n');
626 out
627 }
628}
629
630#[derive(Clone, Debug)]
632pub struct RenderedChangeSet {
633 pub body: String,
635 pub truncated: bool,
637 full: String,
638 expanded: Arc<AtomicBool>,
639}
640
641impl RenderedChangeSet {
642 pub fn expand(&self) -> &str {
644 self.expanded.store(true, Ordering::SeqCst);
645 &self.full
646 }
647
648 pub fn can_approve(&self) -> bool {
650 !self.truncated || self.expanded.load(Ordering::SeqCst)
651 }
652}
653
654#[derive(Clone, Debug, PartialEq)]
665pub enum ChangeSetAnswer {
666 ApproveAll,
668 ApproveFiles(Vec<String>),
670 DenyAll {
672 message: Option<String>,
674 },
675 Edit(Vec<(String, Value)>),
678}
679
680impl ChangeSetAnswer {
681 pub fn from_edit_document(text: &str) -> Result<Self, String> {
687 let json: String = text
688 .lines()
689 .filter(|line| !line.trim_start().starts_with('#'))
690 .collect::<Vec<_>>()
691 .join("\n");
692 let calls: Vec<Value> = serde_json::from_str(&json)
693 .map_err(|error| format!("not a JSON array of calls: {error}"))?;
694 calls
695 .into_iter()
696 .map(|call| {
697 let id =
698 call.get("call").and_then(Value::as_str).ok_or("each call needs \"call\"")?;
699 let args = call.get("args").cloned().ok_or("each call needs \"args\"")?;
700 Ok((id.to_string(), args))
701 })
702 .collect::<Result<_, &str>>()
703 .map(Self::Edit)
704 .map_err(str::to_string)
705 }
706}
707
708#[cfg(test)]
709mod tests {
710 use super::*;
711
712 #[test]
713 fn a_diff_shows_each_change_with_context_and_line_numbers() {
714 let old = (1..=20).map(|n| format!("line {n}\n")).collect::<String>();
715 let new = old.replace("line 3\n", "line three\n").replace("line 18\n", "");
716 let diff = unified_diff(&old, &new);
717 assert!(
718 diff.starts_with("@@ -1,6 +1,6 @@\n line 1\n line 2\n-line 3\n+line three\n"),
719 "{diff}"
720 );
721 assert!(
722 diff.contains("@@ -15,6 +15,5 @@\n line 15\n line 16\n line 17\n-line 18\n"),
723 "{diff}"
724 );
725 assert_eq!(unified_diff("same\n", "same\n"), "");
726 assert_eq!(unified_diff("", "a\nb\n"), "@@ -0,0 +1,2 @@\n+a\n+b\n");
727 assert_eq!(unified_diff("a\n", ""), "@@ -1,1 +0,0 @@\n-a\n");
728 }
729
730 #[test]
731 fn an_edit_document_round_trips() {
732 let text = "# change set\n# @@ -1 +1 @@\n[\n {\"call\": \"c1\", \"tool\": \"edit_file\", \"args\": {\"path\": \"a\"}}\n]\n";
733 assert_eq!(
734 ChangeSetAnswer::from_edit_document(text).unwrap(),
735 ChangeSetAnswer::Edit(vec![("c1".into(), json!({ "path": "a" }))])
736 );
737 assert!(ChangeSetAnswer::from_edit_document("# only comments").is_err());
738 }
739}