tidev 0.2.0

A terminal-based AI coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
mod git;

use anyhow::{Context, Result};
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
    sync::Arc,
};
use tokio::sync::Mutex;

use crate::config::ConfigPaths;

const BATCH_SIZE: usize = 100;

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Patch {
    pub hash: String,
    pub files: Vec<String>,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct FileDiff {
    pub file: String,
    pub patch: String,
    pub additions: usize,
    pub deletions: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

#[derive(Clone)]
pub struct SnapshotService {
    worktree: PathBuf,
    gitdir: PathBuf,
    lock: Arc<Mutex<()>>,
}

impl SnapshotService {
    pub fn new(workspace_root: &Path, paths: &ConfigPaths) -> Result<Self> {
        let worktree = workspace_root.canonicalize().with_context(|| {
            format!(
                "failed to canonicalize workspace root {}",
                workspace_root.display()
            )
        })?;

        let worktree_hash = blake3::hash(worktree.to_string_lossy().as_bytes())
            .to_hex()
            .to_string();

        let gitdir = paths.data_dir.join("snapshot").join(&worktree_hash);

        Ok(Self {
            worktree,
            gitdir,
            lock: Arc::new(Mutex::new(())),
        })
    }

    pub async fn track(&self) -> Result<Option<String>> {
        let _guard = self.lock.lock().await;

        let existed = self.gitdir.exists();
        std::fs::create_dir_all(&self.gitdir).with_context(|| {
            format!(
                "failed to create snapshot directory {}",
                self.gitdir.display()
            )
        })?;

        if !existed {
            git::init_snapshot_repo(&self.gitdir)?;
        }

        let all_files = git::find_changed_files(&self.gitdir, &self.worktree)?;
        let ignored = if all_files.is_empty() {
            HashSet::new()
        } else {
            git::check_ignored(&self.gitdir, &self.worktree, &all_files)?
        };

        if !ignored.is_empty() {
            let ignored_files: Vec<_> = ignored.iter().cloned().collect();
            git::drop_files(&self.gitdir, &self.worktree, &ignored_files)?;
        }

        let allowed: Vec<_> = all_files
            .iter()
            .filter(|f| !ignored.contains(*f))
            .cloned()
            .collect();

        let large_files = git::filter_large_files(&self.worktree, &allowed, 2 * 1024 * 1024)?;
        let blocked: HashSet<_> = large_files.iter().cloned().collect();

        let to_stage: Vec<_> = allowed
            .iter()
            .filter(|f| !blocked.contains(*f))
            .cloned()
            .collect();

        if !large_files.is_empty() {
            git::sync_exclude(&self.gitdir, &self.worktree, &large_files)?;
        } else {
            git::sync_exclude(&self.gitdir, &self.worktree, &[])?;
        }

        if !to_stage.is_empty() {
            git::stage_files(&self.gitdir, &self.worktree, &to_stage)?;
        }

        let hash = git::write_tree(&self.gitdir)?;

        Ok(Some(hash))
    }

    pub async fn patch(&self, hash: &str) -> Result<Patch> {
        let _guard = self.lock.lock().await;

        self.update_index()?;

        let changed = git::diff_cached_names(&self.gitdir, &self.worktree, hash)?;

        let ignored = git::check_ignored(&self.gitdir, &self.worktree, &changed)?;
        let files: Vec<String> = changed
            .iter()
            .filter(|f| !ignored.contains(*f))
            .map(|f| self.worktree.join(f).to_string_lossy().replace('\\', "/"))
            .collect();

        Ok(Patch {
            hash: hash.to_string(),
            files,
        })
    }

    pub async fn revert(&self, patches: &[Patch]) -> Result<()> {
        let _guard = self.lock.lock().await;

        let mut ops: Vec<(String, String, String)> = Vec::new();
        let mut seen: HashSet<String> = HashSet::new();

        for patch in patches {
            for file in &patch.files {
                if seen.contains(file) {
                    continue;
                }
                seen.insert(file.clone());

                let rel = Path::new(file)
                    .strip_prefix(&self.worktree)
                    .with_context(|| format!("path {} is not under worktree", file))?
                    .to_string_lossy()
                    .replace('\\', "/");

                ops.push((patch.hash.clone(), file.clone(), rel));
            }
        }

        let mut i = 0;
        while i < ops.len() {
            let first = &ops[i];
            let mut batch_indices = vec![i];
            let mut j = i + 1;

            while j < ops.len() && batch_indices.len() < BATCH_SIZE {
                let next = &ops[j];
                if next.0 != first.0 {
                    break;
                }
                if batch_indices.iter().any(|&idx| clash(&ops[idx].2, &next.2)) {
                    break;
                }
                batch_indices.push(j);
                j += 1;
            }

            if batch_indices.len() == 1 {
                self.revert_single(&first.0, &first.1, &first.2)?;
            } else {
                let batch: Vec<_> = batch_indices.iter().map(|&idx| &ops[idx]).collect();
                self.revert_batch(&batch)?;
            }

            i = j;
        }

        Ok(())
    }

    fn revert_single(&self, hash: &str, file: &str, rel: &str) -> Result<()> {
        match git::checkout_file(&self.gitdir, &self.worktree, hash, file) {
            Ok(()) => return Ok(()),
            Err(_) => match git::ls_tree(&self.gitdir, hash, rel)? {
                Some(_) => {
                    return Ok(());
                }
                None => {
                    self.remove_path(file)?;
                }
            },
        }
        Ok(())
    }

    fn revert_batch(&self, batch: &[&(String, String, String)]) -> Result<()> {
        let hash = &batch[0].0;
        let rels: Vec<&str> = batch.iter().map(|op| op.2.as_str()).collect();

        let tree_output = git::ls_tree_names(&self.gitdir, hash, &rels)?;
        let have: HashSet<&str> = tree_output
            .lines()
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();

        let to_checkout: Vec<&str> = batch
            .iter()
            .filter(|op| have.contains(op.2.as_str()))
            .map(|op| op.1.as_str())
            .collect();

        if !to_checkout.is_empty()
            && let Err(_) = git::checkout_files(&self.gitdir, &self.worktree, hash, &to_checkout)
        {
            for op in batch {
                if have.contains(op.2.as_str()) {
                    self.revert_single(&op.0, &op.1, &op.2)?;
                }
            }
        }

        for op in batch {
            if !have.contains(op.2.as_str()) {
                self.remove_path(&op.1)?;
            }
        }

        Ok(())
    }

    fn remove_path(&self, file: &str) -> Result<()> {
        let path = Path::new(file);
        if path.exists() {
            if path.is_dir() {
                std::fs::remove_dir_all(path)
                    .with_context(|| format!("failed to remove directory {}", file))?;
            } else {
                std::fs::remove_file(path)
                    .with_context(|| format!("failed to remove file {}", file))?;
            }
        }
        Ok(())
    }

    pub async fn restore(&self, snapshot: &str) -> Result<()> {
        let _guard = self.lock.lock().await;

        git::read_tree(&self.gitdir, snapshot)?;
        git::checkout_index(&self.gitdir, &self.worktree)?;

        Ok(())
    }

    pub async fn cleanup(&self) -> Result<()> {
        let _guard = self.lock.lock().await;

        if !self.gitdir.exists() {
            return Ok(());
        }

        git::gc_prune(&self.gitdir, "7.days")?;

        Ok(())
    }

    pub async fn diff(&self, hash: &str) -> Result<String> {
        let _guard = self.lock.lock().await;

        self.update_index()?;

        git::diff_cached(&self.gitdir, &self.worktree, hash)
    }

    /// Lightweight diff between two snapshot tree hashes.
    /// Returns FileDiff entries with file, additions, deletions, and status
    /// but WITHOUT full patch content. Used for per-step sidebar updates.
    /// Does NOT call update_index() since it compares two committed trees.
    /// Much cheaper than diff_full() — only 2 git subprocess calls total.
    pub async fn diff_lightweight(&self, from: &str, to: &str) -> Result<Vec<FileDiff>> {
        let _guard = self.lock.lock().await;

        let statuses = git::diff_name_status(&self.gitdir, &self.worktree, from, to)?;
        let numstat = git::diff_numstat(&self.gitdir, &self.worktree, from, to)?;

        let mut status_map: HashMap<String, String> = HashMap::new();
        for (status, file) in &statuses {
            let s = if status.starts_with('A') {
                "added"
            } else if status.starts_with('D') {
                "deleted"
            } else {
                "modified"
            };
            status_map.insert(file.clone(), s.to_string());
        }

        let mut result: Vec<FileDiff> = Vec::new();
        for (adds, dels, file) in &numstat {
            let binary = adds == "-" && dels == "-";
            result.push(FileDiff {
                file: file.clone(),
                patch: String::new(), // lightweight — no patch content
                additions: if binary { 0 } else { adds.parse().unwrap_or(0) },
                deletions: if binary { 0 } else { dels.parse().unwrap_or(0) },
                status: status_map.get(file).cloned(),
            });
        }

        Ok(result)
    }

    pub async fn diff_full(&self, from: &str, to: &str) -> Result<Vec<FileDiff>> {
        let _guard = self.lock.lock().await;

        self.update_index()?;

        let statuses = git::diff_name_status(&self.gitdir, &self.worktree, from, to)?;
        let numstat = git::diff_numstat(&self.gitdir, &self.worktree, from, to)?;

        let mut status_map: HashMap<String, String> = HashMap::new();
        for (status, file) in &statuses {
            let s = if status.starts_with('A') {
                "added"
            } else if status.starts_with('D') {
                "deleted"
            } else {
                "modified"
            };
            status_map.insert(file.clone(), s.to_string());
        }

        let ignored = git::check_ignored(
            &self.gitdir,
            &self.worktree,
            &numstat
                .iter()
                .map(|(_, _, f)| f.clone())
                .collect::<Vec<_>>(),
        )?;

        let mut result: Vec<FileDiff> = Vec::new();
        let mut total_patch_size = 0;
        let max_patch_size = 10 * 1024 * 1024; // 10MB limit

        for (adds, dels, file) in &numstat {
            if ignored.contains(file) {
                continue;
            }

            let binary = adds == "-" && dels == "-";
            let additions = if binary { 0 } else { adds.parse().unwrap_or(0) };
            let deletions = if binary { 0 } else { dels.parse().unwrap_or(0) };

            let patch = if binary {
                String::new()
            } else {
                let content = git::diff_file(&self.gitdir, &self.worktree, from, to, file)?;
                total_patch_size += content.len();
                if total_patch_size > max_patch_size {
                    return Err(anyhow::anyhow!(
                        "Total diff size exceeded limit of {} bytes",
                        max_patch_size
                    ));
                }
                content
            };

            result.push(FileDiff {
                file: file.clone(),
                patch,
                additions,
                deletions,
                status: status_map.get(file).cloned(),
            });
        }

        Ok(result)
    }

    fn update_index(&self) -> Result<()> {
        let all_files = git::find_changed_files(&self.gitdir, &self.worktree)?;
        if all_files.is_empty() {
            return Ok(());
        }

        let ignored = git::check_ignored(&self.gitdir, &self.worktree, &all_files)?;

        if !ignored.is_empty() {
            let ignored_files: Vec<_> = ignored.iter().cloned().collect();
            git::drop_files(&self.gitdir, &self.worktree, &ignored_files)?;
        }

        git::sync_exclude(&self.gitdir, &self.worktree, &[])?;

        let allowed: Vec<_> = all_files
            .iter()
            .filter(|f| !ignored.contains(*f))
            .cloned()
            .collect();

        if !allowed.is_empty() {
            git::stage_files(&self.gitdir, &self.worktree, &allowed)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{ConfigPaths, SnapshotService};
    use std::{fs, path::PathBuf};

    fn unique_temp_dir(prefix: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("{}-{}", prefix, uuid::Uuid::new_v4()));
        fs::create_dir_all(&dir).expect("temp dir should be created");
        dir
    }

    #[tokio::test]
    async fn track_returns_snapshot_even_when_worktree_is_clean() {
        let workspace_root = unique_temp_dir("tidev-snapshot-worktree");
        let data_dir = unique_temp_dir("tidev-snapshot-data");
        let file_path = workspace_root.join("note.txt");

        fs::write(&file_path, "hello\n").expect("file should be written");

        let paths = ConfigPaths {
            config_dir: data_dir.join("config"),
            data_dir: data_dir.clone(),
            config_file: data_dir.join("config/config.toml"),
            auth_file: data_dir.join("auth.json"),
            database_file: data_dir.join("sessions.sqlite3"),
        };

        let snapshot = SnapshotService::new(&workspace_root, &paths).expect("snapshot should init");

        let first = snapshot
            .track()
            .await
            .expect("initial track should succeed");
        assert!(first.is_some(), "initial track should capture a snapshot");

        let second = snapshot.track().await.expect("clean track should succeed");
        assert!(
            second.is_some(),
            "clean track should still capture a snapshot for redo"
        );
        assert_eq!(
            first, second,
            "clean worktree should produce the same tree hash"
        );

        let _ = fs::remove_dir_all(&workspace_root);
        let _ = fs::remove_dir_all(&data_dir);
    }

    #[tokio::test]
    async fn restore_round_trips_without_git_repo() {
        let workspace_root = unique_temp_dir("tidev-restore-worktree");
        let data_dir = unique_temp_dir("tidev-restore-data");
        let file_path = workspace_root.join("note.txt");

        fs::write(&file_path, "before\n").expect("file should be written");

        let paths = ConfigPaths {
            config_dir: data_dir.join("config"),
            data_dir: data_dir.clone(),
            config_file: data_dir.join("config/config.toml"),
            auth_file: data_dir.join("auth.json"),
            database_file: data_dir.join("sessions.sqlite3"),
        };

        let snapshot = SnapshotService::new(&workspace_root, &paths).expect("snapshot should init");
        let hash = snapshot
            .track()
            .await
            .expect("track should succeed")
            .expect("hash should exist");

        fs::write(&file_path, "after\n").expect("file should be modified");

        snapshot
            .restore(&hash)
            .await
            .expect("restore should succeed");

        assert_eq!(
            fs::read_to_string(&file_path).expect("file should be readable"),
            "before\n"
        );

        let _ = fs::remove_dir_all(&workspace_root);
        let _ = fs::remove_dir_all(&data_dir);
    }

    #[tokio::test]
    async fn revert_round_trips_without_git_repo() {
        let workspace_root = unique_temp_dir("tidev-revert-worktree");
        let data_dir = unique_temp_dir("tidev-revert-data");
        let file_path = workspace_root.join("note.txt");

        fs::write(&file_path, "before\n").expect("file should be written");

        let paths = ConfigPaths {
            config_dir: data_dir.join("config"),
            data_dir: data_dir.clone(),
            config_file: data_dir.join("config/config.toml"),
            auth_file: data_dir.join("auth.json"),
            database_file: data_dir.join("sessions.sqlite3"),
        };

        let snapshot = SnapshotService::new(&workspace_root, &paths).expect("snapshot should init");
        let hash = snapshot
            .track()
            .await
            .expect("track should succeed")
            .expect("hash should exist");

        fs::write(&file_path, "after\n").expect("file should be modified");

        let patch = snapshot.patch(&hash).await.expect("patch should succeed");
        assert!(
            !patch.files.is_empty(),
            "patch should include the modified file"
        );

        snapshot
            .revert(&[patch])
            .await
            .expect("revert should succeed");

        assert_eq!(
            fs::read_to_string(&file_path).expect("file should be readable"),
            "before\n"
        );

        let _ = fs::remove_dir_all(&workspace_root);
        let _ = fs::remove_dir_all(&data_dir);
    }
}

fn clash(a: &str, b: &str) -> bool {
    a == b || a.starts_with(&format!("{}/", b)) || b.starts_with(&format!("{}/", a))
}