claude-oops 0.4.0

Automatic safety net for Claude Code: snapshot before risky ops, restore in seconds.
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! End-to-end tests that drive the compiled `claude-oops` binary against
//! throwaway git repos.

mod helpers;

use helpers::{run_oops, TempRepo};

#[test]
fn snap_in_clean_tree_records_a_baseline() {
    let repo = TempRepo::new();
    let (stdout, stderr, code) = run_oops(repo.path(), &["snap", "-m", "first"]);
    assert_eq!(code, 0, "snap failed: stdout={stdout} stderr={stderr}");
    let (list_out, _, list_code) = run_oops(repo.path(), &["list"]);
    assert_eq!(list_code, 0);
    assert!(
        list_out.contains("first") || list_out.contains("manual"),
        "list output missing snapshot: {list_out}"
    );
}

#[test]
fn snap_with_changes_records_diff_stats() {
    let repo = TempRepo::new();
    repo.write("foo.txt", "one\ntwo\nthree\n");
    let (_, _, code) = run_oops(repo.path(), &["snap", "-m", "added foo"]);
    assert_eq!(code, 0);
    let (list_out, _, _) = run_oops(repo.path(), &["list"]);
    // 3 lines added, 0 deleted.
    assert!(list_out.contains("+3/-0"), "expected +3/-0 in: {list_out}");
}

#[test]
fn list_json_emits_valid_records() {
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap", "-m", "alpha"]);
    repo.write("a.txt", "data\n");
    run_oops(repo.path(), &["snap", "-m", "beta"]);
    let (out, _, code) = run_oops(repo.path(), &["list", "--json"]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    let arr = v.as_array().expect("array");
    assert_eq!(arr.len(), 2);
    assert_eq!(arr[0]["message"], "alpha");
    assert_eq!(arr[1]["message"], "beta");
}

#[test]
fn manual_snap_ignores_idempotency() {
    // Two manual snaps in a row on the same tree should both succeed
    // because manual is force=true.
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap", "-m", "one"]);
    run_oops(repo.path(), &["snap", "-m", "two"]);
    let (out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v.as_array().unwrap().len(), 2);
}

#[test]
fn auto_trigger_skips_when_tree_unchanged() {
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap", "--trigger", "session-start"]);
    // Same tree, non-manual trigger — should be skipped.
    let (stdout, _, _) = run_oops(repo.path(), &["snap", "--trigger", "pre-edit"]);
    assert!(stdout.contains("no change"), "expected skip, got: {stdout}");
    let (out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v.as_array().unwrap().len(), 1);
}

#[test]
fn restore_brings_back_deleted_file() {
    let repo = TempRepo::new();
    repo.write("important.txt", "do not delete me\n");
    run_oops(repo.path(), &["snap", "-m", "before disaster"]);

    // Get the snapshot id from list --json.
    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let id = v[0]["id"].as_str().unwrap().to_string();

    // Disaster strikes.
    std::fs::remove_file(repo.path().join("important.txt")).unwrap();
    assert!(!repo.exists("important.txt"));

    // Oops.
    let (_, stderr, code) = run_oops(repo.path(), &["to", &id, "--force"]);
    assert_eq!(code, 0, "restore failed: {stderr}");
    assert!(repo.exists("important.txt"));
    assert_eq!(repo.read("important.txt"), "do not delete me\n");
}

#[test]
fn diff_shows_changes_against_snapshot() {
    let repo = TempRepo::new();
    repo.write("file.txt", "v1\n");
    run_oops(repo.path(), &["snap", "-m", "v1"]);
    repo.write("file.txt", "v2\n");

    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let id = v[0]["id"].as_str().unwrap().to_string();

    let (out, _, code) = run_oops(repo.path(), &["diff", &id]);
    assert_eq!(code, 0);
    assert!(out.contains("+v2"), "diff missing change: {out}");
    assert!(out.contains("-v1"), "diff missing change: {out}");
}

#[test]
fn drop_removes_snapshot_and_ref() {
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap", "-m", "doomed"]);
    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let id = v[0]["id"].as_str().unwrap().to_string();

    let (_, _, code) = run_oops(repo.path(), &["drop", &id]);
    assert_eq!(code, 0);

    let (out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v.as_array().unwrap().len(), 0);

    // Ref should be gone.
    let ref_check = std::process::Command::new("git")
        .args([
            "rev-parse",
            "--verify",
            "--quiet",
            &format!("refs/claude-oops/{}", id),
        ])
        .current_dir(repo.path())
        .status()
        .unwrap();
    assert!(!ref_check.success(), "ref should have been deleted");
}

#[test]
fn install_then_uninstall_round_trip() {
    use std::process::Command;

    let dir = tempfile::tempdir().unwrap();
    let settings = dir.path().join("settings.json");
    let commands_dir = dir.path().join("commands");
    // Pre-existing user content we must NOT touch.
    std::fs::write(
        &settings,
        r#"{"permissions": {"allow": ["bash"]}, "hooks": {"PreToolUse": [
          {"matcher": "Read", "hooks": [{"type": "command", "command": "echo user-hook"}]}
        ]}}"#,
    )
    .unwrap();

    let bin = helpers::bin_path();

    let out = Command::new(&bin)
        .arg("install")
        .env("CLAUDE_OOPS_SETTINGS", &settings)
        .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
        .output()
        .unwrap();
    assert!(out.status.success(), "install failed: {:?}", out);
    // Slash command was written.
    assert!(commands_dir.join("oops.md").exists());

    let after_install: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
    // User's permission block survives.
    assert_eq!(after_install["permissions"]["allow"][0], "bash");
    // User's pre-existing PreToolUse hook survives.
    let pre = after_install["hooks"]["PreToolUse"].as_array().unwrap();
    assert!(
        pre.iter().any(|e| e["matcher"] == "Read"),
        "user hook lost: {pre:?}"
    );
    // Our two hooks are present.
    assert!(after_install["hooks"]["SessionStart"].is_array());
    assert!(pre.iter().any(|e| e["matcher"] == "Edit|Write|Bash"));

    let out = Command::new(&bin)
        .arg("uninstall")
        .env("CLAUDE_OOPS_SETTINGS", &settings)
        .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
        .output()
        .unwrap();
    assert!(out.status.success());

    let after_uninstall: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
    // User's stuff still here.
    assert_eq!(after_uninstall["permissions"]["allow"][0], "bash");
    let pre = after_uninstall["hooks"]["PreToolUse"].as_array().unwrap();
    assert!(pre.iter().any(|e| e["matcher"] == "Read"));
    // Our entry is gone.
    assert!(!pre.iter().any(|e| e["matcher"] == "Edit|Write|Bash"));
    // Slash command was cleaned up too.
    assert!(!commands_dir.join("oops.md").exists());
}

