cosh-tools 0.1.2

Tools crate for cosh - coding agent for the terminal
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
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use cosh_sdk::rollback::record;

use super::super::rollback::rollback;
use super::super::types::{FsMetadata, FsRollback};

/// Unique scratch root for each rollback test: fixtures live in a per-test
/// temp directory, never in a developer's real project tree.
struct TempRoot(PathBuf);

impl TempRoot {
    fn new(label: &str) -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time is after UNIX_EPOCH")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("cosh_fs_rb_{label}_{id}_{nanos}"));
        std::fs::create_dir_all(&dir).expect("create temp root");
        Self(dir)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempRoot {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

static TEST_ID: AtomicU64 = AtomicU64::new(0);

fn tmp(root: &TempRoot, label: &str) -> String {
    let id = TEST_ID.fetch_add(1, Ordering::Relaxed);
    root.0
        .join(format!("cosh_test_rb_{label}_{id}.txt"))
        .to_string_lossy()
        .into_owned()
}

fn meta(root: &TempRoot) -> FsMetadata {
    FsMetadata {
        root: root.path().to_path_buf(),
        allowlist: None,
        blocklist: None,
    }
}

fn write_file(path: &str, content: &str) {
    std::fs::write(path, content).expect("write test file");
}

fn rm(path: &str) {
    let _ = std::fs::remove_file(path);
}

// Permission enforcement — the tool's primary responsibility

#[tokio::test]
async fn rollback_denied_when_path_is_outside_project_root() {
    let root = TempRoot::new("outside");
    let outside = std::env::temp_dir().join(format!(
        "cosh_tool_rb_outside_{}.txt",
        TEST_ID.fetch_add(1, Ordering::Relaxed)
    ));
    let outside = outside.to_string_lossy().into_owned();
    std::fs::write(&outside, "content").unwrap();
    let _ = record(&outside, "content");

    let err = rollback(&FsRollback, meta(&root), &outside, "")
        .await
        .unwrap_err();

    assert!(
        err.contains("permission denied"),
        "should deny path outside root, got: {err}"
    );
    let _ = std::fs::remove_file(&outside);
}

#[tokio::test]
async fn rollback_denied_when_path_is_in_blocklist() {
    let root = TempRoot::new("blocked");
    let path = tmp(&root, "blocked");
    write_file(&path, "v1\n");
    let _ = record(&path, "v1\n");
    write_file(&path, "v2\n");
    let _ = record(&path, "v2\n");

    let blocked_meta = FsMetadata {
        root: root.path().to_path_buf(),
        allowlist: None,
        blocklist: Some(vec![root.path().to_path_buf()]),
    };

    let err = rollback(&FsRollback, blocked_meta, &path, "")
        .await
        .unwrap_err();

    assert!(
        err.contains("permission denied"),
        "blocked path must be denied, got: {err}"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_returns_error_on_blocklist_allowlist_mismatch() {
    let root = TempRoot::new("mismatch");
    let path = tmp(&root, "mismatch");
    write_file(&path, "content\n");
    let _ = record(&path, "content\n");

    let mismatch_meta = FsMetadata {
        root: root.path().to_path_buf(),
        allowlist: Some(vec![Path::new(&path).to_path_buf()]),
        blocklist: Some(vec![Path::new(&path).to_path_buf()]),
    };

    let result = rollback(&FsRollback, mismatch_meta, &path, "").await;
    assert!(result.is_err(), "both-list mismatch must return an error");
    rm(&path);
}

#[tokio::test]
async fn rollback_allowed_outside_root_when_path_in_allowlist() {
    let root = TempRoot::new("allowlist");
    let outside = std::env::temp_dir().join(format!(
        "cosh_tool_rb_allowlist_{}.txt",
        TEST_ID.fetch_add(1, Ordering::Relaxed)
    ));
    let outside = outside.to_string_lossy().into_owned();
    std::fs::write(&outside, "v1\n").unwrap();
    let _ = record(&outside, "v1\n");
    std::fs::write(&outside, "v2\n").unwrap();
    let _ = record(&outside, "v2\n");

    let allowed_meta = FsMetadata {
        root: root.path().to_path_buf(),
        allowlist: Some(vec![Path::new(&outside).to_path_buf()]),
        blocklist: None,
    };

    let result = rollback(&FsRollback, allowed_meta, &outside, "").await;
    assert!(
        result.is_ok(),
        "explicitly allowed path outside root must succeed, got: {:?}",
        result.err()
    );
    let _ = std::fs::remove_file(&outside);
}

// Schema conversion — hash field interpretation

#[tokio::test]
async fn rollback_empty_hash_restores_previous_version() {
    let root = TempRoot::new("empty_hash");
    let path = tmp(&root, "empty_hash");
    write_file(&path, "version one\n");
    let _ = record(&path, "version one\n");
    write_file(&path, "version two\n");
    let _ = record(&path, "version two\n");

    let out = rollback(&FsRollback, meta(&root), &path, "")
        .await
        .expect("empty hash must trigger previous-version restore");

    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        "version one\n",
        "empty hash must restore the preceding version"
    );
    assert!(!out.file_hash.is_empty());
    rm(&path);
}

#[tokio::test]
async fn rollback_whitespace_only_hash_treated_as_empty() {
    let root = TempRoot::new("ws_hash");
    let path = tmp(&root, "ws_hash");
    write_file(&path, "v1\n");
    let _ = record(&path, "v1\n");
    write_file(&path, "v2\n");
    let _ = record(&path, "v2\n");

    let out = rollback(&FsRollback, meta(&root), &path, "   ")
        .await
        .expect("whitespace-only hash must be treated as empty");

    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        "v1\n",
        "whitespace hash must restore the preceding version"
    );
    drop(out);
    rm(&path);
}

#[tokio::test]
async fn rollback_hash_with_surrounding_whitespace_is_trimmed() {
    let root = TempRoot::new("trim_hash");
    let path = tmp(&root, "trim_hash");
    write_file(&path, "original\n");
    let h = record(&path, "original\n").unwrap();
    write_file(&path, "updated\n");
    let _ = record(&path, "updated\n");

    let padded = format!("  {h}  ");
    let out = rollback(&FsRollback, meta(&root), &path, &padded)
        .await
        .expect("hash with surrounding whitespace must be trimmed and resolved");

    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        "original\n",
        "restore must succeed after trimming hash whitespace"
    );
    assert_eq!(out.file_hash, h);
    rm(&path);
}

#[tokio::test]
async fn rollback_explicit_hash_restores_target_version() {
    let root = TempRoot::new("explicit_hash");
    let path = tmp(&root, "explicit_hash");
    write_file(&path, "state a\n");
    let h_a = record(&path, "state a\n").unwrap();
    write_file(&path, "state b\n");
    let _ = record(&path, "state b\n");

    let out = rollback(&FsRollback, meta(&root), &path, &h_a)
        .await
        .expect("explicit hash restore must succeed");

    assert_eq!(std::fs::read_to_string(&path).unwrap(), "state a\n");
    assert_eq!(
        out.file_hash, h_a,
        "file_hash must equal the restored version"
    );
    rm(&path);
}

// Result contract — shape of the output the LLM receives

#[tokio::test]
async fn rollback_header_has_hashline_format() {
    let root = TempRoot::new("header_shape");
    let path = tmp(&root, "header_shape");
    write_file(&path, "v1\n");
    let h = record(&path, "v1\n").unwrap();
    write_file(&path, "v2\n");
    let _ = record(&path, "v2\n");

    let out = rollback(&FsRollback, meta(&root), &path, &h).await.unwrap();

    assert!(
        out.header.starts_with('\u{00B6}'),
        "header must start with the paragraph sigil ¶"
    );
    assert!(
        out.header.contains(&path),
        "header must contain the file path"
    );
    assert!(
        out.header.contains(&format!("#{h}")),
        "header must contain the restored hash"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_replaced_hash_reflects_content_before_restore() {
    let root = TempRoot::new("replaced_hash");
    let path = tmp(&root, "replaced_hash");
    write_file(&path, "before\n");
    let _ = record(&path, "before\n");
    write_file(&path, "after\n");
    let h_after = record(&path, "after\n").unwrap();

    let out = rollback(&FsRollback, meta(&root), &path, "").await.unwrap();

    assert_eq!(
        out.replaced_hash, h_after,
        "replaced_hash must be the hash of what was on disk before the restore"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_replaced_hash_is_empty_when_file_did_not_exist() {
    let root = TempRoot::new("replaced_hash_deleted");
    let path = tmp(&root, "replaced_hash_deleted");
    write_file(&path, "content\n");
    let h = record(&path, "content\n").unwrap();
    rm(&path);

    let out = rollback(&FsRollback, meta(&root), &path, &h)
        .await
        .expect("restore of deleted file must succeed");

    assert_eq!(
        out.replaced_hash, "",
        "replaced_hash must be empty when the file did not exist before restore"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_warning_is_none_on_clean_restore() {
    let root = TempRoot::new("clean_restore");
    let path = tmp(&root, "clean_restore");
    write_file(&path, "v1\n");
    let _ = record(&path, "v1\n");
    write_file(&path, "v2\n");
    let _ = record(&path, "v2\n");

    let out = rollback(&FsRollback, meta(&root), &path, "").await.unwrap();

    assert!(
        out.warning.is_none(),
        "clean restore must not emit a warning"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_warning_is_some_when_file_was_externally_modified() {
    let root = TempRoot::new("ext_mod_warning");
    let path = tmp(&root, "ext_mod_warning");
    write_file(&path, "session version\n");
    let h = record(&path, "session version\n").unwrap();

    // Simulate external modification — write directly without record()
    write_file(&path, "externally changed\n");

    let out = rollback(&FsRollback, meta(&root), &path, &h)
        .await
        .expect("restore over external modification must succeed");

    assert!(
        out.warning.is_some(),
        "external modification must produce a warning"
    );
    assert!(
        out.warning
            .as_deref()
            .is_some_and(|w| w.contains("externally")),
        "warning must mention external modification"
    );
    rm(&path);
}

// Error propagation — engine errors surface correctly through the tool layer

#[tokio::test]
async fn rollback_error_no_history_for_path() {
    let root = TempRoot::new("no_history");
    let path = tmp(&root, "no_history_tool");
    write_file(&path, "fresh file\n");

    let err = rollback(&FsRollback, meta(&root), &path, "")
        .await
        .unwrap_err();

    assert!(
        err.contains("no rollback history"),
        "engine error must be forwarded as-is, got: {err}"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_error_hash_not_found_in_history() {
    let root = TempRoot::new("bad_hash");
    let path = tmp(&root, "bad_hash_tool");
    write_file(&path, "content\n");
    let h = record(&path, "content\n").unwrap();
    write_file(&path, "updated\n");
    let _ = record(&path, "updated\n");

    let err = rollback(&FsRollback, meta(&root), &path, "DEAD")
        .await
        .unwrap_err();

    assert!(err.contains("DEAD"), "error must mention the bad hash");
    assert!(err.contains(&h), "error must list known hashes");
    rm(&path);
}

#[tokio::test]
async fn rollback_error_already_at_requested_version() {
    let root = TempRoot::new("already_current");
    let path = tmp(&root, "already_current_tool");
    write_file(&path, "v1\n");
    let h = record(&path, "v1\n").unwrap();
    write_file(&path, "v2\n");
    let _ = record(&path, "v2\n");

    // Restore to v1 first
    rollback(&FsRollback, meta(&root), &path, &h).await.unwrap();

    // Restore again — disk already has v1
    let err = rollback(&FsRollback, meta(&root), &path, &h)
        .await
        .unwrap_err();

    assert!(
        err.contains("already at version"),
        "must error when file is already at the target, got: {err}"
    );
    rm(&path);
}

#[tokio::test]
async fn rollback_error_no_previous_when_only_one_version() {
    let root = TempRoot::new("single_version");
    let path = tmp(&root, "single_version_tool");
    write_file(&path, "only version\n");
    let _ = record(&path, "only version\n");

    let err = rollback(&FsRollback, meta(&root), &path, "")
        .await
        .unwrap_err();

    assert!(
        err.contains("no previous version"),
        "must error when at the oldest version, got: {err}"
    );
    rm(&path);
}