1#![allow(clippy::unwrap_used)]
2use anyhow::Result;
3use rand::RngExt;
4use serde::{Deserialize, Serialize};
5use std::collections::{HashMap, VecDeque};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use tokio::sync::Mutex;
9use tracing::info;
10
11use crate::state::persistence::{
12 load_bash_state as load_state_file, save_bash_state as save_state_file, BashStateSnapshot,
13};
14use crate::state::pty::PtyShell;
15use crate::types::{
16 AllowedCommands, AllowedGlobs, BashCommandMode, BashMode, FileEditMode, Modes, WriteIfEmptyMode,
17};
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct FileWhitelistData {
21 pub file_hash: String,
22 pub line_ranges_read: Vec<(usize, usize)>,
23 pub total_lines: usize,
24}
25
26fn clamped_sorted(ranges: &[(usize, usize)], total_lines: usize) -> Vec<(usize, usize)> {
29 let mut v: Vec<(usize, usize)> = ranges
30 .iter()
31 .map(|&(s, e)| (s.max(1), e.min(total_lines)))
32 .filter(|&(s, e)| s <= e)
33 .collect();
34 v.sort_unstable();
35 v
36}
37
38fn covered_line_count(ranges: &[(usize, usize)], total_lines: usize) -> usize {
41 let mut covered = 0usize;
42 let mut last_end = 0usize; for (s, e) in clamped_sorted(ranges, total_lines) {
44 let s = s.max(last_end + 1);
45 if s <= e {
46 covered += e - s + 1;
47 last_end = e;
48 }
49 }
50 covered
51}
52
53impl FileWhitelistData {
54 pub fn new(
55 file_hash: String,
56 line_ranges_read: Vec<(usize, usize)>,
57 total_lines: usize,
58 ) -> Self {
59 let mut data = Self { file_hash, line_ranges_read: Vec::new(), total_lines };
60 data.merge_ranges(line_ranges_read);
61 data
62 }
63
64 pub fn is_read_enough(&self) -> bool {
65 self.get_percentage_read() >= 99.0
66 }
67
68 #[allow(clippy::cast_precision_loss)]
69 pub fn get_percentage_read(&self) -> f64 {
70 if self.total_lines == 0 {
71 return 100.0;
72 }
73 let covered = covered_line_count(&self.line_ranges_read, self.total_lines);
77 (covered as f64 / self.total_lines as f64) * 100.0
78 }
79
80 pub fn get_unread_ranges(&self) -> Vec<(usize, usize)> {
81 if self.total_lines == 0 {
82 return vec![];
83 }
84 let sorted = clamped_sorted(&self.line_ranges_read, self.total_lines);
85 let mut unread = vec![];
86 let mut next = 1usize; for (s, e) in sorted {
88 if s > next {
89 unread.push((next, s - 1));
90 }
91 next = next.max(e.saturating_add(1));
92 }
93 if next <= self.total_lines {
94 unread.push((next, self.total_lines));
95 }
96 unread
97 }
98
99 pub fn add_range(&mut self, start: usize, end: usize) {
104 self.merge_ranges(std::iter::once((start, end)));
105 }
106
107 pub fn merge_ranges(&mut self, new: impl IntoIterator<Item = (usize, usize)>) {
110 self.line_ranges_read.extend(new);
111 self.line_ranges_read.retain(|(s, e)| s <= e);
112 self.line_ranges_read.sort_unstable();
113 let mut merged: Vec<(usize, usize)> = Vec::with_capacity(self.line_ranges_read.len());
114 for (s, e) in self.line_ranges_read.drain(..) {
115 match merged.last_mut() {
116 Some(last) if s <= last.1.saturating_add(1) => last.1 = last.1.max(e),
117 _ => merged.push((s, e)),
118 }
119 }
120 self.line_ranges_read = merged;
121 }
122
123 pub fn needs_more_reading(&self) -> bool {
124 !self.is_read_enough()
125 }
126}
127
128const EDIT_CHECKPOINT_CAP: usize = 10;
131
132const EDIT_CHECKPOINT_MAX_CONTENT_BYTES: usize = 1_000_000;
137
138const MAX_WHITELIST_FILES: usize = 1_024;
143
144const IMAGE_DELIVERY_CACHE_CAP: usize = 32;
148
149#[derive(Debug, Clone)]
153pub struct EditCheckpoint {
154 pub file_path_str: String,
156 pub path: PathBuf,
157 pub prior_content: String,
159 pub prior_whitelist: Option<FileWhitelistData>,
162}
163
164#[derive(Debug, Clone)]
165pub struct BashState {
166 pub cwd: PathBuf,
167 pub workspace_root: PathBuf,
168 pub current_thread_id: String,
169 pub mode: Modes,
170 pub bash_command_mode: BashCommandMode,
171 pub file_edit_mode: FileEditMode,
172 pub write_if_empty_mode: WriteIfEmptyMode,
173 pub whitelist_for_overwrite: HashMap<String, FileWhitelistData>,
174 whitelist_recency: VecDeque<String>,
178 pub pty_shell: Arc<Mutex<Option<PtyShell>>>,
179 pub foreground_command_gate: Arc<Mutex<()>>,
182 pub initialized: bool,
183 pub edit_checkpoints: VecDeque<EditCheckpoint>,
187 pub derived_code_map_usage: crate::utils::agent_temp::DerivedCodeMapUsage,
190 image_deliveries: VecDeque<String>,
191}
192
193impl Default for BashState {
194 fn default() -> Self {
195 Self::new()
196 }
197}
198
199impl BashState {
200 pub fn new() -> Self {
201 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
202 Self {
203 cwd: cwd.clone(),
204 workspace_root: cwd,
205 current_thread_id: generate_thread_id(),
206 mode: Modes::Wcgw,
207 bash_command_mode: BashCommandMode {
208 bash_mode: BashMode::NormalMode,
209 allowed_commands: AllowedCommands::All("all".to_string()),
210 },
211 file_edit_mode: FileEditMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
212 write_if_empty_mode: WriteIfEmptyMode {
213 allowed_globs: AllowedGlobs::All("all".to_string()),
214 },
215 whitelist_for_overwrite: HashMap::new(),
216 whitelist_recency: VecDeque::new(),
217 pty_shell: Arc::new(Mutex::new(None)),
218 foreground_command_gate: Arc::new(Mutex::new(())),
219 initialized: false,
220 edit_checkpoints: VecDeque::new(),
221 derived_code_map_usage: crate::utils::agent_temp::DerivedCodeMapUsage::default(),
222 image_deliveries: VecDeque::new(),
223 }
224 }
225
226 pub(crate) fn image_was_delivered(&mut self, fingerprint: &str) -> bool {
230 let Some(index) = self.image_deliveries.iter().position(|item| item == fingerprint) else {
231 return false;
232 };
233 if let Some(item) = self.image_deliveries.remove(index) {
234 self.image_deliveries.push_back(item);
235 }
236 true
237 }
238
239 pub(crate) fn record_image_delivery(&mut self, fingerprint: String) {
241 if let Some(index) = self.image_deliveries.iter().position(|item| item == &fingerprint) {
242 self.image_deliveries.remove(index);
243 }
244 self.image_deliveries.push_back(fingerprint);
245 while self.image_deliveries.len() > IMAGE_DELIVERY_CACHE_CAP {
246 self.image_deliveries.pop_front();
247 }
248 }
249
250 pub fn push_edit_checkpoint(&mut self, checkpoint: EditCheckpoint) {
253 if checkpoint.prior_content.len() > EDIT_CHECKPOINT_MAX_CONTENT_BYTES {
254 info!(
255 file = %checkpoint.file_path_str,
256 "UndoEdit: not checkpointing a file over 1 MB (too large to hold in memory)"
257 );
258 return;
259 }
260 self.edit_checkpoints.push_back(checkpoint);
261 while self.edit_checkpoints.len() > EDIT_CHECKPOINT_CAP {
262 self.edit_checkpoints.pop_front();
263 }
264 }
265
266 pub fn pop_edit_checkpoint_for(&mut self, file_path_str: &str) -> Option<EditCheckpoint> {
270 let index =
271 self.edit_checkpoints.iter().rposition(|cp| cp.file_path_str == file_path_str)?;
272 self.edit_checkpoints.remove(index)
273 }
274
275 pub fn record_read_coverage(
280 &mut self,
281 path: &str,
282 ranges: impl IntoIterator<Item = (usize, usize)>,
283 file_hash: String,
284 total_lines: usize,
285 ) {
286 let ranges = ranges.into_iter().collect::<Vec<_>>();
287 match self.whitelist_for_overwrite.get_mut(path) {
288 Some(existing)
289 if existing.file_hash == file_hash && existing.total_lines == total_lines =>
290 {
291 existing.merge_ranges(ranges);
292 }
293 Some(existing) => {
294 *existing = FileWhitelistData::new(file_hash, ranges, total_lines);
295 }
296 None => {
297 self.whitelist_for_overwrite.insert(
298 path.to_string(),
299 FileWhitelistData::new(file_hash, ranges, total_lines),
300 );
301 }
302 }
303 self.touch_whitelist(path);
304 self.enforce_whitelist_cap();
305 }
306
307 pub fn set_whitelist_entry(&mut self, path: &str, entry: FileWhitelistData) {
309 self.whitelist_for_overwrite.insert(path.to_string(), entry);
310 self.touch_whitelist(path);
311 self.enforce_whitelist_cap();
312 }
313
314 pub fn remove_whitelist_entry(&mut self, path: &str) -> Option<FileWhitelistData> {
316 self.whitelist_recency.retain(|candidate| candidate != path);
317 self.whitelist_for_overwrite.remove(path)
318 }
319
320 fn touch_whitelist(&mut self, path: &str) {
321 self.whitelist_recency.retain(|candidate| candidate != path);
322 self.whitelist_recency.push_back(path.to_string());
323 }
324
325 fn rebuild_whitelist_recency(&mut self) {
326 let mut paths = self.whitelist_for_overwrite.keys().cloned().collect::<Vec<_>>();
327 paths.sort_unstable();
328 self.whitelist_recency = paths.into();
329 self.enforce_whitelist_cap();
330 }
331
332 fn enforce_whitelist_cap(&mut self) {
333 self.whitelist_recency.retain(|path| self.whitelist_for_overwrite.contains_key(path));
334 while self.whitelist_for_overwrite.len() > MAX_WHITELIST_FILES {
335 let victim = self.whitelist_recency.pop_front().or_else(|| {
336 self.whitelist_for_overwrite.keys().min().cloned()
339 });
340 let Some(victim) = victim else { break };
341 self.whitelist_for_overwrite.remove(&victim);
342 }
343 }
344
345 pub async fn init_pty_shell(&mut self) -> Result<()> {
346 let cwd = self.cwd.clone();
347 let workspace_root = self.workspace_root.clone();
348 let temporary_artifact_dir =
349 crate::utils::agent_temp::session_info(&workspace_root, &self.current_thread_id)
350 .directory;
351 let restricted = self.bash_command_mode.bash_mode == BashMode::RestrictedMode;
352 let shell = tokio::task::spawn_blocking(move || {
356 PtyShell::new_with_agent_paths(
357 &cwd,
358 restricted,
359 Some(&workspace_root),
360 Some(&temporary_artifact_dir),
361 )
362 })
363 .await
364 .map_err(|e| {
365 crate::errors::WinxError::ShellInitializationError(format!("PTY init task failed: {e}"))
366 })??;
367 *self.pty_shell.lock().await = Some(shell);
368 Ok(())
369 }
370
371 pub fn update_cwd(&mut self, path: &Path) -> Result<()> {
372 self.cwd = path.to_path_buf();
373 Ok(())
374 }
375
376 pub fn update_workspace_root(&mut self, path: &Path) -> Result<()> {
377 self.workspace_root = path.to_path_buf();
378 Ok(())
379 }
380
381 pub fn is_command_allowed(&self, command: &str) -> bool {
382 if self.mode == Modes::Architect {
383 crate::utils::bash_parser::is_architect_command_allowed(command)
384 } else {
385 self.bash_command_mode.allowed_commands.is_allowed(command)
386 }
387 }
388
389 pub fn is_file_edit_allowed(&self, path: &str) -> bool {
390 self.file_edit_mode.allowed_globs.is_allowed(path)
391 }
392
393 pub fn is_file_write_allowed(&self, path: &str) -> bool {
394 self.write_if_empty_mode.allowed_globs.is_allowed(path)
395 }
396 pub fn save_state_to_disk(&self) -> Result<()> {
397 let snapshot = self.snapshot();
398 save_state_file(&self.current_thread_id, &snapshot)?;
399 Ok(())
400 }
401
402 pub fn snapshot(&self) -> BashStateSnapshot {
403 BashStateSnapshot::from_state(
404 &self.cwd.to_string_lossy(),
405 &self.workspace_root.to_string_lossy(),
406 &self.mode,
407 &self.bash_command_mode,
408 &self.file_edit_mode,
409 &self.write_if_empty_mode,
410 &self.whitelist_for_overwrite,
411 &self.current_thread_id,
412 )
413 }
414
415 pub fn apply_snapshot(&mut self, snapshot: &BashStateSnapshot) {
416 let (cwd, root, mode, bmode, emode, wmode, whitelist, tid) = snapshot.to_state_components();
417 let root = PathBuf::from(root);
418 let image_identity_changed = self.current_thread_id != tid || self.workspace_root != root;
419
420 self.cwd = PathBuf::from(cwd);
421 self.workspace_root = root;
422 self.mode = mode;
423 self.bash_command_mode = bmode;
424 self.file_edit_mode = emode;
425 self.write_if_empty_mode = wmode;
426 self.whitelist_for_overwrite = whitelist;
427 self.rebuild_whitelist_recency();
428 self.current_thread_id = tid;
429 if image_identity_changed {
430 self.image_deliveries.clear();
431 }
432 self.initialized = true;
433 }
434
435 pub fn load_state_from_disk(&mut self, thread_id: &str) -> Result<bool> {
436 if let Some(snapshot) = load_state_file(thread_id)? {
437 self.apply_snapshot(&snapshot);
438 Ok(true)
439 } else {
440 Ok(false)
441 }
442 }
443
444 pub fn new_with_thread_id(thread_id: Option<&str>) -> Self {
445 let mut state = Self::new();
446
447 if let Some(tid) = thread_id {
448 if !tid.is_empty() {
449 if let Ok(true) = state.load_state_from_disk(tid) {
450 info!("Loaded state for thread_id '{}'", tid);
451 } else {
452 state.current_thread_id = tid.to_string();
453 }
454 }
455 }
456
457 state
458 }
459}
460
461pub fn generate_thread_id() -> String {
462 let mut rng = rand::rng();
463 format!("tid_{:x}", rng.random::<u64>())
464}
465
466#[cfg(test)]
467mod whitelist_range_tests {
468 use super::{BashState, FileWhitelistData, MAX_WHITELIST_FILES};
469
470 fn wl(ranges: &[(usize, usize)], total: usize) -> FileWhitelistData {
471 FileWhitelistData::new("h".to_string(), ranges.to_vec(), total)
472 }
473
474 #[test]
475 fn merge_collapses_overlap_and_adjacency() {
476 let w = wl(&[(4, 5), (1, 3), (8, 12), (7, 9)], 20);
478 assert_eq!(w.line_ranges_read, vec![(1, 5), (7, 12)]);
479 }
480
481 #[test]
482 fn re_reading_does_not_grow_unbounded() {
483 let mut w = wl(&[(1, 10)], 100);
484 for _ in 0..1000 {
485 w.merge_ranges(std::iter::once((1, 10)));
486 w.merge_ranges(std::iter::once((5, 15)));
487 }
488 assert_eq!(w.line_ranges_read, vec![(1, 15)]);
490 }
491
492 #[test]
493 fn percentage_counts_distinct_lines_with_overlap() {
494 let w = wl(&[(1, 5), (3, 8)], 10);
496 assert!((w.get_percentage_read() - 80.0).abs() < 1e-9);
497 assert!(wl(&[(1, 10)], 10).is_read_enough());
498 }
499
500 #[test]
501 fn unread_ranges_are_the_gaps() {
502 let w = wl(&[(2, 4), (7, 8)], 10);
504 assert_eq!(w.get_unread_ranges(), vec![(1, 1), (5, 6), (9, 10)]);
505 }
506
507 #[test]
508 fn out_of_range_entries_are_clamped() {
509 let w = wl(&[(0, 999)], 10);
511 assert!((w.get_percentage_read() - 100.0).abs() < 1e-9);
512 assert!(w.get_unread_ranges().is_empty());
513 }
514
515 #[test]
516 fn coverage_from_different_file_versions_is_not_combined() {
517 let mut state = BashState::new();
518 state.record_read_coverage("/workspace/file.rs", [(1, 50)], "old-hash".to_string(), 100);
519 state.record_read_coverage("/workspace/file.rs", [(51, 100)], "new-hash".to_string(), 100);
520
521 let coverage = &state.whitelist_for_overwrite["/workspace/file.rs"];
522 assert_eq!(coverage.file_hash, "new-hash");
523 assert_eq!(coverage.line_ranges_read, vec![(51, 100)]);
524 assert_eq!(coverage.get_unread_ranges(), vec![(1, 50)]);
525 }
526
527 #[test]
528 fn whitelist_is_lru_bounded_and_recent_entries_survive() {
529 let mut state = BashState::new();
530 for index in 0..MAX_WHITELIST_FILES {
531 let path = format!("/workspace/file-{index:04}.rs");
532 state.record_read_coverage(&path, [(1, 1)], format!("hash-{index}"), 1);
533 }
534
535 state.record_read_coverage("/workspace/file-0000.rs", [(1, 1)], "hash-0".to_string(), 1);
538 state.record_read_coverage("/workspace/newest.rs", [(1, 1)], "newest-hash".to_string(), 1);
539
540 assert_eq!(state.whitelist_for_overwrite.len(), MAX_WHITELIST_FILES);
541 assert!(state.whitelist_for_overwrite.contains_key("/workspace/file-0000.rs"));
542 assert!(!state.whitelist_for_overwrite.contains_key("/workspace/file-0001.rs"));
543 assert!(state.whitelist_for_overwrite.contains_key("/workspace/newest.rs"));
544 }
545
546 #[test]
547 fn image_delivery_cache_survives_same_session_snapshot_sync_only() {
548 let mut state = BashState::new();
549 state.workspace_root = "/workspace/one".into();
550 state.current_thread_id = "one".to_string();
551 state.record_image_delivery("fingerprint".to_string());
552
553 let same_session = state.snapshot();
554 state.apply_snapshot(&same_session);
555 assert!(state.image_was_delivered("fingerprint"));
556
557 let mut other = BashState::new();
558 other.workspace_root = "/workspace/two".into();
559 other.current_thread_id = "two".to_string();
560 state.apply_snapshot(&other.snapshot());
561 assert!(!state.image_was_delivered("fingerprint"));
562 }
563}