#[test]
fn uninstall_preserves_user_modified_slash_command() {
    use std::process::Command;
    let dir = tempfile::tempdir().unwrap();
    let settings = dir.path().join("settings.json");
    let commands_dir = dir.path().join("commands");
    let bin = helpers::bin_path();

    Command::new(&bin)
        .arg("install")
        .env("CLAUDE_OOPS_SETTINGS", &settings)
        .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
        .output()
        .unwrap();

    // User edits the slash command.
    let oops_md = commands_dir.join("oops.md");
    std::fs::write(&oops_md, "user customized this\n").unwrap();

    Command::new(&bin)
        .arg("uninstall")
        .env("CLAUDE_OOPS_SETTINGS", &settings)
        .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
        .output()
        .unwrap();

    // Should still exist with user's content.
    assert!(oops_md.exists());
    assert_eq!(
        std::fs::read_to_string(&oops_md).unwrap(),
        "user customized this\n"
    );
}

#[test]
fn install_writes_stop_hook() {
    use std::process::Command;
    let dir = tempfile::tempdir().unwrap();
    let settings = dir.path().join("settings.json");
    let commands_dir = dir.path().join("commands");
    let bin = helpers::bin_path();

    let out = Command::new(&bin)
        .arg("install")
        .env("CLAUDE_OOPS_SETTINGS", &settings)
        .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
        .output()
        .unwrap();
    assert!(out.status.success());

    let v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
    let stop = v["hooks"]["Stop"].as_array().expect("Stop array");
    assert_eq!(stop.len(), 1, "expected one Stop entry");
    let cmd = stop[0]["hooks"][0]["command"].as_str().unwrap();
    assert!(cmd.contains("snap"), "Stop command should call snap: {cmd}");
    assert!(
        cmd.contains("post-turn"),
        "Stop command should use post-turn trigger: {cmd}"
    );
}

