Skip to main content

adk_harness/approvals/
changeset.rs

1//! Change sets: the held edits of one model turn reviewed as one diff and decided once
2//! (spec 3.1 §7.26, §9.2 I66).
3//!
4//! [`ChangeSet::compose`] applies `write_file`, `edit_file` and `apply_patch` calls in call
5//! order to an in-memory overlay of the workspace, read through the file tools' own rules,
6//! so successive edits of one file compose. Each composed call carries the `expect_sha256`
7//! its file had at that point of the composition — the batch's base for the first call on a
8//! file, the intermediate hash for the next — so the call writes only against the content
9//! the person reviewed.
10
11use 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
23/// Most bytes of a change set's rendered diff a prompt shows before `?` expands it.
24///
25/// # Example
26///
27/// ```rust
28/// assert_eq!(adk_harness::CHANGE_SET_MAX_BYTES, 16 * 1024);
29/// ```
30pub const CHANGE_SET_MAX_BYTES: usize = 16 * 1024;
31
32/// Lines of context around each change of a diff.
33const CONTEXT_LINES: usize = 3;
34/// Above this many cells the middle of a diff is shown as replaced rather than aligned.
35const DIFF_CELLS_MAX: usize = 4_000_000;
36
37/// One call of a [`ChangeSet`], in call order.
38#[derive(Clone, Debug, PartialEq)]
39#[non_exhaustive]
40pub struct ChangeSetCall {
41    /// The call's ID.
42    pub function_call_id: String,
43    /// `write_file`, `edit_file` or `apply_patch`.
44    pub tool: String,
45    /// The call's arguments.
46    pub args: Value,
47    /// The files it changes, as the workspace names them.
48    pub files: Vec<String>,
49    /// Why the call would fail; such a call is answered with this reason and never runs.
50    pub failure: Option<String>,
51    /// `expect_sha256` as the composition bound it: a digest or `absent`, or a map of them
52    /// for `apply_patch`.
53    expect: Option<Value>,
54}
55
56impl ChangeSetCall {
57    /// The arguments the call is approved with: its own, with `expect_sha256` set to the
58    /// content its files had at its place in the change set; `None` for a failing call.
59    ///
60    /// # Example
61    ///
62    /// ```rust
63    /// # async fn example(workspace: adk_devtools::Workspace) {
64    /// use adk_harness::ChangeSet;
65    /// use serde_json::json;
66    ///
67    /// let set = ChangeSet::compose(
68    ///     &workspace,
69    ///     vec![("c1".into(), "write_file".into(), json!({ "path": "new.md", "content": "x" }))],
70    /// )
71    /// .await;
72    /// assert_eq!(set.calls[0].approved_args().unwrap()["expect_sha256"], "absent");
73    /// # }
74    /// ```
75    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/// One file of a [`ChangeSet`]: its content before the batch and after every call of it.
88#[derive(Clone, Debug, PartialEq)]
89#[non_exhaustive]
90pub struct ChangeSetFile {
91    /// The file, relative to the workspace root.
92    pub path: String,
93    /// Its sha256 before the batch; `None` when it does not exist yet.
94    pub before_sha256: Option<String>,
95    /// Its sha256 after the batch; `None` when the batch deletes it.
96    pub after_sha256: Option<String>,
97    /// A unified diff from before to after.
98    pub diff: String,
99    /// The calls that change it, in call order.
100    pub call_ids: Vec<String>,
101}
102
103/// The held edits of one model turn, composed (spec 3.1 §7.26).
104#[derive(Clone, Debug, PartialEq)]
105#[non_exhaustive]
106pub struct ChangeSet {
107    /// `sha256:` over the sorted (path, before, after) triples of its files.
108    pub digest: String,
109    /// The files it changes, in the order the calls first touch them.
110    pub files: Vec<ChangeSetFile>,
111    /// Its calls, in call order.
112    pub calls: Vec<ChangeSetCall>,
113}
114
115/// A file as the composition sees it.
116struct 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/// The overlay: every file a call touched, by record key, in first-touch order.
127#[derive(Default)]
128struct Overlay {
129    entries: BTreeMap<String, Entry>,
130    order: Vec<String>,
131}
132
133impl Overlay {
134    /// The key of `path`, loading its content through the workspace on first touch.
135    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
162/// The text of `bytes`, or why a text edit cannot apply to it.
163fn 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
168/// The model's own `expect_sha256` for a file, checked against the composed content.
169fn 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    /// Composes `calls` — (call ID, tool, arguments) — in order over an overlay of
188    /// `workspace`, reading each file once through the file tools' containment, symlink
189    /// and exclusion rules (spec 3.1 §7.26).
190    ///
191    /// A call that would fail — no match, an escape, a hunk that does not apply — is kept
192    /// with its [`failure`](ChangeSetCall::failure) and changes nothing.
193    ///
194    /// # Example
195    ///
196    /// ```rust
197    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
198    /// use adk_harness::ChangeSet;
199    /// use serde_json::json;
200    ///
201    /// let dir = tempfile::tempdir().unwrap();
202    /// std::fs::write(dir.path().join("a.txt"), "one\n").unwrap();
203    /// let workspace = adk_devtools::Workspace::new(dir.path());
204    /// let set = ChangeSet::compose(&workspace, vec![
205    ///     ("c1".into(), "edit_file".into(), json!({ "path": "a.txt", "old_string": "one", "new_string": "two" })),
206    ///     ("c2".into(), "edit_file".into(), json!({ "path": "a.txt", "old_string": "two", "new_string": "three" })),
207    /// ]).await;
208    /// assert_eq!(set.files.len(), 1);
209    /// assert!(set.files[0].diff.contains("-one\n+three"));
210    /// // The second edit is bound to the content the first leaves.
211    /// let second = set.calls[1].approved_args().unwrap();
212    /// assert_eq!(second["expect_sha256"], adk_devtools::sha256_hex(b"two\n"));
213    /// # });
214    /// ```
215    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    /// The change set for a reader: per file its digests and diff, then the calls that fail.
276    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    /// The calls that change only files in `approved`, and do not fail.
301    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
311/// `sha256:1a2b3c4d5e6f…`
312fn short(digest: &str) -> String {
313    format!("sha256:{}…", &digest[..12.min(digest.len())])
314}
315
316/// Escapes control characters but keeps tabs, so code reads as code.
317fn display_safe(text: &str) -> String {
318    text.split('\t').map(crate::approvals::escape_control).collect::<Vec<_>>().join("\t")
319}
320
321/// Composes one `write_file` or `edit_file` call; returns its file and `expect_sha256`.
322async 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
348/// Composes one `apply_patch` call, all or nothing; returns its files and the per-file
349/// `expect_sha256` map.
350async 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
425/// A unified diff of a file's content before and after.
426fn 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
445/// A unified diff of `old` and `new` with `@@ -a,b +c,d @@` hunk headers and three lines
446/// of context.
447pub(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    // Align the changed middle; the common prefix and suffix are equal by construction.
451    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        // Longest common subsequence, filled from the end.
462        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    // Each op's line numbers (1-based) in old and new.
496    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/// A change set as a prompt shows it (spec 3.1 §7.26).
548#[derive(Clone, Debug)]
549#[non_exhaustive]
550pub struct ChangeSetPrompt {
551    /// The composed calls and files.
552    pub change_set: ChangeSet,
553    /// The session's mode.
554    pub mode: HarnessMode,
555    /// The acting agent.
556    pub agent: String,
557    /// Edits of the same turn a standing rule allows: they run without being in the card.
558    pub under_rules: usize,
559    /// Edits of the same turn asked about on their own after the card: protected paths
560    /// (I29), and edits of a file a call outside the card also changes.
561    pub asked_separately: usize,
562    /// The change set rendered for display.
563    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    /// One line naming the change set: its edits, files and digest.
597    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    /// The document an editor opens for "edit": the diff as comment lines, then the
609    /// calls' arguments as JSON; [`ChangeSetAnswer::from_edit_document`] reads it back.
610    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/// A change set rendered for a person; approval needs the whole diff shown (I21).
631#[derive(Clone, Debug)]
632pub struct RenderedChangeSet {
633    /// The diff, cut to [`CHANGE_SET_MAX_BYTES`].
634    pub body: String,
635    /// Whether [`body`](Self::body) was cut.
636    pub truncated: bool,
637    full: String,
638    expanded: Arc<AtomicBool>,
639}
640
641impl RenderedChangeSet {
642    /// The whole diff. Showing it lets a cut change set be approved.
643    pub fn expand(&self) -> &str {
644        self.expanded.store(true, Ordering::SeqCst);
645        &self.full
646    }
647
648    /// Whether an approval may stand: the whole diff was shown.
649    pub fn can_approve(&self) -> bool {
650        !self.truncated || self.expanded.load(Ordering::SeqCst)
651    }
652}
653
654/// A person's one answer to a [`ChangeSetPrompt`] (spec 3.1 §7.26).
655///
656/// # Example
657///
658/// ```rust
659/// use adk_harness::ChangeSetAnswer;
660///
661/// let answer = ChangeSetAnswer::ApproveFiles(vec!["src/lib.rs".into()]);
662/// assert!(matches!(answer, ChangeSetAnswer::ApproveFiles(_)));
663/// ```
664#[derive(Clone, Debug, PartialEq)]
665pub enum ChangeSetAnswer {
666    /// Run every call that does not fail.
667    ApproveAll,
668    /// Run the calls that change only these files; deny the others.
669    ApproveFiles(Vec<String>),
670    /// Run none; the message is reported to the model.
671    DenyAll {
672        /// Reported to the model.
673        message: Option<String>,
674    },
675    /// Replace calls' arguments, by call ID, and show the change set again; the policy
676    /// checks the edited calls again.
677    Edit(Vec<(String, Value)>),
678}
679
680impl ChangeSetAnswer {
681    /// Reads an edited [`ChangeSetPrompt::edit_document`] back as [`Edit`](Self::Edit).
682    ///
683    /// # Errors
684    ///
685    /// Returns why the document is not a JSON array of `{ "call", "args" }` objects.
686    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}