Skip to main content

adk_harness/snapshot/
plan.rs

1//! What a rewind will do, and what it did (spec 3.1 §7.27): the difference between a
2//! snapshot and the current tree, with conflicts, protected paths, files not covered,
3//! effects not undone, the transcript fork and the plan.
4
5use std::fmt::Write as _;
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::store::{FileEntry, SnapshotKind};
11use super::walk::{NotCovered, SkipReason};
12
13// The rewind half of the plan — the file diff, the transcript cut and the writes the
14// transcript records — runs only with `runner`, which has the sessions it reads.
15#[cfg(feature = "runner")]
16use std::collections::{BTreeMap, BTreeSet, HashMap};
17#[cfg(feature = "runner")]
18use std::path::{Component, Path};
19
20#[cfg(feature = "runner")]
21use adk_core::{Event, Part};
22#[cfg(feature = "runner")]
23use serde_json::Value;
24
25#[cfg(feature = "runner")]
26use super::runtime::TreeScan;
27#[cfg(feature = "runner")]
28use super::store::SnapshotRecord;
29
30/// Most paths a rendered plan or report lists per section.
31const RENDER_PATHS: usize = 12;
32
33/// Where to rewind to (spec 3.1 §7.27).
34///
35/// # Example
36///
37/// ```rust
38/// use adk_harness::snapshot::RewindTarget;
39///
40/// assert_eq!(RewindTarget::Turn(2).to_string(), "before turn 2");
41/// assert_eq!(RewindTarget::PlanStep("3".into()).to_string(), "before plan step 3");
42/// ```
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub enum RewindTarget {
46    /// Before the session's user turn `n` (from 1), as `/rewind` numbers them.
47    Turn(u32),
48    /// Before the plan step with this id ran: the step and the ones after it run again.
49    PlanStep(String),
50    /// The snapshot with this id; `/redo` names the one taken before the last rewind.
51    Snapshot(String),
52}
53
54impl std::fmt::Display for RewindTarget {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        match self {
57            Self::Turn(n) => write!(f, "before turn {n}"),
58            Self::PlanStep(step) => write!(f, "before plan step {step}"),
59            Self::Snapshot(id) => write!(f, "snapshot {id}"),
60        }
61    }
62}
63
64/// What a rewind does to one path.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67pub enum ChangeKind {
68    /// Modified since the target: its content is put back.
69    Restore,
70    /// Deleted since the target: it is written again.
71    Recreate,
72    /// Created since the target: it is removed.
73    Delete,
74}
75
76impl ChangeKind {
77    fn label(self) -> &'static str {
78        match self {
79            Self::Restore => "restore",
80            Self::Recreate => "recreate",
81            Self::Delete => "delete",
82        }
83    }
84}
85
86/// One path a rewind changes.
87#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct RewindEntry {
90    /// Relative to the workspace root.
91    pub path: String,
92    /// What happens to it.
93    pub change: ChangeKind,
94    /// Its content's hash when the plan was made; `None` when absent or not hashed. A path
95    /// that changed since is skipped.
96    pub current_sha256: Option<String>,
97    /// Its entry in the target snapshot; `None` for a delete.
98    pub target: Option<FileEntry>,
99    /// Changed since the latest snapshot by something other than a harness file tool — a
100    /// command or the person: restored only when chosen.
101    pub conflict: bool,
102    /// A protected path (I29): restored only under the rewind's confirmation.
103    pub protected: bool,
104    /// Whether the rewind changes it; a conflict starts unchosen.
105    pub chosen: bool,
106}
107
108/// An effect after the target that a rewind cannot take back (spec 3.1 §7.27, 3.3 D-8).
109#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct NotUndone {
112    /// The tool that ran.
113    pub tool: String,
114    /// What it did, in one line.
115    pub summary: String,
116    /// Its action-ledger key, when the ledger recorded it.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub ledger_key: Option<String>,
119}
120
121/// What a rewind does to the session's transcript.
122#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct TranscriptPlan {
125    /// The id of the last event kept; `None` keeps none.
126    pub keep_through: Option<String>,
127    /// Events removed from the end.
128    pub events_removed: usize,
129    /// Events a redo puts back after `keep_through`.
130    pub events_restored: usize,
131    /// Whether the transcript stays as it is.
132    pub unchanged: bool,
133}
134
135/// What a rewind does to the session's plan graph (spec 3.1 §7.11).
136#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase", tag = "action")]
138pub enum PlanRewind {
139    /// `PlanGraphs::rewind` to just after this step completed.
140    #[serde(rename_all = "camelCase")]
141    AfterStep {
142        /// The step.
143        step_id: String,
144    },
145    /// No step had completed: the plan runs from its first step again.
146    Restart,
147    /// The plan goes back to the thread it ran on before a rewind (`/redo`).
148    #[serde(rename_all = "camelCase")]
149    Restore {
150        /// The thread.
151        thread_id: String,
152    },
153}
154
155/// The difference between a snapshot and the current tree, shown and confirmed once before
156/// [`Harness::rewind`](crate::Harness::rewind) applies it (spec 3.1 §7.27).
157///
158/// Conflicts start unchosen ([`choose_conflicts`](Self::choose_conflicts)); protected paths
159/// are restored only after [`confirm_protected`](Self::confirm_protected), which a surface
160/// calls when the person confirms a plan that lists them.
161#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct RewindPlan {
164    /// The application.
165    pub app_name: String,
166    /// The user.
167    pub user_id: String,
168    /// The session.
169    pub session_id: String,
170    /// What was asked for.
171    pub target: RewindTarget,
172    /// The snapshot the files come from.
173    pub snapshot_id: String,
174    /// Its kind.
175    pub snapshot_kind: SnapshotKind,
176    /// When it was taken.
177    pub taken_at: DateTime<Utc>,
178    /// The turn it precedes, numbered as `/rewind` numbers them.
179    pub turn: Option<u32>,
180    /// Paths that change.
181    pub entries: Vec<RewindEntry>,
182    /// Files the snapshot left out, never touched.
183    pub not_covered: Vec<NotCovered>,
184    /// How many more it left out than listed.
185    pub not_covered_more: usize,
186    /// Whether the snapshot stopped at `max_files`: a file it did not reach is never
187    /// deleted.
188    pub partial: bool,
189    /// Effects after the target a rewind cannot take back.
190    pub not_undone: Vec<NotUndone>,
191    /// The transcript fork.
192    pub transcript: TranscriptPlan,
193    /// The plan graph's rewind, when the session has a plan.
194    pub plan: Option<PlanRewind>,
195    /// Why the plan does not move, when it does not.
196    pub plan_note: Option<String>,
197    /// Whether the person confirmed the protected paths the plan lists.
198    pub protected_confirmed: bool,
199}
200
201impl RewindPlan {
202    /// The paths of `change`.
203    pub fn paths(&self, change: ChangeKind) -> Vec<&str> {
204        self.entries.iter().filter(|e| e.change == change).map(|e| e.path.as_str()).collect()
205    }
206
207    /// The conflicting entries.
208    pub fn conflicts(&self) -> impl Iterator<Item = &RewindEntry> {
209        self.entries.iter().filter(|entry| entry.conflict)
210    }
211
212    /// The protected entries.
213    pub fn protected(&self) -> impl Iterator<Item = &RewindEntry> {
214        self.entries.iter().filter(|entry| entry.protected)
215    }
216
217    /// Chooses, or leaves out, every conflicting path.
218    pub fn choose_conflicts(&mut self, chosen: bool) {
219        for entry in self.entries.iter_mut().filter(|entry| entry.conflict) {
220            entry.chosen = chosen;
221        }
222    }
223
224    /// Chooses the entry for `path`; returns whether the plan has one.
225    pub fn choose(&mut self, path: &str) -> bool {
226        match self.entries.iter_mut().find(|entry| entry.path == path) {
227            Some(entry) => {
228                entry.chosen = true;
229                true
230            }
231            None => false,
232        }
233    }
234
235    /// Records that the person confirmed the protected paths listed (the non-waivable
236    /// approval the rewind's confirmation carries, I29).
237    pub fn confirm_protected(&mut self) {
238        self.protected_confirmed = true;
239    }
240
241    /// Whether the rewind would change nothing: no path, the transcript as it is, no plan.
242    pub fn is_empty(&self) -> bool {
243        self.entries.is_empty() && self.transcript.unchanged && self.plan.is_none()
244    }
245
246    /// The plan as every surface shows it.
247    ///
248    /// # Example
249    ///
250    /// ```rust,ignore
251    /// let plan = harness.rewind_plan(&user, &session, RewindTarget::Turn(1)).await?;
252    /// println!("{}", plan.render());
253    /// ```
254    pub fn render(&self) -> String {
255        let mut out = String::new();
256        let when = self.taken_at.format("%Y-%m-%d %H:%M:%S UTC");
257        let _ = match self.snapshot_kind {
258            SnapshotKind::Rewind => writeln!(
259                out,
260                "Redo: put back what the rewind at {when} replaced (snapshot {})",
261                self.snapshot_id
262            ),
263            _ => writeln!(
264                out,
265                "Rewind {} — snapshot {} ({}, {when})",
266                self.target, self.snapshot_id, self.snapshot_kind
267            ),
268        };
269        for (change, heading) in [
270            (ChangeKind::Restore, "modified since, put back"),
271            (ChangeKind::Recreate, "deleted since, written again"),
272            (ChangeKind::Delete, "created since, removed"),
273        ] {
274            let paths: Vec<&str> = self
275                .entries
276                .iter()
277                .filter(|e| e.change == change && !e.conflict)
278                .map(|e| e.path.as_str())
279                .collect();
280            if !paths.is_empty() {
281                let _ = writeln!(
282                    out,
283                    "  {:<9} {} {heading}: {}",
284                    change.label(),
285                    count(paths.len(), "file"),
286                    list(&paths)
287                );
288            }
289        }
290        let conflicts: Vec<String> =
291            self.conflicts().map(|e| format!("{} ({})", e.path, e.change.label())).collect();
292        if !conflicts.is_empty() {
293            let chosen = self.conflicts().filter(|e| e.chosen).count();
294            let _ = writeln!(
295                out,
296                "  conflicts {} changed since the latest snapshot by a command or by you, {}: {}",
297                count(conflicts.len(), "file"),
298                if chosen == conflicts.len() {
299                    "restored as chosen"
300                } else {
301                    "kept unless you choose them"
302                },
303                list(&conflicts.iter().map(String::as_str).collect::<Vec<_>>())
304            );
305        }
306        let protected: Vec<&str> = self.protected().map(|e| e.path.as_str()).collect();
307        if !protected.is_empty() {
308            let _ = writeln!(
309                out,
310                "  protected {} changed only with your confirmation: {}",
311                count(protected.len(), "path"),
312                list(&protected)
313            );
314        }
315        if !self.not_covered.is_empty() || self.partial {
316            let reasons: Vec<String> = self
317                .not_covered
318                .iter()
319                .map(|item| match &item.reason {
320                    SkipReason::TooLarge { len } => {
321                        format!("{} (over the size limit, {len} bytes)", item.path)
322                    }
323                    SkipReason::Excluded => format!("{} (excluded)", item.path),
324                })
325                .collect();
326            let mut line = format!(
327                "  not covered, never touched: {}",
328                list(&reasons.iter().map(String::as_str).collect::<Vec<_>>())
329            );
330            if self.not_covered_more > 0 {
331                let _ = write!(line, " (+{} more)", self.not_covered_more);
332            }
333            if self.partial {
334                line.push_str("; the snapshot was partial (file cap reached): files it did not reach are kept");
335            }
336            let _ = writeln!(out, "{line}");
337        }
338        if !self.not_undone.is_empty() {
339            let items: Vec<String> = self
340                .not_undone
341                .iter()
342                .map(|item| format!("{}: {}", item.tool, item.summary))
343                .collect();
344            let _ = writeln!(
345                out,
346                "  not undone (effects outside the workspace stay): {}",
347                list(&items.iter().map(String::as_str).collect::<Vec<_>>())
348            );
349        }
350        let transcript = &self.transcript;
351        if transcript.unchanged {
352            let _ = writeln!(out, "  transcript stays as it is");
353        } else if transcript.events_restored > 0 {
354            let _ = writeln!(
355                out,
356                "  transcript {} removed, {} put back",
357                count(transcript.events_removed, "event"),
358                count(transcript.events_restored, "event")
359            );
360        } else {
361            let at = match self.turn {
362                Some(turn) => format!("before turn {turn}"),
363                None => "at the snapshot".to_string(),
364            };
365            let _ = writeln!(
366                out,
367                "  transcript forks {at}: {} removed",
368                count(transcript.events_removed, "event")
369            );
370        }
371        match (&self.plan, &self.plan_note) {
372            (Some(PlanRewind::AfterStep { step_id }), _) => {
373                let _ = writeln!(
374                    out,
375                    "  plan      rewinds to just after step {step_id}; the steps after it run again"
376                );
377            }
378            (Some(PlanRewind::Restart), _) => {
379                let _ = writeln!(out, "  plan      runs again from its first step");
380            }
381            (Some(PlanRewind::Restore { .. }), _) => {
382                let _ = writeln!(out, "  plan      goes back to where it stood before the rewind");
383            }
384            (None, Some(note)) => {
385                let _ = writeln!(out, "  plan      {note}");
386            }
387            (None, None) => {}
388        }
389        if self.entries.is_empty() {
390            let _ = writeln!(out, "  files     no file differs from the snapshot");
391        }
392        out
393    }
394}
395
396/// A path a rewind left as it was, and why.
397#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399pub struct SkippedPath {
400    /// Relative to the workspace root.
401    pub path: String,
402    /// Why.
403    pub reason: String,
404}
405
406/// What [`Harness::rewind`](crate::Harness::rewind) did.
407#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct RewindReport {
410    /// The snapshot taken before the rewind, which `/redo` restores.
411    pub before_rewind: String,
412    /// Paths put back.
413    pub restored: Vec<String>,
414    /// Paths written again.
415    pub recreated: Vec<String>,
416    /// Paths removed.
417    pub deleted: Vec<String>,
418    /// Paths left as they were.
419    pub skipped: Vec<SkippedPath>,
420    /// Events removed from the transcript.
421    pub events_removed: usize,
422    /// Events put back (`/redo`).
423    pub events_restored: usize,
424    /// The plan's thread after the rewind, when the plan moved.
425    pub plan_thread: Option<String>,
426    /// Effects the rewind could not take back.
427    pub not_undone: Vec<NotUndone>,
428}
429
430impl RewindReport {
431    /// The report as every surface shows it.
432    pub fn render(&self) -> String {
433        let mut out = format!(
434            "Rewound: {} restored, {} recreated, {} deleted",
435            self.restored.len(),
436            self.recreated.len(),
437            self.deleted.len()
438        );
439        if self.events_removed > 0 || self.events_restored > 0 {
440            let _ = write!(
441                out,
442                "; transcript: {} removed, {} put back",
443                count(self.events_removed, "event"),
444                count(self.events_restored, "event")
445            );
446        }
447        if let Some(thread) = &self.plan_thread {
448            let _ = write!(out, "; plan now on {thread}");
449        }
450        out.push('.');
451        for skipped in &self.skipped {
452            let _ = write!(out, "\n  kept {}: {}", skipped.path, skipped.reason);
453        }
454        if !self.not_undone.is_empty() {
455            let _ = write!(out, "\n  not undone: {}", self.not_undone.len());
456        }
457        let _ = write!(out, "\n/redo restores what was there before this rewind.");
458        out
459    }
460}
461
462/// One user turn of a session, as `/rewind` lists it.
463#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
464#[serde(rename_all = "camelCase")]
465pub struct RewindTurn {
466    /// From 1.
467    pub number: u32,
468    /// Its run.
469    pub invocation_id: String,
470    /// The start of what the person typed.
471    pub preview: String,
472    /// The snapshot taken before it, if any.
473    pub snapshot_id: Option<String>,
474    /// Files that differ between its snapshot and the next one (or the current tree).
475    pub changed_files: Option<usize>,
476    /// Whether its snapshot was partial.
477    pub partial: bool,
478}
479
480fn count(n: usize, noun: &str) -> String {
481    if n == 1 { format!("1 {noun}") } else { format!("{n} {noun}s") }
482}
483
484fn list(items: &[&str]) -> String {
485    let mut shown: Vec<String> =
486        items.iter().take(RENDER_PATHS).map(|item| adk_core_escape(item)).collect();
487    if items.len() > RENDER_PATHS {
488        shown.push(format!("+{} more", items.len() - RENDER_PATHS));
489    }
490    shown.join(", ")
491}
492
493/// Paths and summaries come from the workspace and the model; control characters never
494/// reach the terminal.
495fn adk_core_escape(text: &str) -> String {
496    crate::approvals::escape_control(text)
497}
498
499/// The rewind of the files: the target's entries against the current tree. A path the
500/// target did not cover — left out by size or exclusion, or past a partial walk — is never
501/// deleted.
502#[cfg(feature = "runner")]
503pub(crate) fn diff(
504    target: &[FileEntry],
505    target_partial: bool,
506    target_not_covered: &[NotCovered],
507    current: &TreeScan,
508) -> Vec<RewindEntry> {
509    let now: HashMap<&str, &FileEntry> =
510        current.files.iter().map(|file| (file.path.as_str(), file)).collect();
511    let now_not_covered: BTreeSet<&str> =
512        current.not_covered.iter().map(|item| item.path.as_str()).collect();
513    let then: HashMap<&str, &FileEntry> =
514        target.iter().map(|file| (file.path.as_str(), file)).collect();
515    let then_not_covered: BTreeSet<&str> =
516        target_not_covered.iter().map(|item| item.path.as_str()).collect();
517    let mut entries = Vec::new();
518    for file in target {
519        match now.get(file.path.as_str()) {
520            Some(current) if current.same_content(file) => {}
521            Some(current) => {
522                entries.push(entry(&file.path, ChangeKind::Restore, Some(current), Some(file)))
523            }
524            // Left out of this walk (now too large or excluded): it exists, so it is restored.
525            None if now_not_covered.contains(file.path.as_str()) => {
526                entries.push(entry(&file.path, ChangeKind::Restore, None, Some(file)));
527            }
528            None => entries.push(entry(&file.path, ChangeKind::Recreate, None, Some(file))),
529        }
530    }
531    for file in &current.files {
532        if then.contains_key(file.path.as_str())
533            || then_not_covered.contains(file.path.as_str())
534            || target_partial
535        {
536            continue;
537        }
538        entries.push(entry(&file.path, ChangeKind::Delete, Some(file), None));
539    }
540    entries.sort_by(|a, b| a.path.cmp(&b.path));
541    entries
542}
543
544#[cfg(feature = "runner")]
545fn entry(
546    path: &str,
547    change: ChangeKind,
548    current: Option<&FileEntry>,
549    target: Option<&FileEntry>,
550) -> RewindEntry {
551    RewindEntry {
552        path: path.to_string(),
553        change,
554        current_sha256: current.map(|file| file.sha256.clone()),
555        target: target.cloned(),
556        conflict: false,
557        protected: crate::approvals::matcher::is_protected_path(path),
558        chosen: true,
559    }
560}
561
562/// The paths that differ between two file lists.
563#[cfg(feature = "runner")]
564pub(crate) fn changed_paths(before: &[FileEntry], after: &[FileEntry]) -> BTreeSet<String> {
565    let mut by_path: BTreeMap<&str, (Option<&FileEntry>, Option<&FileEntry>)> = BTreeMap::new();
566    for file in before {
567        by_path.entry(file.path.as_str()).or_default().0 = Some(file);
568    }
569    for file in after {
570        by_path.entry(file.path.as_str()).or_default().1 = Some(file);
571    }
572    by_path
573        .into_iter()
574        .filter(|(_, pair)| match pair {
575            (Some(a), Some(b)) => !a.same_content(b),
576            _ => true,
577        })
578        .map(|(path, _)| path.to_string())
579        .collect()
580}
581
582/// The user turns of a session's events: a user message that starts a run, numbered from 1,
583/// with the index of its first event and the start of its text.
584#[cfg(feature = "runner")]
585pub(crate) fn turns_of(events: &[Event]) -> Vec<(u32, String, usize, String)> {
586    let mut seen: BTreeSet<&str> = BTreeSet::new();
587    let mut turns = Vec::new();
588    for (index, event) in events.iter().enumerate() {
589        let first = seen.insert(event.invocation_id.as_str());
590        if !first || event.author != "user" {
591            continue;
592        }
593        let text: String = event
594            .llm_response
595            .content
596            .iter()
597            .flat_map(|content| content.parts.iter())
598            .filter_map(Part::text)
599            .collect::<Vec<_>>()
600            .join(" ");
601        if text.trim().is_empty() {
602            continue;
603        }
604        let mut preview: String =
605            text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(60).collect();
606        if text.chars().count() > 60 {
607            preview.push('…');
608        }
609        turns.push((turns.len() as u32 + 1, event.invocation_id.clone(), index, preview));
610    }
611    turns
612}
613
614/// Where the transcript forks for `record`: the index of the first event a rewind to it
615/// removes, or `None` when it removes none. A turn snapshot forks before the turn's user
616/// message; a step or `Destructive` snapshot before the next user message that followed it.
617#[cfg(feature = "runner")]
618pub(crate) fn transcript_cut(events: &[Event], record: &SnapshotRecord) -> Option<usize> {
619    match record.kind {
620        SnapshotKind::Turn => events
621            .iter()
622            .position(|event| event.invocation_id == record.invocation_id)
623            .or_else(|| after(events, record, true)),
624        SnapshotKind::Step | SnapshotKind::Destructive | SnapshotKind::Rewind => {
625            after(events, record, true)
626        }
627    }
628}
629
630/// The index of the first event at or after `record` (a user message when `user_only`).
631#[cfg(feature = "runner")]
632fn after(events: &[Event], record: &SnapshotRecord, user_only: bool) -> Option<usize> {
633    events.iter().position(|event| {
634        event.timestamp >= record.created_at && (!user_only || event.author == "user")
635    })
636}
637
638/// The index of the first event after `record` was taken: where "since this snapshot"
639/// starts in the transcript.
640#[cfg(feature = "runner")]
641pub(crate) fn position_after(events: &[Event], record: &SnapshotRecord) -> usize {
642    let found = match record.kind {
643        SnapshotKind::Turn => {
644            events.iter().position(|event| event.invocation_id == record.invocation_id)
645        }
646        _ => None,
647    };
648    found.or_else(|| after(events, record, false)).unwrap_or(events.len())
649}
650
651/// A tool call in the transcript and whether it ran without an error.
652#[cfg(feature = "runner")]
653#[derive(Clone, Debug)]
654pub(crate) struct RanCall {
655    pub(crate) name: String,
656    pub(crate) args: Value,
657    pub(crate) call_id: Option<String>,
658    pub(crate) invocation_id: String,
659    pub(crate) succeeded: bool,
660    /// The background shell the call started, which outlives a rewind (spec 3.1 §7.29).
661    pub(crate) shell_id: Option<String>,
662}
663
664/// The tool calls in `events` that have a response, with whether it was a success.
665#[cfg(feature = "runner")]
666pub(crate) fn calls_in(events: &[Event]) -> Vec<RanCall> {
667    let mut calls: Vec<RanCall> = Vec::new();
668    let mut answered: HashMap<String, bool> = HashMap::new();
669    let mut shells: HashMap<String, String> = HashMap::new();
670    for event in events {
671        for part in event.llm_response.content.iter().flat_map(|content| content.parts.iter()) {
672            match part {
673                Part::FunctionCall { name, args, id, .. } => calls.push(RanCall {
674                    name: name.clone(),
675                    args: args.clone(),
676                    call_id: id.clone(),
677                    invocation_id: event.invocation_id.clone(),
678                    succeeded: false,
679                    shell_id: None,
680                }),
681                Part::FunctionResponse { function_response, id, .. } if id.is_some() => {
682                    let failed = function_response.response.get("error").is_some()
683                        || function_response
684                            .response
685                            .get("status")
686                            .and_then(Value::as_str)
687                            .is_some_and(|status| {
688                                matches!(status, "denied" | "not_run" | "result_withheld" | "held")
689                            });
690                    let response = &function_response.response;
691                    if response.get("status").and_then(Value::as_str) == Some("running")
692                        && let Some(shell) = response.get("shell_id").and_then(Value::as_str)
693                    {
694                        shells.insert(id.clone().unwrap_or_default(), shell.to_string());
695                    }
696                    answered.insert(id.clone().unwrap_or_default(), !failed);
697                }
698                _ => {}
699            }
700        }
701    }
702    calls
703        .into_iter()
704        .filter_map(|mut call| {
705            let id = call.call_id.as_deref()?;
706            call.succeeded = *answered.get(id)?;
707            call.shell_id = shells.get(id).cloned();
708            Some(call)
709        })
710        .collect()
711}
712
713/// The harness file tools whose effect is the workspace files a snapshot restores.
714#[cfg(feature = "runner")]
715pub(crate) const FILE_TOOLS: &[&str] = &["write_file", "edit_file", "apply_patch"];
716
717/// The paths the harness's file tools wrote in `events`: a file a command or the person
718/// changed is a conflict, one a file tool wrote is not (spec 3.1 §7.27). The transcript is
719/// the write record here; the digest records of §7.26 tighten it to the content written.
720#[cfg(feature = "runner")]
721pub(crate) fn harness_writes(events: &[Event], root: &Path) -> BTreeSet<String> {
722    let mut paths = BTreeSet::new();
723    for call in calls_in(events) {
724        if !call.succeeded || !FILE_TOOLS.contains(&call.name.as_str()) {
725            continue;
726        }
727        if let Some(path) = call.args.get("path").and_then(Value::as_str) {
728            paths.extend(normalize(path, root));
729        }
730        // `apply_patch` names its files in the patch headers.
731        for text in call
732            .args
733            .as_object()
734            .into_iter()
735            .flat_map(|args| args.values())
736            .filter_map(Value::as_str)
737        {
738            for line in text.lines() {
739                for marker in
740                    ["*** Add File: ", "*** Update File: ", "*** Delete File: ", "*** Move to: "]
741                {
742                    if let Some(path) = line.strip_prefix(marker) {
743                        paths.extend(normalize(path.trim(), root));
744                    }
745                }
746            }
747        }
748    }
749    paths
750}
751
752/// A tool's path argument as a workspace-relative path with `/` separators.
753#[cfg(feature = "runner")]
754fn normalize(path: &str, root: &Path) -> Option<String> {
755    let path = Path::new(path);
756    let relative = if path.is_absolute() { path.strip_prefix(root).ok()? } else { path };
757    let mut parts: Vec<String> = Vec::new();
758    for component in relative.components() {
759        match component {
760            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
761            Component::CurDir => {}
762            Component::ParentDir => {
763                parts.pop()?;
764            }
765            Component::RootDir | Component::Prefix(_) => return None,
766        }
767    }
768    (!parts.is_empty()).then(|| parts.join("/"))
769}
770
771// The tests exercise the rewind half, which needs `runner`.
772#[cfg(all(test, feature = "runner"))]
773mod tests {
774    use super::*;
775    use adk_core::{Content, FunctionResponseData};
776    use serde_json::json;
777
778    fn file(path: &str, sha: &str) -> FileEntry {
779        FileEntry {
780            path: path.into(),
781            sha256: sha.into(),
782            len: 1,
783            mode: 0o644,
784            mtime_ns: 0,
785            inode: 0,
786            link: None,
787        }
788    }
789
790    #[test]
791    fn the_diff_restores_recreates_and_deletes_but_never_what_the_target_did_not_cover() {
792        let target = vec![file("a", "1"), file("b", "2"), file("AGENTS.md", "3")];
793        let current = TreeScan {
794            files: vec![file("a", "1"), file("AGENTS.md", "4"), file("new", "5"), file("big", "6")],
795            partial: false,
796            not_covered: Vec::new(),
797        };
798        let skipped =
799            vec![NotCovered { path: "big".into(), reason: SkipReason::TooLarge { len: 9 } }];
800        let entries = diff(&target, false, &skipped, &current);
801        let summary: Vec<(&str, ChangeKind, bool)> =
802            entries.iter().map(|e| (e.path.as_str(), e.change, e.protected)).collect();
803        assert_eq!(
804            summary,
805            [
806                ("AGENTS.md", ChangeKind::Restore, true),
807                ("b", ChangeKind::Recreate, false),
808                ("new", ChangeKind::Delete, false),
809            ]
810        );
811        // A partial target deletes nothing it may not have reached.
812        let partial = diff(&target, true, &[], &current);
813        assert!(partial.iter().all(|e| e.change != ChangeKind::Delete));
814    }
815
816    fn event(invocation: &str, author: &str, parts: Vec<Part>) -> Event {
817        let mut event = Event::new(invocation);
818        event.author = author.into();
819        event.llm_response.content = Some(Content { role: author.into(), parts });
820        event
821    }
822
823    #[test]
824    fn turns_are_user_messages_that_start_a_run() {
825        let events = vec![
826            event("i1", "user", vec![Part::Text { text: "make two files".into() }]),
827            event("i1", "harness", vec![Part::Text { text: "done".into() }]),
828            event("i1", "user", vec![Part::Text { text: "[plan step 1] ...".into() }]),
829            event("i2", "user", vec![Part::Text { text: "now delete one".into() }]),
830        ];
831        let turns = turns_of(&events);
832        assert_eq!(turns.len(), 2);
833        assert_eq!((turns[1].0, turns[1].1.as_str(), turns[1].2), (2, "i2", 3));
834        assert_eq!(turns[0].3, "make two files");
835    }
836
837    #[test]
838    fn file_tool_writes_are_known_and_command_writes_are_not() {
839        let call = |id: &str, name: &str, args: Value| Part::FunctionCall {
840            name: name.into(),
841            args,
842            id: Some(id.into()),
843            thought_signature: None,
844        };
845        let answer = |id: &str, name: &str, response: Value| Part::FunctionResponse {
846            function_response: FunctionResponseData::new(name, response),
847            id: Some(id.into()),
848            annotations: None,
849        };
850        // `/work` has no drive letter, so it is not absolute on Windows.
851        let root = &std::env::temp_dir().join("work");
852        let absolute = root.join("src").join("c.rs");
853        let events = vec![
854            event(
855                "i1",
856                "harness",
857                vec![
858                    call("c1", "write_file", json!({"path": "./a.txt", "content": "x"})),
859                    call("c2", "bash", json!({"command": "echo b > b.txt"})),
860                    call("c3", "edit_file", json!({"path": absolute.to_string_lossy()})),
861                    call("c4", "write_file", json!({"path": "denied.txt"})),
862                ],
863            ),
864            event(
865                "i1",
866                "harness",
867                vec![
868                    answer("c1", "write_file", json!({"path": "a.txt"})),
869                    answer("c2", "bash", json!({"exit_code": 0})),
870                    answer("c3", "edit_file", json!({"path": "src/c.rs"})),
871                    answer("c4", "write_file", json!({"error": "denied"})),
872                ],
873            ),
874        ];
875        let written = harness_writes(&events, root);
876        assert_eq!(written.into_iter().collect::<Vec<_>>(), ["a.txt", "src/c.rs"]);
877        assert_eq!(normalize("../outside", root), None);
878    }
879}