#[test]
fn install_is_idempotent() {
    use std::process::Command;
    let dir = tempfile::tempdir().unwrap();
    let settings = dir.path().join("settings.json");
    let commands_dir = dir.path().join("commands");
    let bin = helpers::bin_path();

    for _ in 0..3 {
        let out = Command::new(&bin)
            .arg("install")
            .env("CLAUDE_OOPS_SETTINGS", &settings)
            .env("CLAUDE_OOPS_COMMANDS_DIR", &commands_dir)
            .output()
            .unwrap();
        assert!(out.status.success());
    }

    let v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
    assert_eq!(v["hooks"]["SessionStart"].as_array().unwrap().len(), 1);
    assert_eq!(v["hooks"]["PreToolUse"].as_array().unwrap().len(), 1);
    assert!(commands_dir.join("oops.md").exists());
}

#[test]
fn show_lists_files_that_would_change_on_restore() {
    let repo = TempRepo::new();
    repo.write("a.txt", "v1\n");
    repo.write("b.txt", "v1\n");
    run_oops(repo.path(), &["snap", "-m", "snap1"]);

    // Change one file, leave the other alone.
    repo.write("a.txt", "v2\n");

    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let id = v[0]["id"].as_str().unwrap().to_string();

    let (out, _, code) = run_oops(repo.path(), &["show", &id]);
    assert_eq!(code, 0);
    assert!(out.contains("a.txt"), "show should mention a.txt: {out}");
    assert!(
        !out.contains("b.txt"),
        "b.txt unchanged, shouldn't appear: {out}"
    );
}

#[test]
fn show_on_unchanged_tree_says_no_changes() {
    let repo = TempRepo::new();
    repo.write("file.txt", "x\n");
    run_oops(repo.path(), &["snap", "-m", "snap"]);

    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let id = v[0]["id"].as_str().unwrap().to_string();

    let (out, _, code) = run_oops(repo.path(), &["show", &id]);
    assert_eq!(code, 0);
    assert!(out.to_lowercase().contains("no changes"), "got: {out}");
}

#[test]
fn hook_emits_visible_feedback_on_stderr() {
    use std::io::Write;
    use std::process::{Command, Stdio};
    let repo = TempRepo::new();
    let payload = serde_json::json!({
        "tool_name": "Bash",
        "tool_input": {"command": "rm -rf important_dir"},
        "cwd": repo.path().to_string_lossy(),
    });
    let mut child = Command::new(helpers::bin_path())
        .arg("_hook-pre-tool-use")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(payload.to_string().as_bytes())
        .unwrap();
    let out = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&out.stderr);
    // stdout must stay empty so Claude Code doesn't try to parse it as a
    // permission decision.
    assert!(
        out.stdout.is_empty(),
        "stdout should be empty, got: {:?}",
        out.stdout
    );
    assert!(
        stderr.contains("claude-oops"),
        "expected feedback in stderr: {stderr}"
    );
    assert!(
        stderr.contains("pre-bash"),
        "expected trigger label: {stderr}"
    );
}

#[test]
fn pre_tool_use_hook_snapshots_on_dangerous_bash() {
    use std::io::Write;
    use std::process::{Command, Stdio};
    let repo = TempRepo::new();
    repo.write("data.txt", "important\n");

    let payload = serde_json::json!({
        "tool_name": "Bash",
        "tool_input": {"command": "rm -rf data.txt"},
        "cwd": repo.path().to_string_lossy(),
    });
    let mut child = Command::new(helpers::bin_path())
        .arg("_hook-pre-tool-use")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(payload.to_string().as_bytes())
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success());

    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 1, "expected 1 snapshot, got {arr:?}");
    assert_eq!(arr[0]["trigger"], "pre-bash");
}

#[test]
fn pre_tool_use_hook_skips_safe_bash() {
    use std::io::Write;
    use std::process::{Command, Stdio};
    let repo = TempRepo::new();
    let payload = serde_json::json!({
        "tool_name": "Bash",
        "tool_input": {"command": "ls -la"},
        "cwd": repo.path().to_string_lossy(),
    });
    let mut child = Command::new(helpers::bin_path())
        .arg("_hook-pre-tool-use")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(payload.to_string().as_bytes())
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success());
    let (json_out, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json_out).unwrap();
    assert_eq!(v.as_array().unwrap().len(), 0);
}

#[test]
fn clean_removes_snapshots_and_refs() {
    // We can't easily create a snapshot >7 days old without time travel,
    // so we test the keep-last-N path: take 5 snaps, retain only the last 2.
    let repo = TempRepo::new();
    for i in 0..5 {
        repo.write("f.txt", &format!("v{i}\n"));
        run_oops(repo.path(), &["snap", "-m", &format!("v{i}")]);
    }

    // Hand-edit the index to set keep_last_n=2 by directly running clean
    // wouldn't work — clean uses the constants. Instead verify the no-op
    // behaviour: no snapshots are old enough to drop, all stay.
    let (out, _, code) = run_oops(repo.path(), &["clean"]);
    assert_eq!(code, 0);
    assert!(out.contains("kept 5"), "unexpected output: {out}");
    assert!(out.contains("deleted 0"), "unexpected output: {out}");
}

