1use 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#[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
30const RENDER_PATHS: usize = 12;
32
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub enum RewindTarget {
46 Turn(u32),
48 PlanStep(String),
50 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67pub enum ChangeKind {
68 Restore,
70 Recreate,
72 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct RewindEntry {
90 pub path: String,
92 pub change: ChangeKind,
94 pub current_sha256: Option<String>,
97 pub target: Option<FileEntry>,
99 pub conflict: bool,
102 pub protected: bool,
104 pub chosen: bool,
106}
107
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct NotUndone {
112 pub tool: String,
114 pub summary: String,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub ledger_key: Option<String>,
119}
120
121#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct TranscriptPlan {
125 pub keep_through: Option<String>,
127 pub events_removed: usize,
129 pub events_restored: usize,
131 pub unchanged: bool,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase", tag = "action")]
138pub enum PlanRewind {
139 #[serde(rename_all = "camelCase")]
141 AfterStep {
142 step_id: String,
144 },
145 Restart,
147 #[serde(rename_all = "camelCase")]
149 Restore {
150 thread_id: String,
152 },
153}
154
155#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct RewindPlan {
164 pub app_name: String,
166 pub user_id: String,
168 pub session_id: String,
170 pub target: RewindTarget,
172 pub snapshot_id: String,
174 pub snapshot_kind: SnapshotKind,
176 pub taken_at: DateTime<Utc>,
178 pub turn: Option<u32>,
180 pub entries: Vec<RewindEntry>,
182 pub not_covered: Vec<NotCovered>,
184 pub not_covered_more: usize,
186 pub partial: bool,
189 pub not_undone: Vec<NotUndone>,
191 pub transcript: TranscriptPlan,
193 pub plan: Option<PlanRewind>,
195 pub plan_note: Option<String>,
197 pub protected_confirmed: bool,
199}
200
201impl RewindPlan {
202 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 pub fn conflicts(&self) -> impl Iterator<Item = &RewindEntry> {
209 self.entries.iter().filter(|entry| entry.conflict)
210 }
211
212 pub fn protected(&self) -> impl Iterator<Item = &RewindEntry> {
214 self.entries.iter().filter(|entry| entry.protected)
215 }
216
217 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 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 pub fn confirm_protected(&mut self) {
238 self.protected_confirmed = true;
239 }
240
241 pub fn is_empty(&self) -> bool {
243 self.entries.is_empty() && self.transcript.unchanged && self.plan.is_none()
244 }
245
246 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399pub struct SkippedPath {
400 pub path: String,
402 pub reason: String,
404}
405
406#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct RewindReport {
410 pub before_rewind: String,
412 pub restored: Vec<String>,
414 pub recreated: Vec<String>,
416 pub deleted: Vec<String>,
418 pub skipped: Vec<SkippedPath>,
420 pub events_removed: usize,
422 pub events_restored: usize,
424 pub plan_thread: Option<String>,
426 pub not_undone: Vec<NotUndone>,
428}
429
430impl RewindReport {
431 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
464#[serde(rename_all = "camelCase")]
465pub struct RewindTurn {
466 pub number: u32,
468 pub invocation_id: String,
470 pub preview: String,
472 pub snapshot_id: Option<String>,
474 pub changed_files: Option<usize>,
476 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
493fn adk_core_escape(text: &str) -> String {
496 crate::approvals::escape_control(text)
497}
498
499#[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 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 ¤t.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#[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#[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#[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#[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#[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#[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 pub(crate) shell_id: Option<String>,
662}
663
664#[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#[cfg(feature = "runner")]
715pub(crate) const FILE_TOOLS: &[&str] = &["write_file", "edit_file", "apply_patch"];
716
717#[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 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#[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#[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, ¤t);
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 let partial = diff(&target, true, &[], ¤t);
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 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}