#[test]
fn per_file_restore_only_touches_requested_paths() {
    let repo = TempRepo::new();
    repo.write("keep.txt", "v1\n");
    repo.write("oops.txt", "v1\n");
    run_oops(repo.path(), &["snap", "-m", "v1"]);

    // User makes good and bad changes.
    repo.write("keep.txt", "good edit\n");
    repo.write("oops.txt", "bad edit\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Restore only oops.txt.
    let (out, stderr, code) = run_oops(repo.path(), &["to", &id, "--force", "--", "oops.txt"]);
    assert_eq!(code, 0, "out={out} stderr={stderr}");

    // oops.txt is back to v1, keep.txt keeps the good edit.
    assert_eq!(repo.read("oops.txt"), "v1\n");
    assert_eq!(repo.read("keep.txt"), "good edit\n");
}

#[test]
fn per_file_restore_brings_back_deleted_file() {
    let repo = TempRepo::new();
    repo.write("a.txt", "alpha\n");
    repo.write("b.txt", "beta\n");
    run_oops(repo.path(), &["snap"]);

    std::fs::remove_file(repo.path().join("a.txt")).unwrap();

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let (_, _, code) = run_oops(repo.path(), &["to", &id, "--force", "--", "a.txt"]);
    assert_eq!(code, 0);
    assert!(repo.exists("a.txt"));
    assert_eq!(repo.read("a.txt"), "alpha\n");
}

#[test]
fn per_file_restore_removes_files_added_after_snapshot() {
    let repo = TempRepo::new();
    repo.write("orig.txt", "orig\n");
    run_oops(repo.path(), &["snap"]);

    // User adds a new file after the snapshot.
    repo.write("garbage.txt", "garbage\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Restore just garbage.txt — it isn't in the snapshot, so it should
    // disappear from the working tree.
    let (_, _, code) = run_oops(repo.path(), &["to", &id, "--force", "--", "garbage.txt"]);
    assert_eq!(code, 0);
    assert!(!repo.exists("garbage.txt"));
    // orig.txt is untouched.
    assert!(repo.exists("orig.txt"));
}

#[test]
fn per_file_restore_handles_directory_pathspec() {
    let repo = TempRepo::new();
    repo.write("src/a.rs", "v1\n");
    repo.write("src/b.rs", "v1\n");
    repo.write("docs/intro.md", "v1\n");
    run_oops(repo.path(), &["snap"]);

    repo.write("src/a.rs", "edited\n");
    repo.write("src/b.rs", "edited\n");
    repo.write("docs/intro.md", "edited\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Restore only the src/ subtree.
    let (_, _, code) = run_oops(repo.path(), &["to", &id, "--force", "--", "src"]);
    assert_eq!(code, 0);
    assert_eq!(repo.read("src/a.rs"), "v1\n");
    assert_eq!(repo.read("src/b.rs"), "v1\n");
    assert_eq!(repo.read("docs/intro.md"), "edited\n"); // untouched
}

#[test]
fn per_file_restore_with_no_matches_errors() {
    let repo = TempRepo::new();
    repo.write("a.txt", "v1\n");
    run_oops(repo.path(), &["snap"]);

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let (_, stderr, code) = run_oops(
        repo.path(),
        &["to", &id, "--force", "--", "nonexistent.txt"],
    );
    assert_ne!(code, 0);
    assert!(
        stderr.to_lowercase().contains("no matching"),
        "expected no-match error, got: {stderr}"
    );
}

#[test]
fn per_file_restore_resolves_paths_relative_to_cwd() {
    // Run claude-oops from a subdirectory and pass a relative path —
    // it should resolve correctly against the repo root.
    let repo = TempRepo::new();
    repo.write("src/main.rs", "v1\n");
    run_oops(repo.path(), &["snap"]);
    repo.write("src/main.rs", "v2\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // cwd = src/, path = main.rs → should resolve to src/main.rs
    let src = repo.path().join("src");
    let (_, stderr, code) = run_oops(&src, &["to", &id, "--force", "--", "main.rs"]);
    assert_eq!(code, 0, "stderr: {stderr}");
    assert_eq!(repo.read("src/main.rs"), "v1\n");
}

#[test]
fn per_file_restore_rejects_paths_outside_repo() {
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap"]);
    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Try to escape via ..
    let (_, stderr, code) = run_oops(
        repo.path(),
        &["to", &id, "--force", "--", "../../etc/passwd"],
    );
    assert_ne!(code, 0);
    assert!(
        stderr.to_lowercase().contains("outside the repo"),
        "expected outside-repo error, got: {stderr}"
    );
}

#[test]
fn restore_overwrites_conflicting_local_changes() {
    // Reproducer for the bug seen in the wild: a session-start snapshot
    // captures `.gitignore` as it was; later, the user has uncommitted
    // local edits to `.gitignore`. Restore must overwrite — that's exactly
    // what the user is asking for.
    let repo = TempRepo::new();
    repo.write(".gitignore", "*.log\n");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(repo.path())
        .status()
        .unwrap();
    std::process::Command::new("git")
        .args(["commit", "-q", "-m", "add gitignore"])
        .current_dir(repo.path())
        .status()
        .unwrap();
    run_oops(repo.path(), &["snap", "-m", "before edits"]);

    // User edits .gitignore (uncommitted, conflicting).
    repo.write(".gitignore", "*.log\nbuild/\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Whole-tree restore — must overwrite the local change, not refuse.
    let (out, stderr, code) = run_oops(repo.path(), &["to", &id, "--force"]);
    assert_eq!(
        code, 0,
        "restore should succeed even with local conflicts — out={out} stderr={stderr}"
    );
    assert_eq!(repo.read(".gitignore"), "*.log\n");
}

#[test]
fn restore_deletes_files_added_after_snapshot() {
    let repo = TempRepo::new();
    repo.write("a.txt", "alpha\n");
    run_oops(repo.path(), &["snap"]);
    repo.write("b.txt", "added later\n");

    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let (_, _, code) = run_oops(repo.path(), &["to", &id, "--force"]);
    assert_eq!(code, 0);
    assert!(repo.exists("a.txt"));
    assert!(
        !repo.exists("b.txt"),
        "files added after the snapshot should disappear on whole-tree restore"
    );
}

#[test]
fn confirm_errors_clearly_on_empty_piped_stdin() {
    // Slash commands run the binary without a TTY and without piping
    // anything — read_line returns 0 bytes. We should error with a
    // helpful "pass --force" message, not silently abort.
    use std::process::{Command, Stdio};
    let repo = TempRepo::new();
    run_oops(repo.path(), &["snap"]);
    let (json, _, _) = run_oops(repo.path(), &["list", "--json"]);
    let id = serde_json::from_str::<serde_json::Value>(&json).unwrap()[0]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let out = Command::new(helpers::bin_path())
        .args(["to", &id])
        .current_dir(repo.path())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();
    assert_ne!(out.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--force"),
        "stderr should mention --force, got: {stderr}"
    );
}

#[test]
fn outside_git_repo_snap_errors_clearly() {
    let dir = tempfile::tempdir().unwrap();
    let (_, stderr, code) = run_oops(dir.path(), &["snap"]);
    assert_ne!(code, 0);
    assert!(
        stderr.to_lowercase().contains("git"),
        "error should mention git: {stderr}"
    );
}

#[test]
fn outside_git_repo_quiet_snap_exits_zero() {
    // The SessionStart hook calls `snap --quiet` — that must not fail in
    // non-git projects, otherwise the hook blows up everywhere.
    let dir = tempfile::tempdir().unwrap();
    let (_, _, code) = run_oops(
        dir.path(),
        &["snap", "--quiet", "--trigger", "session-start"],
    );
    assert_eq!(code, 0);
}

#[test]
fn outside_git_repo_list_says_so_and_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let (out, _, code) = run_oops(dir.path(), &["list"]);
    assert_eq!(code, 0);
    assert!(
        out.to_lowercase().contains("not a git repository") || out.contains("git init"),
        "expected helpful message, got: {out}"
    );
    // JSON variant: empty array + exit 0, so callers can pipe through jq safely.
    let (json_out, _, json_code) = run_oops(dir.path(), &["list", "--json"]);
    assert_eq!(json_code, 0);
    assert_eq!(json_out.trim(), "[]");
}

#[test]
fn outside_git_repo_status_says_so_and_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let (out, _, code) = run_oops(dir.path(), &["status"]);
    assert_eq!(code, 0);
    assert!(
        out.to_lowercase().contains("not a git repository") || out.contains("git init"),
        "expected helpful message, got: {out}"
    );
}